teodor-new-chat-ui 4.3.145 → 4.3.147
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.esm.js +66 -62
- package/dist/index.umd.js +6 -6
- package/package.json +1 -1
package/dist/index.umd.js
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
`+te+N}}var q=!1,ie;{var ce=typeof WeakMap=="function"?WeakMap:Map;ie=new ce}function U(N,Y){if(!N||q)return"";{var ae=ie.get(N);if(ae!==void 0)return ae}var Ce;q=!0;var Ge=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var qe;qe=ke.current,ke.current=null,J();try{if(Y){var He=function(){throw Error()};if(Object.defineProperty(He.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(He,[])}catch(zt){Ce=zt}Reflect.construct(N,[],He)}else{try{He.call()}catch(zt){Ce=zt}N.call(He.prototype)}}else{try{throw Error()}catch(zt){Ce=zt}N()}}catch(zt){if(zt&&Ce&&typeof zt.stack=="string"){for(var Re=zt.stack.split(`
|
|
19
19
|
`),At=Ce.stack.split(`
|
|
20
20
|
`),gt=Re.length-1,Ct=At.length-1;gt>=1&&Ct>=0&&Re[gt]!==At[Ct];)Ct--;for(;gt>=1&&Ct>=0;gt--,Ct--)if(Re[gt]!==At[Ct]){if(gt!==1||Ct!==1)do if(gt--,Ct--,Ct<0||Re[gt]!==At[Ct]){var Zt=`
|
|
21
|
-
`+Re[gt].replace(" at new "," at ");return N.displayName&&Zt.includes("<anonymous>")&&(Zt=Zt.replace("<anonymous>",N.displayName)),typeof N=="function"&&ie.set(N,Zt),Zt}while(gt>=1&&Ct>=0);break}}}finally{q=!1,ke.current=qe,ue(),Error.prepareStackTrace=Ge}var Fn=N?N.displayName||N.name:"",hn=Fn?L(Fn):"";return typeof N=="function"&&ie.set(N,hn),hn}function We(N,Y,ae){return U(N,!1)}function re(N){var Y=N.prototype;return!!(Y&&Y.isReactComponent)}function xe(N,Y,ae){if(N==null)return"";if(typeof N=="function")return U(N,re(N));if(typeof N=="string")return L(N);switch(N){case c:return L("Suspense");case d:return L("SuspenseList")}if(typeof N=="object")switch(N.$$typeof){case l:return We(N.render);case f:return xe(N.type,Y,ae);case h:{var Ce=N,Ge=Ce._payload,qe=Ce._init;try{return xe(qe(Ge),Y,ae)}catch{}}}return""}var Pe=Object.prototype.hasOwnProperty,$e={},rt=x.ReactDebugCurrentFrame;function Se(N){if(N){var Y=N._owner,ae=xe(N.type,N._source,Y?Y.type:null);rt.setExtraStackFrame(ae)}else rt.setExtraStackFrame(null)}function Ye(N,Y,ae,Ce,Ge){{var qe=Function.call.bind(Pe);for(var He in N)if(qe(N,He)){var Re=void 0;try{if(typeof N[He]!="function"){var At=Error((Ce||"React class")+": "+ae+" type `"+He+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof N[He]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw At.name="Invariant Violation",At}Re=N[He](Y,He,Ce,ae,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(gt){Re=gt}Re&&!(Re instanceof Error)&&(Se(Ge),w("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",Ce||"React class",ae,He,typeof Re),Se(null)),Re instanceof Error&&!(Re.message in $e)&&($e[Re.message]=!0,Se(Ge),w("Failed %s type: %s",ae,Re.message),Se(null))}}}var ot=Array.isArray;function et(N){return ot(N)}function Xe(N){{var Y=typeof Symbol=="function"&&Symbol.toStringTag,ae=Y&&N[Symbol.toStringTag]||N.constructor.name||"Object";return ae}}function Ke(N){try{return tt(N),!1}catch{return!0}}function tt(N){return""+N}function
|
|
21
|
+
`+Re[gt].replace(" at new "," at ");return N.displayName&&Zt.includes("<anonymous>")&&(Zt=Zt.replace("<anonymous>",N.displayName)),typeof N=="function"&&ie.set(N,Zt),Zt}while(gt>=1&&Ct>=0);break}}}finally{q=!1,ke.current=qe,ue(),Error.prepareStackTrace=Ge}var Fn=N?N.displayName||N.name:"",hn=Fn?L(Fn):"";return typeof N=="function"&&ie.set(N,hn),hn}function We(N,Y,ae){return U(N,!1)}function re(N){var Y=N.prototype;return!!(Y&&Y.isReactComponent)}function xe(N,Y,ae){if(N==null)return"";if(typeof N=="function")return U(N,re(N));if(typeof N=="string")return L(N);switch(N){case c:return L("Suspense");case d:return L("SuspenseList")}if(typeof N=="object")switch(N.$$typeof){case l:return We(N.render);case f:return xe(N.type,Y,ae);case h:{var Ce=N,Ge=Ce._payload,qe=Ce._init;try{return xe(qe(Ge),Y,ae)}catch{}}}return""}var Pe=Object.prototype.hasOwnProperty,$e={},rt=x.ReactDebugCurrentFrame;function Se(N){if(N){var Y=N._owner,ae=xe(N.type,N._source,Y?Y.type:null);rt.setExtraStackFrame(ae)}else rt.setExtraStackFrame(null)}function Ye(N,Y,ae,Ce,Ge){{var qe=Function.call.bind(Pe);for(var He in N)if(qe(N,He)){var Re=void 0;try{if(typeof N[He]!="function"){var At=Error((Ce||"React class")+": "+ae+" type `"+He+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof N[He]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw At.name="Invariant Violation",At}Re=N[He](Y,He,Ce,ae,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(gt){Re=gt}Re&&!(Re instanceof Error)&&(Se(Ge),w("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",Ce||"React class",ae,He,typeof Re),Se(null)),Re instanceof Error&&!(Re.message in $e)&&($e[Re.message]=!0,Se(Ge),w("Failed %s type: %s",ae,Re.message),Se(null))}}}var ot=Array.isArray;function et(N){return ot(N)}function Xe(N){{var Y=typeof Symbol=="function"&&Symbol.toStringTag,ae=Y&&N[Symbol.toStringTag]||N.constructor.name||"Object";return ae}}function Ke(N){try{return tt(N),!1}catch{return!0}}function tt(N){return""+N}function Ot(N){if(Ke(N))return w("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",Xe(N)),tt(N)}var St=x.ReactCurrentOwner,nt={key:!0,ref:!0,__self:!0,__source:!0},yt,Nt;function st(N){if(Pe.call(N,"ref")){var Y=Object.getOwnPropertyDescriptor(N,"ref").get;if(Y&&Y.isReactWarning)return!1}return N.ref!==void 0}function Gt(N){if(Pe.call(N,"key")){var Y=Object.getOwnPropertyDescriptor(N,"key").get;if(Y&&Y.isReactWarning)return!1}return N.key!==void 0}function Yt(N,Y){typeof N.ref=="string"&&St.current}function Xt(N,Y){{var ae=function(){yt||(yt=!0,w("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",Y))};ae.isReactWarning=!0,Object.defineProperty(N,"key",{get:ae,configurable:!0})}}function Jt(N,Y){{var ae=function(){Nt||(Nt=!0,w("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",Y))};ae.isReactWarning=!0,Object.defineProperty(N,"ref",{get:ae,configurable:!0})}}var ft=function(N,Y,ae,Ce,Ge,qe,He){var Re={$$typeof:t,type:N,key:Y,ref:ae,props:He,_owner:qe};return Re._store={},Object.defineProperty(Re._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(Re,"_self",{configurable:!1,enumerable:!1,writable:!1,value:Ce}),Object.defineProperty(Re,"_source",{configurable:!1,enumerable:!1,writable:!1,value:Ge}),Object.freeze&&(Object.freeze(Re.props),Object.freeze(Re)),Re};function Ve(N,Y,ae,Ce,Ge){{var qe,He={},Re=null,At=null;ae!==void 0&&(Ot(ae),Re=""+ae),Gt(Y)&&(Ot(Y.key),Re=""+Y.key),st(Y)&&(At=Y.ref,Yt(Y,Ge));for(qe in Y)Pe.call(Y,qe)&&!nt.hasOwnProperty(qe)&&(He[qe]=Y[qe]);if(N&&N.defaultProps){var gt=N.defaultProps;for(qe in gt)He[qe]===void 0&&(He[qe]=gt[qe])}if(Re||At){var Ct=typeof N=="function"?N.displayName||N.name||"Unknown":N;Re&&Xt(He,Ct),At&&Jt(He,Ct)}return ft(N,Re,At,Ge,Ce,St.current,He)}}var Mt=x.ReactCurrentOwner,_t=x.ReactDebugCurrentFrame;function G(N){if(N){var Y=N._owner,ae=xe(N.type,N._source,Y?Y.type:null);_t.setExtraStackFrame(ae)}else _t.setExtraStackFrame(null)}var Te;Te=!1;function ve(N){return typeof N=="object"&&N!==null&&N.$$typeof===t}function pt(){{if(Mt.current){var N=B(Mt.current.type);if(N)return`
|
|
22
22
|
|
|
23
23
|
Check the render method of \``+N+"`."}return""}}function mt(N){return""}var ct={};function Me(N){{var Y=pt();if(!Y){var ae=typeof N=="string"?N:N.displayName||N.name;ae&&(Y=`
|
|
24
24
|
|
|
@@ -32,10 +32,10 @@ React keys must be passed directly to JSX without using spread:
|
|
|
32
32
|
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[hc]=this[hc]={accessors:{}}).accessors,o=this.prototype;function s(i){const a=go(i);r[a]||(ty(o,i),r[a]=!0)}return M.isArray(t)?t.forEach(s):s(t),this}};ln.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),M.reduceDescriptors(ln.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}}),M.freezeMethods(ln);function Bi(e,t){const n=this||mo,r=t||n,o=ln.from(r.headers);let s=r.data;return M.forEach(e,function(a){s=a.call(n,s,o.normalize(),t?t.status:void 0)}),o.normalize(),s}function pc(e){return!!(e&&e.__CANCEL__)}function Ur(e,t,n){Fe.call(this,e??"canceled",Fe.ERR_CANCELED,t,n),this.name="CanceledError"}M.inherits(Ur,Fe,{__CANCEL__:!0});function mc(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new Fe("Request failed with status code "+n.status,[Fe.ERR_BAD_REQUEST,Fe.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function ny(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function ry(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,s=0,i;return t=t!==void 0?t:1e3,function(l){const c=Date.now(),d=r[s];i||(i=c),n[o]=l,r[o]=c;let f=s,h=0;for(;f!==o;)h+=n[f++],f=f%e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),c-i<t)return;const p=d&&c-d;return p?Math.round(h*1e3/p):void 0}}function oy(e,t){let n=0,r=1e3/t,o,s;const i=(c,d=Date.now())=>{n=d,o=null,s&&(clearTimeout(s),s=null),e(...c)};return[(...c)=>{const d=Date.now(),f=d-n;f>=r?i(c,d):(o=c,s||(s=setTimeout(()=>{s=null,i(o)},r-f)))},()=>o&&i(o)]}const ns=(e,t,n=3)=>{let r=0;const o=ry(50,250);return oy(s=>{const i=s.loaded,a=s.lengthComputable?s.total:void 0,l=i-r,c=o(l),d=i<=a;r=i;const f={loaded:i,total:a,progress:a?i/a:void 0,bytes:l,rate:c||void 0,estimated:c&&a&&d?(a-i)/c:void 0,event:s,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(f)},n)},gc=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},yc=e=>(...t)=>M.asap(()=>e(...t)),sy=Qt.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,Qt.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(Qt.origin),Qt.navigator&&/(msie|trident)/i.test(Qt.navigator.userAgent)):()=>!0,iy=Qt.hasStandardBrowserEnv?{write(e,t,n,r,o,s){const i=[e+"="+encodeURIComponent(t)];M.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),M.isString(r)&&i.push("path="+r),M.isString(o)&&i.push("domain="+o),s===!0&&i.push("secure"),document.cookie=i.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function ay(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function ly(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function xc(e,t,n){let r=!ay(t);return e&&(r||n==!1)?ly(e,t):t}const vc=e=>e instanceof ln?{...e}:e;function br(e,t){t=t||{};const n={};function r(c,d,f,h){return M.isPlainObject(c)&&M.isPlainObject(d)?M.merge.call({caseless:h},c,d):M.isPlainObject(d)?M.merge({},d):M.isArray(d)?d.slice():d}function o(c,d,f,h){if(M.isUndefined(d)){if(!M.isUndefined(c))return r(void 0,c,f,h)}else return r(c,d,f,h)}function s(c,d){if(!M.isUndefined(d))return r(void 0,d)}function i(c,d){if(M.isUndefined(d)){if(!M.isUndefined(c))return r(void 0,c)}else return r(void 0,d)}function a(c,d,f){if(f in t)return r(c,d);if(f in e)return r(void 0,c)}const l={url:s,method:s,data:s,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:a,headers:(c,d,f)=>o(vc(c),vc(d),f,!0)};return M.forEach(Object.keys({...e,...t}),function(d){const f=l[d]||o,h=f(e[d],t[d],d);M.isUndefined(h)&&f!==a||(n[d]=h)}),n}const wc=e=>{const t=br({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:i,auth:a}=t;if(t.headers=i=ln.from(i),t.url=cc(xc(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),M.isFormData(n)){if(Qt.hasStandardBrowserEnv||Qt.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(M.isFunction(n.getHeaders)){const l=n.getHeaders(),c=["content-type","content-length"];Object.entries(l).forEach(([d,f])=>{c.includes(d.toLowerCase())&&i.set(d,f)})}}if(Qt.hasStandardBrowserEnv&&(r&&M.isFunction(r)&&(r=r(t)),r||r!==!1&&sy(t.url))){const l=o&&s&&iy.read(s);l&&i.set(o,l)}return t},cy=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(n,r){const o=wc(e);let s=o.data;const i=ln.from(o.headers).normalize();let{responseType:a,onUploadProgress:l,onDownloadProgress:c}=o,d,f,h,p,m;function g(){p&&p(),m&&m(),o.cancelToken&&o.cancelToken.unsubscribe(d),o.signal&&o.signal.removeEventListener("abort",d)}let y=new XMLHttpRequest;y.open(o.method.toUpperCase(),o.url,!0),y.timeout=o.timeout;function x(){if(!y)return;const C=ln.from("getAllResponseHeaders"in y&&y.getAllResponseHeaders()),k={data:!a||a==="text"||a==="json"?y.responseText:y.response,status:y.status,statusText:y.statusText,headers:C,config:e,request:y};mc(function(E){n(E),g()},function(E){r(E),g()},k),y=null}"onloadend"in y?y.onloadend=x:y.onreadystatechange=function(){!y||y.readyState!==4||y.status===0&&!(y.responseURL&&y.responseURL.indexOf("file:")===0)||setTimeout(x)},y.onabort=function(){y&&(r(new Fe("Request aborted",Fe.ECONNABORTED,e,y)),y=null)},y.onerror=function(T){const k=T&&T.message?T.message:"Network Error",S=new Fe(k,Fe.ERR_NETWORK,e,y);S.event=T||null,r(S),y=null},y.ontimeout=function(){let T=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const k=o.transitional||dc;o.timeoutErrorMessage&&(T=o.timeoutErrorMessage),r(new Fe(T,k.clarifyTimeoutError?Fe.ETIMEDOUT:Fe.ECONNABORTED,e,y)),y=null},s===void 0&&i.setContentType(null),"setRequestHeader"in y&&M.forEach(i.toJSON(),function(T,k){y.setRequestHeader(k,T)}),M.isUndefined(o.withCredentials)||(y.withCredentials=!!o.withCredentials),a&&a!=="json"&&(y.responseType=o.responseType),c&&([h,m]=ns(c,!0),y.addEventListener("progress",h)),l&&y.upload&&([f,p]=ns(l),y.upload.addEventListener("progress",f),y.upload.addEventListener("loadend",p)),(o.cancelToken||o.signal)&&(d=C=>{y&&(r(!C||C.type?new Ur(null,e,y):C),y.abort(),y=null)},o.cancelToken&&o.cancelToken.subscribe(d),o.signal&&(o.signal.aborted?d():o.signal.addEventListener("abort",d)));const w=ny(o.url);if(w&&Qt.protocols.indexOf(w)===-1){r(new Fe("Unsupported protocol "+w+":",Fe.ERR_BAD_REQUEST,e));return}y.send(s||null)})},uy=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,o;const s=function(c){if(!o){o=!0,a();const d=c instanceof Error?c:this.reason;r.abort(d instanceof Fe?d:new Ur(d instanceof Error?d.message:d))}};let i=t&&setTimeout(()=>{i=null,s(new Fe(`timeout ${t} of ms exceeded`,Fe.ETIMEDOUT))},t);const a=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(c=>{c.unsubscribe?c.unsubscribe(s):c.removeEventListener("abort",s)}),e=null)};e.forEach(c=>c.addEventListener("abort",s));const{signal:l}=r;return l.unsubscribe=()=>M.asap(a),l}},dy=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let r=0,o;for(;r<n;)o=r+t,yield e.slice(r,o),r=o},fy=async function*(e,t){for await(const n of hy(e))yield*dy(n,t)},hy=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},bc=(e,t,n,r)=>{const o=fy(e,t);let s=0,i,a=l=>{i||(i=!0,r&&r(l))};return new ReadableStream({async pull(l){try{const{done:c,value:d}=await o.next();if(c){a(),l.close();return}let f=d.byteLength;if(n){let h=s+=f;n(h)}l.enqueue(new Uint8Array(d))}catch(c){throw a(c),c}},cancel(l){return a(l),o.return()}},{highWaterMark:2})},Sc=64*1024,{isFunction:rs}=M,py=(({Request:e,Response:t})=>({Request:e,Response:t}))(M.global),{ReadableStream:Cc,TextEncoder:kc}=M.global,Tc=(e,...t)=>{try{return!!e(...t)}catch{return!1}},my=e=>{e=M.merge.call({skipUndefined:!0},py,e);const{fetch:t,Request:n,Response:r}=e,o=t?rs(t):typeof fetch=="function",s=rs(n),i=rs(r);if(!o)return!1;const a=o&&rs(Cc),l=o&&(typeof kc=="function"?(m=>g=>m.encode(g))(new kc):async m=>new Uint8Array(await new n(m).arrayBuffer())),c=s&&a&&Tc(()=>{let m=!1;const g=new n(Qt.origin,{body:new Cc,method:"POST",get duplex(){return m=!0,"half"}}).headers.has("Content-Type");return m&&!g}),d=i&&a&&Tc(()=>M.isReadableStream(new r("").body)),f={stream:d&&(m=>m.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(m=>{!f[m]&&(f[m]=(g,y)=>{let x=g&&g[m];if(x)return x.call(g);throw new Fe(`Response type '${m}' is not supported`,Fe.ERR_NOT_SUPPORT,y)})});const h=async m=>{if(m==null)return 0;if(M.isBlob(m))return m.size;if(M.isSpecCompliantForm(m))return(await new n(Qt.origin,{method:"POST",body:m}).arrayBuffer()).byteLength;if(M.isArrayBufferView(m)||M.isArrayBuffer(m))return m.byteLength;if(M.isURLSearchParams(m)&&(m=m+""),M.isString(m))return(await l(m)).byteLength},p=async(m,g)=>{const y=M.toFiniteNumber(m.getContentLength());return y??h(g)};return async m=>{let{url:g,method:y,data:x,signal:w,cancelToken:C,timeout:T,onDownloadProgress:k,onUploadProgress:S,responseType:E,headers:j,withCredentials:_="same-origin",fetchOptions:P}=wc(m),D=t||fetch;E=E?(E+"").toLowerCase():"text";let z=uy([w,C&&C.toAbortSignal()],T),B=null;const O=z&&z.unsubscribe&&(()=>{z.unsubscribe()});let H;try{if(S&&c&&y!=="get"&&y!=="head"&&(H=await p(j,x))!==0){let Q=new n(g,{method:"POST",body:x,duplex:"half"}),ye;if(M.isFormData(x)&&(ye=Q.headers.get("content-type"))&&j.setContentType(ye),Q.body){const[je,J]=gc(H,ns(yc(S)));x=bc(Q.body,Sc,je,J)}}M.isString(_)||(_=_?"include":"omit");const R=s&&"credentials"in n.prototype,V={...P,signal:z,method:y.toUpperCase(),headers:j.normalize().toJSON(),body:x,duplex:"half",credentials:R?_:void 0};B=s&&new n(g,V);let $=await(s?D(B,P):D(g,V));const F=d&&(E==="stream"||E==="response");if(d&&(k||F&&O)){const Q={};["status","statusText","headers"].forEach(ue=>{Q[ue]=$[ue]});const ye=M.toFiniteNumber($.headers.get("content-length")),[je,J]=k&&gc(ye,ns(yc(k),!0))||[];$=new r(bc($.body,Sc,je,()=>{J&&J(),O&&O()}),Q)}E=E||"text";let ne=await f[M.findKey(f,E)||"text"]($,m);return!F&&O&&O(),await new Promise((Q,ye)=>{mc(Q,ye,{data:ne,headers:ln.from($.headers),status:$.status,statusText:$.statusText,config:m,request:B})})}catch(R){throw O&&O(),R&&R.name==="TypeError"&&/Load failed|fetch/i.test(R.message)?Object.assign(new Fe("Network Error",Fe.ERR_NETWORK,m,B),{cause:R.cause||R}):Fe.from(R,R&&R.code,m,B)}}},gy=new Map,Ec=e=>{let t=e?e.env:{};const{fetch:n,Request:r,Response:o}=t,s=[r,o,n];let i=s.length,a=i,l,c,d=gy;for(;a--;)l=s[a],c=d.get(l),c===void 0&&d.set(l,c=a?new Map:my(t)),d=c;return c};Ec();const Hi={http:Fg,xhr:cy,fetch:{get:Ec}};M.forEach(Hi,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Ic=e=>`- ${e}`,yy=e=>M.isFunction(e)||e===null||e===!1,Nc={getAdapter:(e,t)=>{e=M.isArray(e)?e:[e];const{length:n}=e;let r,o;const s={};for(let i=0;i<n;i++){r=e[i];let a;if(o=r,!yy(r)&&(o=Hi[(a=String(r)).toLowerCase()],o===void 0))throw new Fe(`Unknown adapter '${a}'`);if(o&&(M.isFunction(o)||(o=o.get(t))))break;s[a||"#"+i]=o}if(!o){const i=Object.entries(s).map(([l,c])=>`adapter ${l} `+(c===!1?"is not supported by the environment":"is not available in the build"));let a=n?i.length>1?`since :
|
|
33
33
|
`+i.map(Ic).join(`
|
|
34
34
|
`):" "+Ic(i[0]):"as no adapter specified";throw new Fe("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return o},adapters:Hi};function Ui(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Ur(null,e)}function Ac(e){return Ui(e),e.headers=ln.from(e.headers),e.data=Bi.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Nc.getAdapter(e.adapter||mo.adapter,e)(e).then(function(r){return Ui(e),r.data=Bi.call(e,e.transformResponse,r),r.headers=ln.from(r.headers),r},function(r){return pc(r)||(Ui(e),r&&r.response&&(r.response.data=Bi.call(e,e.transformResponse,r.response),r.response.headers=ln.from(r.response.headers))),Promise.reject(r)})}const _c="1.12.2",os={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{os[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const jc={};os.transitional=function(t,n,r){function o(s,i){return"[Axios v"+_c+"] Transitional option '"+s+"'"+i+(r?". "+r:"")}return(s,i,a)=>{if(t===!1)throw new Fe(o(i," has been removed"+(n?" in "+n:"")),Fe.ERR_DEPRECATED);return n&&!jc[i]&&(jc[i]=!0,console.warn(o(i," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(s,i,a):!0}},os.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function xy(e,t,n){if(typeof e!="object")throw new Fe("options must be an object",Fe.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const s=r[o],i=t[s];if(i){const a=e[s],l=a===void 0||i(a,s,e);if(l!==!0)throw new Fe("option "+s+" must be "+l,Fe.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Fe("Unknown option "+s,Fe.ERR_BAD_OPTION)}}const ss={assertOptions:xy,validators:os},zn=ss.validators;let Sr=class{constructor(t){this.defaults=t||{},this.interceptors={request:new uc,response:new uc}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=`
|
|
35
|
-
`+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=br(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&ss.assertOptions(r,{silentJSONParsing:zn.transitional(zn.boolean),forcedJSONParsing:zn.transitional(zn.boolean),clarifyTimeoutError:zn.transitional(zn.boolean)},!1),o!=null&&(M.isFunction(o)?n.paramsSerializer={serialize:o}:ss.assertOptions(o,{encode:zn.function,serialize:zn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),ss.assertOptions(n,{baseUrl:zn.spelling("baseURL"),withXsrfToken:zn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&M.merge(s.common,s[n.method]);s&&M.forEach(["delete","get","head","post","put","patch","common"],m=>{delete s[m]}),n.headers=ln.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(n)===!1||(l=l&&g.synchronous,a.unshift(g.fulfilled,g.rejected))});const c=[];this.interceptors.response.forEach(function(g){c.push(g.fulfilled,g.rejected)});let d,f=0,h;if(!l){const m=[Ac.bind(this),void 0];for(m.unshift(...a),m.push(...c),h=m.length,d=Promise.resolve(n);f<h;)d=d.then(m[f++],m[f++]);return d}h=a.length;let p=n;for(;f<h;){const m=a[f++],g=a[f++];try{p=m(p)}catch(y){g.call(this,y);break}}try{d=Ac.call(this,p)}catch(m){return Promise.reject(m)}for(f=0,h=c.length;f<h;)d=d.then(c[f++],c[f++]);return d}getUri(t){t=br(this.defaults,t);const n=xc(t.baseURL,t.url,t.allowAbsoluteUrls);return cc(n,t.params,t.paramsSerializer)}};M.forEach(["delete","get","head","options"],function(t){Sr.prototype[t]=function(n,r){return this.request(br(r||{},{method:t,url:n,data:(r||{}).data}))}}),M.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(br(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Sr.prototype[t]=n(),Sr.prototype[t+"Form"]=n(!0)});let vy=class Ym{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(o=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{r.subscribe(a),s=a}).then(o);return i.cancel=function(){r.unsubscribe(s)},i},t(function(s,i,a){r.reason||(r.reason=new Ur(s,i,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Ym(function(o){t=o}),cancel:t}}};function wy(e){return function(n){return e.apply(null,n)}}function by(e){return M.isObject(e)&&e.isAxiosError===!0}const Wi={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Wi).forEach(([e,t])=>{Wi[t]=e});function Pc(e){const t=new Sr(e),n=Gl(Sr.prototype.request,t);return M.extend(n,Sr.prototype,t,{allOwnKeys:!0}),M.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Pc(br(e,o))},n}const Rt=Pc(mo);Rt.Axios=Sr,Rt.CanceledError=Ur,Rt.CancelToken=vy,Rt.isCancel=pc,Rt.VERSION=_c,Rt.toFormData=es,Rt.AxiosError=Fe,Rt.Cancel=Rt.CanceledError,Rt.all=function(t){return Promise.all(t)},Rt.spread=wy,Rt.isAxiosError=by,Rt.mergeConfig=br,Rt.AxiosHeaders=ln,Rt.formToJSON=e=>fc(M.isHTMLForm(e)?new FormData(e):e),Rt.getAdapter=Nc.getAdapter,Rt.HttpStatusCode=Wi,Rt.default=Rt;const{Axios:kT,AxiosError:TT,CanceledError:ET,isCancel:IT,CancelToken:NT,VERSION:AT,all:_T,Cancel:jT,isAxiosError:PT,spread:RT,toFormData:OT,AxiosHeaders:MT,HttpStatusCode:DT,formToJSON:LT,getAdapter:FT,mergeConfig:$T}=Rt,Rc=typeof window<"u"?window.__API_BASE_URL__:void 0,Oc=Rc?Zn(Rc):void 0;function Zn(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let is=null;const Vi=new Set;let Ki=null;function Mc(){return is}function qi(e){is=e,Vi.forEach(t=>t(e))}function Dc(e){return Vi.add(e),()=>Vi.delete(e)}function Sy(e){Ki=e}const Cy=3e4,ky=9e4,vn=Rt.create({...Oc?{baseURL:Oc}:{},timeout:Cy,withCredentials:!0});vn.interceptors.request.use(e=>(is&&(e.headers.Authorization=`Bearer ${is}`),e)),vn.interceptors.response.use(e=>{if(Ki&&(e!=null&&e.data))try{Ki(e.data)}catch(t){console.warn("[chat-api] Error in token sync handler:",t)}return e},e=>Promise.reject(e));async function wn(e,t){return vn.defaults.baseURL?(await vn.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function Gi(e,t,n){return vn.defaults.baseURL?(await vn.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Lc(e,t,n){return vn.defaults.baseURL?(await vn.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Fc(e,t){return vn.defaults.baseURL?(await vn.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function bn(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class $c{get baseUrl(){const t=vn.defaults.baseURL;return t?Zn(String(t)):""}updateConfig(t){t.baseUrl&&(vn.defaults.baseURL=Zn(String(t.baseUrl))),t.authToken!==void 0&&qi(t.authToken)}getAuthToken(){return Mc()}setAuthToken(t){qi(t)}onTokenChange(t){return Dc(t)}async listThreads(){const t=await wn("/threads"),n=bn(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await Gi("/threads",t?{title:t}:void 0);return bn(r)}async updateThread(t,n){const r=await Lc(`/threads/${t}`,{title:n});return bn(r)}async deleteThread(t){const n=await Fc(`/threads/${t}`);return bn(n)}async threadInfo(t){const n=await wn(`/threads/${t}/info`);return bn(n)}async listAgents(){const t=await wn("/agents"),n=bn(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await wn(`/agents/${t}`);return bn(n)}async getAgentSchema(t){const n=await wn(`/agents/${t}/schema`);return bn(n)}async getState(t){const n=await wn(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return bn(n)}async getStateHistory(t){const n=await wn(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:ky});return bn(n)}async cancelRun(t){const n=await Gi("/runs/cancel",{threadId:t});return bn(n)}async listCheckpointSummaries(t){const n=await wn(`/threads/${t}/state/checkpoints`,{params:{thread_id:t}}),r=bn(n);return(r==null?void 0:r.items)??[]}}const sr=new $c,zc=b.createContext(null);function Ty({children:e,apiConfig:t}){const n=sr;if(t){const o=n.baseUrl,s=n.getAuthToken();t.baseUrl&&t.baseUrl!==o&&n.updateConfig({baseUrl:t.baseUrl}),t.apiKey!==void 0&&t.apiKey!==s&&n.updateConfig({authToken:t.apiKey})}const r={token:n.getAuthToken(),setToken:o=>n.setAuthToken(o),api:n,baseUrl:n.baseUrl};return u.jsx(zc.Provider,{value:r,children:e})}function Yi(){const e=b.useContext(zc);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function Ey(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const o=r.result,s=new Uint8Array(o);let i="";const a=s.byteLength;for(let l=0;l<a;l++)i+=String.fromCharCode(s[l]);t(btoa(i))}catch(o){n(o)}},r.onerror=o=>n(o),r.readAsArrayBuffer(e)})}async function Iy(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const c=await Ey(l);a.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const Ny={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function Xi(e){if(!e||typeof e!="object")return!1;const t=e;return"values"in t&&"config"in t&&typeof t.values=="object"&&t.values!==null&&typeof t.config=="object"&&t.config!==null}function Wr(e,t){return`${e??""}::${t??""}`}function as(e){const t=Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[],n=(e==null?void 0:e.threadId)??"",r=t[0];if(!Xi(r))return{threadId:n,latest:null,checkpoints:[],interrupt:null,snapshots:{}};const{orderedSnapshots:o,snapshotMap:s}=_y(t),i=Bc(r,0);return{threadId:n,latest:i,checkpoints:o,interrupt:(i==null?void 0:i.interrupt)??null,snapshots:s}}function Bc(e,t){if(!Xi(e))return null;const n=e.values??{messages:[]},r=Array.isArray(n==null?void 0:n.messages)?n.messages:[],{messages:o,...s}=n,i=Object.keys(s).length?s:null,a=e.tasks,l=Array.isArray(a)?a.filter(_=>!!_&&typeof _=="object").map(_=>({..._})):a===null?null:void 0,c=r.map((_,P)=>Ly(_,P)).filter(_=>!!_),d=cn(e.config),f=cn(d==null?void 0:d.configurable),h=Lt(f,["checkpoint_id","checkpointId"]),p=Lt(f,["checkpoint_ns","checkpointNs"]),m=cn(e==null?void 0:e.parentConfig),g=cn(m==null?void 0:m.configurable),y=Lt(g,["checkpoint_id","checkpointId"])??null,x=Lt(g,["checkpoint_ns","checkpointNs"])??null,w=e==null?void 0:e.createdAt,C=typeof w=="string"&&w.trim()?w:new Date(Date.now()-t).toISOString(),T=c[c.length-1]??null,k=cn(e==null?void 0:e.metadata),S=Lt(k,["branch_label","branchLabel"]),E=Lt(g,["checkpoint_id","checkpointId"]),j=Array.isArray(e.next)?[...e.next]:(e==null?void 0:e.next)===null?null:void 0;return{messages:c,checkpointId:h??null,checkpointNs:p??null,nextCursor:y,nextCursorNs:x,interrupt:Ay(a,c,t),createdAt:C,parentId:E??null,branchLabel:S??null,lastMessageId:(T==null?void 0:T.id)??null,hasMessages:c.length>0,messagesLen:c.length,metadata:k??null,config:d??null,parentConfig:m??null,next:j??null,tasks:l??null,values:i??null}}function Ay(e,t,n){const r=My(e,n);return r||Oy(t,n)}function _y(e){const t=new Map;e.forEach((o,s)=>{if(!Xi(o))return;const i=Bc(o,s);if(!(i!=null&&i.checkpointId))return;const a=Wr(i.checkpointId,i.checkpointNs??null),l=t.get(a);if(!l){t.set(a,i);return}t.set(a,jy(l,i))});const n=Array.from(t.values());n.sort((o,s)=>Uc(s.createdAt??"")-Uc(o.createdAt??""));const r={};for(const[o,s]of t.entries())r[o]=s;return{orderedSnapshots:n,snapshotMap:r}}function jy(e,t){return{...e,metadata:ls(e.metadata,t.metadata)??null,config:ls(e.config,t.config)??null,parentConfig:ls(e.parentConfig,t.parentConfig)??null,next:Py(e.next,t.next)??null,tasks:Ry(e.tasks,t.tasks)??null,values:ls(e.values,t.values)??null}}function ls(e,t){return t&&typeof t=="object"?{...e&&typeof e=="object"?e:{},...t}:t===null?e&&typeof e=="object"?{...e}:e??null:e&&typeof e=="object"?{...e}:e??void 0}function Py(e,t){return Array.isArray(t)?t.slice():t===null?Array.isArray(e)?e.slice():e??null:Array.isArray(e)?e.slice():e??void 0}function Ry(e,t){return Array.isArray(t)?t.map(n=>({...n})):t===null?Array.isArray(e)?e.map(n=>({...n})):e??null:Array.isArray(e)?e.map(n=>({...n})):e??void 0}function Oy(e,t){var n;for(let r=e.length-1;r>=0;r--){const o=((n=e[r])==null?void 0:n.content)??[];for(let s=o.length-1;s>=0;s--){const i=o[s];if((i==null?void 0:i.type)==="interrupt"){const a=i;return{id:typeof a.id=="string"&&a.id.trim()?a.id:`interrupt-${t}-${r}-${s}`,value:a.value}}}}return null}function My(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=Dy(e[n],`task-${t}-${n}`);if(!r)continue;const o=r.id||`task-${t}-${n}`;if(Array.isArray(r.interrupts)&&r.interrupts.length)for(let s=r.interrupts.length-1;s>=0;s--){const i=yo(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=yo(r.state,`${o}-state`);if(s)return s}}return null}function Dy(e,t){if(!e)return null;if(Array.isArray(e)){const[a,l,c,,d,,f,...h]=e,p=typeof a=="string"&&a.trim()?a:t,m=typeof l=="string"&&l.trim()?l:Array.isArray(c)&&typeof c[0]=="string"?String(c[0]):"task",g=Array.isArray(d)?d:void 0,y=h.length?h[h.length-1]:void 0;return{id:p,name:m,interrupts:g,state:y!==void 0?y:f}}const n=cn(e);if(!n)return null;const r=Lt(n,["id","task_id","taskId"])??t,o=Lt(n,["name"])??"task",s=Array.isArray(n.interrupts)?n.interrupts:void 0,i=Object.prototype.hasOwnProperty.call(n,"state")?n.state:void 0;return{id:r,name:o,interrupts:s,state:i}}function yo(e,t,n=0,r=new Set){if(n>6||e==null)return null;if(typeof e=="object"){if(r.has(e))return null;r.add(e)}const o=Hc(e,t);if(o)return o;if(Array.isArray(e)){for(let s=e.length-1;s>=0;s--){const i=yo(e[s],t,n+1,r);if(i)return i}return null}if(typeof e=="object"){const s=e,i=["interrupt","pending_interrupt","pendingInterrupt","value","data","payload","result","response"];for(const a of i)if(a in s){const l=yo(s[a],t,n+1,r);if(l)return l}for(const[a,l]of Object.entries(s)){if(i.includes(a)||a==="messages"||a==="results")continue;const c=yo(l,t,n+1,r);if(c)return c}}return null}function Hc(e,t){if(!e)return null;if(typeof e=="object"&&!Array.isArray(e)){const n=e,r=Lt(n,["type","event","kind"]),o=Lt(n,["id","interrupt_id","interruptId","value_id"])??(r&&r.toLowerCase().includes("interrupt")?t:void 0);if(!(Object.prototype.hasOwnProperty.call(n,"value")||Object.prototype.hasOwnProperty.call(n,"data")||Object.prototype.hasOwnProperty.call(n,"payload"))&&!(r&&r.toLowerCase().includes("interrupt")))return null;const i=Object.prototype.hasOwnProperty.call(n,"value")?n.value:Object.prototype.hasOwnProperty.call(n,"data")?n.data:Object.prototype.hasOwnProperty.call(n,"payload")?n.payload:n,a=o&&o.trim()?o:t;return a?{id:a,value:i}:null}if(Array.isArray(e)){for(let n=e.length-1;n>=0;n--){const r=Hc(e[n],t);if(r)return r}return e.length>=2&&typeof e[0]=="string"&&e[0].trim()?{id:e[0],value:e[1]}:null}if(typeof e=="string"){const n=e.trim();return n?{id:t||n,value:n}:null}return null}function Uc(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Ly(e,t){if(!e||typeof e!="object")return null;const n=e,r=cn(e)??{},o=cn(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=Ny[s];if(!i)return null;const a=o.id??o.message_id??o.run_id??null,l=typeof a=="string"&&a.trim()?a:`history-${i}-${t}`,c=cn(o.additional_kwargs)??cn(o.additionalKwargs),d=cn(o.response_metadata)??cn(o.responseMetadata),f=Lt(c,["createdAt","created_at"])??Lt(o,["created_at","createdAt"]),h=Lt(c,["checkpointId","checkpoint_id"]),p=Lt(c,["checkpointNs","checkpoint_ns"]),m=Fy(o.content),g={id:l,role:i,content:m};f&&(g.createdAt=f),typeof o.name=="string"&&o.name.trim()&&(g.name=o.name),typeof(d==null?void 0:d.model_name)=="string"&&(g.model=String(d.model_name)),!g.model&&typeof o.model=="string"&&(g.model=o.model),h&&(g.checkpointId=h),p&&(g.checkpointNs=p);const y=Hy(c,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),x=d?{...d}:void 0;y&&Object.keys(y).length&&(g.additionalKwargs=y),x&&Object.keys(x).length&&(g.responseMetadata=x);const w=$y((c==null?void 0:c.tool_calls)??o.tool_calls);if(w.length&&(g.content=[...g.content,...w]),i==="tool"){const C=zy(o,g.content);C&&(g.content=C)}return g}function Fy(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>Wc(t)).filter(t=>!!t);if(typeof e=="string")return e.trim()?[{type:"text",text:e.trim()}]:[];if(typeof e=="object"){const t=Wc(e);return t?[t]:[]}return[]}function Wc(e){if(!e||typeof e!="object")return typeof e=="string"&&e.trim()?{type:"text",text:e}:null;const t=e,n=String(t.type??"").toLowerCase();if(!n||n==="text"){const o=typeof t.text=="string"?t.text:typeof t.value=="string"?t.value:"";return o.trim()?{type:"text",text:o}:null}if(n==="image"||n==="image_url"){const o=Lt(t,["url","src"]);if(!o)return null;const s={type:"image_url",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.alt=="string"&&(s.alt=t.alt),s}if(n==="file"){const o=Lt(t,["url"]);if(!o)return null;const s={type:"file",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.name=="string"&&(s.name=t.name),typeof t.size=="number"&&(s.size=t.size),typeof t.sourceType=="string"&&(s.sourceType=t.sourceType),s}if(n==="tool_call")return Vc(t)??null;if(n==="tool_end"){const o="output"in t?t.output:t.content;return o?{type:"text",text:typeof o=="string"?o:JSON.stringify(o)}:null}if(n==="interrupt")return{type:"interrupt",value:t.value,...t};if(n==="tool"){const o=Lt(t,["text","content"]);if(o)return{type:"text",text:o}}const r=typeof t.content=="string"?t.content:typeof t.value=="string"?t.value:JSON.stringify(t);return r?{type:"text",text:r}:null}function Vc(e,t){var s;const n=Lt(e,["id","call_id"])??t,r=Lt(e,["name"])??Lt(cn(e.function),["name"]);if(!n||!r)return null;const o=By(e.args??e.arguments??((s=cn(e.function))==null?void 0:s.arguments));return{type:"tool_call",id:n,name:r,args:o}}function $y(e){return Array.isArray(e)?e.map((t,n)=>Vc(t,`tool_call_${n}`)).filter(t=>!!t):[]}function zy(e,t){const n=e.content??e.output;if(!n)return t;const o={type:"text",text:typeof n=="string"?n:JSON.stringify(n)};return[...t,o]}function By(e){if(!e)return{};if(typeof e=="string")try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{raw:e}}catch{return{raw:e}}return typeof e=="object"&&!Array.isArray(e)?{...e}:{}}function cn(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function Lt(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r}}function Hy(e,t){if(!e)return;const n={};let r=!1;for(const[o,s]of Object.entries(e)){if(t.includes(o)){r=!0;continue}s!==void 0&&(n[o]=s)}return r?Object.keys(n).length?n:void 0:e}function Uy(e){return e.type!=="thread_info"&&e.type!=="token"}const Wy={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,messagesStreamMeta:{},pendingInterrupt:null};function Vy(e,t){var n;switch(t.type){case"reset":return{messages:Ji(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,pendingInterrupt:null};case"seed":{const r=Ji(t.payload.messages),o={...e,messages:r,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(o.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(o.lastCheckpointNs=t.payload.checkpointNs??null),o}case"prepend":{const r=Ji(t.payload.messages);if(!r.length)return e;const o=new Set(e.messages.map(i=>i.id)),s=r.filter(i=>!o.has(i.id));return s.length?{...e,messages:[...s,...e.messages]}:e}case"user_message":{const r=t.payload.message;return e.messages.some(o=>o.id===r.id)?e:{...e,messages:[...e.messages,r]}}case"event":return qc(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>qc(o,s),e):e}case"interrupt_response":return{...e,messages:Gc(e.messages),pendingInterrupt:null};default:return e}}function Kc(e=[]){const[t,n]=b.useReducer(Vy,{...Wy,messages:e}),r=b.useRef([]),o=b.useRef(null),s=b.useRef(null),i=b.useCallback(()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),o.current=null,s.current=null;const d=r.current;d.length&&(r.current=[],n({type:"batch",payload:{events:d}}))},[]),a=b.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o.current===null&&(o.current=window.requestAnimationFrame(()=>i())):s.current===null&&(s.current=setTimeout(i,8))},[i]),l=b.useCallback(d=>{r.current.push(d),a()},[a]);b.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const c=b.useMemo(()=>({reset:d=>n({type:"reset",payload:{messages:d}}),seed:(d,f)=>n({type:"seed",payload:{messages:d,...f??{}}}),prepend:d=>n({type:"prepend",payload:{messages:d}}),pushUser:d=>n({type:"user_message",payload:{message:d}}),onEvent:l}),[l]);return{state:t,dispatch:n,...c}}function qc(e,t){var n,r,o,s,i;if(t.type==="message_start"&&t.role==="assistant"){const a=t.id,l=Yy(t.model);if(e.messages.some(f=>f.id===a)){const f=e.messagesStreamMeta??{},h={...f,[a]:f[a]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:a,messagesStreamMeta:h}}const d={id:a,role:"assistant",name:l||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:a,messages:[...e.messages,d]}}if(t.type==="message_delta"){const a=e.assemblingId??Yc(e.messages);if(!a)return e;const l=e.messages,c=l.findIndex(T=>T.id===a&&T.role==="assistant");if(c===-1)return e;const d=l[c],f=e.messagesStreamMeta??{},h=f[a]??{lastSeq:null,lastText:Zc(d.content)},p=t.seq??null;if(p!==null&&typeof p=="number"&&typeof h.lastSeq=="number"&&p<=h.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:p,lastSeq:h.lastSeq}),e;const{newParts:m,newMeta:g,changed:y}=Ky(d.content,t.delta,h,p);if(!y)return e;const x={...d,content:m},w=cs(l,c,x),C={...f,[a]:g};return{...e,messages:w,messagesStreamMeta:C}}if(t.type==="message_end"){const a=e.assemblingId??Yc(e.messages);if(!a)return{...e,assemblingId:null};const l=e.messages,c=l.findIndex(d=>d.id===a&&d.role==="assistant");if(c>=0){const d=l[c];if(!((n=d.content)==null?void 0:n.some(h=>{var p;return(h==null?void 0:h.type)==="text"&&((p=h.text)==null?void 0:p.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:d.id,contentTypes:(r=d.content)==null?void 0:r.map(p=>p==null?void 0:p.type),contentPreview:(o=d.content)==null?void 0:o.map(p=>(p==null?void 0:p.type)==="text"?String(p.text).slice(0,100):p==null?void 0:p.type)});const h=[...l.slice(0,c),...l.slice(c+1)];return{...e,assemblingId:null,messages:h}}}return e}if(t.type==="tool_start"){const a=Xc(t),l=a[0]??(typeof t.id=="string"?t.id:null)??(typeof t.call_id=="string"?t.call_id:null),c=t.name??t.tool??"tool";!l&&a.length===0&&a.push(`${c}-${Date.now()}`);const d=a.length?a:l?[l]:[],f=Jc(e,d,c),h=f>=0?e.messages[f]:null,p=l??d[0]??`${c}-${Date.now()}`,m=(h==null?void 0:h.id)??`tool-${p}`,g=d[0]??p,y={type:"tool_call",id:g,name:c,args:t.args};if(h){const C=Qi(h,d,c,t.args),T={...h,name:h.name??c,additionalKwargs:C},k=f,S=k>=0?cs(e.messages,k,T):e.messages,E=us(T,d),j=ea(e.toolIndex,m,E);return{...e,messages:S,toolIndex:j}}const x={id:m,role:"tool",name:c,createdAt:new Date().toISOString(),content:[y],additionalKwargs:Qi(void 0,d.length?d:[g],c,t.args)},w=us(x,d.length?d:[g]);return{...e,messages:[...e.messages,x],toolIndex:ea(e.toolIndex,m,w)}}if(t.type==="tool_end"){const a=Xc(t);if(!a.length&&!(typeof t.id=="string"&&t.id))return e;const l=t.name??null,c=Jc(e,a,l),d=c>=0?e.messages[c]:null,f=l??(d==null?void 0:d.name)??((s=d==null?void 0:d.additionalKwargs)==null?void 0:s.toolName)??"tool",h=a[0]??((i=d==null?void 0:d.id)==null?void 0:i.replace(/^tool-/,""))??`${f}-${Date.now()}`,p=(d==null?void 0:d.id)??`tool-${h}`,m=us(d,a);let g=t.output;if(typeof t.output=="string")try{const S=t.output.trim();(S.startsWith("{")||S.startsWith("["))&&(g=JSON.parse(S))}catch{g=t.output}const y={type:"text",text:typeof g=="string"?g:JSON.stringify(g)},x=(d==null?void 0:d.createdAt)??new Date().toISOString(),w=Qi(d??void 0,m.length?m:a,f),C={id:p,role:"tool",name:f??(d==null?void 0:d.name)??"tool",content:[y],createdAt:x,additionalKwargs:w},T=c>=0?cs(e.messages,c,C):[...e.messages,C],k=us(C,a.length?a:m);return{...e,messages:T,toolIndex:ea(e.toolIndex,p,k)}}if(t.type==="checkpoint"){const a=t.checkpointNs??e.lastCheckpointNs??null,l=Gy(e.messages,t.checkpointId,a);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:a,messages:l}}if(t.type==="branch"){const a=t.checkpointId??e.lastCheckpointId,l=t.checkpointNs??e.lastCheckpointNs;return{...e,lastBranch:t,lastCheckpointId:a??null,lastCheckpointNs:l??null}}if(t.type==="error"){const a={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,a]}}if(t.type==="state_history"){const a=as(t),l=a.interrupt,c=a.latest,d=l===null?Gc(e.messages):e.messages;return{...e,messages:d,pendingInterrupt:l,lastCheckpointId:(c==null?void 0:c.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(c==null?void 0:c.checkpointNs)??e.lastCheckpointNs}}return e}function Ji(e){return e.filter(t=>{if(t.role!=="assistant")return!0;const n=(t.content||[]).some(o=>{var s;return o&&o.type==="text"&&((s=o.text)==null?void 0:s.trim())}),r=(t.content||[]).some(o=>o&&o.type==="image_url");return!!(n||r)})}function cs(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function Gc(e){let t=!1;const n=e.map(r=>{const o=(r.content??[]).filter(s=>s.type!=="interrupt");return o.length!==r.content.length?(t=!0,{...r,content:o}):r});return t?n:e}function Yc(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function Xc(e){const t=new Set,n=r=>{typeof r=="string"&&r.trim()&&t.add(r.trim())};return n(e.id),n(e==null?void 0:e.call_id),n(e==null?void 0:e.callId),Array.from(t)}function Zi(e){if(!e)return[];const t=new Set,n=o=>{typeof o=="string"&&o.trim()&&t.add(o.trim())},r=e.additionalKwargs;if(r){n(r.toolCallId);const o=r.toolCallIds;if(Array.isArray(o))for(const s of o)n(s)}for(const o of e.content??[])(o==null?void 0:o.type)==="tool_call"&&n(o.id);return Array.from(t)}function Qi(e,t,n,r){const o=new Set,s=l=>{typeof l=="string"&&l.trim()&&o.add(l.trim())};if(e){const l=Zi(e);for(const c of l)s(c)}for(const l of t)s(l);const i=Array.from(o),a={...(e==null?void 0:e.additionalKwargs)??{}};if(i.length){a.toolCallIds=i;const l=typeof a.toolCallId=="string"?a.toolCallId.trim():null;a.toolCallId=l&&o.has(l)?l:i[0]}return n&&(a.toolName=n),r!==void 0&&(a.toolArgs=r),a}function us(e,t){const n=new Set;for(const o of t)typeof o=="string"&&o.trim()&&n.add(o.trim());const r=Zi(e);for(const o of r)n.add(o);return Array.from(n)}function ea(e,t,n){if(!n.length)return e;let r=!1;const o={...e};for(const s of n)s&&o[s]!==t&&(o[s]=t,r=!0);return r?o:e}function Jc(e,t,n){var o,s;const r=new Set(t.filter(i=>typeof i=="string"&&i.trim()));for(const i of r){const a=e.toolIndex[i];if(a){const l=e.messages.findIndex(c=>c.id===a);if(l!==-1)return l}}for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool")continue;if(Zi(a).some(c=>r.has(c)))return i}if(typeof n=="string"&&n.trim())for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool"||a.name&&a.name!==n)continue;if(!((o=a.content)==null?void 0:o.some(c=>c.type!=="tool_call")))return i}for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool")continue;if(!((s=a.content)==null?void 0:s.some(c=>c.type!=="tool_call")))return i}return-1}function Zc(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function Ky(e,t,n,r){const o={...n};if(r!==null&&typeof r=="number"){if(typeof o.lastSeq=="number"&&r<=o.lastSeq)return{newParts:e,newMeta:o,changed:!1};o.lastSeq=r}const s=t.filter(f=>f.type==="text").map(f=>f.text??"").join(""),i=t.filter(f=>f.type!=="text"),a=o.lastText??Zc(e);let l="",c=e.slice();if(s){const f=qy(a,s);if(f===""?l="":f===s?l=s:l=f,l){const h=c[c.length-1];if((h==null?void 0:h.type)==="text"){const p=h.text??"",m={...h,text:p+l};c=[...c.slice(0,c.length-1),m]}else c=[...c,{type:"text",text:l}];o.lastText=a+l}else o.lastText=a}i.length&&(c=[...c,...i]);const d=!!(l||i.length);return{newParts:c,newMeta:o,changed:d}}function Qc(e){return e.replace(/\s+/g," ").trim()}function qy(e,t){if(!t)return"";if(!e)return t;if(e===t)return"";const n=Math.min(e.length,t.length);for(let i=n;i>0;i--)if(e.slice(-i)===t.slice(0,i))return t.slice(i);const r=Qc(e),o=Qc(t);if(r===o)return"";const s=Math.min(r.length,o.length);for(let i=s;i>0;i--)if(r.slice(-i)===o.slice(0,i))return t;return t}function Gy(e,t,n){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const s={...e[r],checkpointId:t,checkpointNs:n??void 0};return cs(e,r,s)}return e}function Yy(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}function eu(e={}){const t=b.useMemo(()=>Zn(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=b.useState(e.token??null),s=b.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=b.useState(!1),[c,d]=b.useState(null),[f,h]=b.useState(""),[p,m]=b.useState(null),[g,y]=b.useState(0),[x,w]=b.useState(!1),C=b.useRef(null),T=b.useRef(!0),k=b.useRef(0),S=b.useRef(null),E=b.useRef(null),j=b.useRef(null),_=b.useRef(null),P=b.useCallback(O=>{o(O)},[]),D=b.useCallback(()=>{h(""),m(null),d(null),E.current=null,j.current=null,_.current=null},[]),z=b.useCallback(()=>{var O;console.debug("[use-chat] stop() invoked - aborting stream"),(O=C.current)==null||O.abort(),C.current=null,S.current=null,l(!1),w(!1),k.current=0,y(0)},[]),B=b.useCallback((O,H,R)=>{C.current&&(C.current.abort(),C.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&h(""),m(null),E.current=null,j.current=null,_.current=null;const V=new AbortController;C.current=V;let $=null,F=null,ne=!1;return S.current={threadId:O.threadId??null,headers:{}},(async()=>{var ye,je,J,ue,ke,te,L,q,ie,ce,U,We,re,xe,Pe,$e,rt,Se;const Q=Ye=>{var ot;try{const et=JSON.parse(JSON.stringify(Ye));return(ot=et==null?void 0:et.payload)!=null&&ot.files_info&&Array.isArray(et.payload.files_info)&&(et.payload.files_info=et.payload.files_info.map(Xe=>({...Xe,data:Xe!=null&&Xe.data?`<base64 ${String(Xe.data).length} chars>`:Xe==null?void 0:Xe.data}))),et}catch{return Ye}};try{let Ye={};try{if(r)Ye={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const Ve=window.__AUTH_TOKEN__,Mt=((ye=window.localStorage)==null?void 0:ye.getItem("authToken"))||null;let jt=null;try{const Te=(je=window.localStorage)==null?void 0:je.getItem("chat-settings");Te&&(jt=((J=JSON.parse(Te))==null?void 0:J.apiKey)||null)}catch{}const G=Ve||Mt||jt||null;G&&(Ye={Authorization:`Bearer ${G}`})}}catch{}console.debug("[use-chat] POST",t+n,Q(O));let ot={};if(typeof window<"u")try{const ft=(ue=window.localStorage)==null?void 0:ue.getItem("authSessionId");ft&&(ot={"X-Session-Id":ft})}catch{}const et={...Ye,...ot,...s.current},Xe={"Content-Type":"application/json",Accept:"text/event-stream",...et},Ke=await fetch(t+n,{method:"POST",headers:Xe,body:JSON.stringify(O),signal:V.signal,credentials:i});if(S.current&&(S.current.headers=et),!Ke.ok||!Ke.body){const ft=await Ke.text().catch(()=>"");console.debug("[use-chat] non-OK response",Ke.status,ft==null?void 0:ft.slice(0,500));const Ve=`stream ${Ke.status}${ft?": "+ft:""}`;throw(ke=R==null?void 0:R.onConnectionError)==null||ke.call(R,Ve),ne=!0,$="error",F=Ve,new Error(Ve)}w(!0);const tt=Ke.body.getReader(),_t=new TextDecoder;let St="",nt=[];k.current=0,y(0);let yt=0,Nt=null;const st=()=>{if(nt.length){const ft=nt.join("");nt=[],T.current&&h(Ve=>Ve+ft)}Nt=null},Gt=()=>{typeof window<"u"&&Nt==null&&(Nt=requestAnimationFrame(st))};let Yt=Date.now();const Xt=setInterval(()=>{var ft;if(Date.now()-Yt>18e5){const Ve="Stream idle timeout";d(Ve),$="error",F=Ve,V.abort(),(ft=R==null?void 0:R.onError)==null||ft.call(R,Ve)}},5e3),Jt=1024*1024;try{const ft=Ke.headers.get("X-Thread-Id")||Ke.headers.get("x-thread-id"),Ve=Ke.headers.get("X-Thread-Created")||Ke.headers.get("x-thread-created"),Mt=ft??null,jt=String(Ve??"").toLowerCase()==="true";for(S.current&&!S.current.threadId&&(S.current={...S.current,threadId:Mt}),(te=R==null?void 0:R.onOpen)==null||te.call(R,{threadId:Mt,created:jt});;){const{value:G,done:Te}=await tt.read();if(Te)break;St+=_t.decode(G,{stream:!0}),St.length>Jt&&(St="",console.warn("Stream buffer reset: exceeded 1MB"));let ve;for(;(ve=St.indexOf(`
|
|
35
|
+
`+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=br(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&ss.assertOptions(r,{silentJSONParsing:zn.transitional(zn.boolean),forcedJSONParsing:zn.transitional(zn.boolean),clarifyTimeoutError:zn.transitional(zn.boolean)},!1),o!=null&&(M.isFunction(o)?n.paramsSerializer={serialize:o}:ss.assertOptions(o,{encode:zn.function,serialize:zn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),ss.assertOptions(n,{baseUrl:zn.spelling("baseURL"),withXsrfToken:zn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&M.merge(s.common,s[n.method]);s&&M.forEach(["delete","get","head","post","put","patch","common"],m=>{delete s[m]}),n.headers=ln.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(n)===!1||(l=l&&g.synchronous,a.unshift(g.fulfilled,g.rejected))});const c=[];this.interceptors.response.forEach(function(g){c.push(g.fulfilled,g.rejected)});let d,f=0,h;if(!l){const m=[Ac.bind(this),void 0];for(m.unshift(...a),m.push(...c),h=m.length,d=Promise.resolve(n);f<h;)d=d.then(m[f++],m[f++]);return d}h=a.length;let p=n;for(;f<h;){const m=a[f++],g=a[f++];try{p=m(p)}catch(y){g.call(this,y);break}}try{d=Ac.call(this,p)}catch(m){return Promise.reject(m)}for(f=0,h=c.length;f<h;)d=d.then(c[f++],c[f++]);return d}getUri(t){t=br(this.defaults,t);const n=xc(t.baseURL,t.url,t.allowAbsoluteUrls);return cc(n,t.params,t.paramsSerializer)}};M.forEach(["delete","get","head","options"],function(t){Sr.prototype[t]=function(n,r){return this.request(br(r||{},{method:t,url:n,data:(r||{}).data}))}}),M.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(br(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Sr.prototype[t]=n(),Sr.prototype[t+"Form"]=n(!0)});let vy=class Ym{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(o=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{r.subscribe(a),s=a}).then(o);return i.cancel=function(){r.unsubscribe(s)},i},t(function(s,i,a){r.reason||(r.reason=new Ur(s,i,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Ym(function(o){t=o}),cancel:t}}};function wy(e){return function(n){return e.apply(null,n)}}function by(e){return M.isObject(e)&&e.isAxiosError===!0}const Wi={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Wi).forEach(([e,t])=>{Wi[t]=e});function Pc(e){const t=new Sr(e),n=Gl(Sr.prototype.request,t);return M.extend(n,Sr.prototype,t,{allOwnKeys:!0}),M.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Pc(br(e,o))},n}const Pt=Pc(mo);Pt.Axios=Sr,Pt.CanceledError=Ur,Pt.CancelToken=vy,Pt.isCancel=pc,Pt.VERSION=_c,Pt.toFormData=es,Pt.AxiosError=Fe,Pt.Cancel=Pt.CanceledError,Pt.all=function(t){return Promise.all(t)},Pt.spread=wy,Pt.isAxiosError=by,Pt.mergeConfig=br,Pt.AxiosHeaders=ln,Pt.formToJSON=e=>fc(M.isHTMLForm(e)?new FormData(e):e),Pt.getAdapter=Nc.getAdapter,Pt.HttpStatusCode=Wi,Pt.default=Pt;const{Axios:kT,AxiosError:TT,CanceledError:ET,isCancel:IT,CancelToken:NT,VERSION:AT,all:_T,Cancel:jT,isAxiosError:PT,spread:RT,toFormData:OT,AxiosHeaders:MT,HttpStatusCode:DT,formToJSON:LT,getAdapter:FT,mergeConfig:$T}=Pt,Rc=typeof window<"u"?window.__API_BASE_URL__:void 0,Oc=Rc?Zn(Rc):void 0;function Zn(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let is=null;const Vi=new Set;let Ki=null;function Mc(){return is}function qi(e){is=e,Vi.forEach(t=>t(e))}function Dc(e){return Vi.add(e),()=>Vi.delete(e)}function Sy(e){Ki=e}const Cy=3e4,ky=9e4,vn=Pt.create({...Oc?{baseURL:Oc}:{},timeout:Cy,withCredentials:!0});vn.interceptors.request.use(e=>(is&&(e.headers.Authorization=`Bearer ${is}`),e)),vn.interceptors.response.use(e=>{if(Ki&&(e!=null&&e.data))try{Ki(e.data)}catch(t){console.warn("[chat-api] Error in token sync handler:",t)}return e},e=>Promise.reject(e));async function wn(e,t){return vn.defaults.baseURL?(await vn.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function Gi(e,t,n){return vn.defaults.baseURL?(await vn.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Lc(e,t,n){return vn.defaults.baseURL?(await vn.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Fc(e,t){return vn.defaults.baseURL?(await vn.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function bn(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class $c{get baseUrl(){const t=vn.defaults.baseURL;return t?Zn(String(t)):""}updateConfig(t){t.baseUrl&&(vn.defaults.baseURL=Zn(String(t.baseUrl))),t.authToken!==void 0&&qi(t.authToken)}getAuthToken(){return Mc()}setAuthToken(t){qi(t)}onTokenChange(t){return Dc(t)}async listThreads(){const t=await wn("/threads"),n=bn(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await Gi("/threads",t?{title:t}:void 0);return bn(r)}async updateThread(t,n){const r=await Lc(`/threads/${t}`,{title:n});return bn(r)}async deleteThread(t){const n=await Fc(`/threads/${t}`);return bn(n)}async threadInfo(t){const n=await wn(`/threads/${t}/info`);return bn(n)}async listAgents(){const t=await wn("/agents"),n=bn(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await wn(`/agents/${t}`);return bn(n)}async getAgentSchema(t){const n=await wn(`/agents/${t}/schema`);return bn(n)}async getState(t){const n=await wn(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return bn(n)}async getStateHistory(t){const n=await wn(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:ky});return bn(n)}async cancelRun(t){const n=await Gi("/runs/cancel",{threadId:t});return bn(n)}async listCheckpointSummaries(t){const n=await wn(`/threads/${t}/state/checkpoints`,{params:{thread_id:t}}),r=bn(n);return(r==null?void 0:r.items)??[]}}const sr=new $c,zc=b.createContext(null);function Ty({children:e,apiConfig:t}){const n=sr;if(t){const o=n.baseUrl,s=n.getAuthToken();t.baseUrl&&t.baseUrl!==o&&n.updateConfig({baseUrl:t.baseUrl}),t.apiKey!==void 0&&t.apiKey!==s&&n.updateConfig({authToken:t.apiKey})}const r={token:n.getAuthToken(),setToken:o=>n.setAuthToken(o),api:n,baseUrl:n.baseUrl};return u.jsx(zc.Provider,{value:r,children:e})}function Yi(){const e=b.useContext(zc);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function Ey(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const o=r.result,s=new Uint8Array(o);let i="";const a=s.byteLength;for(let l=0;l<a;l++)i+=String.fromCharCode(s[l]);t(btoa(i))}catch(o){n(o)}},r.onerror=o=>n(o),r.readAsArrayBuffer(e)})}async function Iy(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const c=await Ey(l);a.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const Ny={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function Xi(e){if(!e||typeof e!="object")return!1;const t=e;return"values"in t&&"config"in t&&typeof t.values=="object"&&t.values!==null&&typeof t.config=="object"&&t.config!==null}function Wr(e,t){return`${e??""}::${t??""}`}function as(e){const t=Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[],n=(e==null?void 0:e.threadId)??"",r=t[0];if(!Xi(r))return{threadId:n,latest:null,checkpoints:[],interrupt:null,snapshots:{}};const{orderedSnapshots:o,snapshotMap:s}=_y(t),i=Bc(r,0);return{threadId:n,latest:i,checkpoints:o,interrupt:(i==null?void 0:i.interrupt)??null,snapshots:s}}function Bc(e,t){if(!Xi(e))return null;const n=e.values??{messages:[]},r=Array.isArray(n==null?void 0:n.messages)?n.messages:[],{messages:o,...s}=n,i=Object.keys(s).length?s:null,a=e.tasks,l=Array.isArray(a)?a.filter(_=>!!_&&typeof _=="object").map(_=>({..._})):a===null?null:void 0,c=r.map((_,P)=>Ly(_,P)).filter(_=>!!_),d=cn(e.config),f=cn(d==null?void 0:d.configurable),h=Lt(f,["checkpoint_id","checkpointId"]),p=Lt(f,["checkpoint_ns","checkpointNs"]),m=cn(e==null?void 0:e.parentConfig),g=cn(m==null?void 0:m.configurable),y=Lt(g,["checkpoint_id","checkpointId"])??null,x=Lt(g,["checkpoint_ns","checkpointNs"])??null,w=e==null?void 0:e.createdAt,C=typeof w=="string"&&w.trim()?w:new Date(Date.now()-t).toISOString(),T=c[c.length-1]??null,k=cn(e==null?void 0:e.metadata),S=Lt(k,["branch_label","branchLabel"]),E=Lt(g,["checkpoint_id","checkpointId"]),j=Array.isArray(e.next)?[...e.next]:(e==null?void 0:e.next)===null?null:void 0;return{messages:c,checkpointId:h??null,checkpointNs:p??null,nextCursor:y,nextCursorNs:x,interrupt:Ay(a,c,t),createdAt:C,parentId:E??null,branchLabel:S??null,lastMessageId:(T==null?void 0:T.id)??null,hasMessages:c.length>0,messagesLen:c.length,metadata:k??null,config:d??null,parentConfig:m??null,next:j??null,tasks:l??null,values:i??null}}function Ay(e,t,n){const r=My(e,n);return r||Oy(t,n)}function _y(e){const t=new Map;e.forEach((o,s)=>{if(!Xi(o))return;const i=Bc(o,s);if(!(i!=null&&i.checkpointId))return;const a=Wr(i.checkpointId,i.checkpointNs??null),l=t.get(a);if(!l){t.set(a,i);return}t.set(a,jy(l,i))});const n=Array.from(t.values());n.sort((o,s)=>Uc(s.createdAt??"")-Uc(o.createdAt??""));const r={};for(const[o,s]of t.entries())r[o]=s;return{orderedSnapshots:n,snapshotMap:r}}function jy(e,t){return{...e,metadata:ls(e.metadata,t.metadata)??null,config:ls(e.config,t.config)??null,parentConfig:ls(e.parentConfig,t.parentConfig)??null,next:Py(e.next,t.next)??null,tasks:Ry(e.tasks,t.tasks)??null,values:ls(e.values,t.values)??null}}function ls(e,t){return t&&typeof t=="object"?{...e&&typeof e=="object"?e:{},...t}:t===null?e&&typeof e=="object"?{...e}:e??null:e&&typeof e=="object"?{...e}:e??void 0}function Py(e,t){return Array.isArray(t)?t.slice():t===null?Array.isArray(e)?e.slice():e??null:Array.isArray(e)?e.slice():e??void 0}function Ry(e,t){return Array.isArray(t)?t.map(n=>({...n})):t===null?Array.isArray(e)?e.map(n=>({...n})):e??null:Array.isArray(e)?e.map(n=>({...n})):e??void 0}function Oy(e,t){var n;for(let r=e.length-1;r>=0;r--){const o=((n=e[r])==null?void 0:n.content)??[];for(let s=o.length-1;s>=0;s--){const i=o[s];if((i==null?void 0:i.type)==="interrupt"){const a=i;return{id:typeof a.id=="string"&&a.id.trim()?a.id:`interrupt-${t}-${r}-${s}`,value:a.value}}}}return null}function My(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=Dy(e[n],`task-${t}-${n}`);if(!r)continue;const o=r.id||`task-${t}-${n}`;if(Array.isArray(r.interrupts)&&r.interrupts.length)for(let s=r.interrupts.length-1;s>=0;s--){const i=yo(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=yo(r.state,`${o}-state`);if(s)return s}}return null}function Dy(e,t){if(!e)return null;if(Array.isArray(e)){const[a,l,c,,d,,f,...h]=e,p=typeof a=="string"&&a.trim()?a:t,m=typeof l=="string"&&l.trim()?l:Array.isArray(c)&&typeof c[0]=="string"?String(c[0]):"task",g=Array.isArray(d)?d:void 0,y=h.length?h[h.length-1]:void 0;return{id:p,name:m,interrupts:g,state:y!==void 0?y:f}}const n=cn(e);if(!n)return null;const r=Lt(n,["id","task_id","taskId"])??t,o=Lt(n,["name"])??"task",s=Array.isArray(n.interrupts)?n.interrupts:void 0,i=Object.prototype.hasOwnProperty.call(n,"state")?n.state:void 0;return{id:r,name:o,interrupts:s,state:i}}function yo(e,t,n=0,r=new Set){if(n>6||e==null)return null;if(typeof e=="object"){if(r.has(e))return null;r.add(e)}const o=Hc(e,t);if(o)return o;if(Array.isArray(e)){for(let s=e.length-1;s>=0;s--){const i=yo(e[s],t,n+1,r);if(i)return i}return null}if(typeof e=="object"){const s=e,i=["interrupt","pending_interrupt","pendingInterrupt","value","data","payload","result","response"];for(const a of i)if(a in s){const l=yo(s[a],t,n+1,r);if(l)return l}for(const[a,l]of Object.entries(s)){if(i.includes(a)||a==="messages"||a==="results")continue;const c=yo(l,t,n+1,r);if(c)return c}}return null}function Hc(e,t){if(!e)return null;if(typeof e=="object"&&!Array.isArray(e)){const n=e,r=Lt(n,["type","event","kind"]),o=Lt(n,["id","interrupt_id","interruptId","value_id"])??(r&&r.toLowerCase().includes("interrupt")?t:void 0);if(!(Object.prototype.hasOwnProperty.call(n,"value")||Object.prototype.hasOwnProperty.call(n,"data")||Object.prototype.hasOwnProperty.call(n,"payload"))&&!(r&&r.toLowerCase().includes("interrupt")))return null;const i=Object.prototype.hasOwnProperty.call(n,"value")?n.value:Object.prototype.hasOwnProperty.call(n,"data")?n.data:Object.prototype.hasOwnProperty.call(n,"payload")?n.payload:n,a=o&&o.trim()?o:t;return a?{id:a,value:i}:null}if(Array.isArray(e)){for(let n=e.length-1;n>=0;n--){const r=Hc(e[n],t);if(r)return r}return e.length>=2&&typeof e[0]=="string"&&e[0].trim()?{id:e[0],value:e[1]}:null}if(typeof e=="string"){const n=e.trim();return n?{id:t||n,value:n}:null}return null}function Uc(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Ly(e,t){if(!e||typeof e!="object")return null;const n=e,r=cn(e)??{},o=cn(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=Ny[s];if(!i)return null;const a=o.id??o.message_id??o.run_id??null,l=typeof a=="string"&&a.trim()?a:`history-${i}-${t}`,c=cn(o.additional_kwargs)??cn(o.additionalKwargs),d=cn(o.response_metadata)??cn(o.responseMetadata),f=Lt(c,["createdAt","created_at"])??Lt(o,["created_at","createdAt"]),h=Lt(c,["checkpointId","checkpoint_id"]),p=Lt(c,["checkpointNs","checkpoint_ns"]),m=Fy(o.content),g={id:l,role:i,content:m};f&&(g.createdAt=f),typeof o.name=="string"&&o.name.trim()&&(g.name=o.name),typeof(d==null?void 0:d.model_name)=="string"&&(g.model=String(d.model_name)),!g.model&&typeof o.model=="string"&&(g.model=o.model),h&&(g.checkpointId=h),p&&(g.checkpointNs=p);const y=Hy(c,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),x=d?{...d}:void 0;y&&Object.keys(y).length&&(g.additionalKwargs=y),x&&Object.keys(x).length&&(g.responseMetadata=x);const w=$y((c==null?void 0:c.tool_calls)??o.tool_calls);if(w.length&&(g.content=[...g.content,...w]),i==="tool"){const C=zy(o,g.content);C&&(g.content=C)}return g}function Fy(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>Wc(t)).filter(t=>!!t);if(typeof e=="string")return e.trim()?[{type:"text",text:e.trim()}]:[];if(typeof e=="object"){const t=Wc(e);return t?[t]:[]}return[]}function Wc(e){if(!e||typeof e!="object")return typeof e=="string"&&e.trim()?{type:"text",text:e}:null;const t=e,n=String(t.type??"").toLowerCase();if(!n||n==="text"){const o=typeof t.text=="string"?t.text:typeof t.value=="string"?t.value:"";return o.trim()?{type:"text",text:o}:null}if(n==="image"||n==="image_url"){const o=Lt(t,["url","src"]);if(!o)return null;const s={type:"image_url",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.alt=="string"&&(s.alt=t.alt),s}if(n==="file"){const o=Lt(t,["url"]);if(!o)return null;const s={type:"file",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.name=="string"&&(s.name=t.name),typeof t.size=="number"&&(s.size=t.size),typeof t.sourceType=="string"&&(s.sourceType=t.sourceType),s}if(n==="tool_call")return Vc(t)??null;if(n==="tool_end"){const o="output"in t?t.output:t.content;return o?{type:"text",text:typeof o=="string"?o:JSON.stringify(o)}:null}if(n==="interrupt")return{type:"interrupt",value:t.value,...t};if(n==="tool"){const o=Lt(t,["text","content"]);if(o)return{type:"text",text:o}}const r=typeof t.content=="string"?t.content:typeof t.value=="string"?t.value:JSON.stringify(t);return r?{type:"text",text:r}:null}function Vc(e,t){var s;const n=Lt(e,["id","call_id"])??t,r=Lt(e,["name"])??Lt(cn(e.function),["name"]);if(!n||!r)return null;const o=By(e.args??e.arguments??((s=cn(e.function))==null?void 0:s.arguments));return{type:"tool_call",id:n,name:r,args:o}}function $y(e){return Array.isArray(e)?e.map((t,n)=>Vc(t,`tool_call_${n}`)).filter(t=>!!t):[]}function zy(e,t){const n=e.content??e.output;if(!n)return t;const o={type:"text",text:typeof n=="string"?n:JSON.stringify(n)};return[...t,o]}function By(e){if(!e)return{};if(typeof e=="string")try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{raw:e}}catch{return{raw:e}}return typeof e=="object"&&!Array.isArray(e)?{...e}:{}}function cn(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function Lt(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r}}function Hy(e,t){if(!e)return;const n={};let r=!1;for(const[o,s]of Object.entries(e)){if(t.includes(o)){r=!0;continue}s!==void 0&&(n[o]=s)}return r?Object.keys(n).length?n:void 0:e}function Uy(e){return e.type!=="thread_info"&&e.type!=="token"}const Wy={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,messagesStreamMeta:{},pendingInterrupt:null};function Vy(e,t){var n;switch(t.type){case"reset":return{messages:Ji(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,pendingInterrupt:null};case"seed":{const r=Ji(t.payload.messages),o={...e,messages:r,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(o.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(o.lastCheckpointNs=t.payload.checkpointNs??null),o}case"prepend":{const r=Ji(t.payload.messages);if(!r.length)return e;const o=new Set(e.messages.map(i=>i.id)),s=r.filter(i=>!o.has(i.id));return s.length?{...e,messages:[...s,...e.messages]}:e}case"user_message":{const r=t.payload.message;return e.messages.some(o=>o.id===r.id)?e:{...e,messages:[...e.messages,r]}}case"event":return qc(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>qc(o,s),e):e}case"interrupt_response":return{...e,messages:Gc(e.messages),pendingInterrupt:null};default:return e}}function Kc(e=[]){const[t,n]=b.useReducer(Vy,{...Wy,messages:e}),r=b.useRef([]),o=b.useRef(null),s=b.useRef(null),i=b.useCallback(()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),o.current=null,s.current=null;const d=r.current;d.length&&(r.current=[],n({type:"batch",payload:{events:d}}))},[]),a=b.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o.current===null&&(o.current=window.requestAnimationFrame(()=>i())):s.current===null&&(s.current=setTimeout(i,8))},[i]),l=b.useCallback(d=>{r.current.push(d),a()},[a]);b.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const c=b.useMemo(()=>({reset:d=>n({type:"reset",payload:{messages:d}}),seed:(d,f)=>n({type:"seed",payload:{messages:d,...f??{}}}),prepend:d=>n({type:"prepend",payload:{messages:d}}),pushUser:d=>n({type:"user_message",payload:{message:d}}),onEvent:l}),[l]);return{state:t,dispatch:n,...c}}function qc(e,t){var n,r,o,s,i;if(t.type==="message_start"&&t.role==="assistant"){const a=t.id,l=Yy(t.model);if(e.messages.some(f=>f.id===a)){const f=e.messagesStreamMeta??{},h={...f,[a]:f[a]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:a,messagesStreamMeta:h}}const d={id:a,role:"assistant",name:l||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:a,messages:[...e.messages,d]}}if(t.type==="message_delta"){const a=e.assemblingId??Yc(e.messages);if(!a)return e;const l=e.messages,c=l.findIndex(T=>T.id===a&&T.role==="assistant");if(c===-1)return e;const d=l[c],f=e.messagesStreamMeta??{},h=f[a]??{lastSeq:null,lastText:Zc(d.content)},p=t.seq??null;if(p!==null&&typeof p=="number"&&typeof h.lastSeq=="number"&&p<=h.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:p,lastSeq:h.lastSeq}),e;const{newParts:m,newMeta:g,changed:y}=Ky(d.content,t.delta,h,p);if(!y)return e;const x={...d,content:m},w=cs(l,c,x),C={...f,[a]:g};return{...e,messages:w,messagesStreamMeta:C}}if(t.type==="message_end"){const a=e.assemblingId??Yc(e.messages);if(!a)return{...e,assemblingId:null};const l=e.messages,c=l.findIndex(d=>d.id===a&&d.role==="assistant");if(c>=0){const d=l[c];if(!((n=d.content)==null?void 0:n.some(h=>{var p;return(h==null?void 0:h.type)==="text"&&((p=h.text)==null?void 0:p.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:d.id,contentTypes:(r=d.content)==null?void 0:r.map(p=>p==null?void 0:p.type),contentPreview:(o=d.content)==null?void 0:o.map(p=>(p==null?void 0:p.type)==="text"?String(p.text).slice(0,100):p==null?void 0:p.type)});const h=[...l.slice(0,c),...l.slice(c+1)];return{...e,assemblingId:null,messages:h}}}return e}if(t.type==="tool_start"){const a=Xc(t),l=a[0]??(typeof t.id=="string"?t.id:null)??(typeof t.call_id=="string"?t.call_id:null),c=t.name??t.tool??"tool";!l&&a.length===0&&a.push(`${c}-${Date.now()}`);const d=a.length?a:l?[l]:[],f=Jc(e,d,c),h=f>=0?e.messages[f]:null,p=l??d[0]??`${c}-${Date.now()}`,m=(h==null?void 0:h.id)??`tool-${p}`,g=d[0]??p,y={type:"tool_call",id:g,name:c,args:t.args};if(h){const C=Qi(h,d,c,t.args),T={...h,name:h.name??c,additionalKwargs:C},k=f,S=k>=0?cs(e.messages,k,T):e.messages,E=us(T,d),j=ea(e.toolIndex,m,E);return{...e,messages:S,toolIndex:j}}const x={id:m,role:"tool",name:c,createdAt:new Date().toISOString(),content:[y],additionalKwargs:Qi(void 0,d.length?d:[g],c,t.args)},w=us(x,d.length?d:[g]);return{...e,messages:[...e.messages,x],toolIndex:ea(e.toolIndex,m,w)}}if(t.type==="tool_end"){const a=Xc(t);if(!a.length&&!(typeof t.id=="string"&&t.id))return e;const l=t.name??null,c=Jc(e,a,l),d=c>=0?e.messages[c]:null,f=l??(d==null?void 0:d.name)??((s=d==null?void 0:d.additionalKwargs)==null?void 0:s.toolName)??"tool",h=a[0]??((i=d==null?void 0:d.id)==null?void 0:i.replace(/^tool-/,""))??`${f}-${Date.now()}`,p=(d==null?void 0:d.id)??`tool-${h}`,m=us(d,a);let g=t.output;if(typeof t.output=="string")try{const S=t.output.trim();(S.startsWith("{")||S.startsWith("["))&&(g=JSON.parse(S))}catch{g=t.output}const y={type:"text",text:typeof g=="string"?g:JSON.stringify(g)},x=(d==null?void 0:d.createdAt)??new Date().toISOString(),w=Qi(d??void 0,m.length?m:a,f),C={id:p,role:"tool",name:f??(d==null?void 0:d.name)??"tool",content:[y],createdAt:x,additionalKwargs:w},T=c>=0?cs(e.messages,c,C):[...e.messages,C],k=us(C,a.length?a:m);return{...e,messages:T,toolIndex:ea(e.toolIndex,p,k)}}if(t.type==="checkpoint"){const a=t.checkpointNs??e.lastCheckpointNs??null,l=Gy(e.messages,t.checkpointId,a);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:a,messages:l}}if(t.type==="branch"){const a=t.checkpointId??e.lastCheckpointId,l=t.checkpointNs??e.lastCheckpointNs;return{...e,lastBranch:t,lastCheckpointId:a??null,lastCheckpointNs:l??null}}if(t.type==="error"){const a={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,a]}}if(t.type==="state_history"){const a=as(t),l=a.interrupt,c=a.latest,d=l===null?Gc(e.messages):e.messages;return{...e,messages:d,pendingInterrupt:l,lastCheckpointId:(c==null?void 0:c.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(c==null?void 0:c.checkpointNs)??e.lastCheckpointNs}}return e}function Ji(e){return e.filter(t=>{if(t.role!=="assistant")return!0;const n=(t.content||[]).some(o=>{var s;return o&&o.type==="text"&&((s=o.text)==null?void 0:s.trim())}),r=(t.content||[]).some(o=>o&&o.type==="image_url");return!!(n||r)})}function cs(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function Gc(e){let t=!1;const n=e.map(r=>{const o=(r.content??[]).filter(s=>s.type!=="interrupt");return o.length!==r.content.length?(t=!0,{...r,content:o}):r});return t?n:e}function Yc(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function Xc(e){const t=new Set,n=r=>{typeof r=="string"&&r.trim()&&t.add(r.trim())};return n(e.id),n(e==null?void 0:e.call_id),n(e==null?void 0:e.callId),Array.from(t)}function Zi(e){if(!e)return[];const t=new Set,n=o=>{typeof o=="string"&&o.trim()&&t.add(o.trim())},r=e.additionalKwargs;if(r){n(r.toolCallId);const o=r.toolCallIds;if(Array.isArray(o))for(const s of o)n(s)}for(const o of e.content??[])(o==null?void 0:o.type)==="tool_call"&&n(o.id);return Array.from(t)}function Qi(e,t,n,r){const o=new Set,s=l=>{typeof l=="string"&&l.trim()&&o.add(l.trim())};if(e){const l=Zi(e);for(const c of l)s(c)}for(const l of t)s(l);const i=Array.from(o),a={...(e==null?void 0:e.additionalKwargs)??{}};if(i.length){a.toolCallIds=i;const l=typeof a.toolCallId=="string"?a.toolCallId.trim():null;a.toolCallId=l&&o.has(l)?l:i[0]}return n&&(a.toolName=n),r!==void 0&&(a.toolArgs=r),a}function us(e,t){const n=new Set;for(const o of t)typeof o=="string"&&o.trim()&&n.add(o.trim());const r=Zi(e);for(const o of r)n.add(o);return Array.from(n)}function ea(e,t,n){if(!n.length)return e;let r=!1;const o={...e};for(const s of n)s&&o[s]!==t&&(o[s]=t,r=!0);return r?o:e}function Jc(e,t,n){var o,s;const r=new Set(t.filter(i=>typeof i=="string"&&i.trim()));for(const i of r){const a=e.toolIndex[i];if(a){const l=e.messages.findIndex(c=>c.id===a);if(l!==-1)return l}}for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool")continue;if(Zi(a).some(c=>r.has(c)))return i}if(typeof n=="string"&&n.trim())for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool"||a.name&&a.name!==n)continue;if(!((o=a.content)==null?void 0:o.some(c=>c.type!=="tool_call")))return i}for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool")continue;if(!((s=a.content)==null?void 0:s.some(c=>c.type!=="tool_call")))return i}return-1}function Zc(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function Ky(e,t,n,r){const o={...n};if(r!==null&&typeof r=="number"){if(typeof o.lastSeq=="number"&&r<=o.lastSeq)return{newParts:e,newMeta:o,changed:!1};o.lastSeq=r}const s=t.filter(f=>f.type==="text").map(f=>f.text??"").join(""),i=t.filter(f=>f.type!=="text"),a=o.lastText??Zc(e);let l="",c=e.slice();if(s){const f=qy(a,s);if(f===""?l="":f===s?l=s:l=f,l){const h=c[c.length-1];if((h==null?void 0:h.type)==="text"){const p=h.text??"",m={...h,text:p+l};c=[...c.slice(0,c.length-1),m]}else c=[...c,{type:"text",text:l}];o.lastText=a+l}else o.lastText=a}i.length&&(c=[...c,...i]);const d=!!(l||i.length);return{newParts:c,newMeta:o,changed:d}}function Qc(e){return e.replace(/\s+/g," ").trim()}function qy(e,t){if(!t)return"";if(!e)return t;if(e===t)return"";const n=Math.min(e.length,t.length);for(let i=n;i>0;i--)if(e.slice(-i)===t.slice(0,i))return t.slice(i);const r=Qc(e),o=Qc(t);if(r===o)return"";const s=Math.min(r.length,o.length);for(let i=s;i>0;i--)if(r.slice(-i)===o.slice(0,i))return t;return t}function Gy(e,t,n){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const s={...e[r],checkpointId:t,checkpointNs:n??void 0};return cs(e,r,s)}return e}function Yy(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}function eu(e={}){const t=b.useMemo(()=>Zn(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=b.useState(e.token??null),s=b.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=b.useState(!1),[c,d]=b.useState(null),[f,h]=b.useState(""),[p,m]=b.useState(null),[g,y]=b.useState(0),[x,w]=b.useState(!1),C=b.useRef(null),T=b.useRef(!0),k=b.useRef(0),S=b.useRef(null),E=b.useRef(null),j=b.useRef(null),_=b.useRef(null),P=b.useCallback(O=>{o(O)},[]),D=b.useCallback(()=>{h(""),m(null),d(null),E.current=null,j.current=null,_.current=null},[]),z=b.useCallback(()=>{var O;console.debug("[use-chat] stop() invoked - aborting stream"),(O=C.current)==null||O.abort(),C.current=null,S.current=null,l(!1),w(!1),k.current=0,y(0)},[]),B=b.useCallback((O,H,R)=>{C.current&&(C.current.abort(),C.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&h(""),m(null),E.current=null,j.current=null,_.current=null;const V=new AbortController;C.current=V;let $=null,F=null,ne=!1;return S.current={threadId:O.threadId??null,headers:{}},(async()=>{var ye,je,J,ue,ke,te,L,q,ie,ce,U,We,re,xe,Pe,$e,rt,Se;const Q=Ye=>{var ot;try{const et=JSON.parse(JSON.stringify(Ye));return(ot=et==null?void 0:et.payload)!=null&&ot.files_info&&Array.isArray(et.payload.files_info)&&(et.payload.files_info=et.payload.files_info.map(Xe=>({...Xe,data:Xe!=null&&Xe.data?`<base64 ${String(Xe.data).length} chars>`:Xe==null?void 0:Xe.data}))),et}catch{return Ye}};try{let Ye={};try{if(r)Ye={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const Ve=window.__AUTH_TOKEN__,Mt=((ye=window.localStorage)==null?void 0:ye.getItem("authToken"))||null;let _t=null;try{const Te=(je=window.localStorage)==null?void 0:je.getItem("chat-settings");Te&&(_t=((J=JSON.parse(Te))==null?void 0:J.apiKey)||null)}catch{}const G=Ve||Mt||_t||null;G&&(Ye={Authorization:`Bearer ${G}`})}}catch{}console.debug("[use-chat] POST",t+n,Q(O));let ot={};if(typeof window<"u")try{const ft=(ue=window.localStorage)==null?void 0:ue.getItem("authSessionId");ft&&(ot={"X-Session-Id":ft})}catch{}const et={...Ye,...ot,...s.current},Xe={"Content-Type":"application/json",Accept:"text/event-stream",...et},Ke=await fetch(t+n,{method:"POST",headers:Xe,body:JSON.stringify(O),signal:V.signal,credentials:i});if(S.current&&(S.current.headers=et),!Ke.ok||!Ke.body){const ft=await Ke.text().catch(()=>"");console.debug("[use-chat] non-OK response",Ke.status,ft==null?void 0:ft.slice(0,500));const Ve=`stream ${Ke.status}${ft?": "+ft:""}`;throw(ke=R==null?void 0:R.onConnectionError)==null||ke.call(R,Ve),ne=!0,$="error",F=Ve,new Error(Ve)}w(!0);const tt=Ke.body.getReader(),Ot=new TextDecoder;let St="",nt=[];k.current=0,y(0);let yt=0,Nt=null;const st=()=>{if(nt.length){const ft=nt.join("");nt=[],T.current&&h(Ve=>Ve+ft)}Nt=null},Gt=()=>{typeof window<"u"&&Nt==null&&(Nt=requestAnimationFrame(st))};let Yt=Date.now();const Xt=setInterval(()=>{var ft;if(Date.now()-Yt>18e5){const Ve="Stream idle timeout";d(Ve),$="error",F=Ve,V.abort(),(ft=R==null?void 0:R.onError)==null||ft.call(R,Ve)}},5e3),Jt=1024*1024;try{const ft=Ke.headers.get("X-Thread-Id")||Ke.headers.get("x-thread-id"),Ve=Ke.headers.get("X-Thread-Created")||Ke.headers.get("x-thread-created"),Mt=ft??null,_t=String(Ve??"").toLowerCase()==="true";for(S.current&&!S.current.threadId&&(S.current={...S.current,threadId:Mt}),(te=R==null?void 0:R.onOpen)==null||te.call(R,{threadId:Mt,created:_t});;){const{value:G,done:Te}=await tt.read();if(Te)break;St+=Ot.decode(G,{stream:!0}),St.length>Jt&&(St="",console.warn("Stream buffer reset: exceeded 1MB"));let ve;for(;(ve=St.indexOf(`
|
|
36
36
|
|
|
37
37
|
`))>=0;){const pt=St.slice(0,ve);St=St.slice(ve+2);const mt=Jy(pt);if(!mt)continue;let ct;try{ct=JSON.parse(mt)}catch{console.debug("[use-chat] malformed SSE:",mt.slice(0,200));continue}const Me=Xy(ct)?ct.data:ct;Yt=Date.now();const Ut=Me.seq;if(Ut!==void 0){if(Ut<=yt){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:Ut,lastProcessedSeq:yt,type:Me.type});continue}yt>0&&Ut>yt+1&&((L=R==null?void 0:R.onGap)==null||L.call(R,{from:yt,to:Ut})),yt=Ut,k.current=Ut,y(Ut)}if(console.debug("[use-chat] received event",{seq:Me.seq,type:Me.type,preview:(()=>{var Le;try{return Me.type==="message_delta"?{deltaTypes:(Le=Me.delta)==null?void 0:Le.map(xt=>xt.type),textLen:(Me.delta||[]).filter(xt=>xt.type==="text").map(xt=>String(xt.text||"").length)}:Me.content||Me.delta?{hasContent:!0}:{}}catch(xt){return{err:String(xt)}}})()}),Me.type==="checkpoint")E.current=Me.checkpointId??null,j.current=Me.checkpointNs??null,m(Me.checkpointId??null);else if(Me.type==="state_history"){_.current=Me;try{const xt=as(Me).latest;xt&&(E.current=xt.checkpointId??null,j.current=xt.checkpointNs??null,m(xt.checkpointId??null))}catch(Le){console.warn("[use-chat] Failed to hydrate state_history payload",Le)}}try{H==null||H(Me)}catch(Le){console.error("[use-chat] Error in onEvent callback:",Le,"for event:",Me.type)}if(Me.type==="token"&&e.autoAppendAssistant!==!1)nt.push(Me.content),Gt();else if(Me.type==="message_delta"){const Le=Me.delta.filter(xt=>xt.type==="text").map(xt=>xt.text).join("");Le&&e.autoAppendAssistant!==!1&&(nt.push(Le),Gt())}else if(Me.type==="heartbeat"){console.debug("[use-chat] heartbeat received");try{(q=R==null?void 0:R.onHeartbeat)==null||q.call(R,Me)}catch(Le){console.warn("[use-chat] heartbeat callback failed",Le)}}else if(Nt!==null&&cancelAnimationFrame(Nt),st(),Me.type==="checkpoint")m(Me.checkpointId);else if(Me.type==="error"){const Le=Me;if(d(Le.message),$="error",F=Le.message,Le.error_type==="auth_error"||Le.code==="TOKEN_EXPIRED"||((ie=Le.message)==null?void 0:ie.includes("token"))||((ce=Le.message)==null?void 0:ce.includes("401"))||((U=Le.message)==null?void 0:U.includes("unauthorized"))||((We=Le.message)==null?void 0:We.includes("Unauthorized"))){console.error("[use-chat] Auth error detected:",Le.message);try{(re=R==null?void 0:R.onAuthError)==null||re.call(R,Le.message)}catch(Ln){console.warn("[use-chat] onAuthError handler failed",Ln)}V.abort()}}}}st(),$===null&&!V.signal.aborted&&($="complete")}catch(ft){if(ft.name==="AbortError")$=$??"aborted";else{const Ve=ft.message||String(ft);$="error",F=Ve,d(Ve),(xe=R==null?void 0:R.onError)==null||xe.call(R,Ve)}}finally{try{await tt.cancel()}catch{}finally{(Pe=tt.releaseLock)==null||Pe.call(tt)}Nt!==null&&typeof window<"u"&&window.cancelAnimationFrame(Nt),clearInterval(Xt)}}catch(Ye){if(Ye.name==="AbortError")$=$??"aborted";else{const ot=Ye.message||String(Ye);$="error",F=ot,d(ot),($e=R==null?void 0:R.onError)==null||$e.call(R,ot),ne||((rt=R==null?void 0:R.onConnectionError)==null||rt.call(R,ot),ne=!0)}}finally{const Ye=k.current,ot=E.current,et=j.current,Xe=_.current,Ke=$??(V.signal.aborted?"aborted":F?"error":"complete");try{(Se=R==null?void 0:R.onClosed)==null||Se.call(R,{reason:Ke,lastSeq:Ye,lastCheckpointId:ot,lastCheckpointNs:et,lastStateHistory:Xe,error:F})}catch(tt){console.warn("[use-chat] onClosed callback failed",tt)}l(!1),w(!1),C.current=null,k.current=0,y(0),S.current=null}})(),{close:()=>V.abort()}},[t,n,r,e.autoAppendAssistant]);return b.useEffect(()=>()=>{var O;T.current=!1,(O=C.current)==null||O.abort()},[]),{isStreaming:a,error:c,assistantText:f,lastCheckpointId:p,lastSeq:g,connected:x,stream:B,stop:z,clear:D,setToken:P}}function Xy(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function Jy(e){const t=e.split(/\r?\n/),n=[];for(const r of t)if(r&&!r.startsWith(":")&&r.startsWith("data:")){const o=r.slice(5);n.push(o.startsWith(" ")?o.slice(1):o)}return n.length===0?null:n.join(`
|
|
38
|
-
`)}const tu=200;function Zy({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onUnhandledEvent:r,onSequenceGap:o,onStreamClosed:s,onConnectionError:i,onAuthError:a,onHeartbeat:l}){const c=b.useRef(null),d=b.useRef(null),f=b.useRef(new Map),h=b.useRef(null),p=b.useCallback(_=>{try{const P=globalThis.structuredClone;if(typeof P=="function")return P(_)}catch{}try{return JSON.parse(JSON.stringify(_))}catch{return _}},[]),m=b.useCallback((_,P)=>{if(!_)return;const D=f.current.get(_)??[],z=p(P),B=D.length>=tu?[...D.slice(D.length-tu+1),z]:[...D,z];f.current.set(_,B)},[p]),g=b.useCallback(_=>{_&&f.current.set(_,[])},[]),y=b.useCallback(_=>{const P=_??d.current;if(!P)return;const D=f.current.get(P);D!=null&&D.length&&D.forEach(z=>{try{n(z)}catch(B){console.error("[useChatStreamingService] Failed to replay buffered event",B)}})},[n]),x=b.useCallback(_=>{var z,B,O,H,R;const P=_.seq??null;if(P!==null){const V=c.current;if(V!==null){if(P<=V)return;P>V+1&&(o==null||o({from:V,to:P}))}c.current=P}if(_.type==="thread_info"){d.current=_.threadId,h.current&&(h.current.threadIdGuess=_.threadId),g(_.threadId),console.log("[useChatStreamingService] 🎯 Received thread_info event:",_);try{t(_)}catch(V){console.error("[useChatStreamingService] Error in onThreadInfo handler:",V)}return}if(_.type==="heartbeat"){try{l==null||l(_)}catch(V){console.error("[useChatStreamingService] Error in onHeartbeat handler:",V)}return}if(_.type==="error"){const V=_;if(V.error_type==="auth_error"||V.code==="TOKEN_EXPIRED"||((z=V.message)==null?void 0:z.includes("token"))||((B=V.message)==null?void 0:B.includes("401"))||((O=V.message)==null?void 0:O.includes("unauthorized"))||((H=V.message)==null?void 0:H.includes("Unauthorized"))){console.error("[useChatStreamingService] Auth error event detected:",V.message);try{a==null||a(V.message)}catch(F){console.warn("[useChatStreamingService] onAuthError handler failed",F)}}}const D=_.threadId??(_.type==="state_history"?_.threadId:void 0)??d.current??((R=h.current)==null?void 0:R.threadIdGuess)??null;if(_.type==="state_history"&&(d.current=D??d.current),Uy(_)){_.type==="checkpoint"||_.type==="state_history"?g(D??null):m(D??null,_);try{n(_)}catch(V){console.error("[useChatStreamingService] Error in onMessageEvent handler:",V)}return}try{r==null||r(_)}catch(V){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",V)}},[m,g,n,o,t,r]),{stream:w,stop:C,isStreaming:T,error:k,setToken:S}=eu({baseUrl:e,token:void 0}),E=b.useCallback((_,P)=>{c.current=null,d.current=_.threadId??null,h.current={request:_,callbacks:P,manualStop:!1,threadIdGuess:_.threadId??null},w(_,x,{onOpen:P==null?void 0:P.onOpen,onError:D=>{var z;(z=P==null?void 0:P.onError)==null||z.call(P,D)},onGap:(P==null?void 0:P.onGap)??o,onConnectionError:D=>{var z;i==null||i(D),(z=P==null?void 0:P.onConnectionError)==null||z.call(P,D)},onAuthError:D=>{var z;a==null||a(D),(z=P==null?void 0:P.onAuthError)==null||z.call(P,D)},onHeartbeat:D=>{var z;try{l==null||l(D)}catch(B){console.warn("[useChatStreamingService] onHeartbeat handler failed",B)}try{(z=P==null?void 0:P.onHeartbeat)==null||z.call(P,D)}catch(B){console.warn("[useChatStreamingService] downstream onHeartbeat handler failed",B)}},onClosed:D=>{var H,R,V,$;const z=((H=h.current)==null?void 0:H.manualStop)??!1,B=d.current??((R=h.current)==null?void 0:R.threadIdGuess)??((V=D.lastStateHistory)==null?void 0:V.threadId)??null;(D.reason==="complete"||D.reason==="aborted"&&z)&&g(B);const O={...D,threadId:B,manualStop:z};try{s==null||s(O)}catch(F){console.warn("[useChatStreamingService] onStreamClosed handler failed",F)}try{($=P==null?void 0:P.onClosed)==null||$.call(P,O)}catch(F){console.warn("[useChatStreamingService] downstream onClosed handler failed",F)}h.current&&(h.current=null)}})},[g,x,a,i,l,o,s,w]),j=b.useCallback(()=>{h.current&&(h.current.manualStop=!0),C()},[C]);return b.useMemo(()=>({startStream:E,stop:j,isStreaming:T,error:k,setAuthToken:S,replayBufferedEvents:y}),[E,j,T,k,S,y])}const nu=50,Qy=750,ta="chat-history@1",ex=5,tx=1e3,nx=15e3,ds=300;function ru(e,t=ds){if(typeof window<"u"&&"requestIdleCallback"in window)try{window.requestIdleCallback(e,{timeout:t});return}catch{}window.setTimeout(e,t)}function Cr(){return typeof window<"u"&&typeof window.localStorage<"u"}function na(e){if(!Cr())return null;try{return window.localStorage.getItem(e)}catch{return null}}function ra(e,t){if(!Cr())return!1;try{return window.localStorage.setItem(e,t),!0}catch{return!1}}function oa(e){if(Cr())try{window.localStorage.removeItem(e)}catch{}}function sa(e){return e==null?e:{...e}}function rx(e){return e==null?e:{...e}}function ox(e){if(Array.isArray(e))return e.slice();if(e==null)return e}function sx(e){if(Array.isArray(e))return e.map(t=>({...t}));if(e==null)return e}function un(e,t={}){const n=t.cloneMessages??!1,r=Array.isArray(e==null?void 0:e.messages)?e.messages:[],o=sa(e==null?void 0:e.metadata),s=sa(e==null?void 0:e.config),i=sa(e==null?void 0:e.parentConfig),a=ox(e==null?void 0:e.next),l=sx(e==null?void 0:e.tasks),c=rx(e==null?void 0:e.values),d={checkpointId:(e==null?void 0:e.checkpointId)??null,checkpointNs:(e==null?void 0:e.checkpointNs)??null,createdAt:(e==null?void 0:e.createdAt)??null,parentId:(e==null?void 0:e.parentId)??null,branchLabel:(e==null?void 0:e.branchLabel)??null,lastMessageId:(e==null?void 0:e.lastMessageId)??null,messagesLen:typeof(e==null?void 0:e.messagesLen)=="number"?e.messagesLen:r.length,hasMessages:typeof(e==null?void 0:e.hasMessages)=="boolean"?e.hasMessages:r.length>0,messages:n?r.slice():r,nextCursor:(e==null?void 0:e.nextCursor)??null,nextCursorNs:(e==null?void 0:e.nextCursorNs)??null,interrupt:(e==null?void 0:e.interrupt)??null};return o!==void 0&&(d.metadata=o),s!==void 0&&(d.config=s),i!==void 0&&(d.parentConfig=i),a!==void 0&&(d.next=a),l!==void 0&&(d.tasks=l),c!==void 0&&(d.values=c),d}function ix(e){var t;for(let n=e.length-1;n>=0;n--){const r=((t=e[n])==null?void 0:t.content)??[];for(let o=r.length-1;o>=0;o--){const s=r[o];if((s==null?void 0:s.type)==="interrupt"){const i=s.id;return{id:(typeof i=="string"?i:null)??`interrupt-${e[n].id??o}`,value:s.value}}}}return null}function ou(e,t){if(!e&&!t)return!0;if(!e||!t||e.id!==t.id)return!1;try{return JSON.stringify(e.value)===JSON.stringify(t.value)}catch{return e.value===t.value}}function ia(e,t){return`${e}${t}`}function ax(e,t){const n=na(ia(e,t));if(!n)return null;try{const r=JSON.parse(n);return typeof(r==null?void 0:r.threadId)!="string"?null:{threadId:r.threadId,snapshot:un(r.snapshot,{cloneMessages:!0}),updatedAt:typeof r.updatedAt=="number"?r.updatedAt:void 0}}catch{return null}}function lx(e,t,n=100){if(!Cr())return;const r=un(t.snapshot,{cloneMessages:!0}),o={threadId:t.threadId,snapshot:{...r,messages:r.messages.slice(-n)},updatedAt:Date.now()},s=ia(e,t.threadId),i=JSON.stringify(o);if(!ra(s,i))try{const a=[];for(let l=0;l<window.localStorage.length;l++){const c=window.localStorage.key(l);if(!c||c===s||!c.startsWith(e))continue;const d=window.localStorage.getItem(c);if(!d){a.push({key:c,updatedAt:0});continue}try{const f=JSON.parse(d),h=typeof(f==null?void 0:f.updatedAt)=="number"&&Number.isFinite(f.updatedAt)?f.updatedAt:0;a.push({key:c,updatedAt:h})}catch{a.push({key:c,updatedAt:0})}}a.sort((l,c)=>l.updatedAt-c.updatedAt);for(const l of a)if(window.localStorage.removeItem(l.key),ra(s,i))break}catch{}}function cx(e,t){oa(ia(e,t))}function ux(e){if(Cr())try{for(let t=0;t<window.localStorage.length;t++){const n=window.localStorage.key(t);n&&n.startsWith(e)&&window.localStorage.removeItem(n)}}catch{}}function su(e,t,n){return`${e}__${t??""}__${n??""}`}function fs(e,t){return t&&typeof t=="object"?{...e&&typeof e=="object"?{...e}:{},...t}:t===null?e&&typeof e=="object"?{...e}:e??null:e&&typeof e=="object"?{...e}:e??void 0}function dx(e,t){return fs(e,t)}function fx(e,t){return Array.isArray(t)?t.slice():t===null?Array.isArray(e)?e.slice():e??null:Array.isArray(e)?e.slice():e??void 0}function hx(e,t){return Array.isArray(t)?t.map(n=>({...n})):t===null?Array.isArray(e)?e.map(n=>({...n})):e??null:Array.isArray(e)?e.map(n=>({...n})):e??void 0}function iu(e,t){const n=fs(e.metadata,t.metadata),r=fs(e.config,t.config),o=fs(e.parentConfig,t.parentConfig),s=fx(e.next,t.next),i=hx(e.tasks,t.tasks),a=dx(e.values,t.values),l={};return n!==void 0&&(l.metadata=n??null),r!==void 0&&(l.config=r??null),o!==void 0&&(l.parentConfig=o??null),s!==void 0&&(l.next=s??null),i!==void 0&&(l.tasks=i??null),a!==void 0&&(l.values=a??null),l}function au(e){return Array.isArray(e)?e.filter(t=>!!(t&&(t.checkpointId||t.checkpointNs))).map(t=>{const n=un(t,{cloneMessages:!0});return{...n,messages:Array.isArray(n.messages)?n.messages:[],values:n.values??null}}):[]}const px="cachedThreads",mx="v1",aa=200;function gx(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n);return(t>>>0).toString(36)}function la(e,t){return`cachedThreads:v1:${e}:${gx(t||"anon")}`}function yx(){const e=na(px);if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>{if(!n||typeof n!="object")return!1;const r=n;return typeof r.threadId=="string"&&typeof r.title=="string"}):[]}catch{return[]}}function xx(e){const t=na(e);if(!t)return[];try{const n=JSON.parse(t);return Array.isArray(n)?n.filter(r=>{if(!r||typeof r!="object")return!1;const o=r;return typeof o.threadId=="string"&&typeof o.title=="string"}):[]}catch{return[]}}function ca(e,t){ra(e,JSON.stringify(t))}function ua(e){const t=xx(e);if(t.length>0)return t;const n=yx();if(n.length>0)try{ca(e,n.slice(0,aa))}catch{}return n}function hs(e){const t={},n=[];for(const r of e)!r||typeof r.threadId!="string"||t[r.threadId]||(t[r.threadId]=r,n.push(r.threadId));return{byId:t,order:n}}function da(e){return e.order.map(t=>e.byId[t]).filter(Boolean)}function vx({currentThreadId:e,currentThreadIdRef:t}){const[n,r]=b.useState([]),o=b.useRef(new Map),s=b.useRef(new Map),i=b.useCallback(m=>{if(!m){r([]);return}const g=o.current.get(m);if(!g||!g.length){r([]);return}r(g.map(y=>un(y,{cloneMessages:!0})))},[]);b.useEffect(()=>{i(e)},[e,i]);const a=b.useCallback((m,g,y)=>{if(!m)return;const x=y==="replace"?[]:o.current.get(m)??[],w=y==="replace"?g:[...g,...x];if(!w.length){y==="replace"&&o.current.set(m,[]),m===t.current&&r([]);return}const C=new Map;for(const k of w){if(!(k!=null&&k.checkpointId))continue;const S=`${k.checkpointId}::${k.checkpointNs??""}`,E=un(k,{cloneMessages:!0}),j=C.get(S);if(!j){C.set(S,E);continue}const _=iu(j,E);C.set(S,{...j,..._})}const T=Array.from(C.values()).sort((k,S)=>{const E=Number.isFinite(Date.parse(k.createdAt??""))?Date.parse(k.createdAt??""):0;return(Number.isFinite(Date.parse(S.createdAt??""))?Date.parse(S.createdAt??""):0)-E});o.current.set(m,T),m===t.current&&i(m)},[t,i]),l=b.useCallback((m,g,y)=>{if(!m)return;const x=s.current.get(m),w=y==="replace"||!x?new Map:new Map(x);if(g&&typeof g=="object")for(const[C,T]of Object.entries(g)){if(!(T!=null&&T.checkpointId))continue;const k=C||Wr(T.checkpointId,T.checkpointNs??null);w.set(k,un(T,{cloneMessages:!0}))}s.current.set(m,w)},[]),c=b.useCallback((m,g)=>{if(!m)return!1;const y=au(g);if(!y.length)return!1;const x=o.current.get(m)??[],w=new Map,C=(k,{preferExisting:S})=>{for(const E of k){if(!(E!=null&&E.checkpointId)&&!(E!=null&&E.checkpointNs))continue;const j=Wr(E.checkpointId??null,E.checkpointNs??null);j&&(S&&w.has(j)?w.set(j,E):w.has(j)&&S||w.set(j,E))}};C(y,{preferExisting:!1}),C(x,{preferExisting:!0});const T=Array.from(w.values()).sort((k,S)=>{const E=Number.isFinite(Date.parse(k.createdAt??""))?Date.parse(k.createdAt??""):0;return(Number.isFinite(Date.parse(S.createdAt??""))?Date.parse(S.createdAt??""):0)-E});return o.current.set(m,T),m===t.current&&r(T.map(k=>un(k,{cloneMessages:!0}))),!0},[t]),d=b.useCallback(m=>{m&&(o.current.delete(m),s.current.delete(m),m===t.current&&r([]))},[t]),f=b.useCallback(()=>{r([])},[]),h=b.useCallback(m=>m?s.current.get(m)??null:null,[]),p=b.useCallback((m,g)=>{var y;if(m)return(y=s.current.get(m))==null?void 0:y.get(g)},[]);return{threadCheckpoints:n,syncActiveThreadCheckpoints:i,updateCheckpointCache:a,updateCheckpointSnapshots:l,applyCheckpointSummaries:c,clearThreadCaches:d,resetThreadCheckpoints:f,getSnapshotCache:h,getSnapshotFromCache:p}}const lu=b.createContext(null),cu=b.createContext(null),uu=b.createContext(null),wx=b.createContext(!1);function bx({children:e,initialThreadId:t=null,autoLoadInitial:n=!0,disableAutoRestore:r=!1,enableFileAgentRouting:o=!1,fileAgentId:s="invoice_reader",onError:i,onAuthError:a,onThreadChange:l}){const{api:c,baseUrl:d}=Yi(),f=b.useMemo(()=>Zn(d),[d]),h=b.useMemo(()=>{try{return new URL(d).host}catch{return"unknown"}},[d]),p=b.useMemo(()=>`threadPayload:${mx}:${h}:`,[h]),m=b.useCallback(I=>ax(p,I),[p]),g=b.useCallback((I,A=100)=>{lx(p,I,A)},[p]),y=b.useCallback(I=>{cx(p,I)},[p]),x=b.useCallback(()=>{ux(p)},[p]),[w,C]=b.useState(()=>{var I;return la(h,(I=c.getAuthToken)==null?void 0:I.call(c))}),[T,k]=b.useState(()=>{var A;const I=ua(la(h,(A=c.getAuthToken)==null?void 0:A.call(c)));return hs(I)}),S=b.useMemo(()=>da(T),[T]),[E,j]=b.useState(t),[_,P]=b.useState(!1),[D,z]=b.useState(!1),[B,O]=b.useState(null),[H,R]=b.useState(null),[V,$]=b.useState(null),F=b.useCallback(()=>{const I=ua(w);b.startTransition(()=>{k(hs(I))})},[w]),[ne,Q]=b.useState(!1),[ye,je]=b.useState(!1),[J,ue]=b.useState(null),[ke,te]=b.useState(void 0),[L,q]=b.useState(void 0),[ie,ce]=b.useState(void 0),{state:U,dispatch:We,seed:re,prepend:xe,pushUser:Pe,onEvent:$e,reset:rt}=Kc(),Se=b.useRef(E);b.useEffect(()=>{Se.current=E},[E]);const Ye=b.useRef(!1),ot=b.useRef([]),et=b.useRef(null),Xe=b.useRef(null),Ke=b.useRef(new Map),tt=b.useRef(E),_t=b.useRef(!1),St=b.useRef(null),nt=b.useRef(new Map),yt=b.useRef(new Map),{threadCheckpoints:Nt,syncActiveThreadCheckpoints:st,updateCheckpointCache:Gt,updateCheckpointSnapshots:Yt,applyCheckpointSummaries:Xt,clearThreadCaches:Jt,resetThreadCheckpoints:ft,getSnapshotCache:Ve,getSnapshotFromCache:Mt}=vx({currentThreadId:E,currentThreadIdRef:Se}),jt=b.useCallback(()=>{var K;const I=yt.current;if(I.size<=nu)return;const A=Array.from(I.entries()).sort((fe,le)=>fe[1].timestamp-le[1].timestamp),W=I.size-nu;for(let fe=0;fe<W;fe++){const le=(K=A[fe])==null?void 0:K[0];le&&I.delete(le)}},[]),G=b.useCallback((I,A)=>{if(!I)return null;const W=Array.isArray(I.checkpoints)?I.checkpoints:[];return W.length===0?null:{version:I.version===ta?I.version:ta,threadId:I.threadId??A,checkpoints:W}},[]),Te=b.useCallback((I,A)=>{const{threadId:W,checkpointId:K=null,checkpointNs:fe=null}=I,le=su(W,K,fe);if(A!=null&&A.force)nt.current.delete(le),yt.current.delete(le);else{if(A!=null&&A.preferCache){const kt=yt.current.get(le);if(kt)return Promise.resolve(kt.result)}const Be=nt.current.get(le);if(Be)return Be}const bt=(async()=>{try{const Be=await c.getStateHistory({threadId:W,checkpointId:K??void 0,checkpointNs:fe??void 0}),kt=G(Be,W);if(kt)return{payload:kt,usedHistoryApi:!0};throw new Error("History response missing checkpoints")}catch(Be){console.warn("[ChatSessionProvider] getStateHistory failed, falling back to getState:",Be);const kt=await c.getState({threadId:W,checkpointId:K??void 0,checkpointNs:fe??void 0});return{payload:{version:ta,threadId:W,checkpoints:[kt]},usedHistoryApi:!1}}})().then(Be=>(yt.current.set(le,{result:Be,timestamp:Date.now()}),jt(),Be)).finally(()=>{nt.current.get(le)===bt&&nt.current.delete(le)});return nt.current.set(le,bt),bt},[c,G,jt]),ve=b.useCallback((I,A)=>new Promise((W,K)=>{const fe=async()=>{Ye.current=!0;try{await I(),W()}catch(le){K(le)}finally{Ye.current=!1;const le=ot.current.shift();le&&le().catch(()=>{})}};Ye.current?ot.current.push(fe):fe().catch(le=>{K(le)})}),[]),pt=b.useRef(S.length),mt=b.useRef(!1);b.useEffect(()=>{pt.current=S.length},[S.length]),b.useEffect(()=>{const I=U.pendingInterrupt??ix(U.messages);ou(V,I)||$(I??null)},[V,U.messages,U.pendingInterrupt]);const ct=b.useCallback(async()=>{const I=pt.current>0;I||P(!0);try{const A=await c.listThreads();b.startTransition(()=>{k(W=>{const K=ht=>ht.map(bt=>`${bt.threadId}:${bt.updatedAt??""}:${bt.messageCount??""}`).join("|"),fe=da(W);return K(fe)===K(A)||A.length===0&&fe.length>0&&!mt.current?W:hs(A)}),I||P(!1)}),O(null),mt.current||(mt.current=!0)}catch(A){i==null||i(String(A)),console.error("[ChatSessionProvider] Failed to refresh threads:",A),O(String(A)),I||P(!1)}},[c,i]),Me=b.useRef(!1),Ut=b.useRef(null),Le=b.useRef(null),xt=b.useRef(""),[Ln,Dt]=b.useState("idle"),fn=b.useRef({attempts:0,timer:null,reason:null}),io=b.useRef(null),ao=b.useRef(0),Lr=b.useRef(()=>{}),Fr=b.useRef(()=>{}),N=b.useRef(()=>{}),Y=I=>{if(!I||typeof I!="object")return!1;const A=I;return A.code==="ECONNABORTED"?!0:(typeof A.message=="string"?A.message.toLowerCase():"").includes("timeout")},ae=b.useCallback(async I=>{const A=await c.listCheckpointSummaries(I);return au(A??[])},[c]),Ce=b.useCallback((I,A)=>{if(!Cr())return;Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null);const W=I.map(fe=>`${fe.threadId}:${fe.updatedAt??""}:${fe.messageCount??""}`).join("|");if(I.length===0){try{oa(w)}catch{}xt.current="";return}if(W===xt.current)return;const K=()=>{try{const fe=I.slice(0,aa);ca(w,fe),xt.current=W}catch{}finally{Le.current=null}};if(A!=null&&A.immediate){K();return}Le.current=window.setTimeout(()=>{ru(K)},ds)},[w]),Ge=b.useCallback(()=>{Ce(S,{immediate:!0})},[Ce,S]),qe=b.useCallback((I,A,W,K)=>{var Ul;const fe=W??Se.current;if(!fe)return;const le=un(I),ht=fe===Se.current,bt=(K==null?void 0:K.persist)!==!1;if(A==="replace"){if(bt){const Vt={threadId:fe,snapshot:un(I,{cloneMessages:!0})};Ke.current.set(fe,Vt),tt.current=fe}if(!ht)return;re(le.messages,{checkpointId:le.checkpointId??null,checkpointNs:le.checkpointNs??null,pendingInterrupt:le.interrupt??null}),$(le.interrupt??null),ue(le.nextCursor??null),Q(!!le.nextCursor),te(le.checkpointId??void 0),q(le.checkpointNs??void 0),ce(le.nextCursorNs??void 0);return}const Be=Ke.current.get(fe),kt=(Be==null?void 0:Be.snapshot)??null,Ht=Array.isArray(kt==null?void 0:kt.messages)?kt.messages:[],pn=un(kt),Jn=Array.isArray(I==null?void 0:I.messages)?I.messages:[],Wt=new Set,Pt=[...Jn,...Ht].filter(Vt=>{const Wl=Vt==null?void 0:Vt.id;return Wl?Wt.has(Wl)?!1:(Wt.add(Wl),!0):!0}),or=iu(pn,le),$r={checkpointId:pn.checkpointId??le.checkpointId??null,checkpointNs:pn.checkpointNs??le.checkpointNs??null,createdAt:le.createdAt??pn.createdAt??null,parentId:le.parentId??pn.parentId??null,branchLabel:le.branchLabel??pn.branchLabel??null,lastMessageId:((Ul=Pt[Pt.length-1])==null?void 0:Ul.id)??null,messagesLen:Pt.length,hasMessages:Pt.length>0,messages:Pt,nextCursor:le.nextCursor??pn.nextCursor??null,nextCursorNs:le.nextCursorNs??pn.nextCursorNs??null,interrupt:pn.interrupt??le.interrupt??null,...or};if(Ke.current.set(fe,{threadId:fe,snapshot:un($r,{cloneMessages:!0})}),!ht)return;Jn.length&&xe(Jn);const lo=I&&Object.prototype.hasOwnProperty.call(I,"checkpointId")?I.checkpointId:void 0,An=I&&Object.prototype.hasOwnProperty.call(I,"checkpointNs")?I.checkpointNs:void 0,zr=I&&Object.prototype.hasOwnProperty.call(I,"nextCursor")?I.nextCursor:void 0,xr=I&&Object.prototype.hasOwnProperty.call(I,"nextCursorNs")?I.nextCursorNs:void 0;ue(Vt=>zr!==void 0?zr??Vt??null:Vt??null),Q(Vt=>zr!==void 0?!!zr:Vt),te(Vt=>lo!==void 0?lo??Vt??void 0:Vt??void 0),q(Vt=>An!==void 0?An??Vt??void 0:Vt??void 0),ce(Vt=>xr!==void 0?xr??void 0:Vt)},[xe,re,$]),He=b.useCallback(I=>{if(I.threadId!=null&&I.threadId!==Se.current)return;const A=un(I.snapshot,{cloneMessages:!0});re(A.messages,{checkpointId:A.checkpointId??null,checkpointNs:A.checkpointNs??null,pendingInterrupt:A.interrupt??null}),$(A.interrupt??null),ue(A.nextCursor??null),Q(!!A.nextCursor),te(A.checkpointId??void 0),q(A.checkpointNs??void 0),ce(A.nextCursorNs??void 0),tt.current=I.threadId,st(I.threadId??Se.current??null)},[re,$,st]),Re=b.useCallback(I=>{if(!I)return;Ke.current.delete(I),y(I),Jt(I);const A=`${I}__`;for(const W of nt.current.keys())W.startsWith(A)&&nt.current.delete(W);for(const W of yt.current.keys())W.startsWith(A)&&yt.current.delete(W);tt.current===I&&(tt.current=null)},[Jt,y]),At=b.useCallback(()=>{const I=Se.current;I&&Re(I),rt([]),Q(!1),je(!1),ue(null),te(void 0),q(void 0),ce(void 0)},[Re,rt]),gt=b.useCallback(({from:I,to:A})=>{const W=Se.current;W&&console.warn(`[ChatSessionProvider] Stream sequence gap detected (${I} -> ${A}) for thread ${W}`)},[]),Ct=b.useCallback(I=>{const A=I.threadId;console.log("[ChatSessionProvider] 📥 Handling thread_info event:",{threadId:A,title:I.title,created:I.created,currentThreads:S.length});const W={threadId:A,title:I.title||`Thread ${A.slice(0,8)}`,createdAt:I.createdAt||new Date().toISOString(),updatedAt:I.updatedAt||new Date().toISOString(),messageCount:I.messageCount||0};Se.current!==A&&(!Se.current&&U.messages.length<=1&&(Xe.current=A),j(A)),b.startTransition(()=>{k(K=>{const fe=K.byId[A];return fe?fe.title===W.title&&fe.updatedAt===W.updatedAt&&fe.messageCount===W.messageCount?K:{byId:{...K.byId,[A]:W},order:K.order}:{byId:{...K.byId,[A]:W},order:[A,...K.order]}})})},[U.messages.length]),{startStream:Zt,stop:Fn,isStreaming:hn,error:zt,setAuthToken:$n,replayBufferedEvents:Z}=Zy({baseUrl:f,onThreadInfo:Ct,onMessageEvent:$e,onUnhandledEvent:I=>{console.warn(`[ChatSessionProvider] Unhandled stream event: ${I.type}`,I)},onSequenceGap:gt,onStreamClosed:I=>{Lr.current(I)},onConnectionError:I=>{Fr.current(I)},onAuthError:a,onHeartbeat:I=>{N.current(I)}}),se=b.useCallback(()=>{const I=fn.current;I.timer!==null&&(window.clearTimeout(I.timer),I.timer=null),I.reason=null},[]),de=b.useCallback((I,A)=>{Dt("connecting"),Zt(I,{onOpen:W=>{var K;se(),fn.current.attempts=0,Dt("connected"),(K=A==null?void 0:A.onOpen)==null||K.call(A,W)},onError:W=>{var K;(K=A==null?void 0:A.onError)==null||K.call(A,W)},onGap:(A==null?void 0:A.onGap)??gt,onConnectionError:W=>{var K;Fr.current(W),(K=A==null?void 0:A.onConnectionError)==null||K.call(A,W)},onHeartbeat:W=>{var K;N.current(W),(K=A==null?void 0:A.onHeartbeat)==null||K.call(A,W)},onClosed:W=>{var K;Lr.current(W),(K=A==null?void 0:A.onClosed)==null||K.call(A,W)}})},[se,gt,Dt,Zt]),Ie=b.useCallback(()=>{const I=Se.current;if(!I)return null;const A=io.current,W=U.lastCheckpointId??(A==null?void 0:A.lastCheckpointId)??null,K=U.lastCheckpointNs??(A==null?void 0:A.lastCheckpointNs)??null,fe={};return W&&(fe.checkpointId=W),K&&(fe.checkpointNs=K),{threadId:I,checkpointId:W,checkpointNs:K,command:{kind:"resume",value:fe}}},[U.lastCheckpointId,U.lastCheckpointNs]),lt=b.useCallback(I=>{const A=fn.current;if(A.timer!==null)return;if(A.attempts>=ex){Dt("error");return}A.attempts+=1,A.reason=I;const W=Math.min(tx*Math.pow(2,A.attempts-1),nx);Dt("reconnecting"),A.timer=window.setTimeout(()=>{A.timer=null,A.reason=null;const K=Ie();if(!K){Dt("error");return}Z(K.threadId??void 0),de(K)},W)},[Ie,Z,Dt,de]),Je=b.useCallback(I=>{var A;if(io.current=I,I.manualStop||I.reason==="complete"){se(),fn.current.attempts=0,Dt("idle");return}if(I.error&&(I.error.includes("token")||I.error.includes("401")||I.error.includes("unauthorized")||I.error.includes("Unauthorized")||I.error.includes("TOKEN_EXPIRED")||I.error.includes("auth_error"))){console.error("[ChatSessionProvider] Auth error detected:",I.error);try{a==null||a(I.error)}catch(K){console.error("[ChatSessionProvider] Error in onAuthError handler:",K)}return}if(I.reason==="error"||I.reason==="aborted"){if((A=I.error)!=null&&A.includes("Stream idle timeout")){console.warn("[ChatSessionProvider] Idle timeout - not scheduling resume (watchdog is generous)");return}lt(`closed:${I.reason}`)}},[se,lt,Dt,a]),it=b.useCallback(I=>{console.warn("[ChatSessionProvider] Stream connection error:",I),lt("connection-error")},[lt]),Bt=b.useCallback(I=>{ao.current=Date.now(),Dt(A=>A==="reconnecting"?"connected":A)},[Dt]);Lr.current=Je,Fr.current=it,N.current=Bt,b.useEffect(()=>()=>{se()},[se]);const sn=b.useCallback(()=>{se(),fn.current.attempts=0,Dt("idle"),Fn()},[se,Dt,Fn]);b.useEffect(()=>{Me.current=hn},[hn]),b.useEffect(()=>{if(!Cr())return;Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null);const I=S.map(W=>`${W.threadId}:${W.updatedAt??""}:${W.messageCount??""}`).join("|");if(S.length===0){try{oa(w)}catch{}xt.current="";return}if(I===xt.current)return;const A=()=>{try{const W=S.slice(0,aa);ca(w,W),xt.current=I}catch{}finally{Le.current=null}};return Le.current=window.setTimeout(()=>{ru(A),Le.current=null},ds),()=>{Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null)}},[S,Ce]),b.useEffect(()=>{var K;const I=c.getAuthToken();$n(I);const A=fe=>{const le=la(h,fe);St.current!==le&&(St.current=le,_t.current=!1),C(le);const ht=ua(le);b.startTransition(()=>{k(hs(ht))}),fe&&!_t.current&&(_t.current=!0)};A(I);const W=(K=c.onTokenChange)==null?void 0:K.call(c,fe=>{fe!==I&&($n(fe),x(),nt.current.clear(),yt.current.clear(),A(fe))});return()=>{W==null||W()}},[c,h,$n,x]);const Xn=b.useCallback(async I=>{var K;const A=`Thread ${(K=crypto.randomUUID)==null?void 0:K.call(crypto)}`,W={threadId:A,title:I||"New Chat",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:0};k(fe=>({byId:{...fe.byId,[A]:W},order:[A,...fe.order]})),j(A);try{const fe=await c.createThread(I),le=typeof fe=="string"?fe:fe.threadId;return k(ht=>{const bt=ht.byId[A];if(!bt)return ht;const Be={...ht.byId};delete Be[A],Be[le]={...bt,threadId:le};const kt=ht.order.map(Ht=>Ht===A?le:Ht);return{byId:Be,order:kt}}),j(le),setTimeout(()=>ct(),10),O(null),le}catch(fe){throw k(le=>{if(!le.byId[A])return le;const ht={...le.byId};delete ht[A];const bt=le.order.filter(Be=>Be!==A);return{byId:ht,order:bt}}),j(null),O(String(fe)),fe}},[c,ct]),Ko=b.useCallback(async I=>{try{await c.deleteThread(I);let A=null;k(W=>{if(!W.byId[I])return W;const K={...W.byId};delete K[I];const fe=W.order.filter(ht=>ht!==I),le={byId:K,order:fe};return A=da(le),le}),A&&Ce(A,{immediate:!0}),Re(I),Se.current===I&&(Xe.current=I,j(null),Se.current=null,tt.current=null,At()),await ct(),O(null)}catch(A){throw O(String(A)),A}},[c,At,Re,ct,Ce]),_i=b.useCallback(async(I,A)=>{try{await c.updateThread(I,A),k(W=>{const K=W.byId[I];return K?{byId:{...W.byId,[I]:{...K,title:A}},order:W.order}:W}),O(null)}catch(W){throw await ct(),O(String(W)),W}},[c,ct]),Nn=b.useCallback(async(I,A,W,K=!1)=>{await ve(async()=>{if(Xe.current===I&&!K){Xe.current=null;return}if(et.current===I&&!K)return;j(Wt=>Wt===I?Wt:I),Se.current=I;const ht=su(I,A??null,W??null),bt=yt.current.get(ht),Be=!K&&!A&&!W&&bt&&Date.now()-bt.timestamp<Qy,kt=!K&&!A&&!W;let Ht=!1;if(kt){const Wt=Ke.current.get(I);if(Wt)He(Wt),Ht=!0;else{const Pt=m(I);Pt&&(Ke.current.set(I,Pt),He(Pt),Ht=!0)}}const pn=K||!Ht||!!A||!!W,Jn=async Wt=>{Wt&&z(!0),et.current=I;try{const Pt=await Te({threadId:I,checkpointId:A,checkpointNs:W},{force:K}),{latest:or,checkpoints:$r,snapshots:lo}=as(Pt.payload);b.startTransition(()=>{qe(or,"replace",I),Gt(I,$r,"replace"),Yt(I,lo,"replace"),R(null),Wt&&z(!1)}),Pt.usedHistoryApi||ae(I).then(An=>{Xt(I,An)}).catch(An=>{console.warn("[ChatSessionProvider] Failed to refresh checkpoint summaries:",An)})}catch(Pt){if(Y(Pt))try{const or=await ae(I),$r=Xt(I,or);if(Q(!1),ue(null),ce(void 0),te(void 0),q(void 0),$r){R("History request timed out. Select a checkpoint to load manually.");return}}catch(or){console.warn("[ChatSessionProvider] Failed to fetch checkpoint summaries after timeout:",or)}throw(!Ht||K||Wt)&&(i==null||i(String(Pt))),R(String(Pt)),Pt}finally{et.current=null}};pn?await Jn(!0):kt&&Ht&&!Be&&Jn(!1).catch(Wt=>{console.warn("[ChatSessionProvider] Background refresh failed:",Wt)})},`loadThread-${I}`)},[He,Xt,qe,ve,ae,Te,Y,i,Gt,Yt]),ji=b.useCallback(async()=>{await ve(async()=>{const I=Se.current;I&&Re(I),Xe.current=null,j(null),Se.current=null,tt.current=null,At(),te(void 0),q(void 0),ce(void 0),ft();try{localStorage.removeItem("lastThreadId")}catch(A){console.warn("[ChatSessionProvider] Failed to clear lastThreadId:",A)}},"clearCurrentThread")},[At,Re,ve,ft]),Um=b.useCallback(async(I,A)=>{const W=Se.current;if(!W)throw new Error("No active thread");const K=Wr(I,A??null),fe=Mt(W,K);if(fe){await ve(async()=>{qe(fe,"replace",W,{persist:!1})},`navigateToCheckpoint-${W}-${K}`);return}await Nn(W,I,A??void 0,!0)},[qe,ve,Mt,Nn]),Wm=b.useCallback(async()=>{if(!Se.current)throw new Error("No active thread");await Nn(Se.current,void 0,void 0,!0)},[Nn]),Vm=b.useCallback(async()=>{if(!Se.current)throw new Error("No active thread");if(ye||!ne)return;const I=J;if(I){je(!0);try{const A=Se.current,W=await Te({threadId:A,checkpointId:I??ke??null,checkpointNs:ie??L??null}),{latest:K,checkpoints:fe,snapshots:le}=as(W.payload),ht=Ve(A);let bt=fe.length>0;if(bt&&ht&&ht.size>0&&(bt=fe.some(Be=>{if(!(Be!=null&&Be.checkpointId))return!1;const kt=Wr(Be.checkpointId,Be.checkpointNs??null);return!ht.has(kt)})),!bt){ue(null),ce(void 0),Q(!1),R(null);return}if(qe(K,"prepend",A??void 0),A&&(Gt(A,fe,"prepend"),Yt(A,le,"prepend"),!W.usedHistoryApi))try{const Be=await ae(A);Xt(A,Be)}catch(Be){console.warn("[ChatSessionProvider] Failed to refresh checkpoint summaries during prepend:",Be)}R(null)}catch(A){throw R(String(A)),A}finally{je(!1)}}},[qe,Te,Ve,ne,ke,L,ie,J,ae,Xt,ye,Gt,Yt]),Km=b.useCallback(I=>{if(I!=null&&I.threadId){if(I.checkpointId){const A=Wr(I.checkpointId,I.checkpointNs??null),W=un({...I,interrupt:I.interrupt??null},{cloneMessages:!0});Yt(I.threadId,{[A]:W},"prepend")}qe(I,"replace",I.threadId)}},[qe,Yt]),qo=b.useCallback(async(I,A)=>{var zr;const W=Se.current,K=(I==null?void 0:I.text)??"",fe=(I==null?void 0:I.attachments)??[],le=fe.length?fe:(A==null?void 0:A.attachments)??[],ht=I==null?void 0:I.messageAdditionalKwargs,bt={...(A==null?void 0:A.payloadExtras)??{},...(I==null?void 0:I.payload)??{}};if(!W&&!Object.keys(bt).length&&le.length===0&&!K.trim()){console.warn("[ChatSessionProvider] Nothing to submit - skipping");return}!W&&!bt.messages&&console.warn("[ChatSessionProvider] No thread ID - message will create new thread");const{contentParts:Be,filesInfo:kt}=await Iy(c,le),Ht=[...Be];K&&K.trim()&&Ht.push({type:"text",text:K.trim()});const pn=!!W,Jn=pn?(A==null?void 0:A.checkpointId)??U.lastCheckpointId??void 0:void 0,Wt=pn?(A==null?void 0:A.checkpointNs)??U.lastCheckpointNs??void 0:void 0,Pt={id:((zr=crypto.randomUUID)==null?void 0:zr.call(crypto))||`user-${Date.now()}`,role:"user",content:Ht,createdAt:new Date().toISOString(),...Jn!=null?{checkpointId:Jn}:{},...Wt!=null?{checkpointNs:Wt}:{}};ht&&Object.keys(ht).length&&(Pt.additionalKwargs={...Pt.additionalKwargs??{},...ht}),Ht.length>0&&Pe(Pt);const or={...Pt,content:Ht},$r=le.length>0,lo={messages:Ht.length>0?[or]:[],files_info:kt,...o&&$r&&s?{active_agent:s}:{},...bt},An={threadId:W??null,payload:lo,checkpointId:Jn??null,checkpointNs:Wt??null,nodeFilter:(A==null?void 0:A.nodeFilter)??null,config:A==null?void 0:A.config,command:(A==null?void 0:A.command)??null};An.threadId||delete An.threadId,An.command||delete An.command,de(An,{onError:xr=>{console.warn("[ChatSessionProvider] Stream error:",xr)},onOpen:({threadId:xr})=>{!Se.current&&xr&&(U.messages.length<=1&&(Xe.current=xr),j(xr))},onGap:gt})},[c,o,s,gt,U.lastCheckpointId,U.lastCheckpointNs,U.messages.length,Pe,de]),qm=b.useCallback(async(I,A,W)=>{if(!Se.current)throw new Error("No active thread to handle interrupt");const fe=A?W??!0:!1;try{try{We({type:"interrupt_response",payload:{interruptId:I}})}catch(le){console.warn("[ChatSessionProvider] optimistic interrupt_response dispatch failed:",le)}await qo({payload:{}},{checkpointId:U.lastCheckpointId??void 0,checkpointNs:U.lastCheckpointNs??void 0,command:{kind:"resume",value:fe}}),$(null)}catch(le){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${I}:`,le),le}},[We,U.lastCheckpointId,U.lastCheckpointNs,qo]);b.useEffect(()=>{if(l==null||l(E),E)try{localStorage.setItem("lastThreadId",E)}catch(I){console.warn("[ChatSessionProvider] Failed to persist lastThreadId:",I)}},[E,l]),b.useEffect(()=>_t.current?void 0:(_t.current=!0,(async()=>{try{if(await ct(),!r&&!t)try{const A=localStorage.getItem("lastThreadId");A&&(j(A),n&&await Nn(A))}catch(A){console.warn("[ChatSessionProvider] Failed to restore last thread:",A)}else t&&n&&await Nn(t)}catch(A){console.error("[ChatSessionProvider] Initialization failed:",A),i==null||i(String(A))}})(),()=>{}),[]),b.useEffect(()=>{const I=Se.current;if(!I||tt.current!==I)return;U.messages.length&&U.messages[U.messages.length-1];const A=un({checkpointId:U.lastCheckpointId??null,checkpointNs:U.lastCheckpointNs??null,messages:U.messages.slice(),nextCursor:J??null,nextCursorNs:ie??null,interrupt:U.pendingInterrupt??V??null}),W=Ke.current.get(I),K=W==null?void 0:W.snapshot,fe=!K||K.messages.length!==A.messages.length||K.messages.some((Be,kt)=>{var Ht;return(Be==null?void 0:Be.id)!==((Ht=A.messages[kt])==null?void 0:Ht.id)}),le=((K==null?void 0:K.checkpointId)??null)!==A.checkpointId||((K==null?void 0:K.checkpointNs)??null)!==A.checkpointNs,ht=((K==null?void 0:K.nextCursor)??null)!==A.nextCursor||((K==null?void 0:K.nextCursorNs)??null)!==A.nextCursorNs,bt=!ou((K==null?void 0:K.interrupt)??null,A.interrupt??null);if(fe||le||ht||bt){const Be={threadId:I,snapshot:A};Ke.current.set(I,Be),Ut.current&&window.clearTimeout(Ut.current),Ut.current=window.setTimeout(()=>{try{g(Be,100)}catch(kt){console.warn("[ChatSessionProvider] Failed to persist thread payload:",kt)}},ds)}},[J,ie,U.lastCheckpointId,U.lastCheckpointNs,U.messages,U.pendingInterrupt,V,g]);const hT=b.useMemo(()=>({threads:S,currentThreadId:E,setCurrentThreadId:j,isLoading:_,error:B,actions:{createThread:Xn,deleteThread:Ko,renameThread:_i,refreshThreads:()=>ct()},persistThreadsCache:Ge,hydrateFromCache:F}),[S,E,_,B,Xn,Ko,_i,ct,Ge,F,j]),pT=b.useMemo(()=>{const I=U.lastBranch??null,A=U.assemblingId??null,W=I||A?{branchLabel:(I==null?void 0:I.branchLabel)??null,lastBranch:I,assemblingMessageId:A}:null;return{threadId:E,messages:U.messages,interrupt:V,checkpoint:{id:U.lastCheckpointId??null,namespace:U.lastCheckpointNs??null},checkpoints:Nt,metadata:W,isLoading:D,isHistoryLoading:ye,error:H,hasMore:ne,loadOlder:Vm,seedFromSnapshot:Km,clearState:At,navigateToCheckpoint:Um,returnToLatest:Wm,loadThread:Nn,clearThread:ji,respondToInterrupt:qm}},[ji,At,E,V,ne,ye,D,Vm,Nn,U.assemblingId,U.lastBranch,U.lastCheckpointId,U.lastCheckpointNs,U.messages,Um,qm,Wm,Km,H,Nt]),mT=b.useMemo(()=>({isStreaming:hn,error:zt,connectionState:Ln,submit:qo,send:qo,stop:sn,setAuthToken:$n}),[Ln,hn,zt,sn,qo,$n]);return u.jsx(wx.Provider,{value:!0,children:u.jsx(uu.Provider,{value:mT,children:u.jsx(lu.Provider,{value:hT,children:u.jsx(cu.Provider,{value:pT,children:e})})})})}function ps(){const e=b.useContext(lu);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function ms(){const e=b.useContext(cu);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function du(){const e=b.useContext(uu);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function gs({children:e,apiConfig:t,initialThreadId:n=null,autoLoadInitial:r=!0,disableAutoRestore:o=!1,enableFileAgentRouting:s=!1,fileAgentId:i="invoice_reader",onError:a,onAuthError:l,onThreadChange:c}){return u.jsx(Ty,{apiConfig:t,children:u.jsx(bx,{initialThreadId:n,autoLoadInitial:r,disableAutoRestore:o,enableFileAgentRouting:s,fileAgentId:i,onError:a,onAuthError:l,onThreadChange:c,children:e})})}function oe(...e){return Jm.twMerge(Xm.clsx(e))}const Sx=Go.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),ut=v.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?vr.Slot:"button";return u.jsx(i,{className:oe(Sx({variant:t,size:n,className:e})),ref:s,...o})});ut.displayName="Button";const fu=v.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{className:oe("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));fu.displayName="Textarea";function hu({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=2e4,value:i,onValueChange:a,onSend:l,onCancelEdit:c,onStop:d,className:f="",textareaClassName:h="",allowEmptySend:p=!1}){const m=i!==void 0,[g,y]=b.useState(e),x=(m?i:g)??"",[w,C]=b.useTransition(),T=b.useRef(null),k=b.useRef(0),S=b.useRef(null);b.useEffect(()=>{m||(y(e??""),S.current=null,T.current&&(T.current.style.height="auto",T.current.style.height=`${T.current.scrollHeight}px`))},[e,t,m]);const E=b.useCallback(()=>{const H=T.current;H&&(H.style.height="auto",H.style.height=`${H.scrollHeight}px`)},[]);b.useEffect(()=>{E()},[E,x]);const j=b.useCallback((H,{fromUser:R})=>{m||y(H),R&&(a==null||a(H))},[m,a]),_=b.useCallback(async H=>{H&&H.preventDefault();const R=(x??"").trim();if(!R&&!p)return;const V=++k.current;S.current={id:V,shouldClear:!0},C(()=>{var $,F,ne;try{const Q=l(R);Q&&typeof Q.then=="function"?Q.then(()=>{var ye,je;((ye=S.current)==null?void 0:ye.id)===V&&S.current.shouldClear&&(m||(y(""),T.current&&(T.current.style.height="auto"),a==null||a(""))),((je=S.current)==null?void 0:je.id)===V&&(S.current=null)}).catch(()=>{var ye;((ye=S.current)==null?void 0:ye.id)===V&&(S.current=null)}):((($=S.current)==null?void 0:$.id)===V&&S.current.shouldClear&&(m||(y(""),T.current&&(T.current.style.height="auto"),a==null||a(""))),((F=S.current)==null?void 0:F.id)===V&&(S.current=null))}catch{((ne=S.current)==null?void 0:ne.id)===V&&(S.current=null)}})},[x,l,p,m,a]),P=b.useCallback(H=>{const R=H.target.value;j(R,{fromUser:!0}),S.current&&(S.current.shouldClear=!1),T.current&&(T.current.style.height="auto",T.current.style.height=`${T.current.scrollHeight}px`)},[j]),D=b.useCallback(H=>{H.key==="Enter"&&!H.shiftKey?(H.preventDefault(),_()):H.key==="Escape"&&t&&(H.preventDefault(),c==null||c())},[_,t,c]),O=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${t?"border-[hsl(var(--ring))] bg-[hsl(var(--card))] text-[hsl(var(--card-foreground))] dark:bg-[hsl(var(--card))] dark:text-[hsl(var(--card-foreground))]":""} ${h}`;return u.jsx("form",{onSubmit:H=>void _(H),className:`w-full ${f}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(fu,{ref:T,value:x,onChange:P,onKeyDown:D,placeholder:t?"Edit your message...":n,className:O,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx(ut,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:u.jsx(he.Square,{size:16})}):u.jsx(ut,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!x.trim()&&!p||w,children:u.jsx(he.Send,{size:16})})})]})})}const Cx=b.memo(hu);function ge(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function pu(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function fa(...e){return t=>{let n=!1;const r=e.map(o=>{const s=pu(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():pu(e[o],null)}}}}function Ze(...e){return v.useCallback(fa(...e),e)}function kx(e,t){const n=v.createContext(t),r=s=>{const{children:i,...a}=s,l=v.useMemo(()=>a,Object.values(a));return u.jsx(n.Provider,{value:l,children:i})};r.displayName=e+"Provider";function o(s){const i=v.useContext(n);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function Qn(e,t=[]){let n=[];function r(s,i){const a=v.createContext(i),l=n.length;n=[...n,i];const c=f=>{var x;const{scope:h,children:p,...m}=f,g=((x=h==null?void 0:h[e])==null?void 0:x[l])||a,y=v.useMemo(()=>m,Object.values(m));return u.jsx(g.Provider,{value:y,children:p})};c.displayName=s+"Provider";function d(f,h){var g;const p=((g=h==null?void 0:h[e])==null?void 0:g[l])||a,m=v.useContext(p);if(m)return m;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>v.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return v.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,Tx(o,...t)]}function Tx(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const f=l(s)[`__scope${c}`];return{...a,...f}},{});return v.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var Kt=globalThis!=null&&globalThis.document?v.useLayoutEffect:()=>{},Ex=v[" useInsertionEffect ".trim().toString()]||Kt;function Vr({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=Ix({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const d=v.useRef(e!==void 0);v.useEffect(()=>{const f=d.current;f!==a&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,r])}const c=v.useCallback(d=>{var f;if(a){const h=Nx(d)?d(e):d;h!==e&&((f=i.current)==null||f.call(i,h))}else s(d)},[a,e,s,i]);return[l,c]}function Ix({defaultProp:e,onChange:t}){const[n,r]=v.useState(e),o=v.useRef(n),s=v.useRef(t);return Ex(()=>{s.current=t},[t]),v.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function Nx(e){return typeof e=="function"}var Ax=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],De=Ax.reduce((e,t)=>{const n=vr.createSlot(`Primitive.${t}`),r=v.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function mu(e,t){e&&Yo.flushSync(()=>e.dispatchEvent(t))}function ha(e){const t=e+"CollectionProvider",[n,r]=Qn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=g=>{const{scope:y,children:x}=g,w=b.useRef(null),C=b.useRef(new Map).current;return u.jsx(o,{scope:y,itemMap:C,collectionRef:w,children:x})};i.displayName=t;const a=e+"CollectionSlot",l=vr.createSlot(a),c=b.forwardRef((g,y)=>{const{scope:x,children:w}=g,C=s(a,x),T=Ze(y,C.collectionRef);return u.jsx(l,{ref:T,children:w})});c.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",h=vr.createSlot(d),p=b.forwardRef((g,y)=>{const{scope:x,children:w,...C}=g,T=b.useRef(null),k=Ze(y,T),S=s(d,x);return b.useEffect(()=>(S.itemMap.set(T,{ref:T,...C}),()=>void S.itemMap.delete(T))),u.jsx(h,{[f]:"",ref:k,children:w})});p.displayName=d;function m(g){const y=s(e+"CollectionConsumer",g);return b.useCallback(()=>{const w=y.collectionRef.current;if(!w)return[];const C=Array.from(w.querySelectorAll(`[${f}]`));return Array.from(y.itemMap.values()).sort((S,E)=>C.indexOf(S.ref.current)-C.indexOf(E.ref.current))},[y.collectionRef,y.itemMap])}return[{Provider:i,Slot:c,ItemSlot:p},m,r]}var _x=v.createContext(void 0);function ys(e){const t=v.useContext(_x);return e||t||"ltr"}function qt(e){const t=v.useRef(e);return v.useEffect(()=>{t.current=e}),v.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function jx(e,t=globalThis==null?void 0:globalThis.document){const n=qt(e);v.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var Px="DismissableLayer",pa="dismissableLayer.update",Rx="dismissableLayer.pointerDownOutside",Ox="dismissableLayer.focusOutside",gu,yu=v.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),xs=v.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=v.useContext(yu),[d,f]=v.useState(null),h=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=v.useState({}),m=Ze(t,E=>f(E)),g=Array.from(c.layers),[y]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),x=g.indexOf(y),w=d?g.indexOf(d):-1,C=c.layersWithOutsidePointerEventsDisabled.size>0,T=w>=x,k=Lx(E=>{const j=E.target,_=[...c.branches].some(P=>P.contains(j));!T||_||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},h),S=Fx(E=>{const j=E.target;[...c.branches].some(P=>P.contains(j))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},h);return jx(E=>{w===c.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},h),v.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(gu=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),xu(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=gu)}},[d,h,n,c]),v.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),xu())},[d,c]),v.useEffect(()=>{const E=()=>p({});return document.addEventListener(pa,E),()=>document.removeEventListener(pa,E)},[]),u.jsx(De.div,{...l,ref:m,style:{pointerEvents:C?T?"auto":"none":void 0,...e.style},onFocusCapture:ge(e.onFocusCapture,S.onFocusCapture),onBlurCapture:ge(e.onBlurCapture,S.onBlurCapture),onPointerDownCapture:ge(e.onPointerDownCapture,k.onPointerDownCapture)})});xs.displayName=Px;var Mx="DismissableLayerBranch",Dx=v.forwardRef((e,t)=>{const n=v.useContext(yu),r=v.useRef(null),o=Ze(t,r);return v.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(De.div,{...e,ref:o})});Dx.displayName=Mx;function Lx(e,t=globalThis==null?void 0:globalThis.document){const n=qt(e),r=v.useRef(!1),o=v.useRef(()=>{});return v.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){vu(Rx,n,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function Fx(e,t=globalThis==null?void 0:globalThis.document){const n=qt(e),r=v.useRef(!1);return v.useEffect(()=>{const o=s=>{s.target&&!r.current&&vu(Ox,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function xu(){const e=new CustomEvent(pa);document.dispatchEvent(e)}function vu(e,t,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?mu(o,s):o.dispatchEvent(s)}var ma=0;function ga(){v.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??wu()),document.body.insertAdjacentElement("beforeend",e[1]??wu()),ma++,()=>{ma===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),ma--}},[])}function wu(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var ya="focusScope.autoFocusOnMount",xa="focusScope.autoFocusOnUnmount",bu={bubbles:!1,cancelable:!0},$x="FocusScope",vs=v.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=v.useState(null),c=qt(o),d=qt(s),f=v.useRef(null),h=Ze(t,g=>l(g)),p=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(r){let g=function(C){if(p.paused||!a)return;const T=C.target;a.contains(T)?f.current=T:ir(f.current,{select:!0})},y=function(C){if(p.paused||!a)return;const T=C.relatedTarget;T!==null&&(a.contains(T)||ir(f.current,{select:!0}))},x=function(C){if(document.activeElement===document.body)for(const k of C)k.removedNodes.length>0&&ir(a)};document.addEventListener("focusin",g),document.addEventListener("focusout",y);const w=new MutationObserver(x);return a&&w.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",y),w.disconnect()}}},[r,a,p.paused]),v.useEffect(()=>{if(a){ku.add(p);const g=document.activeElement;if(!a.contains(g)){const x=new CustomEvent(ya,bu);a.addEventListener(ya,c),a.dispatchEvent(x),x.defaultPrevented||(zx(Vx(Su(a)),{select:!0}),document.activeElement===g&&ir(a))}return()=>{a.removeEventListener(ya,c),setTimeout(()=>{const x=new CustomEvent(xa,bu);a.addEventListener(xa,d),a.dispatchEvent(x),x.defaultPrevented||ir(g??document.body,{select:!0}),a.removeEventListener(xa,d),ku.remove(p)},0)}}},[a,c,d,p]);const m=v.useCallback(g=>{if(!n&&!r||p.paused)return;const y=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,x=document.activeElement;if(y&&x){const w=g.currentTarget,[C,T]=Bx(w);C&&T?!g.shiftKey&&x===T?(g.preventDefault(),n&&ir(C,{select:!0})):g.shiftKey&&x===C&&(g.preventDefault(),n&&ir(T,{select:!0})):x===w&&g.preventDefault()}},[n,r,p.paused]);return u.jsx(De.div,{tabIndex:-1,...i,ref:h,onKeyDown:m})});vs.displayName=$x;function zx(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(ir(r,{select:t}),document.activeElement!==n)return}function Bx(e){const t=Su(e),n=Cu(t,e),r=Cu(t.reverse(),e);return[n,r]}function Su(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Cu(e,t){for(const n of e)if(!Hx(n,{upTo:t}))return n}function Hx(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function Ux(e){return e instanceof HTMLInputElement&&"select"in e}function ir(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Ux(e)&&t&&e.select()}}var ku=Wx();function Wx(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Tu(e,t),e.unshift(t)},remove(t){var n;e=Tu(e,t),(n=e[0])==null||n.resume()}}}function Tu(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function Vx(e){return e.filter(t=>t.tagName!=="A")}var Kx=v[" useId ".trim().toString()]||(()=>{}),qx=0;function er(e){const[t,n]=v.useState(Kx());return Kt(()=>{n(r=>r??String(qx++))},[e]),t?`radix-${t}`:""}const Gx=["top","right","bottom","left"],ar=Math.min,mn=Math.max,ws=Math.round,bs=Math.floor,Bn=e=>({x:e,y:e}),Yx={left:"right",right:"left",bottom:"top",top:"bottom"},Xx={start:"end",end:"start"};function va(e,t,n){return mn(e,ar(t,n))}function tr(e,t){return typeof e=="function"?e(t):e}function nr(e){return e.split("-")[0]}function Kr(e){return e.split("-")[1]}function wa(e){return e==="x"?"y":"x"}function ba(e){return e==="y"?"height":"width"}const Jx=new Set(["top","bottom"]);function Hn(e){return Jx.has(nr(e))?"y":"x"}function Sa(e){return wa(Hn(e))}function Zx(e,t,n){n===void 0&&(n=!1);const r=Kr(e),o=Sa(e),s=ba(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=Ss(i)),[i,Ss(i)]}function Qx(e){const t=Ss(e);return[Ca(e),t,Ca(t)]}function Ca(e){return e.replace(/start|end/g,t=>Xx[t])}const Eu=["left","right"],Iu=["right","left"],ev=["top","bottom"],tv=["bottom","top"];function nv(e,t,n){switch(e){case"top":case"bottom":return n?t?Iu:Eu:t?Eu:Iu;case"left":case"right":return t?ev:tv;default:return[]}}function rv(e,t,n,r){const o=Kr(e);let s=nv(nr(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(Ca)))),s}function Ss(e){return e.replace(/left|right|bottom|top/g,t=>Yx[t])}function ov(e){return{top:0,right:0,bottom:0,left:0,...e}}function Nu(e){return typeof e!="number"?ov(e):{top:e,right:e,bottom:e,left:e}}function Cs(e){const{x:t,y:n,width:r,height:o}=e;return{width:r,height:o,top:n,left:t,right:t+r,bottom:n+o,x:t,y:n}}function Au(e,t,n){let{reference:r,floating:o}=e;const s=Hn(t),i=Sa(t),a=ba(i),l=nr(t),c=s==="y",d=r.x+r.width/2-o.width/2,f=r.y+r.height/2-o.height/2,h=r[a]/2-o[a]/2;let p;switch(l){case"top":p={x:d,y:r.y-o.height};break;case"bottom":p={x:d,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:f};break;case"left":p={x:r.x-o.width,y:f};break;default:p={x:r.x,y:r.y}}switch(Kr(t)){case"start":p[i]-=h*(n&&c?-1:1);break;case"end":p[i]+=h*(n&&c?-1:1);break}return p}const sv=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,a=s.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(t));let c=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:f}=Au(c,r,l),h=r,p={},m=0;for(let g=0;g<a.length;g++){const{name:y,fn:x}=a[g],{x:w,y:C,data:T,reset:k}=await x({x:d,y:f,initialPlacement:r,placement:h,strategy:o,middlewareData:p,rects:c,platform:i,elements:{reference:e,floating:t}});d=w??d,f=C??f,p={...p,[y]:{...p[y],...T}},k&&m<=50&&(m++,typeof k=="object"&&(k.placement&&(h=k.placement),k.rects&&(c=k.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):k.rects),{x:d,y:f}=Au(c,h,l)),g=-1)}return{x:d,y:f,placement:h,strategy:o,middlewareData:p}};async function xo(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:f="floating",altBoundary:h=!1,padding:p=0}=tr(t,e),m=Nu(p),y=a[h?f==="floating"?"reference":"floating":f],x=Cs(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(y)))==null||n?y:y.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:d,strategy:l})),w=f==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.reference,C=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),T=await(s.isElement==null?void 0:s.isElement(C))?await(s.getScale==null?void 0:s.getScale(C))||{x:1,y:1}:{x:1,y:1},k=Cs(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:w,offsetParent:C,strategy:l}):w);return{top:(x.top-k.top+m.top)/T.y,bottom:(k.bottom-x.bottom+m.bottom)/T.y,left:(x.left-k.left+m.left)/T.x,right:(k.right-x.right+m.right)/T.x}}const iv=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:s,platform:i,elements:a,middlewareData:l}=t,{element:c,padding:d=0}=tr(e,t)||{};if(c==null)return{};const f=Nu(d),h={x:n,y:r},p=Sa(o),m=ba(p),g=await i.getDimensions(c),y=p==="y",x=y?"top":"left",w=y?"bottom":"right",C=y?"clientHeight":"clientWidth",T=s.reference[m]+s.reference[p]-h[p]-s.floating[m],k=h[p]-s.reference[p],S=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let E=S?S[C]:0;(!E||!await(i.isElement==null?void 0:i.isElement(S)))&&(E=a.floating[C]||s.floating[m]);const j=T/2-k/2,_=E/2-g[m]/2-1,P=ar(f[x],_),D=ar(f[w],_),z=P,B=E-g[m]-D,O=E/2-g[m]/2+j,H=va(z,O,B),R=!l.arrow&&Kr(o)!=null&&O!==H&&s.reference[m]/2-(O<z?P:D)-g[m]/2<0,V=R?O<z?O-z:O-B:0;return{[p]:h[p]+V,data:{[p]:H,centerOffset:O-H-V,...R&&{alignmentOffset:V}},reset:R}}}),av=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:s,rects:i,initialPlacement:a,platform:l,elements:c}=t,{mainAxis:d=!0,crossAxis:f=!0,fallbackPlacements:h,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:m="none",flipAlignment:g=!0,...y}=tr(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const x=nr(o),w=Hn(a),C=nr(a)===a,T=await(l.isRTL==null?void 0:l.isRTL(c.floating)),k=h||(C||!g?[Ss(a)]:Qx(a)),S=m!=="none";!h&&S&&k.push(...rv(a,g,m,T));const E=[a,...k],j=await xo(t,y),_=[];let P=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&_.push(j[x]),f){const O=Zx(o,i,T);_.push(j[O[0]],j[O[1]])}if(P=[...P,{placement:o,overflows:_}],!_.every(O=>O<=0)){var D,z;const O=(((D=s.flip)==null?void 0:D.index)||0)+1,H=E[O];if(H&&(!(f==="alignment"?w!==Hn(H):!1)||P.every($=>Hn($.placement)===w?$.overflows[0]>0:!0)))return{data:{index:O,overflows:P},reset:{placement:H}};let R=(z=P.filter(V=>V.overflows[0]<=0).sort((V,$)=>V.overflows[1]-$.overflows[1])[0])==null?void 0:z.placement;if(!R)switch(p){case"bestFit":{var B;const V=(B=P.filter($=>{if(S){const F=Hn($.placement);return F===w||F==="y"}return!0}).map($=>[$.placement,$.overflows.filter(F=>F>0).reduce((F,ne)=>F+ne,0)]).sort(($,F)=>$[1]-F[1])[0])==null?void 0:B[0];V&&(R=V);break}case"initialPlacement":R=a;break}if(o!==R)return{reset:{placement:R}}}return{}}}};function _u(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function ju(e){return Gx.some(t=>e[t]>=0)}const lv=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=tr(e,t);switch(r){case"referenceHidden":{const s=await xo(t,{...o,elementContext:"reference"}),i=_u(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:ju(i)}}}case"escaped":{const s=await xo(t,{...o,altBoundary:!0}),i=_u(s,n.floating);return{data:{escapedOffsets:i,escaped:ju(i)}}}default:return{}}}}},Pu=new Set(["left","top"]);async function cv(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=nr(n),a=Kr(n),l=Hn(n)==="y",c=Pu.has(i)?-1:1,d=s&&l?-1:1,f=tr(t,e);let{mainAxis:h,crossAxis:p,alignmentAxis:m}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof m=="number"&&(p=a==="end"?m*-1:m),l?{x:p*d,y:h*c}:{x:h*c,y:p*d}}const uv=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:s,placement:i,middlewareData:a}=t,l=await cv(t,e);return i===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:s+l.y,data:{...l,placement:i}}}}},dv=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:s=!0,crossAxis:i=!1,limiter:a={fn:y=>{let{x,y:w}=y;return{x,y:w}}},...l}=tr(e,t),c={x:n,y:r},d=await xo(t,l),f=Hn(nr(o)),h=wa(f);let p=c[h],m=c[f];if(s){const y=h==="y"?"top":"left",x=h==="y"?"bottom":"right",w=p+d[y],C=p-d[x];p=va(w,p,C)}if(i){const y=f==="y"?"top":"left",x=f==="y"?"bottom":"right",w=m+d[y],C=m-d[x];m=va(w,m,C)}const g=a.fn({...t,[h]:p,[f]:m});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[h]:s,[f]:i}}}}}},fv=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:s,middlewareData:i}=t,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=tr(e,t),d={x:n,y:r},f=Hn(o),h=wa(f);let p=d[h],m=d[f];const g=tr(a,t),y=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(l){const C=h==="y"?"height":"width",T=s.reference[h]-s.floating[C]+y.mainAxis,k=s.reference[h]+s.reference[C]-y.mainAxis;p<T?p=T:p>k&&(p=k)}if(c){var x,w;const C=h==="y"?"width":"height",T=Pu.has(nr(o)),k=s.reference[f]-s.floating[C]+(T&&((x=i.offset)==null?void 0:x[f])||0)+(T?0:y.crossAxis),S=s.reference[f]+s.reference[C]+(T?0:((w=i.offset)==null?void 0:w[f])||0)-(T?y.crossAxis:0);m<k?m=k:m>S&&(m=S)}return{[h]:p,[f]:m}}}},hv=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:s,platform:i,elements:a}=t,{apply:l=()=>{},...c}=tr(e,t),d=await xo(t,c),f=nr(o),h=Kr(o),p=Hn(o)==="y",{width:m,height:g}=s.floating;let y,x;f==="top"||f==="bottom"?(y=f,x=h===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(x=f,y=h==="end"?"top":"bottom");const w=g-d.top-d.bottom,C=m-d.left-d.right,T=ar(g-d[y],w),k=ar(m-d[x],C),S=!t.middlewareData.shift;let E=T,j=k;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(j=C),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(E=w),S&&!h){const P=mn(d.left,0),D=mn(d.right,0),z=mn(d.top,0),B=mn(d.bottom,0);p?j=m-2*(P!==0||D!==0?P+D:mn(d.left,d.right)):E=g-2*(z!==0||B!==0?z+B:mn(d.top,d.bottom))}await l({...t,availableWidth:j,availableHeight:E});const _=await i.getDimensions(a.floating);return m!==_.width||g!==_.height?{reset:{rects:!0}}:{}}}};function ks(){return typeof window<"u"}function qr(e){return Ru(e)?(e.nodeName||"").toLowerCase():"#document"}function gn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Un(e){var t;return(t=(Ru(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Ru(e){return ks()?e instanceof Node||e instanceof gn(e).Node:!1}function jn(e){return ks()?e instanceof Element||e instanceof gn(e).Element:!1}function Wn(e){return ks()?e instanceof HTMLElement||e instanceof gn(e).HTMLElement:!1}function Ou(e){return!ks()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof gn(e).ShadowRoot}const pv=new Set(["inline","contents"]);function vo(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Pn(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!pv.has(o)}const mv=new Set(["table","td","th"]);function gv(e){return mv.has(qr(e))}const yv=[":popover-open",":modal"];function Ts(e){return yv.some(t=>{try{return e.matches(t)}catch{return!1}})}const xv=["transform","translate","scale","rotate","perspective"],vv=["transform","translate","scale","rotate","perspective","filter"],wv=["paint","layout","strict","content"];function ka(e){const t=Ta(),n=jn(e)?Pn(e):e;return xv.some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||vv.some(r=>(n.willChange||"").includes(r))||wv.some(r=>(n.contain||"").includes(r))}function bv(e){let t=lr(e);for(;Wn(t)&&!Gr(t);){if(ka(t))return t;if(Ts(t))return null;t=lr(t)}return null}function Ta(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const Sv=new Set(["html","body","#document"]);function Gr(e){return Sv.has(qr(e))}function Pn(e){return gn(e).getComputedStyle(e)}function Es(e){return jn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function lr(e){if(qr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Ou(e)&&e.host||Un(e);return Ou(t)?t.host:t}function Mu(e){const t=lr(e);return Gr(t)?e.ownerDocument?e.ownerDocument.body:e.body:Wn(t)&&vo(t)?t:Mu(t)}function wo(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=Mu(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=gn(o);if(s){const a=Ea(i);return t.concat(i,i.visualViewport||[],vo(o)?o:[],a&&n?wo(a):[])}return t.concat(o,wo(o,[],n))}function Ea(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Du(e){const t=Pn(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Wn(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=ws(n)!==s||ws(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function Ia(e){return jn(e)?e:e.contextElement}function Yr(e){const t=Ia(e);if(!Wn(t))return Bn(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=Du(t);let i=(s?ws(n.width):n.width)/r,a=(s?ws(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const Cv=Bn(0);function Lu(e){const t=gn(e);return!Ta()||!t.visualViewport?Cv:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function kv(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==gn(e)?!1:t}function kr(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=Ia(e);let i=Bn(1);t&&(r?jn(r)&&(i=Yr(r)):i=Yr(e));const a=kv(s,n,r)?Lu(s):Bn(0);let l=(o.left+a.x)/i.x,c=(o.top+a.y)/i.y,d=o.width/i.x,f=o.height/i.y;if(s){const h=gn(s),p=r&&jn(r)?gn(r):r;let m=h,g=Ea(m);for(;g&&r&&p!==m;){const y=Yr(g),x=g.getBoundingClientRect(),w=Pn(g),C=x.left+(g.clientLeft+parseFloat(w.paddingLeft))*y.x,T=x.top+(g.clientTop+parseFloat(w.paddingTop))*y.y;l*=y.x,c*=y.y,d*=y.x,f*=y.y,l+=C,c+=T,m=gn(g),g=Ea(m)}}return Cs({width:d,height:f,x:l,y:c})}function Is(e,t){const n=Es(e).scrollLeft;return t?t.left+n:kr(Un(e)).left+n}function Fu(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Is(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function Tv(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=Un(r),a=t?Ts(t.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=Bn(1);const d=Bn(0),f=Wn(r);if((f||!f&&!s)&&((qr(r)!=="body"||vo(i))&&(l=Es(r)),Wn(r))){const p=kr(r);c=Yr(r),d.x=p.x+r.clientLeft,d.y=p.y+r.clientTop}const h=i&&!f&&!s?Fu(i,l):Bn(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+d.x+h.x,y:n.y*c.y-l.scrollTop*c.y+d.y+h.y}}function Ev(e){return Array.from(e.getClientRects())}function Iv(e){const t=Un(e),n=Es(e),r=e.ownerDocument.body,o=mn(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=mn(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+Is(e);const a=-n.scrollTop;return Pn(r).direction==="rtl"&&(i+=mn(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const $u=25;function Nv(e,t){const n=gn(e),r=Un(e),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,a=0,l=0;if(o){s=o.width,i=o.height;const d=Ta();(!d||d&&t==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const c=Is(r);if(c<=0){const d=r.ownerDocument,f=d.body,h=getComputedStyle(f),p=d.compatMode==="CSS1Compat"&&parseFloat(h.marginLeft)+parseFloat(h.marginRight)||0,m=Math.abs(r.clientWidth-f.clientWidth-p);m<=$u&&(s-=m)}else c<=$u&&(s+=c);return{width:s,height:i,x:a,y:l}}const Av=new Set(["absolute","fixed"]);function _v(e,t){const n=kr(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=Wn(e)?Yr(e):Bn(1),i=e.clientWidth*s.x,a=e.clientHeight*s.y,l=o*s.x,c=r*s.y;return{width:i,height:a,x:l,y:c}}function zu(e,t,n){let r;if(t==="viewport")r=Nv(e,n);else if(t==="document")r=Iv(Un(e));else if(jn(t))r=_v(t,n);else{const o=Lu(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return Cs(r)}function Bu(e,t){const n=lr(e);return n===t||!jn(n)||Gr(n)?!1:Pn(n).position==="fixed"||Bu(n,t)}function jv(e,t){const n=t.get(e);if(n)return n;let r=wo(e,[],!1).filter(a=>jn(a)&&qr(a)!=="body"),o=null;const s=Pn(e).position==="fixed";let i=s?lr(e):e;for(;jn(i)&&!Gr(i);){const a=Pn(i),l=ka(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&Av.has(o.position)||vo(i)&&!l&&Bu(e,i))?r=r.filter(d=>d!==i):o=a,i=lr(i)}return t.set(e,r),r}function Pv(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?Ts(t)?[]:jv(t,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,d)=>{const f=zu(t,d,o);return c.top=mn(f.top,c.top),c.right=ar(f.right,c.right),c.bottom=ar(f.bottom,c.bottom),c.left=mn(f.left,c.left),c},zu(t,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function Rv(e){const{width:t,height:n}=Du(e);return{width:t,height:n}}function Ov(e,t,n){const r=Wn(t),o=Un(t),s=n==="fixed",i=kr(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const l=Bn(0);function c(){l.x=Is(o)}if(r||!r&&!s)if((qr(t)!=="body"||vo(o))&&(a=Es(t)),r){const p=kr(t,!0,s,t);l.x=p.x+t.clientLeft,l.y=p.y+t.clientTop}else o&&c();s&&!r&&o&&c();const d=o&&!r&&!s?Fu(o,a):Bn(0),f=i.left+a.scrollLeft-l.x-d.x,h=i.top+a.scrollTop-l.y-d.y;return{x:f,y:h,width:i.width,height:i.height}}function Na(e){return Pn(e).position==="static"}function Hu(e,t){if(!Wn(e)||Pn(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Un(e)===n&&(n=n.ownerDocument.body),n}function Uu(e,t){const n=gn(e);if(Ts(e))return n;if(!Wn(e)){let o=lr(e);for(;o&&!Gr(o);){if(jn(o)&&!Na(o))return o;o=lr(o)}return n}let r=Hu(e,t);for(;r&&gv(r)&&Na(r);)r=Hu(r,t);return r&&Gr(r)&&Na(r)&&!ka(r)?n:r||bv(e)||n}const Mv=async function(e){const t=this.getOffsetParent||Uu,n=this.getDimensions,r=await n(e.floating);return{reference:Ov(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function Dv(e){return Pn(e).direction==="rtl"}const Lv={convertOffsetParentRelativeRectToViewportRelativeRect:Tv,getDocumentElement:Un,getClippingRect:Pv,getOffsetParent:Uu,getElementRects:Mv,getClientRects:Ev,getDimensions:Rv,getScale:Yr,isElement:jn,isRTL:Dv};function Wu(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Fv(e,t){let n=null,r;const o=Un(e);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function i(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),s();const c=e.getBoundingClientRect(),{left:d,top:f,width:h,height:p}=c;if(a||t(),!h||!p)return;const m=bs(f),g=bs(o.clientWidth-(d+h)),y=bs(o.clientHeight-(f+p)),x=bs(d),C={rootMargin:-m+"px "+-g+"px "+-y+"px "+-x+"px",threshold:mn(0,ar(1,l))||1};let T=!0;function k(S){const E=S[0].intersectionRatio;if(E!==l){if(!T)return i();E?i(!1,E):r=setTimeout(()=>{i(!1,1e-7)},1e3)}E===1&&!Wu(c,e.getBoundingClientRect())&&i(),T=!1}try{n=new IntersectionObserver(k,{...C,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,C)}n.observe(e)}return i(!0),s}function $v(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,c=Ia(e),d=o||s?[...c?wo(c):[],...wo(t)]:[];d.forEach(x=>{o&&x.addEventListener("scroll",n,{passive:!0}),s&&x.addEventListener("resize",n)});const f=c&&a?Fv(c,n):null;let h=-1,p=null;i&&(p=new ResizeObserver(x=>{let[w]=x;w&&w.target===c&&p&&(p.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var C;(C=p)==null||C.observe(t)})),n()}),c&&!l&&p.observe(c),p.observe(t));let m,g=l?kr(e):null;l&&y();function y(){const x=kr(e);g&&!Wu(g,x)&&n(),g=x,m=requestAnimationFrame(y)}return n(),()=>{var x;d.forEach(w=>{o&&w.removeEventListener("scroll",n),s&&w.removeEventListener("resize",n)}),f==null||f(),(x=p)==null||x.disconnect(),p=null,l&&cancelAnimationFrame(m)}}const zv=uv,Bv=dv,Hv=av,Uv=hv,Wv=lv,Vu=iv,Vv=fv,Kv=(e,t,n)=>{const r=new Map,o={platform:Lv,...n},s={...o.platform,_c:r};return sv(e,t,{...o,platform:s})};var qv=typeof document<"u",Gv=function(){},Ns=qv?b.useLayoutEffect:Gv;function As(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!As(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const s=o[r];if(!(s==="_owner"&&e.$$typeof)&&!As(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function Ku(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function qu(e,t){const n=Ku(e);return Math.round(t*n)/n}function Aa(e){const t=v.useRef(e);return Ns(()=>{t.current=e}),t}function Yv(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:s,floating:i}={},transform:a=!0,whileElementsMounted:l,open:c}=e,[d,f]=v.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[h,p]=v.useState(r);As(h,r)||p(r);const[m,g]=v.useState(null),[y,x]=v.useState(null),w=v.useCallback($=>{$!==S.current&&(S.current=$,g($))},[]),C=v.useCallback($=>{$!==E.current&&(E.current=$,x($))},[]),T=s||m,k=i||y,S=v.useRef(null),E=v.useRef(null),j=v.useRef(d),_=l!=null,P=Aa(l),D=Aa(o),z=Aa(c),B=v.useCallback(()=>{if(!S.current||!E.current)return;const $={placement:t,strategy:n,middleware:h};D.current&&($.platform=D.current),Kv(S.current,E.current,$).then(F=>{const ne={...F,isPositioned:z.current!==!1};O.current&&!As(j.current,ne)&&(j.current=ne,Yo.flushSync(()=>{f(ne)}))})},[h,t,n,D,z]);Ns(()=>{c===!1&&j.current.isPositioned&&(j.current.isPositioned=!1,f($=>({...$,isPositioned:!1})))},[c]);const O=v.useRef(!1);Ns(()=>(O.current=!0,()=>{O.current=!1}),[]),Ns(()=>{if(T&&(S.current=T),k&&(E.current=k),T&&k){if(P.current)return P.current(T,k,B);B()}},[T,k,B,P,_]);const H=v.useMemo(()=>({reference:S,floating:E,setReference:w,setFloating:C}),[w,C]),R=v.useMemo(()=>({reference:T,floating:k}),[T,k]),V=v.useMemo(()=>{const $={position:n,left:0,top:0};if(!R.floating)return $;const F=qu(R.floating,d.x),ne=qu(R.floating,d.y);return a?{...$,transform:"translate("+F+"px, "+ne+"px)",...Ku(R.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:F,top:ne}},[n,a,R.floating,d.x,d.y]);return v.useMemo(()=>({...d,update:B,refs:H,elements:R,floatingStyles:V}),[d,B,H,R,V])}const Xv=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Vu({element:r.current,padding:o}).fn(n):{}:r?Vu({element:r,padding:o}).fn(n):{}}}},Jv=(e,t)=>({...zv(e),options:[e,t]}),Zv=(e,t)=>({...Bv(e),options:[e,t]}),Qv=(e,t)=>({...Vv(e),options:[e,t]}),ew=(e,t)=>({...Hv(e),options:[e,t]}),tw=(e,t)=>({...Uv(e),options:[e,t]}),nw=(e,t)=>({...Wv(e),options:[e,t]}),rw=(e,t)=>({...Xv(e),options:[e,t]});var ow="Arrow",Gu=v.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return u.jsx(De.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:u.jsx("polygon",{points:"0,0 30,0 15,10"})})});Gu.displayName=ow;var sw=Gu;function Yu(e){const[t,n]=v.useState(void 0);return Kt(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let i,a;if("borderBoxSize"in s){const l=s.borderBoxSize,c=Array.isArray(l)?l[0]:l;i=c.inlineSize,a=c.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var _a="Popper",[Xu,_s]=Qn(_a),[iw,Ju]=Xu(_a),Zu=e=>{const{__scopePopper:t,children:n}=e,[r,o]=v.useState(null);return u.jsx(iw,{scope:t,anchor:r,onAnchorChange:o,children:n})};Zu.displayName=_a;var Qu="PopperAnchor",ed=v.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=Ju(Qu,n),i=v.useRef(null),a=Ze(t,i),l=v.useRef(null);return v.useEffect(()=>{const c=l.current;l.current=(r==null?void 0:r.current)||i.current,c!==l.current&&s.onAnchorChange(l.current)}),r?null:u.jsx(De.div,{...o,ref:a})});ed.displayName=Qu;var ja="PopperContent",[aw,lw]=Xu(ja),td=v.forwardRef((e,t)=>{var te,L,q,ie,ce,U;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:d=0,sticky:f="partial",hideWhenDetached:h=!1,updatePositionStrategy:p="optimized",onPlaced:m,...g}=e,y=Ju(ja,n),[x,w]=v.useState(null),C=Ze(t,We=>w(We)),[T,k]=v.useState(null),S=Yu(T),E=(S==null?void 0:S.width)??0,j=(S==null?void 0:S.height)??0,_=r+(s!=="center"?"-"+s:""),P=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},D=Array.isArray(c)?c:[c],z=D.length>0,B={padding:P,boundary:D.filter(uw),altBoundary:z},{refs:O,floatingStyles:H,placement:R,isPositioned:V,middlewareData:$}=Yv({strategy:"fixed",placement:_,whileElementsMounted:(...We)=>$v(...We,{animationFrame:p==="always"}),elements:{reference:y.anchor},middleware:[Jv({mainAxis:o+j,alignmentAxis:i}),l&&Zv({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?Qv():void 0,...B}),l&&ew({...B}),tw({...B,apply:({elements:We,rects:re,availableWidth:xe,availableHeight:Pe})=>{const{width:$e,height:rt}=re.reference,Se=We.floating.style;Se.setProperty("--radix-popper-available-width",`${xe}px`),Se.setProperty("--radix-popper-available-height",`${Pe}px`),Se.setProperty("--radix-popper-anchor-width",`${$e}px`),Se.setProperty("--radix-popper-anchor-height",`${rt}px`)}}),T&&rw({element:T,padding:a}),dw({arrowWidth:E,arrowHeight:j}),h&&nw({strategy:"referenceHidden",...B})]}),[F,ne]=od(R),Q=qt(m);Kt(()=>{V&&(Q==null||Q())},[V,Q]);const ye=(te=$.arrow)==null?void 0:te.x,je=(L=$.arrow)==null?void 0:L.y,J=((q=$.arrow)==null?void 0:q.centerOffset)!==0,[ue,ke]=v.useState();return Kt(()=>{x&&ke(window.getComputedStyle(x).zIndex)},[x]),u.jsx("div",{ref:O.setFloating,"data-radix-popper-content-wrapper":"",style:{...H,transform:V?H.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ue,"--radix-popper-transform-origin":[(ie=$.transformOrigin)==null?void 0:ie.x,(ce=$.transformOrigin)==null?void 0:ce.y].join(" "),...((U=$.hide)==null?void 0:U.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:u.jsx(aw,{scope:n,placedSide:F,onArrowChange:k,arrowX:ye,arrowY:je,shouldHideArrow:J,children:u.jsx(De.div,{"data-side":F,"data-align":ne,...g,ref:C,style:{...g.style,animation:V?void 0:"none"}})})})});td.displayName=ja;var nd="PopperArrow",cw={top:"bottom",right:"left",bottom:"top",left:"right"},rd=v.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=lw(nd,r),i=cw[s.placedSide];return u.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:u.jsx(sw,{...o,ref:n,style:{...o.style,display:"block"}})})});rd.displayName=nd;function uw(e){return e!==null}var dw=e=>({name:"transformOrigin",options:e,fn(t){var y,x,w;const{placement:n,rects:r,middlewareData:o}=t,i=((y=o.arrow)==null?void 0:y.centerOffset)!==0,a=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[c,d]=od(n),f={start:"0%",center:"50%",end:"100%"}[d],h=(((x=o.arrow)==null?void 0:x.x)??0)+a/2,p=(((w=o.arrow)==null?void 0:w.y)??0)+l/2;let m="",g="";return c==="bottom"?(m=i?f:`${h}px`,g=`${-l}px`):c==="top"?(m=i?f:`${h}px`,g=`${r.floating.height+l}px`):c==="right"?(m=`${-l}px`,g=i?f:`${p}px`):c==="left"&&(m=`${r.floating.width+l}px`,g=i?f:`${p}px`),{data:{x:m,y:g}}}});function od(e){const[t,n="center"]=e.split("-");return[t,n]}var sd=Zu,id=ed,ad=td,ld=rd,fw="Portal",js=v.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=v.useState(!1);Kt(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Pi.createPortal(u.jsx(De.div,{...r,ref:t}),i):null});js.displayName=fw;function hw(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var Sn=e=>{const{present:t,children:n}=e,r=pw(t),o=typeof n=="function"?n({present:r.isPresent}):v.Children.only(n),s=Ze(r.ref,mw(o));return typeof n=="function"||r.isPresent?v.cloneElement(o,{ref:s}):null};Sn.displayName="Presence";function pw(e){const[t,n]=v.useState(),r=v.useRef(null),o=v.useRef(e),s=v.useRef("none"),i=e?"mounted":"unmounted",[a,l]=hw(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return v.useEffect(()=>{const c=Ps(r.current);s.current=a==="mounted"?c:"none"},[a]),Kt(()=>{const c=r.current,d=o.current;if(d!==e){const h=s.current,p=Ps(c);e?l("MOUNT"):p==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(d&&h!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),Kt(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,f=p=>{const g=Ps(r.current).includes(CSS.escape(p.animationName));if(p.target===t&&g&&(l("ANIMATION_END"),!o.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",c=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},h=p=>{p.target===t&&(s.current=Ps(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{d.clearTimeout(c),t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:v.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function Ps(e){return(e==null?void 0:e.animationName)||"none"}function mw(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Pa="rovingFocusGroup.onEntryFocus",gw={bubbles:!1,cancelable:!0},bo="RovingFocusGroup",[Ra,cd,yw]=ha(bo),[xw,ud]=Qn(bo,[yw]),[vw,ww]=xw(bo),dd=v.forwardRef((e,t)=>u.jsx(Ra.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Ra.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(bw,{...e,ref:t})})}));dd.displayName=bo;var bw=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:d=!1,...f}=e,h=v.useRef(null),p=Ze(t,h),m=ys(s),[g,y]=Vr({prop:i,defaultProp:a??null,onChange:l,caller:bo}),[x,w]=v.useState(!1),C=qt(c),T=cd(n),k=v.useRef(!1),[S,E]=v.useState(0);return v.useEffect(()=>{const j=h.current;if(j)return j.addEventListener(Pa,C),()=>j.removeEventListener(Pa,C)},[C]),u.jsx(vw,{scope:n,orientation:r,dir:m,loop:o,currentTabStopId:g,onItemFocus:v.useCallback(j=>y(j),[y]),onItemShiftTab:v.useCallback(()=>w(!0),[]),onFocusableItemAdd:v.useCallback(()=>E(j=>j+1),[]),onFocusableItemRemove:v.useCallback(()=>E(j=>j-1),[]),children:u.jsx(De.div,{tabIndex:x||S===0?-1:0,"data-orientation":r,...f,ref:p,style:{outline:"none",...e.style},onMouseDown:ge(e.onMouseDown,()=>{k.current=!0}),onFocus:ge(e.onFocus,j=>{const _=!k.current;if(j.target===j.currentTarget&&_&&!x){const P=new CustomEvent(Pa,gw);if(j.currentTarget.dispatchEvent(P),!P.defaultPrevented){const D=T().filter(R=>R.focusable),z=D.find(R=>R.active),B=D.find(R=>R.id===g),H=[z,B,...D].filter(Boolean).map(R=>R.ref.current);pd(H,d)}}k.current=!1}),onBlur:ge(e.onBlur,()=>w(!1))})})}),fd="RovingFocusGroupItem",hd=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,l=er(),c=s||l,d=ww(fd,n),f=d.currentTabStopId===c,h=cd(n),{onFocusableItemAdd:p,onFocusableItemRemove:m,currentTabStopId:g}=d;return v.useEffect(()=>{if(r)return p(),()=>m()},[r,p,m]),u.jsx(Ra.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:u.jsx(De.span,{tabIndex:f?0:-1,"data-orientation":d.orientation,...a,ref:t,onMouseDown:ge(e.onMouseDown,y=>{r?d.onItemFocus(c):y.preventDefault()}),onFocus:ge(e.onFocus,()=>d.onItemFocus(c)),onKeyDown:ge(e.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){d.onItemShiftTab();return}if(y.target!==y.currentTarget)return;const x=kw(y,d.orientation,d.dir);if(x!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.preventDefault();let C=h().filter(T=>T.focusable).map(T=>T.ref.current);if(x==="last")C.reverse();else if(x==="prev"||x==="next"){x==="prev"&&C.reverse();const T=C.indexOf(y.currentTarget);C=d.loop?Tw(C,T+1):C.slice(T+1)}setTimeout(()=>pd(C))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:g!=null}):i})})});hd.displayName=fd;var Sw={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Cw(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function kw(e,t,n){const r=Cw(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Sw[r]}function pd(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Tw(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Ew=dd,Iw=hd,Nw=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Xr=new WeakMap,Rs=new WeakMap,Os={},Oa=0,md=function(e){return e&&(e.host||md(e.parentNode))},Aw=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=md(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},_w=function(e,t,n,r){var o=Aw(t,Array.isArray(e)?e:[e]);Os[n]||(Os[n]=new WeakMap);var s=Os[n],i=[],a=new Set,l=new Set(o),c=function(f){!f||a.has(f)||(a.add(f),c(f.parentNode))};o.forEach(c);var d=function(f){!f||l.has(f)||Array.prototype.forEach.call(f.children,function(h){if(a.has(h))d(h);else try{var p=h.getAttribute(r),m=p!==null&&p!=="false",g=(Xr.get(h)||0)+1,y=(s.get(h)||0)+1;Xr.set(h,g),s.set(h,y),i.push(h),g===1&&m&&Rs.set(h,!0),y===1&&h.setAttribute(n,"true"),m||h.setAttribute(r,"true")}catch(x){console.error("aria-hidden: cannot operate on ",h,x)}})};return d(t),a.clear(),Oa++,function(){i.forEach(function(f){var h=Xr.get(f)-1,p=s.get(f)-1;Xr.set(f,h),s.set(f,p),h||(Rs.has(f)||f.removeAttribute(r),Rs.delete(f)),p||f.removeAttribute(n)}),Oa--,Oa||(Xr=new WeakMap,Xr=new WeakMap,Rs=new WeakMap,Os={})}},Ma=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=Nw(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),_w(r,o,n,"aria-hidden")):function(){return null}},Vn=function(){return Vn=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},Vn.apply(this,arguments)};function gd(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function jw(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}typeof SuppressedError=="function"&&SuppressedError;var Ms="right-scroll-bar-position",Ds="width-before-scroll-bar",Pw="with-scroll-bars-hidden",Rw="--removed-body-scroll-bar-size";function Da(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function Ow(e,t){var n=b.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var Mw=typeof window<"u"?v.useLayoutEffect:v.useEffect,yd=new WeakMap;function Dw(e,t){var n=Ow(null,function(r){return e.forEach(function(o){return Da(o,r)})});return Mw(function(){var r=yd.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||Da(a,null)}),s.forEach(function(a){o.has(a)||Da(a,i)})}yd.set(n,e)},[e]),n}function Lw(e){return e}function Fw(e,t){t===void 0&&(t=Lw);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(s){var i=t(s,r);return n.push(i),function(){n=n.filter(function(a){return a!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var a=n;n=[],a.forEach(s),i=n}var l=function(){var d=i;i=[],d.forEach(s)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(d){i.push(d),c()},filter:function(d){return i=i.filter(d),n}}}};return o}function $w(e){e===void 0&&(e={});var t=Fw(null);return t.options=Vn({async:!0,ssr:!1},e),t}var xd=function(e){var t=e.sideCar,n=gd(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return v.createElement(r,Vn({},n))};xd.isSideCarExport=!0;function zw(e,t){return e.useMedium(t),xd}var vd=$w(),La=function(){},Ls=v.forwardRef(function(e,t){var n=v.useRef(null),r=v.useState({onScrollCapture:La,onWheelCapture:La,onTouchMoveCapture:La}),o=r[0],s=r[1],i=e.forwardProps,a=e.children,l=e.className,c=e.removeScrollBar,d=e.enabled,f=e.shards,h=e.sideCar,p=e.noRelative,m=e.noIsolation,g=e.inert,y=e.allowPinchZoom,x=e.as,w=x===void 0?"div":x,C=e.gapMode,T=gd(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=h,S=Dw([n,t]),E=Vn(Vn({},T),o);return v.createElement(v.Fragment,null,d&&v.createElement(k,{sideCar:vd,removeScrollBar:c,shards:f,noRelative:p,noIsolation:m,inert:g,setCallbacks:s,allowPinchZoom:!!y,lockRef:n,gapMode:C}),i?v.cloneElement(v.Children.only(a),Vn(Vn({},E),{ref:S})):v.createElement(w,Vn({},E,{className:l,ref:S}),a))});Ls.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},Ls.classNames={fullWidth:Ds,zeroRight:Ms};var Bw=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Hw(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Bw();return t&&e.setAttribute("nonce",t),e}function Uw(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Ww(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Vw=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Hw())&&(Uw(t,n),Ww(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Kw=function(){var e=Vw();return function(t,n){v.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},wd=function(){var e=Kw(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},qw={left:0,top:0,right:0,gap:0},Fa=function(e){return parseInt(e||"",10)||0},Gw=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[Fa(n),Fa(r),Fa(o)]},Yw=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return qw;var t=Gw(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},Xw=wd(),Jr="data-scroll-locked",Jw=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
|
|
38
|
+
`)}const tu=200;function Zy({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onUnhandledEvent:r,onSequenceGap:o,onStreamClosed:s,onConnectionError:i,onAuthError:a,onHeartbeat:l}){const c=b.useRef(null),d=b.useRef(null),f=b.useRef(new Map),h=b.useRef(null),p=b.useCallback(_=>{try{const P=globalThis.structuredClone;if(typeof P=="function")return P(_)}catch{}try{return JSON.parse(JSON.stringify(_))}catch{return _}},[]),m=b.useCallback((_,P)=>{if(!_)return;const D=f.current.get(_)??[],z=p(P),B=D.length>=tu?[...D.slice(D.length-tu+1),z]:[...D,z];f.current.set(_,B)},[p]),g=b.useCallback(_=>{_&&f.current.set(_,[])},[]),y=b.useCallback(_=>{const P=_??d.current;if(!P)return;const D=f.current.get(P);D!=null&&D.length&&D.forEach(z=>{try{n(z)}catch(B){console.error("[useChatStreamingService] Failed to replay buffered event",B)}})},[n]),x=b.useCallback(_=>{var z,B,O,H,R;const P=_.seq??null;if(P!==null){const V=c.current;if(V!==null){if(P<=V)return;P>V+1&&(o==null||o({from:V,to:P}))}c.current=P}if(_.type==="thread_info"){d.current=_.threadId,h.current&&(h.current.threadIdGuess=_.threadId),g(_.threadId),console.log("[useChatStreamingService] 🎯 Received thread_info event:",_);try{t(_)}catch(V){console.error("[useChatStreamingService] Error in onThreadInfo handler:",V)}return}if(_.type==="heartbeat"){try{l==null||l(_)}catch(V){console.error("[useChatStreamingService] Error in onHeartbeat handler:",V)}return}if(_.type==="error"){const V=_;if(V.error_type==="auth_error"||V.code==="TOKEN_EXPIRED"||((z=V.message)==null?void 0:z.includes("token"))||((B=V.message)==null?void 0:B.includes("401"))||((O=V.message)==null?void 0:O.includes("unauthorized"))||((H=V.message)==null?void 0:H.includes("Unauthorized"))){console.error("[useChatStreamingService] Auth error event detected:",V.message);try{a==null||a(V.message)}catch(F){console.warn("[useChatStreamingService] onAuthError handler failed",F)}}}const D=_.threadId??(_.type==="state_history"?_.threadId:void 0)??d.current??((R=h.current)==null?void 0:R.threadIdGuess)??null;if(_.type==="state_history"&&(d.current=D??d.current),Uy(_)){_.type==="checkpoint"||_.type==="state_history"?g(D??null):m(D??null,_);try{n(_)}catch(V){console.error("[useChatStreamingService] Error in onMessageEvent handler:",V)}return}try{r==null||r(_)}catch(V){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",V)}},[m,g,n,o,t,r]),{stream:w,stop:C,isStreaming:T,error:k,setToken:S}=eu({baseUrl:e,token:void 0}),E=b.useCallback((_,P)=>{c.current=null,d.current=_.threadId??null,h.current={request:_,callbacks:P,manualStop:!1,threadIdGuess:_.threadId??null},w(_,x,{onOpen:P==null?void 0:P.onOpen,onError:D=>{var z;(z=P==null?void 0:P.onError)==null||z.call(P,D)},onGap:(P==null?void 0:P.onGap)??o,onConnectionError:D=>{var z;i==null||i(D),(z=P==null?void 0:P.onConnectionError)==null||z.call(P,D)},onAuthError:D=>{var z;a==null||a(D),(z=P==null?void 0:P.onAuthError)==null||z.call(P,D)},onHeartbeat:D=>{var z;try{l==null||l(D)}catch(B){console.warn("[useChatStreamingService] onHeartbeat handler failed",B)}try{(z=P==null?void 0:P.onHeartbeat)==null||z.call(P,D)}catch(B){console.warn("[useChatStreamingService] downstream onHeartbeat handler failed",B)}},onClosed:D=>{var H,R,V,$;const z=((H=h.current)==null?void 0:H.manualStop)??!1,B=d.current??((R=h.current)==null?void 0:R.threadIdGuess)??((V=D.lastStateHistory)==null?void 0:V.threadId)??null;(D.reason==="complete"||D.reason==="aborted"&&z)&&g(B);const O={...D,threadId:B,manualStop:z};try{s==null||s(O)}catch(F){console.warn("[useChatStreamingService] onStreamClosed handler failed",F)}try{($=P==null?void 0:P.onClosed)==null||$.call(P,O)}catch(F){console.warn("[useChatStreamingService] downstream onClosed handler failed",F)}h.current&&(h.current=null)}})},[g,x,a,i,l,o,s,w]),j=b.useCallback(()=>{h.current&&(h.current.manualStop=!0),C()},[C]);return b.useMemo(()=>({startStream:E,stop:j,isStreaming:T,error:k,setAuthToken:S,replayBufferedEvents:y}),[E,j,T,k,S,y])}const nu=50,Qy=750,ta="chat-history@1",ex=5,tx=1e3,nx=15e3,ds=300;function ru(e,t=ds){if(typeof window<"u"&&"requestIdleCallback"in window)try{window.requestIdleCallback(e,{timeout:t});return}catch{}window.setTimeout(e,t)}function Cr(){return typeof window<"u"&&typeof window.localStorage<"u"}function na(e){if(!Cr())return null;try{return window.localStorage.getItem(e)}catch{return null}}function ra(e,t){if(!Cr())return!1;try{return window.localStorage.setItem(e,t),!0}catch{return!1}}function oa(e){if(Cr())try{window.localStorage.removeItem(e)}catch{}}function sa(e){return e==null?e:{...e}}function rx(e){return e==null?e:{...e}}function ox(e){if(Array.isArray(e))return e.slice();if(e==null)return e}function sx(e){if(Array.isArray(e))return e.map(t=>({...t}));if(e==null)return e}function un(e,t={}){const n=t.cloneMessages??!1,r=Array.isArray(e==null?void 0:e.messages)?e.messages:[],o=sa(e==null?void 0:e.metadata),s=sa(e==null?void 0:e.config),i=sa(e==null?void 0:e.parentConfig),a=ox(e==null?void 0:e.next),l=sx(e==null?void 0:e.tasks),c=rx(e==null?void 0:e.values),d={checkpointId:(e==null?void 0:e.checkpointId)??null,checkpointNs:(e==null?void 0:e.checkpointNs)??null,createdAt:(e==null?void 0:e.createdAt)??null,parentId:(e==null?void 0:e.parentId)??null,branchLabel:(e==null?void 0:e.branchLabel)??null,lastMessageId:(e==null?void 0:e.lastMessageId)??null,messagesLen:typeof(e==null?void 0:e.messagesLen)=="number"?e.messagesLen:r.length,hasMessages:typeof(e==null?void 0:e.hasMessages)=="boolean"?e.hasMessages:r.length>0,messages:n?r.slice():r,nextCursor:(e==null?void 0:e.nextCursor)??null,nextCursorNs:(e==null?void 0:e.nextCursorNs)??null,interrupt:(e==null?void 0:e.interrupt)??null};return o!==void 0&&(d.metadata=o),s!==void 0&&(d.config=s),i!==void 0&&(d.parentConfig=i),a!==void 0&&(d.next=a),l!==void 0&&(d.tasks=l),c!==void 0&&(d.values=c),d}function ix(e){var t;for(let n=e.length-1;n>=0;n--){const r=((t=e[n])==null?void 0:t.content)??[];for(let o=r.length-1;o>=0;o--){const s=r[o];if((s==null?void 0:s.type)==="interrupt"){const i=s.id;return{id:(typeof i=="string"?i:null)??`interrupt-${e[n].id??o}`,value:s.value}}}}return null}function ou(e,t){if(!e&&!t)return!0;if(!e||!t||e.id!==t.id)return!1;try{return JSON.stringify(e.value)===JSON.stringify(t.value)}catch{return e.value===t.value}}function ia(e,t){return`${e}${t}`}function ax(e,t){const n=na(ia(e,t));if(!n)return null;try{const r=JSON.parse(n);return typeof(r==null?void 0:r.threadId)!="string"?null:{threadId:r.threadId,snapshot:un(r.snapshot,{cloneMessages:!0}),updatedAt:typeof r.updatedAt=="number"?r.updatedAt:void 0}}catch{return null}}function lx(e,t,n=100){if(!Cr())return;const r=un(t.snapshot,{cloneMessages:!0}),o={threadId:t.threadId,snapshot:{...r,messages:r.messages.slice(-n)},updatedAt:Date.now()},s=ia(e,t.threadId),i=JSON.stringify(o);if(!ra(s,i))try{const a=[];for(let l=0;l<window.localStorage.length;l++){const c=window.localStorage.key(l);if(!c||c===s||!c.startsWith(e))continue;const d=window.localStorage.getItem(c);if(!d){a.push({key:c,updatedAt:0});continue}try{const f=JSON.parse(d),h=typeof(f==null?void 0:f.updatedAt)=="number"&&Number.isFinite(f.updatedAt)?f.updatedAt:0;a.push({key:c,updatedAt:h})}catch{a.push({key:c,updatedAt:0})}}a.sort((l,c)=>l.updatedAt-c.updatedAt);for(const l of a)if(window.localStorage.removeItem(l.key),ra(s,i))break}catch{}}function cx(e,t){oa(ia(e,t))}function ux(e){if(Cr())try{for(let t=0;t<window.localStorage.length;t++){const n=window.localStorage.key(t);n&&n.startsWith(e)&&window.localStorage.removeItem(n)}}catch{}}function su(e,t,n){return`${e}__${t??""}__${n??""}`}function fs(e,t){return t&&typeof t=="object"?{...e&&typeof e=="object"?{...e}:{},...t}:t===null?e&&typeof e=="object"?{...e}:e??null:e&&typeof e=="object"?{...e}:e??void 0}function dx(e,t){return fs(e,t)}function fx(e,t){return Array.isArray(t)?t.slice():t===null?Array.isArray(e)?e.slice():e??null:Array.isArray(e)?e.slice():e??void 0}function hx(e,t){return Array.isArray(t)?t.map(n=>({...n})):t===null?Array.isArray(e)?e.map(n=>({...n})):e??null:Array.isArray(e)?e.map(n=>({...n})):e??void 0}function iu(e,t){const n=fs(e.metadata,t.metadata),r=fs(e.config,t.config),o=fs(e.parentConfig,t.parentConfig),s=fx(e.next,t.next),i=hx(e.tasks,t.tasks),a=dx(e.values,t.values),l={};return n!==void 0&&(l.metadata=n??null),r!==void 0&&(l.config=r??null),o!==void 0&&(l.parentConfig=o??null),s!==void 0&&(l.next=s??null),i!==void 0&&(l.tasks=i??null),a!==void 0&&(l.values=a??null),l}function au(e){return Array.isArray(e)?e.filter(t=>!!(t&&(t.checkpointId||t.checkpointNs))).map(t=>{const n=un(t,{cloneMessages:!0});return{...n,messages:Array.isArray(n.messages)?n.messages:[],values:n.values??null}}):[]}const px="cachedThreads",mx="v1",aa=200;function gx(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n);return(t>>>0).toString(36)}function la(e,t){return`cachedThreads:v1:${e}:${gx(t||"anon")}`}function yx(){const e=na(px);if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>{if(!n||typeof n!="object")return!1;const r=n;return typeof r.threadId=="string"&&typeof r.title=="string"}):[]}catch{return[]}}function xx(e){const t=na(e);if(!t)return[];try{const n=JSON.parse(t);return Array.isArray(n)?n.filter(r=>{if(!r||typeof r!="object")return!1;const o=r;return typeof o.threadId=="string"&&typeof o.title=="string"}):[]}catch{return[]}}function ca(e,t){ra(e,JSON.stringify(t))}function ua(e){const t=xx(e);if(t.length>0)return t;const n=yx();if(n.length>0)try{ca(e,n.slice(0,aa))}catch{}return n}function hs(e){const t={},n=[];for(const r of e)!r||typeof r.threadId!="string"||t[r.threadId]||(t[r.threadId]=r,n.push(r.threadId));return{byId:t,order:n}}function da(e){return e.order.map(t=>e.byId[t]).filter(Boolean)}function vx({currentThreadId:e,currentThreadIdRef:t}){const[n,r]=b.useState([]),o=b.useRef(new Map),s=b.useRef(new Map),i=b.useCallback(m=>{if(!m){r([]);return}const g=o.current.get(m);if(!g||!g.length){r([]);return}r(g.map(y=>un(y,{cloneMessages:!0})))},[]);b.useEffect(()=>{i(e)},[e,i]);const a=b.useCallback((m,g,y)=>{if(!m)return;const x=y==="replace"?[]:o.current.get(m)??[],w=y==="replace"?g:[...g,...x];if(!w.length){y==="replace"&&o.current.set(m,[]),m===t.current&&r([]);return}const C=new Map;for(const k of w){if(!(k!=null&&k.checkpointId))continue;const S=`${k.checkpointId}::${k.checkpointNs??""}`,E=un(k,{cloneMessages:!0}),j=C.get(S);if(!j){C.set(S,E);continue}const _=iu(j,E);C.set(S,{...j,..._})}const T=Array.from(C.values()).sort((k,S)=>{const E=Number.isFinite(Date.parse(k.createdAt??""))?Date.parse(k.createdAt??""):0;return(Number.isFinite(Date.parse(S.createdAt??""))?Date.parse(S.createdAt??""):0)-E});o.current.set(m,T),m===t.current&&i(m)},[t,i]),l=b.useCallback((m,g,y)=>{if(!m)return;const x=s.current.get(m),w=y==="replace"||!x?new Map:new Map(x);if(g&&typeof g=="object")for(const[C,T]of Object.entries(g)){if(!(T!=null&&T.checkpointId))continue;const k=C||Wr(T.checkpointId,T.checkpointNs??null);w.set(k,un(T,{cloneMessages:!0}))}s.current.set(m,w)},[]),c=b.useCallback((m,g)=>{if(!m)return!1;const y=au(g);if(!y.length)return!1;const x=o.current.get(m)??[],w=new Map,C=(k,{preferExisting:S})=>{for(const E of k){if(!(E!=null&&E.checkpointId)&&!(E!=null&&E.checkpointNs))continue;const j=Wr(E.checkpointId??null,E.checkpointNs??null);j&&(S&&w.has(j)?w.set(j,E):w.has(j)&&S||w.set(j,E))}};C(y,{preferExisting:!1}),C(x,{preferExisting:!0});const T=Array.from(w.values()).sort((k,S)=>{const E=Number.isFinite(Date.parse(k.createdAt??""))?Date.parse(k.createdAt??""):0;return(Number.isFinite(Date.parse(S.createdAt??""))?Date.parse(S.createdAt??""):0)-E});return o.current.set(m,T),m===t.current&&r(T.map(k=>un(k,{cloneMessages:!0}))),!0},[t]),d=b.useCallback(m=>{m&&(o.current.delete(m),s.current.delete(m),m===t.current&&r([]))},[t]),f=b.useCallback(()=>{r([])},[]),h=b.useCallback(m=>m?s.current.get(m)??null:null,[]),p=b.useCallback((m,g)=>{var y;if(m)return(y=s.current.get(m))==null?void 0:y.get(g)},[]);return{threadCheckpoints:n,syncActiveThreadCheckpoints:i,updateCheckpointCache:a,updateCheckpointSnapshots:l,applyCheckpointSummaries:c,clearThreadCaches:d,resetThreadCheckpoints:f,getSnapshotCache:h,getSnapshotFromCache:p}}const lu=b.createContext(null),cu=b.createContext(null),uu=b.createContext(null),wx=b.createContext(!1);function bx({children:e,initialThreadId:t=null,autoLoadInitial:n=!0,disableAutoRestore:r=!1,enableFileAgentRouting:o=!1,fileAgentId:s="invoice_reader",onError:i,onAuthError:a,onThreadChange:l}){const{api:c,baseUrl:d}=Yi(),f=b.useMemo(()=>Zn(d),[d]),h=b.useMemo(()=>{try{return new URL(d).host}catch{return"unknown"}},[d]),p=b.useMemo(()=>`threadPayload:${mx}:${h}:`,[h]),m=b.useCallback(I=>ax(p,I),[p]),g=b.useCallback((I,A=100)=>{lx(p,I,A)},[p]),y=b.useCallback(I=>{cx(p,I)},[p]),x=b.useCallback(()=>{ux(p)},[p]),[w,C]=b.useState(()=>{var I;return la(h,(I=c.getAuthToken)==null?void 0:I.call(c))}),[T,k]=b.useState(()=>{var A;const I=ua(la(h,(A=c.getAuthToken)==null?void 0:A.call(c)));return hs(I)}),S=b.useMemo(()=>da(T),[T]),[E,j]=b.useState(t),[_,P]=b.useState(!1),[D,z]=b.useState(!1),[B,O]=b.useState(null),[H,R]=b.useState(null),[V,$]=b.useState(null),F=b.useCallback(()=>{const I=ua(w);b.startTransition(()=>{k(hs(I))})},[w]),[ne,Q]=b.useState(!1),[ye,je]=b.useState(!1),[J,ue]=b.useState(null),[ke,te]=b.useState(void 0),[L,q]=b.useState(void 0),[ie,ce]=b.useState(void 0),{state:U,dispatch:We,seed:re,prepend:xe,pushUser:Pe,onEvent:$e,reset:rt}=Kc(),Se=b.useRef(E);b.useEffect(()=>{Se.current=E},[E]);const Ye=b.useRef(!1),ot=b.useRef([]),et=b.useRef(null),Xe=b.useRef(null),Ke=b.useRef(new Map),tt=b.useRef(E),Ot=b.useRef(!1),St=b.useRef(null),nt=b.useRef(new Map),yt=b.useRef(new Map),{threadCheckpoints:Nt,syncActiveThreadCheckpoints:st,updateCheckpointCache:Gt,updateCheckpointSnapshots:Yt,applyCheckpointSummaries:Xt,clearThreadCaches:Jt,resetThreadCheckpoints:ft,getSnapshotCache:Ve,getSnapshotFromCache:Mt}=vx({currentThreadId:E,currentThreadIdRef:Se}),_t=b.useCallback(()=>{var K;const I=yt.current;if(I.size<=nu)return;const A=Array.from(I.entries()).sort((fe,le)=>fe[1].timestamp-le[1].timestamp),W=I.size-nu;for(let fe=0;fe<W;fe++){const le=(K=A[fe])==null?void 0:K[0];le&&I.delete(le)}},[]),G=b.useCallback((I,A)=>{if(!I)return null;const W=Array.isArray(I.checkpoints)?I.checkpoints:[];return W.length===0?null:{version:I.version===ta?I.version:ta,threadId:I.threadId??A,checkpoints:W}},[]),Te=b.useCallback((I,A)=>{const{threadId:W,checkpointId:K=null,checkpointNs:fe=null}=I,le=su(W,K,fe);if(A!=null&&A.force)nt.current.delete(le),yt.current.delete(le);else{if(A!=null&&A.preferCache){const kt=yt.current.get(le);if(kt)return Promise.resolve(kt.result)}const Be=nt.current.get(le);if(Be)return Be}const bt=(async()=>{try{const Be=await c.getStateHistory({threadId:W,checkpointId:K??void 0,checkpointNs:fe??void 0}),kt=G(Be,W);if(kt)return{payload:kt,usedHistoryApi:!0};throw new Error("History response missing checkpoints")}catch(Be){console.warn("[ChatSessionProvider] getStateHistory failed, falling back to getState:",Be);const kt=await c.getState({threadId:W,checkpointId:K??void 0,checkpointNs:fe??void 0});return{payload:{version:ta,threadId:W,checkpoints:[kt]},usedHistoryApi:!1}}})().then(Be=>(yt.current.set(le,{result:Be,timestamp:Date.now()}),_t(),Be)).finally(()=>{nt.current.get(le)===bt&&nt.current.delete(le)});return nt.current.set(le,bt),bt},[c,G,_t]),ve=b.useCallback((I,A)=>new Promise((W,K)=>{const fe=async()=>{Ye.current=!0;try{await I(),W()}catch(le){K(le)}finally{Ye.current=!1;const le=ot.current.shift();le&&le().catch(()=>{})}};Ye.current?ot.current.push(fe):fe().catch(le=>{K(le)})}),[]),pt=b.useRef(S.length),mt=b.useRef(!1);b.useEffect(()=>{pt.current=S.length},[S.length]),b.useEffect(()=>{const I=U.pendingInterrupt??ix(U.messages);ou(V,I)||$(I??null)},[V,U.messages,U.pendingInterrupt]);const ct=b.useCallback(async()=>{const I=pt.current>0;I||P(!0);try{const A=await c.listThreads();b.startTransition(()=>{k(W=>{const K=ht=>ht.map(bt=>`${bt.threadId}:${bt.updatedAt??""}:${bt.messageCount??""}`).join("|"),fe=da(W);return K(fe)===K(A)||A.length===0&&fe.length>0&&!mt.current?W:hs(A)})}),O(null),mt.current||(mt.current=!0)}catch(A){i==null||i(String(A)),console.error("[ChatSessionProvider] Failed to refresh threads:",A),O(String(A))}finally{I||P(!1)}},[c,i]),Me=b.useRef(!1),Ut=b.useRef(null),Le=b.useRef(null),xt=b.useRef(""),[Ln,Dt]=b.useState("idle"),fn=b.useRef({attempts:0,timer:null,reason:null}),io=b.useRef(null),ao=b.useRef(0),Lr=b.useRef(()=>{}),Fr=b.useRef(()=>{}),N=b.useRef(()=>{}),Y=I=>{if(!I||typeof I!="object")return!1;const A=I;return A.code==="ECONNABORTED"?!0:(typeof A.message=="string"?A.message.toLowerCase():"").includes("timeout")},ae=b.useCallback(async I=>{const A=await c.listCheckpointSummaries(I);return au(A??[])},[c]),Ce=b.useCallback((I,A)=>{if(!Cr())return;Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null);const W=I.map(fe=>`${fe.threadId}:${fe.updatedAt??""}:${fe.messageCount??""}`).join("|");if(I.length===0){try{oa(w)}catch{}xt.current="";return}if(W===xt.current)return;const K=()=>{try{const fe=I.slice(0,aa);ca(w,fe),xt.current=W}catch{}finally{Le.current=null}};if(A!=null&&A.immediate){K();return}Le.current=window.setTimeout(()=>{ru(K)},ds)},[w]),Ge=b.useCallback(()=>{Ce(S,{immediate:!0})},[Ce,S]),qe=b.useCallback((I,A,W,K)=>{var Ul;const fe=W??Se.current;if(!fe)return;const le=un(I),ht=fe===Se.current,bt=(K==null?void 0:K.persist)!==!1;if(A==="replace"){if(bt){const Vt={threadId:fe,snapshot:un(I,{cloneMessages:!0})};Ke.current.set(fe,Vt),tt.current=fe}if(!ht)return;re(le.messages,{checkpointId:le.checkpointId??null,checkpointNs:le.checkpointNs??null,pendingInterrupt:le.interrupt??null}),$(le.interrupt??null),ue(le.nextCursor??null),Q(!!le.nextCursor),te(le.checkpointId??void 0),q(le.checkpointNs??void 0),ce(le.nextCursorNs??void 0);return}const Be=Ke.current.get(fe),kt=(Be==null?void 0:Be.snapshot)??null,Ht=Array.isArray(kt==null?void 0:kt.messages)?kt.messages:[],pn=un(kt),Jn=Array.isArray(I==null?void 0:I.messages)?I.messages:[],Wt=new Set,jt=[...Jn,...Ht].filter(Vt=>{const Wl=Vt==null?void 0:Vt.id;return Wl?Wt.has(Wl)?!1:(Wt.add(Wl),!0):!0}),or=iu(pn,le),$r={checkpointId:pn.checkpointId??le.checkpointId??null,checkpointNs:pn.checkpointNs??le.checkpointNs??null,createdAt:le.createdAt??pn.createdAt??null,parentId:le.parentId??pn.parentId??null,branchLabel:le.branchLabel??pn.branchLabel??null,lastMessageId:((Ul=jt[jt.length-1])==null?void 0:Ul.id)??null,messagesLen:jt.length,hasMessages:jt.length>0,messages:jt,nextCursor:le.nextCursor??pn.nextCursor??null,nextCursorNs:le.nextCursorNs??pn.nextCursorNs??null,interrupt:pn.interrupt??le.interrupt??null,...or};if(Ke.current.set(fe,{threadId:fe,snapshot:un($r,{cloneMessages:!0})}),!ht)return;Jn.length&&xe(Jn);const lo=I&&Object.prototype.hasOwnProperty.call(I,"checkpointId")?I.checkpointId:void 0,An=I&&Object.prototype.hasOwnProperty.call(I,"checkpointNs")?I.checkpointNs:void 0,zr=I&&Object.prototype.hasOwnProperty.call(I,"nextCursor")?I.nextCursor:void 0,xr=I&&Object.prototype.hasOwnProperty.call(I,"nextCursorNs")?I.nextCursorNs:void 0;ue(Vt=>zr!==void 0?zr??Vt??null:Vt??null),Q(Vt=>zr!==void 0?!!zr:Vt),te(Vt=>lo!==void 0?lo??Vt??void 0:Vt??void 0),q(Vt=>An!==void 0?An??Vt??void 0:Vt??void 0),ce(Vt=>xr!==void 0?xr??void 0:Vt)},[xe,re,$]),He=b.useCallback(I=>{if(I.threadId!=null&&I.threadId!==Se.current)return;const A=un(I.snapshot,{cloneMessages:!0});re(A.messages,{checkpointId:A.checkpointId??null,checkpointNs:A.checkpointNs??null,pendingInterrupt:A.interrupt??null}),$(A.interrupt??null),ue(A.nextCursor??null),Q(!!A.nextCursor),te(A.checkpointId??void 0),q(A.checkpointNs??void 0),ce(A.nextCursorNs??void 0),tt.current=I.threadId,st(I.threadId??Se.current??null)},[re,$,st]),Re=b.useCallback(I=>{if(!I)return;Ke.current.delete(I),y(I),Jt(I);const A=`${I}__`;for(const W of nt.current.keys())W.startsWith(A)&&nt.current.delete(W);for(const W of yt.current.keys())W.startsWith(A)&&yt.current.delete(W);tt.current===I&&(tt.current=null)},[Jt,y]),At=b.useCallback(()=>{const I=Se.current;I&&Re(I),rt([]),Q(!1),je(!1),ue(null),te(void 0),q(void 0),ce(void 0)},[Re,rt]),gt=b.useCallback(({from:I,to:A})=>{const W=Se.current;W&&console.warn(`[ChatSessionProvider] Stream sequence gap detected (${I} -> ${A}) for thread ${W}`)},[]),Ct=b.useCallback(I=>{const A=I.threadId;console.log("[ChatSessionProvider] 📥 Handling thread_info event:",{threadId:A,title:I.title,created:I.created,currentThreads:S.length});const W={threadId:A,title:I.title||`Thread ${A.slice(0,8)}`,createdAt:I.createdAt||new Date().toISOString(),updatedAt:I.updatedAt||new Date().toISOString(),messageCount:I.messageCount||0};Se.current!==A&&(!Se.current&&U.messages.length<=1&&(Xe.current=A),j(A)),b.startTransition(()=>{k(K=>{const fe=K.byId[A];return fe?fe.title===W.title&&fe.updatedAt===W.updatedAt&&fe.messageCount===W.messageCount?K:{byId:{...K.byId,[A]:W},order:K.order}:{byId:{...K.byId,[A]:W},order:[A,...K.order]}})})},[U.messages.length]),{startStream:Zt,stop:Fn,isStreaming:hn,error:zt,setAuthToken:$n,replayBufferedEvents:Z}=Zy({baseUrl:f,onThreadInfo:Ct,onMessageEvent:$e,onUnhandledEvent:I=>{console.warn(`[ChatSessionProvider] Unhandled stream event: ${I.type}`,I)},onSequenceGap:gt,onStreamClosed:I=>{Lr.current(I)},onConnectionError:I=>{Fr.current(I)},onAuthError:a,onHeartbeat:I=>{N.current(I)}}),se=b.useCallback(()=>{const I=fn.current;I.timer!==null&&(window.clearTimeout(I.timer),I.timer=null),I.reason=null},[]),de=b.useCallback((I,A)=>{Dt("connecting"),Zt(I,{onOpen:W=>{var K;se(),fn.current.attempts=0,Dt("connected"),(K=A==null?void 0:A.onOpen)==null||K.call(A,W)},onError:W=>{var K;(K=A==null?void 0:A.onError)==null||K.call(A,W)},onGap:(A==null?void 0:A.onGap)??gt,onConnectionError:W=>{var K;Fr.current(W),(K=A==null?void 0:A.onConnectionError)==null||K.call(A,W)},onHeartbeat:W=>{var K;N.current(W),(K=A==null?void 0:A.onHeartbeat)==null||K.call(A,W)},onClosed:W=>{var K;Lr.current(W),(K=A==null?void 0:A.onClosed)==null||K.call(A,W)}})},[se,gt,Dt,Zt]),Ie=b.useCallback(()=>{const I=Se.current;if(!I)return null;const A=io.current,W=U.lastCheckpointId??(A==null?void 0:A.lastCheckpointId)??null,K=U.lastCheckpointNs??(A==null?void 0:A.lastCheckpointNs)??null,fe={};return W&&(fe.checkpointId=W),K&&(fe.checkpointNs=K),{threadId:I,checkpointId:W,checkpointNs:K,command:{kind:"resume",value:fe}}},[U.lastCheckpointId,U.lastCheckpointNs]),lt=b.useCallback(I=>{const A=fn.current;if(A.timer!==null)return;if(A.attempts>=ex){Dt("error");return}A.attempts+=1,A.reason=I;const W=Math.min(tx*Math.pow(2,A.attempts-1),nx);Dt("reconnecting"),A.timer=window.setTimeout(()=>{A.timer=null,A.reason=null;const K=Ie();if(!K){Dt("error");return}Z(K.threadId??void 0),de(K)},W)},[Ie,Z,Dt,de]),Je=b.useCallback(I=>{var A;if(io.current=I,I.manualStop||I.reason==="complete"){se(),fn.current.attempts=0,Dt("idle");return}if(I.error&&(I.error.includes("token")||I.error.includes("401")||I.error.includes("unauthorized")||I.error.includes("Unauthorized")||I.error.includes("TOKEN_EXPIRED")||I.error.includes("auth_error"))){console.error("[ChatSessionProvider] Auth error detected:",I.error);try{a==null||a(I.error)}catch(K){console.error("[ChatSessionProvider] Error in onAuthError handler:",K)}return}if(I.reason==="error"||I.reason==="aborted"){if((A=I.error)!=null&&A.includes("Stream idle timeout")){console.warn("[ChatSessionProvider] Idle timeout - not scheduling resume (watchdog is generous)");return}lt(`closed:${I.reason}`)}},[se,lt,Dt,a]),it=b.useCallback(I=>{console.warn("[ChatSessionProvider] Stream connection error:",I),lt("connection-error")},[lt]),Bt=b.useCallback(I=>{ao.current=Date.now(),Dt(A=>A==="reconnecting"?"connected":A)},[Dt]);Lr.current=Je,Fr.current=it,N.current=Bt,b.useEffect(()=>()=>{se()},[se]);const sn=b.useCallback(()=>{se(),fn.current.attempts=0,Dt("idle"),Fn()},[se,Dt,Fn]);b.useEffect(()=>{Me.current=hn},[hn]),b.useEffect(()=>{if(!Cr())return;Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null);const I=S.map(W=>`${W.threadId}:${W.updatedAt??""}:${W.messageCount??""}`).join("|");if(S.length===0){try{oa(w)}catch{}xt.current="";return}if(I===xt.current)return;const A=()=>{try{const W=S.slice(0,aa);ca(w,W),xt.current=I}catch{}finally{Le.current=null}};return Le.current=window.setTimeout(()=>{ru(A),Le.current=null},ds),()=>{Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null)}},[S,Ce]),b.useEffect(()=>{var K;const I=c.getAuthToken();$n(I);const A=fe=>{const le=la(h,fe);St.current!==le&&(St.current=le,Ot.current=!1),C(le);const ht=ua(le);b.startTransition(()=>{k(hs(ht))}),fe&&!Ot.current&&(Ot.current=!0)};A(I);const W=(K=c.onTokenChange)==null?void 0:K.call(c,fe=>{fe!==I&&($n(fe),x(),nt.current.clear(),yt.current.clear(),A(fe))});return()=>{W==null||W()}},[c,h,$n,x]);const Xn=b.useCallback(async I=>{var K;const A=`Thread ${(K=crypto.randomUUID)==null?void 0:K.call(crypto)}`,W={threadId:A,title:I||"New Chat",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:0};k(fe=>({byId:{...fe.byId,[A]:W},order:[A,...fe.order]})),j(A);try{const fe=await c.createThread(I),le=typeof fe=="string"?fe:fe.threadId;return k(ht=>{const bt=ht.byId[A];if(!bt)return ht;const Be={...ht.byId};delete Be[A],Be[le]={...bt,threadId:le};const kt=ht.order.map(Ht=>Ht===A?le:Ht);return{byId:Be,order:kt}}),j(le),setTimeout(()=>ct(),10),O(null),le}catch(fe){throw k(le=>{if(!le.byId[A])return le;const ht={...le.byId};delete ht[A];const bt=le.order.filter(Be=>Be!==A);return{byId:ht,order:bt}}),j(null),O(String(fe)),fe}},[c,ct]),Ko=b.useCallback(async I=>{try{await c.deleteThread(I);let A=null;k(W=>{if(!W.byId[I])return W;const K={...W.byId};delete K[I];const fe=W.order.filter(ht=>ht!==I),le={byId:K,order:fe};return A=da(le),le}),A&&Ce(A,{immediate:!0}),Re(I),Se.current===I&&(Xe.current=I,j(null),Se.current=null,tt.current=null,At()),await ct(),O(null)}catch(A){throw O(String(A)),A}},[c,At,Re,ct,Ce]),_i=b.useCallback(async(I,A)=>{try{await c.updateThread(I,A),k(W=>{const K=W.byId[I];return K?{byId:{...W.byId,[I]:{...K,title:A}},order:W.order}:W}),O(null)}catch(W){throw await ct(),O(String(W)),W}},[c,ct]),Nn=b.useCallback(async(I,A,W,K=!1)=>{await ve(async()=>{if(Xe.current===I&&!K){Xe.current=null;return}if(et.current===I&&!K)return;j(Wt=>Wt===I?Wt:I),Se.current=I;const ht=su(I,A??null,W??null),bt=yt.current.get(ht),Be=!K&&!A&&!W&&bt&&Date.now()-bt.timestamp<Qy,kt=!K&&!A&&!W;let Ht=!1;if(kt){const Wt=Ke.current.get(I);if(Wt)He(Wt),Ht=!0;else{const jt=m(I);jt&&(Ke.current.set(I,jt),He(jt),Ht=!0)}}const pn=K||!Ht||!!A||!!W,Jn=async Wt=>{Wt&&z(!0),et.current=I;try{const jt=await Te({threadId:I,checkpointId:A,checkpointNs:W},{force:K}),{latest:or,checkpoints:$r,snapshots:lo}=as(jt.payload);b.startTransition(()=>{qe(or,"replace",I),Gt(I,$r,"replace"),Yt(I,lo,"replace"),R(null)}),jt.usedHistoryApi||ae(I).then(An=>{Xt(I,An)}).catch(An=>{console.warn("[ChatSessionProvider] Failed to refresh checkpoint summaries:",An)})}catch(jt){if(Y(jt))try{const or=await ae(I),$r=Xt(I,or);if(Q(!1),ue(null),ce(void 0),te(void 0),q(void 0),$r){R("History request timed out. Select a checkpoint to load manually.");return}}catch(or){console.warn("[ChatSessionProvider] Failed to fetch checkpoint summaries after timeout:",or)}throw(!Ht||K||Wt)&&(i==null||i(String(jt))),R(String(jt)),jt}finally{et.current=null,Wt&&z(!1)}};pn?await Jn(!0):kt&&Ht&&!Be&&Jn(!1).catch(Wt=>{console.warn("[ChatSessionProvider] Background refresh failed:",Wt)})},`loadThread-${I}`)},[He,Xt,qe,ve,ae,Te,Y,i,Gt,Yt]),ji=b.useCallback(async()=>{await ve(async()=>{const I=Se.current;I&&Re(I),Xe.current=null,j(null),Se.current=null,tt.current=null,At(),te(void 0),q(void 0),ce(void 0),ft();try{localStorage.removeItem("lastThreadId")}catch(A){console.warn("[ChatSessionProvider] Failed to clear lastThreadId:",A)}},"clearCurrentThread")},[At,Re,ve,ft]),Um=b.useCallback(async(I,A)=>{const W=Se.current;if(!W)throw new Error("No active thread");const K=Wr(I,A??null),fe=Mt(W,K);if(fe){await ve(async()=>{qe(fe,"replace",W,{persist:!1})},`navigateToCheckpoint-${W}-${K}`);return}await Nn(W,I,A??void 0,!0)},[qe,ve,Mt,Nn]),Wm=b.useCallback(async()=>{if(!Se.current)throw new Error("No active thread");await Nn(Se.current,void 0,void 0,!0)},[Nn]),Vm=b.useCallback(async()=>{if(!Se.current)throw new Error("No active thread");if(ye||!ne)return;const I=J;if(I){je(!0);try{const A=Se.current,W=await Te({threadId:A,checkpointId:I??ke??null,checkpointNs:ie??L??null}),{latest:K,checkpoints:fe,snapshots:le}=as(W.payload),ht=Ve(A);let bt=fe.length>0;if(bt&&ht&&ht.size>0&&(bt=fe.some(Be=>{if(!(Be!=null&&Be.checkpointId))return!1;const kt=Wr(Be.checkpointId,Be.checkpointNs??null);return!ht.has(kt)})),!bt){ue(null),ce(void 0),Q(!1),R(null);return}if(qe(K,"prepend",A??void 0),A&&(Gt(A,fe,"prepend"),Yt(A,le,"prepend"),!W.usedHistoryApi))try{const Be=await ae(A);Xt(A,Be)}catch(Be){console.warn("[ChatSessionProvider] Failed to refresh checkpoint summaries during prepend:",Be)}R(null)}catch(A){throw R(String(A)),A}finally{je(!1)}}},[qe,Te,Ve,ne,ke,L,ie,J,ae,Xt,ye,Gt,Yt]),Km=b.useCallback(I=>{if(I!=null&&I.threadId){if(I.checkpointId){const A=Wr(I.checkpointId,I.checkpointNs??null),W=un({...I,interrupt:I.interrupt??null},{cloneMessages:!0});Yt(I.threadId,{[A]:W},"prepend")}qe(I,"replace",I.threadId)}},[qe,Yt]),qo=b.useCallback(async(I,A)=>{var zr;const W=Se.current,K=(I==null?void 0:I.text)??"",fe=(I==null?void 0:I.attachments)??[],le=fe.length?fe:(A==null?void 0:A.attachments)??[],ht=I==null?void 0:I.messageAdditionalKwargs,bt={...(A==null?void 0:A.payloadExtras)??{},...(I==null?void 0:I.payload)??{}};if(!W&&!Object.keys(bt).length&&le.length===0&&!K.trim()){console.warn("[ChatSessionProvider] Nothing to submit - skipping");return}!W&&!bt.messages&&console.warn("[ChatSessionProvider] No thread ID - message will create new thread");const{contentParts:Be,filesInfo:kt}=await Iy(c,le),Ht=[...Be];K&&K.trim()&&Ht.push({type:"text",text:K.trim()});const pn=!!W,Jn=pn?(A==null?void 0:A.checkpointId)??U.lastCheckpointId??void 0:void 0,Wt=pn?(A==null?void 0:A.checkpointNs)??U.lastCheckpointNs??void 0:void 0,jt={id:((zr=crypto.randomUUID)==null?void 0:zr.call(crypto))||`user-${Date.now()}`,role:"user",content:Ht,createdAt:new Date().toISOString(),...Jn!=null?{checkpointId:Jn}:{},...Wt!=null?{checkpointNs:Wt}:{}};ht&&Object.keys(ht).length&&(jt.additionalKwargs={...jt.additionalKwargs??{},...ht}),Ht.length>0&&Pe(jt);const or={...jt,content:Ht},$r=le.length>0,lo={messages:Ht.length>0?[or]:[],files_info:kt,...o&&$r&&s?{active_agent:s}:{},...bt},An={threadId:W??null,payload:lo,checkpointId:Jn??null,checkpointNs:Wt??null,nodeFilter:(A==null?void 0:A.nodeFilter)??null,config:A==null?void 0:A.config,command:(A==null?void 0:A.command)??null};An.threadId||delete An.threadId,An.command||delete An.command,de(An,{onError:xr=>{console.warn("[ChatSessionProvider] Stream error:",xr)},onOpen:({threadId:xr})=>{!Se.current&&xr&&(U.messages.length<=1&&(Xe.current=xr),j(xr))},onGap:gt})},[c,o,s,gt,U.lastCheckpointId,U.lastCheckpointNs,U.messages.length,Pe,de]),qm=b.useCallback(async(I,A,W)=>{if(!Se.current)throw new Error("No active thread to handle interrupt");const fe=A?W??!0:!1;try{try{We({type:"interrupt_response",payload:{interruptId:I}})}catch(le){console.warn("[ChatSessionProvider] optimistic interrupt_response dispatch failed:",le)}await qo({payload:{}},{checkpointId:U.lastCheckpointId??void 0,checkpointNs:U.lastCheckpointNs??void 0,command:{kind:"resume",value:fe}}),$(null)}catch(le){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${I}:`,le),le}},[We,U.lastCheckpointId,U.lastCheckpointNs,qo]);b.useEffect(()=>{if(l==null||l(E),E)try{localStorage.setItem("lastThreadId",E)}catch(I){console.warn("[ChatSessionProvider] Failed to persist lastThreadId:",I)}},[E,l]),b.useEffect(()=>((async()=>{try{if(ct().catch(A=>{console.error("[ChatSessionProvider] Failed to refresh threads (background):",A),i==null||i(String(A))}),!r&&!t)try{const A=localStorage.getItem("lastThreadId");A&&(j(A),n&&await Nn(A))}catch(A){console.warn("[ChatSessionProvider] Failed to restore last thread:",A)}else t&&n&&await Nn(t)}catch(A){console.error("[ChatSessionProvider] Initialization failed:",A),i==null||i(String(A))}})(),()=>{}),[]),b.useEffect(()=>{const I=Se.current;if(!I||tt.current!==I)return;U.messages.length&&U.messages[U.messages.length-1];const A=un({checkpointId:U.lastCheckpointId??null,checkpointNs:U.lastCheckpointNs??null,messages:U.messages.slice(),nextCursor:J??null,nextCursorNs:ie??null,interrupt:U.pendingInterrupt??V??null}),W=Ke.current.get(I),K=W==null?void 0:W.snapshot,fe=!K||K.messages.length!==A.messages.length||K.messages.some((Be,kt)=>{var Ht;return(Be==null?void 0:Be.id)!==((Ht=A.messages[kt])==null?void 0:Ht.id)}),le=((K==null?void 0:K.checkpointId)??null)!==A.checkpointId||((K==null?void 0:K.checkpointNs)??null)!==A.checkpointNs,ht=((K==null?void 0:K.nextCursor)??null)!==A.nextCursor||((K==null?void 0:K.nextCursorNs)??null)!==A.nextCursorNs,bt=!ou((K==null?void 0:K.interrupt)??null,A.interrupt??null);if(fe||le||ht||bt){const Be={threadId:I,snapshot:A};Ke.current.set(I,Be),Ut.current&&window.clearTimeout(Ut.current),Ut.current=window.setTimeout(()=>{try{g(Be,100)}catch(kt){console.warn("[ChatSessionProvider] Failed to persist thread payload:",kt)}},ds)}},[J,ie,U.lastCheckpointId,U.lastCheckpointNs,U.messages,U.pendingInterrupt,V,g]);const hT=b.useMemo(()=>({threads:S,currentThreadId:E,setCurrentThreadId:j,isLoading:_,error:B,actions:{createThread:Xn,deleteThread:Ko,renameThread:_i,refreshThreads:()=>ct()},persistThreadsCache:Ge,hydrateFromCache:F}),[S,E,_,B,Xn,Ko,_i,ct,Ge,F,j]),pT=b.useMemo(()=>{const I=U.lastBranch??null,A=U.assemblingId??null,W=I||A?{branchLabel:(I==null?void 0:I.branchLabel)??null,lastBranch:I,assemblingMessageId:A}:null;return{threadId:E,messages:U.messages,interrupt:V,checkpoint:{id:U.lastCheckpointId??null,namespace:U.lastCheckpointNs??null},checkpoints:Nt,metadata:W,isLoading:D,isHistoryLoading:ye,error:H,hasMore:ne,loadOlder:Vm,seedFromSnapshot:Km,clearState:At,navigateToCheckpoint:Um,returnToLatest:Wm,loadThread:Nn,clearThread:ji,respondToInterrupt:qm}},[ji,At,E,V,ne,ye,D,Vm,Nn,U.assemblingId,U.lastBranch,U.lastCheckpointId,U.lastCheckpointNs,U.messages,Um,qm,Wm,Km,H,Nt]),mT=b.useMemo(()=>({isStreaming:hn,error:zt,connectionState:Ln,submit:qo,send:qo,stop:sn,setAuthToken:$n}),[Ln,hn,zt,sn,qo,$n]);return u.jsx(wx.Provider,{value:!0,children:u.jsx(uu.Provider,{value:mT,children:u.jsx(lu.Provider,{value:hT,children:u.jsx(cu.Provider,{value:pT,children:e})})})})}function ps(){const e=b.useContext(lu);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function ms(){const e=b.useContext(cu);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function du(){const e=b.useContext(uu);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function gs({children:e,apiConfig:t,initialThreadId:n=null,autoLoadInitial:r=!0,disableAutoRestore:o=!1,enableFileAgentRouting:s=!1,fileAgentId:i="invoice_reader",onError:a,onAuthError:l,onThreadChange:c}){return u.jsx(Ty,{apiConfig:t,children:u.jsx(bx,{initialThreadId:n,autoLoadInitial:r,disableAutoRestore:o,enableFileAgentRouting:s,fileAgentId:i,onError:a,onAuthError:l,onThreadChange:c,children:e})})}function oe(...e){return Jm.twMerge(Xm.clsx(e))}const Sx=Go.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),ut=v.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?vr.Slot:"button";return u.jsx(i,{className:oe(Sx({variant:t,size:n,className:e})),ref:s,...o})});ut.displayName="Button";const fu=v.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{className:oe("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));fu.displayName="Textarea";function hu({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=2e4,value:i,onValueChange:a,onSend:l,onCancelEdit:c,onStop:d,className:f="",textareaClassName:h="",allowEmptySend:p=!1}){const m=i!==void 0,[g,y]=b.useState(e),x=(m?i:g)??"",[w,C]=b.useTransition(),T=b.useRef(null),k=b.useRef(0),S=b.useRef(null);b.useEffect(()=>{m||(y(e??""),S.current=null,T.current&&(T.current.style.height="auto",T.current.style.height=`${T.current.scrollHeight}px`))},[e,t,m]);const E=b.useCallback(()=>{const H=T.current;H&&(H.style.height="auto",H.style.height=`${H.scrollHeight}px`)},[]);b.useEffect(()=>{E()},[E,x]);const j=b.useCallback((H,{fromUser:R})=>{m||y(H),R&&(a==null||a(H))},[m,a]),_=b.useCallback(async H=>{H&&H.preventDefault();const R=(x??"").trim();if(!R&&!p)return;const V=++k.current;S.current={id:V,shouldClear:!0},C(()=>{var $,F,ne;try{const Q=l(R);Q&&typeof Q.then=="function"?Q.then(()=>{var ye,je;((ye=S.current)==null?void 0:ye.id)===V&&S.current.shouldClear&&(m||(y(""),T.current&&(T.current.style.height="auto"),a==null||a(""))),((je=S.current)==null?void 0:je.id)===V&&(S.current=null)}).catch(()=>{var ye;((ye=S.current)==null?void 0:ye.id)===V&&(S.current=null)}):((($=S.current)==null?void 0:$.id)===V&&S.current.shouldClear&&(m||(y(""),T.current&&(T.current.style.height="auto"),a==null||a(""))),((F=S.current)==null?void 0:F.id)===V&&(S.current=null))}catch{((ne=S.current)==null?void 0:ne.id)===V&&(S.current=null)}})},[x,l,p,m,a]),P=b.useCallback(H=>{const R=H.target.value;j(R,{fromUser:!0}),S.current&&(S.current.shouldClear=!1),T.current&&(T.current.style.height="auto",T.current.style.height=`${T.current.scrollHeight}px`)},[j]),D=b.useCallback(H=>{H.key==="Enter"&&!H.shiftKey?(H.preventDefault(),_()):H.key==="Escape"&&t&&(H.preventDefault(),c==null||c())},[_,t,c]),O=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${t?"border-[hsl(var(--ring))] bg-[hsl(var(--card))] text-[hsl(var(--card-foreground))] dark:bg-[hsl(var(--card))] dark:text-[hsl(var(--card-foreground))]":""} ${h}`;return u.jsx("form",{onSubmit:H=>void _(H),className:`w-full ${f}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(fu,{ref:T,value:x,onChange:P,onKeyDown:D,placeholder:t?"Edit your message...":n,className:O,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx(ut,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:u.jsx(he.Square,{size:16})}):u.jsx(ut,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!x.trim()&&!p||w,children:u.jsx(he.Send,{size:16})})})]})})}const Cx=b.memo(hu);function ge(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function pu(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function fa(...e){return t=>{let n=!1;const r=e.map(o=>{const s=pu(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():pu(e[o],null)}}}}function Ze(...e){return v.useCallback(fa(...e),e)}function kx(e,t){const n=v.createContext(t),r=s=>{const{children:i,...a}=s,l=v.useMemo(()=>a,Object.values(a));return u.jsx(n.Provider,{value:l,children:i})};r.displayName=e+"Provider";function o(s){const i=v.useContext(n);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function Qn(e,t=[]){let n=[];function r(s,i){const a=v.createContext(i),l=n.length;n=[...n,i];const c=f=>{var x;const{scope:h,children:p,...m}=f,g=((x=h==null?void 0:h[e])==null?void 0:x[l])||a,y=v.useMemo(()=>m,Object.values(m));return u.jsx(g.Provider,{value:y,children:p})};c.displayName=s+"Provider";function d(f,h){var g;const p=((g=h==null?void 0:h[e])==null?void 0:g[l])||a,m=v.useContext(p);if(m)return m;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>v.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return v.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,Tx(o,...t)]}function Tx(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const f=l(s)[`__scope${c}`];return{...a,...f}},{});return v.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var Kt=globalThis!=null&&globalThis.document?v.useLayoutEffect:()=>{},Ex=v[" useInsertionEffect ".trim().toString()]||Kt;function Vr({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=Ix({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const d=v.useRef(e!==void 0);v.useEffect(()=>{const f=d.current;f!==a&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,r])}const c=v.useCallback(d=>{var f;if(a){const h=Nx(d)?d(e):d;h!==e&&((f=i.current)==null||f.call(i,h))}else s(d)},[a,e,s,i]);return[l,c]}function Ix({defaultProp:e,onChange:t}){const[n,r]=v.useState(e),o=v.useRef(n),s=v.useRef(t);return Ex(()=>{s.current=t},[t]),v.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function Nx(e){return typeof e=="function"}var Ax=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],De=Ax.reduce((e,t)=>{const n=vr.createSlot(`Primitive.${t}`),r=v.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function mu(e,t){e&&Yo.flushSync(()=>e.dispatchEvent(t))}function ha(e){const t=e+"CollectionProvider",[n,r]=Qn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=g=>{const{scope:y,children:x}=g,w=b.useRef(null),C=b.useRef(new Map).current;return u.jsx(o,{scope:y,itemMap:C,collectionRef:w,children:x})};i.displayName=t;const a=e+"CollectionSlot",l=vr.createSlot(a),c=b.forwardRef((g,y)=>{const{scope:x,children:w}=g,C=s(a,x),T=Ze(y,C.collectionRef);return u.jsx(l,{ref:T,children:w})});c.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",h=vr.createSlot(d),p=b.forwardRef((g,y)=>{const{scope:x,children:w,...C}=g,T=b.useRef(null),k=Ze(y,T),S=s(d,x);return b.useEffect(()=>(S.itemMap.set(T,{ref:T,...C}),()=>void S.itemMap.delete(T))),u.jsx(h,{[f]:"",ref:k,children:w})});p.displayName=d;function m(g){const y=s(e+"CollectionConsumer",g);return b.useCallback(()=>{const w=y.collectionRef.current;if(!w)return[];const C=Array.from(w.querySelectorAll(`[${f}]`));return Array.from(y.itemMap.values()).sort((S,E)=>C.indexOf(S.ref.current)-C.indexOf(E.ref.current))},[y.collectionRef,y.itemMap])}return[{Provider:i,Slot:c,ItemSlot:p},m,r]}var _x=v.createContext(void 0);function ys(e){const t=v.useContext(_x);return e||t||"ltr"}function qt(e){const t=v.useRef(e);return v.useEffect(()=>{t.current=e}),v.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function jx(e,t=globalThis==null?void 0:globalThis.document){const n=qt(e);v.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var Px="DismissableLayer",pa="dismissableLayer.update",Rx="dismissableLayer.pointerDownOutside",Ox="dismissableLayer.focusOutside",gu,yu=v.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),xs=v.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=v.useContext(yu),[d,f]=v.useState(null),h=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=v.useState({}),m=Ze(t,E=>f(E)),g=Array.from(c.layers),[y]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),x=g.indexOf(y),w=d?g.indexOf(d):-1,C=c.layersWithOutsidePointerEventsDisabled.size>0,T=w>=x,k=Lx(E=>{const j=E.target,_=[...c.branches].some(P=>P.contains(j));!T||_||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},h),S=Fx(E=>{const j=E.target;[...c.branches].some(P=>P.contains(j))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},h);return jx(E=>{w===c.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},h),v.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(gu=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),xu(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=gu)}},[d,h,n,c]),v.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),xu())},[d,c]),v.useEffect(()=>{const E=()=>p({});return document.addEventListener(pa,E),()=>document.removeEventListener(pa,E)},[]),u.jsx(De.div,{...l,ref:m,style:{pointerEvents:C?T?"auto":"none":void 0,...e.style},onFocusCapture:ge(e.onFocusCapture,S.onFocusCapture),onBlurCapture:ge(e.onBlurCapture,S.onBlurCapture),onPointerDownCapture:ge(e.onPointerDownCapture,k.onPointerDownCapture)})});xs.displayName=Px;var Mx="DismissableLayerBranch",Dx=v.forwardRef((e,t)=>{const n=v.useContext(yu),r=v.useRef(null),o=Ze(t,r);return v.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(De.div,{...e,ref:o})});Dx.displayName=Mx;function Lx(e,t=globalThis==null?void 0:globalThis.document){const n=qt(e),r=v.useRef(!1),o=v.useRef(()=>{});return v.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){vu(Rx,n,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function Fx(e,t=globalThis==null?void 0:globalThis.document){const n=qt(e),r=v.useRef(!1);return v.useEffect(()=>{const o=s=>{s.target&&!r.current&&vu(Ox,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function xu(){const e=new CustomEvent(pa);document.dispatchEvent(e)}function vu(e,t,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?mu(o,s):o.dispatchEvent(s)}var ma=0;function ga(){v.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??wu()),document.body.insertAdjacentElement("beforeend",e[1]??wu()),ma++,()=>{ma===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),ma--}},[])}function wu(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var ya="focusScope.autoFocusOnMount",xa="focusScope.autoFocusOnUnmount",bu={bubbles:!1,cancelable:!0},$x="FocusScope",vs=v.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=v.useState(null),c=qt(o),d=qt(s),f=v.useRef(null),h=Ze(t,g=>l(g)),p=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(r){let g=function(C){if(p.paused||!a)return;const T=C.target;a.contains(T)?f.current=T:ir(f.current,{select:!0})},y=function(C){if(p.paused||!a)return;const T=C.relatedTarget;T!==null&&(a.contains(T)||ir(f.current,{select:!0}))},x=function(C){if(document.activeElement===document.body)for(const k of C)k.removedNodes.length>0&&ir(a)};document.addEventListener("focusin",g),document.addEventListener("focusout",y);const w=new MutationObserver(x);return a&&w.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",y),w.disconnect()}}},[r,a,p.paused]),v.useEffect(()=>{if(a){ku.add(p);const g=document.activeElement;if(!a.contains(g)){const x=new CustomEvent(ya,bu);a.addEventListener(ya,c),a.dispatchEvent(x),x.defaultPrevented||(zx(Vx(Su(a)),{select:!0}),document.activeElement===g&&ir(a))}return()=>{a.removeEventListener(ya,c),setTimeout(()=>{const x=new CustomEvent(xa,bu);a.addEventListener(xa,d),a.dispatchEvent(x),x.defaultPrevented||ir(g??document.body,{select:!0}),a.removeEventListener(xa,d),ku.remove(p)},0)}}},[a,c,d,p]);const m=v.useCallback(g=>{if(!n&&!r||p.paused)return;const y=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,x=document.activeElement;if(y&&x){const w=g.currentTarget,[C,T]=Bx(w);C&&T?!g.shiftKey&&x===T?(g.preventDefault(),n&&ir(C,{select:!0})):g.shiftKey&&x===C&&(g.preventDefault(),n&&ir(T,{select:!0})):x===w&&g.preventDefault()}},[n,r,p.paused]);return u.jsx(De.div,{tabIndex:-1,...i,ref:h,onKeyDown:m})});vs.displayName=$x;function zx(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(ir(r,{select:t}),document.activeElement!==n)return}function Bx(e){const t=Su(e),n=Cu(t,e),r=Cu(t.reverse(),e);return[n,r]}function Su(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Cu(e,t){for(const n of e)if(!Hx(n,{upTo:t}))return n}function Hx(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function Ux(e){return e instanceof HTMLInputElement&&"select"in e}function ir(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Ux(e)&&t&&e.select()}}var ku=Wx();function Wx(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Tu(e,t),e.unshift(t)},remove(t){var n;e=Tu(e,t),(n=e[0])==null||n.resume()}}}function Tu(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function Vx(e){return e.filter(t=>t.tagName!=="A")}var Kx=v[" useId ".trim().toString()]||(()=>{}),qx=0;function er(e){const[t,n]=v.useState(Kx());return Kt(()=>{n(r=>r??String(qx++))},[e]),t?`radix-${t}`:""}const Gx=["top","right","bottom","left"],ar=Math.min,mn=Math.max,ws=Math.round,bs=Math.floor,Bn=e=>({x:e,y:e}),Yx={left:"right",right:"left",bottom:"top",top:"bottom"},Xx={start:"end",end:"start"};function va(e,t,n){return mn(e,ar(t,n))}function tr(e,t){return typeof e=="function"?e(t):e}function nr(e){return e.split("-")[0]}function Kr(e){return e.split("-")[1]}function wa(e){return e==="x"?"y":"x"}function ba(e){return e==="y"?"height":"width"}const Jx=new Set(["top","bottom"]);function Hn(e){return Jx.has(nr(e))?"y":"x"}function Sa(e){return wa(Hn(e))}function Zx(e,t,n){n===void 0&&(n=!1);const r=Kr(e),o=Sa(e),s=ba(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=Ss(i)),[i,Ss(i)]}function Qx(e){const t=Ss(e);return[Ca(e),t,Ca(t)]}function Ca(e){return e.replace(/start|end/g,t=>Xx[t])}const Eu=["left","right"],Iu=["right","left"],ev=["top","bottom"],tv=["bottom","top"];function nv(e,t,n){switch(e){case"top":case"bottom":return n?t?Iu:Eu:t?Eu:Iu;case"left":case"right":return t?ev:tv;default:return[]}}function rv(e,t,n,r){const o=Kr(e);let s=nv(nr(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(Ca)))),s}function Ss(e){return e.replace(/left|right|bottom|top/g,t=>Yx[t])}function ov(e){return{top:0,right:0,bottom:0,left:0,...e}}function Nu(e){return typeof e!="number"?ov(e):{top:e,right:e,bottom:e,left:e}}function Cs(e){const{x:t,y:n,width:r,height:o}=e;return{width:r,height:o,top:n,left:t,right:t+r,bottom:n+o,x:t,y:n}}function Au(e,t,n){let{reference:r,floating:o}=e;const s=Hn(t),i=Sa(t),a=ba(i),l=nr(t),c=s==="y",d=r.x+r.width/2-o.width/2,f=r.y+r.height/2-o.height/2,h=r[a]/2-o[a]/2;let p;switch(l){case"top":p={x:d,y:r.y-o.height};break;case"bottom":p={x:d,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:f};break;case"left":p={x:r.x-o.width,y:f};break;default:p={x:r.x,y:r.y}}switch(Kr(t)){case"start":p[i]-=h*(n&&c?-1:1);break;case"end":p[i]+=h*(n&&c?-1:1);break}return p}const sv=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,a=s.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(t));let c=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:f}=Au(c,r,l),h=r,p={},m=0;for(let g=0;g<a.length;g++){const{name:y,fn:x}=a[g],{x:w,y:C,data:T,reset:k}=await x({x:d,y:f,initialPlacement:r,placement:h,strategy:o,middlewareData:p,rects:c,platform:i,elements:{reference:e,floating:t}});d=w??d,f=C??f,p={...p,[y]:{...p[y],...T}},k&&m<=50&&(m++,typeof k=="object"&&(k.placement&&(h=k.placement),k.rects&&(c=k.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):k.rects),{x:d,y:f}=Au(c,h,l)),g=-1)}return{x:d,y:f,placement:h,strategy:o,middlewareData:p}};async function xo(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:f="floating",altBoundary:h=!1,padding:p=0}=tr(t,e),m=Nu(p),y=a[h?f==="floating"?"reference":"floating":f],x=Cs(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(y)))==null||n?y:y.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:d,strategy:l})),w=f==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.reference,C=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),T=await(s.isElement==null?void 0:s.isElement(C))?await(s.getScale==null?void 0:s.getScale(C))||{x:1,y:1}:{x:1,y:1},k=Cs(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:w,offsetParent:C,strategy:l}):w);return{top:(x.top-k.top+m.top)/T.y,bottom:(k.bottom-x.bottom+m.bottom)/T.y,left:(x.left-k.left+m.left)/T.x,right:(k.right-x.right+m.right)/T.x}}const iv=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:s,platform:i,elements:a,middlewareData:l}=t,{element:c,padding:d=0}=tr(e,t)||{};if(c==null)return{};const f=Nu(d),h={x:n,y:r},p=Sa(o),m=ba(p),g=await i.getDimensions(c),y=p==="y",x=y?"top":"left",w=y?"bottom":"right",C=y?"clientHeight":"clientWidth",T=s.reference[m]+s.reference[p]-h[p]-s.floating[m],k=h[p]-s.reference[p],S=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let E=S?S[C]:0;(!E||!await(i.isElement==null?void 0:i.isElement(S)))&&(E=a.floating[C]||s.floating[m]);const j=T/2-k/2,_=E/2-g[m]/2-1,P=ar(f[x],_),D=ar(f[w],_),z=P,B=E-g[m]-D,O=E/2-g[m]/2+j,H=va(z,O,B),R=!l.arrow&&Kr(o)!=null&&O!==H&&s.reference[m]/2-(O<z?P:D)-g[m]/2<0,V=R?O<z?O-z:O-B:0;return{[p]:h[p]+V,data:{[p]:H,centerOffset:O-H-V,...R&&{alignmentOffset:V}},reset:R}}}),av=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:s,rects:i,initialPlacement:a,platform:l,elements:c}=t,{mainAxis:d=!0,crossAxis:f=!0,fallbackPlacements:h,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:m="none",flipAlignment:g=!0,...y}=tr(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const x=nr(o),w=Hn(a),C=nr(a)===a,T=await(l.isRTL==null?void 0:l.isRTL(c.floating)),k=h||(C||!g?[Ss(a)]:Qx(a)),S=m!=="none";!h&&S&&k.push(...rv(a,g,m,T));const E=[a,...k],j=await xo(t,y),_=[];let P=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&_.push(j[x]),f){const O=Zx(o,i,T);_.push(j[O[0]],j[O[1]])}if(P=[...P,{placement:o,overflows:_}],!_.every(O=>O<=0)){var D,z;const O=(((D=s.flip)==null?void 0:D.index)||0)+1,H=E[O];if(H&&(!(f==="alignment"?w!==Hn(H):!1)||P.every($=>Hn($.placement)===w?$.overflows[0]>0:!0)))return{data:{index:O,overflows:P},reset:{placement:H}};let R=(z=P.filter(V=>V.overflows[0]<=0).sort((V,$)=>V.overflows[1]-$.overflows[1])[0])==null?void 0:z.placement;if(!R)switch(p){case"bestFit":{var B;const V=(B=P.filter($=>{if(S){const F=Hn($.placement);return F===w||F==="y"}return!0}).map($=>[$.placement,$.overflows.filter(F=>F>0).reduce((F,ne)=>F+ne,0)]).sort(($,F)=>$[1]-F[1])[0])==null?void 0:B[0];V&&(R=V);break}case"initialPlacement":R=a;break}if(o!==R)return{reset:{placement:R}}}return{}}}};function _u(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function ju(e){return Gx.some(t=>e[t]>=0)}const lv=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=tr(e,t);switch(r){case"referenceHidden":{const s=await xo(t,{...o,elementContext:"reference"}),i=_u(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:ju(i)}}}case"escaped":{const s=await xo(t,{...o,altBoundary:!0}),i=_u(s,n.floating);return{data:{escapedOffsets:i,escaped:ju(i)}}}default:return{}}}}},Pu=new Set(["left","top"]);async function cv(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=nr(n),a=Kr(n),l=Hn(n)==="y",c=Pu.has(i)?-1:1,d=s&&l?-1:1,f=tr(t,e);let{mainAxis:h,crossAxis:p,alignmentAxis:m}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof m=="number"&&(p=a==="end"?m*-1:m),l?{x:p*d,y:h*c}:{x:h*c,y:p*d}}const uv=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:s,placement:i,middlewareData:a}=t,l=await cv(t,e);return i===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:s+l.y,data:{...l,placement:i}}}}},dv=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:s=!0,crossAxis:i=!1,limiter:a={fn:y=>{let{x,y:w}=y;return{x,y:w}}},...l}=tr(e,t),c={x:n,y:r},d=await xo(t,l),f=Hn(nr(o)),h=wa(f);let p=c[h],m=c[f];if(s){const y=h==="y"?"top":"left",x=h==="y"?"bottom":"right",w=p+d[y],C=p-d[x];p=va(w,p,C)}if(i){const y=f==="y"?"top":"left",x=f==="y"?"bottom":"right",w=m+d[y],C=m-d[x];m=va(w,m,C)}const g=a.fn({...t,[h]:p,[f]:m});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[h]:s,[f]:i}}}}}},fv=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:s,middlewareData:i}=t,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=tr(e,t),d={x:n,y:r},f=Hn(o),h=wa(f);let p=d[h],m=d[f];const g=tr(a,t),y=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(l){const C=h==="y"?"height":"width",T=s.reference[h]-s.floating[C]+y.mainAxis,k=s.reference[h]+s.reference[C]-y.mainAxis;p<T?p=T:p>k&&(p=k)}if(c){var x,w;const C=h==="y"?"width":"height",T=Pu.has(nr(o)),k=s.reference[f]-s.floating[C]+(T&&((x=i.offset)==null?void 0:x[f])||0)+(T?0:y.crossAxis),S=s.reference[f]+s.reference[C]+(T?0:((w=i.offset)==null?void 0:w[f])||0)-(T?y.crossAxis:0);m<k?m=k:m>S&&(m=S)}return{[h]:p,[f]:m}}}},hv=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:s,platform:i,elements:a}=t,{apply:l=()=>{},...c}=tr(e,t),d=await xo(t,c),f=nr(o),h=Kr(o),p=Hn(o)==="y",{width:m,height:g}=s.floating;let y,x;f==="top"||f==="bottom"?(y=f,x=h===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(x=f,y=h==="end"?"top":"bottom");const w=g-d.top-d.bottom,C=m-d.left-d.right,T=ar(g-d[y],w),k=ar(m-d[x],C),S=!t.middlewareData.shift;let E=T,j=k;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(j=C),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(E=w),S&&!h){const P=mn(d.left,0),D=mn(d.right,0),z=mn(d.top,0),B=mn(d.bottom,0);p?j=m-2*(P!==0||D!==0?P+D:mn(d.left,d.right)):E=g-2*(z!==0||B!==0?z+B:mn(d.top,d.bottom))}await l({...t,availableWidth:j,availableHeight:E});const _=await i.getDimensions(a.floating);return m!==_.width||g!==_.height?{reset:{rects:!0}}:{}}}};function ks(){return typeof window<"u"}function qr(e){return Ru(e)?(e.nodeName||"").toLowerCase():"#document"}function gn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Un(e){var t;return(t=(Ru(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Ru(e){return ks()?e instanceof Node||e instanceof gn(e).Node:!1}function jn(e){return ks()?e instanceof Element||e instanceof gn(e).Element:!1}function Wn(e){return ks()?e instanceof HTMLElement||e instanceof gn(e).HTMLElement:!1}function Ou(e){return!ks()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof gn(e).ShadowRoot}const pv=new Set(["inline","contents"]);function vo(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Pn(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!pv.has(o)}const mv=new Set(["table","td","th"]);function gv(e){return mv.has(qr(e))}const yv=[":popover-open",":modal"];function Ts(e){return yv.some(t=>{try{return e.matches(t)}catch{return!1}})}const xv=["transform","translate","scale","rotate","perspective"],vv=["transform","translate","scale","rotate","perspective","filter"],wv=["paint","layout","strict","content"];function ka(e){const t=Ta(),n=jn(e)?Pn(e):e;return xv.some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||vv.some(r=>(n.willChange||"").includes(r))||wv.some(r=>(n.contain||"").includes(r))}function bv(e){let t=lr(e);for(;Wn(t)&&!Gr(t);){if(ka(t))return t;if(Ts(t))return null;t=lr(t)}return null}function Ta(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const Sv=new Set(["html","body","#document"]);function Gr(e){return Sv.has(qr(e))}function Pn(e){return gn(e).getComputedStyle(e)}function Es(e){return jn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function lr(e){if(qr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Ou(e)&&e.host||Un(e);return Ou(t)?t.host:t}function Mu(e){const t=lr(e);return Gr(t)?e.ownerDocument?e.ownerDocument.body:e.body:Wn(t)&&vo(t)?t:Mu(t)}function wo(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=Mu(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=gn(o);if(s){const a=Ea(i);return t.concat(i,i.visualViewport||[],vo(o)?o:[],a&&n?wo(a):[])}return t.concat(o,wo(o,[],n))}function Ea(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Du(e){const t=Pn(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Wn(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=ws(n)!==s||ws(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function Ia(e){return jn(e)?e:e.contextElement}function Yr(e){const t=Ia(e);if(!Wn(t))return Bn(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=Du(t);let i=(s?ws(n.width):n.width)/r,a=(s?ws(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const Cv=Bn(0);function Lu(e){const t=gn(e);return!Ta()||!t.visualViewport?Cv:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function kv(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==gn(e)?!1:t}function kr(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=Ia(e);let i=Bn(1);t&&(r?jn(r)&&(i=Yr(r)):i=Yr(e));const a=kv(s,n,r)?Lu(s):Bn(0);let l=(o.left+a.x)/i.x,c=(o.top+a.y)/i.y,d=o.width/i.x,f=o.height/i.y;if(s){const h=gn(s),p=r&&jn(r)?gn(r):r;let m=h,g=Ea(m);for(;g&&r&&p!==m;){const y=Yr(g),x=g.getBoundingClientRect(),w=Pn(g),C=x.left+(g.clientLeft+parseFloat(w.paddingLeft))*y.x,T=x.top+(g.clientTop+parseFloat(w.paddingTop))*y.y;l*=y.x,c*=y.y,d*=y.x,f*=y.y,l+=C,c+=T,m=gn(g),g=Ea(m)}}return Cs({width:d,height:f,x:l,y:c})}function Is(e,t){const n=Es(e).scrollLeft;return t?t.left+n:kr(Un(e)).left+n}function Fu(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Is(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function Tv(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=Un(r),a=t?Ts(t.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=Bn(1);const d=Bn(0),f=Wn(r);if((f||!f&&!s)&&((qr(r)!=="body"||vo(i))&&(l=Es(r)),Wn(r))){const p=kr(r);c=Yr(r),d.x=p.x+r.clientLeft,d.y=p.y+r.clientTop}const h=i&&!f&&!s?Fu(i,l):Bn(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+d.x+h.x,y:n.y*c.y-l.scrollTop*c.y+d.y+h.y}}function Ev(e){return Array.from(e.getClientRects())}function Iv(e){const t=Un(e),n=Es(e),r=e.ownerDocument.body,o=mn(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=mn(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+Is(e);const a=-n.scrollTop;return Pn(r).direction==="rtl"&&(i+=mn(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const $u=25;function Nv(e,t){const n=gn(e),r=Un(e),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,a=0,l=0;if(o){s=o.width,i=o.height;const d=Ta();(!d||d&&t==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const c=Is(r);if(c<=0){const d=r.ownerDocument,f=d.body,h=getComputedStyle(f),p=d.compatMode==="CSS1Compat"&&parseFloat(h.marginLeft)+parseFloat(h.marginRight)||0,m=Math.abs(r.clientWidth-f.clientWidth-p);m<=$u&&(s-=m)}else c<=$u&&(s+=c);return{width:s,height:i,x:a,y:l}}const Av=new Set(["absolute","fixed"]);function _v(e,t){const n=kr(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=Wn(e)?Yr(e):Bn(1),i=e.clientWidth*s.x,a=e.clientHeight*s.y,l=o*s.x,c=r*s.y;return{width:i,height:a,x:l,y:c}}function zu(e,t,n){let r;if(t==="viewport")r=Nv(e,n);else if(t==="document")r=Iv(Un(e));else if(jn(t))r=_v(t,n);else{const o=Lu(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return Cs(r)}function Bu(e,t){const n=lr(e);return n===t||!jn(n)||Gr(n)?!1:Pn(n).position==="fixed"||Bu(n,t)}function jv(e,t){const n=t.get(e);if(n)return n;let r=wo(e,[],!1).filter(a=>jn(a)&&qr(a)!=="body"),o=null;const s=Pn(e).position==="fixed";let i=s?lr(e):e;for(;jn(i)&&!Gr(i);){const a=Pn(i),l=ka(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&Av.has(o.position)||vo(i)&&!l&&Bu(e,i))?r=r.filter(d=>d!==i):o=a,i=lr(i)}return t.set(e,r),r}function Pv(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?Ts(t)?[]:jv(t,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,d)=>{const f=zu(t,d,o);return c.top=mn(f.top,c.top),c.right=ar(f.right,c.right),c.bottom=ar(f.bottom,c.bottom),c.left=mn(f.left,c.left),c},zu(t,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function Rv(e){const{width:t,height:n}=Du(e);return{width:t,height:n}}function Ov(e,t,n){const r=Wn(t),o=Un(t),s=n==="fixed",i=kr(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const l=Bn(0);function c(){l.x=Is(o)}if(r||!r&&!s)if((qr(t)!=="body"||vo(o))&&(a=Es(t)),r){const p=kr(t,!0,s,t);l.x=p.x+t.clientLeft,l.y=p.y+t.clientTop}else o&&c();s&&!r&&o&&c();const d=o&&!r&&!s?Fu(o,a):Bn(0),f=i.left+a.scrollLeft-l.x-d.x,h=i.top+a.scrollTop-l.y-d.y;return{x:f,y:h,width:i.width,height:i.height}}function Na(e){return Pn(e).position==="static"}function Hu(e,t){if(!Wn(e)||Pn(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Un(e)===n&&(n=n.ownerDocument.body),n}function Uu(e,t){const n=gn(e);if(Ts(e))return n;if(!Wn(e)){let o=lr(e);for(;o&&!Gr(o);){if(jn(o)&&!Na(o))return o;o=lr(o)}return n}let r=Hu(e,t);for(;r&&gv(r)&&Na(r);)r=Hu(r,t);return r&&Gr(r)&&Na(r)&&!ka(r)?n:r||bv(e)||n}const Mv=async function(e){const t=this.getOffsetParent||Uu,n=this.getDimensions,r=await n(e.floating);return{reference:Ov(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function Dv(e){return Pn(e).direction==="rtl"}const Lv={convertOffsetParentRelativeRectToViewportRelativeRect:Tv,getDocumentElement:Un,getClippingRect:Pv,getOffsetParent:Uu,getElementRects:Mv,getClientRects:Ev,getDimensions:Rv,getScale:Yr,isElement:jn,isRTL:Dv};function Wu(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Fv(e,t){let n=null,r;const o=Un(e);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function i(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),s();const c=e.getBoundingClientRect(),{left:d,top:f,width:h,height:p}=c;if(a||t(),!h||!p)return;const m=bs(f),g=bs(o.clientWidth-(d+h)),y=bs(o.clientHeight-(f+p)),x=bs(d),C={rootMargin:-m+"px "+-g+"px "+-y+"px "+-x+"px",threshold:mn(0,ar(1,l))||1};let T=!0;function k(S){const E=S[0].intersectionRatio;if(E!==l){if(!T)return i();E?i(!1,E):r=setTimeout(()=>{i(!1,1e-7)},1e3)}E===1&&!Wu(c,e.getBoundingClientRect())&&i(),T=!1}try{n=new IntersectionObserver(k,{...C,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,C)}n.observe(e)}return i(!0),s}function $v(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,c=Ia(e),d=o||s?[...c?wo(c):[],...wo(t)]:[];d.forEach(x=>{o&&x.addEventListener("scroll",n,{passive:!0}),s&&x.addEventListener("resize",n)});const f=c&&a?Fv(c,n):null;let h=-1,p=null;i&&(p=new ResizeObserver(x=>{let[w]=x;w&&w.target===c&&p&&(p.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var C;(C=p)==null||C.observe(t)})),n()}),c&&!l&&p.observe(c),p.observe(t));let m,g=l?kr(e):null;l&&y();function y(){const x=kr(e);g&&!Wu(g,x)&&n(),g=x,m=requestAnimationFrame(y)}return n(),()=>{var x;d.forEach(w=>{o&&w.removeEventListener("scroll",n),s&&w.removeEventListener("resize",n)}),f==null||f(),(x=p)==null||x.disconnect(),p=null,l&&cancelAnimationFrame(m)}}const zv=uv,Bv=dv,Hv=av,Uv=hv,Wv=lv,Vu=iv,Vv=fv,Kv=(e,t,n)=>{const r=new Map,o={platform:Lv,...n},s={...o.platform,_c:r};return sv(e,t,{...o,platform:s})};var qv=typeof document<"u",Gv=function(){},Ns=qv?b.useLayoutEffect:Gv;function As(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!As(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const s=o[r];if(!(s==="_owner"&&e.$$typeof)&&!As(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function Ku(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function qu(e,t){const n=Ku(e);return Math.round(t*n)/n}function Aa(e){const t=v.useRef(e);return Ns(()=>{t.current=e}),t}function Yv(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:s,floating:i}={},transform:a=!0,whileElementsMounted:l,open:c}=e,[d,f]=v.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[h,p]=v.useState(r);As(h,r)||p(r);const[m,g]=v.useState(null),[y,x]=v.useState(null),w=v.useCallback($=>{$!==S.current&&(S.current=$,g($))},[]),C=v.useCallback($=>{$!==E.current&&(E.current=$,x($))},[]),T=s||m,k=i||y,S=v.useRef(null),E=v.useRef(null),j=v.useRef(d),_=l!=null,P=Aa(l),D=Aa(o),z=Aa(c),B=v.useCallback(()=>{if(!S.current||!E.current)return;const $={placement:t,strategy:n,middleware:h};D.current&&($.platform=D.current),Kv(S.current,E.current,$).then(F=>{const ne={...F,isPositioned:z.current!==!1};O.current&&!As(j.current,ne)&&(j.current=ne,Yo.flushSync(()=>{f(ne)}))})},[h,t,n,D,z]);Ns(()=>{c===!1&&j.current.isPositioned&&(j.current.isPositioned=!1,f($=>({...$,isPositioned:!1})))},[c]);const O=v.useRef(!1);Ns(()=>(O.current=!0,()=>{O.current=!1}),[]),Ns(()=>{if(T&&(S.current=T),k&&(E.current=k),T&&k){if(P.current)return P.current(T,k,B);B()}},[T,k,B,P,_]);const H=v.useMemo(()=>({reference:S,floating:E,setReference:w,setFloating:C}),[w,C]),R=v.useMemo(()=>({reference:T,floating:k}),[T,k]),V=v.useMemo(()=>{const $={position:n,left:0,top:0};if(!R.floating)return $;const F=qu(R.floating,d.x),ne=qu(R.floating,d.y);return a?{...$,transform:"translate("+F+"px, "+ne+"px)",...Ku(R.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:F,top:ne}},[n,a,R.floating,d.x,d.y]);return v.useMemo(()=>({...d,update:B,refs:H,elements:R,floatingStyles:V}),[d,B,H,R,V])}const Xv=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Vu({element:r.current,padding:o}).fn(n):{}:r?Vu({element:r,padding:o}).fn(n):{}}}},Jv=(e,t)=>({...zv(e),options:[e,t]}),Zv=(e,t)=>({...Bv(e),options:[e,t]}),Qv=(e,t)=>({...Vv(e),options:[e,t]}),ew=(e,t)=>({...Hv(e),options:[e,t]}),tw=(e,t)=>({...Uv(e),options:[e,t]}),nw=(e,t)=>({...Wv(e),options:[e,t]}),rw=(e,t)=>({...Xv(e),options:[e,t]});var ow="Arrow",Gu=v.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return u.jsx(De.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:u.jsx("polygon",{points:"0,0 30,0 15,10"})})});Gu.displayName=ow;var sw=Gu;function Yu(e){const[t,n]=v.useState(void 0);return Kt(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let i,a;if("borderBoxSize"in s){const l=s.borderBoxSize,c=Array.isArray(l)?l[0]:l;i=c.inlineSize,a=c.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var _a="Popper",[Xu,_s]=Qn(_a),[iw,Ju]=Xu(_a),Zu=e=>{const{__scopePopper:t,children:n}=e,[r,o]=v.useState(null);return u.jsx(iw,{scope:t,anchor:r,onAnchorChange:o,children:n})};Zu.displayName=_a;var Qu="PopperAnchor",ed=v.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=Ju(Qu,n),i=v.useRef(null),a=Ze(t,i),l=v.useRef(null);return v.useEffect(()=>{const c=l.current;l.current=(r==null?void 0:r.current)||i.current,c!==l.current&&s.onAnchorChange(l.current)}),r?null:u.jsx(De.div,{...o,ref:a})});ed.displayName=Qu;var ja="PopperContent",[aw,lw]=Xu(ja),td=v.forwardRef((e,t)=>{var te,L,q,ie,ce,U;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:d=0,sticky:f="partial",hideWhenDetached:h=!1,updatePositionStrategy:p="optimized",onPlaced:m,...g}=e,y=Ju(ja,n),[x,w]=v.useState(null),C=Ze(t,We=>w(We)),[T,k]=v.useState(null),S=Yu(T),E=(S==null?void 0:S.width)??0,j=(S==null?void 0:S.height)??0,_=r+(s!=="center"?"-"+s:""),P=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},D=Array.isArray(c)?c:[c],z=D.length>0,B={padding:P,boundary:D.filter(uw),altBoundary:z},{refs:O,floatingStyles:H,placement:R,isPositioned:V,middlewareData:$}=Yv({strategy:"fixed",placement:_,whileElementsMounted:(...We)=>$v(...We,{animationFrame:p==="always"}),elements:{reference:y.anchor},middleware:[Jv({mainAxis:o+j,alignmentAxis:i}),l&&Zv({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?Qv():void 0,...B}),l&&ew({...B}),tw({...B,apply:({elements:We,rects:re,availableWidth:xe,availableHeight:Pe})=>{const{width:$e,height:rt}=re.reference,Se=We.floating.style;Se.setProperty("--radix-popper-available-width",`${xe}px`),Se.setProperty("--radix-popper-available-height",`${Pe}px`),Se.setProperty("--radix-popper-anchor-width",`${$e}px`),Se.setProperty("--radix-popper-anchor-height",`${rt}px`)}}),T&&rw({element:T,padding:a}),dw({arrowWidth:E,arrowHeight:j}),h&&nw({strategy:"referenceHidden",...B})]}),[F,ne]=od(R),Q=qt(m);Kt(()=>{V&&(Q==null||Q())},[V,Q]);const ye=(te=$.arrow)==null?void 0:te.x,je=(L=$.arrow)==null?void 0:L.y,J=((q=$.arrow)==null?void 0:q.centerOffset)!==0,[ue,ke]=v.useState();return Kt(()=>{x&&ke(window.getComputedStyle(x).zIndex)},[x]),u.jsx("div",{ref:O.setFloating,"data-radix-popper-content-wrapper":"",style:{...H,transform:V?H.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ue,"--radix-popper-transform-origin":[(ie=$.transformOrigin)==null?void 0:ie.x,(ce=$.transformOrigin)==null?void 0:ce.y].join(" "),...((U=$.hide)==null?void 0:U.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:u.jsx(aw,{scope:n,placedSide:F,onArrowChange:k,arrowX:ye,arrowY:je,shouldHideArrow:J,children:u.jsx(De.div,{"data-side":F,"data-align":ne,...g,ref:C,style:{...g.style,animation:V?void 0:"none"}})})})});td.displayName=ja;var nd="PopperArrow",cw={top:"bottom",right:"left",bottom:"top",left:"right"},rd=v.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=lw(nd,r),i=cw[s.placedSide];return u.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:u.jsx(sw,{...o,ref:n,style:{...o.style,display:"block"}})})});rd.displayName=nd;function uw(e){return e!==null}var dw=e=>({name:"transformOrigin",options:e,fn(t){var y,x,w;const{placement:n,rects:r,middlewareData:o}=t,i=((y=o.arrow)==null?void 0:y.centerOffset)!==0,a=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[c,d]=od(n),f={start:"0%",center:"50%",end:"100%"}[d],h=(((x=o.arrow)==null?void 0:x.x)??0)+a/2,p=(((w=o.arrow)==null?void 0:w.y)??0)+l/2;let m="",g="";return c==="bottom"?(m=i?f:`${h}px`,g=`${-l}px`):c==="top"?(m=i?f:`${h}px`,g=`${r.floating.height+l}px`):c==="right"?(m=`${-l}px`,g=i?f:`${p}px`):c==="left"&&(m=`${r.floating.width+l}px`,g=i?f:`${p}px`),{data:{x:m,y:g}}}});function od(e){const[t,n="center"]=e.split("-");return[t,n]}var sd=Zu,id=ed,ad=td,ld=rd,fw="Portal",js=v.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=v.useState(!1);Kt(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Pi.createPortal(u.jsx(De.div,{...r,ref:t}),i):null});js.displayName=fw;function hw(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var Sn=e=>{const{present:t,children:n}=e,r=pw(t),o=typeof n=="function"?n({present:r.isPresent}):v.Children.only(n),s=Ze(r.ref,mw(o));return typeof n=="function"||r.isPresent?v.cloneElement(o,{ref:s}):null};Sn.displayName="Presence";function pw(e){const[t,n]=v.useState(),r=v.useRef(null),o=v.useRef(e),s=v.useRef("none"),i=e?"mounted":"unmounted",[a,l]=hw(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return v.useEffect(()=>{const c=Ps(r.current);s.current=a==="mounted"?c:"none"},[a]),Kt(()=>{const c=r.current,d=o.current;if(d!==e){const h=s.current,p=Ps(c);e?l("MOUNT"):p==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(d&&h!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),Kt(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,f=p=>{const g=Ps(r.current).includes(CSS.escape(p.animationName));if(p.target===t&&g&&(l("ANIMATION_END"),!o.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",c=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},h=p=>{p.target===t&&(s.current=Ps(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{d.clearTimeout(c),t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:v.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function Ps(e){return(e==null?void 0:e.animationName)||"none"}function mw(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Pa="rovingFocusGroup.onEntryFocus",gw={bubbles:!1,cancelable:!0},bo="RovingFocusGroup",[Ra,cd,yw]=ha(bo),[xw,ud]=Qn(bo,[yw]),[vw,ww]=xw(bo),dd=v.forwardRef((e,t)=>u.jsx(Ra.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Ra.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(bw,{...e,ref:t})})}));dd.displayName=bo;var bw=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:d=!1,...f}=e,h=v.useRef(null),p=Ze(t,h),m=ys(s),[g,y]=Vr({prop:i,defaultProp:a??null,onChange:l,caller:bo}),[x,w]=v.useState(!1),C=qt(c),T=cd(n),k=v.useRef(!1),[S,E]=v.useState(0);return v.useEffect(()=>{const j=h.current;if(j)return j.addEventListener(Pa,C),()=>j.removeEventListener(Pa,C)},[C]),u.jsx(vw,{scope:n,orientation:r,dir:m,loop:o,currentTabStopId:g,onItemFocus:v.useCallback(j=>y(j),[y]),onItemShiftTab:v.useCallback(()=>w(!0),[]),onFocusableItemAdd:v.useCallback(()=>E(j=>j+1),[]),onFocusableItemRemove:v.useCallback(()=>E(j=>j-1),[]),children:u.jsx(De.div,{tabIndex:x||S===0?-1:0,"data-orientation":r,...f,ref:p,style:{outline:"none",...e.style},onMouseDown:ge(e.onMouseDown,()=>{k.current=!0}),onFocus:ge(e.onFocus,j=>{const _=!k.current;if(j.target===j.currentTarget&&_&&!x){const P=new CustomEvent(Pa,gw);if(j.currentTarget.dispatchEvent(P),!P.defaultPrevented){const D=T().filter(R=>R.focusable),z=D.find(R=>R.active),B=D.find(R=>R.id===g),H=[z,B,...D].filter(Boolean).map(R=>R.ref.current);pd(H,d)}}k.current=!1}),onBlur:ge(e.onBlur,()=>w(!1))})})}),fd="RovingFocusGroupItem",hd=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,l=er(),c=s||l,d=ww(fd,n),f=d.currentTabStopId===c,h=cd(n),{onFocusableItemAdd:p,onFocusableItemRemove:m,currentTabStopId:g}=d;return v.useEffect(()=>{if(r)return p(),()=>m()},[r,p,m]),u.jsx(Ra.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:u.jsx(De.span,{tabIndex:f?0:-1,"data-orientation":d.orientation,...a,ref:t,onMouseDown:ge(e.onMouseDown,y=>{r?d.onItemFocus(c):y.preventDefault()}),onFocus:ge(e.onFocus,()=>d.onItemFocus(c)),onKeyDown:ge(e.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){d.onItemShiftTab();return}if(y.target!==y.currentTarget)return;const x=kw(y,d.orientation,d.dir);if(x!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.preventDefault();let C=h().filter(T=>T.focusable).map(T=>T.ref.current);if(x==="last")C.reverse();else if(x==="prev"||x==="next"){x==="prev"&&C.reverse();const T=C.indexOf(y.currentTarget);C=d.loop?Tw(C,T+1):C.slice(T+1)}setTimeout(()=>pd(C))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:g!=null}):i})})});hd.displayName=fd;var Sw={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Cw(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function kw(e,t,n){const r=Cw(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Sw[r]}function pd(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Tw(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Ew=dd,Iw=hd,Nw=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Xr=new WeakMap,Rs=new WeakMap,Os={},Oa=0,md=function(e){return e&&(e.host||md(e.parentNode))},Aw=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=md(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},_w=function(e,t,n,r){var o=Aw(t,Array.isArray(e)?e:[e]);Os[n]||(Os[n]=new WeakMap);var s=Os[n],i=[],a=new Set,l=new Set(o),c=function(f){!f||a.has(f)||(a.add(f),c(f.parentNode))};o.forEach(c);var d=function(f){!f||l.has(f)||Array.prototype.forEach.call(f.children,function(h){if(a.has(h))d(h);else try{var p=h.getAttribute(r),m=p!==null&&p!=="false",g=(Xr.get(h)||0)+1,y=(s.get(h)||0)+1;Xr.set(h,g),s.set(h,y),i.push(h),g===1&&m&&Rs.set(h,!0),y===1&&h.setAttribute(n,"true"),m||h.setAttribute(r,"true")}catch(x){console.error("aria-hidden: cannot operate on ",h,x)}})};return d(t),a.clear(),Oa++,function(){i.forEach(function(f){var h=Xr.get(f)-1,p=s.get(f)-1;Xr.set(f,h),s.set(f,p),h||(Rs.has(f)||f.removeAttribute(r),Rs.delete(f)),p||f.removeAttribute(n)}),Oa--,Oa||(Xr=new WeakMap,Xr=new WeakMap,Rs=new WeakMap,Os={})}},Ma=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=Nw(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),_w(r,o,n,"aria-hidden")):function(){return null}},Vn=function(){return Vn=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},Vn.apply(this,arguments)};function gd(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function jw(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}typeof SuppressedError=="function"&&SuppressedError;var Ms="right-scroll-bar-position",Ds="width-before-scroll-bar",Pw="with-scroll-bars-hidden",Rw="--removed-body-scroll-bar-size";function Da(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function Ow(e,t){var n=b.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var Mw=typeof window<"u"?v.useLayoutEffect:v.useEffect,yd=new WeakMap;function Dw(e,t){var n=Ow(null,function(r){return e.forEach(function(o){return Da(o,r)})});return Mw(function(){var r=yd.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||Da(a,null)}),s.forEach(function(a){o.has(a)||Da(a,i)})}yd.set(n,e)},[e]),n}function Lw(e){return e}function Fw(e,t){t===void 0&&(t=Lw);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(s){var i=t(s,r);return n.push(i),function(){n=n.filter(function(a){return a!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var a=n;n=[],a.forEach(s),i=n}var l=function(){var d=i;i=[],d.forEach(s)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(d){i.push(d),c()},filter:function(d){return i=i.filter(d),n}}}};return o}function $w(e){e===void 0&&(e={});var t=Fw(null);return t.options=Vn({async:!0,ssr:!1},e),t}var xd=function(e){var t=e.sideCar,n=gd(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return v.createElement(r,Vn({},n))};xd.isSideCarExport=!0;function zw(e,t){return e.useMedium(t),xd}var vd=$w(),La=function(){},Ls=v.forwardRef(function(e,t){var n=v.useRef(null),r=v.useState({onScrollCapture:La,onWheelCapture:La,onTouchMoveCapture:La}),o=r[0],s=r[1],i=e.forwardProps,a=e.children,l=e.className,c=e.removeScrollBar,d=e.enabled,f=e.shards,h=e.sideCar,p=e.noRelative,m=e.noIsolation,g=e.inert,y=e.allowPinchZoom,x=e.as,w=x===void 0?"div":x,C=e.gapMode,T=gd(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=h,S=Dw([n,t]),E=Vn(Vn({},T),o);return v.createElement(v.Fragment,null,d&&v.createElement(k,{sideCar:vd,removeScrollBar:c,shards:f,noRelative:p,noIsolation:m,inert:g,setCallbacks:s,allowPinchZoom:!!y,lockRef:n,gapMode:C}),i?v.cloneElement(v.Children.only(a),Vn(Vn({},E),{ref:S})):v.createElement(w,Vn({},E,{className:l,ref:S}),a))});Ls.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},Ls.classNames={fullWidth:Ds,zeroRight:Ms};var Bw=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Hw(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Bw();return t&&e.setAttribute("nonce",t),e}function Uw(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Ww(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Vw=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Hw())&&(Uw(t,n),Ww(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Kw=function(){var e=Vw();return function(t,n){v.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},wd=function(){var e=Kw(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},qw={left:0,top:0,right:0,gap:0},Fa=function(e){return parseInt(e||"",10)||0},Gw=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[Fa(n),Fa(r),Fa(o)]},Yw=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return qw;var t=Gw(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},Xw=wd(),Jr="data-scroll-locked",Jw=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
|
|
39
39
|
.`.concat(Pw,` {
|
|
40
40
|
overflow: hidden `).concat(r,`;
|
|
41
41
|
padding-right: `).concat(a,"px ").concat(r,`;
|
|
@@ -83,7 +83,7 @@ React keys must be passed directly to JSX without using spread:
|
|
|
83
83
|
`).replace(/<ul>/gi,"").replace(/<\/ul>/gi,`
|
|
84
84
|
`).replace(/<ol>/gi,"").replace(/<\/ol>/gi,`
|
|
85
85
|
`).replace(/<li>(.*?)<\/li>/gi,`- $1
|
|
86
|
-
`).trim():n.replace(/</g,"<").replace(/>/g,">").trim()}function j0(e,t=Ks){if(!e||typeof e!="string")throw new Error("Invalid content: must be a non-empty string");if(e.length>t)throw new Error(`Message exceeds maximum length of ${t} characters`);return e}function P0(e){let t;return typeof e=="string"?t=e:typeof e=="object"&&e!==null?t=JSON.stringify(e):t=String(e),j0(t),_0(t)}const qs=0,cr=1,eo=2,kf=4;function Tf(e){return()=>e}function R0(e){e()}function Ef(e,t){return n=>e(t(n))}function If(e,t){return()=>e(t)}function O0(e,t){return n=>e(t,n)}function Ya(e){return e!==void 0}function M0(...e){return()=>{e.map(R0)}}function to(){}function Gs(e,t){return t(e),e}function D0(e,t){return t(e)}function Tt(...e){return e}function dt(e,t){return e(cr,t)}function ze(e,t){e(qs,t)}function Xa(e){e(eo)}function Ot(e){return e(kf)}function we(e,t){return dt(e,O0(t,qs))}function Rn(e,t){const n=e(cr,r=>{n(),t(r)});return n}function Nf(e){let t,n;return r=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{r(t)},e)}}function Af(e,t){return e===t}function Et(e=Af){let t;return n=>r=>{e(t,r)||(t=r,n(r))}}function _e(e){return t=>n=>{e(n)&&t(n)}}function pe(e){return t=>Ef(t,e)}function Kn(e){return t=>()=>{t(e)}}function X(e,...t){const n=L0(...t);return(r,o)=>{switch(r){case eo:Xa(e);return;case cr:return dt(e,n(o))}}}function qn(e,t){return n=>r=>{n(t=e(t,r))}}function Ir(e){return t=>n=>{e>0?e--:t(n)}}function rr(e){let t=null,n;return r=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,r(t)},e))}}function Ue(...e){const t=new Array(e.length);let n=0,r=null;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);dt(s,l=>{const c=n;n=n|a,t[i]=l,c!==o&&n===o&&r&&(r(),r=null)})}),s=>i=>{const a=()=>{s([i].concat(t))};n===o?a():r=a}}function L0(...e){return t=>e.reduceRight(D0,t)}function F0(e){let t,n;const r=()=>t==null?void 0:t();return function(o,s){switch(o){case cr:return s?n===s?void 0:(r(),n=s,t=dt(e,s),t):(r(),to);case eo:r(),n=null;return}}}function ee(e){let t=e;const n=Qe();return(r,o)=>{switch(r){case qs:t=o;break;case cr:{o(t);break}case kf:return t}return n(r,o)}}function en(e,t){return Gs(ee(t),n=>we(e,n))}function Qe(){const e=[];return(t,n)=>{switch(t){case qs:e.slice().forEach(r=>{r(n)});return;case eo:e.splice(0,e.length);return;case cr:return e.push(n),()=>{const r=e.indexOf(n);r>-1&&e.splice(r,1)}}}}function yn(e){return Gs(Qe(),t=>we(e,t))}function at(e,t=[],{singleton:n}={singleton:!0}){return{constructor:e,dependencies:t,id:$0(),singleton:n}}const $0=()=>Symbol();function z0(e){const t=new Map,n=({constructor:r,dependencies:o,id:s,singleton:i})=>{if(i&&t.has(s))return t.get(s);const a=r(o.map(l=>n(l)));return i&&t.set(s,a),a};return n(e)}function Ft(...e){const t=Qe(),n=new Array(e.length);let r=0;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);dt(s,l=>{n[i]=l,r=r|a,r===o&&ze(t,n)})}),function(s,i){switch(s){case eo:{Xa(t);return}case cr:return r===o&&i(n),dt(t,i)}}}function Ne(e,t=Af){return X(e,Et(t))}function Ja(...e){return function(t,n){switch(t){case eo:return;case cr:return M0(...e.map(r=>dt(r,n)))}}}var dn=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(dn||{});const B0={0:"debug",3:"error",1:"log",2:"warn"},H0=()=>typeof globalThis>"u"?window:globalThis,ur=at(()=>{const e=ee(3);return{log:ee((t,n,r=1)=>{var o;const s=(o=H0().VIRTUOSO_LOG_LEVEL)!=null?o:Ot(e);r>=s&&console[B0[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function Nr(e,t,n){return Za(e,t,n).callbackRef}function Za(e,t,n){const r=b.useRef(null);let o=i=>{};const s=b.useMemo(()=>typeof ResizeObserver<"u"?new ResizeObserver(i=>{const a=()=>{const l=i[0].target;l.offsetParent!==null&&e(l)};n?a():requestAnimationFrame(a)}):null,[e,n]);return o=i=>{i&&t?(s==null||s.observe(i),r.current=i):(r.current&&(s==null||s.unobserve(r.current)),r.current=null)},{callbackRef:o,ref:r}}function U0(e,t,n,r,o,s,i,a,l){const c=b.useCallback(d=>{const f=W0(d.children,t,a?"offsetWidth":"offsetHeight",o);let h=d.parentElement;for(;!h.dataset.virtuosoScroller;)h=h.parentElement;const p=h.lastElementChild.dataset.viewportType==="window";let m;p&&(m=h.ownerDocument.defaultView);const g=i?a?i.scrollLeft:i.scrollTop:p?a?m.scrollX||m.document.documentElement.scrollLeft:m.scrollY||m.document.documentElement.scrollTop:a?h.scrollLeft:h.scrollTop,y=i?a?i.scrollWidth:i.scrollHeight:p?a?m.document.documentElement.scrollWidth:m.document.documentElement.scrollHeight:a?h.scrollWidth:h.scrollHeight,x=i?a?i.offsetWidth:i.offsetHeight:p?a?m.innerWidth:m.innerHeight:a?h.offsetWidth:h.offsetHeight;r({scrollHeight:y,scrollTop:Math.max(g,0),viewportHeight:x}),s==null||s(a?_f("column-gap",getComputedStyle(d).columnGap,o):_f("row-gap",getComputedStyle(d).rowGap,o)),f!==null&&e(f)},[e,t,o,s,i,r,a]);return Za(c,n,l)}function W0(e,t,n,r){const o=e.length;if(o===0)return null;const s=[];for(let i=0;i<o;i++){const a=e.item(i);if(a.dataset.index===void 0)continue;const l=parseInt(a.dataset.index),c=parseFloat(a.dataset.knownSize),d=t(a,n);if(d===0&&r("Zero-sized element, this should not happen",{child:a},dn.ERROR),d===c)continue;const f=s[s.length-1];s.length===0||f.size!==d||f.endIndex!==l-1?s.push({endIndex:l,size:d,startIndex:l}):s[s.length-1].endIndex++}return s}function _f(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,dn.WARN),t==="normal"?0:parseInt(t??"0",10)}function jf(e,t,n){const r=b.useRef(null),o=b.useCallback(l=>{if(!(l!=null&&l.offsetParent))return;const c=l.getBoundingClientRect(),d=c.width;let f,h;if(t){const p=t.getBoundingClientRect(),m=c.top-p.top;h=p.height-Math.max(0,m),f=m+t.scrollTop}else{const p=i.current.ownerDocument.defaultView;h=p.innerHeight-Math.max(0,c.top),f=c.top+p.scrollY}r.current={offsetTop:f,visibleHeight:h,visibleWidth:d},e(r.current)},[e,t]),{callbackRef:s,ref:i}=Za(o,!0,n),a=b.useCallback(()=>{o(i.current)},[o,i]);return b.useEffect(()=>{var l;if(t){t.addEventListener("scroll",a);const c=new ResizeObserver(()=>{requestAnimationFrame(a)});return c.observe(t),()=>{t.removeEventListener("scroll",a),c.unobserve(t)}}else{const c=(l=i.current)==null?void 0:l.ownerDocument.defaultView;return c==null||c.addEventListener("scroll",a),c==null||c.addEventListener("resize",a),()=>{c==null||c.removeEventListener("scroll",a),c==null||c.removeEventListener("resize",a)}}},[a,t,i]),s}const on=at(()=>{const e=Qe(),t=Qe(),n=ee(0),r=Qe(),o=ee(0),s=Qe(),i=Qe(),a=ee(0),l=ee(0),c=ee(0),d=ee(0),f=Qe(),h=Qe(),p=ee(!1),m=ee(!1),g=ee(!1);return we(X(e,pe(({scrollTop:y})=>y)),t),we(X(e,pe(({scrollHeight:y})=>y)),i),we(t,o),{deviation:n,fixedFooterHeight:c,fixedHeaderHeight:l,footerHeight:d,headerHeight:a,horizontalDirection:m,scrollBy:h,scrollContainerState:e,scrollHeight:i,scrollingInProgress:p,scrollTo:f,scrollTop:t,skipAnimationFrameInResizeObserver:g,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:s}},[],{singleton:!0}),Io={lvl:0};function Pf(e,t){const n=e.length;if(n===0)return[];let{index:r,value:o}=t(e[0]);const s=[];for(let i=1;i<n;i++){const{index:a,value:l}=t(e[i]);s.push({end:a-1,start:r,value:o}),r=a,o=l}return s.push({end:1/0,start:r,value:o}),s}function vt(e){return e===Io}function No(e,t){if(!vt(e))return t===e.k?e.v:t<e.k?No(e.l,t):No(e.r,t)}function On(e,t,n="k"){if(vt(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const r=On(e.r,t,n);return r[0]===-1/0?[e.k,e.v]:r}return On(e.l,t,n)}function xn(e,t,n){return vt(e)?Mf(t,n,1):t===e.k?$t(e,{k:t,v:n}):t<e.k?Df($t(e,{l:xn(e.l,t,n)})):Df($t(e,{r:xn(e.r,t,n)}))}function no(){return Io}function Ys(e,t,n){if(vt(e))return[];const r=On(e,t)[0];return V0(el(e,r,n))}function Qa(e,t){if(vt(e))return Io;const{k:n,l:r,r:o}=e;if(t===n){if(vt(r))return o;if(vt(o))return r;{const[s,i]=Of(r);return Xs($t(e,{k:s,l:Rf(r),v:i}))}}else return t<n?Xs($t(e,{l:Qa(r,t)})):Xs($t(e,{r:Qa(o,t)}))}function Ar(e){return vt(e)?[]:[...Ar(e.l),{k:e.k,v:e.v},...Ar(e.r)]}function el(e,t,n){if(vt(e))return[];const{k:r,l:o,r:s,v:i}=e;let a=[];return r>t&&(a=a.concat(el(o,t,n))),r>=t&&r<=n&&a.push({k:r,v:i}),r<=n&&(a=a.concat(el(s,t,n))),a}function Xs(e){const{l:t,lvl:n,r}=e;if(r.lvl>=n-1&&t.lvl>=n-1)return e;if(n>r.lvl+1){if(tl(t))return Lf($t(e,{lvl:n-1}));if(!vt(t)&&!vt(t.r))return $t(t.r,{l:$t(t,{r:t.r.l}),lvl:n,r:$t(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}else{if(tl(e))return nl($t(e,{lvl:n-1}));if(!vt(r)&&!vt(r.l)){const o=r.l,s=tl(o)?r.lvl-1:r.lvl;return $t(o,{l:$t(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:nl($t(r,{l:o.r,lvl:s}))})}else throw new Error("Unexpected empty nodes")}}function $t(e,t){return Mf(t.k!==void 0?t.k:e.k,t.v!==void 0?t.v:e.v,t.lvl!==void 0?t.lvl:e.lvl,t.l!==void 0?t.l:e.l,t.r!==void 0?t.r:e.r)}function Rf(e){return vt(e.r)?e.l:Xs($t(e,{r:Rf(e.r)}))}function tl(e){return vt(e)||e.lvl>e.r.lvl}function Of(e){return vt(e.r)?[e.k,e.v]:Of(e.r)}function Mf(e,t,n,r=Io,o=Io){return{k:e,l:r,lvl:n,r:o,v:t}}function Df(e){return nl(Lf(e))}function Lf(e){const{l:t}=e;return!vt(t)&&t.lvl===e.lvl?$t(t,{r:$t(e,{l:t.r})}):e}function nl(e){const{lvl:t,r:n}=e;return!vt(n)&&!vt(n.r)&&n.lvl===t&&n.r.lvl===t?$t(n,{l:$t(e,{r:n.l}),lvl:t+1}):e}function V0(e){return Pf(e,({k:t,v:n})=>({index:t,value:n}))}function Ff(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}function Ao(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}const rl=at(()=>({recalcInProgress:ee(!1)}),[],{singleton:!0});function $f(e,t,n){return e[Js(e,t,n)]}function Js(e,t,n,r=0){let o=e.length-1;for(;r<=o;){const s=Math.floor((r+o)/2),i=e[s],a=n(i,t);if(a===0)return s;if(a===-1){if(o-r<2)return s-1;o=s-1}else{if(o===r)return s;r=s+1}}throw new Error(`Failed binary finding record in array - ${e.join(",")}, searched for ${t}`)}function K0(e,t,n,r){const o=Js(e,t,r),s=Js(e,n,r,o);return e.slice(o,s+1)}function dr(e,t){return Math.round(e.getBoundingClientRect()[t])}function Zs(e){return!vt(e.groupOffsetTree)}function ol({index:e},t){return t===e?0:t<e?-1:1}function q0(){return{groupIndices:[],groupOffsetTree:no(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:no()}}function G0(e,t){let n=vt(e)?0:1/0;for(const r of t){const{endIndex:o,size:s,startIndex:i}=r;if(n=Math.min(n,i),vt(e)){e=xn(e,0,s);continue}const a=Ys(e,i-1,o+1);if(a.some(tS(r)))continue;let l=!1,c=!1;for(const{end:d,start:f,value:h}of a)l?(o>=f||s===h)&&(e=Qa(e,f)):(c=h!==s,l=!0),d>o&&o>=f&&h!==s&&(e=xn(e,o+1,h));c&&(e=xn(e,i,s))}return[e,n]}function Y0(e){return typeof e.groupIndex<"u"}function X0({offset:e},t){return t===e?0:t<e?-1:1}function _o(e,t,n){if(t.length===0)return 0;const{index:r,offset:o,size:s}=$f(t,e,ol),i=e-r,a=s*i+(i-1)*n+o;return a>0?a+n:a}function zf(e,t){if(!Zs(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function Bf(e,t,n){if(Y0(e))return t.groupIndices[e.groupIndex]+1;{const r=e.index==="LAST"?n:e.index;let o=zf(r,t);return o=Math.max(0,o,Math.min(n,o)),o}}function J0(e,t,n,r=0){return r>0&&(t=Math.max(t,$f(e,r,ol).offset)),Pf(K0(e,t,n,X0),eS)}function Z0(e,[t,n,r,o]){t.length>0&&r("received item sizes",t,dn.DEBUG);const s=e.sizeTree;let i=s,a=0;if(n.length>0&&vt(s)&&t.length===2){const h=t[0].size,p=t[1].size;i=n.reduce((m,g)=>xn(xn(m,g,h),g+1,p),i)}else[i,a]=G0(i,t);if(i===s)return e;const{lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f}=sl(e.offsetTree,a,i,o);return{groupIndices:n,groupOffsetTree:n.reduce((h,p)=>xn(h,p,_o(p,f,o)),no()),lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f,sizeTree:i}}function Q0(e){return Ar(e).map(({k:t,v:n},r,o)=>{const s=o[r+1];return{endIndex:s?s.k-1:1/0,size:n,startIndex:t}})}function Hf(e,t){let n=0,r=0;for(;n<e;)n+=t[r+1]-t[r]-1,r++;return r-(n===e?0:1)}function sl(e,t,n,r){let o=e,s=0,i=0,a=0,l=0;if(t!==0){l=Js(o,t-1,ol),a=o[l].offset;const c=On(n,t-1);s=c[0],i=c[1],o.length&&o[l].size===On(n,t)[1]&&(l-=1),o=o.slice(0,l+1)}else o=[];for(const{start:c,value:d}of Ys(n,t,1/0)){const f=c-s,h=f*i+a+f*r;o.push({index:c,offset:h,size:d}),s=c,a=h,i=d}return{lastIndex:s,lastOffset:a,lastSize:i,offsetTree:o}}function eS(e){return{index:e.index,value:e}}function tS(e){const{endIndex:t,size:n,startIndex:r}=e;return o=>o.start===r&&(o.end===t||o.end===1/0)&&o.value===n}const nS={offsetHeight:"height",offsetWidth:"width"},Gn=at(([{log:e},{recalcInProgress:t}])=>{const n=Qe(),r=Qe(),o=en(r,0),s=Qe(),i=Qe(),a=ee(0),l=ee([]),c=ee(void 0),d=ee(void 0),f=ee((k,S)=>dr(k,nS[S])),h=ee(void 0),p=ee(0),m=q0(),g=en(X(n,Ue(l,e,p),qn(Z0,m),Et()),m),y=en(X(l,Et(),qn((k,S)=>({current:S,prev:k.current}),{current:[],prev:[]}),pe(({prev:k})=>k)),[]);we(X(l,_e(k=>k.length>0),Ue(g,p),pe(([k,S,E])=>{const j=k.reduce((_,P,D)=>xn(_,P,_o(P,S.offsetTree,E)||D),no());return{...S,groupIndices:k,groupOffsetTree:j}})),g),we(X(r,Ue(g),_e(([k,{lastIndex:S}])=>k<S),pe(([k,{lastIndex:S,lastSize:E}])=>[{endIndex:S,size:E,startIndex:k}])),n),we(c,d);const x=en(X(c,pe(k=>k===void 0)),!0);we(X(d,_e(k=>k!==void 0&&vt(Ot(g).sizeTree)),pe(k=>[{endIndex:0,size:k,startIndex:0}])),n);const w=yn(X(n,Ue(g),qn(({sizes:k},[S,E])=>({changed:E!==k,sizes:E}),{changed:!1,sizes:m}),pe(k=>k.changed)));dt(X(a,qn((k,S)=>({diff:k.prev-S,prev:S}),{diff:0,prev:0}),pe(k=>k.diff)),k=>{const{groupIndices:S}=Ot(g);if(k>0)ze(t,!0),ze(s,k+Hf(k,S));else if(k<0){const E=Ot(y);E.length>0&&(k-=Hf(-k,E)),ze(i,k)}}),dt(X(a,Ue(e)),([k,S])=>{k<0&&S("`firstItemIndex` prop should not be set to less than zero. If you don't know the total count, just use a very high value",{firstItemIndex:a},dn.ERROR)});const C=yn(s);we(X(s,Ue(g),pe(([k,S])=>{const E=S.groupIndices.length>0,j=[],_=S.lastSize;if(E){const P=No(S.sizeTree,0);let D=0,z=0;for(;D<k;){const O=S.groupIndices[z],H=S.groupIndices.length===z+1?1/0:S.groupIndices[z+1]-O-1;j.push({endIndex:O,size:P,startIndex:O}),j.push({endIndex:O+1+H-1,size:_,startIndex:O+1}),z++,D+=H+1}const B=Ar(S.sizeTree);return D!==k&&B.shift(),B.reduce((O,{k:H,v:R})=>{let V=O.ranges;return O.prevSize!==0&&(V=[...O.ranges,{endIndex:H+k-1,size:O.prevSize,startIndex:O.prevIndex}]),{prevIndex:H+k,prevSize:R,ranges:V}},{prevIndex:k,prevSize:0,ranges:j}).ranges}return Ar(S.sizeTree).reduce((P,{k:D,v:z})=>({prevIndex:D+k,prevSize:z,ranges:[...P.ranges,{endIndex:D+k-1,size:P.prevSize,startIndex:P.prevIndex}]}),{prevIndex:0,prevSize:_,ranges:[]}).ranges})),n);const T=yn(X(i,Ue(g,p),pe(([k,{offsetTree:S},E])=>{const j=-k;return _o(j,S,E)})));return we(X(i,Ue(g,p),pe(([k,S,E])=>{if(S.groupIndices.length>0){if(vt(S.sizeTree))return S;let j=no();const _=Ot(y);let P=0,D=0,z=0;for(;P<-k;){z=_[D];const B=_[D+1]-z-1;D++,P+=B+1}if(j=Ar(S.sizeTree).reduce((B,{k:O,v:H})=>xn(B,Math.max(0,O+k),H),j),P!==-k){const B=No(S.sizeTree,z);j=xn(j,0,B);const O=On(S.sizeTree,-k+1)[1];j=xn(j,1,O)}return{...S,sizeTree:j,...sl(S.offsetTree,0,j,E)}}else{const j=Ar(S.sizeTree).reduce((_,{k:P,v:D})=>xn(_,Math.max(0,P+k),D),no());return{...S,sizeTree:j,...sl(S.offsetTree,0,j,E)}}})),g),{beforeUnshiftWith:C,data:h,defaultItemSize:d,firstItemIndex:a,fixedItemSize:c,gap:p,groupIndices:l,itemSize:f,listRefresh:w,shiftWith:i,shiftWithOffset:T,sizeRanges:n,sizes:g,statefulTotalCount:o,totalCount:r,trackItemSizes:x,unshiftWith:s}},Tt(ur,rl),{singleton:!0});function rS(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const Uf=at(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:r,scrollTop:o}])=>{const s=Qe(),i=Qe(),a=yn(X(s,pe(rS)));return we(X(a,pe(l=>l.totalCount)),n),we(X(a,pe(l=>l.groupIndices)),e),we(X(Ft(o,t,r),_e(([l,c])=>Zs(c)),pe(([l,c,d])=>On(c.groupOffsetTree,Math.max(l-d,0),"v")[0]),Et(),pe(l=>[l])),i),{groupCounts:s,topItemsIndexes:i}},Tt(Gn,on)),fr=at(([{log:e}])=>{const t=ee(!1),n=yn(X(t,_e(r=>r),Et()));return dt(t,r=>{r&&Ot(e)("props updated",{},dn.DEBUG)}),{didMount:n,propsReady:t}},Tt(ur),{singleton:!0}),oS=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function Wf(e){const t=typeof e=="number"?{index:e}:e;return t.align||(t.align="start"),(!t.behavior||!oS)&&(t.behavior="auto"),t.offset||(t.offset=0),t}const jo=at(([{gap:e,listRefresh:t,sizes:n,totalCount:r},{fixedFooterHeight:o,fixedHeaderHeight:s,footerHeight:i,headerHeight:a,scrollingInProgress:l,scrollTo:c,smoothScrollTargetReached:d,viewportHeight:f},{log:h}])=>{const p=Qe(),m=Qe(),g=ee(0);let y=null,x=null,w=null;function C(){y&&(y(),y=null),w&&(w(),w=null),x&&(clearTimeout(x),x=null),ze(l,!1)}return we(X(p,Ue(n,f,r,g,a,i,h),Ue(e,s,o),pe(([[T,k,S,E,j,_,P,D],z,B,O])=>{const H=Wf(T),{align:R,behavior:V,offset:$}=H,F=E-1,ne=Bf(H,k,F);let Q=_o(ne,k.offsetTree,z)+_;R==="end"?(Q+=B+On(k.sizeTree,ne)[1]-S+O,ne===F&&(Q+=P)):R==="center"?Q+=(B+On(k.sizeTree,ne)[1]-S+O)/2:Q-=j,$&&(Q+=$);const ye=je=>{C(),je?(D("retrying to scroll to",{location:T},dn.DEBUG),ze(p,T)):(ze(m,!0),D("list did not change, scroll successful",{},dn.DEBUG))};if(C(),V==="smooth"){let je=!1;w=dt(t,J=>{je=je||J}),y=Rn(d,()=>{ye(je)})}else y=Rn(X(t,sS(150)),ye);return x=setTimeout(()=>{C()},1200),ze(l,!0),D("scrolling from index to",{behavior:V,index:ne,top:Q},dn.DEBUG),{behavior:V,top:Q}})),c),{scrollTargetReached:m,scrollToIndex:p,topListHeight:g}},Tt(Gn,on,ur),{singleton:!0});function sS(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return r=>{r&&(t(!0),clearTimeout(n))}}}function il(e,t){e==0?t():requestAnimationFrame(()=>{il(e-1,t)})}function al(e,t){const n=t-1;return typeof e=="number"?e:e.index==="LAST"?n:e.index}const Po=at(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:r},{scrollTargetReached:o,scrollToIndex:s},{didMount:i}])=>{const a=ee(!0),l=ee(0),c=ee(!0);return we(X(i,Ue(l),_e(([d,f])=>!!f),Kn(!1)),a),we(X(i,Ue(l),_e(([d,f])=>!!f),Kn(!1)),c),dt(X(Ft(t,i),Ue(a,n,e,c),_e(([[,d],f,{sizeTree:h},p,m])=>d&&(!vt(h)||Ya(p))&&!f&&!m),Ue(l)),([,d])=>{Rn(o,()=>{ze(c,!0)}),il(4,()=>{Rn(r,()=>{ze(a,!0)}),ze(s,d)})}),{initialItemFinalLocationReached:c,initialTopMostItemIndex:l,scrolledToInitialItem:a}},Tt(Gn,on,jo,fr),{singleton:!0});function Vf(e,t){return Math.abs(e-t)<1.01}const Ro="up",Oo="down",iS="none",aS={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},lS=0,Mo=at(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:r,scrollTop:o,viewportHeight:s}])=>{const i=ee(!1),a=ee(!0),l=Qe(),c=Qe(),d=ee(4),f=ee(lS),h=en(X(Ja(X(Ne(o),Ir(1),Kn(!0)),X(Ne(o),Ir(1),Kn(!1),Nf(100))),Et()),!1),p=en(X(Ja(X(n,Kn(!0)),X(n,Kn(!1),Nf(200))),Et()),!1);we(X(Ft(Ne(o),Ne(f)),pe(([w,C])=>w<=C),Et()),a),we(X(a,rr(50)),c);const m=yn(X(Ft(r,Ne(s),Ne(t),Ne(e),Ne(d)),qn((w,[{scrollHeight:C,scrollTop:T},k,S,E,j])=>{const _=T+k-C>-j,P={scrollHeight:C,scrollTop:T,viewportHeight:k};if(_){let z,B;return T>w.state.scrollTop?(z="SCROLLED_DOWN",B=w.state.scrollTop-T):(z="SIZE_DECREASED",B=w.state.scrollTop-T||w.scrollTopDelta),{atBottom:!0,atBottomBecause:z,scrollTopDelta:B,state:P}}let D;return P.scrollHeight>w.state.scrollHeight?D="SIZE_INCREASED":k<w.state.viewportHeight?D="VIEWPORT_HEIGHT_DECREASING":T<w.state.scrollTop?D="SCROLLING_UPWARDS":D="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:D,state:P}},aS),Et((w,C)=>w&&w.atBottom===C.atBottom))),g=en(X(r,qn((w,{scrollHeight:C,scrollTop:T,viewportHeight:k})=>{if(Vf(w.scrollHeight,C))return{changed:!1,jump:0,scrollHeight:C,scrollTop:T};{const S=C-(T+k)<1;return w.scrollTop!==T&&S?{changed:!0,jump:w.scrollTop-T,scrollHeight:C,scrollTop:T}:{changed:!0,jump:0,scrollHeight:C,scrollTop:T}}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),_e(w=>w.changed),pe(w=>w.jump)),0);we(X(m,pe(w=>w.atBottom)),i),we(X(i,rr(50)),l);const y=ee(Oo);we(X(r,pe(({scrollTop:w})=>w),Et(),qn((w,C)=>Ot(p)?{direction:w.direction,prevScrollTop:C}:{direction:C<w.prevScrollTop?Ro:Oo,prevScrollTop:C},{direction:Oo,prevScrollTop:0}),pe(w=>w.direction)),y),we(X(r,rr(50),Kn(iS)),y);const x=ee(0);return we(X(h,_e(w=>!w),Kn(0)),x),we(X(o,rr(100),Ue(h),_e(([w,C])=>!!C),qn(([w,C],[T])=>[C,T],[0,0]),pe(([w,C])=>C-w)),x),{atBottomState:m,atBottomStateChange:l,atBottomThreshold:d,atTopStateChange:c,atTopThreshold:f,isAtBottom:i,isAtTop:a,isScrolling:h,lastJumpDueToItemResize:g,scrollDirection:y,scrollVelocity:x}},Tt(on)),Qs="top",ei="bottom",Kf="none";function qf(e,t,n){return typeof e=="number"?n===Ro&&t===Qs||n===Oo&&t===ei?e:0:n===Ro?t===Qs?e.main:e.reverse:t===ei?e.main:e.reverse}function Gf(e,t){var n;return typeof e=="number"?e:(n=e[t])!=null?n:0}const ll=at(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:r,viewportHeight:o}])=>{const s=Qe(),i=ee(0),a=ee(0),l=ee(0),c=en(X(Ft(Ne(r),Ne(o),Ne(n),Ne(s,Ao),Ne(l),Ne(i),Ne(t),Ne(e),Ne(a)),pe(([d,f,h,[p,m],g,y,x,w,C])=>{const T=d-w,k=y+x,S=Math.max(h-T,0);let E=Kf;const j=Gf(C,Qs),_=Gf(C,ei);return p-=w,p+=h+x,m+=h+x,m-=w,p>d+k-j&&(E=Ro),m<d-S+f+_&&(E=Oo),E!==Kf?[Math.max(T-h-qf(g,Qs,E)-j,0),T-S-x+f+qf(g,ei,E)+_]:null}),_e(d=>d!=null),Et(Ao)),[0,0]);return{increaseViewportBy:a,listBoundary:s,overscan:l,topListHeight:i,visibleRange:c}},Tt(on),{singleton:!0});function cS(e,t,n){if(Zs(t)){const r=zf(e,t);return[{index:On(t.groupOffsetTree,r)[0],offset:0,size:0},{data:n==null?void 0:n[0],index:r,offset:0,size:0}]}return[{data:n==null?void 0:n[0],index:e,offset:0,size:0}]}const cl={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function ti(e,t,n,r,o,s){const{lastIndex:i,lastOffset:a,lastSize:l}=o;let c=0,d=0;if(e.length>0){c=e[0].offset;const g=e[e.length-1];d=g.offset+g.size}const f=n-i,h=a+f*l+(f-1)*r,p=c,m=h-d;return{bottom:d,firstItemIndex:s,items:Xf(e,o,s),offsetBottom:m,offsetTop:c,top:p,topItems:Xf(t,o,s),topListHeight:t.reduce((g,y)=>y.size+g,0),totalCount:n}}function Yf(e,t,n,r,o,s){let i=0;if(n.groupIndices.length>0)for(const d of n.groupIndices){if(d-i>=e)break;i++}const a=e+i,l=al(t,a),c=Array.from({length:a}).map((d,f)=>({data:s[f+l],index:f+l,offset:0,size:0}));return ti(c,[],a,o,n,r)}function Xf(e,t,n){if(e.length===0)return[];if(!Zs(t))return e.map(c=>({...c,index:c.index+n,originalIndex:c.index}));const r=e[0].index,o=e[e.length-1].index,s=[],i=Ys(t.groupOffsetTree,r,o);let a,l=0;for(const c of e){(!a||a.end<c.index)&&(a=i.shift(),l=t.groupIndices.indexOf(a.start));let d;c.index===a.start?d={index:l,type:"group"}:d={groupIndex:l,index:c.index-(l+1)+n},s.push({...d,data:c.data,offset:c.offset,originalIndex:c.index,size:c.size})}return s}const _r=at(([{data:e,firstItemIndex:t,gap:n,sizes:r,totalCount:o},s,{listBoundary:i,topListHeight:a,visibleRange:l},{initialTopMostItemIndex:c,scrolledToInitialItem:d},{topListHeight:f},h,{didMount:p},{recalcInProgress:m}])=>{const g=ee([]),y=ee(0),x=Qe();we(s.topItemsIndexes,g);const w=en(X(Ft(p,m,Ne(l,Ao),Ne(o),Ne(r),Ne(c),d,Ne(g),Ne(t),Ne(n),e),_e(([S,E,,j,,,,,,,_])=>{const P=_&&_.length!==j;return S&&!E&&!P}),pe(([,,[S,E],j,_,P,D,z,B,O,H])=>{const R=_,{offsetTree:V,sizeTree:$}=R,F=Ot(y);if(j===0)return{...cl,totalCount:j};if(S===0&&E===0)return F===0?{...cl,totalCount:j}:Yf(F,P,_,B,O,H||[]);if(vt($))return F>0?null:ti(cS(al(P,j),R,H),[],j,O,R,B);const ne=[];if(z.length>0){const ue=z[0],ke=z[z.length-1];let te=0;for(const L of Ys($,ue,ke)){const q=L.value,ie=Math.max(L.start,ue),ce=Math.min(L.end,ke);for(let U=ie;U<=ce;U++)ne.push({data:H==null?void 0:H[U],index:U,offset:te,size:q}),te+=q}}if(!D)return ti([],ne,j,O,R,B);const Q=z.length>0?z[z.length-1]+1:0,ye=J0(V,S,E,Q);if(ye.length===0)return null;const je=j-1,J=Gs([],ue=>{for(const ke of ye){const te=ke.value;let L=te.offset,q=ke.start;const ie=te.size;if(te.offset<S){q+=Math.floor((S-te.offset+O)/(ie+O));const U=q-ke.start;L+=U*ie+U*O}q<Q&&(L+=(Q-q)*ie,q=Q);const ce=Math.min(ke.end,je);for(let U=q;U<=ce&&!(L>=E);U++)ue.push({data:H==null?void 0:H[U],index:U,offset:L,size:ie}),L+=ie+O}});return ti(J,ne,j,O,R,B)}),_e(S=>S!==null),Et()),cl);we(X(e,_e(Ya),pe(S=>S==null?void 0:S.length)),o),we(X(w,pe(S=>S.topListHeight)),f),we(f,a),we(X(w,pe(S=>[S.top,S.bottom])),i),we(X(w,pe(S=>S.items)),x);const C=yn(X(w,_e(({items:S})=>S.length>0),Ue(o,e),_e(([{items:S},E])=>S[S.length-1].originalIndex===E-1),pe(([,S,E])=>[S-1,E]),Et(Ao),pe(([S])=>S))),T=yn(X(w,rr(200),_e(({items:S,topItems:E})=>S.length>0&&S[0].originalIndex===E.length),pe(({items:S})=>S[0].index),Et())),k=yn(X(w,_e(({items:S})=>S.length>0),pe(({items:S})=>{let E=0,j=S.length-1;for(;S[E].type==="group"&&E<j;)E++;for(;S[j].type==="group"&&j>E;)j--;return{endIndex:S[j].index,startIndex:S[E].index}}),Et(Ff)));return{endReached:C,initialItemCount:y,itemsRendered:x,listState:w,rangeChanged:k,startReached:T,topItemsIndexes:g,...h}},Tt(Gn,Uf,ll,Po,jo,Mo,fr,rl),{singleton:!0}),Jf=at(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:r},{listState:o}])=>{const s=Qe(),i=en(X(Ft(n,e,r,t,o),pe(([a,l,c,d,f])=>a+l+c+d+f.offsetBottom+f.bottom)),0);return we(Ne(i),s),{totalListHeight:i,totalListHeightChanged:s}},Tt(on,_r),{singleton:!0}),uS=at(([{viewportHeight:e},{totalListHeight:t}])=>{const n=ee(!1),r=en(X(Ft(n,e,t),_e(([o])=>o),pe(([,o,s])=>Math.max(0,o-s)),rr(0),Et()),0);return{alignToBottom:n,paddingTopAddition:r}},Tt(on,Jf),{singleton:!0}),Zf=at(()=>({context:ee(null)})),dS=({itemBottom:e,itemTop:t,locationParams:{align:n,behavior:r,...o},viewportBottom:s,viewportTop:i})=>t<i?{...o,align:n??"start",behavior:r}:e>s?{...o,align:n??"end",behavior:r}:null,Qf=at(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:s,scrollingInProgress:i,scrollTop:a,viewportHeight:l},{scrollToIndex:c}])=>{const d=Qe();return we(X(d,Ue(t,l,n,s,o,r,a),Ue(e),pe(([[f,h,p,m,g,y,x,w],C])=>{const{align:T,behavior:k,calculateViewLocation:S=dS,done:E,...j}=f,_=Bf(f,h,m-1),P=_o(_,h.offsetTree,C)+g+y,D=P+On(h.sizeTree,_)[1],z=w+y,B=w+p-x,O=S({itemBottom:D,itemTop:P,locationParams:{align:T,behavior:k,...j},viewportBottom:B,viewportTop:z});return O?E&&Rn(X(i,_e(H=>!H),Ir(Ot(i)?1:2)),E):E&&E(),O}),_e(f=>f!==null)),c),{scrollIntoView:d}},Tt(Gn,on,jo,_r,ur),{singleton:!0});function eh(e){return e?e==="smooth"?"smooth":"auto":!1}const fS=(e,t)=>typeof e=="function"?eh(e(t)):t&&eh(e),hS=at(([{listRefresh:e,totalCount:t,fixedItemSize:n,data:r},{atBottomState:o,isAtBottom:s},{scrollToIndex:i},{scrolledToInitialItem:a},{didMount:l,propsReady:c},{log:d},{scrollingInProgress:f},{context:h},{scrollIntoView:p}])=>{const m=ee(!1),g=Qe();let y=null;function x(k){ze(i,{align:"end",behavior:k,index:"LAST"})}dt(X(Ft(X(Ne(t),Ir(1)),l),Ue(Ne(m),s,a,f),pe(([[k,S],E,j,_,P])=>{let D=S&&_,z="auto";return D&&(z=fS(E,j||P),D=D&&!!z),{followOutputBehavior:z,shouldFollow:D,totalCount:k}}),_e(({shouldFollow:k})=>k)),({followOutputBehavior:k,totalCount:S})=>{y&&(y(),y=null),Ot(n)?requestAnimationFrame(()=>{Ot(d)("following output to ",{totalCount:S},dn.DEBUG),x(k)}):y=Rn(e,()=>{Ot(d)("following output to ",{totalCount:S},dn.DEBUG),x(k),y=null})});function w(k){const S=Rn(o,E=>{k&&!E.atBottom&&E.notAtBottomBecause==="SIZE_INCREASED"&&!y&&(Ot(d)("scrolling to bottom due to increased size",{},dn.DEBUG),x("auto"))});setTimeout(S,100)}dt(X(Ft(Ne(m),t,c),_e(([k,,S])=>k&&S),qn(({value:k},[,S])=>({refreshed:k===S,value:S}),{refreshed:!1,value:0}),_e(({refreshed:k})=>k),Ue(m,t)),([,k])=>{Ot(a)&&w(k!==!1)}),dt(g,()=>{w(Ot(m)!==!1)}),dt(Ft(Ne(m),o),([k,S])=>{k&&!S.atBottom&&S.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&x("auto")});const C=ee(null),T=Qe();return we(Ja(X(Ne(r),pe(k=>{var S;return(S=k==null?void 0:k.length)!=null?S:0})),X(Ne(t))),T),dt(X(Ft(X(T,Ir(1)),l),Ue(Ne(C),a,f,h),pe(([[k,S],E,j,_,P])=>S&&j&&(E==null?void 0:E({context:P,totalCount:k,scrollingInProgress:_}))),_e(k=>!!k),rr(0)),k=>{y&&(y(),y=null),Ot(n)?requestAnimationFrame(()=>{Ot(d)("scrolling into view",{}),ze(p,k)}):y=Rn(e,()=>{Ot(d)("scrolling into view",{}),ze(p,k),y=null})}),{autoscrollToBottom:g,followOutput:m,scrollIntoViewOnChange:C}},Tt(Gn,Mo,jo,Po,fr,ur,on,Zf,Qf)),pS=at(([{data:e,firstItemIndex:t,gap:n,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:s,listState:i},{didMount:a}])=>(we(X(a,Ue(s),_e(([,l])=>l!==0),Ue(o,r,t,n,e),pe(([[,l],c,d,f,h,p=[]])=>Yf(l,c,d,f,h,p))),i),{}),Tt(Gn,Po,_r,fr),{singleton:!0}),mS=at(([{didMount:e},{scrollTo:t},{listState:n}])=>{const r=ee(0);return dt(X(e,Ue(r),_e(([,o])=>o!==0),pe(([,o])=>({top:o}))),o=>{Rn(X(n,Ir(1),_e(s=>s.items.length>1)),()=>{requestAnimationFrame(()=>{ze(t,o)})})}),{initialScrollTop:r}},Tt(fr,on,_r),{singleton:!0}),th=at(([{scrollVelocity:e}])=>{const t=ee(!1),n=Qe(),r=ee(!1);return we(X(e,Ue(r,t,n),_e(([o,s])=>!!s),pe(([o,s,i,a])=>{const{enter:l,exit:c}=s;if(i){if(c(o,a))return!1}else if(l(o,a))return!0;return i}),Et()),t),dt(X(Ft(t,e,n),Ue(r)),([[o,s,i],a])=>{o&&a&&a.change&&a.change(s,i)}),{isSeeking:t,scrollSeekConfiguration:r,scrollSeekRangeChanged:n,scrollVelocity:e}},Tt(Mo),{singleton:!0}),ul=at(([{scrollContainerState:e,scrollTo:t}])=>{const n=Qe(),r=Qe(),o=Qe(),s=ee(!1),i=ee(void 0);return we(X(Ft(n,r),pe(([{scrollHeight:a,scrollTop:l,viewportHeight:c},{offsetTop:d}])=>({scrollHeight:a,scrollTop:Math.max(0,l-d),viewportHeight:c}))),e),we(X(t,Ue(r),pe(([a,{offsetTop:l}])=>({...a,top:a.top+l}))),o),{customScrollParent:i,useWindowScroll:s,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:r}},Tt(on)),gS=at(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:r},{initialTopMostItemIndex:o},{didMount:s},{useWindowScroll:i,windowScrollContainerState:a,windowViewportRect:l}])=>{const c=Qe(),d=ee(void 0),f=ee(null),h=ee(null);return we(a,f),we(l,h),dt(X(c,Ue(t,r,i,f,h,n)),([p,m,g,y,x,w,C])=>{const T=Q0(m.sizeTree);y&&x!==null&&w!==null&&(g=x.scrollTop-w.offsetTop),g-=C,p({ranges:T,scrollTop:g})}),we(X(d,_e(Ya),pe(yS)),o),we(X(s,Ue(d),_e(([,p])=>p!==void 0),Et(),pe(([,p])=>p.ranges)),e),{getState:c,restoreStateFrom:d}},Tt(Gn,on,Po,fr,ul));function yS(e){return{align:"start",index:0,offset:e.scrollTop}}const xS=at(([{topItemsIndexes:e}])=>{const t=ee(0);return we(X(t,_e(n=>n>=0),pe(n=>Array.from({length:n}).map((r,o)=>o))),e),{topItemCount:t}},Tt(_r));function nh(e){let t=!1,n;return()=>(t||(t=!0,n=e()),n)}const vS=nh(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),wS=at(([{deviation:e,scrollBy:t,scrollingInProgress:n,scrollTop:r},{isAtBottom:o,isScrolling:s,lastJumpDueToItemResize:i,scrollDirection:a},{listState:l},{beforeUnshiftWith:c,gap:d,shiftWithOffset:f,sizes:h},{log:p},{recalcInProgress:m}])=>{const g=yn(X(l,Ue(i),qn(([,x,w,C],[{bottom:T,items:k,offsetBottom:S,totalCount:E},j])=>{const _=T+S;let P=0;return w===E&&x.length>0&&k.length>0&&(k[0].originalIndex===0&&x[0].originalIndex===0||(P=_-C,P!==0&&(P+=j))),[P,k,E,_]},[0,[],0,0]),_e(([x])=>x!==0),Ue(r,a,n,o,p,m),_e(([,x,w,C,,,T])=>!T&&!C&&x!==0&&w===Ro),pe(([[x],,,,,w])=>(w("Upward scrolling compensation",{amount:x},dn.DEBUG),x))));function y(x){x>0?(ze(t,{behavior:"auto",top:-x}),ze(e,0)):(ze(e,0),ze(t,{behavior:"auto",top:-x}))}return dt(X(g,Ue(e,s)),([x,w,C])=>{C&&vS()?ze(e,w-x):y(-x)}),dt(X(Ft(en(s,!1),e,m),_e(([x,w,C])=>!x&&!C&&w!==0),pe(([x,w])=>w),rr(1)),y),we(X(f,pe(x=>({top:-x}))),t),dt(X(c,Ue(h,d),pe(([x,{groupIndices:w,lastSize:C,sizeTree:T},k])=>{function S(E){return E*(C+k)}if(w.length===0)return S(x);{let E=0;const j=No(T,0);let _=0,P=0;for(;_<x;){_++,E+=j;let D=w.length===P+1?1/0:w[P+1]-w[P]-1;_+D>x&&(E-=j,D=x-_+1),_+=D,E+=S(D),P++}return E}})),x=>{ze(e,x),requestAnimationFrame(()=>{ze(t,{top:x}),requestAnimationFrame(()=>{ze(e,0),ze(m,!1)})})}),{deviation:e}},Tt(on,Mo,_r,Gn,ur,rl)),bS=at(([e,t,n,r,o,s,i,a,l,c,d])=>({...e,...t,...n,...r,...o,...s,...i,...a,...l,...c,...d}),Tt(ll,pS,fr,th,Jf,mS,uS,ul,Qf,ur,Zf)),rh=at(([{data:e,defaultItemSize:t,firstItemIndex:n,fixedItemSize:r,gap:o,groupIndices:s,itemSize:i,sizeRanges:a,sizes:l,statefulTotalCount:c,totalCount:d,trackItemSizes:f},{initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:m},g,y,x,{listState:w,topItemsIndexes:C,...T},{scrollToIndex:k},S,{topItemCount:E},{groupCounts:j},_])=>(we(T.rangeChanged,_.scrollSeekRangeChanged),we(X(_.windowViewportRect,pe(P=>P.visibleHeight)),g.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:r,gap:o,groupCounts:j,initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:m,sizeRanges:a,topItemCount:E,topItemsIndexes:C,totalCount:d,...x,groupIndices:s,itemSize:i,listState:w,scrollToIndex:k,statefulTotalCount:c,trackItemSizes:f,...T,..._,...g,sizes:l,...y}),Tt(Gn,Po,on,gS,hS,_r,jo,wS,xS,Uf,bS));function SS(e,t){const n={},r={};let o=0;const s=e.length;for(;o<s;)r[e[o]]=1,o+=1;for(const i in t)Object.hasOwn(r,i)||(n[i]=t[i]);return n}const ni=typeof document<"u"?b.useLayoutEffect:b.useEffect;function oh(e,t,n){const r=Object.keys(t.required||{}),o=Object.keys(t.optional||{}),s=Object.keys(t.methods||{}),i=Object.keys(t.events||{}),a=b.createContext({});function l(y,x){y.propsReady&&ze(y.propsReady,!1);for(const w of r){const C=y[t.required[w]];ze(C,x[w])}for(const w of o)if(w in x){const C=y[t.optional[w]];ze(C,x[w])}y.propsReady&&ze(y.propsReady,!0)}function c(y){return s.reduce((x,w)=>(x[w]=C=>{const T=y[t.methods[w]];ze(T,C)},x),{})}function d(y){return i.reduce((x,w)=>(x[w]=F0(y[t.events[w]]),x),{})}const f=b.forwardRef((y,x)=>{const{children:w,...C}=y,[T]=b.useState(()=>Gs(z0(e),E=>{l(E,C)})),[k]=b.useState(If(d,T));ni(()=>{for(const E of i)E in C&&dt(k[E],C[E]);return()=>{Object.values(k).map(Xa)}},[C,k,T]),ni(()=>{l(T,C)}),b.useImperativeHandle(x,Tf(c(T)));const S=n;return u.jsx(a.Provider,{value:T,children:n?u.jsx(S,{...SS([...r,...o,...i],C),children:w}):w})}),h=y=>{const x=b.useContext(a);return b.useCallback(w=>{ze(x[y],w)},[x,y])},p=y=>{const x=b.useContext(a)[y],w=b.useCallback(C=>dt(x,C),[x]);return b.useSyncExternalStore(w,()=>Ot(x),()=>Ot(x))},m=y=>{const x=b.useContext(a)[y],[w,C]=b.useState(If(Ot,x));return ni(()=>dt(x,T=>{T!==w&&C(Tf(T))}),[x,w]),w},g=b.version.startsWith("18")?p:m;return{Component:f,useEmitter:(y,x)=>{const w=b.useContext(a)[y];ni(()=>dt(w,x),[x,w])},useEmitterValue:g,usePublisher:h}}const sh=b.createContext(void 0),ih=b.createContext(void 0),ah=typeof document<"u"?b.useLayoutEffect:b.useEffect;function dl(e){return"self"in e}function CS(e){return"body"in e}function lh(e,t,n,r=to,o,s){const i=b.useRef(null),a=b.useRef(null),l=b.useRef(null),c=b.useCallback(h=>{let p,m,g;const y=h.target;if(CS(y)||dl(y)){const w=dl(y)?y:y.defaultView;g=s?w.scrollX:w.scrollY,p=s?w.document.documentElement.scrollWidth:w.document.documentElement.scrollHeight,m=s?w.innerWidth:w.innerHeight}else g=s?y.scrollLeft:y.scrollTop,p=s?y.scrollWidth:y.scrollHeight,m=s?y.offsetWidth:y.offsetHeight;const x=()=>{e({scrollHeight:p,scrollTop:Math.max(g,0),viewportHeight:m})};h.suppressFlushSync?x():Pi.flushSync(x),a.current!==null&&(g===a.current||g<=0||g===p-m)&&(a.current=null,t(!0),l.current&&(clearTimeout(l.current),l.current=null))},[e,t,s]);b.useEffect(()=>{const h=o||i.current;return r(o||i.current),c({suppressFlushSync:!0,target:h}),h.addEventListener("scroll",c,{passive:!0}),()=>{r(null),h.removeEventListener("scroll",c)}},[i,c,n,r,o]);function d(h){const p=i.current;if(!p||(s?"offsetWidth"in p&&p.offsetWidth===0:"offsetHeight"in p&&p.offsetHeight===0))return;const m=h.behavior==="smooth";let g,y,x;dl(p)?(y=Math.max(dr(p.document.documentElement,s?"width":"height"),s?p.document.documentElement.scrollWidth:p.document.documentElement.scrollHeight),g=s?p.innerWidth:p.innerHeight,x=s?window.scrollX:window.scrollY):(y=p[s?"scrollWidth":"scrollHeight"],g=dr(p,s?"width":"height"),x=p[s?"scrollLeft":"scrollTop"]);const w=y-g;if(h.top=Math.ceil(Math.max(Math.min(w,h.top),0)),Vf(g,y)||h.top===x){e({scrollHeight:y,scrollTop:x,viewportHeight:g}),m&&t(!0);return}m?(a.current=h.top,l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{l.current=null,a.current=null,t(!0)},1e3)):a.current=null,s&&(h={behavior:h.behavior,left:h.top}),p.scrollTo(h)}function f(h){s&&(h={behavior:h.behavior,left:h.top}),i.current.scrollBy(h)}return{scrollByCallback:f,scrollerRef:i,scrollToCallback:d}}const fl="-webkit-sticky",ch="sticky",hl=nh(()=>{if(typeof document>"u")return ch;const e=document.createElement("div");return e.style.position=fl,e.style.position===fl?fl:ch});function pl(e){return e}const kS=at(()=>{const e=ee(a=>`Item ${a}`),t=ee(a=>`Group ${a}`),n=ee({}),r=ee(pl),o=ee("div"),s=ee(to),i=(a,l=null)=>en(X(n,pe(c=>c[a]),Et()),l);return{components:n,computeItemKey:r,EmptyPlaceholder:i("EmptyPlaceholder"),FooterComponent:i("Footer"),GroupComponent:i("Group","div"),groupContent:t,HeaderComponent:i("Header"),HeaderFooterTag:o,ItemComponent:i("Item","div"),itemContent:e,ListComponent:i("List","div"),ScrollerComponent:i("Scroller","div"),scrollerRef:s,ScrollSeekPlaceholder:i("ScrollSeekPlaceholder"),TopItemListComponent:i("TopItemList")}}),TS=at(([e,t])=>({...e,...t}),Tt(rh,kS)),ES=({height:e})=>u.jsx("div",{style:{height:e}}),IS={overflowAnchor:"none",position:hl(),zIndex:1},uh={overflowAnchor:"none"},NS={...uh,display:"inline-block",height:"100%"},dh=b.memo(function({showTopList:e=!1}){const t=Oe("listState"),n=kn("sizeRanges"),r=Oe("useWindowScroll"),o=Oe("customScrollParent"),s=kn("windowScrollContainerState"),i=kn("scrollContainerState"),a=o||r?s:i,l=Oe("itemContent"),c=Oe("context"),d=Oe("groupContent"),f=Oe("trackItemSizes"),h=Oe("itemSize"),p=Oe("log"),m=kn("gap"),g=Oe("horizontalDirection"),{callbackRef:y}=U0(n,h,f,e?to:a,p,m,o,g,Oe("skipAnimationFrameInResizeObserver")),[x,w]=b.useState(0);ml("deviation",O=>{x!==O&&w(O)});const C=Oe("EmptyPlaceholder"),T=Oe("ScrollSeekPlaceholder")||ES,k=Oe("ListComponent"),S=Oe("ItemComponent"),E=Oe("GroupComponent"),j=Oe("computeItemKey"),_=Oe("isSeeking"),P=Oe("groupIndices").length>0,D=Oe("alignToBottom"),z=Oe("initialItemFinalLocationReached"),B=e?{}:{boxSizing:"border-box",...g?{display:"inline-block",height:"100%",marginLeft:x!==0?x:D?"auto":0,paddingLeft:t.offsetTop,paddingRight:t.offsetBottom,whiteSpace:"nowrap"}:{marginTop:x!==0?x:D?"auto":0,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...z?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&C?u.jsx(C,{...tn(C,c)}):u.jsx(k,{...tn(k,c),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:y,style:B,children:(e?t.topItems:t.items).map(O=>{const H=O.originalIndex,R=j(H+t.firstItemIndex,O.data,c);return _?b.createElement(T,{...tn(T,c),height:O.size,index:O.index,key:R,type:O.type||"item",...O.type==="group"?{}:{groupIndex:O.groupIndex}}):O.type==="group"?b.createElement(E,{...tn(E,c),"data-index":H,"data-item-index":O.index,"data-known-size":O.size,key:R,style:IS},d(O.index,c)):b.createElement(S,{...tn(S,c),...PS(S,O.data),"data-index":H,"data-item-group-index":O.groupIndex,"data-item-index":O.index,"data-known-size":O.size,key:R,style:g?NS:uh},P?l(O.index,O.groupIndex,O.data,c):l(O.index,O.data,c))})})}),AS={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},_S={outline:"none",overflowX:"auto",position:"relative"},ri=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:{}}),jS={position:hl(),top:0,width:"100%",zIndex:1};function tn(e,t){if(typeof e!="string")return{context:t}}function PS(e,t){return{item:typeof e=="string"?void 0:t}}const RS=b.memo(function(){const e=Oe("HeaderComponent"),t=kn("headerHeight"),n=Oe("HeaderFooterTag"),r=Nr(b.useMemo(()=>s=>{t(dr(s,"height"))},[t]),!0,Oe("skipAnimationFrameInResizeObserver")),o=Oe("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...tn(e,o)})}):null}),OS=b.memo(function(){const e=Oe("FooterComponent"),t=kn("footerHeight"),n=Oe("HeaderFooterTag"),r=Nr(b.useMemo(()=>s=>{t(dr(s,"height"))},[t]),!0,Oe("skipAnimationFrameInResizeObserver")),o=Oe("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...tn(e,o)})}):null});function fh({useEmitter:e,useEmitterValue:t,usePublisher:n}){return b.memo(function({children:r,style:o,context:s,...i}){const a=n("scrollContainerState"),l=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=t("scrollerRef"),f=t("horizontalDirection")||!1,{scrollByCallback:h,scrollerRef:p,scrollToCallback:m}=lh(a,c,l,d,void 0,f);return e("scrollTo",m),e("scrollBy",h),u.jsx(l,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:p,style:{...f?_S:AS,...o},tabIndex:0,...i,...tn(l,s),children:r})})}function hh({useEmitter:e,useEmitterValue:t,usePublisher:n}){return b.memo(function({children:r,style:o,context:s,...i}){const a=n("windowScrollContainerState"),l=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=t("totalListHeight"),f=t("deviation"),h=t("customScrollParent"),p=b.useRef(null),m=t("scrollerRef"),{scrollByCallback:g,scrollerRef:y,scrollToCallback:x}=lh(a,c,l,m,h);return ah(()=>{var w;return y.current=h||((w=p.current)==null?void 0:w.ownerDocument.defaultView),()=>{y.current=null}},[y,h]),e("windowScrollTo",x),e("scrollBy",g),u.jsx(l,{ref:p,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...d!==0?{height:d+f}:{}},...i,...tn(l,s),children:r})})}const MS=({children:e})=>{const t=b.useContext(sh),n=kn("viewportHeight"),r=kn("fixedItemHeight"),o=Oe("alignToBottom"),s=Oe("horizontalDirection"),i=b.useMemo(()=>Ef(n,l=>dr(l,s?"width":"height")),[n,s]),a=Nr(i,!0,Oe("skipAnimationFrameInResizeObserver"));return b.useEffect(()=>{t&&(n(t.viewportHeight),r(t.itemHeight))},[t,n,r]),u.jsx("div",{"data-viewport-type":"element",ref:a,style:ri(o),children:e})},DS=({children:e})=>{const t=b.useContext(sh),n=kn("windowViewportRect"),r=kn("fixedItemHeight"),o=Oe("customScrollParent"),s=jf(n,o,Oe("skipAnimationFrameInResizeObserver")),i=Oe("alignToBottom");return b.useEffect(()=>{t&&(r(t.itemHeight),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:100}))},[t,n,r]),u.jsx("div",{"data-viewport-type":"window",ref:s,style:ri(i),children:e})},LS=({children:e})=>{const t=Oe("TopItemListComponent")||"div",n=Oe("headerHeight"),r={...jS,marginTop:`${n}px`},o=Oe("context");return u.jsx(t,{style:r,...tn(t,o),children:e})},FS=b.memo(function(e){const t=Oe("useWindowScroll"),n=Oe("topItemsIndexes").length>0,r=Oe("customScrollParent"),o=Oe("context");return u.jsxs(r||t?BS:zS,{...e,context:o,children:[n&&u.jsx(LS,{children:u.jsx(dh,{showTopList:!0})}),u.jsxs(r||t?DS:MS,{children:[u.jsx(RS,{}),u.jsx(dh,{}),u.jsx(OS,{})]})]})}),{Component:$S,useEmitter:ml,useEmitterValue:Oe,usePublisher:kn}=oh(TS,{required:{},optional:{restoreStateFrom:"restoreStateFrom",context:"context",followOutput:"followOutput",scrollIntoViewOnChange:"scrollIntoViewOnChange",itemContent:"itemContent",groupContent:"groupContent",overscan:"overscan",increaseViewportBy:"increaseViewportBy",totalCount:"totalCount",groupCounts:"groupCounts",topItemCount:"topItemCount",firstItemIndex:"firstItemIndex",initialTopMostItemIndex:"initialTopMostItemIndex",components:"components",atBottomThreshold:"atBottomThreshold",atTopThreshold:"atTopThreshold",computeItemKey:"computeItemKey",defaultItemHeight:"defaultItemHeight",fixedItemHeight:"fixedItemHeight",itemSize:"itemSize",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"HeaderFooterTag",data:"data",initialItemCount:"initialItemCount",initialScrollTop:"initialScrollTop",alignToBottom:"alignToBottom",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",horizontalDirection:"horizontalDirection",skipAnimationFrameInResizeObserver:"skipAnimationFrameInResizeObserver"},methods:{scrollToIndex:"scrollToIndex",scrollIntoView:"scrollIntoView",scrollTo:"scrollTo",scrollBy:"scrollBy",autoscrollToBottom:"autoscrollToBottom",getState:"getState"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",totalListHeightChanged:"totalListHeightChanged",itemsRendered:"itemsRendered",groupIndices:"groupIndices"}},FS),zS=fh({useEmitter:ml,useEmitterValue:Oe,usePublisher:kn}),BS=hh({useEmitter:ml,useEmitterValue:Oe,usePublisher:kn}),HS=$S;Tt(rh,at(()=>{const e=ee(c=>u.jsxs("td",{children:["Item $",c]})),t=ee(null),n=ee(c=>u.jsxs("td",{colSpan:1e3,children:["Group ",c]})),r=ee(null),o=ee(null),s=ee({}),i=ee(pl),a=ee(to),l=(c,d=null)=>en(X(s,pe(f=>f[c]),Et()),d);return{components:s,computeItemKey:i,context:t,EmptyPlaceholder:l("EmptyPlaceholder"),FillerRow:l("FillerRow"),fixedFooterContent:o,fixedHeaderContent:r,itemContent:e,groupContent:n,ScrollerComponent:l("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder"),TableBodyComponent:l("TableBody","tbody"),TableComponent:l("Table","table"),TableFooterComponent:l("TableFoot","tfoot"),TableHeadComponent:l("TableHead","thead"),TableRowComponent:l("TableRow","tr"),GroupComponent:l("Group","tr")}})),hl();const ph={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},US={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:mh,floor:oi,max:Do,min:gl,round:gh}=Math;function yh(e,t,n){return Array.from({length:t-e+1}).map((r,o)=>({data:n===null?null:n[o+e],index:o+e}))}function WS(e){return{...US,items:e}}function si(e,t){return e&&e.width===t.width&&e.height===t.height}function VS(e,t){return e&&e.column===t.column&&e.row===t.row}const KS=at(([{increaseViewportBy:e,listBoundary:t,overscan:n,visibleRange:r},{footerHeight:o,headerHeight:s,scrollBy:i,scrollContainerState:a,scrollTo:l,scrollTop:c,smoothScrollTargetReached:d,viewportHeight:f},h,p,{didMount:m,propsReady:g},{customScrollParent:y,useWindowScroll:x,windowScrollContainerState:w,windowScrollTo:C,windowViewportRect:T},k])=>{const S=ee(0),E=ee(0),j=ee(ph),_=ee({height:0,width:0}),P=ee({height:0,width:0}),D=Qe(),z=Qe(),B=ee(0),O=ee(null),H=ee({column:0,row:0}),R=Qe(),V=Qe(),$=ee(!1),F=ee(0),ne=ee(!0),Q=ee(!1),ye=ee(!1);dt(X(m,Ue(F),_e(([L,q])=>!!q)),()=>{ze(ne,!1)}),dt(X(Ft(m,ne,P,_,F,Q),_e(([L,q,ie,ce,,U])=>L&&!q&&ie.height!==0&&ce.height!==0&&!U)),([,,,,L])=>{ze(Q,!0),il(1,()=>{ze(D,L)}),Rn(X(c),()=>{ze(t,[0,0]),ze(ne,!0)})}),we(X(V,_e(L=>L!=null&&L.scrollTop>0),Kn(0)),E),dt(X(m,Ue(V),_e(([,L])=>L!=null)),([,L])=>{L&&(ze(_,L.viewport),ze(P,L.item),ze(H,L.gap),L.scrollTop>0&&(ze($,!0),Rn(X(c,Ir(1)),q=>{ze($,!1)}),ze(l,{top:L.scrollTop})))}),we(X(_,pe(({height:L})=>L)),f),we(X(Ft(Ne(_,si),Ne(P,si),Ne(H,(L,q)=>L&&L.column===q.column&&L.row===q.row),Ne(c)),pe(([L,q,ie,ce])=>({gap:ie,item:q,scrollTop:ce,viewport:L}))),R),we(X(Ft(Ne(S),r,Ne(H,VS),Ne(P,si),Ne(_,si),Ne(O),Ne(E),Ne($),Ne(ne),Ne(F)),_e(([,,,,,,,L])=>!L),pe(([L,[q,ie],ce,U,We,re,xe,,Pe,$e])=>{const{column:rt,row:Se}=ce,{height:Ye,width:ot}=U,{width:et}=We;if(xe===0&&(L===0||et===0))return ph;if(ot===0){const st=al($e,L),Gt=st+Math.max(xe-1,0);return WS(yh(st,Gt,re))}const Xe=xh(et,ot,rt);let Ke,tt;Pe?q===0&&ie===0&&xe>0?(Ke=0,tt=xe-1):(Ke=Xe*oi((q+Se)/(Ye+Se)),tt=Xe*mh((ie+Se)/(Ye+Se))-1,tt=gl(L-1,Do(tt,Xe-1)),Ke=gl(tt,Do(0,Ke))):(Ke=0,tt=-1);const _t=yh(Ke,tt,re),{bottom:St,top:nt}=vh(We,ce,U,_t),yt=mh(L/Xe),Nt=yt*Ye+(yt-1)*Se-St;return{bottom:St,itemHeight:Ye,items:_t,itemWidth:ot,offsetBottom:Nt,offsetTop:nt,top:nt}})),j),we(X(O,_e(L=>L!==null),pe(L=>L.length)),S),we(X(Ft(_,P,j,H),_e(([L,q,{items:ie}])=>ie.length>0&&q.height!==0&&L.height!==0),pe(([L,q,{items:ie},ce])=>{const{bottom:U,top:We}=vh(L,ce,q,ie);return[We,U]}),Et(Ao)),t);const je=ee(!1);we(X(c,Ue(je),pe(([L,q])=>q||L!==0)),je);const J=yn(X(Ft(j,S),_e(([{items:L}])=>L.length>0),Ue(je),_e(([[L,q],ie])=>{const ce=L.items[L.items.length-1].index===q-1;return(ie||L.bottom>0&&L.itemHeight>0&&L.offsetBottom===0&&L.items.length===q)&&ce}),pe(([[,L]])=>L-1),Et())),ue=yn(X(Ne(j),_e(({items:L})=>L.length>0&&L[0].index===0),Kn(0),Et())),ke=yn(X(Ne(j),Ue($),_e(([{items:L},q])=>L.length>0&&!q),pe(([{items:L}])=>({endIndex:L[L.length-1].index,startIndex:L[0].index})),Et(Ff),rr(0)));we(ke,p.scrollSeekRangeChanged),we(X(D,Ue(_,P,S,H),pe(([L,q,ie,ce,U])=>{const We=Wf(L),{align:re,behavior:xe,offset:Pe}=We;let $e=We.index;$e==="LAST"&&($e=ce-1),$e=Do(0,$e,gl(ce-1,$e));let rt=yl(q,U,ie,$e);return re==="end"?rt=gh(rt-q.height+ie.height):re==="center"&&(rt=gh(rt-q.height/2+ie.height/2)),Pe&&(rt+=Pe),{behavior:xe,top:rt}})),l);const te=en(X(j,pe(L=>L.offsetBottom+L.bottom)),0);return we(X(T,pe(L=>({height:L.visibleHeight,width:L.visibleWidth}))),_),{customScrollParent:y,data:O,deviation:B,footerHeight:o,gap:H,headerHeight:s,increaseViewportBy:e,initialItemCount:E,itemDimensions:P,overscan:n,restoreStateFrom:V,scrollBy:i,scrollContainerState:a,scrollHeight:z,scrollTo:l,scrollToIndex:D,scrollTop:c,smoothScrollTargetReached:d,totalCount:S,useWindowScroll:x,viewportDimensions:_,windowScrollContainerState:w,windowScrollTo:C,windowViewportRect:T,...p,gridState:j,horizontalDirection:ye,initialTopMostItemIndex:F,totalListHeight:te,...h,endReached:J,propsReady:g,rangeChanged:ke,startReached:ue,stateChanged:R,stateRestoreInProgress:$,...k}},Tt(ll,on,Mo,th,fr,ul,ur));function xh(e,t,n){return Do(1,oi((e+n)/(oi(t)+n)))}function vh(e,t,n,r){const{height:o}=n;if(o===void 0||r.length===0)return{bottom:0,top:0};const s=yl(e,t,n,r[0].index);return{bottom:yl(e,t,n,r[r.length-1].index)+o,top:s}}function yl(e,t,n,r){const o=xh(e.width,n.width,t.column),s=oi(r/o),i=s*n.height+Do(0,s-1)*t.row;return i>0?i+t.row:i}const qS=at(()=>{const e=ee(f=>`Item ${f}`),t=ee({}),n=ee(null),r=ee("virtuoso-grid-item"),o=ee("virtuoso-grid-list"),s=ee(pl),i=ee("div"),a=ee(to),l=(f,h=null)=>en(X(t,pe(p=>p[f]),Et()),h),c=ee(!1),d=ee(!1);return we(Ne(d),c),{components:t,computeItemKey:s,context:n,FooterComponent:l("Footer"),HeaderComponent:l("Header"),headerFooterTag:i,itemClassName:r,ItemComponent:l("Item","div"),itemContent:e,listClassName:o,ListComponent:l("List","div"),readyStateChanged:c,reportReadyState:d,ScrollerComponent:l("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder","div")}}),GS=at(([e,t])=>({...e,...t}),Tt(KS,qS)),YS=b.memo(function(){const e=It("gridState"),t=It("listClassName"),n=It("itemClassName"),r=It("itemContent"),o=It("computeItemKey"),s=It("isSeeking"),i=Tn("scrollHeight"),a=It("ItemComponent"),l=It("ListComponent"),c=It("ScrollSeekPlaceholder"),d=It("context"),f=Tn("itemDimensions"),h=Tn("gap"),p=It("log"),m=It("stateRestoreInProgress"),g=Tn("reportReadyState"),y=Nr(b.useMemo(()=>x=>{const w=x.parentElement.parentElement.scrollHeight;i(w);const C=x.firstChild;if(C){const{height:T,width:k}=C.getBoundingClientRect();f({height:T,width:k})}h({column:bh("column-gap",getComputedStyle(x).columnGap,p),row:bh("row-gap",getComputedStyle(x).rowGap,p)})},[i,f,h,p]),!0,!1);return ah(()=>{e.itemHeight>0&&e.itemWidth>0&&g(!0)},[e]),m?null:u.jsx(l,{className:t,ref:y,...tn(l,d),"data-testid":"virtuoso-item-list",style:{paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},children:e.items.map(x=>{const w=o(x.index,x.data,d);return s?u.jsx(c,{...tn(c,d),height:e.itemHeight,index:x.index,width:e.itemWidth},w):b.createElement(a,{...tn(a,d),className:n,"data-index":x.index,key:w},r(x.index,x.data,d))})})}),XS=b.memo(function(){const e=It("HeaderComponent"),t=Tn("headerHeight"),n=It("headerFooterTag"),r=Nr(b.useMemo(()=>s=>{t(dr(s,"height"))},[t]),!0,!1),o=It("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...tn(e,o)})}):null}),JS=b.memo(function(){const e=It("FooterComponent"),t=Tn("footerHeight"),n=It("headerFooterTag"),r=Nr(b.useMemo(()=>s=>{t(dr(s,"height"))},[t]),!0,!1),o=It("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...tn(e,o)})}):null}),ZS=({children:e})=>{const t=b.useContext(ih),n=Tn("itemDimensions"),r=Tn("viewportDimensions"),o=Nr(b.useMemo(()=>s=>{r(s.getBoundingClientRect())},[r]),!0,!1);return b.useEffect(()=>{t&&(r({height:t.viewportHeight,width:t.viewportWidth}),n({height:t.itemHeight,width:t.itemWidth}))},[t,r,n]),u.jsx("div",{ref:o,style:ri(!1),children:e})},QS=({children:e})=>{const t=b.useContext(ih),n=Tn("windowViewportRect"),r=Tn("itemDimensions"),o=It("customScrollParent"),s=jf(n,o,!1);return b.useEffect(()=>{t&&(r({height:t.itemHeight,width:t.itemWidth}),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:t.viewportWidth}))},[t,n,r]),u.jsx("div",{ref:s,style:ri(!1),children:e})},eC=b.memo(function({...e}){const t=It("useWindowScroll"),n=It("customScrollParent"),r=n||t?nC:tC,o=n||t?QS:ZS,s=It("context");return u.jsx(r,{...e,...tn(r,s),children:u.jsxs(o,{children:[u.jsx(XS,{}),u.jsx(YS,{}),u.jsx(JS,{})]})})}),{useEmitter:wh,useEmitterValue:It,usePublisher:Tn}=oh(GS,{optional:{context:"context",totalCount:"totalCount",overscan:"overscan",itemContent:"itemContent",components:"components",computeItemKey:"computeItemKey",data:"data",initialItemCount:"initialItemCount",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"headerFooterTag",listClassName:"listClassName",itemClassName:"itemClassName",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",restoreStateFrom:"restoreStateFrom",initialTopMostItemIndex:"initialTopMostItemIndex",increaseViewportBy:"increaseViewportBy"},methods:{scrollTo:"scrollTo",scrollBy:"scrollBy",scrollToIndex:"scrollToIndex"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",stateChanged:"stateChanged",readyStateChanged:"readyStateChanged"}},eC),tC=fh({useEmitter:wh,useEmitterValue:It,usePublisher:Tn}),nC=hh({useEmitter:wh,useEmitterValue:It,usePublisher:Tn});function bh(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,dn.WARN),t==="normal"?0:parseInt(t??"0",10)}const rC=Go.cva("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function Sh({className:e,variant:t,...n}){return u.jsx("div",{className:oe(rC({variant:t}),e),...n})}const Lo=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:oe("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));Lo.displayName="Card";const Fo=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:oe("flex flex-col space-y-1.5 p-6",e),...t}));Fo.displayName="CardHeader";const $o=v.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:oe("text-2xl font-semibold leading-none tracking-tight",e),...t}));$o.displayName="CardTitle";const Ch=v.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:oe("text-sm text-muted-foreground",e),...t}));Ch.displayName="CardDescription";const zo=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:oe("p-6 pt-0",e),...t}));zo.displayName="CardContent";const kh=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:oe("flex items-center p-6 pt-0",e),...t}));kh.displayName="CardFooter";const oC=1,sC=1e6;let xl=0;function iC(){return xl=(xl+1)%Number.MAX_SAFE_INTEGER,xl.toString()}const vl=new Map,Th=e=>{if(vl.has(e))return;const t=setTimeout(()=>{vl.delete(e),Bo({type:"REMOVE_TOAST",toastId:e})},sC);vl.set(e,t)},aC=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,oC)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?Th(n):e.toasts.forEach(r=>{Th(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},ii=[];let ai={toasts:[]};function Bo(e){ai=aC(ai,e),ii.forEach(t=>{t(ai)})}function lC({...e}){const t=iC(),n=o=>Bo({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Bo({type:"DISMISS_TOAST",toastId:t});return Bo({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function wl(){const[e,t]=v.useState(ai);return v.useEffect(()=>(ii.push(t),()=>{const n=ii.indexOf(t);n>-1&&ii.splice(n,1)}),[e]),{...e,toast:lC,dismiss:n=>Bo({type:"DISMISS_TOAST",toastId:n})}}async function Eh(e,t){return await wn(e,{responseType:"blob",onDownloadProgress:r=>{try{t&&r.lengthComputable}catch{}},maxBodyLength:1/0})}async function Ih(e,t){return await(await Eh(`/files/${e}/view`,t)).text()}async function cC(e,t){const n=await Eh(`/files/${e}/download`,t),r=URL.createObjectURL(n);let o=`file_${e}`;try{const i=await wn(`/files/${e}`);o=(i==null?void 0:i.filename)??o}catch{}const s=document.createElement("a");s.href=r,s.download=o,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}async function uC(e,t=50,n=0){const r={limit:t,offset:n};return e&&(r.thread_id=e),await wn("/files",{params:r})}function bl(e){const t=e==null?void 0:e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return null;try{return JSON.parse(t)}catch{return null}}function Nh(e){return!!(e&&typeof e=="object"&&(e.type==="file"||e.mimeType||e.filename||e.sourceType==="base64"))}function Ho(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){if(Array.isArray(e)){const n=e.map(Ho).filter(r=>r!==void 0);if(!n.length){console.debug("[message-utils] sanitizeForDisplay - array emptied -> returning undefined",{originalLength:e.length});return}return n}if(Nh(e)){try{console.debug("[message-utils] sanitizeForDisplay - dropping file-like object",{sampleFilename:e&&(e.filename||e.name)?e.filename||e.name:void 0,keys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - dropped file-like (unable to inspect)",{err:String(n)})}return}const t={};for(const n of Object.keys(e)){const r=e[n];if(n==="data"&&typeof r=="string"&&r.length>100)t[n]=`[base64 ${r.length} chars omitted]`;else{const o=Ho(r);o!==void 0&&(t[n]=o)}}if(Object.keys(t).length)return t;try{console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined",{originalKeys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined (inspect failed)",{err:String(n)})}return}return e}function Uo(e){if(typeof e=="string")return e;if(Nh(e))return"";try{const t=Ho(e);return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}catch{return""}}function dC(e){return typeof e!="string"?!1:/^[\s\n]*[-*]\s|^[\s\n]*#+\s|```|^\s*\[.*\]\(|^>\s/.test(e)}function fC(e){const t=Uo(e);return typeof e=="string"&&dC(e)?{content:e,isMarkdown:!0}:{content:t,isMarkdown:!1}}function li(e){if(e==null)return e;if(typeof e=="string"){const t=e.trim();if(t.startsWith("{")||t.startsWith("[")){const n=bl(t);if(n!==null)return li(n)}return e}return typeof e=="object"&&!Array.isArray(e)&&e.content!==void 0?li(e.content):e}var ci="Dialog",[Ah,UT]=Qn(ci),[hC,Mn]=Ah(ci),_h=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:s,modal:i=!0}=e,a=v.useRef(null),l=v.useRef(null),[c,d]=Vr({prop:r,defaultProp:o??!1,onChange:s,caller:ci});return u.jsx(hC,{scope:t,triggerRef:a,contentRef:l,contentId:er(),titleId:er(),descriptionId:er(),open:c,onOpenChange:d,onOpenToggle:v.useCallback(()=>d(f=>!f),[d]),modal:i,children:n})};_h.displayName=ci;var jh="DialogTrigger",Ph=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Mn(jh,n),s=Ze(t,o.triggerRef);return u.jsx(De.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":kl(o.open),...r,ref:s,onClick:ge(e.onClick,o.onOpenToggle)})});Ph.displayName=jh;var Sl="DialogPortal",[pC,Rh]=Ah(Sl,{forceMount:void 0}),Oh=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,s=Mn(Sl,t);return u.jsx(pC,{scope:t,forceMount:n,children:v.Children.map(r,i=>u.jsx(Sn,{present:n||s.open,children:u.jsx(js,{asChild:!0,container:o,children:i})}))})};Oh.displayName=Sl;var ui="DialogOverlay",Mh=v.forwardRef((e,t)=>{const n=Rh(ui,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=Mn(ui,e.__scopeDialog);return s.modal?u.jsx(Sn,{present:r||s.open,children:u.jsx(gC,{...o,ref:t})}):null});Mh.displayName=ui;var mC=vr.createSlot("DialogOverlay.RemoveScroll"),gC=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Mn(ui,n);return u.jsx(zs,{as:mC,allowPinchZoom:!0,shards:[o.contentRef],children:u.jsx(De.div,{"data-state":kl(o.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),jr="DialogContent",Dh=v.forwardRef((e,t)=>{const n=Rh(jr,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=Mn(jr,e.__scopeDialog);return u.jsx(Sn,{present:r||s.open,children:s.modal?u.jsx(yC,{...o,ref:t}):u.jsx(xC,{...o,ref:t})})});Dh.displayName=jr;var yC=v.forwardRef((e,t)=>{const n=Mn(jr,e.__scopeDialog),r=v.useRef(null),o=Ze(t,n.contentRef,r);return v.useEffect(()=>{const s=r.current;if(s)return Ma(s)},[]),u.jsx(Lh,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ge(e.onCloseAutoFocus,s=>{var i;s.preventDefault(),(i=n.triggerRef.current)==null||i.focus()}),onPointerDownOutside:ge(e.onPointerDownOutside,s=>{const i=s.detail.originalEvent,a=i.button===0&&i.ctrlKey===!0;(i.button===2||a)&&s.preventDefault()}),onFocusOutside:ge(e.onFocusOutside,s=>s.preventDefault())})}),xC=v.forwardRef((e,t)=>{const n=Mn(jr,e.__scopeDialog),r=v.useRef(!1),o=v.useRef(!1);return u.jsx(Lh,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var i,a;(i=e.onCloseAutoFocus)==null||i.call(e,s),s.defaultPrevented||(r.current||(a=n.triggerRef.current)==null||a.focus(),s.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:s=>{var l,c;(l=e.onInteractOutside)==null||l.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const i=s.target;((c=n.triggerRef.current)==null?void 0:c.contains(i))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})}),Lh=v.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:s,...i}=e,a=Mn(jr,n),l=v.useRef(null),c=Ze(t,l);return ga(),u.jsxs(u.Fragment,{children:[u.jsx(vs,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:s,children:u.jsx(xs,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":kl(a.open),...i,ref:c,onDismiss:()=>a.onOpenChange(!1)})}),u.jsxs(u.Fragment,{children:[u.jsx(vC,{titleId:a.titleId}),u.jsx(bC,{contentRef:l,descriptionId:a.descriptionId})]})]})}),Cl="DialogTitle",Fh=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Mn(Cl,n);return u.jsx(De.h2,{id:o.titleId,...r,ref:t})});Fh.displayName=Cl;var $h="DialogDescription",zh=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Mn($h,n);return u.jsx(De.p,{id:o.descriptionId,...r,ref:t})});zh.displayName=$h;var Bh="DialogClose",Hh=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Mn(Bh,n);return u.jsx(De.button,{type:"button",...r,ref:t,onClick:ge(e.onClick,()=>o.onOpenChange(!1))})});Hh.displayName=Bh;function kl(e){return e?"open":"closed"}var Uh="DialogTitleWarning",[WT,Wh]=kx(Uh,{contentName:jr,titleName:Cl,docsSlug:"dialog"}),vC=({titleId:e})=>{const t=Wh(Uh),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
|
|
86
|
+
`).trim():n.replace(/</g,"<").replace(/>/g,">").trim()}function j0(e,t=Ks){if(!e||typeof e!="string")throw new Error("Invalid content: must be a non-empty string");if(e.length>t)throw new Error(`Message exceeds maximum length of ${t} characters`);return e}function P0(e){let t;return typeof e=="string"?t=e:typeof e=="object"&&e!==null?t=JSON.stringify(e):t=String(e),j0(t),_0(t)}const qs=0,cr=1,eo=2,kf=4;function Tf(e){return()=>e}function R0(e){e()}function Ef(e,t){return n=>e(t(n))}function If(e,t){return()=>e(t)}function O0(e,t){return n=>e(t,n)}function Ya(e){return e!==void 0}function M0(...e){return()=>{e.map(R0)}}function to(){}function Gs(e,t){return t(e),e}function D0(e,t){return t(e)}function Tt(...e){return e}function dt(e,t){return e(cr,t)}function ze(e,t){e(qs,t)}function Xa(e){e(eo)}function Rt(e){return e(kf)}function we(e,t){return dt(e,O0(t,qs))}function Rn(e,t){const n=e(cr,r=>{n(),t(r)});return n}function Nf(e){let t,n;return r=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{r(t)},e)}}function Af(e,t){return e===t}function Et(e=Af){let t;return n=>r=>{e(t,r)||(t=r,n(r))}}function _e(e){return t=>n=>{e(n)&&t(n)}}function pe(e){return t=>Ef(t,e)}function Kn(e){return t=>()=>{t(e)}}function X(e,...t){const n=L0(...t);return(r,o)=>{switch(r){case eo:Xa(e);return;case cr:return dt(e,n(o))}}}function qn(e,t){return n=>r=>{n(t=e(t,r))}}function Ir(e){return t=>n=>{e>0?e--:t(n)}}function rr(e){let t=null,n;return r=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,r(t)},e))}}function Ue(...e){const t=new Array(e.length);let n=0,r=null;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);dt(s,l=>{const c=n;n=n|a,t[i]=l,c!==o&&n===o&&r&&(r(),r=null)})}),s=>i=>{const a=()=>{s([i].concat(t))};n===o?a():r=a}}function L0(...e){return t=>e.reduceRight(D0,t)}function F0(e){let t,n;const r=()=>t==null?void 0:t();return function(o,s){switch(o){case cr:return s?n===s?void 0:(r(),n=s,t=dt(e,s),t):(r(),to);case eo:r(),n=null;return}}}function ee(e){let t=e;const n=Qe();return(r,o)=>{switch(r){case qs:t=o;break;case cr:{o(t);break}case kf:return t}return n(r,o)}}function en(e,t){return Gs(ee(t),n=>we(e,n))}function Qe(){const e=[];return(t,n)=>{switch(t){case qs:e.slice().forEach(r=>{r(n)});return;case eo:e.splice(0,e.length);return;case cr:return e.push(n),()=>{const r=e.indexOf(n);r>-1&&e.splice(r,1)}}}}function yn(e){return Gs(Qe(),t=>we(e,t))}function at(e,t=[],{singleton:n}={singleton:!0}){return{constructor:e,dependencies:t,id:$0(),singleton:n}}const $0=()=>Symbol();function z0(e){const t=new Map,n=({constructor:r,dependencies:o,id:s,singleton:i})=>{if(i&&t.has(s))return t.get(s);const a=r(o.map(l=>n(l)));return i&&t.set(s,a),a};return n(e)}function Ft(...e){const t=Qe(),n=new Array(e.length);let r=0;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);dt(s,l=>{n[i]=l,r=r|a,r===o&&ze(t,n)})}),function(s,i){switch(s){case eo:{Xa(t);return}case cr:return r===o&&i(n),dt(t,i)}}}function Ne(e,t=Af){return X(e,Et(t))}function Ja(...e){return function(t,n){switch(t){case eo:return;case cr:return M0(...e.map(r=>dt(r,n)))}}}var dn=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(dn||{});const B0={0:"debug",3:"error",1:"log",2:"warn"},H0=()=>typeof globalThis>"u"?window:globalThis,ur=at(()=>{const e=ee(3);return{log:ee((t,n,r=1)=>{var o;const s=(o=H0().VIRTUOSO_LOG_LEVEL)!=null?o:Rt(e);r>=s&&console[B0[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function Nr(e,t,n){return Za(e,t,n).callbackRef}function Za(e,t,n){const r=b.useRef(null);let o=i=>{};const s=b.useMemo(()=>typeof ResizeObserver<"u"?new ResizeObserver(i=>{const a=()=>{const l=i[0].target;l.offsetParent!==null&&e(l)};n?a():requestAnimationFrame(a)}):null,[e,n]);return o=i=>{i&&t?(s==null||s.observe(i),r.current=i):(r.current&&(s==null||s.unobserve(r.current)),r.current=null)},{callbackRef:o,ref:r}}function U0(e,t,n,r,o,s,i,a,l){const c=b.useCallback(d=>{const f=W0(d.children,t,a?"offsetWidth":"offsetHeight",o);let h=d.parentElement;for(;!h.dataset.virtuosoScroller;)h=h.parentElement;const p=h.lastElementChild.dataset.viewportType==="window";let m;p&&(m=h.ownerDocument.defaultView);const g=i?a?i.scrollLeft:i.scrollTop:p?a?m.scrollX||m.document.documentElement.scrollLeft:m.scrollY||m.document.documentElement.scrollTop:a?h.scrollLeft:h.scrollTop,y=i?a?i.scrollWidth:i.scrollHeight:p?a?m.document.documentElement.scrollWidth:m.document.documentElement.scrollHeight:a?h.scrollWidth:h.scrollHeight,x=i?a?i.offsetWidth:i.offsetHeight:p?a?m.innerWidth:m.innerHeight:a?h.offsetWidth:h.offsetHeight;r({scrollHeight:y,scrollTop:Math.max(g,0),viewportHeight:x}),s==null||s(a?_f("column-gap",getComputedStyle(d).columnGap,o):_f("row-gap",getComputedStyle(d).rowGap,o)),f!==null&&e(f)},[e,t,o,s,i,r,a]);return Za(c,n,l)}function W0(e,t,n,r){const o=e.length;if(o===0)return null;const s=[];for(let i=0;i<o;i++){const a=e.item(i);if(a.dataset.index===void 0)continue;const l=parseInt(a.dataset.index),c=parseFloat(a.dataset.knownSize),d=t(a,n);if(d===0&&r("Zero-sized element, this should not happen",{child:a},dn.ERROR),d===c)continue;const f=s[s.length-1];s.length===0||f.size!==d||f.endIndex!==l-1?s.push({endIndex:l,size:d,startIndex:l}):s[s.length-1].endIndex++}return s}function _f(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,dn.WARN),t==="normal"?0:parseInt(t??"0",10)}function jf(e,t,n){const r=b.useRef(null),o=b.useCallback(l=>{if(!(l!=null&&l.offsetParent))return;const c=l.getBoundingClientRect(),d=c.width;let f,h;if(t){const p=t.getBoundingClientRect(),m=c.top-p.top;h=p.height-Math.max(0,m),f=m+t.scrollTop}else{const p=i.current.ownerDocument.defaultView;h=p.innerHeight-Math.max(0,c.top),f=c.top+p.scrollY}r.current={offsetTop:f,visibleHeight:h,visibleWidth:d},e(r.current)},[e,t]),{callbackRef:s,ref:i}=Za(o,!0,n),a=b.useCallback(()=>{o(i.current)},[o,i]);return b.useEffect(()=>{var l;if(t){t.addEventListener("scroll",a);const c=new ResizeObserver(()=>{requestAnimationFrame(a)});return c.observe(t),()=>{t.removeEventListener("scroll",a),c.unobserve(t)}}else{const c=(l=i.current)==null?void 0:l.ownerDocument.defaultView;return c==null||c.addEventListener("scroll",a),c==null||c.addEventListener("resize",a),()=>{c==null||c.removeEventListener("scroll",a),c==null||c.removeEventListener("resize",a)}}},[a,t,i]),s}const on=at(()=>{const e=Qe(),t=Qe(),n=ee(0),r=Qe(),o=ee(0),s=Qe(),i=Qe(),a=ee(0),l=ee(0),c=ee(0),d=ee(0),f=Qe(),h=Qe(),p=ee(!1),m=ee(!1),g=ee(!1);return we(X(e,pe(({scrollTop:y})=>y)),t),we(X(e,pe(({scrollHeight:y})=>y)),i),we(t,o),{deviation:n,fixedFooterHeight:c,fixedHeaderHeight:l,footerHeight:d,headerHeight:a,horizontalDirection:m,scrollBy:h,scrollContainerState:e,scrollHeight:i,scrollingInProgress:p,scrollTo:f,scrollTop:t,skipAnimationFrameInResizeObserver:g,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:s}},[],{singleton:!0}),Io={lvl:0};function Pf(e,t){const n=e.length;if(n===0)return[];let{index:r,value:o}=t(e[0]);const s=[];for(let i=1;i<n;i++){const{index:a,value:l}=t(e[i]);s.push({end:a-1,start:r,value:o}),r=a,o=l}return s.push({end:1/0,start:r,value:o}),s}function vt(e){return e===Io}function No(e,t){if(!vt(e))return t===e.k?e.v:t<e.k?No(e.l,t):No(e.r,t)}function On(e,t,n="k"){if(vt(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const r=On(e.r,t,n);return r[0]===-1/0?[e.k,e.v]:r}return On(e.l,t,n)}function xn(e,t,n){return vt(e)?Mf(t,n,1):t===e.k?$t(e,{k:t,v:n}):t<e.k?Df($t(e,{l:xn(e.l,t,n)})):Df($t(e,{r:xn(e.r,t,n)}))}function no(){return Io}function Ys(e,t,n){if(vt(e))return[];const r=On(e,t)[0];return V0(el(e,r,n))}function Qa(e,t){if(vt(e))return Io;const{k:n,l:r,r:o}=e;if(t===n){if(vt(r))return o;if(vt(o))return r;{const[s,i]=Of(r);return Xs($t(e,{k:s,l:Rf(r),v:i}))}}else return t<n?Xs($t(e,{l:Qa(r,t)})):Xs($t(e,{r:Qa(o,t)}))}function Ar(e){return vt(e)?[]:[...Ar(e.l),{k:e.k,v:e.v},...Ar(e.r)]}function el(e,t,n){if(vt(e))return[];const{k:r,l:o,r:s,v:i}=e;let a=[];return r>t&&(a=a.concat(el(o,t,n))),r>=t&&r<=n&&a.push({k:r,v:i}),r<=n&&(a=a.concat(el(s,t,n))),a}function Xs(e){const{l:t,lvl:n,r}=e;if(r.lvl>=n-1&&t.lvl>=n-1)return e;if(n>r.lvl+1){if(tl(t))return Lf($t(e,{lvl:n-1}));if(!vt(t)&&!vt(t.r))return $t(t.r,{l:$t(t,{r:t.r.l}),lvl:n,r:$t(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}else{if(tl(e))return nl($t(e,{lvl:n-1}));if(!vt(r)&&!vt(r.l)){const o=r.l,s=tl(o)?r.lvl-1:r.lvl;return $t(o,{l:$t(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:nl($t(r,{l:o.r,lvl:s}))})}else throw new Error("Unexpected empty nodes")}}function $t(e,t){return Mf(t.k!==void 0?t.k:e.k,t.v!==void 0?t.v:e.v,t.lvl!==void 0?t.lvl:e.lvl,t.l!==void 0?t.l:e.l,t.r!==void 0?t.r:e.r)}function Rf(e){return vt(e.r)?e.l:Xs($t(e,{r:Rf(e.r)}))}function tl(e){return vt(e)||e.lvl>e.r.lvl}function Of(e){return vt(e.r)?[e.k,e.v]:Of(e.r)}function Mf(e,t,n,r=Io,o=Io){return{k:e,l:r,lvl:n,r:o,v:t}}function Df(e){return nl(Lf(e))}function Lf(e){const{l:t}=e;return!vt(t)&&t.lvl===e.lvl?$t(t,{r:$t(e,{l:t.r})}):e}function nl(e){const{lvl:t,r:n}=e;return!vt(n)&&!vt(n.r)&&n.lvl===t&&n.r.lvl===t?$t(n,{l:$t(e,{r:n.l}),lvl:t+1}):e}function V0(e){return Pf(e,({k:t,v:n})=>({index:t,value:n}))}function Ff(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}function Ao(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}const rl=at(()=>({recalcInProgress:ee(!1)}),[],{singleton:!0});function $f(e,t,n){return e[Js(e,t,n)]}function Js(e,t,n,r=0){let o=e.length-1;for(;r<=o;){const s=Math.floor((r+o)/2),i=e[s],a=n(i,t);if(a===0)return s;if(a===-1){if(o-r<2)return s-1;o=s-1}else{if(o===r)return s;r=s+1}}throw new Error(`Failed binary finding record in array - ${e.join(",")}, searched for ${t}`)}function K0(e,t,n,r){const o=Js(e,t,r),s=Js(e,n,r,o);return e.slice(o,s+1)}function dr(e,t){return Math.round(e.getBoundingClientRect()[t])}function Zs(e){return!vt(e.groupOffsetTree)}function ol({index:e},t){return t===e?0:t<e?-1:1}function q0(){return{groupIndices:[],groupOffsetTree:no(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:no()}}function G0(e,t){let n=vt(e)?0:1/0;for(const r of t){const{endIndex:o,size:s,startIndex:i}=r;if(n=Math.min(n,i),vt(e)){e=xn(e,0,s);continue}const a=Ys(e,i-1,o+1);if(a.some(tS(r)))continue;let l=!1,c=!1;for(const{end:d,start:f,value:h}of a)l?(o>=f||s===h)&&(e=Qa(e,f)):(c=h!==s,l=!0),d>o&&o>=f&&h!==s&&(e=xn(e,o+1,h));c&&(e=xn(e,i,s))}return[e,n]}function Y0(e){return typeof e.groupIndex<"u"}function X0({offset:e},t){return t===e?0:t<e?-1:1}function _o(e,t,n){if(t.length===0)return 0;const{index:r,offset:o,size:s}=$f(t,e,ol),i=e-r,a=s*i+(i-1)*n+o;return a>0?a+n:a}function zf(e,t){if(!Zs(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function Bf(e,t,n){if(Y0(e))return t.groupIndices[e.groupIndex]+1;{const r=e.index==="LAST"?n:e.index;let o=zf(r,t);return o=Math.max(0,o,Math.min(n,o)),o}}function J0(e,t,n,r=0){return r>0&&(t=Math.max(t,$f(e,r,ol).offset)),Pf(K0(e,t,n,X0),eS)}function Z0(e,[t,n,r,o]){t.length>0&&r("received item sizes",t,dn.DEBUG);const s=e.sizeTree;let i=s,a=0;if(n.length>0&&vt(s)&&t.length===2){const h=t[0].size,p=t[1].size;i=n.reduce((m,g)=>xn(xn(m,g,h),g+1,p),i)}else[i,a]=G0(i,t);if(i===s)return e;const{lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f}=sl(e.offsetTree,a,i,o);return{groupIndices:n,groupOffsetTree:n.reduce((h,p)=>xn(h,p,_o(p,f,o)),no()),lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f,sizeTree:i}}function Q0(e){return Ar(e).map(({k:t,v:n},r,o)=>{const s=o[r+1];return{endIndex:s?s.k-1:1/0,size:n,startIndex:t}})}function Hf(e,t){let n=0,r=0;for(;n<e;)n+=t[r+1]-t[r]-1,r++;return r-(n===e?0:1)}function sl(e,t,n,r){let o=e,s=0,i=0,a=0,l=0;if(t!==0){l=Js(o,t-1,ol),a=o[l].offset;const c=On(n,t-1);s=c[0],i=c[1],o.length&&o[l].size===On(n,t)[1]&&(l-=1),o=o.slice(0,l+1)}else o=[];for(const{start:c,value:d}of Ys(n,t,1/0)){const f=c-s,h=f*i+a+f*r;o.push({index:c,offset:h,size:d}),s=c,a=h,i=d}return{lastIndex:s,lastOffset:a,lastSize:i,offsetTree:o}}function eS(e){return{index:e.index,value:e}}function tS(e){const{endIndex:t,size:n,startIndex:r}=e;return o=>o.start===r&&(o.end===t||o.end===1/0)&&o.value===n}const nS={offsetHeight:"height",offsetWidth:"width"},Gn=at(([{log:e},{recalcInProgress:t}])=>{const n=Qe(),r=Qe(),o=en(r,0),s=Qe(),i=Qe(),a=ee(0),l=ee([]),c=ee(void 0),d=ee(void 0),f=ee((k,S)=>dr(k,nS[S])),h=ee(void 0),p=ee(0),m=q0(),g=en(X(n,Ue(l,e,p),qn(Z0,m),Et()),m),y=en(X(l,Et(),qn((k,S)=>({current:S,prev:k.current}),{current:[],prev:[]}),pe(({prev:k})=>k)),[]);we(X(l,_e(k=>k.length>0),Ue(g,p),pe(([k,S,E])=>{const j=k.reduce((_,P,D)=>xn(_,P,_o(P,S.offsetTree,E)||D),no());return{...S,groupIndices:k,groupOffsetTree:j}})),g),we(X(r,Ue(g),_e(([k,{lastIndex:S}])=>k<S),pe(([k,{lastIndex:S,lastSize:E}])=>[{endIndex:S,size:E,startIndex:k}])),n),we(c,d);const x=en(X(c,pe(k=>k===void 0)),!0);we(X(d,_e(k=>k!==void 0&&vt(Rt(g).sizeTree)),pe(k=>[{endIndex:0,size:k,startIndex:0}])),n);const w=yn(X(n,Ue(g),qn(({sizes:k},[S,E])=>({changed:E!==k,sizes:E}),{changed:!1,sizes:m}),pe(k=>k.changed)));dt(X(a,qn((k,S)=>({diff:k.prev-S,prev:S}),{diff:0,prev:0}),pe(k=>k.diff)),k=>{const{groupIndices:S}=Rt(g);if(k>0)ze(t,!0),ze(s,k+Hf(k,S));else if(k<0){const E=Rt(y);E.length>0&&(k-=Hf(-k,E)),ze(i,k)}}),dt(X(a,Ue(e)),([k,S])=>{k<0&&S("`firstItemIndex` prop should not be set to less than zero. If you don't know the total count, just use a very high value",{firstItemIndex:a},dn.ERROR)});const C=yn(s);we(X(s,Ue(g),pe(([k,S])=>{const E=S.groupIndices.length>0,j=[],_=S.lastSize;if(E){const P=No(S.sizeTree,0);let D=0,z=0;for(;D<k;){const O=S.groupIndices[z],H=S.groupIndices.length===z+1?1/0:S.groupIndices[z+1]-O-1;j.push({endIndex:O,size:P,startIndex:O}),j.push({endIndex:O+1+H-1,size:_,startIndex:O+1}),z++,D+=H+1}const B=Ar(S.sizeTree);return D!==k&&B.shift(),B.reduce((O,{k:H,v:R})=>{let V=O.ranges;return O.prevSize!==0&&(V=[...O.ranges,{endIndex:H+k-1,size:O.prevSize,startIndex:O.prevIndex}]),{prevIndex:H+k,prevSize:R,ranges:V}},{prevIndex:k,prevSize:0,ranges:j}).ranges}return Ar(S.sizeTree).reduce((P,{k:D,v:z})=>({prevIndex:D+k,prevSize:z,ranges:[...P.ranges,{endIndex:D+k-1,size:P.prevSize,startIndex:P.prevIndex}]}),{prevIndex:0,prevSize:_,ranges:[]}).ranges})),n);const T=yn(X(i,Ue(g,p),pe(([k,{offsetTree:S},E])=>{const j=-k;return _o(j,S,E)})));return we(X(i,Ue(g,p),pe(([k,S,E])=>{if(S.groupIndices.length>0){if(vt(S.sizeTree))return S;let j=no();const _=Rt(y);let P=0,D=0,z=0;for(;P<-k;){z=_[D];const B=_[D+1]-z-1;D++,P+=B+1}if(j=Ar(S.sizeTree).reduce((B,{k:O,v:H})=>xn(B,Math.max(0,O+k),H),j),P!==-k){const B=No(S.sizeTree,z);j=xn(j,0,B);const O=On(S.sizeTree,-k+1)[1];j=xn(j,1,O)}return{...S,sizeTree:j,...sl(S.offsetTree,0,j,E)}}else{const j=Ar(S.sizeTree).reduce((_,{k:P,v:D})=>xn(_,Math.max(0,P+k),D),no());return{...S,sizeTree:j,...sl(S.offsetTree,0,j,E)}}})),g),{beforeUnshiftWith:C,data:h,defaultItemSize:d,firstItemIndex:a,fixedItemSize:c,gap:p,groupIndices:l,itemSize:f,listRefresh:w,shiftWith:i,shiftWithOffset:T,sizeRanges:n,sizes:g,statefulTotalCount:o,totalCount:r,trackItemSizes:x,unshiftWith:s}},Tt(ur,rl),{singleton:!0});function rS(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const Uf=at(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:r,scrollTop:o}])=>{const s=Qe(),i=Qe(),a=yn(X(s,pe(rS)));return we(X(a,pe(l=>l.totalCount)),n),we(X(a,pe(l=>l.groupIndices)),e),we(X(Ft(o,t,r),_e(([l,c])=>Zs(c)),pe(([l,c,d])=>On(c.groupOffsetTree,Math.max(l-d,0),"v")[0]),Et(),pe(l=>[l])),i),{groupCounts:s,topItemsIndexes:i}},Tt(Gn,on)),fr=at(([{log:e}])=>{const t=ee(!1),n=yn(X(t,_e(r=>r),Et()));return dt(t,r=>{r&&Rt(e)("props updated",{},dn.DEBUG)}),{didMount:n,propsReady:t}},Tt(ur),{singleton:!0}),oS=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function Wf(e){const t=typeof e=="number"?{index:e}:e;return t.align||(t.align="start"),(!t.behavior||!oS)&&(t.behavior="auto"),t.offset||(t.offset=0),t}const jo=at(([{gap:e,listRefresh:t,sizes:n,totalCount:r},{fixedFooterHeight:o,fixedHeaderHeight:s,footerHeight:i,headerHeight:a,scrollingInProgress:l,scrollTo:c,smoothScrollTargetReached:d,viewportHeight:f},{log:h}])=>{const p=Qe(),m=Qe(),g=ee(0);let y=null,x=null,w=null;function C(){y&&(y(),y=null),w&&(w(),w=null),x&&(clearTimeout(x),x=null),ze(l,!1)}return we(X(p,Ue(n,f,r,g,a,i,h),Ue(e,s,o),pe(([[T,k,S,E,j,_,P,D],z,B,O])=>{const H=Wf(T),{align:R,behavior:V,offset:$}=H,F=E-1,ne=Bf(H,k,F);let Q=_o(ne,k.offsetTree,z)+_;R==="end"?(Q+=B+On(k.sizeTree,ne)[1]-S+O,ne===F&&(Q+=P)):R==="center"?Q+=(B+On(k.sizeTree,ne)[1]-S+O)/2:Q-=j,$&&(Q+=$);const ye=je=>{C(),je?(D("retrying to scroll to",{location:T},dn.DEBUG),ze(p,T)):(ze(m,!0),D("list did not change, scroll successful",{},dn.DEBUG))};if(C(),V==="smooth"){let je=!1;w=dt(t,J=>{je=je||J}),y=Rn(d,()=>{ye(je)})}else y=Rn(X(t,sS(150)),ye);return x=setTimeout(()=>{C()},1200),ze(l,!0),D("scrolling from index to",{behavior:V,index:ne,top:Q},dn.DEBUG),{behavior:V,top:Q}})),c),{scrollTargetReached:m,scrollToIndex:p,topListHeight:g}},Tt(Gn,on,ur),{singleton:!0});function sS(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return r=>{r&&(t(!0),clearTimeout(n))}}}function il(e,t){e==0?t():requestAnimationFrame(()=>{il(e-1,t)})}function al(e,t){const n=t-1;return typeof e=="number"?e:e.index==="LAST"?n:e.index}const Po=at(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:r},{scrollTargetReached:o,scrollToIndex:s},{didMount:i}])=>{const a=ee(!0),l=ee(0),c=ee(!0);return we(X(i,Ue(l),_e(([d,f])=>!!f),Kn(!1)),a),we(X(i,Ue(l),_e(([d,f])=>!!f),Kn(!1)),c),dt(X(Ft(t,i),Ue(a,n,e,c),_e(([[,d],f,{sizeTree:h},p,m])=>d&&(!vt(h)||Ya(p))&&!f&&!m),Ue(l)),([,d])=>{Rn(o,()=>{ze(c,!0)}),il(4,()=>{Rn(r,()=>{ze(a,!0)}),ze(s,d)})}),{initialItemFinalLocationReached:c,initialTopMostItemIndex:l,scrolledToInitialItem:a}},Tt(Gn,on,jo,fr),{singleton:!0});function Vf(e,t){return Math.abs(e-t)<1.01}const Ro="up",Oo="down",iS="none",aS={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},lS=0,Mo=at(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:r,scrollTop:o,viewportHeight:s}])=>{const i=ee(!1),a=ee(!0),l=Qe(),c=Qe(),d=ee(4),f=ee(lS),h=en(X(Ja(X(Ne(o),Ir(1),Kn(!0)),X(Ne(o),Ir(1),Kn(!1),Nf(100))),Et()),!1),p=en(X(Ja(X(n,Kn(!0)),X(n,Kn(!1),Nf(200))),Et()),!1);we(X(Ft(Ne(o),Ne(f)),pe(([w,C])=>w<=C),Et()),a),we(X(a,rr(50)),c);const m=yn(X(Ft(r,Ne(s),Ne(t),Ne(e),Ne(d)),qn((w,[{scrollHeight:C,scrollTop:T},k,S,E,j])=>{const _=T+k-C>-j,P={scrollHeight:C,scrollTop:T,viewportHeight:k};if(_){let z,B;return T>w.state.scrollTop?(z="SCROLLED_DOWN",B=w.state.scrollTop-T):(z="SIZE_DECREASED",B=w.state.scrollTop-T||w.scrollTopDelta),{atBottom:!0,atBottomBecause:z,scrollTopDelta:B,state:P}}let D;return P.scrollHeight>w.state.scrollHeight?D="SIZE_INCREASED":k<w.state.viewportHeight?D="VIEWPORT_HEIGHT_DECREASING":T<w.state.scrollTop?D="SCROLLING_UPWARDS":D="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:D,state:P}},aS),Et((w,C)=>w&&w.atBottom===C.atBottom))),g=en(X(r,qn((w,{scrollHeight:C,scrollTop:T,viewportHeight:k})=>{if(Vf(w.scrollHeight,C))return{changed:!1,jump:0,scrollHeight:C,scrollTop:T};{const S=C-(T+k)<1;return w.scrollTop!==T&&S?{changed:!0,jump:w.scrollTop-T,scrollHeight:C,scrollTop:T}:{changed:!0,jump:0,scrollHeight:C,scrollTop:T}}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),_e(w=>w.changed),pe(w=>w.jump)),0);we(X(m,pe(w=>w.atBottom)),i),we(X(i,rr(50)),l);const y=ee(Oo);we(X(r,pe(({scrollTop:w})=>w),Et(),qn((w,C)=>Rt(p)?{direction:w.direction,prevScrollTop:C}:{direction:C<w.prevScrollTop?Ro:Oo,prevScrollTop:C},{direction:Oo,prevScrollTop:0}),pe(w=>w.direction)),y),we(X(r,rr(50),Kn(iS)),y);const x=ee(0);return we(X(h,_e(w=>!w),Kn(0)),x),we(X(o,rr(100),Ue(h),_e(([w,C])=>!!C),qn(([w,C],[T])=>[C,T],[0,0]),pe(([w,C])=>C-w)),x),{atBottomState:m,atBottomStateChange:l,atBottomThreshold:d,atTopStateChange:c,atTopThreshold:f,isAtBottom:i,isAtTop:a,isScrolling:h,lastJumpDueToItemResize:g,scrollDirection:y,scrollVelocity:x}},Tt(on)),Qs="top",ei="bottom",Kf="none";function qf(e,t,n){return typeof e=="number"?n===Ro&&t===Qs||n===Oo&&t===ei?e:0:n===Ro?t===Qs?e.main:e.reverse:t===ei?e.main:e.reverse}function Gf(e,t){var n;return typeof e=="number"?e:(n=e[t])!=null?n:0}const ll=at(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:r,viewportHeight:o}])=>{const s=Qe(),i=ee(0),a=ee(0),l=ee(0),c=en(X(Ft(Ne(r),Ne(o),Ne(n),Ne(s,Ao),Ne(l),Ne(i),Ne(t),Ne(e),Ne(a)),pe(([d,f,h,[p,m],g,y,x,w,C])=>{const T=d-w,k=y+x,S=Math.max(h-T,0);let E=Kf;const j=Gf(C,Qs),_=Gf(C,ei);return p-=w,p+=h+x,m+=h+x,m-=w,p>d+k-j&&(E=Ro),m<d-S+f+_&&(E=Oo),E!==Kf?[Math.max(T-h-qf(g,Qs,E)-j,0),T-S-x+f+qf(g,ei,E)+_]:null}),_e(d=>d!=null),Et(Ao)),[0,0]);return{increaseViewportBy:a,listBoundary:s,overscan:l,topListHeight:i,visibleRange:c}},Tt(on),{singleton:!0});function cS(e,t,n){if(Zs(t)){const r=zf(e,t);return[{index:On(t.groupOffsetTree,r)[0],offset:0,size:0},{data:n==null?void 0:n[0],index:r,offset:0,size:0}]}return[{data:n==null?void 0:n[0],index:e,offset:0,size:0}]}const cl={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function ti(e,t,n,r,o,s){const{lastIndex:i,lastOffset:a,lastSize:l}=o;let c=0,d=0;if(e.length>0){c=e[0].offset;const g=e[e.length-1];d=g.offset+g.size}const f=n-i,h=a+f*l+(f-1)*r,p=c,m=h-d;return{bottom:d,firstItemIndex:s,items:Xf(e,o,s),offsetBottom:m,offsetTop:c,top:p,topItems:Xf(t,o,s),topListHeight:t.reduce((g,y)=>y.size+g,0),totalCount:n}}function Yf(e,t,n,r,o,s){let i=0;if(n.groupIndices.length>0)for(const d of n.groupIndices){if(d-i>=e)break;i++}const a=e+i,l=al(t,a),c=Array.from({length:a}).map((d,f)=>({data:s[f+l],index:f+l,offset:0,size:0}));return ti(c,[],a,o,n,r)}function Xf(e,t,n){if(e.length===0)return[];if(!Zs(t))return e.map(c=>({...c,index:c.index+n,originalIndex:c.index}));const r=e[0].index,o=e[e.length-1].index,s=[],i=Ys(t.groupOffsetTree,r,o);let a,l=0;for(const c of e){(!a||a.end<c.index)&&(a=i.shift(),l=t.groupIndices.indexOf(a.start));let d;c.index===a.start?d={index:l,type:"group"}:d={groupIndex:l,index:c.index-(l+1)+n},s.push({...d,data:c.data,offset:c.offset,originalIndex:c.index,size:c.size})}return s}const _r=at(([{data:e,firstItemIndex:t,gap:n,sizes:r,totalCount:o},s,{listBoundary:i,topListHeight:a,visibleRange:l},{initialTopMostItemIndex:c,scrolledToInitialItem:d},{topListHeight:f},h,{didMount:p},{recalcInProgress:m}])=>{const g=ee([]),y=ee(0),x=Qe();we(s.topItemsIndexes,g);const w=en(X(Ft(p,m,Ne(l,Ao),Ne(o),Ne(r),Ne(c),d,Ne(g),Ne(t),Ne(n),e),_e(([S,E,,j,,,,,,,_])=>{const P=_&&_.length!==j;return S&&!E&&!P}),pe(([,,[S,E],j,_,P,D,z,B,O,H])=>{const R=_,{offsetTree:V,sizeTree:$}=R,F=Rt(y);if(j===0)return{...cl,totalCount:j};if(S===0&&E===0)return F===0?{...cl,totalCount:j}:Yf(F,P,_,B,O,H||[]);if(vt($))return F>0?null:ti(cS(al(P,j),R,H),[],j,O,R,B);const ne=[];if(z.length>0){const ue=z[0],ke=z[z.length-1];let te=0;for(const L of Ys($,ue,ke)){const q=L.value,ie=Math.max(L.start,ue),ce=Math.min(L.end,ke);for(let U=ie;U<=ce;U++)ne.push({data:H==null?void 0:H[U],index:U,offset:te,size:q}),te+=q}}if(!D)return ti([],ne,j,O,R,B);const Q=z.length>0?z[z.length-1]+1:0,ye=J0(V,S,E,Q);if(ye.length===0)return null;const je=j-1,J=Gs([],ue=>{for(const ke of ye){const te=ke.value;let L=te.offset,q=ke.start;const ie=te.size;if(te.offset<S){q+=Math.floor((S-te.offset+O)/(ie+O));const U=q-ke.start;L+=U*ie+U*O}q<Q&&(L+=(Q-q)*ie,q=Q);const ce=Math.min(ke.end,je);for(let U=q;U<=ce&&!(L>=E);U++)ue.push({data:H==null?void 0:H[U],index:U,offset:L,size:ie}),L+=ie+O}});return ti(J,ne,j,O,R,B)}),_e(S=>S!==null),Et()),cl);we(X(e,_e(Ya),pe(S=>S==null?void 0:S.length)),o),we(X(w,pe(S=>S.topListHeight)),f),we(f,a),we(X(w,pe(S=>[S.top,S.bottom])),i),we(X(w,pe(S=>S.items)),x);const C=yn(X(w,_e(({items:S})=>S.length>0),Ue(o,e),_e(([{items:S},E])=>S[S.length-1].originalIndex===E-1),pe(([,S,E])=>[S-1,E]),Et(Ao),pe(([S])=>S))),T=yn(X(w,rr(200),_e(({items:S,topItems:E})=>S.length>0&&S[0].originalIndex===E.length),pe(({items:S})=>S[0].index),Et())),k=yn(X(w,_e(({items:S})=>S.length>0),pe(({items:S})=>{let E=0,j=S.length-1;for(;S[E].type==="group"&&E<j;)E++;for(;S[j].type==="group"&&j>E;)j--;return{endIndex:S[j].index,startIndex:S[E].index}}),Et(Ff)));return{endReached:C,initialItemCount:y,itemsRendered:x,listState:w,rangeChanged:k,startReached:T,topItemsIndexes:g,...h}},Tt(Gn,Uf,ll,Po,jo,Mo,fr,rl),{singleton:!0}),Jf=at(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:r},{listState:o}])=>{const s=Qe(),i=en(X(Ft(n,e,r,t,o),pe(([a,l,c,d,f])=>a+l+c+d+f.offsetBottom+f.bottom)),0);return we(Ne(i),s),{totalListHeight:i,totalListHeightChanged:s}},Tt(on,_r),{singleton:!0}),uS=at(([{viewportHeight:e},{totalListHeight:t}])=>{const n=ee(!1),r=en(X(Ft(n,e,t),_e(([o])=>o),pe(([,o,s])=>Math.max(0,o-s)),rr(0),Et()),0);return{alignToBottom:n,paddingTopAddition:r}},Tt(on,Jf),{singleton:!0}),Zf=at(()=>({context:ee(null)})),dS=({itemBottom:e,itemTop:t,locationParams:{align:n,behavior:r,...o},viewportBottom:s,viewportTop:i})=>t<i?{...o,align:n??"start",behavior:r}:e>s?{...o,align:n??"end",behavior:r}:null,Qf=at(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:s,scrollingInProgress:i,scrollTop:a,viewportHeight:l},{scrollToIndex:c}])=>{const d=Qe();return we(X(d,Ue(t,l,n,s,o,r,a),Ue(e),pe(([[f,h,p,m,g,y,x,w],C])=>{const{align:T,behavior:k,calculateViewLocation:S=dS,done:E,...j}=f,_=Bf(f,h,m-1),P=_o(_,h.offsetTree,C)+g+y,D=P+On(h.sizeTree,_)[1],z=w+y,B=w+p-x,O=S({itemBottom:D,itemTop:P,locationParams:{align:T,behavior:k,...j},viewportBottom:B,viewportTop:z});return O?E&&Rn(X(i,_e(H=>!H),Ir(Rt(i)?1:2)),E):E&&E(),O}),_e(f=>f!==null)),c),{scrollIntoView:d}},Tt(Gn,on,jo,_r,ur),{singleton:!0});function eh(e){return e?e==="smooth"?"smooth":"auto":!1}const fS=(e,t)=>typeof e=="function"?eh(e(t)):t&&eh(e),hS=at(([{listRefresh:e,totalCount:t,fixedItemSize:n,data:r},{atBottomState:o,isAtBottom:s},{scrollToIndex:i},{scrolledToInitialItem:a},{didMount:l,propsReady:c},{log:d},{scrollingInProgress:f},{context:h},{scrollIntoView:p}])=>{const m=ee(!1),g=Qe();let y=null;function x(k){ze(i,{align:"end",behavior:k,index:"LAST"})}dt(X(Ft(X(Ne(t),Ir(1)),l),Ue(Ne(m),s,a,f),pe(([[k,S],E,j,_,P])=>{let D=S&&_,z="auto";return D&&(z=fS(E,j||P),D=D&&!!z),{followOutputBehavior:z,shouldFollow:D,totalCount:k}}),_e(({shouldFollow:k})=>k)),({followOutputBehavior:k,totalCount:S})=>{y&&(y(),y=null),Rt(n)?requestAnimationFrame(()=>{Rt(d)("following output to ",{totalCount:S},dn.DEBUG),x(k)}):y=Rn(e,()=>{Rt(d)("following output to ",{totalCount:S},dn.DEBUG),x(k),y=null})});function w(k){const S=Rn(o,E=>{k&&!E.atBottom&&E.notAtBottomBecause==="SIZE_INCREASED"&&!y&&(Rt(d)("scrolling to bottom due to increased size",{},dn.DEBUG),x("auto"))});setTimeout(S,100)}dt(X(Ft(Ne(m),t,c),_e(([k,,S])=>k&&S),qn(({value:k},[,S])=>({refreshed:k===S,value:S}),{refreshed:!1,value:0}),_e(({refreshed:k})=>k),Ue(m,t)),([,k])=>{Rt(a)&&w(k!==!1)}),dt(g,()=>{w(Rt(m)!==!1)}),dt(Ft(Ne(m),o),([k,S])=>{k&&!S.atBottom&&S.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&x("auto")});const C=ee(null),T=Qe();return we(Ja(X(Ne(r),pe(k=>{var S;return(S=k==null?void 0:k.length)!=null?S:0})),X(Ne(t))),T),dt(X(Ft(X(T,Ir(1)),l),Ue(Ne(C),a,f,h),pe(([[k,S],E,j,_,P])=>S&&j&&(E==null?void 0:E({context:P,totalCount:k,scrollingInProgress:_}))),_e(k=>!!k),rr(0)),k=>{y&&(y(),y=null),Rt(n)?requestAnimationFrame(()=>{Rt(d)("scrolling into view",{}),ze(p,k)}):y=Rn(e,()=>{Rt(d)("scrolling into view",{}),ze(p,k),y=null})}),{autoscrollToBottom:g,followOutput:m,scrollIntoViewOnChange:C}},Tt(Gn,Mo,jo,Po,fr,ur,on,Zf,Qf)),pS=at(([{data:e,firstItemIndex:t,gap:n,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:s,listState:i},{didMount:a}])=>(we(X(a,Ue(s),_e(([,l])=>l!==0),Ue(o,r,t,n,e),pe(([[,l],c,d,f,h,p=[]])=>Yf(l,c,d,f,h,p))),i),{}),Tt(Gn,Po,_r,fr),{singleton:!0}),mS=at(([{didMount:e},{scrollTo:t},{listState:n}])=>{const r=ee(0);return dt(X(e,Ue(r),_e(([,o])=>o!==0),pe(([,o])=>({top:o}))),o=>{Rn(X(n,Ir(1),_e(s=>s.items.length>1)),()=>{requestAnimationFrame(()=>{ze(t,o)})})}),{initialScrollTop:r}},Tt(fr,on,_r),{singleton:!0}),th=at(([{scrollVelocity:e}])=>{const t=ee(!1),n=Qe(),r=ee(!1);return we(X(e,Ue(r,t,n),_e(([o,s])=>!!s),pe(([o,s,i,a])=>{const{enter:l,exit:c}=s;if(i){if(c(o,a))return!1}else if(l(o,a))return!0;return i}),Et()),t),dt(X(Ft(t,e,n),Ue(r)),([[o,s,i],a])=>{o&&a&&a.change&&a.change(s,i)}),{isSeeking:t,scrollSeekConfiguration:r,scrollSeekRangeChanged:n,scrollVelocity:e}},Tt(Mo),{singleton:!0}),ul=at(([{scrollContainerState:e,scrollTo:t}])=>{const n=Qe(),r=Qe(),o=Qe(),s=ee(!1),i=ee(void 0);return we(X(Ft(n,r),pe(([{scrollHeight:a,scrollTop:l,viewportHeight:c},{offsetTop:d}])=>({scrollHeight:a,scrollTop:Math.max(0,l-d),viewportHeight:c}))),e),we(X(t,Ue(r),pe(([a,{offsetTop:l}])=>({...a,top:a.top+l}))),o),{customScrollParent:i,useWindowScroll:s,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:r}},Tt(on)),gS=at(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:r},{initialTopMostItemIndex:o},{didMount:s},{useWindowScroll:i,windowScrollContainerState:a,windowViewportRect:l}])=>{const c=Qe(),d=ee(void 0),f=ee(null),h=ee(null);return we(a,f),we(l,h),dt(X(c,Ue(t,r,i,f,h,n)),([p,m,g,y,x,w,C])=>{const T=Q0(m.sizeTree);y&&x!==null&&w!==null&&(g=x.scrollTop-w.offsetTop),g-=C,p({ranges:T,scrollTop:g})}),we(X(d,_e(Ya),pe(yS)),o),we(X(s,Ue(d),_e(([,p])=>p!==void 0),Et(),pe(([,p])=>p.ranges)),e),{getState:c,restoreStateFrom:d}},Tt(Gn,on,Po,fr,ul));function yS(e){return{align:"start",index:0,offset:e.scrollTop}}const xS=at(([{topItemsIndexes:e}])=>{const t=ee(0);return we(X(t,_e(n=>n>=0),pe(n=>Array.from({length:n}).map((r,o)=>o))),e),{topItemCount:t}},Tt(_r));function nh(e){let t=!1,n;return()=>(t||(t=!0,n=e()),n)}const vS=nh(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),wS=at(([{deviation:e,scrollBy:t,scrollingInProgress:n,scrollTop:r},{isAtBottom:o,isScrolling:s,lastJumpDueToItemResize:i,scrollDirection:a},{listState:l},{beforeUnshiftWith:c,gap:d,shiftWithOffset:f,sizes:h},{log:p},{recalcInProgress:m}])=>{const g=yn(X(l,Ue(i),qn(([,x,w,C],[{bottom:T,items:k,offsetBottom:S,totalCount:E},j])=>{const _=T+S;let P=0;return w===E&&x.length>0&&k.length>0&&(k[0].originalIndex===0&&x[0].originalIndex===0||(P=_-C,P!==0&&(P+=j))),[P,k,E,_]},[0,[],0,0]),_e(([x])=>x!==0),Ue(r,a,n,o,p,m),_e(([,x,w,C,,,T])=>!T&&!C&&x!==0&&w===Ro),pe(([[x],,,,,w])=>(w("Upward scrolling compensation",{amount:x},dn.DEBUG),x))));function y(x){x>0?(ze(t,{behavior:"auto",top:-x}),ze(e,0)):(ze(e,0),ze(t,{behavior:"auto",top:-x}))}return dt(X(g,Ue(e,s)),([x,w,C])=>{C&&vS()?ze(e,w-x):y(-x)}),dt(X(Ft(en(s,!1),e,m),_e(([x,w,C])=>!x&&!C&&w!==0),pe(([x,w])=>w),rr(1)),y),we(X(f,pe(x=>({top:-x}))),t),dt(X(c,Ue(h,d),pe(([x,{groupIndices:w,lastSize:C,sizeTree:T},k])=>{function S(E){return E*(C+k)}if(w.length===0)return S(x);{let E=0;const j=No(T,0);let _=0,P=0;for(;_<x;){_++,E+=j;let D=w.length===P+1?1/0:w[P+1]-w[P]-1;_+D>x&&(E-=j,D=x-_+1),_+=D,E+=S(D),P++}return E}})),x=>{ze(e,x),requestAnimationFrame(()=>{ze(t,{top:x}),requestAnimationFrame(()=>{ze(e,0),ze(m,!1)})})}),{deviation:e}},Tt(on,Mo,_r,Gn,ur,rl)),bS=at(([e,t,n,r,o,s,i,a,l,c,d])=>({...e,...t,...n,...r,...o,...s,...i,...a,...l,...c,...d}),Tt(ll,pS,fr,th,Jf,mS,uS,ul,Qf,ur,Zf)),rh=at(([{data:e,defaultItemSize:t,firstItemIndex:n,fixedItemSize:r,gap:o,groupIndices:s,itemSize:i,sizeRanges:a,sizes:l,statefulTotalCount:c,totalCount:d,trackItemSizes:f},{initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:m},g,y,x,{listState:w,topItemsIndexes:C,...T},{scrollToIndex:k},S,{topItemCount:E},{groupCounts:j},_])=>(we(T.rangeChanged,_.scrollSeekRangeChanged),we(X(_.windowViewportRect,pe(P=>P.visibleHeight)),g.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:r,gap:o,groupCounts:j,initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:m,sizeRanges:a,topItemCount:E,topItemsIndexes:C,totalCount:d,...x,groupIndices:s,itemSize:i,listState:w,scrollToIndex:k,statefulTotalCount:c,trackItemSizes:f,...T,..._,...g,sizes:l,...y}),Tt(Gn,Po,on,gS,hS,_r,jo,wS,xS,Uf,bS));function SS(e,t){const n={},r={};let o=0;const s=e.length;for(;o<s;)r[e[o]]=1,o+=1;for(const i in t)Object.hasOwn(r,i)||(n[i]=t[i]);return n}const ni=typeof document<"u"?b.useLayoutEffect:b.useEffect;function oh(e,t,n){const r=Object.keys(t.required||{}),o=Object.keys(t.optional||{}),s=Object.keys(t.methods||{}),i=Object.keys(t.events||{}),a=b.createContext({});function l(y,x){y.propsReady&&ze(y.propsReady,!1);for(const w of r){const C=y[t.required[w]];ze(C,x[w])}for(const w of o)if(w in x){const C=y[t.optional[w]];ze(C,x[w])}y.propsReady&&ze(y.propsReady,!0)}function c(y){return s.reduce((x,w)=>(x[w]=C=>{const T=y[t.methods[w]];ze(T,C)},x),{})}function d(y){return i.reduce((x,w)=>(x[w]=F0(y[t.events[w]]),x),{})}const f=b.forwardRef((y,x)=>{const{children:w,...C}=y,[T]=b.useState(()=>Gs(z0(e),E=>{l(E,C)})),[k]=b.useState(If(d,T));ni(()=>{for(const E of i)E in C&&dt(k[E],C[E]);return()=>{Object.values(k).map(Xa)}},[C,k,T]),ni(()=>{l(T,C)}),b.useImperativeHandle(x,Tf(c(T)));const S=n;return u.jsx(a.Provider,{value:T,children:n?u.jsx(S,{...SS([...r,...o,...i],C),children:w}):w})}),h=y=>{const x=b.useContext(a);return b.useCallback(w=>{ze(x[y],w)},[x,y])},p=y=>{const x=b.useContext(a)[y],w=b.useCallback(C=>dt(x,C),[x]);return b.useSyncExternalStore(w,()=>Rt(x),()=>Rt(x))},m=y=>{const x=b.useContext(a)[y],[w,C]=b.useState(If(Rt,x));return ni(()=>dt(x,T=>{T!==w&&C(Tf(T))}),[x,w]),w},g=b.version.startsWith("18")?p:m;return{Component:f,useEmitter:(y,x)=>{const w=b.useContext(a)[y];ni(()=>dt(w,x),[x,w])},useEmitterValue:g,usePublisher:h}}const sh=b.createContext(void 0),ih=b.createContext(void 0),ah=typeof document<"u"?b.useLayoutEffect:b.useEffect;function dl(e){return"self"in e}function CS(e){return"body"in e}function lh(e,t,n,r=to,o,s){const i=b.useRef(null),a=b.useRef(null),l=b.useRef(null),c=b.useCallback(h=>{let p,m,g;const y=h.target;if(CS(y)||dl(y)){const w=dl(y)?y:y.defaultView;g=s?w.scrollX:w.scrollY,p=s?w.document.documentElement.scrollWidth:w.document.documentElement.scrollHeight,m=s?w.innerWidth:w.innerHeight}else g=s?y.scrollLeft:y.scrollTop,p=s?y.scrollWidth:y.scrollHeight,m=s?y.offsetWidth:y.offsetHeight;const x=()=>{e({scrollHeight:p,scrollTop:Math.max(g,0),viewportHeight:m})};h.suppressFlushSync?x():Pi.flushSync(x),a.current!==null&&(g===a.current||g<=0||g===p-m)&&(a.current=null,t(!0),l.current&&(clearTimeout(l.current),l.current=null))},[e,t,s]);b.useEffect(()=>{const h=o||i.current;return r(o||i.current),c({suppressFlushSync:!0,target:h}),h.addEventListener("scroll",c,{passive:!0}),()=>{r(null),h.removeEventListener("scroll",c)}},[i,c,n,r,o]);function d(h){const p=i.current;if(!p||(s?"offsetWidth"in p&&p.offsetWidth===0:"offsetHeight"in p&&p.offsetHeight===0))return;const m=h.behavior==="smooth";let g,y,x;dl(p)?(y=Math.max(dr(p.document.documentElement,s?"width":"height"),s?p.document.documentElement.scrollWidth:p.document.documentElement.scrollHeight),g=s?p.innerWidth:p.innerHeight,x=s?window.scrollX:window.scrollY):(y=p[s?"scrollWidth":"scrollHeight"],g=dr(p,s?"width":"height"),x=p[s?"scrollLeft":"scrollTop"]);const w=y-g;if(h.top=Math.ceil(Math.max(Math.min(w,h.top),0)),Vf(g,y)||h.top===x){e({scrollHeight:y,scrollTop:x,viewportHeight:g}),m&&t(!0);return}m?(a.current=h.top,l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{l.current=null,a.current=null,t(!0)},1e3)):a.current=null,s&&(h={behavior:h.behavior,left:h.top}),p.scrollTo(h)}function f(h){s&&(h={behavior:h.behavior,left:h.top}),i.current.scrollBy(h)}return{scrollByCallback:f,scrollerRef:i,scrollToCallback:d}}const fl="-webkit-sticky",ch="sticky",hl=nh(()=>{if(typeof document>"u")return ch;const e=document.createElement("div");return e.style.position=fl,e.style.position===fl?fl:ch});function pl(e){return e}const kS=at(()=>{const e=ee(a=>`Item ${a}`),t=ee(a=>`Group ${a}`),n=ee({}),r=ee(pl),o=ee("div"),s=ee(to),i=(a,l=null)=>en(X(n,pe(c=>c[a]),Et()),l);return{components:n,computeItemKey:r,EmptyPlaceholder:i("EmptyPlaceholder"),FooterComponent:i("Footer"),GroupComponent:i("Group","div"),groupContent:t,HeaderComponent:i("Header"),HeaderFooterTag:o,ItemComponent:i("Item","div"),itemContent:e,ListComponent:i("List","div"),ScrollerComponent:i("Scroller","div"),scrollerRef:s,ScrollSeekPlaceholder:i("ScrollSeekPlaceholder"),TopItemListComponent:i("TopItemList")}}),TS=at(([e,t])=>({...e,...t}),Tt(rh,kS)),ES=({height:e})=>u.jsx("div",{style:{height:e}}),IS={overflowAnchor:"none",position:hl(),zIndex:1},uh={overflowAnchor:"none"},NS={...uh,display:"inline-block",height:"100%"},dh=b.memo(function({showTopList:e=!1}){const t=Oe("listState"),n=kn("sizeRanges"),r=Oe("useWindowScroll"),o=Oe("customScrollParent"),s=kn("windowScrollContainerState"),i=kn("scrollContainerState"),a=o||r?s:i,l=Oe("itemContent"),c=Oe("context"),d=Oe("groupContent"),f=Oe("trackItemSizes"),h=Oe("itemSize"),p=Oe("log"),m=kn("gap"),g=Oe("horizontalDirection"),{callbackRef:y}=U0(n,h,f,e?to:a,p,m,o,g,Oe("skipAnimationFrameInResizeObserver")),[x,w]=b.useState(0);ml("deviation",O=>{x!==O&&w(O)});const C=Oe("EmptyPlaceholder"),T=Oe("ScrollSeekPlaceholder")||ES,k=Oe("ListComponent"),S=Oe("ItemComponent"),E=Oe("GroupComponent"),j=Oe("computeItemKey"),_=Oe("isSeeking"),P=Oe("groupIndices").length>0,D=Oe("alignToBottom"),z=Oe("initialItemFinalLocationReached"),B=e?{}:{boxSizing:"border-box",...g?{display:"inline-block",height:"100%",marginLeft:x!==0?x:D?"auto":0,paddingLeft:t.offsetTop,paddingRight:t.offsetBottom,whiteSpace:"nowrap"}:{marginTop:x!==0?x:D?"auto":0,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...z?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&C?u.jsx(C,{...tn(C,c)}):u.jsx(k,{...tn(k,c),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:y,style:B,children:(e?t.topItems:t.items).map(O=>{const H=O.originalIndex,R=j(H+t.firstItemIndex,O.data,c);return _?b.createElement(T,{...tn(T,c),height:O.size,index:O.index,key:R,type:O.type||"item",...O.type==="group"?{}:{groupIndex:O.groupIndex}}):O.type==="group"?b.createElement(E,{...tn(E,c),"data-index":H,"data-item-index":O.index,"data-known-size":O.size,key:R,style:IS},d(O.index,c)):b.createElement(S,{...tn(S,c),...PS(S,O.data),"data-index":H,"data-item-group-index":O.groupIndex,"data-item-index":O.index,"data-known-size":O.size,key:R,style:g?NS:uh},P?l(O.index,O.groupIndex,O.data,c):l(O.index,O.data,c))})})}),AS={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},_S={outline:"none",overflowX:"auto",position:"relative"},ri=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:{}}),jS={position:hl(),top:0,width:"100%",zIndex:1};function tn(e,t){if(typeof e!="string")return{context:t}}function PS(e,t){return{item:typeof e=="string"?void 0:t}}const RS=b.memo(function(){const e=Oe("HeaderComponent"),t=kn("headerHeight"),n=Oe("HeaderFooterTag"),r=Nr(b.useMemo(()=>s=>{t(dr(s,"height"))},[t]),!0,Oe("skipAnimationFrameInResizeObserver")),o=Oe("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...tn(e,o)})}):null}),OS=b.memo(function(){const e=Oe("FooterComponent"),t=kn("footerHeight"),n=Oe("HeaderFooterTag"),r=Nr(b.useMemo(()=>s=>{t(dr(s,"height"))},[t]),!0,Oe("skipAnimationFrameInResizeObserver")),o=Oe("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...tn(e,o)})}):null});function fh({useEmitter:e,useEmitterValue:t,usePublisher:n}){return b.memo(function({children:r,style:o,context:s,...i}){const a=n("scrollContainerState"),l=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=t("scrollerRef"),f=t("horizontalDirection")||!1,{scrollByCallback:h,scrollerRef:p,scrollToCallback:m}=lh(a,c,l,d,void 0,f);return e("scrollTo",m),e("scrollBy",h),u.jsx(l,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:p,style:{...f?_S:AS,...o},tabIndex:0,...i,...tn(l,s),children:r})})}function hh({useEmitter:e,useEmitterValue:t,usePublisher:n}){return b.memo(function({children:r,style:o,context:s,...i}){const a=n("windowScrollContainerState"),l=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=t("totalListHeight"),f=t("deviation"),h=t("customScrollParent"),p=b.useRef(null),m=t("scrollerRef"),{scrollByCallback:g,scrollerRef:y,scrollToCallback:x}=lh(a,c,l,m,h);return ah(()=>{var w;return y.current=h||((w=p.current)==null?void 0:w.ownerDocument.defaultView),()=>{y.current=null}},[y,h]),e("windowScrollTo",x),e("scrollBy",g),u.jsx(l,{ref:p,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...d!==0?{height:d+f}:{}},...i,...tn(l,s),children:r})})}const MS=({children:e})=>{const t=b.useContext(sh),n=kn("viewportHeight"),r=kn("fixedItemHeight"),o=Oe("alignToBottom"),s=Oe("horizontalDirection"),i=b.useMemo(()=>Ef(n,l=>dr(l,s?"width":"height")),[n,s]),a=Nr(i,!0,Oe("skipAnimationFrameInResizeObserver"));return b.useEffect(()=>{t&&(n(t.viewportHeight),r(t.itemHeight))},[t,n,r]),u.jsx("div",{"data-viewport-type":"element",ref:a,style:ri(o),children:e})},DS=({children:e})=>{const t=b.useContext(sh),n=kn("windowViewportRect"),r=kn("fixedItemHeight"),o=Oe("customScrollParent"),s=jf(n,o,Oe("skipAnimationFrameInResizeObserver")),i=Oe("alignToBottom");return b.useEffect(()=>{t&&(r(t.itemHeight),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:100}))},[t,n,r]),u.jsx("div",{"data-viewport-type":"window",ref:s,style:ri(i),children:e})},LS=({children:e})=>{const t=Oe("TopItemListComponent")||"div",n=Oe("headerHeight"),r={...jS,marginTop:`${n}px`},o=Oe("context");return u.jsx(t,{style:r,...tn(t,o),children:e})},FS=b.memo(function(e){const t=Oe("useWindowScroll"),n=Oe("topItemsIndexes").length>0,r=Oe("customScrollParent"),o=Oe("context");return u.jsxs(r||t?BS:zS,{...e,context:o,children:[n&&u.jsx(LS,{children:u.jsx(dh,{showTopList:!0})}),u.jsxs(r||t?DS:MS,{children:[u.jsx(RS,{}),u.jsx(dh,{}),u.jsx(OS,{})]})]})}),{Component:$S,useEmitter:ml,useEmitterValue:Oe,usePublisher:kn}=oh(TS,{required:{},optional:{restoreStateFrom:"restoreStateFrom",context:"context",followOutput:"followOutput",scrollIntoViewOnChange:"scrollIntoViewOnChange",itemContent:"itemContent",groupContent:"groupContent",overscan:"overscan",increaseViewportBy:"increaseViewportBy",totalCount:"totalCount",groupCounts:"groupCounts",topItemCount:"topItemCount",firstItemIndex:"firstItemIndex",initialTopMostItemIndex:"initialTopMostItemIndex",components:"components",atBottomThreshold:"atBottomThreshold",atTopThreshold:"atTopThreshold",computeItemKey:"computeItemKey",defaultItemHeight:"defaultItemHeight",fixedItemHeight:"fixedItemHeight",itemSize:"itemSize",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"HeaderFooterTag",data:"data",initialItemCount:"initialItemCount",initialScrollTop:"initialScrollTop",alignToBottom:"alignToBottom",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",horizontalDirection:"horizontalDirection",skipAnimationFrameInResizeObserver:"skipAnimationFrameInResizeObserver"},methods:{scrollToIndex:"scrollToIndex",scrollIntoView:"scrollIntoView",scrollTo:"scrollTo",scrollBy:"scrollBy",autoscrollToBottom:"autoscrollToBottom",getState:"getState"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",totalListHeightChanged:"totalListHeightChanged",itemsRendered:"itemsRendered",groupIndices:"groupIndices"}},FS),zS=fh({useEmitter:ml,useEmitterValue:Oe,usePublisher:kn}),BS=hh({useEmitter:ml,useEmitterValue:Oe,usePublisher:kn}),HS=$S;Tt(rh,at(()=>{const e=ee(c=>u.jsxs("td",{children:["Item $",c]})),t=ee(null),n=ee(c=>u.jsxs("td",{colSpan:1e3,children:["Group ",c]})),r=ee(null),o=ee(null),s=ee({}),i=ee(pl),a=ee(to),l=(c,d=null)=>en(X(s,pe(f=>f[c]),Et()),d);return{components:s,computeItemKey:i,context:t,EmptyPlaceholder:l("EmptyPlaceholder"),FillerRow:l("FillerRow"),fixedFooterContent:o,fixedHeaderContent:r,itemContent:e,groupContent:n,ScrollerComponent:l("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder"),TableBodyComponent:l("TableBody","tbody"),TableComponent:l("Table","table"),TableFooterComponent:l("TableFoot","tfoot"),TableHeadComponent:l("TableHead","thead"),TableRowComponent:l("TableRow","tr"),GroupComponent:l("Group","tr")}})),hl();const ph={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},US={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:mh,floor:oi,max:Do,min:gl,round:gh}=Math;function yh(e,t,n){return Array.from({length:t-e+1}).map((r,o)=>({data:n===null?null:n[o+e],index:o+e}))}function WS(e){return{...US,items:e}}function si(e,t){return e&&e.width===t.width&&e.height===t.height}function VS(e,t){return e&&e.column===t.column&&e.row===t.row}const KS=at(([{increaseViewportBy:e,listBoundary:t,overscan:n,visibleRange:r},{footerHeight:o,headerHeight:s,scrollBy:i,scrollContainerState:a,scrollTo:l,scrollTop:c,smoothScrollTargetReached:d,viewportHeight:f},h,p,{didMount:m,propsReady:g},{customScrollParent:y,useWindowScroll:x,windowScrollContainerState:w,windowScrollTo:C,windowViewportRect:T},k])=>{const S=ee(0),E=ee(0),j=ee(ph),_=ee({height:0,width:0}),P=ee({height:0,width:0}),D=Qe(),z=Qe(),B=ee(0),O=ee(null),H=ee({column:0,row:0}),R=Qe(),V=Qe(),$=ee(!1),F=ee(0),ne=ee(!0),Q=ee(!1),ye=ee(!1);dt(X(m,Ue(F),_e(([L,q])=>!!q)),()=>{ze(ne,!1)}),dt(X(Ft(m,ne,P,_,F,Q),_e(([L,q,ie,ce,,U])=>L&&!q&&ie.height!==0&&ce.height!==0&&!U)),([,,,,L])=>{ze(Q,!0),il(1,()=>{ze(D,L)}),Rn(X(c),()=>{ze(t,[0,0]),ze(ne,!0)})}),we(X(V,_e(L=>L!=null&&L.scrollTop>0),Kn(0)),E),dt(X(m,Ue(V),_e(([,L])=>L!=null)),([,L])=>{L&&(ze(_,L.viewport),ze(P,L.item),ze(H,L.gap),L.scrollTop>0&&(ze($,!0),Rn(X(c,Ir(1)),q=>{ze($,!1)}),ze(l,{top:L.scrollTop})))}),we(X(_,pe(({height:L})=>L)),f),we(X(Ft(Ne(_,si),Ne(P,si),Ne(H,(L,q)=>L&&L.column===q.column&&L.row===q.row),Ne(c)),pe(([L,q,ie,ce])=>({gap:ie,item:q,scrollTop:ce,viewport:L}))),R),we(X(Ft(Ne(S),r,Ne(H,VS),Ne(P,si),Ne(_,si),Ne(O),Ne(E),Ne($),Ne(ne),Ne(F)),_e(([,,,,,,,L])=>!L),pe(([L,[q,ie],ce,U,We,re,xe,,Pe,$e])=>{const{column:rt,row:Se}=ce,{height:Ye,width:ot}=U,{width:et}=We;if(xe===0&&(L===0||et===0))return ph;if(ot===0){const st=al($e,L),Gt=st+Math.max(xe-1,0);return WS(yh(st,Gt,re))}const Xe=xh(et,ot,rt);let Ke,tt;Pe?q===0&&ie===0&&xe>0?(Ke=0,tt=xe-1):(Ke=Xe*oi((q+Se)/(Ye+Se)),tt=Xe*mh((ie+Se)/(Ye+Se))-1,tt=gl(L-1,Do(tt,Xe-1)),Ke=gl(tt,Do(0,Ke))):(Ke=0,tt=-1);const Ot=yh(Ke,tt,re),{bottom:St,top:nt}=vh(We,ce,U,Ot),yt=mh(L/Xe),Nt=yt*Ye+(yt-1)*Se-St;return{bottom:St,itemHeight:Ye,items:Ot,itemWidth:ot,offsetBottom:Nt,offsetTop:nt,top:nt}})),j),we(X(O,_e(L=>L!==null),pe(L=>L.length)),S),we(X(Ft(_,P,j,H),_e(([L,q,{items:ie}])=>ie.length>0&&q.height!==0&&L.height!==0),pe(([L,q,{items:ie},ce])=>{const{bottom:U,top:We}=vh(L,ce,q,ie);return[We,U]}),Et(Ao)),t);const je=ee(!1);we(X(c,Ue(je),pe(([L,q])=>q||L!==0)),je);const J=yn(X(Ft(j,S),_e(([{items:L}])=>L.length>0),Ue(je),_e(([[L,q],ie])=>{const ce=L.items[L.items.length-1].index===q-1;return(ie||L.bottom>0&&L.itemHeight>0&&L.offsetBottom===0&&L.items.length===q)&&ce}),pe(([[,L]])=>L-1),Et())),ue=yn(X(Ne(j),_e(({items:L})=>L.length>0&&L[0].index===0),Kn(0),Et())),ke=yn(X(Ne(j),Ue($),_e(([{items:L},q])=>L.length>0&&!q),pe(([{items:L}])=>({endIndex:L[L.length-1].index,startIndex:L[0].index})),Et(Ff),rr(0)));we(ke,p.scrollSeekRangeChanged),we(X(D,Ue(_,P,S,H),pe(([L,q,ie,ce,U])=>{const We=Wf(L),{align:re,behavior:xe,offset:Pe}=We;let $e=We.index;$e==="LAST"&&($e=ce-1),$e=Do(0,$e,gl(ce-1,$e));let rt=yl(q,U,ie,$e);return re==="end"?rt=gh(rt-q.height+ie.height):re==="center"&&(rt=gh(rt-q.height/2+ie.height/2)),Pe&&(rt+=Pe),{behavior:xe,top:rt}})),l);const te=en(X(j,pe(L=>L.offsetBottom+L.bottom)),0);return we(X(T,pe(L=>({height:L.visibleHeight,width:L.visibleWidth}))),_),{customScrollParent:y,data:O,deviation:B,footerHeight:o,gap:H,headerHeight:s,increaseViewportBy:e,initialItemCount:E,itemDimensions:P,overscan:n,restoreStateFrom:V,scrollBy:i,scrollContainerState:a,scrollHeight:z,scrollTo:l,scrollToIndex:D,scrollTop:c,smoothScrollTargetReached:d,totalCount:S,useWindowScroll:x,viewportDimensions:_,windowScrollContainerState:w,windowScrollTo:C,windowViewportRect:T,...p,gridState:j,horizontalDirection:ye,initialTopMostItemIndex:F,totalListHeight:te,...h,endReached:J,propsReady:g,rangeChanged:ke,startReached:ue,stateChanged:R,stateRestoreInProgress:$,...k}},Tt(ll,on,Mo,th,fr,ul,ur));function xh(e,t,n){return Do(1,oi((e+n)/(oi(t)+n)))}function vh(e,t,n,r){const{height:o}=n;if(o===void 0||r.length===0)return{bottom:0,top:0};const s=yl(e,t,n,r[0].index);return{bottom:yl(e,t,n,r[r.length-1].index)+o,top:s}}function yl(e,t,n,r){const o=xh(e.width,n.width,t.column),s=oi(r/o),i=s*n.height+Do(0,s-1)*t.row;return i>0?i+t.row:i}const qS=at(()=>{const e=ee(f=>`Item ${f}`),t=ee({}),n=ee(null),r=ee("virtuoso-grid-item"),o=ee("virtuoso-grid-list"),s=ee(pl),i=ee("div"),a=ee(to),l=(f,h=null)=>en(X(t,pe(p=>p[f]),Et()),h),c=ee(!1),d=ee(!1);return we(Ne(d),c),{components:t,computeItemKey:s,context:n,FooterComponent:l("Footer"),HeaderComponent:l("Header"),headerFooterTag:i,itemClassName:r,ItemComponent:l("Item","div"),itemContent:e,listClassName:o,ListComponent:l("List","div"),readyStateChanged:c,reportReadyState:d,ScrollerComponent:l("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder","div")}}),GS=at(([e,t])=>({...e,...t}),Tt(KS,qS)),YS=b.memo(function(){const e=It("gridState"),t=It("listClassName"),n=It("itemClassName"),r=It("itemContent"),o=It("computeItemKey"),s=It("isSeeking"),i=Tn("scrollHeight"),a=It("ItemComponent"),l=It("ListComponent"),c=It("ScrollSeekPlaceholder"),d=It("context"),f=Tn("itemDimensions"),h=Tn("gap"),p=It("log"),m=It("stateRestoreInProgress"),g=Tn("reportReadyState"),y=Nr(b.useMemo(()=>x=>{const w=x.parentElement.parentElement.scrollHeight;i(w);const C=x.firstChild;if(C){const{height:T,width:k}=C.getBoundingClientRect();f({height:T,width:k})}h({column:bh("column-gap",getComputedStyle(x).columnGap,p),row:bh("row-gap",getComputedStyle(x).rowGap,p)})},[i,f,h,p]),!0,!1);return ah(()=>{e.itemHeight>0&&e.itemWidth>0&&g(!0)},[e]),m?null:u.jsx(l,{className:t,ref:y,...tn(l,d),"data-testid":"virtuoso-item-list",style:{paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},children:e.items.map(x=>{const w=o(x.index,x.data,d);return s?u.jsx(c,{...tn(c,d),height:e.itemHeight,index:x.index,width:e.itemWidth},w):b.createElement(a,{...tn(a,d),className:n,"data-index":x.index,key:w},r(x.index,x.data,d))})})}),XS=b.memo(function(){const e=It("HeaderComponent"),t=Tn("headerHeight"),n=It("headerFooterTag"),r=Nr(b.useMemo(()=>s=>{t(dr(s,"height"))},[t]),!0,!1),o=It("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...tn(e,o)})}):null}),JS=b.memo(function(){const e=It("FooterComponent"),t=Tn("footerHeight"),n=It("headerFooterTag"),r=Nr(b.useMemo(()=>s=>{t(dr(s,"height"))},[t]),!0,!1),o=It("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...tn(e,o)})}):null}),ZS=({children:e})=>{const t=b.useContext(ih),n=Tn("itemDimensions"),r=Tn("viewportDimensions"),o=Nr(b.useMemo(()=>s=>{r(s.getBoundingClientRect())},[r]),!0,!1);return b.useEffect(()=>{t&&(r({height:t.viewportHeight,width:t.viewportWidth}),n({height:t.itemHeight,width:t.itemWidth}))},[t,r,n]),u.jsx("div",{ref:o,style:ri(!1),children:e})},QS=({children:e})=>{const t=b.useContext(ih),n=Tn("windowViewportRect"),r=Tn("itemDimensions"),o=It("customScrollParent"),s=jf(n,o,!1);return b.useEffect(()=>{t&&(r({height:t.itemHeight,width:t.itemWidth}),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:t.viewportWidth}))},[t,n,r]),u.jsx("div",{ref:s,style:ri(!1),children:e})},eC=b.memo(function({...e}){const t=It("useWindowScroll"),n=It("customScrollParent"),r=n||t?nC:tC,o=n||t?QS:ZS,s=It("context");return u.jsx(r,{...e,...tn(r,s),children:u.jsxs(o,{children:[u.jsx(XS,{}),u.jsx(YS,{}),u.jsx(JS,{})]})})}),{useEmitter:wh,useEmitterValue:It,usePublisher:Tn}=oh(GS,{optional:{context:"context",totalCount:"totalCount",overscan:"overscan",itemContent:"itemContent",components:"components",computeItemKey:"computeItemKey",data:"data",initialItemCount:"initialItemCount",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"headerFooterTag",listClassName:"listClassName",itemClassName:"itemClassName",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",restoreStateFrom:"restoreStateFrom",initialTopMostItemIndex:"initialTopMostItemIndex",increaseViewportBy:"increaseViewportBy"},methods:{scrollTo:"scrollTo",scrollBy:"scrollBy",scrollToIndex:"scrollToIndex"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",stateChanged:"stateChanged",readyStateChanged:"readyStateChanged"}},eC),tC=fh({useEmitter:wh,useEmitterValue:It,usePublisher:Tn}),nC=hh({useEmitter:wh,useEmitterValue:It,usePublisher:Tn});function bh(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,dn.WARN),t==="normal"?0:parseInt(t??"0",10)}const rC=Go.cva("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function Sh({className:e,variant:t,...n}){return u.jsx("div",{className:oe(rC({variant:t}),e),...n})}const Lo=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:oe("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));Lo.displayName="Card";const Fo=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:oe("flex flex-col space-y-1.5 p-6",e),...t}));Fo.displayName="CardHeader";const $o=v.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:oe("text-2xl font-semibold leading-none tracking-tight",e),...t}));$o.displayName="CardTitle";const Ch=v.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:oe("text-sm text-muted-foreground",e),...t}));Ch.displayName="CardDescription";const zo=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:oe("p-6 pt-0",e),...t}));zo.displayName="CardContent";const kh=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:oe("flex items-center p-6 pt-0",e),...t}));kh.displayName="CardFooter";const oC=1,sC=1e6;let xl=0;function iC(){return xl=(xl+1)%Number.MAX_SAFE_INTEGER,xl.toString()}const vl=new Map,Th=e=>{if(vl.has(e))return;const t=setTimeout(()=>{vl.delete(e),Bo({type:"REMOVE_TOAST",toastId:e})},sC);vl.set(e,t)},aC=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,oC)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?Th(n):e.toasts.forEach(r=>{Th(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},ii=[];let ai={toasts:[]};function Bo(e){ai=aC(ai,e),ii.forEach(t=>{t(ai)})}function lC({...e}){const t=iC(),n=o=>Bo({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Bo({type:"DISMISS_TOAST",toastId:t});return Bo({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function wl(){const[e,t]=v.useState(ai);return v.useEffect(()=>(ii.push(t),()=>{const n=ii.indexOf(t);n>-1&&ii.splice(n,1)}),[e]),{...e,toast:lC,dismiss:n=>Bo({type:"DISMISS_TOAST",toastId:n})}}async function Eh(e,t){return await wn(e,{responseType:"blob",onDownloadProgress:r=>{try{t&&r.lengthComputable}catch{}},maxBodyLength:1/0})}async function Ih(e,t){return await(await Eh(`/files/${e}/view`,t)).text()}async function cC(e,t){const n=await Eh(`/files/${e}/download`,t),r=URL.createObjectURL(n);let o=`file_${e}`;try{const i=await wn(`/files/${e}`);o=(i==null?void 0:i.filename)??o}catch{}const s=document.createElement("a");s.href=r,s.download=o,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}async function uC(e,t=50,n=0){const r={limit:t,offset:n};return e&&(r.thread_id=e),await wn("/files",{params:r})}function bl(e){const t=e==null?void 0:e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return null;try{return JSON.parse(t)}catch{return null}}function Nh(e){return!!(e&&typeof e=="object"&&(e.type==="file"||e.mimeType||e.filename||e.sourceType==="base64"))}function Ho(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){if(Array.isArray(e)){const n=e.map(Ho).filter(r=>r!==void 0);if(!n.length){console.debug("[message-utils] sanitizeForDisplay - array emptied -> returning undefined",{originalLength:e.length});return}return n}if(Nh(e)){try{console.debug("[message-utils] sanitizeForDisplay - dropping file-like object",{sampleFilename:e&&(e.filename||e.name)?e.filename||e.name:void 0,keys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - dropped file-like (unable to inspect)",{err:String(n)})}return}const t={};for(const n of Object.keys(e)){const r=e[n];if(n==="data"&&typeof r=="string"&&r.length>100)t[n]=`[base64 ${r.length} chars omitted]`;else{const o=Ho(r);o!==void 0&&(t[n]=o)}}if(Object.keys(t).length)return t;try{console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined",{originalKeys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined (inspect failed)",{err:String(n)})}return}return e}function Uo(e){if(typeof e=="string")return e;if(Nh(e))return"";try{const t=Ho(e);return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}catch{return""}}function dC(e){return typeof e!="string"?!1:/^[\s\n]*[-*]\s|^[\s\n]*#+\s|```|^\s*\[.*\]\(|^>\s/.test(e)}function fC(e){const t=Uo(e);return typeof e=="string"&&dC(e)?{content:e,isMarkdown:!0}:{content:t,isMarkdown:!1}}function li(e){if(e==null)return e;if(typeof e=="string"){const t=e.trim();if(t.startsWith("{")||t.startsWith("[")){const n=bl(t);if(n!==null)return li(n)}return e}return typeof e=="object"&&!Array.isArray(e)&&e.content!==void 0?li(e.content):e}var ci="Dialog",[Ah,UT]=Qn(ci),[hC,Mn]=Ah(ci),_h=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:s,modal:i=!0}=e,a=v.useRef(null),l=v.useRef(null),[c,d]=Vr({prop:r,defaultProp:o??!1,onChange:s,caller:ci});return u.jsx(hC,{scope:t,triggerRef:a,contentRef:l,contentId:er(),titleId:er(),descriptionId:er(),open:c,onOpenChange:d,onOpenToggle:v.useCallback(()=>d(f=>!f),[d]),modal:i,children:n})};_h.displayName=ci;var jh="DialogTrigger",Ph=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Mn(jh,n),s=Ze(t,o.triggerRef);return u.jsx(De.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":kl(o.open),...r,ref:s,onClick:ge(e.onClick,o.onOpenToggle)})});Ph.displayName=jh;var Sl="DialogPortal",[pC,Rh]=Ah(Sl,{forceMount:void 0}),Oh=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,s=Mn(Sl,t);return u.jsx(pC,{scope:t,forceMount:n,children:v.Children.map(r,i=>u.jsx(Sn,{present:n||s.open,children:u.jsx(js,{asChild:!0,container:o,children:i})}))})};Oh.displayName=Sl;var ui="DialogOverlay",Mh=v.forwardRef((e,t)=>{const n=Rh(ui,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=Mn(ui,e.__scopeDialog);return s.modal?u.jsx(Sn,{present:r||s.open,children:u.jsx(gC,{...o,ref:t})}):null});Mh.displayName=ui;var mC=vr.createSlot("DialogOverlay.RemoveScroll"),gC=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Mn(ui,n);return u.jsx(zs,{as:mC,allowPinchZoom:!0,shards:[o.contentRef],children:u.jsx(De.div,{"data-state":kl(o.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),jr="DialogContent",Dh=v.forwardRef((e,t)=>{const n=Rh(jr,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=Mn(jr,e.__scopeDialog);return u.jsx(Sn,{present:r||s.open,children:s.modal?u.jsx(yC,{...o,ref:t}):u.jsx(xC,{...o,ref:t})})});Dh.displayName=jr;var yC=v.forwardRef((e,t)=>{const n=Mn(jr,e.__scopeDialog),r=v.useRef(null),o=Ze(t,n.contentRef,r);return v.useEffect(()=>{const s=r.current;if(s)return Ma(s)},[]),u.jsx(Lh,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ge(e.onCloseAutoFocus,s=>{var i;s.preventDefault(),(i=n.triggerRef.current)==null||i.focus()}),onPointerDownOutside:ge(e.onPointerDownOutside,s=>{const i=s.detail.originalEvent,a=i.button===0&&i.ctrlKey===!0;(i.button===2||a)&&s.preventDefault()}),onFocusOutside:ge(e.onFocusOutside,s=>s.preventDefault())})}),xC=v.forwardRef((e,t)=>{const n=Mn(jr,e.__scopeDialog),r=v.useRef(!1),o=v.useRef(!1);return u.jsx(Lh,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var i,a;(i=e.onCloseAutoFocus)==null||i.call(e,s),s.defaultPrevented||(r.current||(a=n.triggerRef.current)==null||a.focus(),s.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:s=>{var l,c;(l=e.onInteractOutside)==null||l.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const i=s.target;((c=n.triggerRef.current)==null?void 0:c.contains(i))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})}),Lh=v.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:s,...i}=e,a=Mn(jr,n),l=v.useRef(null),c=Ze(t,l);return ga(),u.jsxs(u.Fragment,{children:[u.jsx(vs,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:s,children:u.jsx(xs,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":kl(a.open),...i,ref:c,onDismiss:()=>a.onOpenChange(!1)})}),u.jsxs(u.Fragment,{children:[u.jsx(vC,{titleId:a.titleId}),u.jsx(bC,{contentRef:l,descriptionId:a.descriptionId})]})]})}),Cl="DialogTitle",Fh=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Mn(Cl,n);return u.jsx(De.h2,{id:o.titleId,...r,ref:t})});Fh.displayName=Cl;var $h="DialogDescription",zh=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Mn($h,n);return u.jsx(De.p,{id:o.descriptionId,...r,ref:t})});zh.displayName=$h;var Bh="DialogClose",Hh=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Mn(Bh,n);return u.jsx(De.button,{type:"button",...r,ref:t,onClick:ge(e.onClick,()=>o.onOpenChange(!1))})});Hh.displayName=Bh;function kl(e){return e?"open":"closed"}var Uh="DialogTitleWarning",[WT,Wh]=kx(Uh,{contentName:jr,titleName:Cl,docsSlug:"dialog"}),vC=({titleId:e})=>{const t=Wh(Uh),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
|
|
87
87
|
|
|
88
88
|
If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
|
|
89
89
|
|
|
@@ -133,5 +133,5 @@ ${t}</tr>
|
|
|
133
133
|
`}strong(t){return`<strong>${t}</strong>`}em(t){return`<em>${t}</em>`}codespan(t){return`<code>${t}</code>`}br(){return this.options.xhtml?"<br/>":"<br>"}del(t){return`<del>${t}</del>`}link(t,n,r){if(t=rp(this.options.sanitize,this.options.baseUrl,t),t===null)return r;let o='<a href="'+t+'"';return n&&(o+=' title="'+n+'"'),o+=">"+r+"</a>",o}image(t,n,r){if(t=rp(this.options.sanitize,this.options.baseUrl,t),t===null)return r;let o=`<img src="${t}" alt="${r}"`;return n&&(o+=` title="${n}"`),o+=this.options.xhtml?"/>":">",o}text(t){return t}}class lp{strong(t){return t}em(t){return t}codespan(t){return t}del(t){return t}html(t){return t}text(t){return t}link(t,n,r){return""+r}image(t,n,r){return""+r}br(){return""}}class cp{constructor(){this.seen={}}serialize(t){return t.toLowerCase().trim().replace(/<[!\/a-z].*?>/ig,"").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,"").replace(/\s/g,"-")}getNextSafeSlug(t,n){let r=t,o=0;if(this.seen.hasOwnProperty(r)){o=this.seen[t];do o++,r=t+"-"+o;while(this.seen.hasOwnProperty(r))}return n||(this.seen[t]=o,this.seen[r]=0),r}slug(t,n={}){const r=this.serialize(t);return this.getNextSafeSlug(r,n.dryrun)}}class pr{constructor(t){this.options=t||Rr,this.options.renderer=this.options.renderer||new El,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new lp,this.slugger=new cp}static parse(t,n){return new pr(n).parse(t)}static parseInline(t,n){return new pr(n).parseInline(t)}parse(t,n=!0){let r="",o,s,i,a,l,c,d,f,h,p,m,g,y,x,w,C,T,k,S;const E=t.length;for(o=0;o<E;o++){if(p=t[o],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[p.type]&&(S=this.options.extensions.renderers[p.type].call({parser:this},p),S!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(p.type))){r+=S||"";continue}switch(p.type){case"space":continue;case"hr":{r+=this.renderer.hr();continue}case"heading":{r+=this.renderer.heading(this.parseInline(p.tokens),p.depth,np(this.parseInline(p.tokens,this.textRenderer)),this.slugger);continue}case"code":{r+=this.renderer.code(p.text,p.lang,p.escaped);continue}case"table":{for(f="",d="",a=p.header.length,s=0;s<a;s++)d+=this.renderer.tablecell(this.parseInline(p.header[s].tokens),{header:!0,align:p.align[s]});for(f+=this.renderer.tablerow(d),h="",a=p.rows.length,s=0;s<a;s++){for(c=p.rows[s],d="",l=c.length,i=0;i<l;i++)d+=this.renderer.tablecell(this.parseInline(c[i].tokens),{header:!1,align:p.align[i]});h+=this.renderer.tablerow(d)}r+=this.renderer.table(f,h);continue}case"blockquote":{h=this.parse(p.tokens),r+=this.renderer.blockquote(h);continue}case"list":{for(m=p.ordered,g=p.start,y=p.loose,a=p.items.length,h="",s=0;s<a;s++)w=p.items[s],C=w.checked,T=w.task,x="",w.task&&(k=this.renderer.checkbox(C),y?w.tokens.length>0&&w.tokens[0].type==="paragraph"?(w.tokens[0].text=k+" "+w.tokens[0].text,w.tokens[0].tokens&&w.tokens[0].tokens.length>0&&w.tokens[0].tokens[0].type==="text"&&(w.tokens[0].tokens[0].text=k+" "+w.tokens[0].tokens[0].text)):w.tokens.unshift({type:"text",text:k}):x+=k),x+=this.parse(w.tokens,y),h+=this.renderer.listitem(x,T,C);r+=this.renderer.list(h,m,g);continue}case"html":{r+=this.renderer.html(p.text);continue}case"paragraph":{r+=this.renderer.paragraph(this.parseInline(p.tokens));continue}case"text":{for(h=p.tokens?this.parseInline(p.tokens):p.text;o+1<E&&t[o+1].type==="text";)p=t[++o],h+=`
|
|
134
134
|
`+(p.tokens?this.parseInline(p.tokens):p.text);r+=n?this.renderer.paragraph(h):h;continue}default:{const j='Token with "'+p.type+'" type was not found.';if(this.options.silent){console.error(j);return}else throw new Error(j)}}}return r}parseInline(t,n){n=n||this.renderer;let r="",o,s,i;const a=t.length;for(o=0;o<a;o++){if(s=t[o],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]&&(i=this.options.extensions.renderers[s.type].call({parser:this},s),i!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type))){r+=i||"";continue}switch(s.type){case"escape":{r+=n.text(s.text);break}case"html":{r+=n.html(s.text);break}case"link":{r+=n.link(s.href,s.title,this.parseInline(s.tokens,n));break}case"image":{r+=n.image(s.href,s.title,s.text);break}case"strong":{r+=n.strong(this.parseInline(s.tokens,n));break}case"em":{r+=n.em(this.parseInline(s.tokens,n));break}case"codespan":{r+=n.codespan(s.text);break}case"br":{r+=n.br();break}case"del":{r+=n.del(this.parseInline(s.tokens,n));break}case"text":{r+=n.text(s.text);break}default:{const l='Token with "'+s.type+'" type was not found.';if(this.options.silent){console.error(l);return}else throw new Error(l)}}}return r}}class yi{constructor(t){this.options=t||Rr}preprocess(t){return t}postprocess(t){return t}}Gm(yi,"passThroughHooks",new Set(["preprocess","postprocess"]));function UC(e,t,n){return r=>{if(r.message+=`
|
|
135
135
|
Please report this to https://github.com/markedjs/marked.`,e){const o="<p>An error occurred:</p><pre>"+nn(r.message+"",!0)+"</pre>";if(t)return Promise.resolve(o);if(n){n(null,o);return}return o}if(t)return Promise.reject(r);if(n){n(r);return}throw r}}function up(e,t){return(n,r,o)=>{typeof r=="function"&&(o=r,r=null);const s={...r};r={...be.defaults,...s};const i=UC(r.silent,r.async,o);if(typeof n>"u"||n===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(zC(r),r.hooks&&(r.hooks.options=r),o){const a=r.highlight;let l;try{r.hooks&&(n=r.hooks.preprocess(n)),l=e(n,r)}catch(f){return i(f)}const c=function(f){let h;if(!f)try{r.walkTokens&&be.walkTokens(l,r.walkTokens),h=t(l,r),r.hooks&&(h=r.hooks.postprocess(h))}catch(p){f=p}return r.highlight=a,f?i(f):o(null,h)};if(!a||a.length<3||(delete r.highlight,!l.length))return c();let d=0;be.walkTokens(l,function(f){f.type==="code"&&(d++,setTimeout(()=>{a(f.text,f.lang,function(h,p){if(h)return c(h);p!=null&&p!==f.text&&(f.text=p,f.escaped=!0),d--,d===0&&c()})},0))}),d===0&&c();return}if(r.async)return Promise.resolve(r.hooks?r.hooks.preprocess(n):n).then(a=>e(a,r)).then(a=>r.walkTokens?Promise.all(be.walkTokens(a,r.walkTokens)).then(()=>a):a).then(a=>t(a,r)).then(a=>r.hooks?r.hooks.postprocess(a):a).catch(i);try{r.hooks&&(n=r.hooks.preprocess(n));const a=e(n,r);r.walkTokens&&be.walkTokens(a,r.walkTokens);let l=t(a,r);return r.hooks&&(l=r.hooks.postprocess(l)),l}catch(a){return i(a)}}}function be(e,t,n){return up(hr.lex,pr.parse)(e,t,n)}be.options=be.setOptions=function(e){return be.defaults={...be.defaults,...e},IC(be.defaults),be},be.getDefaults=Zh,be.defaults=Rr,be.use=function(...e){const t=be.defaults.extensions||{renderers:{},childTokens:{}};e.forEach(n=>{const r={...n};if(r.async=be.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if(o.renderer){const s=t.renderers[o.name];s?t.renderers[o.name]=function(...i){let a=o.renderer.apply(this,i);return a===!1&&(a=s.apply(this,i)),a}:t.renderers[o.name]=o.renderer}if(o.tokenizer){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");t[o.level]?t[o.level].unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),r.extensions=t),n.renderer){const o=be.defaults.renderer||new El;for(const s in n.renderer){const i=o[s];o[s]=(...a)=>{let l=n.renderer[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.renderer=o}if(n.tokenizer){const o=be.defaults.tokenizer||new Tl;for(const s in n.tokenizer){const i=o[s];o[s]=(...a)=>{let l=n.tokenizer[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.tokenizer=o}if(n.hooks){const o=be.defaults.hooks||new yi;for(const s in n.hooks){const i=o[s];yi.passThroughHooks.has(s)?o[s]=a=>{if(be.defaults.async)return Promise.resolve(n.hooks[s].call(o,a)).then(c=>i.call(o,c));const l=n.hooks[s].call(o,a);return i.call(o,l)}:o[s]=(...a)=>{let l=n.hooks[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.hooks=o}if(n.walkTokens){const o=be.defaults.walkTokens;r.walkTokens=function(s){let i=[];return i.push(n.walkTokens.call(this,s)),o&&(i=i.concat(o.call(this,s))),i}}be.setOptions(r)})},be.walkTokens=function(e,t){let n=[];for(const r of e)switch(n=n.concat(t.call(be,r)),r.type){case"table":{for(const o of r.header)n=n.concat(be.walkTokens(o.tokens,t));for(const o of r.rows)for(const s of o)n=n.concat(be.walkTokens(s.tokens,t));break}case"list":{n=n.concat(be.walkTokens(r.items,t));break}default:be.defaults.extensions&&be.defaults.extensions.childTokens&&be.defaults.extensions.childTokens[r.type]?be.defaults.extensions.childTokens[r.type].forEach(function(o){n=n.concat(be.walkTokens(r[o],t))}):r.tokens&&(n=n.concat(be.walkTokens(r.tokens,t)))}return n},be.parseInline=up(hr.lexInline,pr.parseInline),be.Parser=pr,be.parser=pr.parse,be.Renderer=El,be.TextRenderer=lp,be.Lexer=hr,be.lexer=hr.lex,be.Tokenizer=Tl,be.Slugger=cp,be.Hooks=yi,be.parse=be,be.options,be.setOptions,be.use,be.walkTokens,be.parseInline,pr.parse,hr.lex;function Wo({content:e,className:t="",allowHtml:n=!1,style:r}){const o=b.useMemo(()=>{try{if(!n){const i=e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");return typeof be.parse=="function"?be.parse(i):be(i)}return typeof be.parse=="function"?be.parse(e):be(e)}catch(i){return console.error("[MarkdownContent] parse error",i),`<pre class="font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words">Error rendering markdown: ${String(i)}</pre>`}},[e,n]),s=b.useMemo(()=>{const i={color:"currentColor",...r};if(r&&r.color){const a=r.color;return{...i,"--tw-prose-body":a,"--tw-prose-headings":a,"--tw-prose-links":a,"--tw-prose-bold":a,"--tw-prose-counters":a,"--tw-prose-bullets":a,"--tw-prose-hr":a,"--tw-prose-quotes":a,"--tw-prose-quote-borders":a,"--tw-prose-captions":a,"--tw-prose-code":a,"--tw-prose-pre-code":a,"--tw-prose-pre-bg":"inherit","--tw-prose-th-borders":a,"--tw-prose-td-borders":a}}return i},[r]);return u.jsx("div",{className:oe("markdown prose prose-sm max-w-none break-words","dark:prose-invert","text-current","prose-headings:text-current prose-p:text-current prose-li:text-current prose-a:text-current prose-strong:text-current","prose-em:text-current prose-blockquote:text-current prose-table:text-current prose-td:text-current prose-th:text-current","prose-pre:font-mono prose-pre:text-xs prose-pre:bg-background/50 prose-pre:border prose-pre:rounded prose-pre:p-3 prose-pre:whitespace-pre prose-pre:overflow-x-auto","prose-code:font-mono prose-code:text-sm prose-code:bg-background/50 prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-current",t),style:s,dangerouslySetInnerHTML:{__html:o}})}const WC="prose prose-sm max-w-none break-words dark:prose-invert prose-headings:break-words prose-p:break-words prose-li:break-words prose-td:break-words prose-th:break-words prose-a:break-all prose-code:break-words prose-blockquote:break-words";function VC(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}function dp(e){const t=e.content.find(s=>s.type==="tool_call"),n=e.additionalKwargs??{},r=typeof(t==null?void 0:t.id)=="string"&&t.id||typeof n.toolCallId=="string"&&n.toolCallId||(e.id.startsWith("tool-")?e.id.slice(5):void 0);return{name:(typeof(t==null?void 0:t.name)=="string"&&t.name||typeof n.toolName=="string"&&n.toolName||e.name&&String(e.name))??void 0,toolCallId:r??void 0}}function xi(e){if(e==null)return null;const t=String(e).trim();return t.length>0?t:null}function KC(e){const t=o=>{try{const s=Ho(o);return typeof s=="string"?s:JSON.stringify(s??"")}catch{return""}},n=e.filter(o=>o.type==="text");let r="";return n.length?r=t(n.map(o=>o.text).join(`
|
|
136
|
-
`)):r=t(e),r||""}function qC(e){return e.name&&e.name.trim()?e.name:e.model&&e.model.includes("/")?e.model.split("/").pop()||null:e.model||null}function fp(e){if("type"in e&&e.type==="default_message")return`default:${e.content.length}`;const t=e.updatedAt??e.createdAt??"",n=Array.isArray(e.content)?e.content.map(r=>{switch(r.type){case"text":return`t:${r.text.length}`;case"image_url":return"img";case"file":return"file";case"tool_call":return"call";case"interrupt":return"interrupt";default:return"unknown"}}).join("|"):"";return`${e.id}:${t}:${n}`}function GC({className:e}){const[t,n]=b.useState(0);return b.useEffect(()=>{const r=setInterval(()=>n(o=>(o+1)%4),500);return()=>clearInterval(r)},[]),u.jsxs("span",{"aria-live":"polite",className:oe("inline-block text-xs opacity-70 ml-1",e),children:["Is thinking",".".repeat(t)]})}const Il=b.memo(function({message:t,messageIndex:n,isStreamingMessage:r=!1,isEditing:o=!1,showActions:s=!0,showTimestamp:i=!0,showAgentName:a=!0,layoutSize:l="desktop",truncateUserMessages:c=!0,userMessagePreviewLength:d=500,showToolMessages:f=!0,customStyles:h={},onEdit:p,onRegenerate:m,onCancelEdit:g,onCopy:y,activeInterrupt:x,disableInterruptActions:w=!1,onInterruptActionStart:C,onInterruptActionEnd:T,checkpointCandidates:k=[],activeCheckpointId:S=null,onSelectCheckpoint:E,defaultCheckpointId:j=null,messageParentCheckpointId:_=null}){const[P,D]=b.useState(!1),[z,B]=b.useState("preview"),[O,H]=b.useState(!1),{currentThreadId:R}=ps(),{respondToInterrupt:V}=ms(),$=l==="phone"||l==="half-screen",F=t.role,ne=F==="tool",Q=b.useMemo(()=>"type"in t&&t.type==="default_message"?t:null,[t]),ye=!!Q,je=!(r&&F!=="user"),{uploadingFiles:J,handleFileClick:ue,fileViewerOpen:ke,currentFileInfo:te,closeFileViewer:L}=XC({allowFileOpen:je,currentThreadId:R}),q=b.useMemo(()=>{switch(F){case"user":return"text-[hsl(var(--chat-bubble-user-text))]";case"assistant":return"text-[hsl(var(--chat-bubble-ai-text))]";case"tool":return"text-secondary-foreground";case"system":return"text-muted-foreground";default:return"text-[hsl(var(--chat-bubble-ai-text))]"}},[F]),ie=b.useMemo(()=>Q?"":VC(t.content),[Q,t]),ce=b.useMemo(()=>Q?{}:dp(t),[Q,t]),U=b.useMemo(()=>Q?[]:t.content.filter(G=>G.type==="image_url"),[Q,t]),We=b.useMemo(()=>Q?[]:t.content.filter(G=>G.type==="file"),[Q,t]),re=b.useMemo(()=>Q?[]:t.content.filter(G=>G.type==="interrupt"),[Q,t]),xe=(x==null?void 0:x.id)??(x==null?void 0:x.interrupt_id),Pe=xi(xe),$e=x==null?void 0:x.value,rt=b.useMemo(()=>Q?"":KC(t.content),[Q,t]),Se=b.useCallback(async()=>{const G=ne?rt:ie;async function Te(ve){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(ve);return}if(navigator.clipboard&&typeof navigator.clipboard.write=="function"&&typeof ClipboardItem<"u"){const pt=new Blob([ve],{type:"text/plain"});await navigator.clipboard.write([new ClipboardItem({"text/plain":pt})]);return}throw new Error("Clipboard API not supported in this context.")}try{await Te(G),D(!0),setTimeout(()=>D(!1),2e3),y==null||y(G)}catch(ve){console.error("Failed to copy:",ve)}},[ne,rt,ie,y]),Ye=b.useCallback(()=>{if(!p)return;const G=ne?rt:ie,Te="type"in t&&t.type==="default_message"?void 0:{checkpointId:t.checkpointId??null,checkpointNs:t.checkpointNs??null};p(t.id,G,Te)},[p,t.id,ne,rt,ie,t]),ot=b.useCallback(()=>{m==null||m(n)},[m,n]),et=b.useCallback(()=>{const Te=oe($?"h-3 w-3":"h-4 w-4","opacity-60 flex-shrink-0",q);switch(F){case"user":return u.jsx(he.User,{className:Te});case"assistant":return u.jsx(he.Bot,{className:Te});case"tool":return u.jsx(he.Wrench,{className:Te});default:return u.jsx(he.Bot,{className:Te})}},[$,q,F]),Xe=b.useCallback(()=>{const G="group relative mb-4 flex w-full";switch(F){case"user":return oe(G,"justify-end");case"assistant":case"tool":case"system":return oe(G,"justify-start");default:return G}},[F]),Ke=b.useCallback(()=>{const G=oe("rounded-lg px-4 py-3 relative min-w-0 max-w-full break-words",$&&"px-3 py-2 text-sm");if(ye)return oe(G,"w-full","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40 shadow-sm");switch(F){case"user":return oe(G,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-user))] text-[hsl(var(--chat-bubble-user-text))]","border border-transparent");case"assistant":return oe(G,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40");case"tool":return oe(G,"w-full md:max-w-[95%] bg-secondary/50 text-secondary-foreground border border-dashed");case"system":return oe(G,"w-full md:max-w-[85%] bg-accent/40 text-muted-foreground border");default:return oe(G,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40")}},[$,ye,F]);if(ye&&Q)return u.jsx("div",{className:oe(Xe(),h.container),children:u.jsxs("div",{className:oe(Ke(),h.content),children:[u.jsxs("div",{className:"flex items-center gap-2 mb-2 pb-2 border-b border-current/10",children:[u.jsx(he.Bot,{className:oe("h-4 w-4",q)}),a&&u.jsx("span",{className:"font-medium text-sm",children:"Assistant"})]}),u.jsx(Wo,{content:Q.content,className:"text-current"})]})});const tt=b.useCallback(async G=>{if(w)return;const Te=xi((G==null?void 0:G.id)??(G==null?void 0:G.interrupt_id));if(!Te){console.warn("Interrupt part missing id",G);return}try{C==null||C(),await V(Te,!0)}catch(ve){console.error("Failed to approve interrupt:",ve)}finally{T==null||T()}},[w,T,C,V]),
|
|
137
|
-
dark:bg-background/10 dark:border-border/30 dark:hover:bg-background/20`,children:[J[Te]?u.jsx(he.Loader,{className:"h-4 w-4 animate-spin"}):null,u.jsxs("span",{className:"truncate max-w-[180px]",children:[pt,J[Te]?" (processing)":""]})]},Te)}if(G.type==="interrupt"){const ve=G,pt=xi((ve==null?void 0:ve.id)??(ve==null?void 0:ve.interrupt_id)),mt=!!(Pe&&pt&&pt===Pe),ct=mt?$e??(ve==null?void 0:ve.value):ve==null?void 0:ve.value,Me=pt?{...ve,id:pt,interrupt_id:pt}:ve;return u.jsx(YC,{interruptPart:Me,onApprove:tt,onReject:_t,disabled:w,isActive:mt,payload:ct},Te)}return null},[ue,J,tt,_t,F,c,d,O,$,Pe,$e,x,w,re]),nt=b.useCallback(()=>u.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted/30 rounded",children:[u.jsx(he.Paperclip,{className:"h-4 w-4 text-muted-foreground"}),u.jsx("span",{className:"text-sm text-muted-foreground",children:"File upload"})]}),[]),yt=b.useCallback(()=>{const G=ie.trim().length>0||U.length>0||We.length>0||re.length>0;if(!ne&&We.length>0&&!r)return nt();if(!ne&&!G&&!r)return null;if(ne)return u.jsx(ZC,{message:t,viewMode:z},t.id);if(!ne&&!Q){const Te=t,ve=u.jsx("div",{className:"space-y-2",children:Te.content.map((pt,mt)=>u.jsx(St,{part:pt,i:mt},mt))});return r?u.jsxs("div",{"aria-busy":"true",role:"status",children:[ve,u.jsx(GC,{className:q})]}):ve}},[ie,U.length,We.length,re.length,r,ne,z,nt,q]),Nt=b.useMemo(()=>Q?"Assistant":qC(t),[Q,t]),st=b.useMemo(()=>Q?[]:Array.isArray(k)?k:[],[k,Q]),Gt=b.useMemo(()=>{var G;return st.length?j&&st.some(Te=>Te.id===j)?j:((G=st[0])==null?void 0:G.id)??null:null},[j,st]),Xt=b.useMemo(()=>!st.length||!S?null:st.some(G=>G.id===S)?S:null,[S,st])??Gt,Jt=F==="user"&&st.length>0&&typeof E=="function",ft=b.useCallback(G=>{if(!E)return;const Te=(G==null?void 0:G.id)??null,ve=(G==null?void 0:G.parentId)??_??null;E(Te,ve)},[_,E]),Ve=b.useMemo(()=>Xt?st.findIndex(G=>G.id===Xt):-1,[Xt,st]),Mt=b.useMemo(()=>Ve<0?null:st[Ve]??null,[Ve,st]),jt=b.useCallback(G=>{const Te=[];if(G.step!==null&&Te.push(`Step ${G.step}`),G.source&&Te.push(G.source),!G.createdAt)return Te.length?Te.join(" • "):G.id.slice(0,8);let ve="";try{const pt=new Date(G.createdAt);Number.isNaN(pt.getTime())||(ve=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(pt))}catch{ve=""}return`${ve}`},[]);return ne&&!f?null:u.jsxs(u.Fragment,{children:[u.jsx("div",{className:oe(Xe(),h.container),children:u.jsxs("div",{className:oe(Ke(),h.content),children:[(i||a||ne)&&u.jsxs("div",{className:oe("flex items-center justify-between mb-2 pb-2 border-b border-current/10",$&&"mb-1 pb-1",q,h.header),children:[u.jsxs("div",{className:"flex items-center gap-2",children:[et(),a&&Nt&&u.jsx("span",{className:oe("font-medium",$?"text-xs":"text-sm"),children:Nt}),ne&&u.jsxs(Sh,{variant:"outline",className:oe("text-xs flex items-center gap-1 cursor-pointer select-none",q,"border border-current/40",$&&"text-xs h-4"),role:"button",tabIndex:0,"aria-expanded":z==="expanded",onClick:()=>B(G=>G==="expanded"?"preview":"expanded"),onKeyDown:G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),B(Te=>Te==="expanded"?"preview":"expanded"))},children:[u.jsx("span",{children:ce.name??"Tool Output"}),ce.toolCallId&&u.jsx("span",{className:"opacity-70",children:ce.toolCallId.slice(0,8)}),z==="expanded"?u.jsx(he.ChevronUp,{className:"h-3 w-3"}):u.jsx(he.ChevronDown,{className:"h-3 w-3"})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[Jt&&Mt&&Ve>=0&&u.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[u.jsx("button",{type:"button",className:oe("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",Ve>0?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(Ve<=0)return;const G=st[Ve-1];G&&ft(G)},"aria-label":"Previous checkpoint",disabled:Ve<=0,children:u.jsx(he.ChevronLeft,{className:"h-3 w-3"})}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs("span",{className:"whitespace-nowrap",children:[Ve+1," / ",st.length]}),u.jsx("span",{className:"text-muted-foreground",children:jt(Mt)})]}),u.jsx("button",{type:"button",className:oe("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",Ve<st.length-1?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(Ve>=st.length-1)return;const G=st[Ve+1];G&&ft(G)},"aria-label":"Next checkpoint",disabled:Ve>=st.length-1,children:u.jsx(he.ChevronRight,{className:"h-3 w-3"})})]}),i&&t.createdAt&&u.jsx("time",{className:oe("text-xs opacity-60",q,$&&"text-xs"),dateTime:new Date(t.createdAt).toISOString(),title:new Date(t.createdAt).toLocaleString(),children:new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(new Date(t.createdAt))}),s&&!o&&u.jsxs("div",{className:oe("opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",h.actions),children:[u.jsx("div",{className:"relative",children:u.jsx(ut,{variant:"ghost",size:"sm",onClick:()=>Se(),className:oe("h-6 w-6 p-0 hover:bg-foreground/10",q,$&&"h-5 w-5"),"aria-label":"Copy message",title:"Copy message",children:u.jsx(he.Copy,{className:oe(P?"text-success":q,$?"h-3 w-3":"h-4 w-4")})})}),F==="user"&&p&&u.jsx(ut,{variant:"ghost",size:"sm",onClick:Ye,className:oe("h-6 w-6 p-0 hover:bg-foreground/10",q,$&&"h-5 w-5"),"aria-label":"Edit message",children:u.jsx(he.Edit,{className:oe(q,$?"h-3 w-3":"h-4 w-4")})}),F==="assistant"&&m&&u.jsx(ut,{variant:"ghost",size:"sm",onClick:ot,className:oe("h-6 w-6 p-0 hover:bg-foreground/10",q,$&&"h-5 w-5"),"aria-label":"Regenerate response",children:u.jsx(he.RotateCcw,{className:oe(q,$?"h-3 w-3":"h-4 w-4")})})]})]})]}),u.jsx("div",{className:"relative",children:yt()}),ne&&z==="expanded"&&(ce.toolCallId||ce.name)&&u.jsxs("div",{className:oe("mt-2 pt-2 border-t border-current/10 text-xs opacity-60",$&&"text-xs"),children:[ce.name&&u.jsxs("div",{children:["Function: ",ce.name]}),ce.toolCallId&&u.jsxs("div",{children:["Call ID: ",ce.toolCallId]})]}),!(i||a||ne)&&s&&!o&&u.jsxs("div",{className:oe("absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",h.actions),children:[u.jsx(ut,{variant:"ghost",size:"sm",onClick:()=>Se(),className:oe("h-6 w-6 p-0 hover:bg-background/50 text-current",$&&"h-5 w-5"),children:u.jsx(he.Copy,{className:oe(P?"text-success":"text-current",$?"h-3 w-3":"h-4 w-4")})}),F==="user"&&p&&u.jsx(ut,{variant:"ghost",size:"sm",onClick:Ye,className:oe("h-6 w-6 p-0 hover:bg-background/50 text-current",$&&"h-5 w-5"),children:u.jsx(he.Edit,{className:oe("text-current",$?"h-3 w-3":"h-4 w-4")})}),F==="assistant"&&m&&u.jsx(ut,{variant:"ghost",size:"sm",onClick:ot,className:oe("h-6 w-6 p-0 hover:bg-background/50 text-current",$&&"h-5 w-5"),children:u.jsx(he.RotateCcw,{className:oe("text-current",$?"h-3 w-3":"h-4 w-4")})})]})]})}),te&&u.jsx(EC,{isOpen:ke,onClose:L,fileId:te.id,fileName:te.name,mimeType:te.mimeType})]})},(e,t)=>{var i,a,l,c,d,f,h,p;if(t.isStreamingMessage||e.isStreamingMessage||!(e.message.id===t.message.id&&fp(e.message)===fp(t.message)))return!1;const o=["isEditing","showActions","layoutSize","showTimestamp","showAgentName","truncateUserMessages","userMessagePreviewLength","showToolMessages"].every(m=>e[m]===t[m]),s=((i=e.customStyles)==null?void 0:i.container)===((a=t.customStyles)==null?void 0:a.container)&&((l=e.customStyles)==null?void 0:l.content)===((c=t.customStyles)==null?void 0:c.content)&&((d=e.customStyles)==null?void 0:d.actions)===((f=t.customStyles)==null?void 0:f.actions)&&((h=e.customStyles)==null?void 0:h.header)===((p=t.customStyles)==null?void 0:p.header);return o&&s});function hp({data:e}){return Array.isArray(e)?e.every(n=>n===null||["string","number","boolean"].includes(typeof n))?u.jsx("div",{className:WC,children:u.jsx("ul",{className:"list-disc pl-5",children:e.map((n,r)=>u.jsx("li",{children:String(n)},r))})}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:Uo(e)}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:Uo(e)})}function YC({interruptPart:e,onApprove:t,onReject:n,disabled:r,isActive:o,payload:s}){const i=e.title??"Approve the result?";let a=null;if(s!=null)if(typeof s=="string")a=u.jsx("p",{className:"text-sm leading-relaxed text-blue-800/90 dark:text-blue-200/90 whitespace-pre-wrap",children:s});else{const c=Uo(s);a=u.jsx("pre",{className:"max-h-48 overflow-auto rounded bg-blue-100/60 p-2 text-xs text-blue-900/90 dark:bg-blue-900/40 dark:text-blue-100/80",children:c})}const l=o?"Please approve or reject this action to resume the workflow.":"Waiting for approval from another participant.";return u.jsxs(Lo,{className:oe("border-blue-200 dark:border-blue-800 bg-blue-50/50 dark:bg-blue-950/10 transition-shadow",o?"shadow-md ring-1 ring-blue-300 dark:ring-blue-500/70":"opacity-80"),children:[u.jsxs(Fo,{className:"pb-3",children:[u.jsx($o,{className:"text-blue-900 dark:text-blue-100 text-base",children:i}),u.jsx(Ch,{className:"text-blue-700 dark:text-blue-300 text-sm",children:l})]}),a&&u.jsx(zo,{className:"pt-0 pb-3",children:a}),u.jsx(kh,{className:"pt-0",children:u.jsxs("div",{className:"flex gap-2 ml-auto",children:[u.jsx(ut,{size:"sm",variant:"outline",onClick:()=>n(e),className:"border-red-300 text-red-700 hover:bg-red-50 dark:border-red-700 dark:text-red-300 dark:hover:bg-red-950/50",disabled:r||!o,children:"Reject"}),u.jsx(ut,{size:"sm",onClick:()=>t(e),className:"bg-blue-600 hover:bg-blue-700 text-white",disabled:r||!o,children:"Approve"})]})})]})}function XC(e){const{allowFileOpen:t,currentThreadId:n}=e,{toast:r}=wl(),[o,s]=b.useState({}),[i,a]=b.useState(null),[l,c]=b.useState(!1),d=b.useCallback(()=>{c(!1),a(null)},[]),f=b.useCallback(p=>{a(p),c(!0)},[]),h=b.useCallback(async(p,m,g)=>{var y,x;if(!t){p.preventDefault();return}if(o[g]){p.preventDefault();return}try{const w=String(m.url??""),C=w.match(/\/chat\/files\/([^/]+)(?:\/(view|download))?/);if(C){p.preventDefault();const T=C[1],k=m.name||`file_${T}`,S=m.mimeType||"application/octet-stream";f({id:T,name:k,mimeType:S});return}if(w.startsWith("data:")){p.preventDefault(),s(k=>({...k,[g]:!0}));const T=r({title:"Fetching file...",description:"",open:!0});try{const k=await uC(n??void 0);if(!k||!Array.isArray(k))throw new Error("Invalid file list response");const S=k.find(E=>!E||typeof E!="object"||!((E.filename??"")===(m.name??""))?!1:typeof m.size=="number"&&typeof E.size=="number"?E.size===m.size:!0);if(!(S!=null&&S.id))throw new Error(`File "${m.name}" is not yet available on the server`);if(!S.id||!S.filename)throw new Error("Invalid file data received from server");f({id:S.id,name:m.name||S.filename||`file_${S.id}`,mimeType:m.mimeType||S.mime_type||"application/octet-stream"}),(y=T.update)==null||y.call(T,{id:T.id,title:"Success",description:`Opened ${m.name}`,open:!0})}catch(k){console.error("Failed to fetch server file:",k);const S=k instanceof Error?k.message:"Unknown error occurred";(x=T.update)==null||x.call(T,{id:T.id,title:"Failed",description:S}),r({title:"Failed to fetch file",description:S,open:!0})}finally{s(k=>({...k,[g]:!1}))}}}catch(w){console.error("File click error:",w),s(C=>({...C,[g]:!1}))}},[t,o,r,n,f]);return{uploadingFiles:o,handleFileClick:h,fileViewerOpen:l,currentFileInfo:i,closeFileViewer:d}}function JC({text:e,expanded:t,onExpandedChange:n,previewLength:r,isCompact:o}){const s=Math.max(e.length-r,0),i=e.substring(0,r);return u.jsxs("div",{className:"flex flex-col gap-1",children:[u.jsx("div",{className:oe("text-sm text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:t?u.jsx(Wo,{content:e,allowHtml:!1}):u.jsxs("pre",{className:oe("font-sans whitespace-pre-wrap break-words bg-transparent p-0 m-0 text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:[i,"..."]})}),u.jsx(ut,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-xs !text-[hsl(var(--chat-bubble-user-text))]",onClick:()=>n(!t),children:t?u.jsxs(u.Fragment,{children:[u.jsx(he.ChevronUp,{className:"h-3 w-3 mr-1"})," Show less"]}):u.jsxs(u.Fragment,{children:[u.jsx(he.ChevronDown,{className:"h-3 w-3 mr-1"})," Show more (",s," chars)"]})})]})}function ZC({message:e,viewMode:t}){const r=dp(e).name||"tool",o=c=>{if(c==null)return null;const d=typeof c=="string"?bl(c)??c:c;if(d&&typeof d=="object")return u.jsx(hp,{data:d});const f=typeof d=="string"?d:(()=>{try{return Uo(d)}catch{return String(d??"")}})();return u.jsx("pre",{className:"whitespace-pre-wrap break-words font-sans text-sm text-foreground/90",children:f})},s=c=>{if(c==null)return null;const{content:d,isMarkdown:f}=fC(c);return f?u.jsx(Wo,{content:d,className:"text-current"}):o(c)};if(t==="preview")return null;const i=e.content.find(c=>c.type!=="tool_call");if(!i)return u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(he.Loader,{className:"h-4 w-4 animate-spin"}),u.jsxs("span",{children:["Waiting for ",r," output…"]})]});if(i.type==="text"){const d=(i.text??"").trim();if(!d)return null;const f=li(d);return s(f)}const a=Ho(i),l=li(a);return s(l)}const pp=(e,t)=>(e==null?void 0:e.id)??`message-${t}`,QC=e=>{const t=e.additionalKwargs??{},n=e.responseMetadata??{},r=t.originalMessageId??n.originalMessageId??t.original_message_id??n.original_message_id;return typeof r=="string"&&r.trim()?r.trim():e.id},Nl=b.forwardRef(({messages:e,isStreaming:t,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onStartReached:a,onEdit:l,onRegenerate:c,onCancelEdit:d,className:f,style:h,emptyMessage:p,followNewMessages:m=!0,isNavigatingCheckpoint:g=!1,onScrollAway:y,onAtBottom:x,activeInterrupt:w,disableInterruptActions:C=!1,onInterruptActionStart:T,onInterruptActionEnd:k,showToolMessages:S=!0,checkpointMetaById:E,checkpointIndexByKey:j,activeCheckpointId:_,onSelectCheckpoint:P,timelineCheckpoints:D},z)=>{const B=b.useRef(null),O=b.useRef(null),H=b.useRef(!1),[R,V]=b.useState(!0),$=b.useMemo(()=>w?e.some(re=>"type"in re&&re.type==="default_message"?!1:Array.isArray(re==null?void 0:re.content)&&re.content.some(xe=>xe&&xe.type==="interrupt"&&(xe.id??xe.interrupt_id)===w.id)):!1,[w,e]),F=b.useMemo(()=>{if(!w||$)return null;const re=w.id&&String(w.id).trim()?String(w.id).trim():"pending-interrupt";let xe;const Pe=w.value;if(Pe&&typeof Pe=="object"&&!Array.isArray(Pe)){const $e=Pe.title;typeof $e=="string"&&$e.trim()&&(xe=$e.trim())}return{id:`interrupt-${re}`,role:"system",createdAt:new Date().toISOString(),content:[{type:"interrupt",id:re,value:Pe,title:xe}]}},[w,$]),ne=b.useMemo(()=>F?[...e,F]:e,[e,F]),Q=b.useMemo(()=>S?ne:ne.filter(re=>(re==null?void 0:re.role)!=="tool"),[ne,S]),ye=b.useMemo(()=>{const re=new Set,xe=[];for(let Pe=Q.length-1;Pe>=0;Pe--){const $e=Q[Pe];if(!$e)continue;if("type"in $e&&$e.type==="default_message"){xe.push($e);continue}const rt=$e,Se=QC(rt);re.has(Se)||(re.add(Se),xe.push(rt))}return xe.reverse()},[Q]),je=b.useCallback(re=>{V(re),y&&y(!re),x&&x(re)},[y,x]),J=b.useMemo(()=>{if(a)return async()=>{if(!H.current){H.current=!0;try{await a()}finally{H.current=!1}}}},[a]),ue=b.useMemo(()=>!m||g?!1:R?"auto":!1,[R,m,g]),ke=b.useMemo(()=>D??[],[D]),te=_??(ke.length?ke[ke.length-1].id:null),L=ke.length>0,q=b.useMemo(()=>{if(typeof p!="string")return null;const re=p.trim();return re?{id:"default-message",role:"assistant",type:"default_message",content:re,createdAt:new Date().toISOString()}:null},[p]),ie=L?u.jsxs("div",{className:"hidden w-48 flex-shrink-0 flex-col border-r border-border/40 pr-4 md:flex",children:[u.jsxs("div",{className:"relative flex-1 overflow-y-auto pt-5 pb-5 pr-1",children:[u.jsxs("div",{className:"absolute left-0 right-0 top-1 flex items-center justify-between px-2 pb-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[u.jsx("span",{children:"Timeline"}),u.jsxs("div",{className:"group relative z-50",children:[u.jsx(he.Info,{className:"h-3.5 w-3.5 text-muted-foreground cursor-help"}),u.jsx("div",{className:"pointer-events-auto fixed hidden w-56 rounded-md border bg-background p-3 text-[11px] font-normal text-muted-foreground shadow-lg group-hover:block whitespace-normal leading-relaxed",style:{zIndex:9999},children:'Shows user inputs and the latest loop checkpoint. Click a dot to jump the chat to that point. Click on the "Latest" button to return to the most recent messages.'})]})]}),u.jsx("div",{className:"pointer-events-none absolute left-5 top-0 bottom-0 w-px bg-border/50"}),u.jsx("div",{className:"flex flex-col gap-4",children:ke.map(re=>{const xe=te===re.id;return u.jsxs("button",{type:"button",disabled:!P,onClick:()=>P==null?void 0:P(re.id),className:`relative flex items-start gap-3 text-left text-xs transition ${xe?"text-primary":"text-muted-foreground"} ${P?"hover:text-foreground":"cursor-default opacity-70"}`,children:[u.jsx("span",{className:`mt-1 inline-flex h-4 w-4 items-center justify-center rounded-full border ${xe?"border-primary bg-primary/10 text-primary":"border-border bg-background"}`,children:u.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${xe?"bg-primary":"bg-border"}`})}),u.jsxs("span",{className:"flex-1",children:[u.jsx("span",{className:"block font-medium",children:re.label||"User input"}),u.jsxs("span",{className:"text-[10px] uppercase tracking-wide text-muted-foreground/70",children:[re.step!==null?`STEP ${re.step}`:"STEP —",re.next?` - ${re.next}`:""]})]})]},re.id)})})]}),P&&u.jsx("button",{type:"button",onClick:()=>P==null?void 0:P(null),className:"mt-auto rounded-md border border-border/70 px-3 py-2 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground transition hover:border-foreground/60 hover:text-foreground",children:"Latest"})]}):null,ce=["flex h-full flex-col md:flex-row",f].filter(Boolean).join(" "),U=()=>q?u.jsx("div",{className:"p-6 h-full overflow-y-auto",children:u.jsx("div",{className:"w-full max-w-full",children:u.jsx(Il,{message:q,messageIndex:0,isStreamingMessage:!1,showActions:!1,showTimestamp:!1,showAgentName:!0,layoutSize:o,onEdit:()=>{},onRegenerate:()=>{},onCancelEdit:()=>{}})})}):u.jsx("div",{className:"flex h-full items-center justify-center py-8 text-center text-muted-foreground",children:p??"No messages yet. Start a conversation!"}),We=ye.length>0;return b.useImperativeHandle(z,()=>({scrollToLatest:()=>{var re,xe;if(B.current&&ye.length>0){const Pe=ye.length-1;(xe=(re=B.current).scrollToIndex)==null||xe.call(re,{index:Pe,align:"end",behavior:"auto"})}else O.current&&(O.current.scrollTop=O.current.scrollHeight)},scrollToTop:()=>{var re,xe;B.current&&ye.length>0?(xe=(re=B.current).scrollToIndex)==null||xe.call(re,{index:0,align:"start",behavior:"auto"}):O.current&&(O.current.scrollTop=0)}}),[ye]),u.jsxs("div",{className:ce,style:h,children:[ie,u.jsx("div",{className:"relative flex-1 min-h-0",children:We?u.jsx(HS,{ref:re=>{B.current=re},scrollerRef:re=>{O.current=re instanceof HTMLDivElement?re:null},data:ye,followOutput:ue,overscan:200,increaseViewportBy:{top:100,bottom:200},defaultItemHeight:80,atBottomThreshold:50,alignToBottom:!1,startReached:()=>{J&&J()},atBottomStateChange:je,style:{height:"100%",overscrollBehavior:"contain"},computeItemKey:(re,xe)=>pp(xe,re),itemContent:(re,xe)=>{var tt;const Pe=pp(xe,re),$e="type"in xe&&xe.type==="default_message";let rt=[],Se=null,Ye={},ot={},et=null,Xe=null;if(!$e){const _t=xe,St=_t.checkpointId??null;Ye=_t.additionalKwargs??{},ot=_t.responseMetadata??{};const nt=St&&E?E.get(St)??null:null;et=typeof Ye.step=="number"?Ye.step:typeof ot.step=="number"?ot.step:(nt==null?void 0:nt.step)??null;const yt=typeof Ye.source=="string"?Ye.source:typeof ot.source=="string"?ot.source:(nt==null?void 0:nt.source)??null;Xe=yt?String(yt):null;const Nt=et!==null&&Xe?`${et}:${Xe}`:null;Nt&&(j!=null&&j.has(Nt))?rt=j.get(Nt)??[]:St&&nt&&(rt=[nt]),Se=St??((tt=rt[0])==null?void 0:tt.id)??null}const Ke=(()=>{if(typeof Ye.parentCheckpointId=="string")return Ye.parentCheckpointId;if(typeof ot.parentCheckpointId=="string")return ot.parentCheckpointId})();return u.jsx("div",{className:"relative mb-4 last:mb-0","data-message-id":Pe,style:{minHeight:"60px",containIntrinsicSize:"auto 120px"},children:u.jsx(Il,{message:xe,messageIndex:re,isStreamingMessage:t&&n===xe.id,streamingDebounceMs:r,isEditing:i===xe.id,showActions:s,showTimestamp:!1,showAgentName:!0,layoutSize:o,onEdit:l,onRegenerate:()=>c(re),onCancelEdit:d,activeInterrupt:w,disableInterruptActions:C,onInterruptActionStart:T,onInterruptActionEnd:k,showToolMessages:S,checkpointCandidates:rt,activeCheckpointId:_??null,onSelectCheckpoint:P,defaultCheckpointId:Se,messageParentCheckpointId:Ke})})}}):U()})]})});Nl.displayName="MessageList";const mp={value:""};function vi({className:e="",placeholder:t="Type your message...",autoFocus:n=!0,maxHeight:r=void 0,streamingDebounceMs:o=500,streamingThrottleMs:s,followNewMessages:i=!0,enableFileUpload:a=!0,enableExcelUpload:l=!1,enableMessageEditing:c=!0,showToolMessages:d=!0,customStyles:f={},onMessageSent:h,onExcelUploadSuccess:p,onError:m}){const{api:g}=Yi(),{currentThreadId:y}=ps(),{threadId:x,messages:w,hasMore:C,isHistoryLoading:T,isLoading:k,loadOlder:S,navigateToCheckpoint:E,returnToLatest:j,checkpoint:_,checkpoints:P,interrupt:D,metadata:z}=ms(),{isStreaming:B,error:O,connectionState:H,submit:R,stop:V}=du(),$=x??y??null,F=(_==null?void 0:_.id)??null,ne=(_==null?void 0:_.namespace)??null,Q=(z==null?void 0:z.assemblingMessageId)??null,ye=D,[je,J]=b.useState(!1);b.useEffect(()=>{ye||J(!1)},[ye]);const ue=b.useCallback(()=>{J(!0)},[]),ke=b.useCallback(()=>{J(!1)},[]),te=!!ye||je,[L,q]=b.useState(null),[ie,ce]=b.useState(""),[U,We]=b.useState(null),[re,xe]=b.useState(null),[Pe,$e]=b.useState([]),[rt,Se]=b.useState(0),[Ye,ot]=b.useState(0),[et,Xe]=b.useState(!1),[Ke,tt]=b.useState(null),[_t,St]=b.useState(null),[nt,yt]=b.useState(!1),[Nt,st]=b.useState(null),[Gt,Yt]=b.useState(!1),Xt=b.useRef(!1),[Jt,ft]=b.useState(()=>mp.value),Ve=b.useRef(Jt),Mt=b.useRef(null),jt=b.useCallback(Z=>{mp.value=Z,ft(Z)},[]),[G,Te]=b.useState(!1),ve=b.useRef(null),pt=b.useCallback(Z=>{if(!Array.isArray(Z))return{text:null,messageId:null};for(let se=Z.length-1;se>=0;se--){const de=Z[se];if(!de||de.role!=="user")continue;const Ie=(de.content??[]).filter(Je=>(Je==null?void 0:Je.type)==="text").map(Je=>Je.text).filter(Je=>typeof Je=="string"&&Je.trim().length>0);return{text:Ie.length?Ie.join(" ").trim():null,messageId:de.id??null}}return{text:null,messageId:null}},[]),mt=b.useCallback((Z,se)=>{if(!Z||typeof Z!="object")return null;const de=Z[se];return typeof de=="number"?de:null},[]),ct=b.useCallback((Z,se)=>{if(!Z||typeof Z!="object")return null;const de=Z[se];return typeof de=="string"&&de.trim()?de:null},[]),Me=b.useMemo(()=>{const Z=Ie=>{if(!Array.isArray(Ie)||Ie.length===0)return null;const lt=Ie.map(Je=>{if(typeof Je=="string")return Je.trim();if(Je&&typeof Je=="object"&&"type"in Je){const it=Je;if(typeof it.type=="string")return it.type}return null}).filter(Je=>!!(Je&&Je.length));return lt.length?lt.join(", "):null},se=Array.isArray(P)?P.map(Ie=>{const lt=Z(Ie.next);return lt?{...Ie,metadata:{...Ie.metadata??{},next:lt}}:Ie}):[];return se.some(Ie=>mt(Ie.metadata,"step")!==null)&&se.sort((Ie,lt)=>{const Je=mt(Ie.metadata,"step"),it=mt(lt.metadata,"step");if(Je!==null||it!==null)return(it??Number.NEGATIVE_INFINITY)-(Je??Number.NEGATIVE_INFINITY);const Bt=Date.parse(Ie.createdAt??""),sn=Date.parse(lt.createdAt??"");return Number.isNaN(Bt)||Number.isNaN(sn)?0:sn-Bt}),se},[P,mt]),{checkpointMetaById:Ut,checkpointIndexByKey:Le}=b.useMemo(()=>{const Z=new Map,se=new Map;for(const de of Me){const Ie=de.checkpointId??null;if(!Ie)continue;const lt=mt(de.metadata,"step"),Je=ct(de.metadata,"source"),it={id:Ie,step:lt,source:Je,createdAt:de.createdAt??null,namespace:de.checkpointNs??null,parentId:de.parentId??null};if(Z.set(Ie,it),lt!==null&&Je){const Bt=`${lt}:${Je}`,sn=se.get(Bt)??[];sn.push(it),se.set(Bt,sn)}}for(const de of se.values())de.sort((Ie,lt)=>{const Je=Ie.createdAt??"";return(lt.createdAt??"").localeCompare(Je)});return{checkpointMetaById:Z,checkpointIndexByKey:se}},[Me,mt,ct]),xt=b.useMemo(()=>{var Je;if(!Me.length)return[];const Z=[...Me].reverse(),se=(it,Bt)=>{const sn=it.checkpointId??null;if(!sn)return null;const Xn=ct(it.metadata,"source");ct(it.metadata,"next");const{text:Ko,messageId:_i}=pt(it.messages),Nn=Ko&&Ko.replace(/\s+/g," ").trim()||ct(it.metadata,"title")||ct(it.metadata,"label")||Bt||Xn||"Checkpoint",ji=Nn.length>60?`${Nn.slice(0,57)}…`:Nn;return{id:sn,label:ji,messageId:_i??null,createdAt:it.createdAt??null,step:mt(it.metadata,"step"),source:Xn??null,next:ct(it.metadata,"next")}},de=[],Ie=new Set;for(const it of Z){const Bt=((Je=ct(it.metadata,"source"))==null?void 0:Je.toLowerCase())??null;if(!(Bt==="input"||Bt==="user_input"||Bt==="user"))continue;const Xn=se(it,"User input");Xn&&!Ie.has(Xn.id)&&(de.push(Xn),Ie.add(Xn.id))}if(!de.length)for(const it of Z){const Bt=se(it);Bt&&!Ie.has(Bt.id)&&(de.push(Bt),Ie.add(Bt.id))}const lt=Me.find(it=>{var sn;return(((sn=ct(it.metadata,"source"))==null?void 0:sn.toLowerCase())??null)==="loop"});if(lt){const it=se(lt,"Latest loop");it&&!Ie.has(it.id)&&(de.push(it),Ie.add(it.id))}return de},[Me,pt,mt,ct]),Ln=b.useRef(null),Dt=b.useRef(null),fn=b.useCallback(()=>{Ln.current&&(Ln.current.value=""),Dt.current&&(Dt.current.value=""),Se(Z=>Z+1),ot(Z=>Z+1)},[]),io=b.useCallback(Z=>{jt(Z)},[jt]),ao=b.useRef(!1);b.useEffect(()=>{ao.current&&!B&&($e([]),fn()),ao.current=B},[B,fn]);const[Lr,Fr]=b.useState("desktop");b.useEffect(()=>{const Z=()=>{const se=window.innerWidth;Fr(se<640?"phone":se<1024?"tablet":"desktop")};return Z(),window.addEventListener("resize",Z),()=>window.removeEventListener("resize",Z)},[]),b.useEffect(()=>{Yt(!1),Xt.current=!1},[$]),b.useEffect(()=>{Ve.current=Jt},[Jt]),b.useEffect(()=>{if(!L){Mt.current=null;return}Mt.current===null&&(Mt.current=Ve.current),jt(ie??"")},[ie,L,jt]);const N=b.useCallback(async()=>{if(!(!C||T||!Gt))try{await S()}catch(Z){console.warn("loadOlder failed",Z)}},[C,Gt,T,S]);b.useEffect(()=>{(async()=>{if(!g.baseUrl){st(null);return}try{const de=(await g.getAgent("default")).uiDefaultMessage||"";st(de||null)}catch(se){console.warn("Failed to fetch default message:",se),st(null)}})()},[g.baseUrl]),b.useEffect(()=>{O&&!nt&&(m==null||m(O))},[O,nt,m]);const Y=Z=>{if(Z.length>Ks)return`Message too long (${Z.length}/${Ks} characters)`;try{return P0(Z),null}catch(se){return(se==null?void 0:se.message)||"Invalid message"}},ae=async Z=>{const se=Z.trim();if(!(!se&&Pe.length===0)){if(se){const de=Y(se);if(de){xe(de);return}}try{const de=F??void 0,Ie=ne??void 0,lt=L?{edit:!0,originalMessageId:L,...U!=null&&U.checkpointId?{originalCheckpointId:U.checkpointId}:{},...U!=null&&U.checkpointNs?{originalCheckpointNs:U.checkpointNs}:{}}:void 0;await R({text:se||"",attachments:Pe,messageAdditionalKwargs:lt},{checkpointId:de,checkpointNs:Ie}),h==null||h(se),jt(""),xe(null),$e([]),fn(),q(null),ce(""),We(null)}catch(de){const Ie=(de==null?void 0:de.message)||"Failed to send message";xe(Ie),m==null||m(Ie)}}},Ce=b.useCallback((Z,se,de)=>{c&&(Mt.current=Jt,q(Z),ce(se),jt(se),xe(null),We({checkpointId:(de==null?void 0:de.checkpointId)??null,checkpointNs:(de==null?void 0:de.checkpointNs)??null}))},[Jt,c,jt]),Ge=b.useCallback(()=>{q(null),ce(""),We(null),xe(null),jt(Mt.current??Jt),Mt.current=null},[Jt,jt]),qe=b.useCallback((Z,se,de)=>{Ce(Z,se,de)},[Ce]),He=b.useCallback(Z=>{for(let se=Z-1;se>=0;se--)if(w[se].role==="user"){const de=w[se].content||[],lt=de.filter(Je=>Je.type==="text").map(Je=>Je.text).join("")||(()=>{try{return JSON.stringify(de,null,2)}catch{return String(de)}})();lt&&R({text:lt},{checkpointId:F??void 0,checkpointNs:ne??void 0});break}},[w,R,F,ne]),Re=Z=>{const se=Array.from(Z.target.files||[]);$e(de=>[...de,...se]),Z.target.value=""},At=Z=>{$e(se=>{const de=se.filter((Ie,lt)=>Z!==lt);return de.length===0&&fn(),de})},gt=async Z=>{const se=(Z.target.files||[])[0];if(se){tt(null),St(null),Xe(!0);try{await R({attachments:[se]},{checkpointId:F??void 0,checkpointNs:ne??void 0});const de=`Uploaded ${se.name} - processing through chat stream`;St(de)}catch(de){const Ie=de instanceof Error?de.message:"Failed to upload Excel file";console.error("Excel upload failed",de),tt(Ie),m==null||m(Ie)}finally{Xe(!1),Z.target.value="",fn()}}},Ct=async Z=>{if(y){Te(!0);try{if(!Z){await j(),Yt(!1),requestAnimationFrame(()=>{var Ie;(Ie=ve.current)==null||Ie.scrollToLatest()});return}const se=Me.find(Ie=>Ie.checkpointId===Z),de=(se==null?void 0:se.checkpointNs)??null;await E(Z,de),Yt(!0),requestAnimationFrame(()=>{var Ie;(Ie=ve.current)==null||Ie.scrollToTop()})}finally{Te(!1)}}},Zt=b.useCallback(async Z=>{await Ct(Z)},[Ct]),Fn=`flex flex-1 w-full flex-col min-h-0 min-w-0 max-h-full overflow-hidden bg-transparent ${e} ${f.container||""}`,hn=`flex-1 min-h-0 min-w-0 max-h-full w-full overflow-hidden overscroll-contain break-words break-anywhere p-4 bg-transparent ${f.messagesArea||""}`,zt=`flex-shrink-0 w-full border-t p-4 bg-transparent ${f.inputArea||""}`,$n=b.useCallback(Z=>{if(!Z)return"Latest";const se=[];Z.step!==null&&se.push(`Step ${Z.step}`),Z.source&&se.push(Z.source);const de=Z.createdAt?new Date(Z.createdAt):null,Ie=de&&!Number.isNaN(de.getTime())?de.toLocaleString():Z.createdAt??Z.id,lt=se.length?` — ${se.join(" • ")}`:"";return`${Ie}${lt}`},[]);return u.jsxs("div",{className:Fn,children:[!!O&&!nt&&u.jsxs("div",{className:"flex-shrink-0 bg-red-50 border border-red-200 text-red-800 px-4 py-2 text-sm flex items-center justify-between",children:[u.jsx("span",{children:O}),u.jsx(ut,{variant:"ghost",size:"sm",onClick:()=>yt(!0),className:"text-red-800 hover:bg-red-100","aria-label":"Dismiss error",children:u.jsx(he.X,{size:16})})]}),y&&Me.length>0&&u.jsxs("div",{className:"flex-shrink-0 flex items-center gap-2 px-4 py-2 border-b border-border bg-muted/60 text-xs dark:bg-muted/50",children:[u.jsx("span",{className:"opacity-70",children:"Checkpoint:"}),u.jsxs("select",{className:"border border-border rounded px-2 py-1 text-xs bg-card text-foreground focus:outline-none focus:ring-1 focus:ring-ring dark:bg-secondary",value:F??"",onChange:Z=>{const se=Z.target.value||null;Ct(se)},children:[u.jsx("option",{value:"",children:"Latest"}),Me.map(Z=>{const se=Ut.get(Z.checkpointId??"")??null;return u.jsx("option",{value:Z.checkpointId??void 0,children:$n(se)},Z.checkpointId)})]})]}),u.jsxs("div",{className:`relative ${hn}`,style:r?{maxHeight:r}:void 0,children:[u.jsx(Nl,{ref:ve,className:"h-full",style:{height:"100%"},messages:w,isStreaming:B,streamingAssistantId:Q,streamingDebounceMs:typeof s=="number"?s:o,followNewMessages:i,layoutSize:Lr,enableMessageEditing:c,editingMessageId:L,onStartReached:()=>{Gt&&N()},onScrollAway:Z=>{if(!Xt.current){Xt.current=!0;return}Z&&Yt(!0)},onEdit:qe,onRegenerate:He,onCancelEdit:Ge,emptyMessage:Nt??void 0,isNavigatingCheckpoint:G,activeInterrupt:ye,disableInterruptActions:je,onInterruptActionStart:ue,onInterruptActionEnd:ke,showToolMessages:d,checkpointMetaById:Ut,checkpointIndexByKey:Le,activeCheckpointId:F,onSelectCheckpoint:Zt,timelineCheckpoints:xt}),(H==="reconnecting"||H==="connecting")&&u.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-muted/80 px-3 py-1 text-xs font-medium text-foreground shadow-sm backdrop-blur-sm dark:bg-muted/60",children:u.jsxs("span",{className:"flex items-center gap-2",children:[u.jsx(he.Loader2,{className:"h-3 w-3 animate-spin"}),H==="reconnecting"?"Reconnecting…":"Connecting…"]})}),H==="error"&&u.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-destructive/10 px-3 py-1 text-xs font-semibold text-destructive shadow-sm",children:"Connection lost"}),k&&u.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-background/80 backdrop-blur-sm text-muted-foreground",children:[u.jsx(he.Loader2,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading messages…"})]})]}),u.jsxs("div",{className:zt,children:[L&&u.jsx("div",{className:"mb-3 p-3 bg-blue-50 border border-blue-200 rounded-lg",children:u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(he.Edit3,{size:16,className:"text-blue-600"}),u.jsx("span",{className:"text-sm font-medium text-blue-800",children:"Editing message"})]}),u.jsx(ut,{variant:"ghost",size:"sm",onClick:Ge,className:"text-blue-600 hover:bg-blue-100",children:u.jsx(he.X,{size:16})})]})}),(a||l)&&u.jsxs("div",{className:"mb-3 space-y-3",children:[a&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:Ln,type:"file",multiple:!0,onChange:Z=>Re(Z),className:"hidden"},rt),Pe.length>0&&u.jsx("div",{className:"flex flex-wrap gap-2",children:Pe.map((Z,se)=>u.jsxs("div",{className:"flex items-center gap-2 bg-gray-100 dark:bg-gray-800 rounded-lg px-3 py-2 text-sm text-gray-900 dark:text-gray-100",children:[u.jsx(he.Paperclip,{size:14}),u.jsx("span",{className:"truncate max-w-[150px]",children:Z.name}),u.jsx(ut,{variant:"ghost",size:"sm",onClick:()=>At(se),className:"h-4 w-4 p-0 text-gray-500 dark:text-gray-400 hover:text-red-500 dark:hover:text-red-400","aria-label":`Remove ${Z.name}`,children:u.jsx(he.X,{size:12})})]},se))})]}),l&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:Dt,type:"file",accept:".xls,.xlsx,.xlsm",onChange:gt,className:"hidden"},Ye),et&&u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(he.Loader2,{className:"h-4 w-4 animate-spin"})," Uploading Excel file..."]}),_t&&!et&&u.jsx("div",{className:"text-sm rounded border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-700",children:_t}),Ke&&!et&&u.jsx("div",{className:"text-sm rounded border border-red-200 bg-red-50 px-3 py-2 text-red-600",children:Ke})]})]}),re&&u.jsx("div",{className:"mb-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2",children:re}),u.jsxs("div",{className:"flex items-end gap-2",children:[(a||l)&&u.jsxs(S0,{children:[u.jsx(C0,{asChild:!0,children:u.jsx(ut,{type:"button",size:"icon",variant:"outline",disabled:B||te,title:"More input actions",className:f.moreButton||"",children:u.jsx(he.Plus,{size:16})})}),u.jsxs(Cf,{align:"start",sideOffset:6,className:"w-52",children:[a&&u.jsxs(Ga,{onClick:()=>{var Z;return(Z=Ln.current)==null?void 0:Z.click()},className:"cursor-pointer",children:[u.jsx(he.Paperclip,{className:"h-4 w-4 mr-2"})," Attach files or images"]}),l&&u.jsxs(Ga,{onClick:()=>{var Z;et||(Z=Dt.current)==null||Z.click()},className:`cursor-pointer ${et?"opacity-60 pointer-events-none":""}`,children:[u.jsx(he.FileSpreadsheet,{className:"h-4 w-4 mr-2"})," Upload Excel file"]})]})]}),u.jsx("div",{className:"flex-1",children:u.jsx(Cx,{initialValue:ie,editingMessageId:L,value:Jt,onValueChange:io,placeholder:L?"Edit your message...":t,isStreaming:B,disabled:te,maxLength:Ks,onSend:ae,onCancelEdit:Ge,onStop:V,allowEmptySend:Pe.length>0,textareaClassName:`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${L?"border-blue-400 bg-blue-50 text-blue-900 dark:border-blue-500 dark:bg-blue-950/60 dark:text-blue-50":""} ${re?"border-red-400":""} ${f.textarea||""}`})})]})]})]})}const wi=v.forwardRef(({className:e,type:t,...n},r)=>u.jsx("input",{type:t,className:oe("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),ref:r,...n}));wi.displayName="Input";function Al(e,[t,n]){return Math.min(n,Math.max(t,e))}function ek(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var _l="ScrollArea",[gp,VT]=Qn(_l),[tk,En]=gp(_l),yp=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:s=600,...i}=e,[a,l]=v.useState(null),[c,d]=v.useState(null),[f,h]=v.useState(null),[p,m]=v.useState(null),[g,y]=v.useState(null),[x,w]=v.useState(0),[C,T]=v.useState(0),[k,S]=v.useState(!1),[E,j]=v.useState(!1),_=Ze(t,D=>l(D)),P=ys(o);return u.jsx(tk,{scope:n,type:r,dir:P,scrollHideDelay:s,scrollArea:a,viewport:c,onViewportChange:d,content:f,onContentChange:h,scrollbarX:p,onScrollbarXChange:m,scrollbarXEnabled:k,onScrollbarXEnabledChange:S,scrollbarY:g,onScrollbarYChange:y,scrollbarYEnabled:E,onScrollbarYEnabledChange:j,onCornerWidthChange:w,onCornerHeightChange:T,children:u.jsx(De.div,{dir:P,...i,ref:_,style:{position:"relative","--radix-scroll-area-corner-width":x+"px","--radix-scroll-area-corner-height":C+"px",...e.style}})})});yp.displayName=_l;var xp="ScrollAreaViewport",vp=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...s}=e,i=En(xp,n),a=v.useRef(null),l=Ze(t,a,i.onViewportChange);return u.jsxs(u.Fragment,{children:[u.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:o}),u.jsx(De.div,{"data-radix-scroll-area-viewport":"",...s,ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style},children:u.jsx("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});vp.displayName=xp;var Yn="ScrollAreaScrollbar",jl=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=En(Yn,e.__scopeScrollArea),{onScrollbarXEnabledChange:s,onScrollbarYEnabledChange:i}=o,a=e.orientation==="horizontal";return v.useEffect(()=>(a?s(!0):i(!0),()=>{a?s(!1):i(!1)}),[a,s,i]),o.type==="hover"?u.jsx(nk,{...r,ref:t,forceMount:n}):o.type==="scroll"?u.jsx(rk,{...r,ref:t,forceMount:n}):o.type==="auto"?u.jsx(wp,{...r,ref:t,forceMount:n}):o.type==="always"?u.jsx(Pl,{...r,ref:t}):null});jl.displayName=Yn;var nk=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=En(Yn,e.__scopeScrollArea),[s,i]=v.useState(!1);return v.useEffect(()=>{const a=o.scrollArea;let l=0;if(a){const c=()=>{window.clearTimeout(l),i(!0)},d=()=>{l=window.setTimeout(()=>i(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",c),a.addEventListener("pointerleave",d),()=>{window.clearTimeout(l),a.removeEventListener("pointerenter",c),a.removeEventListener("pointerleave",d)}}},[o.scrollArea,o.scrollHideDelay]),u.jsx(Sn,{present:n||s,children:u.jsx(wp,{"data-state":s?"visible":"hidden",...r,ref:t})})}),rk=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=En(Yn,e.__scopeScrollArea),s=e.orientation==="horizontal",i=ki(()=>l("SCROLL_END"),100),[a,l]=ek("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return v.useEffect(()=>{if(a==="idle"){const c=window.setTimeout(()=>l("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(c)}},[a,o.scrollHideDelay,l]),v.useEffect(()=>{const c=o.viewport,d=s?"scrollLeft":"scrollTop";if(c){let f=c[d];const h=()=>{const p=c[d];f!==p&&(l("SCROLL"),i()),f=p};return c.addEventListener("scroll",h),()=>c.removeEventListener("scroll",h)}},[o.viewport,s,l,i]),u.jsx(Sn,{present:n||a!=="hidden",children:u.jsx(Pl,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:ge(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:ge(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),wp=v.forwardRef((e,t)=>{const n=En(Yn,e.__scopeScrollArea),{forceMount:r,...o}=e,[s,i]=v.useState(!1),a=e.orientation==="horizontal",l=ki(()=>{if(n.viewport){const c=n.viewport.offsetWidth<n.viewport.scrollWidth,d=n.viewport.offsetHeight<n.viewport.scrollHeight;i(a?c:d)}},10);return ro(n.viewport,l),ro(n.content,l),u.jsx(Sn,{present:r||s,children:u.jsx(Pl,{"data-state":s?"visible":"hidden",...o,ref:t})})}),Pl=v.forwardRef((e,t)=>{const{orientation:n="vertical",...r}=e,o=En(Yn,e.__scopeScrollArea),s=v.useRef(null),i=v.useRef(0),[a,l]=v.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),c=Tp(a.viewport,a.content),d={...r,sizes:a,onSizesChange:l,hasThumb:c>0&&c<1,onThumbChange:h=>s.current=h,onThumbPointerUp:()=>i.current=0,onThumbPointerDown:h=>i.current=h};function f(h,p){return ck(h,i.current,a,p)}return n==="horizontal"?u.jsx(ok,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollLeft,p=Ep(h,a,o.dir);s.current.style.transform=`translate3d(${p}px, 0, 0)`}},onWheelScroll:h=>{o.viewport&&(o.viewport.scrollLeft=h)},onDragScroll:h=>{o.viewport&&(o.viewport.scrollLeft=f(h,o.dir))}}):n==="vertical"?u.jsx(sk,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollTop,p=Ep(h,a);s.current.style.transform=`translate3d(0, ${p}px, 0)`}},onWheelScroll:h=>{o.viewport&&(o.viewport.scrollTop=h)},onDragScroll:h=>{o.viewport&&(o.viewport.scrollTop=f(h))}}):null}),ok=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=En(Yn,e.__scopeScrollArea),[i,a]=v.useState(),l=v.useRef(null),c=Ze(t,l,s.onScrollbarXChange);return v.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(Sp,{"data-orientation":"horizontal",...o,ref:c,sizes:n,style:{bottom:0,left:s.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:s.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Ci(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.x),onDragScroll:d=>e.onDragScroll(d.x),onWheelScroll:(d,f)=>{if(s.viewport){const h=s.viewport.scrollLeft+d.deltaX;e.onWheelScroll(h),Np(h,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollWidth,viewport:s.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:Si(i.paddingLeft),paddingEnd:Si(i.paddingRight)}})}})}),sk=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=En(Yn,e.__scopeScrollArea),[i,a]=v.useState(),l=v.useRef(null),c=Ze(t,l,s.onScrollbarYChange);return v.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(Sp,{"data-orientation":"vertical",...o,ref:c,sizes:n,style:{top:0,right:s.dir==="ltr"?0:void 0,left:s.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Ci(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.y),onDragScroll:d=>e.onDragScroll(d.y),onWheelScroll:(d,f)=>{if(s.viewport){const h=s.viewport.scrollTop+d.deltaY;e.onWheelScroll(h),Np(h,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollHeight,viewport:s.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:Si(i.paddingTop),paddingEnd:Si(i.paddingBottom)}})}})}),[ik,bp]=gp(Yn),Sp=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:s,onThumbPointerUp:i,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:c,onWheelScroll:d,onResize:f,...h}=e,p=En(Yn,n),[m,g]=v.useState(null),y=Ze(t,_=>g(_)),x=v.useRef(null),w=v.useRef(""),C=p.viewport,T=r.content-r.viewport,k=qt(d),S=qt(l),E=ki(f,10);function j(_){if(x.current){const P=_.clientX-x.current.left,D=_.clientY-x.current.top;c({x:P,y:D})}}return v.useEffect(()=>{const _=P=>{const D=P.target;(m==null?void 0:m.contains(D))&&k(P,T)};return document.addEventListener("wheel",_,{passive:!1}),()=>document.removeEventListener("wheel",_,{passive:!1})},[C,m,T,k]),v.useEffect(S,[r,S]),ro(m,E),ro(p.content,E),u.jsx(ik,{scope:n,scrollbar:m,hasThumb:o,onThumbChange:qt(s),onThumbPointerUp:qt(i),onThumbPositionChange:S,onThumbPointerDown:qt(a),children:u.jsx(De.div,{...h,ref:y,style:{position:"absolute",...h.style},onPointerDown:ge(e.onPointerDown,_=>{_.button===0&&(_.target.setPointerCapture(_.pointerId),x.current=m.getBoundingClientRect(),w.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",p.viewport&&(p.viewport.style.scrollBehavior="auto"),j(_))}),onPointerMove:ge(e.onPointerMove,j),onPointerUp:ge(e.onPointerUp,_=>{const P=_.target;P.hasPointerCapture(_.pointerId)&&P.releasePointerCapture(_.pointerId),document.body.style.webkitUserSelect=w.current,p.viewport&&(p.viewport.style.scrollBehavior=""),x.current=null})})})}),bi="ScrollAreaThumb",Cp=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=bp(bi,e.__scopeScrollArea);return u.jsx(Sn,{present:n||o.hasThumb,children:u.jsx(ak,{ref:t,...r})})}),ak=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,s=En(bi,n),i=bp(bi,n),{onThumbPositionChange:a}=i,l=Ze(t,f=>i.onThumbChange(f)),c=v.useRef(void 0),d=ki(()=>{c.current&&(c.current(),c.current=void 0)},100);return v.useEffect(()=>{const f=s.viewport;if(f){const h=()=>{if(d(),!c.current){const p=uk(f,a);c.current=p,a()}};return a(),f.addEventListener("scroll",h),()=>f.removeEventListener("scroll",h)}},[s.viewport,d,a]),u.jsx(De.div,{"data-state":i.hasThumb?"visible":"hidden",...o,ref:l,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:ge(e.onPointerDownCapture,f=>{const p=f.target.getBoundingClientRect(),m=f.clientX-p.left,g=f.clientY-p.top;i.onThumbPointerDown({x:m,y:g})}),onPointerUp:ge(e.onPointerUp,i.onThumbPointerUp)})});Cp.displayName=bi;var Rl="ScrollAreaCorner",kp=v.forwardRef((e,t)=>{const n=En(Rl,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?u.jsx(lk,{...e,ref:t}):null});kp.displayName=Rl;var lk=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=En(Rl,n),[s,i]=v.useState(0),[a,l]=v.useState(0),c=!!(s&&a);return ro(o.scrollbarX,()=>{var f;const d=((f=o.scrollbarX)==null?void 0:f.offsetHeight)||0;o.onCornerHeightChange(d),l(d)}),ro(o.scrollbarY,()=>{var f;const d=((f=o.scrollbarY)==null?void 0:f.offsetWidth)||0;o.onCornerWidthChange(d),i(d)}),c?u.jsx(De.div,{...r,ref:t,style:{width:s,height:a,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function Si(e){return e?parseInt(e,10):0}function Tp(e,t){const n=e/t;return isNaN(n)?0:n}function Ci(e){const t=Tp(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function ck(e,t,n,r="ltr"){const o=Ci(n),s=o/2,i=t||s,a=o-i,l=n.scrollbar.paddingStart+i,c=n.scrollbar.size-n.scrollbar.paddingEnd-a,d=n.content-n.viewport,f=r==="ltr"?[0,d]:[d*-1,0];return Ip([l,c],f)(e)}function Ep(e,t,n="ltr"){const r=Ci(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,s=t.scrollbar.size-o,i=t.content-t.viewport,a=s-r,l=n==="ltr"?[0,i]:[i*-1,0],c=Al(e,l);return Ip([0,i],[0,a])(c)}function Ip(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Np(e,t){return e>0&&e<t}var uk=(e,t=()=>{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const s={left:e.scrollLeft,top:e.scrollTop},i=n.left!==s.left,a=n.top!==s.top;(i||a)&&t(),n=s,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function ki(e,t){const n=qt(e),r=v.useRef(0);return v.useEffect(()=>()=>window.clearTimeout(r.current),[]),v.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function ro(e,t){const n=qt(t);Kt(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}var Ap=yp,dk=vp,fk=kp;const _p=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(Ap,{ref:r,className:oe("relative overflow-hidden",e),...n,children:[u.jsx(dk,{className:"h-full w-full rounded-[inherit] overflow-auto",children:t}),u.jsx(jp,{}),u.jsx(fk,{})]}));_p.displayName=Ap.displayName;const jp=v.forwardRef(({className:e,orientation:t="vertical",...n},r)=>u.jsx(jl,{ref:r,orientation:t,className:oe("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:u.jsx(Cp,{className:"relative flex-1 rounded-full bg-border"})}));jp.displayName=jl.displayName;const Pp=25;function Ol({className:e="",showCreateButton:t=!0,showDeleteButton:n=!0,showEditTitle:r=!0,maxHeight:o="400px",customStyles:s={},currentThreadId:i=null,navigateToThread:a,onThreadSelect:l,onThreadCreate:c,onThreadDelete:d}){const{threads:f,currentThreadId:h,isLoading:p,actions:m}=ps(),{loadThread:g}=ms(),{createThread:y,deleteThread:x,renameThread:w}=m,[C,T]=b.useState(Array.isArray(f)?f:[]),k=b.useRef(C.length>0),S=b.useRef(null),E=b.useRef(0),[j,_]=b.useState(null),[P,D]=b.useState(""),[z,B]=b.useState(!1);b.useEffect(()=>{const J=Array.isArray(f)?f:[];if(J.length>0){k.current=!0,T(J);return}p||(k.current=!1,T(J))},[f,p]),b.useEffect(()=>{if(!S.current)return;const J=S.current.querySelector("[data-radix-scroll-area-viewport]");if(!J)return;let ue=null,ke=null;return ue=requestAnimationFrame(()=>{ke=requestAnimationFrame(()=>{J.scrollTop=E.current})}),()=>{ue!==null&&cancelAnimationFrame(ue),ke!==null&&cancelAnimationFrame(ke)}},[C]);const O=async J=>{try{await g(J),a==null||a(J),l==null||l(J)}catch(ue){console.error("Failed to select thread:",ue)}},H=async()=>{try{B(!0);const J=await y();c==null||c(J),a==null||a(J)}catch(J){console.error("Failed to create thread:",J)}finally{B(!1)}},R=async(J,ue)=>{if(ue.stopPropagation(),!!confirm("Delete this thread?")){if(S.current){const ke=S.current.querySelector("[data-radix-scroll-area-viewport]");ke&&(E.current=ke.scrollTop)}try{await x(J),d==null||d(J)}catch(ke){console.error("Failed to delete thread:",ke)}}},V=(J,ue)=>{ue.stopPropagation(),_(J.threadId),D(J.title||`Thread ${J.threadId.slice(0,8)}`)},$=async J=>{if(P.trim())try{await w(J,P.trim()),_(null),D("")}catch(ue){console.error("Failed to update title:",ue)}},F=()=>{_(null),D("")},ne=(J,ue)=>{J.key==="Enter"?$(ue):J.key==="Escape"&&F()},Q=J=>{if(!J)return"";try{const ue=new Date(J),te=new Date().getTime()-ue.getTime(),L=Math.floor(te/(1e3*60*60*24));return L===0?ue.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):L===1?"Yesterday":L<7?`${L} days ago`:ue.toLocaleDateString()}catch{return""}},ye=J=>J.title||`Thread ${J.threadId.slice(0,8)}`,je=J=>{const ue=ye(J);return ue.length<=Pp?ue:`${ue.slice(0,Pp)}...`};return u.jsxs("div",{className:`flex flex-col h-full ${e} ${s.container||""}`,children:[t&&u.jsx("div",{className:s.header||"flex-shrink-0 p-2 border-b bg-slate-800 border-slate-700 text-slate-100 flex justify-end",children:u.jsx(ut,{onClick:H,disabled:z||p,className:s.createButton||"p-2",size:"sm",variant:"ghost",title:z?"Creating...":"New Chat",children:u.jsx(he.MessageSquarePlus,{size:20})})}),u.jsx(_p,{ref:S,className:`flex-1 min-h-0 ${s.threadList||""}`,style:o?{maxHeight:o}:void 0,children:u.jsx("div",{className:"p-2 space-y-1 pb-4",children:p?u.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-8 text-slate-400",children:[u.jsx(he.Loader2,{className:"h-5 w-5 animate-spin"}),u.jsx("span",{className:"text-sm",children:"Loading threads…"})]}):C.length===0?u.jsxs("div",{className:"text-center py-8 text-slate-400",children:[u.jsx(he.MessageSquare,{className:"w-8 h-8 mx-auto mb-2 opacity-40 text-slate-500"}),u.jsx("p",{className:"text-sm text-slate-500",children:"No conversations yet"})]}):C.slice().sort((J,ue)=>new Date(ue.updatedAt||ue.createdAt||"").getTime()-new Date(J.updatedAt||J.createdAt||"").getTime()).map(J=>u.jsxs("div",{onClick:()=>O(J.threadId),className:`group relative p-3 rounded-lg cursor-pointer transition-colors border ${(i??h)===J.threadId?`${s.activeThread||"bg-slate-600 border-slate-500"} `:`${s.threadItem||"bg-slate-700 border-slate-600 hover:bg-slate-600 text-gray-900 dark:text-slate-100"}`} ${s.threadItem||""} text-gray-900 dark:text-slate-100`,children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("div",{className:"flex-1 min-w-0",children:j===J.threadId?u.jsxs("div",{className:"flex items-center gap-2",onClick:ue=>ue.stopPropagation(),children:[u.jsx(wi,{value:P,onChange:ue=>D(ue.target.value),onKeyDown:ue=>ne(ue,J.threadId),className:"h-6 text-sm",autoFocus:!0}),u.jsx(ut,{variant:"ghost",size:"sm",onClick:()=>$(J.threadId),className:"h-6 w-6 p-0",children:u.jsx(he.Check,{size:12})}),u.jsx(ut,{variant:"ghost",size:"sm",onClick:F,className:"h-6 w-6 p-0",children:u.jsx(he.X,{size:12})})]}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"font-medium text-sm truncate text-gray-900 dark:text-slate-100",children:je(J)}),u.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mt-1",children:[u.jsx(he.Calendar,{size:10}),u.jsx("span",{children:Q(J.updatedAt||J.createdAt)})]})]})}),u.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity ml-2",children:[r&&j!==J.threadId&&u.jsx(ut,{variant:"ghost",size:"sm",onClick:ue=>V(J,ue),className:"h-6 w-6 p-0",title:"Edit title",children:u.jsx(he.Edit3,{size:12})}),n&&u.jsx(ut,{variant:"ghost",size:"sm",onClick:ue=>R(J.threadId,ue),className:"h-6 w-6 p-0 text-red-400 hover:text-red-300 hover:bg-red-900/20",title:"Delete thread",children:u.jsx(he.Trash2,{size:12})})]})]}),i===J.threadId&&u.jsx("div",{className:"absolute left-0 top-1/2 -translate-y-1/2 w-1 h-8 bg-blue-400 rounded-r"})]},J.threadId))})})]})}function oo(e){if(!(typeof globalThis>"u"))return globalThis[e]}function hk(e){if(typeof e!="string")return;const t=e.trim();if(t)return Zn(t)}function Rp(){const e=[oo("__API_BASE_URL__"),oo("__CHAT_API_BASE_URL__"),oo("__CHAT_API_URL__")];for(const t of e){const n=hk(t);if(n)return n}}function Op(){const e=[oo("__API_AUTH_TOKEN__"),oo("__CHAT_API_KEY__"),oo("__CHAT_AUTH_TOKEN__")];for(const t of e)if(typeof t=="string"&&t.trim())return t.trim()}function Mp(...e){for(const t of e)if(typeof t=="string"&&t.trim())return Zn(t);return Zn()}function Dp(){const e={},t=Rp(),n=Op();return t&&(e.baseUrl=t),n&&(e.apiKey=n),e}function Lp(){const e=Dp(),t=sr.getAuthToken(),n=Rp();return{apiBaseUrl:Mp(e.baseUrl,sr.baseUrl,n),apiKey:t||e.apiKey||Op()||"",model:"gpt-4",temperature:.7,maxTokens:4096,layoutSize:"desktop",showThreads:!0,autoScrollMessages:!0,darkMode:!1,enableSound:!1,messageHistory:100}}const Fp="chat-settings";function pk(){try{const e=localStorage.getItem(Fp);return e?JSON.parse(e):{}}catch(e){return console.error("Failed to parse stored settings:",e),{}}}function mk(e){try{const t={...e,apiBaseUrl:Zn(e.apiBaseUrl)};localStorage.setItem(Fp,JSON.stringify(t)),t.apiKey&&sr.setAuthToken(t.apiKey)}catch(t){console.error("Failed to save settings:",t)}}function gk(){const e=Lp(),t=pk(),n=sr.getAuthToken(),r=typeof t.apiBaseUrl=="string"?t.apiBaseUrl:void 0;return{...e,...t,apiKey:n||t.apiKey||e.apiKey,apiBaseUrl:Mp(sr.baseUrl,r,e.apiBaseUrl)}}function yk(e){sr.updateConfig({baseUrl:e.apiBaseUrl,authToken:e.apiKey??void 0}),mk(e)}var xk="Label",$p=v.forwardRef((e,t)=>u.jsx(De.label,{...e,ref:t,onMouseDown:n=>{var o;n.target.closest("button, input, select, textarea")||((o=e.onMouseDown)==null||o.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));$p.displayName=xk;var zp=$p;const vk=Go.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),In=v.forwardRef(({className:e,...t},n)=>u.jsx(zp,{ref:n,className:oe(vk(),e),...t}));In.displayName=zp.displayName;function Bp(e){const t=v.useRef({value:e,previous:e});return v.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Ti="Switch",[wk,KT]=Qn(Ti),[bk,Sk]=wk(Ti),Hp=v.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:s,required:i,disabled:a,value:l="on",onCheckedChange:c,form:d,...f}=e,[h,p]=v.useState(null),m=Ze(t,C=>p(C)),g=v.useRef(!1),y=h?d||!!h.closest("form"):!0,[x,w]=Vr({prop:o,defaultProp:s??!1,onChange:c,caller:Ti});return u.jsxs(bk,{scope:n,checked:x,disabled:a,children:[u.jsx(De.button,{type:"button",role:"switch","aria-checked":x,"aria-required":i,"data-state":Kp(x),"data-disabled":a?"":void 0,disabled:a,value:l,...f,ref:m,onClick:ge(e.onClick,C=>{w(T=>!T),y&&(g.current=C.isPropagationStopped(),g.current||C.stopPropagation())})}),y&&u.jsx(Vp,{control:h,bubbles:!g.current,name:r,value:l,checked:x,required:i,disabled:a,form:d,style:{transform:"translateX(-100%)"}})]})});Hp.displayName=Ti;var Up="SwitchThumb",Wp=v.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=Sk(Up,n);return u.jsx(De.span,{"data-state":Kp(o.checked),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Wp.displayName=Up;var Ck="SwitchBubbleInput",Vp=v.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...o},s)=>{const i=v.useRef(null),a=Ze(i,s),l=Bp(n),c=Yu(t);return v.useEffect(()=>{const d=i.current;if(!d)return;const f=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(f,"checked").set;if(l!==n&&p){const m=new Event("click",{bubbles:r});p.call(d,n),d.dispatchEvent(m)}},[l,n,r]),u.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...o,tabIndex:-1,ref:a,style:{...o.style,...c,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Vp.displayName=Ck;function Kp(e){return e?"checked":"unchecked"}var qp=Hp,kk=Wp;const mr=v.forwardRef(({className:e,...t},n)=>u.jsx(qp,{className:oe("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:u.jsx(kk,{className:oe("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));mr.displayName=qp.displayName;var Gp=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),Tk="VisuallyHidden",Ek=v.forwardRef((e,t)=>u.jsx(De.span,{...e,ref:t,style:{...Gp,...e.style}}));Ek.displayName=Tk;var Ik=[" ","Enter","ArrowUp","ArrowDown"],Nk=[" ","Enter"],Or="Select",[Ei,Ii,Ak]=ha(Or),[so,qT]=Qn(Or,[Ak,_s]),Ni=_s(),[_k,gr]=so(Or),[jk,Pk]=so(Or),Yp=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:s,value:i,defaultValue:a,onValueChange:l,dir:c,name:d,autoComplete:f,disabled:h,required:p,form:m}=e,g=Ni(t),[y,x]=v.useState(null),[w,C]=v.useState(null),[T,k]=v.useState(!1),S=ys(c),[E,j]=Vr({prop:r,defaultProp:o??!1,onChange:s,caller:Or}),[_,P]=Vr({prop:i,defaultProp:a,onChange:l,caller:Or}),D=v.useRef(null),z=y?m||!!y.closest("form"):!0,[B,O]=v.useState(new Set),H=Array.from(B).map(R=>R.props.value).join(";");return u.jsx(sd,{...g,children:u.jsxs(_k,{required:p,scope:t,trigger:y,onTriggerChange:x,valueNode:w,onValueNodeChange:C,valueNodeHasChildren:T,onValueNodeHasChildrenChange:k,contentId:er(),value:_,onValueChange:P,open:E,onOpenChange:j,dir:S,triggerPointerDownPosRef:D,disabled:h,children:[u.jsx(Ei.Provider,{scope:t,children:u.jsx(jk,{scope:e.__scopeSelect,onNativeOptionAdd:v.useCallback(R=>{O(V=>new Set(V).add(R))},[]),onNativeOptionRemove:v.useCallback(R=>{O(V=>{const $=new Set(V);return $.delete(R),$})},[]),children:n})}),z?u.jsxs(vm,{"aria-hidden":!0,required:p,tabIndex:-1,name:d,autoComplete:f,value:_,onChange:R=>P(R.target.value),disabled:h,form:m,children:[_===void 0?u.jsx("option",{value:""}):null,Array.from(B)]},H):null]})})};Yp.displayName=Or;var Xp="SelectTrigger",Jp=v.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,s=Ni(n),i=gr(Xp,n),a=i.disabled||r,l=Ze(t,i.onTriggerChange),c=Ii(n),d=v.useRef("touch"),[f,h,p]=bm(g=>{const y=c().filter(C=>!C.disabled),x=y.find(C=>C.value===i.value),w=Sm(y,g,x);w!==void 0&&i.onValueChange(w.value)}),m=g=>{a||(i.onOpenChange(!0),p()),g&&(i.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)})};return u.jsx(id,{asChild:!0,...s,children:u.jsx(De.button,{type:"button",role:"combobox","aria-controls":i.contentId,"aria-expanded":i.open,"aria-required":i.required,"aria-autocomplete":"none",dir:i.dir,"data-state":i.open?"open":"closed",disabled:a,"data-disabled":a?"":void 0,"data-placeholder":wm(i.value)?"":void 0,...o,ref:l,onClick:ge(o.onClick,g=>{g.currentTarget.focus(),d.current!=="mouse"&&m(g)}),onPointerDown:ge(o.onPointerDown,g=>{d.current=g.pointerType;const y=g.target;y.hasPointerCapture(g.pointerId)&&y.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&g.pointerType==="mouse"&&(m(g),g.preventDefault())}),onKeyDown:ge(o.onKeyDown,g=>{const y=f.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&h(g.key),!(y&&g.key===" ")&&Ik.includes(g.key)&&(m(),g.preventDefault())})})})});Jp.displayName=Xp;var Zp="SelectValue",Qp=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:s,placeholder:i="",...a}=e,l=gr(Zp,n),{onValueNodeHasChildrenChange:c}=l,d=s!==void 0,f=Ze(t,l.onValueNodeChange);return Kt(()=>{c(d)},[c,d]),u.jsx(De.span,{...a,ref:f,style:{pointerEvents:"none"},children:wm(l.value)?u.jsx(u.Fragment,{children:i}):s})});Qp.displayName=Zp;var Rk="SelectIcon",em=v.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return u.jsx(De.span,{"aria-hidden":!0,...o,ref:t,children:r||"▼"})});em.displayName=Rk;var Ok="SelectPortal",tm=e=>u.jsx(js,{asChild:!0,...e});tm.displayName=Ok;var Mr="SelectContent",nm=v.forwardRef((e,t)=>{const n=gr(Mr,e.__scopeSelect),[r,o]=v.useState();if(Kt(()=>{o(new DocumentFragment)},[]),!n.open){const s=r;return s?Yo.createPortal(u.jsx(rm,{scope:e.__scopeSelect,children:u.jsx(Ei.Slot,{scope:e.__scopeSelect,children:u.jsx("div",{children:e.children})})}),s):null}return u.jsx(om,{...e,ref:t})});nm.displayName=Mr;var Dn=10,[rm,yr]=so(Mr),Mk="SelectContentImpl",Dk=vr.createSlot("SelectContent.RemoveScroll"),om=v.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:s,onPointerDownOutside:i,side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:m,hideWhenDetached:g,avoidCollisions:y,...x}=e,w=gr(Mr,n),[C,T]=v.useState(null),[k,S]=v.useState(null),E=Ze(t,te=>T(te)),[j,_]=v.useState(null),[P,D]=v.useState(null),z=Ii(n),[B,O]=v.useState(!1),H=v.useRef(!1);v.useEffect(()=>{if(C)return Ma(C)},[C]),ga();const R=v.useCallback(te=>{const[L,...q]=z().map(U=>U.ref.current),[ie]=q.slice(-1),ce=document.activeElement;for(const U of te)if(U===ce||(U==null||U.scrollIntoView({block:"nearest"}),U===L&&k&&(k.scrollTop=0),U===ie&&k&&(k.scrollTop=k.scrollHeight),U==null||U.focus(),document.activeElement!==ce))return},[z,k]),V=v.useCallback(()=>R([j,C]),[R,j,C]);v.useEffect(()=>{B&&V()},[B,V]);const{onOpenChange:$,triggerPointerDownPosRef:F}=w;v.useEffect(()=>{if(C){let te={x:0,y:0};const L=ie=>{var ce,U;te={x:Math.abs(Math.round(ie.pageX)-(((ce=F.current)==null?void 0:ce.x)??0)),y:Math.abs(Math.round(ie.pageY)-(((U=F.current)==null?void 0:U.y)??0))}},q=ie=>{te.x<=10&&te.y<=10?ie.preventDefault():C.contains(ie.target)||$(!1),document.removeEventListener("pointermove",L),F.current=null};return F.current!==null&&(document.addEventListener("pointermove",L),document.addEventListener("pointerup",q,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",L),document.removeEventListener("pointerup",q,{capture:!0})}}},[C,$,F]),v.useEffect(()=>{const te=()=>$(!1);return window.addEventListener("blur",te),window.addEventListener("resize",te),()=>{window.removeEventListener("blur",te),window.removeEventListener("resize",te)}},[$]);const[ne,Q]=bm(te=>{const L=z().filter(ce=>!ce.disabled),q=L.find(ce=>ce.ref.current===document.activeElement),ie=Sm(L,te,q);ie&&setTimeout(()=>ie.ref.current.focus())}),ye=v.useCallback((te,L,q)=>{const ie=!H.current&&!q;(w.value!==void 0&&w.value===L||ie)&&(_(te),ie&&(H.current=!0))},[w.value]),je=v.useCallback(()=>C==null?void 0:C.focus(),[C]),J=v.useCallback((te,L,q)=>{const ie=!H.current&&!q;(w.value!==void 0&&w.value===L||ie)&&D(te)},[w.value]),ue=r==="popper"?Ml:sm,ke=ue===Ml?{side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:m,hideWhenDetached:g,avoidCollisions:y}:{};return u.jsx(rm,{scope:n,content:C,viewport:k,onViewportChange:S,itemRefCallback:ye,selectedItem:j,onItemLeave:je,itemTextRefCallback:J,focusSelectedItem:V,selectedItemText:P,position:r,isPositioned:B,searchRef:ne,children:u.jsx(zs,{as:Dk,allowPinchZoom:!0,children:u.jsx(vs,{asChild:!0,trapped:w.open,onMountAutoFocus:te=>{te.preventDefault()},onUnmountAutoFocus:ge(o,te=>{var L;(L=w.trigger)==null||L.focus({preventScroll:!0}),te.preventDefault()}),children:u.jsx(xs,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:te=>te.preventDefault(),onDismiss:()=>w.onOpenChange(!1),children:u.jsx(ue,{role:"listbox",id:w.contentId,"data-state":w.open?"open":"closed",dir:w.dir,onContextMenu:te=>te.preventDefault(),...x,...ke,onPlaced:()=>O(!0),ref:E,style:{display:"flex",flexDirection:"column",outline:"none",...x.style},onKeyDown:ge(x.onKeyDown,te=>{const L=te.ctrlKey||te.altKey||te.metaKey;if(te.key==="Tab"&&te.preventDefault(),!L&&te.key.length===1&&Q(te.key),["ArrowUp","ArrowDown","Home","End"].includes(te.key)){let ie=z().filter(ce=>!ce.disabled).map(ce=>ce.ref.current);if(["ArrowUp","End"].includes(te.key)&&(ie=ie.slice().reverse()),["ArrowUp","ArrowDown"].includes(te.key)){const ce=te.target,U=ie.indexOf(ce);ie=ie.slice(U+1)}setTimeout(()=>R(ie)),te.preventDefault()}})})})})})})});om.displayName=Mk;var Lk="SelectItemAlignedPosition",sm=v.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,s=gr(Mr,n),i=yr(Mr,n),[a,l]=v.useState(null),[c,d]=v.useState(null),f=Ze(t,E=>d(E)),h=Ii(n),p=v.useRef(!1),m=v.useRef(!0),{viewport:g,selectedItem:y,selectedItemText:x,focusSelectedItem:w}=i,C=v.useCallback(()=>{if(s.trigger&&s.valueNode&&a&&c&&g&&y&&x){const E=s.trigger.getBoundingClientRect(),j=c.getBoundingClientRect(),_=s.valueNode.getBoundingClientRect(),P=x.getBoundingClientRect();if(s.dir!=="rtl"){const ce=P.left-j.left,U=_.left-ce,We=E.left-U,re=E.width+We,xe=Math.max(re,j.width),Pe=window.innerWidth-Dn,$e=Al(U,[Dn,Math.max(Dn,Pe-xe)]);a.style.minWidth=re+"px",a.style.left=$e+"px"}else{const ce=j.right-P.right,U=window.innerWidth-_.right-ce,We=window.innerWidth-E.right-U,re=E.width+We,xe=Math.max(re,j.width),Pe=window.innerWidth-Dn,$e=Al(U,[Dn,Math.max(Dn,Pe-xe)]);a.style.minWidth=re+"px",a.style.right=$e+"px"}const D=h(),z=window.innerHeight-Dn*2,B=g.scrollHeight,O=window.getComputedStyle(c),H=parseInt(O.borderTopWidth,10),R=parseInt(O.paddingTop,10),V=parseInt(O.borderBottomWidth,10),$=parseInt(O.paddingBottom,10),F=H+R+B+$+V,ne=Math.min(y.offsetHeight*5,F),Q=window.getComputedStyle(g),ye=parseInt(Q.paddingTop,10),je=parseInt(Q.paddingBottom,10),J=E.top+E.height/2-Dn,ue=z-J,ke=y.offsetHeight/2,te=y.offsetTop+ke,L=H+R+te,q=F-L;if(L<=J){const ce=D.length>0&&y===D[D.length-1].ref.current;a.style.bottom="0px";const U=c.clientHeight-g.offsetTop-g.offsetHeight,We=Math.max(ue,ke+(ce?je:0)+U+V),re=L+We;a.style.height=re+"px"}else{const ce=D.length>0&&y===D[0].ref.current;a.style.top="0px";const We=Math.max(J,H+g.offsetTop+(ce?ye:0)+ke)+q;a.style.height=We+"px",g.scrollTop=L-J+g.offsetTop}a.style.margin=`${Dn}px 0`,a.style.minHeight=ne+"px",a.style.maxHeight=z+"px",r==null||r(),requestAnimationFrame(()=>p.current=!0)}},[h,s.trigger,s.valueNode,a,c,g,y,x,s.dir,r]);Kt(()=>C(),[C]);const[T,k]=v.useState();Kt(()=>{c&&k(window.getComputedStyle(c).zIndex)},[c]);const S=v.useCallback(E=>{E&&m.current===!0&&(C(),w==null||w(),m.current=!1)},[C,w]);return u.jsx($k,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:p,onScrollButtonChange:S,children:u.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:T},children:u.jsx(De.div,{...o,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});sm.displayName=Lk;var Fk="SelectPopperPosition",Ml=v.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=Dn,...s}=e,i=Ni(n);return u.jsx(ad,{...i,...s,ref:t,align:r,collisionPadding:o,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});Ml.displayName=Fk;var[$k,Dl]=so(Mr,{}),Ll="SelectViewport",im=v.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...o}=e,s=yr(Ll,n),i=Dl(Ll,n),a=Ze(t,s.onViewportChange),l=v.useRef(0);return u.jsxs(u.Fragment,{children:[u.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),u.jsx(Ei.Slot,{scope:n,children:u.jsx(De.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:ge(o.onScroll,c=>{const d=c.currentTarget,{contentWrapper:f,shouldExpandOnScrollRef:h}=i;if(h!=null&&h.current&&f){const p=Math.abs(l.current-d.scrollTop);if(p>0){const m=window.innerHeight-Dn*2,g=parseFloat(f.style.minHeight),y=parseFloat(f.style.height),x=Math.max(g,y);if(x<m){const w=x+p,C=Math.min(m,w),T=w-C;f.style.height=C+"px",f.style.bottom==="0px"&&(d.scrollTop=T>0?T:0,f.style.justifyContent="flex-end")}}}l.current=d.scrollTop})})})]})});im.displayName=Ll;var am="SelectGroup",[zk,Bk]=so(am),Hk=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=er();return u.jsx(zk,{scope:n,id:o,children:u.jsx(De.div,{role:"group","aria-labelledby":o,...r,ref:t})})});Hk.displayName=am;var lm="SelectLabel",cm=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Bk(lm,n);return u.jsx(De.div,{id:o.id,...r,ref:t})});cm.displayName=lm;var Ai="SelectItem",[Uk,um]=so(Ai),dm=v.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:s,...i}=e,a=gr(Ai,n),l=yr(Ai,n),c=a.value===r,[d,f]=v.useState(s??""),[h,p]=v.useState(!1),m=Ze(t,w=>{var C;return(C=l.itemRefCallback)==null?void 0:C.call(l,w,r,o)}),g=er(),y=v.useRef("touch"),x=()=>{o||(a.onValueChange(r),a.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return u.jsx(Uk,{scope:n,value:r,disabled:o,textId:g,isSelected:c,onItemTextChange:v.useCallback(w=>{f(C=>C||((w==null?void 0:w.textContent)??"").trim())},[]),children:u.jsx(Ei.ItemSlot,{scope:n,value:r,disabled:o,textValue:d,children:u.jsx(De.div,{role:"option","aria-labelledby":g,"data-highlighted":h?"":void 0,"aria-selected":c&&h,"data-state":c?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...i,ref:m,onFocus:ge(i.onFocus,()=>p(!0)),onBlur:ge(i.onBlur,()=>p(!1)),onClick:ge(i.onClick,()=>{y.current!=="mouse"&&x()}),onPointerUp:ge(i.onPointerUp,()=>{y.current==="mouse"&&x()}),onPointerDown:ge(i.onPointerDown,w=>{y.current=w.pointerType}),onPointerMove:ge(i.onPointerMove,w=>{var C;y.current=w.pointerType,o?(C=l.onItemLeave)==null||C.call(l):y.current==="mouse"&&w.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ge(i.onPointerLeave,w=>{var C;w.currentTarget===document.activeElement&&((C=l.onItemLeave)==null||C.call(l))}),onKeyDown:ge(i.onKeyDown,w=>{var T;((T=l.searchRef)==null?void 0:T.current)!==""&&w.key===" "||(Nk.includes(w.key)&&x(),w.key===" "&&w.preventDefault())})})})})});dm.displayName=Ai;var Vo="SelectItemText",fm=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...s}=e,i=gr(Vo,n),a=yr(Vo,n),l=um(Vo,n),c=Pk(Vo,n),[d,f]=v.useState(null),h=Ze(t,x=>f(x),l.onItemTextChange,x=>{var w;return(w=a.itemTextRefCallback)==null?void 0:w.call(a,x,l.value,l.disabled)}),p=d==null?void 0:d.textContent,m=v.useMemo(()=>u.jsx("option",{value:l.value,disabled:l.disabled,children:p},l.value),[l.disabled,l.value,p]),{onNativeOptionAdd:g,onNativeOptionRemove:y}=c;return Kt(()=>(g(m),()=>y(m)),[g,y,m]),u.jsxs(u.Fragment,{children:[u.jsx(De.span,{id:l.textId,...s,ref:h}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?Yo.createPortal(s.children,i.valueNode):null]})});fm.displayName=Vo;var hm="SelectItemIndicator",pm=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return um(hm,n).isSelected?u.jsx(De.span,{"aria-hidden":!0,...r,ref:t}):null});pm.displayName=hm;var Fl="SelectScrollUpButton",mm=v.forwardRef((e,t)=>{const n=yr(Fl,e.__scopeSelect),r=Dl(Fl,e.__scopeSelect),[o,s]=v.useState(!1),i=Ze(t,r.onScrollButtonChange);return Kt(()=>{if(n.viewport&&n.isPositioned){let a=function(){const c=l.scrollTop>0;s(c)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?u.jsx(ym,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});mm.displayName=Fl;var $l="SelectScrollDownButton",gm=v.forwardRef((e,t)=>{const n=yr($l,e.__scopeSelect),r=Dl($l,e.__scopeSelect),[o,s]=v.useState(!1),i=Ze(t,r.onScrollButtonChange);return Kt(()=>{if(n.viewport&&n.isPositioned){let a=function(){const c=l.scrollHeight-l.clientHeight,d=Math.ceil(l.scrollTop)<c;s(d)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?u.jsx(ym,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});gm.displayName=$l;var ym=v.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,s=yr("SelectScrollButton",n),i=v.useRef(null),a=Ii(n),l=v.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return v.useEffect(()=>()=>l(),[l]),Kt(()=>{var d;const c=a().find(f=>f.ref.current===document.activeElement);(d=c==null?void 0:c.ref.current)==null||d.scrollIntoView({block:"nearest"})},[a]),u.jsx(De.div,{"aria-hidden":!0,...o,ref:t,style:{flexShrink:0,...o.style},onPointerDown:ge(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:ge(o.onPointerMove,()=>{var c;(c=s.onItemLeave)==null||c.call(s),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:ge(o.onPointerLeave,()=>{l()})})}),Wk="SelectSeparator",xm=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return u.jsx(De.div,{"aria-hidden":!0,...r,ref:t})});xm.displayName=Wk;var zl="SelectArrow",Vk=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Ni(n),s=gr(zl,n),i=yr(zl,n);return s.open&&i.position==="popper"?u.jsx(ld,{...o,...r,ref:t}):null});Vk.displayName=zl;var Kk="SelectBubbleInput",vm=v.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const o=v.useRef(null),s=Ze(r,o),i=Bp(t);return v.useEffect(()=>{const a=o.current;if(!a)return;const l=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&d){const f=new Event("change",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),u.jsx(De.select,{...n,style:{...Gp,...n.style},ref:s,defaultValue:t})});vm.displayName=Kk;function wm(e){return e===""||e===void 0}function bm(e){const t=qt(e),n=v.useRef(""),r=v.useRef(0),o=v.useCallback(i=>{const a=n.current+i;t(a),function l(c){n.current=c,window.clearTimeout(r.current),c!==""&&(r.current=window.setTimeout(()=>l(""),1e3))}(a)},[t]),s=v.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return v.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,s]}function Sm(e,t,n){const o=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=qk(e,Math.max(s,0));o.length===1&&(i=i.filter(c=>c!==n));const l=i.find(c=>c.textValue.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function qk(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Gk=Yp,Cm=Jp,Yk=Qp,Xk=em,Jk=tm,km=nm,Zk=im,Tm=cm,Em=dm,Qk=fm,eT=pm,Im=mm,Nm=gm,Am=xm;const _m=Gk,jm=Yk,Bl=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(Cm,{ref:r,className:oe("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,u.jsx(Xk,{asChild:!0,children:u.jsx(he.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));Bl.displayName=Cm.displayName;const Pm=v.forwardRef(({className:e,...t},n)=>u.jsx(Im,{ref:n,className:oe("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(he.ChevronUp,{className:"h-4 w-4"})}));Pm.displayName=Im.displayName;const Rm=v.forwardRef(({className:e,...t},n)=>u.jsx(Nm,{ref:n,className:oe("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(he.ChevronDown,{className:"h-4 w-4"})}));Rm.displayName=Nm.displayName;const Hl=v.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>u.jsx(Jk,{children:u.jsxs(km,{ref:o,className:oe("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[u.jsx(Pm,{}),u.jsx(Zk,{className:oe("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),u.jsx(Rm,{})]})}));Hl.displayName=km.displayName;const tT=v.forwardRef(({className:e,...t},n)=>u.jsx(Tm,{ref:n,className:oe("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));tT.displayName=Tm.displayName;const Dr=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(Em,{ref:r,className:oe("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(eT,{children:u.jsx(he.Check,{className:"h-4 w-4"})})}),u.jsx(Qk,{children:t})]}));Dr.displayName=Em.displayName;const nT=v.forwardRef(({className:e,...t},n)=>u.jsx(Am,{ref:n,className:oe("-mx-1 my-1 h-px bg-muted",e),...t}));nT.displayName=Am.displayName;var rT="Separator",Om="horizontal",oT=["horizontal","vertical"],Mm=v.forwardRef((e,t)=>{const{decorative:n,orientation:r=Om,...o}=e,s=sT(r)?r:Om,a=n?{role:"none"}:{"aria-orientation":s==="vertical"?s:void 0,role:"separator"};return u.jsx(De.div,{"data-orientation":s,...a,...o,ref:t})});Mm.displayName=rT;function sT(e){return oT.includes(e)}var Dm=Mm;const Lm=v.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>u.jsx(Dm,{ref:o,decorative:n,orientation:t,className:oe("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Lm.displayName=Dm.displayName;const iT=Vh,aT=SC,lT=Kh,Fm=v.forwardRef(({className:e,...t},n)=>u.jsx(di,{className:oe("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));Fm.displayName=di.displayName;const cT=Go.cva("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),$m=v.forwardRef(({side:e="right",className:t,children:n,...r},o)=>u.jsxs(lT,{children:[u.jsx(Fm,{}),u.jsxs(fi,{ref:o,className:oe(cT({side:e}),t),...r,children:[n,u.jsxs(qh,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[u.jsx(he.X,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));$m.displayName=fi.displayName;const zm=({className:e,...t})=>u.jsx("div",{className:oe("flex flex-col space-y-2 text-center sm:text-left",e),...t});zm.displayName="SheetHeader";const Bm=v.forwardRef(({className:e,...t},n)=>u.jsx(Pr,{ref:n,className:oe("text-lg font-semibold text-foreground",e),...t}));Bm.displayName=Pr.displayName;const Hm=v.forwardRef(({className:e,...t},n)=>u.jsx(hi,{ref:n,className:oe("text-sm text-muted-foreground",e),...t}));Hm.displayName=hi.displayName;const uT={api:{baseUrl:"http://localhost:8000/api",authToken:"",enableAuth:!1},ui:{layout:"sidebar",theme:"light",showTimestamps:!0,showAgentNames:!0,compactMessages:!1},behavior:{autoSave:!0,enableStreaming:!0,showTypingIndicator:!0}};function dT({settings:e,onSettingsChange:t,className:n=""}){const[r,o]=b.useState(!1),[s,i]=b.useState(!1),[a,l]=b.useState(e),[c,d]=b.useState(!1),{toast:f}=wl();b.useEffect(()=>{const y=JSON.stringify(a)!==JSON.stringify(e);d(y)},[a,e]),b.useEffect(()=>{l(e)},[e]);const h=()=>{t(a),d(!1),f({title:"Settings saved",description:"Your chat configuration has been updated successfully."})},p=()=>{l(uT),d(!0),f({title:"Settings reset",description:"Configuration has been reset to defaults."})},m=()=>{l(e),d(!1),o(!1)},g=async()=>{try{const x=await(await fetch(`${a.api.baseUrl}/health`)).json();f({title:"Connection successful",description:`API is ${x.status||"healthy"}`})}catch{f({title:"Connection failed",description:"Unable to connect to the API endpoint.",variant:"destructive"})}};return u.jsxs(iT,{open:r,onOpenChange:o,children:[u.jsx(aT,{asChild:!0,children:u.jsxs(ut,{variant:"outline",size:"sm",className:n,children:[u.jsx(he.Settings,{className:"h-4 w-4 mr-2"}),"Settings",c&&u.jsx(Sh,{variant:"destructive",className:"ml-2 h-4 w-4 p-0"})]})}),u.jsxs($m,{className:"w-[500px] sm:w-[600px] overflow-y-auto",children:[u.jsxs(zm,{children:[u.jsx(Bm,{children:"Chat Settings"}),u.jsx(Hm,{children:"Configure your chat interface, API connection, and behavior preferences."})]}),u.jsxs("div",{className:"space-y-6 py-6",children:[u.jsxs(Lo,{children:[u.jsx(Fo,{className:"pb-3",children:u.jsxs($o,{className:"text-lg flex items-center gap-2",children:[u.jsx(he.Server,{className:"h-5 w-5"}),"API Configuration"]})}),u.jsxs(zo,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(In,{htmlFor:"api-url",children:"API Base URL"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(wi,{id:"api-url",value:a.api.baseUrl,onChange:y=>l(x=>({...x,api:{...x.api,baseUrl:y.target.value}})),placeholder:"http://localhost:8000/api"}),u.jsx(ut,{variant:"outline",onClick:g,children:"Test"})]})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(In,{htmlFor:"enable-auth",children:"Enable Authentication"}),u.jsx(mr,{id:"enable-auth",checked:a.api.enableAuth,onCheckedChange:y=>l(x=>({...x,api:{...x.api,enableAuth:y}}))})]}),a.api.enableAuth&&u.jsxs("div",{className:"space-y-2",children:[u.jsx(In,{htmlFor:"auth-token",children:"Authentication Token"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(wi,{id:"auth-token",type:s?"text":"password",value:a.api.authToken,onChange:y=>l(x=>({...x,api:{...x.api,authToken:y.target.value}})),placeholder:"Enter your Bearer token"}),u.jsx(ut,{variant:"outline",size:"icon",onClick:()=>i(!s),children:s?u.jsx(he.EyeOff,{className:"h-4 w-4"}):u.jsx(he.Eye,{className:"h-4 w-4"})})]})]})]})]}),u.jsxs(Lo,{children:[u.jsx(Fo,{className:"pb-3",children:u.jsxs($o,{className:"text-lg flex items-center gap-2",children:[u.jsx(he.Layout,{className:"h-5 w-5"}),"Interface Settings"]})}),u.jsxs(zo,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(In,{htmlFor:"layout",children:"Layout Style"}),u.jsxs(_m,{value:a.ui.layout,onValueChange:y=>l(x=>({...x,ui:{...x.ui,layout:y}})),children:[u.jsx(Bl,{children:u.jsx(jm,{})}),u.jsxs(Hl,{children:[u.jsx(Dr,{value:"sidebar",children:"Sidebar Layout"}),u.jsx(Dr,{value:"fullscreen",children:"Fullscreen"}),u.jsx(Dr,{value:"tabs",children:"Tabbed Interface"})]})]})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(In,{htmlFor:"theme",children:"Theme"}),u.jsxs(_m,{value:a.ui.theme,onValueChange:y=>l(x=>({...x,ui:{...x.ui,theme:y}})),children:[u.jsx(Bl,{children:u.jsx(jm,{})}),u.jsxs(Hl,{children:[u.jsx(Dr,{value:"light",children:"Light"}),u.jsx(Dr,{value:"dark",children:"Dark"}),u.jsx(Dr,{value:"system",children:"System"})]})]})]}),u.jsx(Lm,{}),u.jsxs("div",{className:"space-y-3",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(In,{htmlFor:"show-timestamps",children:"Show Timestamps"}),u.jsx(mr,{id:"show-timestamps",checked:a.ui.showTimestamps,onCheckedChange:y=>l(x=>({...x,ui:{...x.ui,showTimestamps:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(In,{htmlFor:"show-agent-names",children:"Show Agent Names"}),u.jsx(mr,{id:"show-agent-names",checked:a.ui.showAgentNames,onCheckedChange:y=>l(x=>({...x,ui:{...x.ui,showAgentNames:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(In,{htmlFor:"compact-messages",children:"Compact Messages"}),u.jsx(mr,{id:"compact-messages",checked:a.ui.compactMessages,onCheckedChange:y=>l(x=>({...x,ui:{...x.ui,compactMessages:y}}))})]})]})]})]}),u.jsxs(Lo,{children:[u.jsx(Fo,{className:"pb-3",children:u.jsxs($o,{className:"text-lg flex items-center gap-2",children:[u.jsx(he.MessageCircle,{className:"h-5 w-5"}),"Behavior Settings"]})}),u.jsxs(zo,{className:"space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(In,{htmlFor:"auto-save",children:"Auto-save Conversations"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically save messages to threads"})]}),u.jsx(mr,{id:"auto-save",checked:a.behavior.autoSave,onCheckedChange:y=>l(x=>({...x,behavior:{...x.behavior,autoSave:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(In,{htmlFor:"enable-streaming",children:"Enable Streaming"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Stream responses in real-time"})]}),u.jsx(mr,{id:"enable-streaming",checked:a.behavior.enableStreaming,onCheckedChange:y=>l(x=>({...x,behavior:{...x.behavior,enableStreaming:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(In,{htmlFor:"typing-indicator",children:"Typing Indicator"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Show typing indicator during responses"})]}),u.jsx(mr,{id:"typing-indicator",checked:a.behavior.showTypingIndicator,onCheckedChange:y=>l(x=>({...x,behavior:{...x.behavior,showTypingIndicator:y}}))})]})]})]})]}),u.jsxs("div",{className:"flex items-center justify-between pt-6 border-t",children:[u.jsxs(ut,{variant:"outline",onClick:p,children:[u.jsx(he.RotateCcw,{className:"h-4 w-4 mr-2"}),"Reset"]}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(ut,{variant:"outline",onClick:m,children:"Cancel"}),u.jsxs(ut,{onClick:h,disabled:!c,children:[u.jsx(he.Save,{className:"h-4 w-4 mr-2"}),"Save Changes"]})]})]})]})]})}function fT({layout:e="sidebar",layoutSize:t="desktop",showThreads:n=!0,className:r="",customStyles:o={},...s}){const i=c=>{const d="h-full";switch(c){case"phone":return`${d} max-w-none`;case"tablet":return`${d} max-w-4xl mx-auto`;case"half-screen":return`${d} max-w-2xl`;case"desktop":default:return`${d} max-w-7xl mx-auto`}},a=c=>({"--chat-sidebar-width":c==="phone"?"100%":c==="tablet"?"280px":c==="half-screen"?"240px":"320px","--chat-message-max-width":c==="phone"?"95%":c==="tablet"?"90%":c==="half-screen"?"85%":"80%","--chat-input-height":c==="phone"?"120px":"100px"}),l=b.useCallback(c=>{var d;(d=s.onThreadChange)==null||d.call(s,c)},[s]);return e==="fullscreen"?u.jsx(gs,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsx(vi,{className:"flex-1",onError:s.onError,enableFileUpload:!0})})}):e==="tabs"?u.jsx(gs,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsxs("div",{className:"flex-1 flex min-h-0 overflow-hidden",children:[n&&u.jsx("div",{className:`w-80 border-r flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:u.jsx(Ol,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),u.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:u.jsx(vi,{onError:s.onError,enableFileUpload:!0})})]})})}):u.jsx(gs,{...s,onThreadChange:l,children:u.jsxs("div",{className:`${i(t)} flex overflow-hidden ${r} ${o.container||""}`,style:a(t),children:[n&&u.jsx("div",{className:`w-80 border-r bg-gray-50 flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:u.jsx(Ol,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),u.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:u.jsx(vi,{onError:s.onError,enableFileUpload:!0})})]})})}Ae.ChatApi=$c,Ae.ChatInput=hu,Ae.ChatInterface=vi,Ae.ChatProviders=gs,Ae.ChatSettings=dT,Ae.MarkdownContent=Wo,Ae.MessageComponent=Il,Ae.MessageList=Nl,Ae.ThreadManager=Ol,Ae.applySettings=yk,Ae.chatApiClient=sr,Ae.default=fT,Ae.del=Fc,Ae.get=wn,Ae.getChatToken=Mc,Ae.getCurrentSettings=gk,Ae.getDefaultApiConfig=Dp,Ae.getDefaultChatSettings=Lp,Ae.onChatTokenChanged=Dc,Ae.post=Gi,Ae.put=Lc,Ae.registerChatTokenSyncHandler=Sy,Ae.setChatToken=qi,Ae.useApi=Yi,Ae.useChatStream=eu,Ae.useMessagesReducer=Kc,Ae.useStream=du,Ae.useThreadState=ms,Ae.useThreads=ps,Object.defineProperties(Ae,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
136
|
+
`)):r=t(e),r||""}function qC(e){return e.name&&e.name.trim()?e.name:e.model&&e.model.includes("/")?e.model.split("/").pop()||null:e.model||null}function fp(e){if("type"in e&&e.type==="default_message")return`default:${e.content.length}`;const t=e.updatedAt??e.createdAt??"",n=Array.isArray(e.content)?e.content.map(r=>{switch(r.type){case"text":return`t:${r.text.length}`;case"image_url":return"img";case"file":return"file";case"tool_call":return"call";case"interrupt":return"interrupt";default:return"unknown"}}).join("|"):"";return`${e.id}:${t}:${n}`}function GC({className:e}){const[t,n]=b.useState(0);return b.useEffect(()=>{const r=setInterval(()=>n(o=>(o+1)%4),500);return()=>clearInterval(r)},[]),u.jsxs("span",{"aria-live":"polite",className:oe("inline-block text-xs opacity-70 ml-1",e),children:["Is thinking",".".repeat(t)]})}const Il=b.memo(function({message:t,messageIndex:n,isStreamingMessage:r=!1,isEditing:o=!1,showActions:s=!0,showTimestamp:i=!0,showAgentName:a=!0,layoutSize:l="desktop",truncateUserMessages:c=!0,userMessagePreviewLength:d=500,showToolMessages:f=!0,customStyles:h={},onEdit:p,onRegenerate:m,onCancelEdit:g,onCopy:y,activeInterrupt:x,disableInterruptActions:w=!1,onInterruptActionStart:C,onInterruptActionEnd:T,checkpointCandidates:k=[],activeCheckpointId:S=null,onSelectCheckpoint:E,defaultCheckpointId:j=null,messageParentCheckpointId:_=null}){const[P,D]=b.useState(!1),[z,B]=b.useState("preview"),[O,H]=b.useState(!1),{currentThreadId:R}=ps(),{respondToInterrupt:V}=ms(),$=l==="phone"||l==="half-screen",F=t.role,ne=F==="tool",Q=b.useMemo(()=>"type"in t&&t.type==="default_message"?t:null,[t]),ye=!!Q,je=!(r&&F!=="user"),{uploadingFiles:J,handleFileClick:ue,fileViewerOpen:ke,currentFileInfo:te,closeFileViewer:L}=XC({allowFileOpen:je,currentThreadId:R}),q=b.useMemo(()=>{switch(F){case"user":return"text-[hsl(var(--chat-bubble-user-text))]";case"assistant":return"text-[hsl(var(--chat-bubble-ai-text))]";case"tool":return"text-secondary-foreground";case"system":return"text-muted-foreground";default:return"text-[hsl(var(--chat-bubble-ai-text))]"}},[F]),ie=b.useMemo(()=>Q?"":VC(t.content),[Q,t]),ce=b.useMemo(()=>Q?{}:dp(t),[Q,t]),U=b.useMemo(()=>Q?[]:t.content.filter(G=>G.type==="image_url"),[Q,t]),We=b.useMemo(()=>Q?[]:t.content.filter(G=>G.type==="file"),[Q,t]),re=b.useMemo(()=>Q?[]:t.content.filter(G=>G.type==="interrupt"),[Q,t]),xe=(x==null?void 0:x.id)??(x==null?void 0:x.interrupt_id),Pe=xi(xe),$e=x==null?void 0:x.value,rt=b.useMemo(()=>Q?"":KC(t.content),[Q,t]),Se=b.useCallback(async()=>{const G=ne?rt:ie;async function Te(ve){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(ve);return}if(navigator.clipboard&&typeof navigator.clipboard.write=="function"&&typeof ClipboardItem<"u"){const pt=new Blob([ve],{type:"text/plain"});await navigator.clipboard.write([new ClipboardItem({"text/plain":pt})]);return}throw new Error("Clipboard API not supported in this context.")}try{await Te(G),D(!0),setTimeout(()=>D(!1),2e3),y==null||y(G)}catch(ve){console.error("Failed to copy:",ve)}},[ne,rt,ie,y]),Ye=b.useCallback(()=>{if(!p)return;const G=ne?rt:ie,Te="type"in t&&t.type==="default_message"?void 0:{checkpointId:t.checkpointId??null,checkpointNs:t.checkpointNs??null};p(t.id,G,Te)},[p,t.id,ne,rt,ie,t]),ot=b.useCallback(()=>{m==null||m(n)},[m,n]),et=b.useCallback(()=>{const Te=oe($?"h-3 w-3":"h-4 w-4","opacity-60 flex-shrink-0",q);switch(F){case"user":return u.jsx(he.User,{className:Te});case"assistant":return u.jsx(he.Bot,{className:Te});case"tool":return u.jsx(he.Wrench,{className:Te});default:return u.jsx(he.Bot,{className:Te})}},[$,q,F]),Xe=b.useCallback(()=>{const G="group relative mb-4 flex w-full";switch(F){case"user":return oe(G,"justify-end");case"assistant":case"tool":case"system":return oe(G,"justify-start");default:return G}},[F]),Ke=b.useCallback(()=>{const G=oe("rounded-lg px-4 py-3 relative min-w-0 max-w-full break-words",$&&"px-3 py-2 text-sm");if(ye)return oe(G,"w-full","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40 shadow-sm");switch(F){case"user":return oe(G,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-user))] text-[hsl(var(--chat-bubble-user-text))]","border border-transparent");case"assistant":return oe(G,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40");case"tool":return oe(G,"w-full md:max-w-[95%] bg-secondary/50 text-secondary-foreground border border-dashed");case"system":return oe(G,"w-full md:max-w-[85%] bg-accent/40 text-muted-foreground border");default:return oe(G,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40")}},[$,ye,F]);if(ye&&Q)return u.jsx("div",{className:oe(Xe(),h.container),children:u.jsxs("div",{className:oe(Ke(),h.content),children:[u.jsxs("div",{className:"flex items-center gap-2 mb-2 pb-2 border-b border-current/10",children:[u.jsx(he.Bot,{className:oe("h-4 w-4",q)}),a&&u.jsx("span",{className:"font-medium text-sm",children:"Assistant"})]}),u.jsx(Wo,{content:Q.content,className:"text-current"})]})});const tt=b.useCallback(async G=>{if(w)return;const Te=xi((G==null?void 0:G.id)??(G==null?void 0:G.interrupt_id));if(!Te){console.warn("Interrupt part missing id",G);return}try{C==null||C(),await V(Te,!0)}catch(ve){console.error("Failed to approve interrupt:",ve)}finally{T==null||T()}},[w,T,C,V]),Ot=b.useCallback(async G=>{if(w)return;const Te=xi((G==null?void 0:G.id)??(G==null?void 0:G.interrupt_id));if(!Te){console.warn("Interrupt part missing id",G);return}try{C==null||C(),await V(Te,!1)}catch(ve){console.error("Failed to reject interrupt:",ve)}finally{T==null||T()}},[w,T,C,V]),St=b.useCallback(({part:G,i:Te})=>{if(G.type==="text"){const ve=G.text??"",pt=ve.trim(),mt=bl(pt);return mt&&F!=="tool"?u.jsx(hp,{data:mt},Te):F==="user"&&c&&pt.length>d?u.jsx(JC,{text:pt,expanded:O,onExpandedChange:H,previewLength:d,isCompact:$},Te):u.jsx(Wo,{content:ve,allowHtml:!1},Te)}if(G.type==="image_url"){const ve=G;return u.jsx("div",{className:"my-2",children:u.jsx("img",{src:ve.url,alt:ve.alt??"",loading:"lazy",className:"border rounded max-h-[420px] w-auto object-contain"})},Te)}if(G.type==="file"){const ve=G,pt=ve.name||"file";return u.jsxs("a",{href:ve.url,onClick:mt=>ue(mt,ve,Te),className:`inline-flex items-center gap-2 rounded px-2 py-1 text-xs bg-gray-100 border hover:bg-gray-200
|
|
137
|
+
dark:bg-background/10 dark:border-border/30 dark:hover:bg-background/20`,children:[J[Te]?u.jsx(he.Loader,{className:"h-4 w-4 animate-spin"}):null,u.jsxs("span",{className:"truncate max-w-[180px]",children:[pt,J[Te]?" (processing)":""]})]},Te)}if(G.type==="interrupt"){const ve=G,pt=xi((ve==null?void 0:ve.id)??(ve==null?void 0:ve.interrupt_id)),mt=!!(Pe&&pt&&pt===Pe),ct=mt?$e??(ve==null?void 0:ve.value):ve==null?void 0:ve.value,Me=pt?{...ve,id:pt,interrupt_id:pt}:ve;return u.jsx(YC,{interruptPart:Me,onApprove:tt,onReject:Ot,disabled:w,isActive:mt,payload:ct},Te)}return null},[ue,J,tt,Ot,F,c,d,O,$,Pe,$e,x,w,re]),nt=b.useCallback(()=>u.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted/30 rounded",children:[u.jsx(he.Paperclip,{className:"h-4 w-4 text-muted-foreground"}),u.jsx("span",{className:"text-sm text-muted-foreground",children:"File upload"})]}),[]),yt=b.useCallback(()=>{const G=ie.trim().length>0||U.length>0||We.length>0||re.length>0;if(!ne&&We.length>0&&!r)return nt();if(!ne&&!G&&!r)return null;if(ne)return u.jsx(ZC,{message:t,viewMode:z},t.id);if(!ne&&!Q){const Te=t,ve=u.jsx("div",{className:"space-y-2",children:Te.content.map((pt,mt)=>u.jsx(St,{part:pt,i:mt},mt))});return r?u.jsxs("div",{"aria-busy":"true",role:"status",children:[ve,u.jsx(GC,{className:q})]}):ve}},[ie,U.length,We.length,re.length,r,ne,z,nt,q]),Nt=b.useMemo(()=>Q?"Assistant":qC(t),[Q,t]),st=b.useMemo(()=>Q?[]:Array.isArray(k)?k:[],[k,Q]),Gt=b.useMemo(()=>{var G;return st.length?j&&st.some(Te=>Te.id===j)?j:((G=st[0])==null?void 0:G.id)??null:null},[j,st]),Xt=b.useMemo(()=>!st.length||!S?null:st.some(G=>G.id===S)?S:null,[S,st])??Gt,Jt=F==="user"&&st.length>0&&typeof E=="function",ft=b.useCallback(G=>{if(!E)return;const Te=(G==null?void 0:G.id)??null,ve=(G==null?void 0:G.parentId)??_??null;E(Te,ve)},[_,E]),Ve=b.useMemo(()=>Xt?st.findIndex(G=>G.id===Xt):-1,[Xt,st]),Mt=b.useMemo(()=>Ve<0?null:st[Ve]??null,[Ve,st]),_t=b.useCallback(G=>{const Te=[];if(G.step!==null&&Te.push(`Step ${G.step}`),G.source&&Te.push(G.source),!G.createdAt)return Te.length?Te.join(" • "):G.id.slice(0,8);let ve="";try{const pt=new Date(G.createdAt);Number.isNaN(pt.getTime())||(ve=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(pt))}catch{ve=""}return`${ve}`},[]);return ne&&!f?null:u.jsxs(u.Fragment,{children:[u.jsx("div",{className:oe(Xe(),h.container),children:u.jsxs("div",{className:oe(Ke(),h.content),children:[(i||a||ne)&&u.jsxs("div",{className:oe("flex items-center justify-between mb-2 pb-2 border-b border-current/10",$&&"mb-1 pb-1",q,h.header),children:[u.jsxs("div",{className:"flex items-center gap-2",children:[et(),a&&Nt&&u.jsx("span",{className:oe("font-medium",$?"text-xs":"text-sm"),children:Nt}),ne&&u.jsxs(Sh,{variant:"outline",className:oe("text-xs flex items-center gap-1 cursor-pointer select-none",q,"border border-current/40",$&&"text-xs h-4"),role:"button",tabIndex:0,"aria-expanded":z==="expanded",onClick:()=>B(G=>G==="expanded"?"preview":"expanded"),onKeyDown:G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),B(Te=>Te==="expanded"?"preview":"expanded"))},children:[u.jsx("span",{children:ce.name??"Tool Output"}),ce.toolCallId&&u.jsx("span",{className:"opacity-70",children:ce.toolCallId.slice(0,8)}),z==="expanded"?u.jsx(he.ChevronUp,{className:"h-3 w-3"}):u.jsx(he.ChevronDown,{className:"h-3 w-3"})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[Jt&&Mt&&Ve>=0&&u.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[u.jsx("button",{type:"button",className:oe("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",Ve>0?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(Ve<=0)return;const G=st[Ve-1];G&&ft(G)},"aria-label":"Previous checkpoint",disabled:Ve<=0,children:u.jsx(he.ChevronLeft,{className:"h-3 w-3"})}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs("span",{className:"whitespace-nowrap",children:[Ve+1," / ",st.length]}),u.jsx("span",{className:"text-muted-foreground",children:_t(Mt)})]}),u.jsx("button",{type:"button",className:oe("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",Ve<st.length-1?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(Ve>=st.length-1)return;const G=st[Ve+1];G&&ft(G)},"aria-label":"Next checkpoint",disabled:Ve>=st.length-1,children:u.jsx(he.ChevronRight,{className:"h-3 w-3"})})]}),i&&t.createdAt&&u.jsx("time",{className:oe("text-xs opacity-60",q,$&&"text-xs"),dateTime:new Date(t.createdAt).toISOString(),title:new Date(t.createdAt).toLocaleString(),children:new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(new Date(t.createdAt))}),s&&!o&&u.jsxs("div",{className:oe("opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",h.actions),children:[u.jsx("div",{className:"relative",children:u.jsx(ut,{variant:"ghost",size:"sm",onClick:()=>Se(),className:oe("h-6 w-6 p-0 hover:bg-foreground/10",q,$&&"h-5 w-5"),"aria-label":"Copy message",title:"Copy message",children:u.jsx(he.Copy,{className:oe(P?"text-success":q,$?"h-3 w-3":"h-4 w-4")})})}),F==="user"&&p&&u.jsx(ut,{variant:"ghost",size:"sm",onClick:Ye,className:oe("h-6 w-6 p-0 hover:bg-foreground/10",q,$&&"h-5 w-5"),"aria-label":"Edit message",children:u.jsx(he.Edit,{className:oe(q,$?"h-3 w-3":"h-4 w-4")})}),F==="assistant"&&m&&u.jsx(ut,{variant:"ghost",size:"sm",onClick:ot,className:oe("h-6 w-6 p-0 hover:bg-foreground/10",q,$&&"h-5 w-5"),"aria-label":"Regenerate response",children:u.jsx(he.RotateCcw,{className:oe(q,$?"h-3 w-3":"h-4 w-4")})})]})]})]}),u.jsx("div",{className:"relative",children:yt()}),ne&&z==="expanded"&&(ce.toolCallId||ce.name)&&u.jsxs("div",{className:oe("mt-2 pt-2 border-t border-current/10 text-xs opacity-60",$&&"text-xs"),children:[ce.name&&u.jsxs("div",{children:["Function: ",ce.name]}),ce.toolCallId&&u.jsxs("div",{children:["Call ID: ",ce.toolCallId]})]}),!(i||a||ne)&&s&&!o&&u.jsxs("div",{className:oe("absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",h.actions),children:[u.jsx(ut,{variant:"ghost",size:"sm",onClick:()=>Se(),className:oe("h-6 w-6 p-0 hover:bg-background/50 text-current",$&&"h-5 w-5"),children:u.jsx(he.Copy,{className:oe(P?"text-success":"text-current",$?"h-3 w-3":"h-4 w-4")})}),F==="user"&&p&&u.jsx(ut,{variant:"ghost",size:"sm",onClick:Ye,className:oe("h-6 w-6 p-0 hover:bg-background/50 text-current",$&&"h-5 w-5"),children:u.jsx(he.Edit,{className:oe("text-current",$?"h-3 w-3":"h-4 w-4")})}),F==="assistant"&&m&&u.jsx(ut,{variant:"ghost",size:"sm",onClick:ot,className:oe("h-6 w-6 p-0 hover:bg-background/50 text-current",$&&"h-5 w-5"),children:u.jsx(he.RotateCcw,{className:oe("text-current",$?"h-3 w-3":"h-4 w-4")})})]})]})}),te&&u.jsx(EC,{isOpen:ke,onClose:L,fileId:te.id,fileName:te.name,mimeType:te.mimeType})]})},(e,t)=>{var i,a,l,c,d,f,h,p;if(t.isStreamingMessage||e.isStreamingMessage||!(e.message.id===t.message.id&&fp(e.message)===fp(t.message)))return!1;const o=["isEditing","showActions","layoutSize","showTimestamp","showAgentName","truncateUserMessages","userMessagePreviewLength","showToolMessages"].every(m=>e[m]===t[m]),s=((i=e.customStyles)==null?void 0:i.container)===((a=t.customStyles)==null?void 0:a.container)&&((l=e.customStyles)==null?void 0:l.content)===((c=t.customStyles)==null?void 0:c.content)&&((d=e.customStyles)==null?void 0:d.actions)===((f=t.customStyles)==null?void 0:f.actions)&&((h=e.customStyles)==null?void 0:h.header)===((p=t.customStyles)==null?void 0:p.header);return o&&s});function hp({data:e}){return Array.isArray(e)?e.every(n=>n===null||["string","number","boolean"].includes(typeof n))?u.jsx("div",{className:WC,children:u.jsx("ul",{className:"list-disc pl-5",children:e.map((n,r)=>u.jsx("li",{children:String(n)},r))})}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:Uo(e)}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:Uo(e)})}function YC({interruptPart:e,onApprove:t,onReject:n,disabled:r,isActive:o,payload:s}){const i=e.title??"Approve the result?";let a=null;if(s!=null)if(typeof s=="string")a=u.jsx("p",{className:"text-sm leading-relaxed text-blue-800/90 dark:text-blue-200/90 whitespace-pre-wrap",children:s});else{const c=Uo(s);a=u.jsx("pre",{className:"max-h-48 overflow-auto rounded bg-blue-100/60 p-2 text-xs text-blue-900/90 dark:bg-blue-900/40 dark:text-blue-100/80",children:c})}const l=o?"Please approve or reject this action to resume the workflow.":"Waiting for approval from another participant.";return u.jsxs(Lo,{className:oe("border-blue-200 dark:border-blue-800 bg-blue-50/50 dark:bg-blue-950/10 transition-shadow",o?"shadow-md ring-1 ring-blue-300 dark:ring-blue-500/70":"opacity-80"),children:[u.jsxs(Fo,{className:"pb-3",children:[u.jsx($o,{className:"text-blue-900 dark:text-blue-100 text-base",children:i}),u.jsx(Ch,{className:"text-blue-700 dark:text-blue-300 text-sm",children:l})]}),a&&u.jsx(zo,{className:"pt-0 pb-3",children:a}),u.jsx(kh,{className:"pt-0",children:u.jsxs("div",{className:"flex gap-2 ml-auto",children:[u.jsx(ut,{size:"sm",variant:"outline",onClick:()=>n(e),className:"border-red-300 text-red-700 hover:bg-red-50 dark:border-red-700 dark:text-red-300 dark:hover:bg-red-950/50",disabled:r||!o,children:"Reject"}),u.jsx(ut,{size:"sm",onClick:()=>t(e),className:"bg-blue-600 hover:bg-blue-700 text-white",disabled:r||!o,children:"Approve"})]})})]})}function XC(e){const{allowFileOpen:t,currentThreadId:n}=e,{toast:r}=wl(),[o,s]=b.useState({}),[i,a]=b.useState(null),[l,c]=b.useState(!1),d=b.useCallback(()=>{c(!1),a(null)},[]),f=b.useCallback(p=>{a(p),c(!0)},[]),h=b.useCallback(async(p,m,g)=>{var y,x;if(!t){p.preventDefault();return}if(o[g]){p.preventDefault();return}try{const w=String(m.url??""),C=w.match(/\/chat\/files\/([^/]+)(?:\/(view|download))?/);if(C){p.preventDefault();const T=C[1],k=m.name||`file_${T}`,S=m.mimeType||"application/octet-stream";f({id:T,name:k,mimeType:S});return}if(w.startsWith("data:")){p.preventDefault(),s(k=>({...k,[g]:!0}));const T=r({title:"Fetching file...",description:"",open:!0});try{const k=await uC(n??void 0);if(!k||!Array.isArray(k))throw new Error("Invalid file list response");const S=k.find(E=>!E||typeof E!="object"||!((E.filename??"")===(m.name??""))?!1:typeof m.size=="number"&&typeof E.size=="number"?E.size===m.size:!0);if(!(S!=null&&S.id))throw new Error(`File "${m.name}" is not yet available on the server`);if(!S.id||!S.filename)throw new Error("Invalid file data received from server");f({id:S.id,name:m.name||S.filename||`file_${S.id}`,mimeType:m.mimeType||S.mime_type||"application/octet-stream"}),(y=T.update)==null||y.call(T,{id:T.id,title:"Success",description:`Opened ${m.name}`,open:!0})}catch(k){console.error("Failed to fetch server file:",k);const S=k instanceof Error?k.message:"Unknown error occurred";(x=T.update)==null||x.call(T,{id:T.id,title:"Failed",description:S}),r({title:"Failed to fetch file",description:S,open:!0})}finally{s(k=>({...k,[g]:!1}))}}}catch(w){console.error("File click error:",w),s(C=>({...C,[g]:!1}))}},[t,o,r,n,f]);return{uploadingFiles:o,handleFileClick:h,fileViewerOpen:l,currentFileInfo:i,closeFileViewer:d}}function JC({text:e,expanded:t,onExpandedChange:n,previewLength:r,isCompact:o}){const s=Math.max(e.length-r,0),i=e.substring(0,r);return u.jsxs("div",{className:"flex flex-col gap-1",children:[u.jsx("div",{className:oe("text-sm text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:t?u.jsx(Wo,{content:e,allowHtml:!1}):u.jsxs("pre",{className:oe("font-sans whitespace-pre-wrap break-words bg-transparent p-0 m-0 text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:[i,"..."]})}),u.jsx(ut,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-xs !text-[hsl(var(--chat-bubble-user-text))]",onClick:()=>n(!t),children:t?u.jsxs(u.Fragment,{children:[u.jsx(he.ChevronUp,{className:"h-3 w-3 mr-1"})," Show less"]}):u.jsxs(u.Fragment,{children:[u.jsx(he.ChevronDown,{className:"h-3 w-3 mr-1"})," Show more (",s," chars)"]})})]})}function ZC({message:e,viewMode:t}){const r=dp(e).name||"tool",o=c=>{if(c==null)return null;const d=typeof c=="string"?bl(c)??c:c;if(d&&typeof d=="object")return u.jsx(hp,{data:d});const f=typeof d=="string"?d:(()=>{try{return Uo(d)}catch{return String(d??"")}})();return u.jsx("pre",{className:"whitespace-pre-wrap break-words font-sans text-sm text-foreground/90",children:f})},s=c=>{if(c==null)return null;const{content:d,isMarkdown:f}=fC(c);return f?u.jsx(Wo,{content:d,className:"text-current"}):o(c)};if(t==="preview")return null;const i=e.content.find(c=>c.type!=="tool_call");if(!i)return u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(he.Loader,{className:"h-4 w-4 animate-spin"}),u.jsxs("span",{children:["Waiting for ",r," output…"]})]});if(i.type==="text"){const d=(i.text??"").trim();if(!d)return null;const f=li(d);return s(f)}const a=Ho(i),l=li(a);return s(l)}const pp=(e,t)=>(e==null?void 0:e.id)??`message-${t}`,QC=e=>{const t=e.additionalKwargs??{},n=e.responseMetadata??{},r=t.originalMessageId??n.originalMessageId??t.original_message_id??n.original_message_id;return typeof r=="string"&&r.trim()?r.trim():e.id},Nl=b.forwardRef(({messages:e,isStreaming:t,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onStartReached:a,onEdit:l,onRegenerate:c,onCancelEdit:d,className:f,style:h,emptyMessage:p,followNewMessages:m=!0,isNavigatingCheckpoint:g=!1,onScrollAway:y,onAtBottom:x,activeInterrupt:w,disableInterruptActions:C=!1,onInterruptActionStart:T,onInterruptActionEnd:k,showToolMessages:S=!0,checkpointMetaById:E,checkpointIndexByKey:j,activeCheckpointId:_,onSelectCheckpoint:P,timelineCheckpoints:D},z)=>{const B=b.useRef(null),O=b.useRef(null),H=b.useRef(!1),[R,V]=b.useState(!0),$=b.useMemo(()=>w?e.some(re=>"type"in re&&re.type==="default_message"?!1:Array.isArray(re==null?void 0:re.content)&&re.content.some(xe=>xe&&xe.type==="interrupt"&&(xe.id??xe.interrupt_id)===w.id)):!1,[w,e]),F=b.useMemo(()=>{if(!w||$)return null;const re=w.id&&String(w.id).trim()?String(w.id).trim():"pending-interrupt";let xe;const Pe=w.value;if(Pe&&typeof Pe=="object"&&!Array.isArray(Pe)){const $e=Pe.title;typeof $e=="string"&&$e.trim()&&(xe=$e.trim())}return{id:`interrupt-${re}`,role:"system",createdAt:new Date().toISOString(),content:[{type:"interrupt",id:re,value:Pe,title:xe}]}},[w,$]),ne=b.useMemo(()=>F?[...e,F]:e,[e,F]),Q=b.useMemo(()=>S?ne:ne.filter(re=>(re==null?void 0:re.role)!=="tool"),[ne,S]),ye=b.useMemo(()=>{const re=new Set,xe=[];for(let Pe=Q.length-1;Pe>=0;Pe--){const $e=Q[Pe];if(!$e)continue;if("type"in $e&&$e.type==="default_message"){xe.push($e);continue}const rt=$e,Se=QC(rt);re.has(Se)||(re.add(Se),xe.push(rt))}return xe.reverse()},[Q]),je=b.useCallback(re=>{V(re),y&&y(!re),x&&x(re)},[y,x]),J=b.useMemo(()=>{if(a)return async()=>{if(!H.current){H.current=!0;try{await a()}finally{H.current=!1}}}},[a]),ue=b.useMemo(()=>!m||g?!1:R?"auto":!1,[R,m,g]),ke=b.useMemo(()=>D??[],[D]),te=_??(ke.length?ke[ke.length-1].id:null),L=ke.length>0,q=b.useMemo(()=>{if(typeof p!="string")return null;const re=p.trim();return re?{id:"default-message",role:"assistant",type:"default_message",content:re,createdAt:new Date().toISOString()}:null},[p]),ie=L?u.jsxs("div",{className:"hidden w-48 flex-shrink-0 flex-col border-r border-border/40 pr-4 md:flex",children:[u.jsxs("div",{className:"relative flex-1 overflow-y-auto pt-5 pb-5 pr-1",children:[u.jsxs("div",{className:"absolute left-0 right-0 top-1 flex items-center justify-between px-2 pb-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[u.jsx("span",{children:"Timeline"}),u.jsxs("div",{className:"group relative z-50",children:[u.jsx(he.Info,{className:"h-3.5 w-3.5 text-muted-foreground cursor-help"}),u.jsx("div",{className:"pointer-events-auto fixed hidden w-56 rounded-md border bg-background p-3 text-[11px] font-normal text-muted-foreground shadow-lg group-hover:block whitespace-normal leading-relaxed",style:{zIndex:9999},children:'Shows user inputs and the latest loop checkpoint. Click a dot to jump the chat to that point. Click on the "Latest" button to return to the most recent messages.'})]})]}),u.jsx("div",{className:"pointer-events-none absolute left-5 top-0 bottom-0 w-px bg-border/50"}),u.jsx("div",{className:"flex flex-col gap-4",children:ke.map(re=>{const xe=te===re.id;return u.jsxs("button",{type:"button",disabled:!P,onClick:()=>P==null?void 0:P(re.id),className:`relative flex items-start gap-3 text-left text-xs transition ${xe?"text-primary":"text-muted-foreground"} ${P?"hover:text-foreground":"cursor-default opacity-70"}`,children:[u.jsx("span",{className:`mt-1 inline-flex h-4 w-4 items-center justify-center rounded-full border ${xe?"border-primary bg-primary/10 text-primary":"border-border bg-background"}`,children:u.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${xe?"bg-primary":"bg-border"}`})}),u.jsxs("span",{className:"flex-1",children:[u.jsx("span",{className:"block font-medium",children:re.label||"User input"}),u.jsxs("span",{className:"text-[10px] uppercase tracking-wide text-muted-foreground/70",children:[re.step!==null?`STEP ${re.step}`:"STEP —",re.next?` - ${re.next}`:""]})]})]},re.id)})})]}),P&&u.jsx("button",{type:"button",onClick:()=>P==null?void 0:P(null),className:"mt-auto rounded-md border border-border/70 px-3 py-2 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground transition hover:border-foreground/60 hover:text-foreground",children:"Latest"})]}):null,ce=["flex h-full flex-col md:flex-row",f].filter(Boolean).join(" "),U=()=>q?u.jsx("div",{className:"p-6 h-full overflow-y-auto",children:u.jsx("div",{className:"w-full max-w-full",children:u.jsx(Il,{message:q,messageIndex:0,isStreamingMessage:!1,showActions:!1,showTimestamp:!1,showAgentName:!0,layoutSize:o,onEdit:()=>{},onRegenerate:()=>{},onCancelEdit:()=>{}})})}):u.jsx("div",{className:"flex h-full items-center justify-center py-8 text-center text-muted-foreground",children:p??"No messages yet. Start a conversation!"}),We=ye.length>0;return b.useImperativeHandle(z,()=>({scrollToLatest:()=>{var re,xe;if(B.current&&ye.length>0){const Pe=ye.length-1;(xe=(re=B.current).scrollToIndex)==null||xe.call(re,{index:Pe,align:"end",behavior:"auto"})}else O.current&&(O.current.scrollTop=O.current.scrollHeight)},scrollToTop:()=>{var re,xe;B.current&&ye.length>0?(xe=(re=B.current).scrollToIndex)==null||xe.call(re,{index:0,align:"start",behavior:"auto"}):O.current&&(O.current.scrollTop=0)}}),[ye]),u.jsxs("div",{className:ce,style:h,children:[ie,u.jsx("div",{className:"relative flex-1 min-h-0",children:We?u.jsx(HS,{ref:re=>{B.current=re},scrollerRef:re=>{O.current=re instanceof HTMLDivElement?re:null},data:ye,followOutput:ue,overscan:200,increaseViewportBy:{top:100,bottom:200},defaultItemHeight:80,atBottomThreshold:50,alignToBottom:!1,startReached:()=>{J&&J()},atBottomStateChange:je,style:{height:"100%",overscrollBehavior:"contain"},computeItemKey:(re,xe)=>pp(xe,re),itemContent:(re,xe)=>{var tt;const Pe=pp(xe,re),$e="type"in xe&&xe.type==="default_message";let rt=[],Se=null,Ye={},ot={},et=null,Xe=null;if(!$e){const Ot=xe,St=Ot.checkpointId??null;Ye=Ot.additionalKwargs??{},ot=Ot.responseMetadata??{};const nt=St&&E?E.get(St)??null:null;et=typeof Ye.step=="number"?Ye.step:typeof ot.step=="number"?ot.step:(nt==null?void 0:nt.step)??null;const yt=typeof Ye.source=="string"?Ye.source:typeof ot.source=="string"?ot.source:(nt==null?void 0:nt.source)??null;Xe=yt?String(yt):null;const Nt=et!==null&&Xe?`${et}:${Xe}`:null;Nt&&(j!=null&&j.has(Nt))?rt=j.get(Nt)??[]:St&&nt&&(rt=[nt]),Se=St??((tt=rt[0])==null?void 0:tt.id)??null}const Ke=(()=>{if(typeof Ye.parentCheckpointId=="string")return Ye.parentCheckpointId;if(typeof ot.parentCheckpointId=="string")return ot.parentCheckpointId})();return u.jsx("div",{className:"relative mb-4 last:mb-0","data-message-id":Pe,style:{minHeight:"60px",containIntrinsicSize:"auto 120px"},children:u.jsx(Il,{message:xe,messageIndex:re,isStreamingMessage:t&&n===xe.id,streamingDebounceMs:r,isEditing:i===xe.id,showActions:s,showTimestamp:!1,showAgentName:!0,layoutSize:o,onEdit:l,onRegenerate:()=>c(re),onCancelEdit:d,activeInterrupt:w,disableInterruptActions:C,onInterruptActionStart:T,onInterruptActionEnd:k,showToolMessages:S,checkpointCandidates:rt,activeCheckpointId:_??null,onSelectCheckpoint:P,defaultCheckpointId:Se,messageParentCheckpointId:Ke})})}}):U()})]})});Nl.displayName="MessageList";const mp={value:""};function vi({className:e="",placeholder:t="Type your message...",autoFocus:n=!0,maxHeight:r=void 0,streamingDebounceMs:o=500,streamingThrottleMs:s,followNewMessages:i=!0,enableFileUpload:a=!0,enableExcelUpload:l=!1,enableMessageEditing:c=!0,showToolMessages:d=!0,customStyles:f={},onMessageSent:h,onExcelUploadSuccess:p,onError:m}){const{api:g}=Yi(),{currentThreadId:y}=ps(),{threadId:x,messages:w,hasMore:C,isHistoryLoading:T,isLoading:k,loadOlder:S,navigateToCheckpoint:E,returnToLatest:j,checkpoint:_,checkpoints:P,interrupt:D,metadata:z}=ms(),{isStreaming:B,error:O,connectionState:H,submit:R,stop:V}=du(),$=x??y??null,F=(_==null?void 0:_.id)??null,ne=(_==null?void 0:_.namespace)??null,Q=(z==null?void 0:z.assemblingMessageId)??null,ye=D,[je,J]=b.useState(!1);b.useEffect(()=>{ye||J(!1)},[ye]);const ue=b.useCallback(()=>{J(!0)},[]),ke=b.useCallback(()=>{J(!1)},[]),te=!!ye||je,[L,q]=b.useState(null),[ie,ce]=b.useState(""),[U,We]=b.useState(null),[re,xe]=b.useState(null),[Pe,$e]=b.useState([]),[rt,Se]=b.useState(0),[Ye,ot]=b.useState(0),[et,Xe]=b.useState(!1),[Ke,tt]=b.useState(null),[Ot,St]=b.useState(null),[nt,yt]=b.useState(!1),[Nt,st]=b.useState(null),[Gt,Yt]=b.useState(!1),Xt=b.useRef(!1),[Jt,ft]=b.useState(()=>mp.value),Ve=b.useRef(Jt),Mt=b.useRef(null),_t=b.useCallback(Z=>{mp.value=Z,ft(Z)},[]),[G,Te]=b.useState(!1),ve=b.useRef(null),pt=b.useCallback(Z=>{if(!Array.isArray(Z))return{text:null,messageId:null};for(let se=Z.length-1;se>=0;se--){const de=Z[se];if(!de||de.role!=="user")continue;const Ie=(de.content??[]).filter(Je=>(Je==null?void 0:Je.type)==="text").map(Je=>Je.text).filter(Je=>typeof Je=="string"&&Je.trim().length>0);return{text:Ie.length?Ie.join(" ").trim():null,messageId:de.id??null}}return{text:null,messageId:null}},[]),mt=b.useCallback((Z,se)=>{if(!Z||typeof Z!="object")return null;const de=Z[se];return typeof de=="number"?de:null},[]),ct=b.useCallback((Z,se)=>{if(!Z||typeof Z!="object")return null;const de=Z[se];return typeof de=="string"&&de.trim()?de:null},[]),Me=b.useMemo(()=>{const Z=Ie=>{if(!Array.isArray(Ie)||Ie.length===0)return null;const lt=Ie.map(Je=>{if(typeof Je=="string")return Je.trim();if(Je&&typeof Je=="object"&&"type"in Je){const it=Je;if(typeof it.type=="string")return it.type}return null}).filter(Je=>!!(Je&&Je.length));return lt.length?lt.join(", "):null},se=Array.isArray(P)?P.map(Ie=>{const lt=Z(Ie.next);return lt?{...Ie,metadata:{...Ie.metadata??{},next:lt}}:Ie}):[];return se.some(Ie=>mt(Ie.metadata,"step")!==null)&&se.sort((Ie,lt)=>{const Je=mt(Ie.metadata,"step"),it=mt(lt.metadata,"step");if(Je!==null||it!==null)return(it??Number.NEGATIVE_INFINITY)-(Je??Number.NEGATIVE_INFINITY);const Bt=Date.parse(Ie.createdAt??""),sn=Date.parse(lt.createdAt??"");return Number.isNaN(Bt)||Number.isNaN(sn)?0:sn-Bt}),se},[P,mt]),{checkpointMetaById:Ut,checkpointIndexByKey:Le}=b.useMemo(()=>{const Z=new Map,se=new Map;for(const de of Me){const Ie=de.checkpointId??null;if(!Ie)continue;const lt=mt(de.metadata,"step"),Je=ct(de.metadata,"source"),it={id:Ie,step:lt,source:Je,createdAt:de.createdAt??null,namespace:de.checkpointNs??null,parentId:de.parentId??null};if(Z.set(Ie,it),lt!==null&&Je){const Bt=`${lt}:${Je}`,sn=se.get(Bt)??[];sn.push(it),se.set(Bt,sn)}}for(const de of se.values())de.sort((Ie,lt)=>{const Je=Ie.createdAt??"";return(lt.createdAt??"").localeCompare(Je)});return{checkpointMetaById:Z,checkpointIndexByKey:se}},[Me,mt,ct]),xt=b.useMemo(()=>{var Je;if(!Me.length)return[];const Z=[...Me].reverse(),se=(it,Bt)=>{const sn=it.checkpointId??null;if(!sn)return null;const Xn=ct(it.metadata,"source");ct(it.metadata,"next");const{text:Ko,messageId:_i}=pt(it.messages),Nn=Ko&&Ko.replace(/\s+/g," ").trim()||ct(it.metadata,"title")||ct(it.metadata,"label")||Bt||Xn||"Checkpoint",ji=Nn.length>60?`${Nn.slice(0,57)}…`:Nn;return{id:sn,label:ji,messageId:_i??null,createdAt:it.createdAt??null,step:mt(it.metadata,"step"),source:Xn??null,next:ct(it.metadata,"next")}},de=[],Ie=new Set;for(const it of Z){const Bt=((Je=ct(it.metadata,"source"))==null?void 0:Je.toLowerCase())??null;if(!(Bt==="input"||Bt==="user_input"||Bt==="user"))continue;const Xn=se(it,"User input");Xn&&!Ie.has(Xn.id)&&(de.push(Xn),Ie.add(Xn.id))}if(!de.length)for(const it of Z){const Bt=se(it);Bt&&!Ie.has(Bt.id)&&(de.push(Bt),Ie.add(Bt.id))}const lt=Me.find(it=>{var sn;return(((sn=ct(it.metadata,"source"))==null?void 0:sn.toLowerCase())??null)==="loop"});if(lt){const it=se(lt,"Latest loop");it&&!Ie.has(it.id)&&(de.push(it),Ie.add(it.id))}return de},[Me,pt,mt,ct]),Ln=b.useRef(null),Dt=b.useRef(null),fn=b.useCallback(()=>{Ln.current&&(Ln.current.value=""),Dt.current&&(Dt.current.value=""),Se(Z=>Z+1),ot(Z=>Z+1)},[]),io=b.useCallback(Z=>{_t(Z)},[_t]),ao=b.useRef(!1);b.useEffect(()=>{ao.current&&!B&&($e([]),fn()),ao.current=B},[B,fn]);const[Lr,Fr]=b.useState("desktop");b.useEffect(()=>{const Z=()=>{const se=window.innerWidth;Fr(se<640?"phone":se<1024?"tablet":"desktop")};return Z(),window.addEventListener("resize",Z),()=>window.removeEventListener("resize",Z)},[]),b.useEffect(()=>{Yt(!1),Xt.current=!1},[$]),b.useEffect(()=>{Ve.current=Jt},[Jt]),b.useEffect(()=>{if(!L){Mt.current=null;return}Mt.current===null&&(Mt.current=Ve.current),_t(ie??"")},[ie,L,_t]);const N=b.useCallback(async()=>{if(!(!C||T||!Gt))try{await S()}catch(Z){console.warn("loadOlder failed",Z)}},[C,Gt,T,S]);b.useEffect(()=>{(async()=>{if(!g.baseUrl){st(null);return}try{const de=(await g.getAgent("default")).uiDefaultMessage||"";st(de||null)}catch(se){console.warn("Failed to fetch default message:",se),st(null)}})()},[g.baseUrl]),b.useEffect(()=>{O&&!nt&&(m==null||m(O))},[O,nt,m]);const Y=Z=>{if(Z.length>Ks)return`Message too long (${Z.length}/${Ks} characters)`;try{return P0(Z),null}catch(se){return(se==null?void 0:se.message)||"Invalid message"}},ae=async Z=>{const se=Z.trim();if(!(!se&&Pe.length===0)){if(se){const de=Y(se);if(de){xe(de);return}}try{const de=F??void 0,Ie=ne??void 0,lt=L?{edit:!0,originalMessageId:L,...U!=null&&U.checkpointId?{originalCheckpointId:U.checkpointId}:{},...U!=null&&U.checkpointNs?{originalCheckpointNs:U.checkpointNs}:{}}:void 0;await R({text:se||"",attachments:Pe,messageAdditionalKwargs:lt},{checkpointId:de,checkpointNs:Ie}),h==null||h(se),_t(""),xe(null),$e([]),fn(),q(null),ce(""),We(null)}catch(de){const Ie=(de==null?void 0:de.message)||"Failed to send message";xe(Ie),m==null||m(Ie)}}},Ce=b.useCallback((Z,se,de)=>{c&&(Mt.current=Jt,q(Z),ce(se),_t(se),xe(null),We({checkpointId:(de==null?void 0:de.checkpointId)??null,checkpointNs:(de==null?void 0:de.checkpointNs)??null}))},[Jt,c,_t]),Ge=b.useCallback(()=>{q(null),ce(""),We(null),xe(null),_t(Mt.current??Jt),Mt.current=null},[Jt,_t]),qe=b.useCallback((Z,se,de)=>{Ce(Z,se,de)},[Ce]),He=b.useCallback(Z=>{for(let se=Z-1;se>=0;se--)if(w[se].role==="user"){const de=w[se].content||[],lt=de.filter(Je=>Je.type==="text").map(Je=>Je.text).join("")||(()=>{try{return JSON.stringify(de,null,2)}catch{return String(de)}})();lt&&R({text:lt},{checkpointId:F??void 0,checkpointNs:ne??void 0});break}},[w,R,F,ne]),Re=Z=>{const se=Array.from(Z.target.files||[]);$e(de=>[...de,...se]),Z.target.value=""},At=Z=>{$e(se=>{const de=se.filter((Ie,lt)=>Z!==lt);return de.length===0&&fn(),de})},gt=async Z=>{const se=(Z.target.files||[])[0];if(se){tt(null),St(null),Xe(!0);try{await R({attachments:[se]},{checkpointId:F??void 0,checkpointNs:ne??void 0});const de=`Uploaded ${se.name} - processing through chat stream`;St(de)}catch(de){const Ie=de instanceof Error?de.message:"Failed to upload Excel file";console.error("Excel upload failed",de),tt(Ie),m==null||m(Ie)}finally{Xe(!1),Z.target.value="",fn()}}},Ct=async Z=>{if(y){Te(!0);try{if(!Z){await j(),Yt(!1),requestAnimationFrame(()=>{var Ie;(Ie=ve.current)==null||Ie.scrollToLatest()});return}const se=Me.find(Ie=>Ie.checkpointId===Z),de=(se==null?void 0:se.checkpointNs)??null;await E(Z,de),Yt(!0),requestAnimationFrame(()=>{var Ie;(Ie=ve.current)==null||Ie.scrollToTop()})}finally{Te(!1)}}},Zt=b.useCallback(async Z=>{await Ct(Z)},[Ct]),Fn=`flex flex-1 w-full flex-col min-h-0 min-w-0 max-h-full overflow-hidden bg-transparent ${e} ${f.container||""}`,hn=`flex-1 min-h-0 min-w-0 max-h-full w-full overflow-hidden overscroll-contain break-words break-anywhere p-4 bg-transparent ${f.messagesArea||""}`,zt=`flex-shrink-0 w-full border-t p-4 bg-transparent ${f.inputArea||""}`,$n=b.useCallback(Z=>{if(!Z)return"Latest";const se=[];Z.step!==null&&se.push(`Step ${Z.step}`),Z.source&&se.push(Z.source);const de=Z.createdAt?new Date(Z.createdAt):null,Ie=de&&!Number.isNaN(de.getTime())?de.toLocaleString():Z.createdAt??Z.id,lt=se.length?` — ${se.join(" • ")}`:"";return`${Ie}${lt}`},[]);return u.jsxs("div",{className:Fn,children:[!!O&&!nt&&u.jsxs("div",{className:"flex-shrink-0 bg-red-50 border border-red-200 text-red-800 px-4 py-2 text-sm flex items-center justify-between",children:[u.jsx("span",{children:O}),u.jsx(ut,{variant:"ghost",size:"sm",onClick:()=>yt(!0),className:"text-red-800 hover:bg-red-100","aria-label":"Dismiss error",children:u.jsx(he.X,{size:16})})]}),y&&Me.length>0&&u.jsxs("div",{className:"flex-shrink-0 flex items-center gap-2 px-4 py-2 border-b border-border bg-muted/60 text-xs dark:bg-muted/50",children:[u.jsx("span",{className:"opacity-70",children:"Checkpoint:"}),u.jsxs("select",{className:"border border-border rounded px-2 py-1 text-xs bg-card text-foreground focus:outline-none focus:ring-1 focus:ring-ring dark:bg-secondary",value:F??"",onChange:Z=>{const se=Z.target.value||null;Ct(se)},children:[u.jsx("option",{value:"",children:"Latest"}),Me.map(Z=>{const se=Ut.get(Z.checkpointId??"")??null;return u.jsx("option",{value:Z.checkpointId??void 0,children:$n(se)},Z.checkpointId)})]})]}),u.jsxs("div",{className:`relative ${hn}`,style:r?{maxHeight:r}:void 0,children:[u.jsx(Nl,{ref:ve,className:"h-full",style:{height:"100%"},messages:w,isStreaming:B,streamingAssistantId:Q,streamingDebounceMs:typeof s=="number"?s:o,followNewMessages:i,layoutSize:Lr,enableMessageEditing:c,editingMessageId:L,onStartReached:()=>{Gt&&N()},onScrollAway:Z=>{if(!Xt.current){Xt.current=!0;return}Z&&Yt(!0)},onEdit:qe,onRegenerate:He,onCancelEdit:Ge,emptyMessage:Nt??void 0,isNavigatingCheckpoint:G,activeInterrupt:ye,disableInterruptActions:je,onInterruptActionStart:ue,onInterruptActionEnd:ke,showToolMessages:d,checkpointMetaById:Ut,checkpointIndexByKey:Le,activeCheckpointId:F,onSelectCheckpoint:Zt,timelineCheckpoints:xt}),(H==="reconnecting"||H==="connecting")&&u.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-muted/80 px-3 py-1 text-xs font-medium text-foreground shadow-sm backdrop-blur-sm dark:bg-muted/60",children:u.jsxs("span",{className:"flex items-center gap-2",children:[u.jsx(he.Loader2,{className:"h-3 w-3 animate-spin"}),H==="reconnecting"?"Reconnecting…":"Connecting…"]})}),H==="error"&&u.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-destructive/10 px-3 py-1 text-xs font-semibold text-destructive shadow-sm",children:"Connection lost"}),k&&u.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-background/80 backdrop-blur-sm text-muted-foreground",children:[u.jsx(he.Loader2,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading messages…"})]})]}),u.jsxs("div",{className:zt,children:[L&&u.jsx("div",{className:"mb-3 p-3 bg-blue-50 border border-blue-200 rounded-lg",children:u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(he.Edit3,{size:16,className:"text-blue-600"}),u.jsx("span",{className:"text-sm font-medium text-blue-800",children:"Editing message"})]}),u.jsx(ut,{variant:"ghost",size:"sm",onClick:Ge,className:"text-blue-600 hover:bg-blue-100",children:u.jsx(he.X,{size:16})})]})}),(a||l)&&u.jsxs("div",{className:"mb-3 space-y-3",children:[a&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:Ln,type:"file",multiple:!0,onChange:Z=>Re(Z),className:"hidden"},rt),Pe.length>0&&u.jsx("div",{className:"flex flex-wrap gap-2",children:Pe.map((Z,se)=>u.jsxs("div",{className:"flex items-center gap-2 bg-gray-100 dark:bg-gray-800 rounded-lg px-3 py-2 text-sm text-gray-900 dark:text-gray-100",children:[u.jsx(he.Paperclip,{size:14}),u.jsx("span",{className:"truncate max-w-[150px]",children:Z.name}),u.jsx(ut,{variant:"ghost",size:"sm",onClick:()=>At(se),className:"h-4 w-4 p-0 text-gray-500 dark:text-gray-400 hover:text-red-500 dark:hover:text-red-400","aria-label":`Remove ${Z.name}`,children:u.jsx(he.X,{size:12})})]},se))})]}),l&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:Dt,type:"file",accept:".xls,.xlsx,.xlsm",onChange:gt,className:"hidden"},Ye),et&&u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(he.Loader2,{className:"h-4 w-4 animate-spin"})," Uploading Excel file..."]}),Ot&&!et&&u.jsx("div",{className:"text-sm rounded border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-700",children:Ot}),Ke&&!et&&u.jsx("div",{className:"text-sm rounded border border-red-200 bg-red-50 px-3 py-2 text-red-600",children:Ke})]})]}),re&&u.jsx("div",{className:"mb-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2",children:re}),u.jsxs("div",{className:"flex items-end gap-2",children:[(a||l)&&u.jsxs(S0,{children:[u.jsx(C0,{asChild:!0,children:u.jsx(ut,{type:"button",size:"icon",variant:"outline",disabled:B||te,title:"More input actions",className:f.moreButton||"",children:u.jsx(he.Plus,{size:16})})}),u.jsxs(Cf,{align:"start",sideOffset:6,className:"w-52",children:[a&&u.jsxs(Ga,{onClick:()=>{var Z;return(Z=Ln.current)==null?void 0:Z.click()},className:"cursor-pointer",children:[u.jsx(he.Paperclip,{className:"h-4 w-4 mr-2"})," Attach files or images"]}),l&&u.jsxs(Ga,{onClick:()=>{var Z;et||(Z=Dt.current)==null||Z.click()},className:`cursor-pointer ${et?"opacity-60 pointer-events-none":""}`,children:[u.jsx(he.FileSpreadsheet,{className:"h-4 w-4 mr-2"})," Upload Excel file"]})]})]}),u.jsx("div",{className:"flex-1",children:u.jsx(Cx,{initialValue:ie,editingMessageId:L,value:Jt,onValueChange:io,placeholder:L?"Edit your message...":t,isStreaming:B,disabled:te,maxLength:Ks,onSend:ae,onCancelEdit:Ge,onStop:V,allowEmptySend:Pe.length>0,textareaClassName:`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${L?"border-blue-400 bg-blue-50 text-blue-900 dark:border-blue-500 dark:bg-blue-950/60 dark:text-blue-50":""} ${re?"border-red-400":""} ${f.textarea||""}`})})]})]})]})}const wi=v.forwardRef(({className:e,type:t,...n},r)=>u.jsx("input",{type:t,className:oe("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),ref:r,...n}));wi.displayName="Input";function Al(e,[t,n]){return Math.min(n,Math.max(t,e))}function ek(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var _l="ScrollArea",[gp,VT]=Qn(_l),[tk,En]=gp(_l),yp=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:s=600,...i}=e,[a,l]=v.useState(null),[c,d]=v.useState(null),[f,h]=v.useState(null),[p,m]=v.useState(null),[g,y]=v.useState(null),[x,w]=v.useState(0),[C,T]=v.useState(0),[k,S]=v.useState(!1),[E,j]=v.useState(!1),_=Ze(t,D=>l(D)),P=ys(o);return u.jsx(tk,{scope:n,type:r,dir:P,scrollHideDelay:s,scrollArea:a,viewport:c,onViewportChange:d,content:f,onContentChange:h,scrollbarX:p,onScrollbarXChange:m,scrollbarXEnabled:k,onScrollbarXEnabledChange:S,scrollbarY:g,onScrollbarYChange:y,scrollbarYEnabled:E,onScrollbarYEnabledChange:j,onCornerWidthChange:w,onCornerHeightChange:T,children:u.jsx(De.div,{dir:P,...i,ref:_,style:{position:"relative","--radix-scroll-area-corner-width":x+"px","--radix-scroll-area-corner-height":C+"px",...e.style}})})});yp.displayName=_l;var xp="ScrollAreaViewport",vp=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...s}=e,i=En(xp,n),a=v.useRef(null),l=Ze(t,a,i.onViewportChange);return u.jsxs(u.Fragment,{children:[u.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:o}),u.jsx(De.div,{"data-radix-scroll-area-viewport":"",...s,ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style},children:u.jsx("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});vp.displayName=xp;var Yn="ScrollAreaScrollbar",jl=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=En(Yn,e.__scopeScrollArea),{onScrollbarXEnabledChange:s,onScrollbarYEnabledChange:i}=o,a=e.orientation==="horizontal";return v.useEffect(()=>(a?s(!0):i(!0),()=>{a?s(!1):i(!1)}),[a,s,i]),o.type==="hover"?u.jsx(nk,{...r,ref:t,forceMount:n}):o.type==="scroll"?u.jsx(rk,{...r,ref:t,forceMount:n}):o.type==="auto"?u.jsx(wp,{...r,ref:t,forceMount:n}):o.type==="always"?u.jsx(Pl,{...r,ref:t}):null});jl.displayName=Yn;var nk=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=En(Yn,e.__scopeScrollArea),[s,i]=v.useState(!1);return v.useEffect(()=>{const a=o.scrollArea;let l=0;if(a){const c=()=>{window.clearTimeout(l),i(!0)},d=()=>{l=window.setTimeout(()=>i(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",c),a.addEventListener("pointerleave",d),()=>{window.clearTimeout(l),a.removeEventListener("pointerenter",c),a.removeEventListener("pointerleave",d)}}},[o.scrollArea,o.scrollHideDelay]),u.jsx(Sn,{present:n||s,children:u.jsx(wp,{"data-state":s?"visible":"hidden",...r,ref:t})})}),rk=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=En(Yn,e.__scopeScrollArea),s=e.orientation==="horizontal",i=ki(()=>l("SCROLL_END"),100),[a,l]=ek("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return v.useEffect(()=>{if(a==="idle"){const c=window.setTimeout(()=>l("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(c)}},[a,o.scrollHideDelay,l]),v.useEffect(()=>{const c=o.viewport,d=s?"scrollLeft":"scrollTop";if(c){let f=c[d];const h=()=>{const p=c[d];f!==p&&(l("SCROLL"),i()),f=p};return c.addEventListener("scroll",h),()=>c.removeEventListener("scroll",h)}},[o.viewport,s,l,i]),u.jsx(Sn,{present:n||a!=="hidden",children:u.jsx(Pl,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:ge(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:ge(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),wp=v.forwardRef((e,t)=>{const n=En(Yn,e.__scopeScrollArea),{forceMount:r,...o}=e,[s,i]=v.useState(!1),a=e.orientation==="horizontal",l=ki(()=>{if(n.viewport){const c=n.viewport.offsetWidth<n.viewport.scrollWidth,d=n.viewport.offsetHeight<n.viewport.scrollHeight;i(a?c:d)}},10);return ro(n.viewport,l),ro(n.content,l),u.jsx(Sn,{present:r||s,children:u.jsx(Pl,{"data-state":s?"visible":"hidden",...o,ref:t})})}),Pl=v.forwardRef((e,t)=>{const{orientation:n="vertical",...r}=e,o=En(Yn,e.__scopeScrollArea),s=v.useRef(null),i=v.useRef(0),[a,l]=v.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),c=Tp(a.viewport,a.content),d={...r,sizes:a,onSizesChange:l,hasThumb:c>0&&c<1,onThumbChange:h=>s.current=h,onThumbPointerUp:()=>i.current=0,onThumbPointerDown:h=>i.current=h};function f(h,p){return ck(h,i.current,a,p)}return n==="horizontal"?u.jsx(ok,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollLeft,p=Ep(h,a,o.dir);s.current.style.transform=`translate3d(${p}px, 0, 0)`}},onWheelScroll:h=>{o.viewport&&(o.viewport.scrollLeft=h)},onDragScroll:h=>{o.viewport&&(o.viewport.scrollLeft=f(h,o.dir))}}):n==="vertical"?u.jsx(sk,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollTop,p=Ep(h,a);s.current.style.transform=`translate3d(0, ${p}px, 0)`}},onWheelScroll:h=>{o.viewport&&(o.viewport.scrollTop=h)},onDragScroll:h=>{o.viewport&&(o.viewport.scrollTop=f(h))}}):null}),ok=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=En(Yn,e.__scopeScrollArea),[i,a]=v.useState(),l=v.useRef(null),c=Ze(t,l,s.onScrollbarXChange);return v.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(Sp,{"data-orientation":"horizontal",...o,ref:c,sizes:n,style:{bottom:0,left:s.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:s.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Ci(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.x),onDragScroll:d=>e.onDragScroll(d.x),onWheelScroll:(d,f)=>{if(s.viewport){const h=s.viewport.scrollLeft+d.deltaX;e.onWheelScroll(h),Np(h,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollWidth,viewport:s.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:Si(i.paddingLeft),paddingEnd:Si(i.paddingRight)}})}})}),sk=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=En(Yn,e.__scopeScrollArea),[i,a]=v.useState(),l=v.useRef(null),c=Ze(t,l,s.onScrollbarYChange);return v.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(Sp,{"data-orientation":"vertical",...o,ref:c,sizes:n,style:{top:0,right:s.dir==="ltr"?0:void 0,left:s.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Ci(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.y),onDragScroll:d=>e.onDragScroll(d.y),onWheelScroll:(d,f)=>{if(s.viewport){const h=s.viewport.scrollTop+d.deltaY;e.onWheelScroll(h),Np(h,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollHeight,viewport:s.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:Si(i.paddingTop),paddingEnd:Si(i.paddingBottom)}})}})}),[ik,bp]=gp(Yn),Sp=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:s,onThumbPointerUp:i,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:c,onWheelScroll:d,onResize:f,...h}=e,p=En(Yn,n),[m,g]=v.useState(null),y=Ze(t,_=>g(_)),x=v.useRef(null),w=v.useRef(""),C=p.viewport,T=r.content-r.viewport,k=qt(d),S=qt(l),E=ki(f,10);function j(_){if(x.current){const P=_.clientX-x.current.left,D=_.clientY-x.current.top;c({x:P,y:D})}}return v.useEffect(()=>{const _=P=>{const D=P.target;(m==null?void 0:m.contains(D))&&k(P,T)};return document.addEventListener("wheel",_,{passive:!1}),()=>document.removeEventListener("wheel",_,{passive:!1})},[C,m,T,k]),v.useEffect(S,[r,S]),ro(m,E),ro(p.content,E),u.jsx(ik,{scope:n,scrollbar:m,hasThumb:o,onThumbChange:qt(s),onThumbPointerUp:qt(i),onThumbPositionChange:S,onThumbPointerDown:qt(a),children:u.jsx(De.div,{...h,ref:y,style:{position:"absolute",...h.style},onPointerDown:ge(e.onPointerDown,_=>{_.button===0&&(_.target.setPointerCapture(_.pointerId),x.current=m.getBoundingClientRect(),w.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",p.viewport&&(p.viewport.style.scrollBehavior="auto"),j(_))}),onPointerMove:ge(e.onPointerMove,j),onPointerUp:ge(e.onPointerUp,_=>{const P=_.target;P.hasPointerCapture(_.pointerId)&&P.releasePointerCapture(_.pointerId),document.body.style.webkitUserSelect=w.current,p.viewport&&(p.viewport.style.scrollBehavior=""),x.current=null})})})}),bi="ScrollAreaThumb",Cp=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=bp(bi,e.__scopeScrollArea);return u.jsx(Sn,{present:n||o.hasThumb,children:u.jsx(ak,{ref:t,...r})})}),ak=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,s=En(bi,n),i=bp(bi,n),{onThumbPositionChange:a}=i,l=Ze(t,f=>i.onThumbChange(f)),c=v.useRef(void 0),d=ki(()=>{c.current&&(c.current(),c.current=void 0)},100);return v.useEffect(()=>{const f=s.viewport;if(f){const h=()=>{if(d(),!c.current){const p=uk(f,a);c.current=p,a()}};return a(),f.addEventListener("scroll",h),()=>f.removeEventListener("scroll",h)}},[s.viewport,d,a]),u.jsx(De.div,{"data-state":i.hasThumb?"visible":"hidden",...o,ref:l,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:ge(e.onPointerDownCapture,f=>{const p=f.target.getBoundingClientRect(),m=f.clientX-p.left,g=f.clientY-p.top;i.onThumbPointerDown({x:m,y:g})}),onPointerUp:ge(e.onPointerUp,i.onThumbPointerUp)})});Cp.displayName=bi;var Rl="ScrollAreaCorner",kp=v.forwardRef((e,t)=>{const n=En(Rl,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?u.jsx(lk,{...e,ref:t}):null});kp.displayName=Rl;var lk=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=En(Rl,n),[s,i]=v.useState(0),[a,l]=v.useState(0),c=!!(s&&a);return ro(o.scrollbarX,()=>{var f;const d=((f=o.scrollbarX)==null?void 0:f.offsetHeight)||0;o.onCornerHeightChange(d),l(d)}),ro(o.scrollbarY,()=>{var f;const d=((f=o.scrollbarY)==null?void 0:f.offsetWidth)||0;o.onCornerWidthChange(d),i(d)}),c?u.jsx(De.div,{...r,ref:t,style:{width:s,height:a,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function Si(e){return e?parseInt(e,10):0}function Tp(e,t){const n=e/t;return isNaN(n)?0:n}function Ci(e){const t=Tp(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function ck(e,t,n,r="ltr"){const o=Ci(n),s=o/2,i=t||s,a=o-i,l=n.scrollbar.paddingStart+i,c=n.scrollbar.size-n.scrollbar.paddingEnd-a,d=n.content-n.viewport,f=r==="ltr"?[0,d]:[d*-1,0];return Ip([l,c],f)(e)}function Ep(e,t,n="ltr"){const r=Ci(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,s=t.scrollbar.size-o,i=t.content-t.viewport,a=s-r,l=n==="ltr"?[0,i]:[i*-1,0],c=Al(e,l);return Ip([0,i],[0,a])(c)}function Ip(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Np(e,t){return e>0&&e<t}var uk=(e,t=()=>{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const s={left:e.scrollLeft,top:e.scrollTop},i=n.left!==s.left,a=n.top!==s.top;(i||a)&&t(),n=s,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function ki(e,t){const n=qt(e),r=v.useRef(0);return v.useEffect(()=>()=>window.clearTimeout(r.current),[]),v.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function ro(e,t){const n=qt(t);Kt(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}var Ap=yp,dk=vp,fk=kp;const _p=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(Ap,{ref:r,className:oe("relative overflow-hidden",e),...n,children:[u.jsx(dk,{className:"h-full w-full rounded-[inherit] overflow-auto",children:t}),u.jsx(jp,{}),u.jsx(fk,{})]}));_p.displayName=Ap.displayName;const jp=v.forwardRef(({className:e,orientation:t="vertical",...n},r)=>u.jsx(jl,{ref:r,orientation:t,className:oe("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:u.jsx(Cp,{className:"relative flex-1 rounded-full bg-border"})}));jp.displayName=jl.displayName;const Pp=25;function Ol({className:e="",showCreateButton:t=!0,showDeleteButton:n=!0,showEditTitle:r=!0,maxHeight:o="400px",customStyles:s={},currentThreadId:i=null,navigateToThread:a,onThreadSelect:l,onThreadCreate:c,onThreadDelete:d}){const{threads:f,currentThreadId:h,isLoading:p,actions:m}=ps(),{loadThread:g}=ms(),{createThread:y,deleteThread:x,renameThread:w}=m,[C,T]=b.useState(Array.isArray(f)?f:[]),k=b.useRef(C.length>0),S=b.useRef(null),E=b.useRef(0),[j,_]=b.useState(null),[P,D]=b.useState(""),[z,B]=b.useState(!1);b.useEffect(()=>{const J=Array.isArray(f)?f:[];if(J.length>0){k.current=!0,T(J);return}p||(k.current=!1,T(J))},[f,p]),b.useEffect(()=>{if(!S.current)return;const J=S.current.querySelector("[data-radix-scroll-area-viewport]");if(!J)return;let ue=null,ke=null;return ue=requestAnimationFrame(()=>{ke=requestAnimationFrame(()=>{J.scrollTop=E.current})}),()=>{ue!==null&&cancelAnimationFrame(ue),ke!==null&&cancelAnimationFrame(ke)}},[C]);const O=async J=>{try{await g(J),a==null||a(J),l==null||l(J)}catch(ue){console.error("Failed to select thread:",ue)}},H=async()=>{try{B(!0);const J=await y();c==null||c(J),a==null||a(J)}catch(J){console.error("Failed to create thread:",J)}finally{B(!1)}},R=async(J,ue)=>{if(ue.stopPropagation(),!!confirm("Delete this thread?")){if(S.current){const ke=S.current.querySelector("[data-radix-scroll-area-viewport]");ke&&(E.current=ke.scrollTop)}try{await x(J),d==null||d(J)}catch(ke){console.error("Failed to delete thread:",ke)}}},V=(J,ue)=>{ue.stopPropagation(),_(J.threadId),D(J.title||`Thread ${J.threadId.slice(0,8)}`)},$=async J=>{if(P.trim())try{await w(J,P.trim()),_(null),D("")}catch(ue){console.error("Failed to update title:",ue)}},F=()=>{_(null),D("")},ne=(J,ue)=>{J.key==="Enter"?$(ue):J.key==="Escape"&&F()},Q=J=>{if(!J)return"";try{const ue=new Date(J),te=new Date().getTime()-ue.getTime(),L=Math.floor(te/(1e3*60*60*24));return L===0?ue.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):L===1?"Yesterday":L<7?`${L} days ago`:ue.toLocaleDateString()}catch{return""}},ye=J=>J.title||`Thread ${J.threadId.slice(0,8)}`,je=J=>{const ue=ye(J);return ue.length<=Pp?ue:`${ue.slice(0,Pp)}...`};return u.jsxs("div",{className:`flex flex-col h-full ${e} ${s.container||""}`,children:[t&&u.jsx("div",{className:s.header||"flex-shrink-0 p-2 border-b bg-slate-800 border-slate-700 text-slate-100 flex justify-end",children:u.jsx(ut,{onClick:H,disabled:z||p,className:s.createButton||"p-2",size:"sm",variant:"ghost",title:z?"Creating...":"New Chat",children:u.jsx(he.MessageSquarePlus,{size:20})})}),u.jsx(_p,{ref:S,className:`flex-1 min-h-0 ${s.threadList||""}`,style:o?{maxHeight:o}:void 0,children:u.jsx("div",{className:"p-2 space-y-1 pb-4",children:p?u.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-8 text-slate-400",children:[u.jsx(he.Loader2,{className:"h-5 w-5 animate-spin"}),u.jsx("span",{className:"text-sm",children:"Loading threads…"})]}):C.length===0?u.jsxs("div",{className:"text-center py-8 text-slate-400",children:[u.jsx(he.MessageSquare,{className:"w-8 h-8 mx-auto mb-2 opacity-40 text-slate-500"}),u.jsx("p",{className:"text-sm text-slate-500",children:"No conversations yet"})]}):C.slice().sort((J,ue)=>new Date(ue.updatedAt||ue.createdAt||"").getTime()-new Date(J.updatedAt||J.createdAt||"").getTime()).map(J=>u.jsxs("div",{onClick:()=>O(J.threadId),className:`group relative p-3 rounded-lg cursor-pointer transition-colors border ${(i??h)===J.threadId?`${s.activeThread||"bg-slate-600 border-slate-500"} `:`${s.threadItem||"bg-slate-700 border-slate-600 hover:bg-slate-600 text-gray-900 dark:text-slate-100"}`} ${s.threadItem||""} text-gray-900 dark:text-slate-100`,children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("div",{className:"flex-1 min-w-0",children:j===J.threadId?u.jsxs("div",{className:"flex items-center gap-2",onClick:ue=>ue.stopPropagation(),children:[u.jsx(wi,{value:P,onChange:ue=>D(ue.target.value),onKeyDown:ue=>ne(ue,J.threadId),className:"h-6 text-sm",autoFocus:!0}),u.jsx(ut,{variant:"ghost",size:"sm",onClick:()=>$(J.threadId),className:"h-6 w-6 p-0",children:u.jsx(he.Check,{size:12})}),u.jsx(ut,{variant:"ghost",size:"sm",onClick:F,className:"h-6 w-6 p-0",children:u.jsx(he.X,{size:12})})]}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"font-medium text-sm truncate text-gray-900 dark:text-slate-100",children:je(J)}),u.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mt-1",children:[u.jsx(he.Calendar,{size:10}),u.jsx("span",{children:Q(J.updatedAt||J.createdAt)})]})]})}),u.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity ml-2",children:[r&&j!==J.threadId&&u.jsx(ut,{variant:"ghost",size:"sm",onClick:ue=>V(J,ue),className:"h-6 w-6 p-0",title:"Edit title",children:u.jsx(he.Edit3,{size:12})}),n&&u.jsx(ut,{variant:"ghost",size:"sm",onClick:ue=>R(J.threadId,ue),className:"h-6 w-6 p-0 text-red-400 hover:text-red-300 hover:bg-red-900/20",title:"Delete thread",children:u.jsx(he.Trash2,{size:12})})]})]}),i===J.threadId&&u.jsx("div",{className:"absolute left-0 top-1/2 -translate-y-1/2 w-1 h-8 bg-blue-400 rounded-r"})]},J.threadId))})})]})}function oo(e){if(!(typeof globalThis>"u"))return globalThis[e]}function hk(e){if(typeof e!="string")return;const t=e.trim();if(t)return Zn(t)}function Rp(){const e=[oo("__API_BASE_URL__"),oo("__CHAT_API_BASE_URL__"),oo("__CHAT_API_URL__")];for(const t of e){const n=hk(t);if(n)return n}}function Op(){const e=[oo("__API_AUTH_TOKEN__"),oo("__CHAT_API_KEY__"),oo("__CHAT_AUTH_TOKEN__")];for(const t of e)if(typeof t=="string"&&t.trim())return t.trim()}function Mp(...e){for(const t of e)if(typeof t=="string"&&t.trim())return Zn(t);return Zn()}function Dp(){const e={},t=Rp(),n=Op();return t&&(e.baseUrl=t),n&&(e.apiKey=n),e}function Lp(){const e=Dp(),t=sr.getAuthToken(),n=Rp();return{apiBaseUrl:Mp(e.baseUrl,sr.baseUrl,n),apiKey:t||e.apiKey||Op()||"",model:"gpt-4",temperature:.7,maxTokens:4096,layoutSize:"desktop",showThreads:!0,autoScrollMessages:!0,darkMode:!1,enableSound:!1,messageHistory:100}}const Fp="chat-settings";function pk(){try{const e=localStorage.getItem(Fp);return e?JSON.parse(e):{}}catch(e){return console.error("Failed to parse stored settings:",e),{}}}function mk(e){try{const t={...e,apiBaseUrl:Zn(e.apiBaseUrl)};localStorage.setItem(Fp,JSON.stringify(t)),t.apiKey&&sr.setAuthToken(t.apiKey)}catch(t){console.error("Failed to save settings:",t)}}function gk(){const e=Lp(),t=pk(),n=sr.getAuthToken(),r=typeof t.apiBaseUrl=="string"?t.apiBaseUrl:void 0;return{...e,...t,apiKey:n||t.apiKey||e.apiKey,apiBaseUrl:Mp(sr.baseUrl,r,e.apiBaseUrl)}}function yk(e){sr.updateConfig({baseUrl:e.apiBaseUrl,authToken:e.apiKey??void 0}),mk(e)}var xk="Label",$p=v.forwardRef((e,t)=>u.jsx(De.label,{...e,ref:t,onMouseDown:n=>{var o;n.target.closest("button, input, select, textarea")||((o=e.onMouseDown)==null||o.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));$p.displayName=xk;var zp=$p;const vk=Go.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),In=v.forwardRef(({className:e,...t},n)=>u.jsx(zp,{ref:n,className:oe(vk(),e),...t}));In.displayName=zp.displayName;function Bp(e){const t=v.useRef({value:e,previous:e});return v.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Ti="Switch",[wk,KT]=Qn(Ti),[bk,Sk]=wk(Ti),Hp=v.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:s,required:i,disabled:a,value:l="on",onCheckedChange:c,form:d,...f}=e,[h,p]=v.useState(null),m=Ze(t,C=>p(C)),g=v.useRef(!1),y=h?d||!!h.closest("form"):!0,[x,w]=Vr({prop:o,defaultProp:s??!1,onChange:c,caller:Ti});return u.jsxs(bk,{scope:n,checked:x,disabled:a,children:[u.jsx(De.button,{type:"button",role:"switch","aria-checked":x,"aria-required":i,"data-state":Kp(x),"data-disabled":a?"":void 0,disabled:a,value:l,...f,ref:m,onClick:ge(e.onClick,C=>{w(T=>!T),y&&(g.current=C.isPropagationStopped(),g.current||C.stopPropagation())})}),y&&u.jsx(Vp,{control:h,bubbles:!g.current,name:r,value:l,checked:x,required:i,disabled:a,form:d,style:{transform:"translateX(-100%)"}})]})});Hp.displayName=Ti;var Up="SwitchThumb",Wp=v.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=Sk(Up,n);return u.jsx(De.span,{"data-state":Kp(o.checked),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Wp.displayName=Up;var Ck="SwitchBubbleInput",Vp=v.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...o},s)=>{const i=v.useRef(null),a=Ze(i,s),l=Bp(n),c=Yu(t);return v.useEffect(()=>{const d=i.current;if(!d)return;const f=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(f,"checked").set;if(l!==n&&p){const m=new Event("click",{bubbles:r});p.call(d,n),d.dispatchEvent(m)}},[l,n,r]),u.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...o,tabIndex:-1,ref:a,style:{...o.style,...c,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Vp.displayName=Ck;function Kp(e){return e?"checked":"unchecked"}var qp=Hp,kk=Wp;const mr=v.forwardRef(({className:e,...t},n)=>u.jsx(qp,{className:oe("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:u.jsx(kk,{className:oe("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));mr.displayName=qp.displayName;var Gp=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),Tk="VisuallyHidden",Ek=v.forwardRef((e,t)=>u.jsx(De.span,{...e,ref:t,style:{...Gp,...e.style}}));Ek.displayName=Tk;var Ik=[" ","Enter","ArrowUp","ArrowDown"],Nk=[" ","Enter"],Or="Select",[Ei,Ii,Ak]=ha(Or),[so,qT]=Qn(Or,[Ak,_s]),Ni=_s(),[_k,gr]=so(Or),[jk,Pk]=so(Or),Yp=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:s,value:i,defaultValue:a,onValueChange:l,dir:c,name:d,autoComplete:f,disabled:h,required:p,form:m}=e,g=Ni(t),[y,x]=v.useState(null),[w,C]=v.useState(null),[T,k]=v.useState(!1),S=ys(c),[E,j]=Vr({prop:r,defaultProp:o??!1,onChange:s,caller:Or}),[_,P]=Vr({prop:i,defaultProp:a,onChange:l,caller:Or}),D=v.useRef(null),z=y?m||!!y.closest("form"):!0,[B,O]=v.useState(new Set),H=Array.from(B).map(R=>R.props.value).join(";");return u.jsx(sd,{...g,children:u.jsxs(_k,{required:p,scope:t,trigger:y,onTriggerChange:x,valueNode:w,onValueNodeChange:C,valueNodeHasChildren:T,onValueNodeHasChildrenChange:k,contentId:er(),value:_,onValueChange:P,open:E,onOpenChange:j,dir:S,triggerPointerDownPosRef:D,disabled:h,children:[u.jsx(Ei.Provider,{scope:t,children:u.jsx(jk,{scope:e.__scopeSelect,onNativeOptionAdd:v.useCallback(R=>{O(V=>new Set(V).add(R))},[]),onNativeOptionRemove:v.useCallback(R=>{O(V=>{const $=new Set(V);return $.delete(R),$})},[]),children:n})}),z?u.jsxs(vm,{"aria-hidden":!0,required:p,tabIndex:-1,name:d,autoComplete:f,value:_,onChange:R=>P(R.target.value),disabled:h,form:m,children:[_===void 0?u.jsx("option",{value:""}):null,Array.from(B)]},H):null]})})};Yp.displayName=Or;var Xp="SelectTrigger",Jp=v.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,s=Ni(n),i=gr(Xp,n),a=i.disabled||r,l=Ze(t,i.onTriggerChange),c=Ii(n),d=v.useRef("touch"),[f,h,p]=bm(g=>{const y=c().filter(C=>!C.disabled),x=y.find(C=>C.value===i.value),w=Sm(y,g,x);w!==void 0&&i.onValueChange(w.value)}),m=g=>{a||(i.onOpenChange(!0),p()),g&&(i.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)})};return u.jsx(id,{asChild:!0,...s,children:u.jsx(De.button,{type:"button",role:"combobox","aria-controls":i.contentId,"aria-expanded":i.open,"aria-required":i.required,"aria-autocomplete":"none",dir:i.dir,"data-state":i.open?"open":"closed",disabled:a,"data-disabled":a?"":void 0,"data-placeholder":wm(i.value)?"":void 0,...o,ref:l,onClick:ge(o.onClick,g=>{g.currentTarget.focus(),d.current!=="mouse"&&m(g)}),onPointerDown:ge(o.onPointerDown,g=>{d.current=g.pointerType;const y=g.target;y.hasPointerCapture(g.pointerId)&&y.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&g.pointerType==="mouse"&&(m(g),g.preventDefault())}),onKeyDown:ge(o.onKeyDown,g=>{const y=f.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&h(g.key),!(y&&g.key===" ")&&Ik.includes(g.key)&&(m(),g.preventDefault())})})})});Jp.displayName=Xp;var Zp="SelectValue",Qp=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:s,placeholder:i="",...a}=e,l=gr(Zp,n),{onValueNodeHasChildrenChange:c}=l,d=s!==void 0,f=Ze(t,l.onValueNodeChange);return Kt(()=>{c(d)},[c,d]),u.jsx(De.span,{...a,ref:f,style:{pointerEvents:"none"},children:wm(l.value)?u.jsx(u.Fragment,{children:i}):s})});Qp.displayName=Zp;var Rk="SelectIcon",em=v.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return u.jsx(De.span,{"aria-hidden":!0,...o,ref:t,children:r||"▼"})});em.displayName=Rk;var Ok="SelectPortal",tm=e=>u.jsx(js,{asChild:!0,...e});tm.displayName=Ok;var Mr="SelectContent",nm=v.forwardRef((e,t)=>{const n=gr(Mr,e.__scopeSelect),[r,o]=v.useState();if(Kt(()=>{o(new DocumentFragment)},[]),!n.open){const s=r;return s?Yo.createPortal(u.jsx(rm,{scope:e.__scopeSelect,children:u.jsx(Ei.Slot,{scope:e.__scopeSelect,children:u.jsx("div",{children:e.children})})}),s):null}return u.jsx(om,{...e,ref:t})});nm.displayName=Mr;var Dn=10,[rm,yr]=so(Mr),Mk="SelectContentImpl",Dk=vr.createSlot("SelectContent.RemoveScroll"),om=v.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:s,onPointerDownOutside:i,side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:m,hideWhenDetached:g,avoidCollisions:y,...x}=e,w=gr(Mr,n),[C,T]=v.useState(null),[k,S]=v.useState(null),E=Ze(t,te=>T(te)),[j,_]=v.useState(null),[P,D]=v.useState(null),z=Ii(n),[B,O]=v.useState(!1),H=v.useRef(!1);v.useEffect(()=>{if(C)return Ma(C)},[C]),ga();const R=v.useCallback(te=>{const[L,...q]=z().map(U=>U.ref.current),[ie]=q.slice(-1),ce=document.activeElement;for(const U of te)if(U===ce||(U==null||U.scrollIntoView({block:"nearest"}),U===L&&k&&(k.scrollTop=0),U===ie&&k&&(k.scrollTop=k.scrollHeight),U==null||U.focus(),document.activeElement!==ce))return},[z,k]),V=v.useCallback(()=>R([j,C]),[R,j,C]);v.useEffect(()=>{B&&V()},[B,V]);const{onOpenChange:$,triggerPointerDownPosRef:F}=w;v.useEffect(()=>{if(C){let te={x:0,y:0};const L=ie=>{var ce,U;te={x:Math.abs(Math.round(ie.pageX)-(((ce=F.current)==null?void 0:ce.x)??0)),y:Math.abs(Math.round(ie.pageY)-(((U=F.current)==null?void 0:U.y)??0))}},q=ie=>{te.x<=10&&te.y<=10?ie.preventDefault():C.contains(ie.target)||$(!1),document.removeEventListener("pointermove",L),F.current=null};return F.current!==null&&(document.addEventListener("pointermove",L),document.addEventListener("pointerup",q,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",L),document.removeEventListener("pointerup",q,{capture:!0})}}},[C,$,F]),v.useEffect(()=>{const te=()=>$(!1);return window.addEventListener("blur",te),window.addEventListener("resize",te),()=>{window.removeEventListener("blur",te),window.removeEventListener("resize",te)}},[$]);const[ne,Q]=bm(te=>{const L=z().filter(ce=>!ce.disabled),q=L.find(ce=>ce.ref.current===document.activeElement),ie=Sm(L,te,q);ie&&setTimeout(()=>ie.ref.current.focus())}),ye=v.useCallback((te,L,q)=>{const ie=!H.current&&!q;(w.value!==void 0&&w.value===L||ie)&&(_(te),ie&&(H.current=!0))},[w.value]),je=v.useCallback(()=>C==null?void 0:C.focus(),[C]),J=v.useCallback((te,L,q)=>{const ie=!H.current&&!q;(w.value!==void 0&&w.value===L||ie)&&D(te)},[w.value]),ue=r==="popper"?Ml:sm,ke=ue===Ml?{side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:m,hideWhenDetached:g,avoidCollisions:y}:{};return u.jsx(rm,{scope:n,content:C,viewport:k,onViewportChange:S,itemRefCallback:ye,selectedItem:j,onItemLeave:je,itemTextRefCallback:J,focusSelectedItem:V,selectedItemText:P,position:r,isPositioned:B,searchRef:ne,children:u.jsx(zs,{as:Dk,allowPinchZoom:!0,children:u.jsx(vs,{asChild:!0,trapped:w.open,onMountAutoFocus:te=>{te.preventDefault()},onUnmountAutoFocus:ge(o,te=>{var L;(L=w.trigger)==null||L.focus({preventScroll:!0}),te.preventDefault()}),children:u.jsx(xs,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:te=>te.preventDefault(),onDismiss:()=>w.onOpenChange(!1),children:u.jsx(ue,{role:"listbox",id:w.contentId,"data-state":w.open?"open":"closed",dir:w.dir,onContextMenu:te=>te.preventDefault(),...x,...ke,onPlaced:()=>O(!0),ref:E,style:{display:"flex",flexDirection:"column",outline:"none",...x.style},onKeyDown:ge(x.onKeyDown,te=>{const L=te.ctrlKey||te.altKey||te.metaKey;if(te.key==="Tab"&&te.preventDefault(),!L&&te.key.length===1&&Q(te.key),["ArrowUp","ArrowDown","Home","End"].includes(te.key)){let ie=z().filter(ce=>!ce.disabled).map(ce=>ce.ref.current);if(["ArrowUp","End"].includes(te.key)&&(ie=ie.slice().reverse()),["ArrowUp","ArrowDown"].includes(te.key)){const ce=te.target,U=ie.indexOf(ce);ie=ie.slice(U+1)}setTimeout(()=>R(ie)),te.preventDefault()}})})})})})})});om.displayName=Mk;var Lk="SelectItemAlignedPosition",sm=v.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,s=gr(Mr,n),i=yr(Mr,n),[a,l]=v.useState(null),[c,d]=v.useState(null),f=Ze(t,E=>d(E)),h=Ii(n),p=v.useRef(!1),m=v.useRef(!0),{viewport:g,selectedItem:y,selectedItemText:x,focusSelectedItem:w}=i,C=v.useCallback(()=>{if(s.trigger&&s.valueNode&&a&&c&&g&&y&&x){const E=s.trigger.getBoundingClientRect(),j=c.getBoundingClientRect(),_=s.valueNode.getBoundingClientRect(),P=x.getBoundingClientRect();if(s.dir!=="rtl"){const ce=P.left-j.left,U=_.left-ce,We=E.left-U,re=E.width+We,xe=Math.max(re,j.width),Pe=window.innerWidth-Dn,$e=Al(U,[Dn,Math.max(Dn,Pe-xe)]);a.style.minWidth=re+"px",a.style.left=$e+"px"}else{const ce=j.right-P.right,U=window.innerWidth-_.right-ce,We=window.innerWidth-E.right-U,re=E.width+We,xe=Math.max(re,j.width),Pe=window.innerWidth-Dn,$e=Al(U,[Dn,Math.max(Dn,Pe-xe)]);a.style.minWidth=re+"px",a.style.right=$e+"px"}const D=h(),z=window.innerHeight-Dn*2,B=g.scrollHeight,O=window.getComputedStyle(c),H=parseInt(O.borderTopWidth,10),R=parseInt(O.paddingTop,10),V=parseInt(O.borderBottomWidth,10),$=parseInt(O.paddingBottom,10),F=H+R+B+$+V,ne=Math.min(y.offsetHeight*5,F),Q=window.getComputedStyle(g),ye=parseInt(Q.paddingTop,10),je=parseInt(Q.paddingBottom,10),J=E.top+E.height/2-Dn,ue=z-J,ke=y.offsetHeight/2,te=y.offsetTop+ke,L=H+R+te,q=F-L;if(L<=J){const ce=D.length>0&&y===D[D.length-1].ref.current;a.style.bottom="0px";const U=c.clientHeight-g.offsetTop-g.offsetHeight,We=Math.max(ue,ke+(ce?je:0)+U+V),re=L+We;a.style.height=re+"px"}else{const ce=D.length>0&&y===D[0].ref.current;a.style.top="0px";const We=Math.max(J,H+g.offsetTop+(ce?ye:0)+ke)+q;a.style.height=We+"px",g.scrollTop=L-J+g.offsetTop}a.style.margin=`${Dn}px 0`,a.style.minHeight=ne+"px",a.style.maxHeight=z+"px",r==null||r(),requestAnimationFrame(()=>p.current=!0)}},[h,s.trigger,s.valueNode,a,c,g,y,x,s.dir,r]);Kt(()=>C(),[C]);const[T,k]=v.useState();Kt(()=>{c&&k(window.getComputedStyle(c).zIndex)},[c]);const S=v.useCallback(E=>{E&&m.current===!0&&(C(),w==null||w(),m.current=!1)},[C,w]);return u.jsx($k,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:p,onScrollButtonChange:S,children:u.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:T},children:u.jsx(De.div,{...o,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});sm.displayName=Lk;var Fk="SelectPopperPosition",Ml=v.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=Dn,...s}=e,i=Ni(n);return u.jsx(ad,{...i,...s,ref:t,align:r,collisionPadding:o,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});Ml.displayName=Fk;var[$k,Dl]=so(Mr,{}),Ll="SelectViewport",im=v.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...o}=e,s=yr(Ll,n),i=Dl(Ll,n),a=Ze(t,s.onViewportChange),l=v.useRef(0);return u.jsxs(u.Fragment,{children:[u.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),u.jsx(Ei.Slot,{scope:n,children:u.jsx(De.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:ge(o.onScroll,c=>{const d=c.currentTarget,{contentWrapper:f,shouldExpandOnScrollRef:h}=i;if(h!=null&&h.current&&f){const p=Math.abs(l.current-d.scrollTop);if(p>0){const m=window.innerHeight-Dn*2,g=parseFloat(f.style.minHeight),y=parseFloat(f.style.height),x=Math.max(g,y);if(x<m){const w=x+p,C=Math.min(m,w),T=w-C;f.style.height=C+"px",f.style.bottom==="0px"&&(d.scrollTop=T>0?T:0,f.style.justifyContent="flex-end")}}}l.current=d.scrollTop})})})]})});im.displayName=Ll;var am="SelectGroup",[zk,Bk]=so(am),Hk=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=er();return u.jsx(zk,{scope:n,id:o,children:u.jsx(De.div,{role:"group","aria-labelledby":o,...r,ref:t})})});Hk.displayName=am;var lm="SelectLabel",cm=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Bk(lm,n);return u.jsx(De.div,{id:o.id,...r,ref:t})});cm.displayName=lm;var Ai="SelectItem",[Uk,um]=so(Ai),dm=v.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:s,...i}=e,a=gr(Ai,n),l=yr(Ai,n),c=a.value===r,[d,f]=v.useState(s??""),[h,p]=v.useState(!1),m=Ze(t,w=>{var C;return(C=l.itemRefCallback)==null?void 0:C.call(l,w,r,o)}),g=er(),y=v.useRef("touch"),x=()=>{o||(a.onValueChange(r),a.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return u.jsx(Uk,{scope:n,value:r,disabled:o,textId:g,isSelected:c,onItemTextChange:v.useCallback(w=>{f(C=>C||((w==null?void 0:w.textContent)??"").trim())},[]),children:u.jsx(Ei.ItemSlot,{scope:n,value:r,disabled:o,textValue:d,children:u.jsx(De.div,{role:"option","aria-labelledby":g,"data-highlighted":h?"":void 0,"aria-selected":c&&h,"data-state":c?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...i,ref:m,onFocus:ge(i.onFocus,()=>p(!0)),onBlur:ge(i.onBlur,()=>p(!1)),onClick:ge(i.onClick,()=>{y.current!=="mouse"&&x()}),onPointerUp:ge(i.onPointerUp,()=>{y.current==="mouse"&&x()}),onPointerDown:ge(i.onPointerDown,w=>{y.current=w.pointerType}),onPointerMove:ge(i.onPointerMove,w=>{var C;y.current=w.pointerType,o?(C=l.onItemLeave)==null||C.call(l):y.current==="mouse"&&w.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ge(i.onPointerLeave,w=>{var C;w.currentTarget===document.activeElement&&((C=l.onItemLeave)==null||C.call(l))}),onKeyDown:ge(i.onKeyDown,w=>{var T;((T=l.searchRef)==null?void 0:T.current)!==""&&w.key===" "||(Nk.includes(w.key)&&x(),w.key===" "&&w.preventDefault())})})})})});dm.displayName=Ai;var Vo="SelectItemText",fm=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...s}=e,i=gr(Vo,n),a=yr(Vo,n),l=um(Vo,n),c=Pk(Vo,n),[d,f]=v.useState(null),h=Ze(t,x=>f(x),l.onItemTextChange,x=>{var w;return(w=a.itemTextRefCallback)==null?void 0:w.call(a,x,l.value,l.disabled)}),p=d==null?void 0:d.textContent,m=v.useMemo(()=>u.jsx("option",{value:l.value,disabled:l.disabled,children:p},l.value),[l.disabled,l.value,p]),{onNativeOptionAdd:g,onNativeOptionRemove:y}=c;return Kt(()=>(g(m),()=>y(m)),[g,y,m]),u.jsxs(u.Fragment,{children:[u.jsx(De.span,{id:l.textId,...s,ref:h}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?Yo.createPortal(s.children,i.valueNode):null]})});fm.displayName=Vo;var hm="SelectItemIndicator",pm=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return um(hm,n).isSelected?u.jsx(De.span,{"aria-hidden":!0,...r,ref:t}):null});pm.displayName=hm;var Fl="SelectScrollUpButton",mm=v.forwardRef((e,t)=>{const n=yr(Fl,e.__scopeSelect),r=Dl(Fl,e.__scopeSelect),[o,s]=v.useState(!1),i=Ze(t,r.onScrollButtonChange);return Kt(()=>{if(n.viewport&&n.isPositioned){let a=function(){const c=l.scrollTop>0;s(c)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?u.jsx(ym,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});mm.displayName=Fl;var $l="SelectScrollDownButton",gm=v.forwardRef((e,t)=>{const n=yr($l,e.__scopeSelect),r=Dl($l,e.__scopeSelect),[o,s]=v.useState(!1),i=Ze(t,r.onScrollButtonChange);return Kt(()=>{if(n.viewport&&n.isPositioned){let a=function(){const c=l.scrollHeight-l.clientHeight,d=Math.ceil(l.scrollTop)<c;s(d)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?u.jsx(ym,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});gm.displayName=$l;var ym=v.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,s=yr("SelectScrollButton",n),i=v.useRef(null),a=Ii(n),l=v.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return v.useEffect(()=>()=>l(),[l]),Kt(()=>{var d;const c=a().find(f=>f.ref.current===document.activeElement);(d=c==null?void 0:c.ref.current)==null||d.scrollIntoView({block:"nearest"})},[a]),u.jsx(De.div,{"aria-hidden":!0,...o,ref:t,style:{flexShrink:0,...o.style},onPointerDown:ge(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:ge(o.onPointerMove,()=>{var c;(c=s.onItemLeave)==null||c.call(s),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:ge(o.onPointerLeave,()=>{l()})})}),Wk="SelectSeparator",xm=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return u.jsx(De.div,{"aria-hidden":!0,...r,ref:t})});xm.displayName=Wk;var zl="SelectArrow",Vk=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Ni(n),s=gr(zl,n),i=yr(zl,n);return s.open&&i.position==="popper"?u.jsx(ld,{...o,...r,ref:t}):null});Vk.displayName=zl;var Kk="SelectBubbleInput",vm=v.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const o=v.useRef(null),s=Ze(r,o),i=Bp(t);return v.useEffect(()=>{const a=o.current;if(!a)return;const l=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&d){const f=new Event("change",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),u.jsx(De.select,{...n,style:{...Gp,...n.style},ref:s,defaultValue:t})});vm.displayName=Kk;function wm(e){return e===""||e===void 0}function bm(e){const t=qt(e),n=v.useRef(""),r=v.useRef(0),o=v.useCallback(i=>{const a=n.current+i;t(a),function l(c){n.current=c,window.clearTimeout(r.current),c!==""&&(r.current=window.setTimeout(()=>l(""),1e3))}(a)},[t]),s=v.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return v.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,s]}function Sm(e,t,n){const o=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=qk(e,Math.max(s,0));o.length===1&&(i=i.filter(c=>c!==n));const l=i.find(c=>c.textValue.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function qk(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Gk=Yp,Cm=Jp,Yk=Qp,Xk=em,Jk=tm,km=nm,Zk=im,Tm=cm,Em=dm,Qk=fm,eT=pm,Im=mm,Nm=gm,Am=xm;const _m=Gk,jm=Yk,Bl=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(Cm,{ref:r,className:oe("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,u.jsx(Xk,{asChild:!0,children:u.jsx(he.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));Bl.displayName=Cm.displayName;const Pm=v.forwardRef(({className:e,...t},n)=>u.jsx(Im,{ref:n,className:oe("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(he.ChevronUp,{className:"h-4 w-4"})}));Pm.displayName=Im.displayName;const Rm=v.forwardRef(({className:e,...t},n)=>u.jsx(Nm,{ref:n,className:oe("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(he.ChevronDown,{className:"h-4 w-4"})}));Rm.displayName=Nm.displayName;const Hl=v.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>u.jsx(Jk,{children:u.jsxs(km,{ref:o,className:oe("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[u.jsx(Pm,{}),u.jsx(Zk,{className:oe("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),u.jsx(Rm,{})]})}));Hl.displayName=km.displayName;const tT=v.forwardRef(({className:e,...t},n)=>u.jsx(Tm,{ref:n,className:oe("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));tT.displayName=Tm.displayName;const Dr=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(Em,{ref:r,className:oe("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(eT,{children:u.jsx(he.Check,{className:"h-4 w-4"})})}),u.jsx(Qk,{children:t})]}));Dr.displayName=Em.displayName;const nT=v.forwardRef(({className:e,...t},n)=>u.jsx(Am,{ref:n,className:oe("-mx-1 my-1 h-px bg-muted",e),...t}));nT.displayName=Am.displayName;var rT="Separator",Om="horizontal",oT=["horizontal","vertical"],Mm=v.forwardRef((e,t)=>{const{decorative:n,orientation:r=Om,...o}=e,s=sT(r)?r:Om,a=n?{role:"none"}:{"aria-orientation":s==="vertical"?s:void 0,role:"separator"};return u.jsx(De.div,{"data-orientation":s,...a,...o,ref:t})});Mm.displayName=rT;function sT(e){return oT.includes(e)}var Dm=Mm;const Lm=v.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>u.jsx(Dm,{ref:o,decorative:n,orientation:t,className:oe("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Lm.displayName=Dm.displayName;const iT=Vh,aT=SC,lT=Kh,Fm=v.forwardRef(({className:e,...t},n)=>u.jsx(di,{className:oe("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));Fm.displayName=di.displayName;const cT=Go.cva("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),$m=v.forwardRef(({side:e="right",className:t,children:n,...r},o)=>u.jsxs(lT,{children:[u.jsx(Fm,{}),u.jsxs(fi,{ref:o,className:oe(cT({side:e}),t),...r,children:[n,u.jsxs(qh,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[u.jsx(he.X,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));$m.displayName=fi.displayName;const zm=({className:e,...t})=>u.jsx("div",{className:oe("flex flex-col space-y-2 text-center sm:text-left",e),...t});zm.displayName="SheetHeader";const Bm=v.forwardRef(({className:e,...t},n)=>u.jsx(Pr,{ref:n,className:oe("text-lg font-semibold text-foreground",e),...t}));Bm.displayName=Pr.displayName;const Hm=v.forwardRef(({className:e,...t},n)=>u.jsx(hi,{ref:n,className:oe("text-sm text-muted-foreground",e),...t}));Hm.displayName=hi.displayName;const uT={api:{baseUrl:"http://localhost:8000/api",authToken:"",enableAuth:!1},ui:{layout:"sidebar",theme:"light",showTimestamps:!0,showAgentNames:!0,compactMessages:!1},behavior:{autoSave:!0,enableStreaming:!0,showTypingIndicator:!0}};function dT({settings:e,onSettingsChange:t,className:n=""}){const[r,o]=b.useState(!1),[s,i]=b.useState(!1),[a,l]=b.useState(e),[c,d]=b.useState(!1),{toast:f}=wl();b.useEffect(()=>{const y=JSON.stringify(a)!==JSON.stringify(e);d(y)},[a,e]),b.useEffect(()=>{l(e)},[e]);const h=()=>{t(a),d(!1),f({title:"Settings saved",description:"Your chat configuration has been updated successfully."})},p=()=>{l(uT),d(!0),f({title:"Settings reset",description:"Configuration has been reset to defaults."})},m=()=>{l(e),d(!1),o(!1)},g=async()=>{try{const x=await(await fetch(`${a.api.baseUrl}/health`)).json();f({title:"Connection successful",description:`API is ${x.status||"healthy"}`})}catch{f({title:"Connection failed",description:"Unable to connect to the API endpoint.",variant:"destructive"})}};return u.jsxs(iT,{open:r,onOpenChange:o,children:[u.jsx(aT,{asChild:!0,children:u.jsxs(ut,{variant:"outline",size:"sm",className:n,children:[u.jsx(he.Settings,{className:"h-4 w-4 mr-2"}),"Settings",c&&u.jsx(Sh,{variant:"destructive",className:"ml-2 h-4 w-4 p-0"})]})}),u.jsxs($m,{className:"w-[500px] sm:w-[600px] overflow-y-auto",children:[u.jsxs(zm,{children:[u.jsx(Bm,{children:"Chat Settings"}),u.jsx(Hm,{children:"Configure your chat interface, API connection, and behavior preferences."})]}),u.jsxs("div",{className:"space-y-6 py-6",children:[u.jsxs(Lo,{children:[u.jsx(Fo,{className:"pb-3",children:u.jsxs($o,{className:"text-lg flex items-center gap-2",children:[u.jsx(he.Server,{className:"h-5 w-5"}),"API Configuration"]})}),u.jsxs(zo,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(In,{htmlFor:"api-url",children:"API Base URL"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(wi,{id:"api-url",value:a.api.baseUrl,onChange:y=>l(x=>({...x,api:{...x.api,baseUrl:y.target.value}})),placeholder:"http://localhost:8000/api"}),u.jsx(ut,{variant:"outline",onClick:g,children:"Test"})]})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(In,{htmlFor:"enable-auth",children:"Enable Authentication"}),u.jsx(mr,{id:"enable-auth",checked:a.api.enableAuth,onCheckedChange:y=>l(x=>({...x,api:{...x.api,enableAuth:y}}))})]}),a.api.enableAuth&&u.jsxs("div",{className:"space-y-2",children:[u.jsx(In,{htmlFor:"auth-token",children:"Authentication Token"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(wi,{id:"auth-token",type:s?"text":"password",value:a.api.authToken,onChange:y=>l(x=>({...x,api:{...x.api,authToken:y.target.value}})),placeholder:"Enter your Bearer token"}),u.jsx(ut,{variant:"outline",size:"icon",onClick:()=>i(!s),children:s?u.jsx(he.EyeOff,{className:"h-4 w-4"}):u.jsx(he.Eye,{className:"h-4 w-4"})})]})]})]})]}),u.jsxs(Lo,{children:[u.jsx(Fo,{className:"pb-3",children:u.jsxs($o,{className:"text-lg flex items-center gap-2",children:[u.jsx(he.Layout,{className:"h-5 w-5"}),"Interface Settings"]})}),u.jsxs(zo,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(In,{htmlFor:"layout",children:"Layout Style"}),u.jsxs(_m,{value:a.ui.layout,onValueChange:y=>l(x=>({...x,ui:{...x.ui,layout:y}})),children:[u.jsx(Bl,{children:u.jsx(jm,{})}),u.jsxs(Hl,{children:[u.jsx(Dr,{value:"sidebar",children:"Sidebar Layout"}),u.jsx(Dr,{value:"fullscreen",children:"Fullscreen"}),u.jsx(Dr,{value:"tabs",children:"Tabbed Interface"})]})]})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(In,{htmlFor:"theme",children:"Theme"}),u.jsxs(_m,{value:a.ui.theme,onValueChange:y=>l(x=>({...x,ui:{...x.ui,theme:y}})),children:[u.jsx(Bl,{children:u.jsx(jm,{})}),u.jsxs(Hl,{children:[u.jsx(Dr,{value:"light",children:"Light"}),u.jsx(Dr,{value:"dark",children:"Dark"}),u.jsx(Dr,{value:"system",children:"System"})]})]})]}),u.jsx(Lm,{}),u.jsxs("div",{className:"space-y-3",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(In,{htmlFor:"show-timestamps",children:"Show Timestamps"}),u.jsx(mr,{id:"show-timestamps",checked:a.ui.showTimestamps,onCheckedChange:y=>l(x=>({...x,ui:{...x.ui,showTimestamps:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(In,{htmlFor:"show-agent-names",children:"Show Agent Names"}),u.jsx(mr,{id:"show-agent-names",checked:a.ui.showAgentNames,onCheckedChange:y=>l(x=>({...x,ui:{...x.ui,showAgentNames:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(In,{htmlFor:"compact-messages",children:"Compact Messages"}),u.jsx(mr,{id:"compact-messages",checked:a.ui.compactMessages,onCheckedChange:y=>l(x=>({...x,ui:{...x.ui,compactMessages:y}}))})]})]})]})]}),u.jsxs(Lo,{children:[u.jsx(Fo,{className:"pb-3",children:u.jsxs($o,{className:"text-lg flex items-center gap-2",children:[u.jsx(he.MessageCircle,{className:"h-5 w-5"}),"Behavior Settings"]})}),u.jsxs(zo,{className:"space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(In,{htmlFor:"auto-save",children:"Auto-save Conversations"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically save messages to threads"})]}),u.jsx(mr,{id:"auto-save",checked:a.behavior.autoSave,onCheckedChange:y=>l(x=>({...x,behavior:{...x.behavior,autoSave:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(In,{htmlFor:"enable-streaming",children:"Enable Streaming"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Stream responses in real-time"})]}),u.jsx(mr,{id:"enable-streaming",checked:a.behavior.enableStreaming,onCheckedChange:y=>l(x=>({...x,behavior:{...x.behavior,enableStreaming:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(In,{htmlFor:"typing-indicator",children:"Typing Indicator"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Show typing indicator during responses"})]}),u.jsx(mr,{id:"typing-indicator",checked:a.behavior.showTypingIndicator,onCheckedChange:y=>l(x=>({...x,behavior:{...x.behavior,showTypingIndicator:y}}))})]})]})]})]}),u.jsxs("div",{className:"flex items-center justify-between pt-6 border-t",children:[u.jsxs(ut,{variant:"outline",onClick:p,children:[u.jsx(he.RotateCcw,{className:"h-4 w-4 mr-2"}),"Reset"]}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(ut,{variant:"outline",onClick:m,children:"Cancel"}),u.jsxs(ut,{onClick:h,disabled:!c,children:[u.jsx(he.Save,{className:"h-4 w-4 mr-2"}),"Save Changes"]})]})]})]})]})}function fT({layout:e="sidebar",layoutSize:t="desktop",showThreads:n=!0,className:r="",customStyles:o={},...s}){const i=c=>{const d="h-full";switch(c){case"phone":return`${d} max-w-none`;case"tablet":return`${d} max-w-4xl mx-auto`;case"half-screen":return`${d} max-w-2xl`;case"desktop":default:return`${d} max-w-7xl mx-auto`}},a=c=>({"--chat-sidebar-width":c==="phone"?"100%":c==="tablet"?"280px":c==="half-screen"?"240px":"320px","--chat-message-max-width":c==="phone"?"95%":c==="tablet"?"90%":c==="half-screen"?"85%":"80%","--chat-input-height":c==="phone"?"120px":"100px"}),l=b.useCallback(c=>{var d;(d=s.onThreadChange)==null||d.call(s,c)},[s]);return e==="fullscreen"?u.jsx(gs,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsx(vi,{className:"flex-1",onError:s.onError,enableFileUpload:!0})})}):e==="tabs"?u.jsx(gs,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsxs("div",{className:"flex-1 flex min-h-0 overflow-hidden",children:[n&&u.jsx("div",{className:`w-80 border-r flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:u.jsx(Ol,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),u.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:u.jsx(vi,{onError:s.onError,enableFileUpload:!0})})]})})}):u.jsx(gs,{...s,onThreadChange:l,children:u.jsxs("div",{className:`${i(t)} flex overflow-hidden ${r} ${o.container||""}`,style:a(t),children:[n&&u.jsx("div",{className:`w-80 border-r bg-gray-50 flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:u.jsx(Ol,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),u.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:u.jsx(vi,{onError:s.onError,enableFileUpload:!0})})]})})}Ae.ChatApi=$c,Ae.ChatInput=hu,Ae.ChatInterface=vi,Ae.ChatProviders=gs,Ae.ChatSettings=dT,Ae.MarkdownContent=Wo,Ae.MessageComponent=Il,Ae.MessageList=Nl,Ae.ThreadManager=Ol,Ae.applySettings=yk,Ae.chatApiClient=sr,Ae.default=fT,Ae.del=Fc,Ae.get=wn,Ae.getChatToken=Mc,Ae.getCurrentSettings=gk,Ae.getDefaultApiConfig=Dp,Ae.getDefaultChatSettings=Lp,Ae.onChatTokenChanged=Dc,Ae.post=Gi,Ae.put=Lc,Ae.registerChatTokenSyncHandler=Sy,Ae.setChatToken=qi,Ae.useApi=Yi,Ae.useChatStream=eu,Ae.useMessagesReducer=Kc,Ae.useStream=du,Ae.useThreadState=ms,Ae.useThreads=ps,Object.defineProperties(Ae,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|