teodor-new-chat-ui 4.1.82 → 4.1.83

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 CHANGED
@@ -3696,7 +3696,7 @@ function Qx(e) {
3696
3696
  } catch (B) {
3697
3697
  r == null || r(String(B)), console.error("[useThreadList] Failed to refresh threads:", B), y(String(B));
3698
3698
  } finally {
3699
- N || p(!1);
3699
+ p(!1);
3700
3700
  }
3701
3701
  }, [t, r]), O = Ne(
3702
3702
  async (N) => {
package/dist/index.umd.js CHANGED
@@ -35,7 +35,7 @@ React keys must be passed directly to JSX without using spread:
35
35
  `+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Hn(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&Eo.assertOptions(r,{silentJSONParsing:en.transitional(en.boolean),forcedJSONParsing:en.transitional(en.boolean),clarifyTimeoutError:en.transitional(en.boolean)},!1),o!=null&&(O.isFunction(o)?n.paramsSerializer={serialize:o}:Eo.assertOptions(o,{encode:en.function,serialize:en.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Eo.assertOptions(n,{baseUrl:en.spelling("baseURL"),withXsrfToken:en.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&O.merge(s.common,s[n.method]);s&&O.forEach(["delete","get","head","post","put","patch","common"],y=>{delete s[y]}),n.headers=It.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(w){typeof w.runWhen=="function"&&w.runWhen(n)===!1||(l=l&&w.synchronous,a.unshift(w.fulfilled,w.rejected))});const u=[];this.interceptors.response.forEach(function(w){u.push(w.fulfilled,w.rejected)});let d,f=0,h;if(!l){const y=[ql.bind(this),void 0];for(y.unshift(...a),y.push(...u),h=y.length,d=Promise.resolve(n);f<h;)d=d.then(y[f++],y[f++]);return d}h=a.length;let p=n;for(;f<h;){const y=a[f++],w=a[f++];try{p=y(p)}catch(x){w.call(this,x);break}}try{d=ql.call(this,p)}catch(y){return Promise.reject(y)}for(f=0,h=u.length;f<h;)d=d.then(u[f++],u[f++]);return d}getUri(t){t=Hn(this.defaults,t);const n=Ml(t.baseURL,t.url,t.allowAbsoluteUrls);return Il(n,t.params,t.paramsSerializer)}};O.forEach(["delete","get","head","options"],function(t){Un.prototype[t]=function(n,r){return this.request(Hn(r||{},{method:t,url:n,data:(r||{}).data}))}}),O.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(Hn(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Un.prototype[t]=n(),Un.prototype[t+"Form"]=n(!0)});let Rg=class lm{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 hr(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 lm(function(o){t=o}),cancel:t}}};function Pg(e){return function(n){return e.apply(null,n)}}function Og(e){return O.isObject(e)&&e.isAxiosError===!0}const ci={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(ci).forEach(([e,t])=>{ci[t]=e});function Yl(e){const t=new Un(e),n=dl(Un.prototype.request,t);return O.extend(n,Un.prototype,t,{allOwnKeys:!0}),O.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Yl(Hn(e,o))},n}const dt=Yl(zr);dt.Axios=Un,dt.CanceledError=hr,dt.CancelToken=Rg,dt.isCancel=jl,dt.VERSION=Kl,dt.toFormData=So,dt.AxiosError=Me,dt.Cancel=dt.CanceledError,dt.all=function(t){return Promise.all(t)},dt.spread=Pg,dt.isAxiosError=Og,dt.mergeConfig=Hn,dt.AxiosHeaders=It,dt.formToJSON=e=>Al(O.isHTMLForm(e)?new FormData(e):e),dt.getAdapter=Vl.getAdapter,dt.HttpStatusCode=ci,dt.default=dt;const{Axios:hk,AxiosError:pk,CanceledError:mk,isCancel:gk,CancelToken:xk,VERSION:vk,all:wk,Cancel:yk,isAxiosError:bk,spread:Sk,toFormData:Ck,AxiosHeaders:kk,HttpStatusCode:Tk,formToJSON:Ik,getAdapter:Ek,mergeConfig:Nk}=dt,Xl=typeof window<"u"?window.__API_BASE_URL__:void 0,Jl=Xl?xn(Xl):void 0;function xn(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let No=null;const ui=new Set;function Zl(){return No}function di(e){No=e,ui.forEach(t=>t(e))}function Ql(e){return ui.add(e),()=>ui.delete(e)}const $t=dt.create({...Jl?{baseURL:Jl}:{},timeout:3e4,withCredentials:!0});$t.interceptors.request.use(e=>(No&&(e.headers.Authorization=`Bearer ${No}`),e)),$t.interceptors.response.use(e=>e,e=>Promise.reject(e));async function _t(e,t){return $t.defaults.baseURL?(await $t.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function fi(e,t,n){return $t.defaults.baseURL?(await $t.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function ec(e,t,n){return $t.defaults.baseURL?(await $t.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function tc(e,t){return $t.defaults.baseURL?(await $t.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function jt(e){return e&&typeof e=="object"&&"data"in e?e.data:e}function vn(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):null}function Mg(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Number.parseInt(e,10);if(Number.isFinite(t))return t}return 0}function nc(e){if(!e||typeof e!="object")throw new Error("Invalid thread summary data");const t=e,n=vn(t.threadId)??vn(t.thread_id)??vn(t.id);if(!n)throw new Error("Thread summary is missing threadId");const r=vn(t.title)??vn(t.name)??`Thread ${n.slice(0,8)}`,o=vn(t.createdAt)??vn(t.created_at)??new Date().toISOString(),s=vn(t.updatedAt)??vn(t.updated_at)??o,i=t.messageCount??t.message_count??t.messagesCount??t.messages_count,a=Math.max(0,Mg(i));return{threadId:n,title:r,createdAt:o,updatedAt:s,messageCount:a}}function hi(e){if(!e||typeof e!="object")throw new Error("Invalid thread info data");const t=nc(e);return{...e,...t}}function Ao(e){if(!e)return[];if(Array.isArray(e))return e;if(typeof e=="object"){const t=e;if(Array.isArray(t.items))return t.items;if(t.items&&typeof t.items=="object"){const n=Ao(t.items);if(n.length>0)return n}if(Array.isArray(t.threads))return t.threads;if(t.threads&&typeof t.threads=="object"){const n=Ao(t.threads);if(n.length>0)return n}if("data"in t)return Ao(t.data)}return[]}class rc{get baseUrl(){const t=$t.defaults.baseURL;return t?xn(String(t)):""}updateConfig(t){t.baseUrl&&($t.defaults.baseURL=xn(String(t.baseUrl))),t.authToken!==void 0&&di(t.authToken)}getAuthToken(){return Zl()}setAuthToken(t){di(t)}onTokenChange(t){return Ql(t)}async listThreads(){const t=await _t("/threads"),n=jt(t),r=Ao(n),o=[];for(const s of r)try{o.push(nc(s))}catch{}return o}async createThread(t){const r=await fi("/threads",t?{title:t}:void 0);return hi(jt(r))}async updateThread(t,n){const r=await ec(`/threads/${t}`,{title:n});return hi(jt(r))}async deleteThread(t){const n=await tc(`/threads/${t}`);return jt(n)}async threadInfo(t){const n=await _t(`/threads/${t}/info`);return hi(jt(n))}async listAgents(){const t=await _t("/agents"),n=jt(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await _t(`/agents/${t}`);return jt(n)}async getAgentSchema(t){const n=await _t(`/agents/${t}/schema`);return jt(n)}async getMessages(t){const n=await _t(`/threads/${t.threadId}/messages`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs,limit:t.limit,before_id:t.beforeId??void 0}});return jt(n)}async getState(t){const n=await _t(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return jt(n)}async getStateHistory(t){const n=await _t(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return jt(n)}async listCheckpoints(t){const n=await _t(`/threads/${t}/checkpoints`,{params:{thread_id:t}});return jt(n)}resumeStream(t){}async resume(t){const n=await fi("/runs/resume",{thread_id:t.threadId,value:t.value});return jt(n)}}const Cn=new rc,oc=S.createContext(null);function Dg({children:e,apiConfig:t}){const n=Cn;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 c.jsx(oc.Provider,{value:r,children:e})}function pi(){const e=S.useContext(oc);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function Lg(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 Fg(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const u=await Lg(l);a.push({filename:l.name,data:u,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}function $g(e){return e.type!=="thread_info"&&e.type!=="token"}const zg={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,messagesStreamMeta:{}};function Bg(e,t){var n;switch(t.type){case"reset":{console.log("[MessageReducer] 🔄 RESET action received"),console.log("[MessageReducer] 📊 Before reset - messages count:",e.messages.length);const r={messages:mi(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null};return console.log("[MessageReducer] 📊 After reset - messages count:",r.messages.length),r}case"seed":{const r=mi(t.payload.messages),o={...e,messages:r,assemblingId: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),console.log("[MessageReducer] seed action (REPLACE mode):",{incomingCount:t.payload.messages.length,sanitizedCount:r.length,previousCount:e.messages.length,checkpointId:o.lastCheckpointId}),o}case"prepend":{const r=mi(t.payload.messages);if(!r.length)return console.log("[MessageReducer] No incoming messages after sanitize - skipping"),e;const o=new Set(e.messages.map(i=>i.id)),s=r.filter(i=>!o.has(i.id));return console.log("[MessageReducer] After dedup:",{uniqueCount:s.length,duplicates:r.length-s.length,finalTotal:s.length+e.messages.length}),s.length?{...e,messages:[...s,...e.messages]}:(console.log("[MessageReducer] All messages were duplicates - skipping"),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 ic(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>ic(o,s),e):e}case"interrupt_response":{const{interruptId:r}=t.payload,o=e.messages.map(s=>({...s,content:s.content.filter(i=>i.type!=="interrupt")}));return{...e,messages:o,pendingInterrupt:null}}default:return e}}function sc(e=[]){const[t,n]=S.useReducer(Bg,{...zg,messages:e}),r=S.useRef([]),o=S.useRef(null),s=S.useRef(null),i=S.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=S.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=S.useCallback(d=>{r.current.push(d),a()},[a]);S.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const u=S.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,...u}}function ic(e,t){var n,r,o,s;if(t.type==="message_start"&&t.role==="assistant"){const i=t.id,a=Wg(t.model);if(e.messages.some(d=>d.id===i)){const d=e.messagesStreamMeta??{},f={...d,[i]:d[i]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:i,messagesStreamMeta:f}}const u={id:i,role:"assistant",name:a||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:i,messages:[...e.messages,u]}}if(t.type==="message_delta"){const i=e.assemblingId??gi(e.messages);if(!i)return e;const a=e.messages,l=a.findIndex(C=>C.id===i&&C.role==="assistant");if(l===-1)return e;const u=a[l],d=e.messagesStreamMeta??{},f=d[i]??{lastSeq:null,lastText:dc(u.content)},h=t.seq??null;if(h!==null&&typeof h=="number"&&typeof f.lastSeq=="number"&&h<=f.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:h,lastSeq:f.lastSeq}),e;const{newParts:p,newMeta:y,changed:w}=Hg(u.content,t.delta,f,h);if(!w)return e;const x={...u,content:p},v=ac(a,l,x),b={...d,[i]:y};return{...e,messages:v,messagesStreamMeta:b}}if(t.type==="message_end"){const i=e.assemblingId??gi(e.messages);if(!i)return{...e,assemblingId:null};const a=e.messages,l=a.findIndex(u=>u.id===i&&u.role==="assistant");if(l>=0){const u=a[l];if(!((n=u.content)==null?void 0:n.some(f=>{var h;return(f==null?void 0:f.type)==="text"&&((h=f.text)==null?void 0:h.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:u.id,contentTypes:(r=u.content)==null?void 0:r.map(h=>h==null?void 0:h.type),contentPreview:(o=u.content)==null?void 0:o.map(h=>(h==null?void 0:h.type)==="text"?String(h.text).slice(0,100):h==null?void 0:h.type)});const f=[...a.slice(0,l),...a.slice(l+1)];return{...e,assemblingId:null,messages:f}}}return e}if(t.type==="tool_start"){const i=t.id??t.call_id,a=t.name??t.tool??"tool";if(!i)return e;const l=`tool-${i}`,u={type:"tool_call",id:i,name:a,args:t.args};if(e.messages.find(h=>h.id===l))return{...e,toolIndex:{...e.toolIndex,[i]:l}};const f={id:l,role:"tool",name:a,createdAt:new Date().toISOString(),content:[u]};return{...e,messages:[...e.messages,f],toolIndex:{...e.toolIndex,[i]:l}}}if(t.type==="tool_end"){const i=t.id??t.call_id;if(!i)return e;const a=e.toolIndex[i]??`tool-${i}`,l={type:"tool_end",toolCallId:i,output:t.output,error:t.error},u=e.messages.find(h=>h.id===a),d={id:a,role:"tool",name:t.name??((s=e.messages.find(h=>h.id===a))==null?void 0:s.name),content:[l],createdAt:new Date().toISOString()},f=u?cc(e.messages,a,[l]):[...e.messages,d];return{...e,messages:f,toolIndex:{...e.toolIndex,[i]:a}}}if(t.type==="checkpoint"){const i=t.checkpointNs??e.lastCheckpointNs??null,a=Ug(e.messages,t.checkpointId,i);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:i,messages:a}}if(t.type==="branch"){const i=t.checkpointId??e.lastCheckpointId,a=t.checkpointNs??e.lastCheckpointNs;return{...e,lastBranch:t,lastCheckpointId:i??null,lastCheckpointNs:a??null}}if(t.type==="error"){const i={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,i]}}if(t.type==="interrupt"){const i=e.assemblingId??gi(e.messages),a={type:"interrupt",value:t.value,id:t.id};if(i)return{...e,assemblingId:null,messages:cc(e.messages,i,[a]),pendingInterrupt:{id:t.id,value:t.value}};const l=`interrupt-${t.id}`;if(e.messages.findIndex(f=>f.id===l)!==-1)return{...e,assemblingId:null,messages:lc(e.messages,l,f=>({...f,content:uc(f.content??[],[a])})),pendingInterrupt:{id:t.id,value:t.value}};const d={id:l,role:"system",createdAt:new Date().toISOString(),content:[a]};return{...e,messages:[...e.messages,d],pendingInterrupt:{id:t.id,value:t.value}}}return e}function mi(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 ac(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function gi(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function lc(e,t,n){const r=e.findIndex(i=>i.id===t);if(r===-1)return e;const o=e[r],s=n(o);return s===o?e:[...e.slice(0,r),s,...e.slice(r+1)]}function cc(e,t,n){return lc(e,t,r=>({...r,content:uc(r.content,n)}))}function uc(e,t){const n=e.slice();for(const r of t)if(r.type==="text"){const o=n[n.length-1],s=r.text??"";if(!s)continue;if((o==null?void 0:o.type)==="text"){let i=function(p){return p.replace(/\s+/g," ").trim()};const a=o,l=a.text??"";if(console.debug("[MessageReducer] mergeParts",{incomingLength:s.length,previousLength:l.length,incomingSnippet:s.slice(0,100),previousSnippet:l.slice(-100)}),!l){a.text=s;continue}const u=i(s),d=i(l);if(u.startsWith(d)||s.startsWith(l)){console.debug("[MessageReducer] incoming startsWith previous (norm/raw) - replacing",{incomingLength:s.length,previousLength:l.length}),a.text=s;continue}if(u.includes(d)){console.debug("[MessageReducer] incoming includes previous (normalized) - replacing",{incomingLength:s.length,previousLength:l.length}),a.text=s;continue}if(d.includes(u)&&u.length<=3){console.debug("[MessageReducer] previous includes incoming (normalized) - skipping trivial incoming",{incomingLength:s.length,previousLength:l.length});continue}const h=hc(l,s);h?(console.debug("[MessageReducer] suffix computed",{suffixLength:h.length}),a.text=l+h):(console.debug("[MessageReducer] no overlap detected - appending incoming",{incomingLength:s.length}),a.text=l+s)}else n.push({type:"text",text:s})}else n.push(r);return n}function dc(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function Hg(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??dc(e);let l="",u=e.slice();if(s){const f=hc(a,s);if(f===""?l="":f===s?l=s:l=f,l){const h=u[u.length-1];if((h==null?void 0:h.type)==="text"){const p=h.text??"",y={...h,text:p+l};u=[...u.slice(0,u.length-1),y]}else u=[...u,{type:"text",text:l}];o.lastText=a+l}else o.lastText=a}i.length&&(u=[...u,...i]);const d=!!(l||i.length);return{newParts:u,newMeta:o,changed:d}}function fc(e){return e.replace(/\s+/g," ").trim()}function hc(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=fc(e),o=fc(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 Ug(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 ac(e,r,s)}return e}function Wg(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}function pc(e={}){const t=S.useMemo(()=>xn(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=S.useState(e.token??null),s=S.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=S.useState(!1),[u,d]=S.useState(null),[f,h]=S.useState(""),[p,y]=S.useState(null),[w,x]=S.useState(0),[v,b]=S.useState(!1),C=S.useRef(null),E=S.useRef(!0),k=S.useRef(0),T=S.useCallback(M=>{o(M)},[]),N=S.useCallback(()=>{var M;(M=C.current)==null||M.abort(),C.current=null,l(!1),b(!1),k.current=0,x(0)},[]),A=S.useCallback(()=>{h(""),y(null),d(null)},[]),j=S.useCallback((M,F,$)=>{C.current&&(C.current.abort(),C.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&h("");const q=new AbortController;return C.current=q,(async()=>{var H,B,U,D,L,X,R,G;const _=de=>{var ye;try{const Ce=JSON.parse(JSON.stringify(de));return(ye=Ce==null?void 0:Ce.payload)!=null&&ye.files_info&&Array.isArray(Ce.payload.files_info)&&(Ce.payload.files_info=Ce.payload.files_info.map(he=>({...he,data:he!=null&&he.data?`<base64 ${String(he.data).length} chars>`:he==null?void 0:he.data}))),Ce}catch{return de}};try{let de={};try{if(r)de={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const $e=window.__AUTH_TOKEN__,st=((H=window.localStorage)==null?void 0:H.getItem("authToken"))||null;let Xe=null;try{const ht=(B=window.localStorage)==null?void 0:B.getItem("chat-settings");ht&&(Xe=((U=JSON.parse(ht))==null?void 0:U.apiKey)||null)}catch{}const je=$e||st||Xe||null;je&&(de={Authorization:`Bearer ${je}`})}}catch{}console.debug("[use-chat] POST",t+n,_(M));const ye=await fetch(t+n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...de,...s.current},body:JSON.stringify(M),signal:q.signal,credentials:i});if(!ye.ok||!ye.body){const Oe=await ye.text().catch(()=>"");throw console.debug("[use-chat] non-OK response",ye.status,Oe==null?void 0:Oe.slice(0,500)),new Error(`stream ${ye.status}${Oe?": "+Oe:""}`)}b(!0);const Ce=ye.body.getReader(),he=new TextDecoder;let K="",z=[];k.current=0,x(0);let Y=0,J=null;const ge=()=>{if(z.length){const Oe=z.join("");z=[],E.current&&h($e=>$e+Oe)}J=null},oe=()=>{typeof window<"u"&&J==null&&(J=requestAnimationFrame(ge))};let te=Date.now();const Ye=setInterval(()=>{var Oe;if(Date.now()-te>6e4){const $e="Stream idle timeout";d($e),q.abort(),(Oe=$==null?void 0:$.onError)==null||Oe.call($,$e)}},5e3),We=1024*1024;try{const Oe=ye.headers.get("X-Thread-Id")||ye.headers.get("x-thread-id"),$e=ye.headers.get("X-Thread-Created")||ye.headers.get("x-thread-created"),st=Oe??null,Xe=String($e??"").toLowerCase()==="true";for((D=$==null?void 0:$.onOpen)==null||D.call($,{threadId:st,created:Xe});;){const{value:je,done:ht}=await Ce.read();if(ht)break;K+=he.decode(je,{stream:!0}),K.length>We&&(K="",console.warn("Stream buffer reset: exceeded 1MB"));let ne;for(;(ne=K.indexOf(`
36
36
 
37
37
  `))>=0;){const le=K.slice(0,ne);K=K.slice(ne+2);const pe=qg(le);if(!pe)continue;let be;try{be=JSON.parse(pe)}catch{console.debug("[use-chat] malformed SSE:",pe.slice(0,200));continue}const me=Vg(be)?be.data:be;te=Date.now();const Ie=me.seq;if(Ie!==void 0){if(Ie<=Y){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:Ie,lastProcessedSeq:Y,type:me.type});continue}Y>0&&Ie>Y+1&&((L=$==null?void 0:$.onGap)==null||L.call($,{from:Y,to:Ie})),Y=Ie,k.current=Ie,x(Ie)}if(console.debug("[use-chat] received event",{seq:me.seq,type:me.type,preview:(()=>{var Je;try{return me.type==="message_delta"?{deltaTypes:(Je=me.delta)==null?void 0:Je.map(ze=>ze.type),textLen:(me.delta||[]).filter(ze=>ze.type==="text").map(ze=>String(ze.text||"").length)}:me.content||me.delta?{hasContent:!0}:{}}catch(ze){return{err:String(ze)}}})()}),F==null||F(me),me.type==="token"&&e.autoAppendAssistant!==!1)z.push(me.content),oe();else if(me.type==="message_delta"){const Je=me.delta.filter(ze=>ze.type==="text").map(ze=>ze.text).join("");Je&&e.autoAppendAssistant!==!1&&(z.push(Je),oe())}else me.type==="heartbeat"?console.debug("[use-chat] heartbeat received"):(J!==null&&cancelAnimationFrame(J),ge(),me.type==="checkpoint"?y(me.checkpointId):me.type==="error"&&d(me.message))}}ge()}catch(Oe){if(Oe.name!=="AbortError"){const $e=Oe.message||String(Oe);d($e),(X=$==null?void 0:$.onError)==null||X.call($,$e)}}finally{try{await Ce.cancel()}catch{}finally{(R=Ce.releaseLock)==null||R.call(Ce)}J!==null&&typeof window<"u"&&window.cancelAnimationFrame(J),clearInterval(Ye),l(!1),b(!1),C.current=null,k.current=0,x(0)}}catch(de){if(de.name!=="AbortError"){const ye=de.message||String(de);d(ye),(G=$==null?void 0:$.onError)==null||G.call($,ye)}}finally{l(!1),b(!1),C.current=null,k.current=0,x(0)}})(),{close:()=>q.abort()}},[t,n,r,e.autoAppendAssistant]);return S.useEffect(()=>()=>{var M;E.current=!1,(M=C.current)==null||M.abort()},[]),{isStreaming:a,error:u,assistantText:f,lastCheckpointId:p,lastSeq:w,connected:v,stream:j,stop:N,clear:A,setToken:T}}function Vg(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function qg(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
- `)}function Kg({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onUnhandledEvent:r,onSequenceGap:o}){const s=S.useRef(null),i=S.useCallback(p=>{const y=p.seq??null;if(y!==null){const w=s.current;if(w!==null){if(y<=w)return;y>w+1&&(o==null||o({from:w,to:y}))}s.current=y}if(p.type==="thread_info"){console.log("[useChatStreamingService] 🎯 Received thread_info event:",p),t(p);return}if($g(p)){n(p);return}r==null||r(p)},[n,o,t,r]),{stream:a,stop:l,isStreaming:u,error:d,setToken:f}=pc({baseUrl:e,token:null}),h=S.useCallback((p,y)=>{s.current=null,a(p,i,{onOpen:y==null?void 0:y.onOpen,onError:w=>{var x;(x=y==null?void 0:y.onError)==null||x.call(y,w)},onGap:(y==null?void 0:y.onGap)??o})},[i,o,a]);return S.useMemo(()=>({startStream:h,stop:l,isStreaming:u,error:d,setAuthToken:f}),[h,l,u,d,f])}function xi(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 ct(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):null}function _o(e,t){let n=e;for(const r of t){if(!n||typeof n!="object")return;n=n[r]}return n}function vi(e,t){for(const n of t){const r=_o(e,n),o=ct(r);if(o!=null)return o}return null}function wi(e,t){if(!e&&!t)return!0;if(!e||!t||(e==null?void 0:e.id)!==(t==null?void 0:t.id))return!1;try{return JSON.stringify(e==null?void 0:e.value)===JSON.stringify(t==null?void 0:t.value)}catch{return(e==null?void 0:e.value)===(t==null?void 0:t.value)}}function Gg(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 mc(e){if(!e||typeof e!="object")return null;const t=e.tasks;if(!Array.isArray(t))return null;for(const n of t){if(!n||typeof n!="object")continue;const r=n.interrupts;if(!Array.isArray(r)||r.length===0)continue;const o=r[0];if(!o)continue;return{id:(typeof(o==null?void 0:o.id)=="string"?o.id:typeof n.id=="string"?n.id:null)??"interrupt-task",value:o==null?void 0:o.value}}return null}function Wn(e,t){var a,l;const n=[e==null?void 0:e.metadata,e==null?void 0:e.config,e==null?void 0:e.values,(a=e==null?void 0:e.values)==null?void 0:a.config,(l=e==null?void 0:e.values)==null?void 0:l.metadata,e==null?void 0:e.parentConfig,t];let r=(t==null?void 0:t.checkpointId)??null,o=(t==null?void 0:t.checkpointNs)??null;const s=[["checkpointId"],["checkpoint_id"],["checkpoint","checkpointId"],["checkpoint","checkpoint_id"],["checkpoint","id"],["configurable","checkpointId"],["configurable","checkpoint_id"],["configurable","checkpoint","id"],["config","configurable","checkpoint_id"],["config","checkpoint_id"]],i=[["checkpointNs"],["checkpoint_ns"],["checkpoint","checkpointNs"],["checkpoint","checkpoint_ns"],["checkpoint","namespace"],["configurable","checkpointNs"],["configurable","checkpoint_ns"],["configurable","checkpoint","namespace"],["config","configurable","checkpoint_ns"],["config","checkpoint_ns"]];for(const u of n)if(!(!u||typeof u!="object")){if(!r){const d=vi(u,s);d&&(r=d)}if(o===null){const d=vi(u,i);d!==null&&(o=d)}if(r&&o!==null)break}return{checkpointId:r??null,checkpointNs:o??null}}function jo(e){return`${e.checkpointNs??"default"}:${e.checkpointId}`}function yi(e){return e.checkpointId?jo({checkpointId:e.checkpointId,checkpointNs:e.checkpointNs}):`anon:${e.checkpointNs??"default"}`}function Hr(e){const t=Wn(e);if(t.checkpointId)return yi(t);const n=ct(e.createdAt)??vi(e.metadata,[["createdAt"],["created_at"]]);return n?`created:${n}`:`anon:${xi(JSON.stringify(e.values??{}))}`}function gc(e){if(!e)return null;if(typeof e=="string")return{checkpointId:e,checkpointNs:null};if(typeof e!="object")return null;const n=e.config,r=n==null?void 0:n.configurable,o=ct(r==null?void 0:r.checkpoint_id);if(!o)return null;const s=ct(r==null?void 0:r.checkpoint_ns);return{checkpointId:o,checkpointNs:s}}function kn(e){if(!e||!e.values||typeof e.values!="object")return[];const t=e.values.messages;return Array.isArray(t)?t.filter(n=>n&&typeof n=="object").map(n=>({...n,content:Array.isArray(n.content)?n.content.slice():[]})):[]}function xc(e){const t=new Map,n=[];return e.forEach(r=>{const o=Hr(r);t.has(o)||n.push(o),t.set(o,r)}),n.map(r=>t.get(r))}function Yg(e,t,n){return xc(n==="replace"?t:[...t,...e])}function bi(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(!Number.isNaN(t))return t}return null}function Xg(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Number.parseFloat(e);if(!Number.isNaN(t))return t}return null}function Jg(e){return e.length<=1?e:e.map((t,n)=>{const r=bi(t.createdAt)??bi(_o(t.metadata,["createdAt"]))??bi(_o(t.metadata,["created_at"])),o=Xg(_o(t.metadata,["step"]));return{snapshot:t,index:n,ts:r,step:o}}).sort((t,n)=>t.ts!==null&&n.ts!==null&&t.ts!==n.ts?t.ts-n.ts:t.step!==null&&n.step!==null&&t.step!==n.step?t.step-n.step:t.index-n.index).map(t=>t.snapshot)}function Zg(e,t){const n=new Set;e.forEach(s=>{n.add(Hr(s))});const r=[],o=new Set;for(const s of t){const i=jo(s);n.has(i)||o.has(i)||(r.push(s),o.add(i))}return e.forEach(s=>{(Array.isArray(s.next)?s.next:[]).forEach(a=>{const l=gc(a);if(!l)return;const u=jo(l);n.has(u)||o.has(u)||(r.push(l),o.add(u))})}),r}function Ro(e,t){if(!t.checkpointId)return null;const n=yi(t);return e.find(r=>Hr(r)===n)??null}function vc(e){return e.map(t=>{const n=Hr(t),r=xi(JSON.stringify(t.values??{}));return`${n}:${r}`}).join("|")}const Qg="cachedThreads",ex="v1",Si=300,wc=200;function tx(e){if(typeof window<"u"&&"requestIdleCallback"in window)try{window.requestIdleCallback(e,{timeout:1e3});return}catch{}typeof window<"u"&&window.setTimeout(e,Si)}function pr(){return typeof window<"u"&&typeof window.localStorage<"u"}function Ci(e){if(!pr())return null;try{return window.localStorage.getItem(e)}catch{return null}}function yc(e,t){if(pr())try{window.localStorage.setItem(e,t)}catch{}}function bc(e){if(pr())try{window.localStorage.removeItem(e)}catch{}}function nx(){const e=Ci(Qg);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 ki(e,t){return`cachedThreads:v1:${e}:${xi(t||"anon")}`}function rx(e){const t=Ci(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 Sc(e,t){try{yc(e,JSON.stringify(t))}catch{}}function Ti(e){const t=rx(e);if(t.length>0)return t;const n=nx();if(n.length>0)try{Sc(e,n.slice(0,wc))}catch{}return n}function Po(e){const t={},n=[];for(const r of e){if(!r||typeof r!="object")continue;const o=r,s=wn(o.threadId)??wn(o.thread_id)??wn(o.id);if(!s||t[s])continue;const i=wn(o.title)??wn(o.name)??`Thread ${s.slice(0,8)}`,a=wn(o.createdAt)??wn(o.created_at)??new Date().toISOString(),l=wn(o.updatedAt)??wn(o.updated_at)??a,u=o.messageCount??o.message_count??o.messages_count,d={threadId:s,title:i,createdAt:a,updatedAt:l,messageCount:Math.max(0,ox(u))};t[s]=d,n.push(s)}return{byId:t,order:n}}function Ii(e){return e.order.map(t=>e.byId[t]).filter(Boolean)}function wn(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):null}function ox(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Number.parseInt(e,10);if(Number.isFinite(t))return t}return 0}function sx(e){const{api:t,baseHost:n,onError:r,initialThreadId:o=null}=e,[s,i]=S.useState(()=>{var _;return ki(n,(_=t.getAuthToken)==null?void 0:_.call(t))}),[a,l]=S.useState(()=>{var H;const _=Ti(ki(n,(H=t.getAuthToken)==null?void 0:H.call(t)));return Po(_)}),u=S.useMemo(()=>Ii(a),[a]),[d,f]=S.useState(o),[h,p]=S.useState(!1),[y,w]=S.useState(null),x=S.useRef(u.length),v=S.useRef(!1),b=S.useRef(null),C=S.useRef(""),E=S.useRef(!1),k=S.useRef(null);S.useEffect(()=>{x.current=u.length},[u.length]);const T=S.useCallback(()=>{const _=Ti(s);l(Po(_))},[s]),N=S.useCallback((_,H)=>{if(!pr())return;b.current!==null&&(window.clearTimeout(b.current),b.current=null);const B=_.map(D=>`${D.threadId}:${D.updatedAt??""}:${D.messageCount??""}`).join("|");if(_.length===0){try{bc(s)}catch{}C.current="";return}if(B===C.current)return;const U=()=>{try{const D=_.slice(0,wc);Sc(s,D),C.current=B}catch{}finally{b.current=null}};if(H!=null&&H.immediate){U();return}b.current=window.setTimeout(()=>{tx(U)},Si)},[s]),A=S.useCallback(()=>{N(u,{immediate:!0})},[N,u]),j=S.useCallback(async()=>{const _=x.current>0;_||p(!0);try{const H=await t.listThreads(),B=()=>{l(U=>{const D=R=>R.map(G=>`${G.threadId}:${G.updatedAt??""}:${G.messageCount??""}`).join("|"),L=Ii(U);return D(L)===D(H)||H.length===0&&L.length>0&&!v.current?U:Po(H)})};_?S.startTransition(B):B(),w(null),v.current||(v.current=!0)}catch(H){r==null||r(String(H)),console.error("[useThreadList] Failed to refresh threads:",H),w(String(H))}finally{_||p(!1)}},[t,r]),M=S.useCallback(async _=>{var U;const H=`thread-${((U=crypto.randomUUID)==null?void 0:U.call(crypto))??Date.now().toString(36)}`,B={threadId:H,title:_||"New Chat",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:0};l(D=>({byId:{...D.byId,[H]:B},order:[H,...D.order]})),f(H);try{const D=await t.createThread(_);return l(L=>{const X={...L.byId};delete X[H],X[D.threadId]=D;const R=L.order.map(G=>G===H?D.threadId:G);return{byId:X,order:R}}),f(D.threadId),w(null),D}catch(D){throw l(L=>{const X={...L.byId};return delete X[H],{byId:X,order:L.order.filter(R=>R!==H)}}),w(String(D)),r==null||r(String(D)),D}},[t,r]),F=S.useCallback(async _=>{var H;try{await t.deleteThread(_);let B=null;l(D=>{if(!D.byId[_])return D;const L={...D.byId};delete L[_];const X=D.order.filter(G=>G!==_),R={byId:L,order:X};return B=Ii(R),R}),B&&N(B,{immediate:!0});const U=d===_;U&&f(null),(H=e.onThreadRemoved)==null||H.call(e,_,{wasCurrent:U}),await j(),w(null)}catch(B){throw w(String(B)),B}},[t,d,e,j,N]),$=S.useCallback(async(_,H)=>{try{await t.updateThread(_,H),l(B=>{const U=B.byId[_];return U?{byId:{...B.byId,[_]:{...U,title:H}},order:B.order}:B}),w(null)}catch(B){throw await j(),w(String(B)),B}},[t,j]);S.useEffect(()=>{if(pr())return N(u),()=>{b.current!==null&&(window.clearTimeout(b.current),b.current=null)}},[u,N]),S.useEffect(()=>{var U,D,L;const _=X=>{const R=ki(n,X??null);k.current!==R&&(k.current=R,E.current=!1),i(R);const G=Ti(R);l(Po(G)),E.current||(E.current=!0,j().catch(()=>{}))},H=((U=t.getAuthToken)==null?void 0:U.call(t))??null;(D=e.onAuthTokenChange)==null||D.call(e,H),_(H);const B=(L=t.onTokenChange)==null?void 0:L.call(t,X=>{var R,G;(R=e.onAuthTokenChange)==null||R.call(e,X),(G=e.clearAllMessageCaches)==null||G.call(e),_(X)});return()=>B==null?void 0:B()},[t,n,j,e.clearAllMessageCaches,e.onAuthTokenChange]);const q=S.useCallback(_=>{l(H=>{const B=H.byId[_.threadId];return B?B.title===_.title&&B.updatedAt===_.updatedAt&&B.messageCount===_.messageCount?H:{byId:{...H.byId,[_.threadId]:_},order:H.order}:{byId:{...H.byId,[_.threadId]:_},order:[_.threadId,...H.order]}})},[]);return{threads:u,currentThreadId:d,setCurrentThreadId:f,isLoadingThreads:h,threadsError:y,refreshThreads:j,createThread:M,deleteThread:F,renameThread:$,persistThreadsCache:A,hydrateThreadsFromCache:T,upsertThreadSummary:q}}const Cc=S.createContext(null),kc=S.createContext(null),Tc=S.createContext(null),ix=S.createContext(!1);function ax({children:e,initialThreadId:t=null,autoLoadInitial:n=!0,disableAutoRestore:r=!1,enableFileAgentRouting:o=!1,fileAgentId:s="invoice_reader",onError:i,onThreadChange:a}){const{api:l,baseUrl:u}=pi(),d=S.useMemo(()=>xn(u),[u]),f=S.useMemo(()=>{try{return new URL(u).host}catch{return"unknown"}},[u]),h=S.useMemo(()=>`threadPayload:${ex}:${f}:`,[f]),p=S.useCallback(g=>`${h}${g}`,[h]),y=S.useCallback(g=>{if(!g||typeof g!="object")return null;const I=g;if(typeof I.threadId!="string")return null;const P=Array.isArray(I.checkpoints)?I.checkpoints.filter(Q=>Q&&typeof Q=="object"):[],W=Array.isArray(I.pendingCheckpoints)?I.pendingCheckpoints.map(Q=>gc(Q)).filter(Q=>!!Q):[],ee=I.activeCheckpointId===null||I.activeCheckpointId===void 0?null:ct(I.activeCheckpointId)??null,se=I.activeCheckpointNs===null||I.activeCheckpointNs===void 0?null:ct(I.activeCheckpointNs)??null;return{threadId:I.threadId,checkpoints:P,pendingCheckpoints:W,activeCheckpointId:ee,activeCheckpointNs:se}},[]),w=S.useCallback(g=>{const I=Ci(p(g));if(!I)return null;try{const P=JSON.parse(I);return y(P)}catch{return null}},[p,y]),x=S.useCallback(g=>{const I={threadId:g.threadId,checkpoints:Array.isArray(g.checkpoints)?g.checkpoints:[],pendingCheckpoints:Array.isArray(g.pendingCheckpoints)?g.pendingCheckpoints.map(P=>({checkpointId:P.checkpointId,checkpointNs:P.checkpointNs??null})):[],activeCheckpointId:g.activeCheckpointId??null,activeCheckpointNs:g.activeCheckpointNs??null};try{yc(p(g.threadId),JSON.stringify(I))}catch{}},[p]),v=S.useCallback(g=>{bc(p(g))},[p]),b=S.useCallback(()=>{if(pr())try{const g=h;for(let I=0;I<window.localStorage.length;I++){const P=window.localStorage.key(I);P&&P.startsWith(g)&&window.localStorage.removeItem(P)}}catch{}},[h]),C=S.useRef(()=>{}),{threads:E,currentThreadId:k,setCurrentThreadId:T,isLoadingThreads:N,threadsError:A,refreshThreads:j,createThread:M,deleteThread:F,renameThread:$,persistThreadsCache:q,hydrateThreadsFromCache:_,upsertThreadSummary:H}=sx({api:l,baseHost:f,onError:i,initialThreadId:t,clearAllMessageCaches:b,onAuthTokenChange:g=>C.current(g??null)}),[B,U]=S.useState(!1),[D,L]=S.useState(null),[X,R]=S.useState(null),[G,de]=S.useState(!1),[ye,Ce]=S.useState(!1),[he,K]=S.useState([]),[z,Y]=S.useState([]),J=S.useRef([]),[ge,oe]=S.useState(null),{state:te,dispatch:Ye,seed:We,prepend:Oe,pushUser:$e,onEvent:st,reset:Xe}=sc(),je=S.useRef(k);S.useEffect(()=>{je.current=k},[k]);const ht=S.useRef(!1),ne=S.useRef([]),le=S.useRef(null),pe=S.useRef(null),be=S.useRef(new Map),me=S.useRef(k),Ie=S.useRef({threadId:null,checkpointId:null,checkpointNs:null}),Je=S.useCallback((g,I)=>new Promise((P,W)=>{const ee=async()=>{ht.current=!0;try{await g(),P()}catch(se){W(se)}finally{ht.current=!1;const se=ne.current.shift();se&&se().catch(()=>{})}};ht.current?ne.current.push(ee):ee().catch(se=>{W(se)})}),[]);S.useEffect(()=>{var ee;const g=je.current;if(!g){X!==null&&R(null),Ie.current={threadId:null,checkpointId:null,checkpointNs:null};return}const I=te.pendingInterrupt??Gg(te.messages);if(I){wi(X,I)||R(I),Ie.current={threadId:g,checkpointId:te.lastCheckpointId??null,checkpointNs:te.lastCheckpointNs??null};return}const P={threadId:g,checkpointId:te.lastCheckpointId??null,checkpointNs:te.lastCheckpointNs??null};if(ge){const se=(ee=ge.values)==null?void 0:ee.state,Q=mc(se);if(Q!==null){wi(X,Q)||R(Q),Ie.current=P;return}if(Ie.current.threadId===P.threadId&&Ie.current.checkpointId===P.checkpointId&&Ie.current.checkpointNs===P.checkpointNs&&X===null){Ie.current=P;return}}if(!(l!=null&&l.getState)){X!==null&&R(null),Ie.current=P;return}let W=!1;return Ie.current=P,l.getState({threadId:g,checkpointId:P.checkpointId??void 0,checkpointNs:P.checkpointNs??void 0}).then(se=>{if(W)return;const Q=mc(se==null?void 0:se.state);wi(X,Q??null)||R(Q??null)}).catch(se=>{W||(console.warn("[ChatSessionProvider] Failed to inspect thread state for interrupts:",se),X!==null&&R(null))}),()=>{W=!0}},[ge,l,X,te.lastCheckpointId,te.lastCheckpointNs,te.messages,te.pendingInterrupt]);const ze=S.useRef(!1),tt=S.useRef(null),ut=S.useCallback((g,I,P,W)=>{const ee=Array.isArray(g==null?void 0:g.checkpoints)?g.checkpoints.filter(Or=>Or&&typeof Or=="object"):[],se=Jg(ee),Q=P??(g==null?void 0:g.threadId)??je.current;if(!Q)return;const xe=Q===je.current,Se=I==="replace"?null:be.current.get(Q)??null,Ee=I==="replace"?[]:xe?he:(Se==null?void 0:Se.checkpoints)??[],qe=I==="replace"?[]:xe?J.current:(Se==null?void 0:Se.pendingCheckpoints)??[],et={checkpointId:(g==null?void 0:g.checkpointId)??null,checkpointNs:(g==null?void 0:g.checkpointNs)??null},nt=se[se.length-1]??null,at=Wn(nt,et),Ge={checkpointId:(W==null?void 0:W.checkpointId)??(I==="replace"?at.checkpointId:(xe?te.lastCheckpointId??null:(Se==null?void 0:Se.activeCheckpointId)??null)??at.checkpointId),checkpointNs:(W==null?void 0:W.checkpointNs)??(I==="replace"?at.checkpointNs:(xe?te.lastCheckpointNs??null:(Se==null?void 0:Se.activeCheckpointNs)??null)??at.checkpointNs)},xt=Yg(Ee,se,I),At=Zg(xt,qe),$n={threadId:Q,checkpoints:xt,pendingCheckpoints:At,activeCheckpointId:Ge.checkpointId,activeCheckpointNs:Ge.checkpointNs};if(be.current.set(Q,$n),me.current=Q,!xe)return;J.current=At,Y(At),de(At.length>0),K(xt);const Ft=Ro(xt,Ge)??xt[xt.length-1]??null;if(oe(Ft),I==="replace"){const Or=kn(Ft??nt);We(Or,{checkpointId:Ge.checkpointId,checkpointNs:Ge.checkpointNs})}else if(I==="prepend"){const im=kn(nt??Ft);im.length&&Oe(im)}},[he,te.lastCheckpointId,te.lastCheckpointNs,J,Oe,We,K,de,Y,oe]),Nt=S.useCallback(g=>{if(g.threadId!=null&&g.threadId!==je.current)return;const I=Array.isArray(g.checkpoints)?g.checkpoints:[];K(I);const P=Array.isArray(g.pendingCheckpoints)?g.pendingCheckpoints:[];J.current=P,Y(P),de(P.length>0);const W={checkpointId:g.activeCheckpointId??null,checkpointNs:g.activeCheckpointNs??null},ee=Ro(I,W)??I[I.length-1]??null;oe(ee);const se=kn(ee);We(se,{checkpointId:W.checkpointId,checkpointNs:W.checkpointNs}),me.current=g.threadId},[We,K,Y,de,oe,J]);S.useEffect(()=>{if(!je.current||!he.length)return;const g={checkpointId:te.lastCheckpointId??null,checkpointNs:te.lastCheckpointNs??null},I=g.checkpointId?yi(g):null;let P=!1;const W=he.map((ee,se)=>{var et;const Q=Hr(ee);if(!(I?Q===I:se===he.length-1))return ee;const Se=Array.isArray((et=ee.values)==null?void 0:et.messages)?ee.values.messages:[];return Se.length===te.messages.length&&Se.every((nt,at)=>{var Ge;return(nt==null?void 0:nt.id)===((Ge=te.messages[at])==null?void 0:Ge.id)})?ee:(P=!0,{...ee,values:{...ee.values??{},messages:te.messages.slice()}})});P&&K(W)},[he,te.lastCheckpointId,te.lastCheckpointNs,te.messages]);const Zt=S.useCallback(g=>{g&&(be.current.delete(g),v(g),me.current===g&&(me.current=null))},[v]),hn=S.useCallback(()=>{const g=je.current;g&&Zt(g),Xe([]),de(!1),Ce(!1),K([]),Y([]),J.current=[],oe(null)},[Zt,Xe]),ir=S.useCallback(({from:g,to:I})=>{const P=je.current;P&&console.warn(`[ChatSessionProvider] Stream sequence gap detected (${g} -> ${I}) for thread ${P}`)},[]),mo=S.useCallback(g=>{const I=g,P=ct(g.threadId)??ct(I.thread_id)??ct(I.id);if(!P){console.warn("[ChatSessionProvider] thread_info event missing threadId",g);return}console.log("[ChatSessionProvider] 📥 Handling thread_info event:",{threadId:P,title:ct(g.title)??ct(I.title),created:ct(g.createdAt)??ct(I.created_at),currentThreads:E.length});const W=ct(g.title)??ct(I.title)??`Thread ${P.slice(0,8)}`,ee=ct(g.createdAt)??ct(I.created_at)??new Date().toISOString(),se=ct(g.updatedAt)??ct(I.updated_at)??ee,Q=g.messageCount??I.message_count??I.messages_count;let xe=0;if(typeof Q=="number"&&Number.isFinite(Q))xe=Q;else if(Q!=null){const Ee=Number.parseInt(String(Q),10);Number.isFinite(Ee)&&(xe=Ee)}const Se={threadId:P,title:W,createdAt:ee,updatedAt:se,messageCount:xe};je.current!==P&&(!je.current&&te.messages.length<=1&&(pe.current=P),T(P)),S.startTransition(()=>{H(Se)})},[te.messages.length,E.length,H]),{startStream:Ar,stop:Ln,isStreaming:pn,error:Lt,setAuthToken:mn}=Kg({baseUrl:d,onThreadInfo:mo,onMessageEvent:st,onUnhandledEvent:g=>{console.warn(`[ChatSessionProvider] Unhandled stream event: ${g.type}`,g)},onSequenceGap:ir});S.useEffect(()=>{ze.current=pn},[pn]),S.useEffect(()=>{C.current=g=>mn(g??null)},[mn]),S.useEffect(()=>{var g;C.current(((g=l.getAuthToken)==null?void 0:g.call(l))??null)},[l]);const Fn=S.useCallback(async g=>{const I=await M(g);return(I==null?void 0:I.threadId)??null},[M]),ar=S.useCallback(async g=>{const I=je.current===g;await F(g),Zt(g),I&&(pe.current=g,T(null),je.current=null,me.current=null,hn())},[F,hn,Zt,T]),_r=S.useCallback((g,I)=>$(g,I),[$]),Qt=S.useCallback(async(g,I,P,W=!1)=>{await Je(async()=>{if(pe.current===g&&!W){pe.current=null;return}if(le.current===g&&!W)return;T(Se=>Se===g?Se:g),je.current=g;const ee=!W&&!I&&!P;let se=!1;if(ee){const Se=be.current.get(g);if(Se)Nt(Se),se=!0;else{const Ee=w(g);Ee&&(be.current.set(g,Ee),Nt(Ee),se=!0)}}const Q=W||!se||!!I||!!P,xe=async Se=>{Se&&U(!0),le.current=g;try{const Ee=await l.getStateHistory({threadId:g,checkpointId:I,checkpointNs:P});ut(Ee,"replace",g),L(null)}catch(Ee){throw(!se||W||Se)&&(i==null||i(String(Ee))),L(String(Ee)),Ee}finally{le.current=null,Se&&U(!1)}};Q?await xe(!0):ee&&se&&xe(!1).catch(Se=>{console.warn("[ChatSessionProvider] Background refresh failed:",Se)})},`loadThread-${g}`)},[l,Nt,ut,Je,i]),jr=S.useCallback(async()=>{await Je(async()=>{const g=je.current;g&&Zt(g),pe.current=null,T(null),je.current=null,me.current=null,hn();try{localStorage.removeItem("lastThreadId")}catch(I){console.warn("[ChatSessionProvider] Failed to clear lastThreadId:",I)}},"clearCurrentThread")},[hn,Zt,Je]),lr=S.useCallback(async(g,I)=>{if(!je.current)throw new Error("No active thread");const W=Ro(he,{checkpointId:g,checkpointNs:I??null});if(!W)throw new Error(`Checkpoint ${g} not found in loaded history`);const ee={checkpointId:g,checkpointNs:I??null},se={threadId:je.current,checkpoints:he,pendingCheckpoints:J.current,activeCheckpointId:ee.checkpointId,activeCheckpointNs:ee.checkpointNs};be.current.set(je.current,se),me.current=je.current,oe(W);const Q=kn(W);We(Q,{checkpointId:ee.checkpointId,checkpointNs:ee.checkpointNs})},[he,Ro,kn,We,oe]),cr=S.useCallback(async()=>{var I,P;if(!je.current)throw new Error("No active thread");const g=he[he.length-1];if(g){const W=g.config,ee={checkpointId:((I=W==null?void 0:W.configurable)==null?void 0:I.checkpoint_id)??null,checkpointNs:((P=W==null?void 0:W.configurable)==null?void 0:P.checkpoint_ns)??null},se={threadId:je.current,checkpoints:he,pendingCheckpoints:J.current,activeCheckpointId:ee.checkpointId,activeCheckpointNs:ee.checkpointNs};be.current.set(je.current,se),me.current=je.current,oe(g);const Q=kn(g);We(Q,{checkpointId:ee.checkpointId,checkpointNs:ee.checkpointNs})}else await Qt(je.current,void 0,void 0,!0)},[he,kn,We,oe,Qt]),Rr=S.useCallback(async()=>{if(!je.current)throw new Error("No active thread");if(ye)return;const g=J.current;if(!g.length){de(!1);return}const[I,...P]=g;J.current=P,Y(P),Ce(!0);try{const W=je.current,ee=await l.getStateHistory({threadId:W,checkpointId:I.checkpointId,checkpointNs:I.checkpointNs??void 0});ut(ee,"prepend",W??void 0,{checkpointId:te.lastCheckpointId??null,checkpointNs:te.lastCheckpointNs??null}),L(null)}catch(W){throw J.current=[I,...J.current],Y(J.current),de(!0),L(String(W)),W}finally{Ce(!1)}},[l,ut,ye,te.lastCheckpointId,te.lastCheckpointNs,J,Y]),Pr=S.useCallback(g=>{var qe,et,nt,at,Ge,xt,At;const I=((qe=g==null?void 0:g.config)==null?void 0:qe.threadId)??((et=g==null?void 0:g.config)==null?void 0:et.thread_id)??(g==null?void 0:g.threadId)??(g==null?void 0:g.thread_id),P=ct(I);if(!P)return;const W=((nt=g==null?void 0:g.config)==null?void 0:nt.checkpointId)??((at=g==null?void 0:g.config)==null?void 0:at.checkpoint_id)??(g==null?void 0:g.checkpointId)??(g==null?void 0:g.checkpoint_id)??((Ge=g==null?void 0:g.checkpoint)==null?void 0:Ge.id),ee=ct(W)??void 0,se=((xt=g==null?void 0:g.config)==null?void 0:xt.checkpointNs)??((At=g==null?void 0:g.config)==null?void 0:At.checkpoint_ns)??(g==null?void 0:g.checkpointNs)??(g==null?void 0:g.checkpoint_ns),Q=ct(se)??void 0,xe=kn(g),Se={createdAt:new Date().toISOString(),config:{configurable:{checkpoint_id:ee,checkpoint_ns:Q}},metadata:{},values:{messages:xe},next:[],parentConfig:null,tasks:g.tasks??[]};ut({threadId:P,checkpointId:ee,checkpointNs:Q,version:"chat-history@1",checkpoints:[Se]},"replace",P,{checkpointId:ee??null,checkpointNs:Q??null})},[ut]),ie=S.useCallback(async(g,I)=>{var $n;const P=je.current,W=(g==null?void 0:g.text)??"",ee=(g==null?void 0:g.attachments)??[],se=ee.length?ee:(I==null?void 0:I.attachments)??[],Q={...(I==null?void 0:I.payloadExtras)??{},...(g==null?void 0:g.payload)??{}};if(!P&&!Object.keys(Q).length&&se.length===0&&!W.trim()){console.warn("[ChatSessionProvider] Nothing to submit - skipping");return}!P&&!Q.messages&&console.warn("[ChatSessionProvider] No thread ID - message will create new thread");const{contentParts:xe,filesInfo:Se}=await Fg(l,se),Ee=[...xe];W&&W.trim()&&Ee.push({type:"text",text:W.trim()});const qe=!!P,et=qe?(I==null?void 0:I.checkpointId)??te.lastCheckpointId??void 0:void 0,nt=qe?(I==null?void 0:I.checkpointNs)??te.lastCheckpointNs??void 0:void 0,at={id:(($n=crypto.randomUUID)==null?void 0:$n.call(crypto))||`user-${Date.now()}`,role:"user",content:Ee,createdAt:new Date().toISOString(),...et!=null?{checkpointId:et}:{},...nt!=null?{checkpointNs:nt}:{}};Ee.length>0&&$e(at);const Ge={...at,content:Ee},xt=se.length>0,At={...P?{threadId:P}:{},payload:{messages:Ee.length>0?[Ge]:[],files_info:Se,...o&&xt&&s?{active_agent:s}:{},...Q},...et!=null?{checkpointId:et}:{},...nt!=null?{checkpointNs:nt}:{},nodeFilter:I==null?void 0:I.nodeFilter,config:I==null?void 0:I.config};Ar(At,{onError:Ft=>{console.warn("[ChatSessionProvider] Stream error:",Ft)},onOpen:({threadId:Ft})=>{!je.current&&Ft&&(te.messages.length<=1&&(pe.current=Ft),T(Ft))},onGap:ir})},[l,o,s,ir,te.lastCheckpointId,te.lastCheckpointNs,te.messages.length,$e,Ar]),ve=S.useCallback(async(g,I,P)=>{var ee,se;const W=je.current;if(!W)throw new Error("No active thread to handle interrupt");try{const Q=I?P??!0:!1;try{Ye({type:"interrupt_response",payload:{interruptId:g}})}catch(at){console.warn("[ChatSessionProvider] optimistic interrupt_response dispatch failed:",at)}const xe=`${d}/runs/resume`,Se=(ee=l.getAuthToken)==null?void 0:ee.call(l),Ee=await fetch(xe,{method:"POST",headers:{"Content-Type":"application/json",...Se?{Authorization:`Bearer ${Se}`}:{}},body:JSON.stringify({thread_id:W,value:Q})});if(!Ee.ok)throw new Error(`Resume failed with status ${Ee.status}`);const qe=(se=Ee.body)==null?void 0:se.getReader();if(!qe)throw new Error("No response body for resume stream");const et=new TextDecoder;let nt="";for(;;){const{done:at,value:Ge}=await qe.read();if(at)break;nt+=et.decode(Ge,{stream:!0});const xt=nt.split(`
38
+ `)}function Kg({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onUnhandledEvent:r,onSequenceGap:o}){const s=S.useRef(null),i=S.useCallback(p=>{const y=p.seq??null;if(y!==null){const w=s.current;if(w!==null){if(y<=w)return;y>w+1&&(o==null||o({from:w,to:y}))}s.current=y}if(p.type==="thread_info"){console.log("[useChatStreamingService] 🎯 Received thread_info event:",p),t(p);return}if($g(p)){n(p);return}r==null||r(p)},[n,o,t,r]),{stream:a,stop:l,isStreaming:u,error:d,setToken:f}=pc({baseUrl:e,token:null}),h=S.useCallback((p,y)=>{s.current=null,a(p,i,{onOpen:y==null?void 0:y.onOpen,onError:w=>{var x;(x=y==null?void 0:y.onError)==null||x.call(y,w)},onGap:(y==null?void 0:y.onGap)??o})},[i,o,a]);return S.useMemo(()=>({startStream:h,stop:l,isStreaming:u,error:d,setAuthToken:f}),[h,l,u,d,f])}function xi(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 ct(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):null}function _o(e,t){let n=e;for(const r of t){if(!n||typeof n!="object")return;n=n[r]}return n}function vi(e,t){for(const n of t){const r=_o(e,n),o=ct(r);if(o!=null)return o}return null}function wi(e,t){if(!e&&!t)return!0;if(!e||!t||(e==null?void 0:e.id)!==(t==null?void 0:t.id))return!1;try{return JSON.stringify(e==null?void 0:e.value)===JSON.stringify(t==null?void 0:t.value)}catch{return(e==null?void 0:e.value)===(t==null?void 0:t.value)}}function Gg(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 mc(e){if(!e||typeof e!="object")return null;const t=e.tasks;if(!Array.isArray(t))return null;for(const n of t){if(!n||typeof n!="object")continue;const r=n.interrupts;if(!Array.isArray(r)||r.length===0)continue;const o=r[0];if(!o)continue;return{id:(typeof(o==null?void 0:o.id)=="string"?o.id:typeof n.id=="string"?n.id:null)??"interrupt-task",value:o==null?void 0:o.value}}return null}function Wn(e,t){var a,l;const n=[e==null?void 0:e.metadata,e==null?void 0:e.config,e==null?void 0:e.values,(a=e==null?void 0:e.values)==null?void 0:a.config,(l=e==null?void 0:e.values)==null?void 0:l.metadata,e==null?void 0:e.parentConfig,t];let r=(t==null?void 0:t.checkpointId)??null,o=(t==null?void 0:t.checkpointNs)??null;const s=[["checkpointId"],["checkpoint_id"],["checkpoint","checkpointId"],["checkpoint","checkpoint_id"],["checkpoint","id"],["configurable","checkpointId"],["configurable","checkpoint_id"],["configurable","checkpoint","id"],["config","configurable","checkpoint_id"],["config","checkpoint_id"]],i=[["checkpointNs"],["checkpoint_ns"],["checkpoint","checkpointNs"],["checkpoint","checkpoint_ns"],["checkpoint","namespace"],["configurable","checkpointNs"],["configurable","checkpoint_ns"],["configurable","checkpoint","namespace"],["config","configurable","checkpoint_ns"],["config","checkpoint_ns"]];for(const u of n)if(!(!u||typeof u!="object")){if(!r){const d=vi(u,s);d&&(r=d)}if(o===null){const d=vi(u,i);d!==null&&(o=d)}if(r&&o!==null)break}return{checkpointId:r??null,checkpointNs:o??null}}function jo(e){return`${e.checkpointNs??"default"}:${e.checkpointId}`}function yi(e){return e.checkpointId?jo({checkpointId:e.checkpointId,checkpointNs:e.checkpointNs}):`anon:${e.checkpointNs??"default"}`}function Hr(e){const t=Wn(e);if(t.checkpointId)return yi(t);const n=ct(e.createdAt)??vi(e.metadata,[["createdAt"],["created_at"]]);return n?`created:${n}`:`anon:${xi(JSON.stringify(e.values??{}))}`}function gc(e){if(!e)return null;if(typeof e=="string")return{checkpointId:e,checkpointNs:null};if(typeof e!="object")return null;const n=e.config,r=n==null?void 0:n.configurable,o=ct(r==null?void 0:r.checkpoint_id);if(!o)return null;const s=ct(r==null?void 0:r.checkpoint_ns);return{checkpointId:o,checkpointNs:s}}function kn(e){if(!e||!e.values||typeof e.values!="object")return[];const t=e.values.messages;return Array.isArray(t)?t.filter(n=>n&&typeof n=="object").map(n=>({...n,content:Array.isArray(n.content)?n.content.slice():[]})):[]}function xc(e){const t=new Map,n=[];return e.forEach(r=>{const o=Hr(r);t.has(o)||n.push(o),t.set(o,r)}),n.map(r=>t.get(r))}function Yg(e,t,n){return xc(n==="replace"?t:[...t,...e])}function bi(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(!Number.isNaN(t))return t}return null}function Xg(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Number.parseFloat(e);if(!Number.isNaN(t))return t}return null}function Jg(e){return e.length<=1?e:e.map((t,n)=>{const r=bi(t.createdAt)??bi(_o(t.metadata,["createdAt"]))??bi(_o(t.metadata,["created_at"])),o=Xg(_o(t.metadata,["step"]));return{snapshot:t,index:n,ts:r,step:o}}).sort((t,n)=>t.ts!==null&&n.ts!==null&&t.ts!==n.ts?t.ts-n.ts:t.step!==null&&n.step!==null&&t.step!==n.step?t.step-n.step:t.index-n.index).map(t=>t.snapshot)}function Zg(e,t){const n=new Set;e.forEach(s=>{n.add(Hr(s))});const r=[],o=new Set;for(const s of t){const i=jo(s);n.has(i)||o.has(i)||(r.push(s),o.add(i))}return e.forEach(s=>{(Array.isArray(s.next)?s.next:[]).forEach(a=>{const l=gc(a);if(!l)return;const u=jo(l);n.has(u)||o.has(u)||(r.push(l),o.add(u))})}),r}function Ro(e,t){if(!t.checkpointId)return null;const n=yi(t);return e.find(r=>Hr(r)===n)??null}function vc(e){return e.map(t=>{const n=Hr(t),r=xi(JSON.stringify(t.values??{}));return`${n}:${r}`}).join("|")}const Qg="cachedThreads",ex="v1",Si=300,wc=200;function tx(e){if(typeof window<"u"&&"requestIdleCallback"in window)try{window.requestIdleCallback(e,{timeout:1e3});return}catch{}typeof window<"u"&&window.setTimeout(e,Si)}function pr(){return typeof window<"u"&&typeof window.localStorage<"u"}function Ci(e){if(!pr())return null;try{return window.localStorage.getItem(e)}catch{return null}}function yc(e,t){if(pr())try{window.localStorage.setItem(e,t)}catch{}}function bc(e){if(pr())try{window.localStorage.removeItem(e)}catch{}}function nx(){const e=Ci(Qg);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 ki(e,t){return`cachedThreads:v1:${e}:${xi(t||"anon")}`}function rx(e){const t=Ci(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 Sc(e,t){try{yc(e,JSON.stringify(t))}catch{}}function Ti(e){const t=rx(e);if(t.length>0)return t;const n=nx();if(n.length>0)try{Sc(e,n.slice(0,wc))}catch{}return n}function Po(e){const t={},n=[];for(const r of e){if(!r||typeof r!="object")continue;const o=r,s=wn(o.threadId)??wn(o.thread_id)??wn(o.id);if(!s||t[s])continue;const i=wn(o.title)??wn(o.name)??`Thread ${s.slice(0,8)}`,a=wn(o.createdAt)??wn(o.created_at)??new Date().toISOString(),l=wn(o.updatedAt)??wn(o.updated_at)??a,u=o.messageCount??o.message_count??o.messages_count,d={threadId:s,title:i,createdAt:a,updatedAt:l,messageCount:Math.max(0,ox(u))};t[s]=d,n.push(s)}return{byId:t,order:n}}function Ii(e){return e.order.map(t=>e.byId[t]).filter(Boolean)}function wn(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):null}function ox(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Number.parseInt(e,10);if(Number.isFinite(t))return t}return 0}function sx(e){const{api:t,baseHost:n,onError:r,initialThreadId:o=null}=e,[s,i]=S.useState(()=>{var _;return ki(n,(_=t.getAuthToken)==null?void 0:_.call(t))}),[a,l]=S.useState(()=>{var H;const _=Ti(ki(n,(H=t.getAuthToken)==null?void 0:H.call(t)));return Po(_)}),u=S.useMemo(()=>Ii(a),[a]),[d,f]=S.useState(o),[h,p]=S.useState(!1),[y,w]=S.useState(null),x=S.useRef(u.length),v=S.useRef(!1),b=S.useRef(null),C=S.useRef(""),E=S.useRef(!1),k=S.useRef(null);S.useEffect(()=>{x.current=u.length},[u.length]);const T=S.useCallback(()=>{const _=Ti(s);l(Po(_))},[s]),N=S.useCallback((_,H)=>{if(!pr())return;b.current!==null&&(window.clearTimeout(b.current),b.current=null);const B=_.map(D=>`${D.threadId}:${D.updatedAt??""}:${D.messageCount??""}`).join("|");if(_.length===0){try{bc(s)}catch{}C.current="";return}if(B===C.current)return;const U=()=>{try{const D=_.slice(0,wc);Sc(s,D),C.current=B}catch{}finally{b.current=null}};if(H!=null&&H.immediate){U();return}b.current=window.setTimeout(()=>{tx(U)},Si)},[s]),A=S.useCallback(()=>{N(u,{immediate:!0})},[N,u]),j=S.useCallback(async()=>{const _=x.current>0;_||p(!0);try{const H=await t.listThreads(),B=()=>{l(U=>{const D=R=>R.map(G=>`${G.threadId}:${G.updatedAt??""}:${G.messageCount??""}`).join("|"),L=Ii(U);return D(L)===D(H)||H.length===0&&L.length>0&&!v.current?U:Po(H)})};_?S.startTransition(B):B(),w(null),v.current||(v.current=!0)}catch(H){r==null||r(String(H)),console.error("[useThreadList] Failed to refresh threads:",H),w(String(H))}finally{p(!1)}},[t,r]),M=S.useCallback(async _=>{var U;const H=`thread-${((U=crypto.randomUUID)==null?void 0:U.call(crypto))??Date.now().toString(36)}`,B={threadId:H,title:_||"New Chat",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:0};l(D=>({byId:{...D.byId,[H]:B},order:[H,...D.order]})),f(H);try{const D=await t.createThread(_);return l(L=>{const X={...L.byId};delete X[H],X[D.threadId]=D;const R=L.order.map(G=>G===H?D.threadId:G);return{byId:X,order:R}}),f(D.threadId),w(null),D}catch(D){throw l(L=>{const X={...L.byId};return delete X[H],{byId:X,order:L.order.filter(R=>R!==H)}}),w(String(D)),r==null||r(String(D)),D}},[t,r]),F=S.useCallback(async _=>{var H;try{await t.deleteThread(_);let B=null;l(D=>{if(!D.byId[_])return D;const L={...D.byId};delete L[_];const X=D.order.filter(G=>G!==_),R={byId:L,order:X};return B=Ii(R),R}),B&&N(B,{immediate:!0});const U=d===_;U&&f(null),(H=e.onThreadRemoved)==null||H.call(e,_,{wasCurrent:U}),await j(),w(null)}catch(B){throw w(String(B)),B}},[t,d,e,j,N]),$=S.useCallback(async(_,H)=>{try{await t.updateThread(_,H),l(B=>{const U=B.byId[_];return U?{byId:{...B.byId,[_]:{...U,title:H}},order:B.order}:B}),w(null)}catch(B){throw await j(),w(String(B)),B}},[t,j]);S.useEffect(()=>{if(pr())return N(u),()=>{b.current!==null&&(window.clearTimeout(b.current),b.current=null)}},[u,N]),S.useEffect(()=>{var U,D,L;const _=X=>{const R=ki(n,X??null);k.current!==R&&(k.current=R,E.current=!1),i(R);const G=Ti(R);l(Po(G)),E.current||(E.current=!0,j().catch(()=>{}))},H=((U=t.getAuthToken)==null?void 0:U.call(t))??null;(D=e.onAuthTokenChange)==null||D.call(e,H),_(H);const B=(L=t.onTokenChange)==null?void 0:L.call(t,X=>{var R,G;(R=e.onAuthTokenChange)==null||R.call(e,X),(G=e.clearAllMessageCaches)==null||G.call(e),_(X)});return()=>B==null?void 0:B()},[t,n,j,e.clearAllMessageCaches,e.onAuthTokenChange]);const q=S.useCallback(_=>{l(H=>{const B=H.byId[_.threadId];return B?B.title===_.title&&B.updatedAt===_.updatedAt&&B.messageCount===_.messageCount?H:{byId:{...H.byId,[_.threadId]:_},order:H.order}:{byId:{...H.byId,[_.threadId]:_},order:[_.threadId,...H.order]}})},[]);return{threads:u,currentThreadId:d,setCurrentThreadId:f,isLoadingThreads:h,threadsError:y,refreshThreads:j,createThread:M,deleteThread:F,renameThread:$,persistThreadsCache:A,hydrateThreadsFromCache:T,upsertThreadSummary:q}}const Cc=S.createContext(null),kc=S.createContext(null),Tc=S.createContext(null),ix=S.createContext(!1);function ax({children:e,initialThreadId:t=null,autoLoadInitial:n=!0,disableAutoRestore:r=!1,enableFileAgentRouting:o=!1,fileAgentId:s="invoice_reader",onError:i,onThreadChange:a}){const{api:l,baseUrl:u}=pi(),d=S.useMemo(()=>xn(u),[u]),f=S.useMemo(()=>{try{return new URL(u).host}catch{return"unknown"}},[u]),h=S.useMemo(()=>`threadPayload:${ex}:${f}:`,[f]),p=S.useCallback(g=>`${h}${g}`,[h]),y=S.useCallback(g=>{if(!g||typeof g!="object")return null;const I=g;if(typeof I.threadId!="string")return null;const P=Array.isArray(I.checkpoints)?I.checkpoints.filter(Q=>Q&&typeof Q=="object"):[],W=Array.isArray(I.pendingCheckpoints)?I.pendingCheckpoints.map(Q=>gc(Q)).filter(Q=>!!Q):[],ee=I.activeCheckpointId===null||I.activeCheckpointId===void 0?null:ct(I.activeCheckpointId)??null,se=I.activeCheckpointNs===null||I.activeCheckpointNs===void 0?null:ct(I.activeCheckpointNs)??null;return{threadId:I.threadId,checkpoints:P,pendingCheckpoints:W,activeCheckpointId:ee,activeCheckpointNs:se}},[]),w=S.useCallback(g=>{const I=Ci(p(g));if(!I)return null;try{const P=JSON.parse(I);return y(P)}catch{return null}},[p,y]),x=S.useCallback(g=>{const I={threadId:g.threadId,checkpoints:Array.isArray(g.checkpoints)?g.checkpoints:[],pendingCheckpoints:Array.isArray(g.pendingCheckpoints)?g.pendingCheckpoints.map(P=>({checkpointId:P.checkpointId,checkpointNs:P.checkpointNs??null})):[],activeCheckpointId:g.activeCheckpointId??null,activeCheckpointNs:g.activeCheckpointNs??null};try{yc(p(g.threadId),JSON.stringify(I))}catch{}},[p]),v=S.useCallback(g=>{bc(p(g))},[p]),b=S.useCallback(()=>{if(pr())try{const g=h;for(let I=0;I<window.localStorage.length;I++){const P=window.localStorage.key(I);P&&P.startsWith(g)&&window.localStorage.removeItem(P)}}catch{}},[h]),C=S.useRef(()=>{}),{threads:E,currentThreadId:k,setCurrentThreadId:T,isLoadingThreads:N,threadsError:A,refreshThreads:j,createThread:M,deleteThread:F,renameThread:$,persistThreadsCache:q,hydrateThreadsFromCache:_,upsertThreadSummary:H}=sx({api:l,baseHost:f,onError:i,initialThreadId:t,clearAllMessageCaches:b,onAuthTokenChange:g=>C.current(g??null)}),[B,U]=S.useState(!1),[D,L]=S.useState(null),[X,R]=S.useState(null),[G,de]=S.useState(!1),[ye,Ce]=S.useState(!1),[he,K]=S.useState([]),[z,Y]=S.useState([]),J=S.useRef([]),[ge,oe]=S.useState(null),{state:te,dispatch:Ye,seed:We,prepend:Oe,pushUser:$e,onEvent:st,reset:Xe}=sc(),je=S.useRef(k);S.useEffect(()=>{je.current=k},[k]);const ht=S.useRef(!1),ne=S.useRef([]),le=S.useRef(null),pe=S.useRef(null),be=S.useRef(new Map),me=S.useRef(k),Ie=S.useRef({threadId:null,checkpointId:null,checkpointNs:null}),Je=S.useCallback((g,I)=>new Promise((P,W)=>{const ee=async()=>{ht.current=!0;try{await g(),P()}catch(se){W(se)}finally{ht.current=!1;const se=ne.current.shift();se&&se().catch(()=>{})}};ht.current?ne.current.push(ee):ee().catch(se=>{W(se)})}),[]);S.useEffect(()=>{var ee;const g=je.current;if(!g){X!==null&&R(null),Ie.current={threadId:null,checkpointId:null,checkpointNs:null};return}const I=te.pendingInterrupt??Gg(te.messages);if(I){wi(X,I)||R(I),Ie.current={threadId:g,checkpointId:te.lastCheckpointId??null,checkpointNs:te.lastCheckpointNs??null};return}const P={threadId:g,checkpointId:te.lastCheckpointId??null,checkpointNs:te.lastCheckpointNs??null};if(ge){const se=(ee=ge.values)==null?void 0:ee.state,Q=mc(se);if(Q!==null){wi(X,Q)||R(Q),Ie.current=P;return}if(Ie.current.threadId===P.threadId&&Ie.current.checkpointId===P.checkpointId&&Ie.current.checkpointNs===P.checkpointNs&&X===null){Ie.current=P;return}}if(!(l!=null&&l.getState)){X!==null&&R(null),Ie.current=P;return}let W=!1;return Ie.current=P,l.getState({threadId:g,checkpointId:P.checkpointId??void 0,checkpointNs:P.checkpointNs??void 0}).then(se=>{if(W)return;const Q=mc(se==null?void 0:se.state);wi(X,Q??null)||R(Q??null)}).catch(se=>{W||(console.warn("[ChatSessionProvider] Failed to inspect thread state for interrupts:",se),X!==null&&R(null))}),()=>{W=!0}},[ge,l,X,te.lastCheckpointId,te.lastCheckpointNs,te.messages,te.pendingInterrupt]);const ze=S.useRef(!1),tt=S.useRef(null),ut=S.useCallback((g,I,P,W)=>{const ee=Array.isArray(g==null?void 0:g.checkpoints)?g.checkpoints.filter(Or=>Or&&typeof Or=="object"):[],se=Jg(ee),Q=P??(g==null?void 0:g.threadId)??je.current;if(!Q)return;const xe=Q===je.current,Se=I==="replace"?null:be.current.get(Q)??null,Ee=I==="replace"?[]:xe?he:(Se==null?void 0:Se.checkpoints)??[],qe=I==="replace"?[]:xe?J.current:(Se==null?void 0:Se.pendingCheckpoints)??[],et={checkpointId:(g==null?void 0:g.checkpointId)??null,checkpointNs:(g==null?void 0:g.checkpointNs)??null},nt=se[se.length-1]??null,at=Wn(nt,et),Ge={checkpointId:(W==null?void 0:W.checkpointId)??(I==="replace"?at.checkpointId:(xe?te.lastCheckpointId??null:(Se==null?void 0:Se.activeCheckpointId)??null)??at.checkpointId),checkpointNs:(W==null?void 0:W.checkpointNs)??(I==="replace"?at.checkpointNs:(xe?te.lastCheckpointNs??null:(Se==null?void 0:Se.activeCheckpointNs)??null)??at.checkpointNs)},xt=Yg(Ee,se,I),At=Zg(xt,qe),$n={threadId:Q,checkpoints:xt,pendingCheckpoints:At,activeCheckpointId:Ge.checkpointId,activeCheckpointNs:Ge.checkpointNs};if(be.current.set(Q,$n),me.current=Q,!xe)return;J.current=At,Y(At),de(At.length>0),K(xt);const Ft=Ro(xt,Ge)??xt[xt.length-1]??null;if(oe(Ft),I==="replace"){const Or=kn(Ft??nt);We(Or,{checkpointId:Ge.checkpointId,checkpointNs:Ge.checkpointNs})}else if(I==="prepend"){const im=kn(nt??Ft);im.length&&Oe(im)}},[he,te.lastCheckpointId,te.lastCheckpointNs,J,Oe,We,K,de,Y,oe]),Nt=S.useCallback(g=>{if(g.threadId!=null&&g.threadId!==je.current)return;const I=Array.isArray(g.checkpoints)?g.checkpoints:[];K(I);const P=Array.isArray(g.pendingCheckpoints)?g.pendingCheckpoints:[];J.current=P,Y(P),de(P.length>0);const W={checkpointId:g.activeCheckpointId??null,checkpointNs:g.activeCheckpointNs??null},ee=Ro(I,W)??I[I.length-1]??null;oe(ee);const se=kn(ee);We(se,{checkpointId:W.checkpointId,checkpointNs:W.checkpointNs}),me.current=g.threadId},[We,K,Y,de,oe,J]);S.useEffect(()=>{if(!je.current||!he.length)return;const g={checkpointId:te.lastCheckpointId??null,checkpointNs:te.lastCheckpointNs??null},I=g.checkpointId?yi(g):null;let P=!1;const W=he.map((ee,se)=>{var et;const Q=Hr(ee);if(!(I?Q===I:se===he.length-1))return ee;const Se=Array.isArray((et=ee.values)==null?void 0:et.messages)?ee.values.messages:[];return Se.length===te.messages.length&&Se.every((nt,at)=>{var Ge;return(nt==null?void 0:nt.id)===((Ge=te.messages[at])==null?void 0:Ge.id)})?ee:(P=!0,{...ee,values:{...ee.values??{},messages:te.messages.slice()}})});P&&K(W)},[he,te.lastCheckpointId,te.lastCheckpointNs,te.messages]);const Zt=S.useCallback(g=>{g&&(be.current.delete(g),v(g),me.current===g&&(me.current=null))},[v]),hn=S.useCallback(()=>{const g=je.current;g&&Zt(g),Xe([]),de(!1),Ce(!1),K([]),Y([]),J.current=[],oe(null)},[Zt,Xe]),ir=S.useCallback(({from:g,to:I})=>{const P=je.current;P&&console.warn(`[ChatSessionProvider] Stream sequence gap detected (${g} -> ${I}) for thread ${P}`)},[]),mo=S.useCallback(g=>{const I=g,P=ct(g.threadId)??ct(I.thread_id)??ct(I.id);if(!P){console.warn("[ChatSessionProvider] thread_info event missing threadId",g);return}console.log("[ChatSessionProvider] 📥 Handling thread_info event:",{threadId:P,title:ct(g.title)??ct(I.title),created:ct(g.createdAt)??ct(I.created_at),currentThreads:E.length});const W=ct(g.title)??ct(I.title)??`Thread ${P.slice(0,8)}`,ee=ct(g.createdAt)??ct(I.created_at)??new Date().toISOString(),se=ct(g.updatedAt)??ct(I.updated_at)??ee,Q=g.messageCount??I.message_count??I.messages_count;let xe=0;if(typeof Q=="number"&&Number.isFinite(Q))xe=Q;else if(Q!=null){const Ee=Number.parseInt(String(Q),10);Number.isFinite(Ee)&&(xe=Ee)}const Se={threadId:P,title:W,createdAt:ee,updatedAt:se,messageCount:xe};je.current!==P&&(!je.current&&te.messages.length<=1&&(pe.current=P),T(P)),S.startTransition(()=>{H(Se)})},[te.messages.length,E.length,H]),{startStream:Ar,stop:Ln,isStreaming:pn,error:Lt,setAuthToken:mn}=Kg({baseUrl:d,onThreadInfo:mo,onMessageEvent:st,onUnhandledEvent:g=>{console.warn(`[ChatSessionProvider] Unhandled stream event: ${g.type}`,g)},onSequenceGap:ir});S.useEffect(()=>{ze.current=pn},[pn]),S.useEffect(()=>{C.current=g=>mn(g??null)},[mn]),S.useEffect(()=>{var g;C.current(((g=l.getAuthToken)==null?void 0:g.call(l))??null)},[l]);const Fn=S.useCallback(async g=>{const I=await M(g);return(I==null?void 0:I.threadId)??null},[M]),ar=S.useCallback(async g=>{const I=je.current===g;await F(g),Zt(g),I&&(pe.current=g,T(null),je.current=null,me.current=null,hn())},[F,hn,Zt,T]),_r=S.useCallback((g,I)=>$(g,I),[$]),Qt=S.useCallback(async(g,I,P,W=!1)=>{await Je(async()=>{if(pe.current===g&&!W){pe.current=null;return}if(le.current===g&&!W)return;T(Se=>Se===g?Se:g),je.current=g;const ee=!W&&!I&&!P;let se=!1;if(ee){const Se=be.current.get(g);if(Se)Nt(Se),se=!0;else{const Ee=w(g);Ee&&(be.current.set(g,Ee),Nt(Ee),se=!0)}}const Q=W||!se||!!I||!!P,xe=async Se=>{Se&&U(!0),le.current=g;try{const Ee=await l.getStateHistory({threadId:g,checkpointId:I,checkpointNs:P});ut(Ee,"replace",g),L(null)}catch(Ee){throw(!se||W||Se)&&(i==null||i(String(Ee))),L(String(Ee)),Ee}finally{le.current=null,Se&&U(!1)}};Q?await xe(!0):ee&&se&&xe(!1).catch(Se=>{console.warn("[ChatSessionProvider] Background refresh failed:",Se)})},`loadThread-${g}`)},[l,Nt,ut,Je,i]),jr=S.useCallback(async()=>{await Je(async()=>{const g=je.current;g&&Zt(g),pe.current=null,T(null),je.current=null,me.current=null,hn();try{localStorage.removeItem("lastThreadId")}catch(I){console.warn("[ChatSessionProvider] Failed to clear lastThreadId:",I)}},"clearCurrentThread")},[hn,Zt,Je]),lr=S.useCallback(async(g,I)=>{if(!je.current)throw new Error("No active thread");const W=Ro(he,{checkpointId:g,checkpointNs:I??null});if(!W)throw new Error(`Checkpoint ${g} not found in loaded history`);const ee={checkpointId:g,checkpointNs:I??null},se={threadId:je.current,checkpoints:he,pendingCheckpoints:J.current,activeCheckpointId:ee.checkpointId,activeCheckpointNs:ee.checkpointNs};be.current.set(je.current,se),me.current=je.current,oe(W);const Q=kn(W);We(Q,{checkpointId:ee.checkpointId,checkpointNs:ee.checkpointNs})},[he,Ro,kn,We,oe]),cr=S.useCallback(async()=>{var I,P;if(!je.current)throw new Error("No active thread");const g=he[he.length-1];if(g){const W=g.config,ee={checkpointId:((I=W==null?void 0:W.configurable)==null?void 0:I.checkpoint_id)??null,checkpointNs:((P=W==null?void 0:W.configurable)==null?void 0:P.checkpoint_ns)??null},se={threadId:je.current,checkpoints:he,pendingCheckpoints:J.current,activeCheckpointId:ee.checkpointId,activeCheckpointNs:ee.checkpointNs};be.current.set(je.current,se),me.current=je.current,oe(g);const Q=kn(g);We(Q,{checkpointId:ee.checkpointId,checkpointNs:ee.checkpointNs})}else await Qt(je.current,void 0,void 0,!0)},[he,kn,We,oe,Qt]),Rr=S.useCallback(async()=>{if(!je.current)throw new Error("No active thread");if(ye)return;const g=J.current;if(!g.length){de(!1);return}const[I,...P]=g;J.current=P,Y(P),Ce(!0);try{const W=je.current,ee=await l.getStateHistory({threadId:W,checkpointId:I.checkpointId,checkpointNs:I.checkpointNs??void 0});ut(ee,"prepend",W??void 0,{checkpointId:te.lastCheckpointId??null,checkpointNs:te.lastCheckpointNs??null}),L(null)}catch(W){throw J.current=[I,...J.current],Y(J.current),de(!0),L(String(W)),W}finally{Ce(!1)}},[l,ut,ye,te.lastCheckpointId,te.lastCheckpointNs,J,Y]),Pr=S.useCallback(g=>{var qe,et,nt,at,Ge,xt,At;const I=((qe=g==null?void 0:g.config)==null?void 0:qe.threadId)??((et=g==null?void 0:g.config)==null?void 0:et.thread_id)??(g==null?void 0:g.threadId)??(g==null?void 0:g.thread_id),P=ct(I);if(!P)return;const W=((nt=g==null?void 0:g.config)==null?void 0:nt.checkpointId)??((at=g==null?void 0:g.config)==null?void 0:at.checkpoint_id)??(g==null?void 0:g.checkpointId)??(g==null?void 0:g.checkpoint_id)??((Ge=g==null?void 0:g.checkpoint)==null?void 0:Ge.id),ee=ct(W)??void 0,se=((xt=g==null?void 0:g.config)==null?void 0:xt.checkpointNs)??((At=g==null?void 0:g.config)==null?void 0:At.checkpoint_ns)??(g==null?void 0:g.checkpointNs)??(g==null?void 0:g.checkpoint_ns),Q=ct(se)??void 0,xe=kn(g),Se={createdAt:new Date().toISOString(),config:{configurable:{checkpoint_id:ee,checkpoint_ns:Q}},metadata:{},values:{messages:xe},next:[],parentConfig:null,tasks:g.tasks??[]};ut({threadId:P,checkpointId:ee,checkpointNs:Q,version:"chat-history@1",checkpoints:[Se]},"replace",P,{checkpointId:ee??null,checkpointNs:Q??null})},[ut]),ie=S.useCallback(async(g,I)=>{var $n;const P=je.current,W=(g==null?void 0:g.text)??"",ee=(g==null?void 0:g.attachments)??[],se=ee.length?ee:(I==null?void 0:I.attachments)??[],Q={...(I==null?void 0:I.payloadExtras)??{},...(g==null?void 0:g.payload)??{}};if(!P&&!Object.keys(Q).length&&se.length===0&&!W.trim()){console.warn("[ChatSessionProvider] Nothing to submit - skipping");return}!P&&!Q.messages&&console.warn("[ChatSessionProvider] No thread ID - message will create new thread");const{contentParts:xe,filesInfo:Se}=await Fg(l,se),Ee=[...xe];W&&W.trim()&&Ee.push({type:"text",text:W.trim()});const qe=!!P,et=qe?(I==null?void 0:I.checkpointId)??te.lastCheckpointId??void 0:void 0,nt=qe?(I==null?void 0:I.checkpointNs)??te.lastCheckpointNs??void 0:void 0,at={id:(($n=crypto.randomUUID)==null?void 0:$n.call(crypto))||`user-${Date.now()}`,role:"user",content:Ee,createdAt:new Date().toISOString(),...et!=null?{checkpointId:et}:{},...nt!=null?{checkpointNs:nt}:{}};Ee.length>0&&$e(at);const Ge={...at,content:Ee},xt=se.length>0,At={...P?{threadId:P}:{},payload:{messages:Ee.length>0?[Ge]:[],files_info:Se,...o&&xt&&s?{active_agent:s}:{},...Q},...et!=null?{checkpointId:et}:{},...nt!=null?{checkpointNs:nt}:{},nodeFilter:I==null?void 0:I.nodeFilter,config:I==null?void 0:I.config};Ar(At,{onError:Ft=>{console.warn("[ChatSessionProvider] Stream error:",Ft)},onOpen:({threadId:Ft})=>{!je.current&&Ft&&(te.messages.length<=1&&(pe.current=Ft),T(Ft))},onGap:ir})},[l,o,s,ir,te.lastCheckpointId,te.lastCheckpointNs,te.messages.length,$e,Ar]),ve=S.useCallback(async(g,I,P)=>{var ee,se;const W=je.current;if(!W)throw new Error("No active thread to handle interrupt");try{const Q=I?P??!0:!1;try{Ye({type:"interrupt_response",payload:{interruptId:g}})}catch(at){console.warn("[ChatSessionProvider] optimistic interrupt_response dispatch failed:",at)}const xe=`${d}/runs/resume`,Se=(ee=l.getAuthToken)==null?void 0:ee.call(l),Ee=await fetch(xe,{method:"POST",headers:{"Content-Type":"application/json",...Se?{Authorization:`Bearer ${Se}`}:{}},body:JSON.stringify({thread_id:W,value:Q})});if(!Ee.ok)throw new Error(`Resume failed with status ${Ee.status}`);const qe=(se=Ee.body)==null?void 0:se.getReader();if(!qe)throw new Error("No response body for resume stream");const et=new TextDecoder;let nt="";for(;;){const{done:at,value:Ge}=await qe.read();if(at)break;nt+=et.decode(Ge,{stream:!0});const xt=nt.split(`
39
39
  `);nt=xt.pop()||"";for(const At of xt)if(At.startsWith("data: ")){const $n=At.slice(6);try{const Ft=JSON.parse($n);Ye({type:"event",payload:{ev:Ft}})}catch(Ft){console.warn("[ChatSessionProvider] Failed to parse resume SSE event:",Ft)}}}R(null)}catch(Q){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${g}:`,Q),Q}},[l,Ye,d]),De=S.useCallback(g=>ve(g.interruptId,g.approved,g.value),[ve]);S.useEffect(()=>{if(a==null||a(k),k)try{localStorage.setItem("lastThreadId",k)}catch(g){console.warn("[ChatSessionProvider] Failed to persist lastThreadId:",g)}},[k,a]),S.useEffect(()=>((async()=>{try{if(j().catch(I=>{console.error("[ChatSessionProvider] Failed to refresh threads (background):",I),i==null||i(String(I))}),!r&&!t)try{const I=localStorage.getItem("lastThreadId");I&&(T(I),n&&await Qt(I))}catch(I){console.warn("[ChatSessionProvider] Failed to restore last thread:",I)}else t&&n&&await Qt(t)}catch(I){console.error("[ChatSessionProvider] Initialization failed:",I),i==null||i(String(I))}})(),()=>{}),[]),S.useEffect(()=>{const g=je.current;if(!g||me.current!==g)return;const I={threadId:g,checkpoints:he,pendingCheckpoints:J.current,activeCheckpointId:te.lastCheckpointId??null,activeCheckpointNs:te.lastCheckpointNs??null},P=be.current.get(g),W=!P||vc(P.checkpoints??[])!==vc(I.checkpoints),ee=xe=>xe.map(Se=>jo(Se)).join("|"),se=!P||ee(P.pendingCheckpoints??[])!==ee(I.pendingCheckpoints),Q=!P||P.activeCheckpointId!==I.activeCheckpointId||P.activeCheckpointNs!==I.activeCheckpointNs;(W||se||Q)&&(be.current.set(g,I),tt.current&&window.clearTimeout(tt.current),tt.current=window.setTimeout(()=>{try{x(I)}catch(xe){console.warn("[ChatSessionProvider] Failed to persist thread payload:",xe)}},Si))},[he,te.lastCheckpointId,te.lastCheckpointNs,z]);const lt=S.useMemo(()=>({threads:E,currentThreadId:k,setCurrentThreadId:T,isLoading:N,error:A,actions:{createThread:Fn,deleteThread:ar,renameThread:_r,refreshThreads:()=>j()},persistThreadsCache:q,hydrateFromCache:_}),[E,k,N,A,Fn,ar,_r,j,q,_,T]),gn=S.useMemo(()=>{const g=te.lastBranch??null,I=te.assemblingId??null,P=g||I?{branchLabel:(g==null?void 0:g.branchLabel)??null,lastBranch:g,assemblingMessageId:I}:null;return{threadId:k,messages:te.messages,interrupt:X,checkpoint:{id:te.lastCheckpointId??null,namespace:te.lastCheckpointNs??null},checkpoints:he,metadata:P,isLoading:B,isHistoryLoading:ye,error:D,hasMore:G,loadOlder:Rr,seedFromSnapshot:Pr,clearState:hn,navigateToCheckpoint:lr,returnToLatest:cr,loadThread:Qt,clearThread:jr,respondToInterrupt:ve}},[jr,hn,k,X,G,ye,B,Rr,Qt,te.assemblingId,te.lastBranch,te.lastCheckpointId,te.lastCheckpointNs,te.messages,lr,ve,cr,Pr,D]),ur=S.useMemo(()=>({isStreaming:pn,error:Lt,submit:ie,stop:Ln,resume:De,setAuthToken:mn}),[pn,Lt,ie,Ln,De,mn]);return c.jsx(ix.Provider,{value:!0,children:c.jsx(Tc.Provider,{value:ur,children:c.jsx(Cc.Provider,{value:lt,children:c.jsx(kc.Provider,{value:gn,children:e})})})})}function Oo(){const e=S.useContext(Cc);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function Mo(){const e=S.useContext(kc);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function Ic(){const e=S.useContext(Tc);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function Do({children:e,apiConfig:t,initialThreadId:n=null,autoLoadInitial:r=!0,disableAutoRestore:o=!1,enableFileAgentRouting:s=!1,fileAgentId:i="invoice_reader",onError:a,onThreadChange:l}){return c.jsx(Dg,{apiConfig:t,children:c.jsx(ax,{initialThreadId:n,autoLoadInitial:r,disableAutoRestore:o,enableFileAgentRouting:s,fileAgentId:i,onError:a,onThreadChange:l,children:e})})}function re(...e){return um.twMerge(cm.clsx(e))}const lx=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"}}),Ue=m.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?zn.Slot:"button";return c.jsx(i,{className:re(lx({variant:t,size:n,className:e})),ref:s,...o})});Ue.displayName="Button";const Ec=m.forwardRef(({className:e,...t},n)=>c.jsx("textarea",{className:re("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}));Ec.displayName="Textarea";function cx({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=2e4,onSend:i,onCancelEdit:a,onStop:l,className:u="",textareaClassName:d="",allowEmptySend:f=!1}){const[h,p]=S.useState(e),[y,w]=S.useTransition(),x=S.useRef(null);S.useEffect(()=>{p(e??""),x.current&&(x.current.style.height="auto",x.current.style.height=`${x.current.scrollHeight}px`)},[e,t]);const v=S.useCallback(()=>{const A=x.current;A&&(A.style.height="auto",A.style.height=`${A.scrollHeight}px`)},[]);S.useEffect(()=>{v()},[v]);const b=S.useCallback(async A=>{A&&A.preventDefault();const j=(h??"").trim();!j&&!f||w(()=>{try{const M=i(j);M&&typeof M.then=="function"?M.then(()=>{p(""),x.current&&(x.current.style.height="auto")}).catch(()=>{}):(p(""),x.current&&(x.current.style.height="auto"))}catch{}})},[h,i,f]),C=S.useCallback(A=>{p(A.target.value),x.current&&(x.current.style.height="auto",x.current.style.height=`${x.current.scrollHeight}px`)},[]),E=S.useCallback(A=>{A.key==="Enter"&&!A.shiftKey?(A.preventDefault(),b()):A.key==="Escape"&&t&&(A.preventDefault(),a==null||a())},[b,t,a]),N=`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))]":""} ${d}`;return c.jsx("form",{onSubmit:A=>void b(A),className:`w-full ${u}`,children:c.jsxs("div",{className:"flex items-end gap-2",children:[c.jsx("div",{className:"flex-1",children:c.jsx(Ec,{ref:x,value:h,onChange:C,onKeyDown:E,placeholder:t?"Edit your message...":n,className:N,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),c.jsx("div",{children:r?c.jsx(Ue,{type:"button",onClick:()=>{l==null||l()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!l,children:c.jsx(ae.Square,{size:16})}):c.jsx(Ue,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!h.trim()&&!f||y,children:c.jsx(ae.Send,{size:16})})})]})})}const ux=S.memo(cx),Lo=0,Tn=1,mr=2,Nc=4;function Ac(e){return()=>e}function dx(e){e()}function _c(e,t){return n=>e(t(n))}function jc(e,t){return()=>e(t)}function fx(e,t){return n=>e(t,n)}function Ei(e){return e!==void 0}function hx(...e){return()=>{e.map(dx)}}function gr(){}function Fo(e,t){return t(e),e}function px(e,t){return t(e)}function rt(...e){return e}function Ke(e,t){return e(Tn,t)}function Le(e,t){e(Lo,t)}function Ni(e){e(mr)}function ft(e){return e(Nc)}function we(e,t){return Ke(e,fx(t,Lo))}function qt(e,t){const n=e(Tn,r=>{n(),t(r)});return n}function Rc(e){let t,n;return r=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{r(t)},e)}}function Pc(e,t){return e===t}function ot(e=Pc){let t;return n=>r=>{e(t,r)||(t=r,n(r))}}function Ae(e){return t=>n=>{e(n)&&t(n)}}function ce(e){return t=>_c(t,e)}function tn(e){return t=>()=>{t(e)}}function V(e,...t){const n=mx(...t);return(r,o)=>{switch(r){case mr:Ni(e);return;case Tn:return Ke(e,n(o))}}}function nn(e,t){return n=>r=>{n(t=e(t,r))}}function Vn(e){return t=>n=>{e>0?e--:t(n)}}function yn(e){let t=null,n;return r=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,r(t)},e))}}function Fe(...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);Ke(s,l=>{const u=n;n=n|a,t[i]=l,u!==o&&n===o&&r&&(r(),r=null)})}),s=>i=>{const a=()=>{s([i].concat(t))};n===o?a():r=a}}function mx(...e){return t=>e.reduceRight(px,t)}function gx(e){let t,n;const r=()=>t==null?void 0:t();return function(o,s){switch(o){case Tn:return s?n===s?void 0:(r(),n=s,t=Ke(e,s),t):(r(),gr);case mr:r(),n=null;return}}}function Z(e){let t=e;const n=He();return(r,o)=>{switch(r){case Lo:t=o;break;case Tn:{o(t);break}case Nc:return t}return n(r,o)}}function yt(e,t){return Fo(Z(t),n=>we(e,n))}function He(){const e=[];return(t,n)=>{switch(t){case Lo:e.slice().forEach(r=>{r(n)});return;case mr:e.splice(0,e.length);return;case Tn:return e.push(n),()=>{const r=e.indexOf(n);r>-1&&e.splice(r,1)}}}}function Rt(e){return Fo(He(),t=>we(e,t))}function Ve(e,t=[],{singleton:n}={singleton:!0}){return{constructor:e,dependencies:t,id:xx(),singleton:n}}const xx=()=>Symbol();function vx(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 pt(...e){const t=He(),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);Ke(s,l=>{n[i]=l,r=r|a,r===o&&Le(t,n)})}),function(s,i){switch(s){case mr:{Ni(t);return}case Tn:return r===o&&i(n),Ke(t,i)}}}function Ne(e,t=Pc){return V(e,ot(t))}function Ai(...e){return function(t,n){switch(t){case mr:return;case Tn:return hx(...e.map(r=>Ke(r,n)))}}}var Et=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(Et||{});const wx={0:"debug",3:"error",1:"log",2:"warn"},yx=()=>typeof globalThis>"u"?window:globalThis,In=Ve(()=>{const e=Z(3);return{log:Z((t,n,r=1)=>{var o;const s=(o=yx().VIRTUOSO_LOG_LEVEL)!=null?o:ft(e);r>=s&&console[wx[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function qn(e,t,n){return _i(e,t,n).callbackRef}function _i(e,t,n){const r=S.useRef(null);let o=i=>{};const s=S.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 bx(e,t,n,r,o,s,i,a,l){const u=S.useCallback(d=>{const f=Sx(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 y;p&&(y=h.ownerDocument.defaultView);const w=i?a?i.scrollLeft:i.scrollTop:p?a?y.scrollX||y.document.documentElement.scrollLeft:y.scrollY||y.document.documentElement.scrollTop:a?h.scrollLeft:h.scrollTop,x=i?a?i.scrollWidth:i.scrollHeight:p?a?y.document.documentElement.scrollWidth:y.document.documentElement.scrollHeight:a?h.scrollWidth:h.scrollHeight,v=i?a?i.offsetWidth:i.offsetHeight:p?a?y.innerWidth:y.innerHeight:a?h.offsetWidth:h.offsetHeight;r({scrollHeight:x,scrollTop:Math.max(w,0),viewportHeight:v}),s==null||s(a?Oc("column-gap",getComputedStyle(d).columnGap,o):Oc("row-gap",getComputedStyle(d).rowGap,o)),f!==null&&e(f)},[e,t,o,s,i,r,a]);return _i(u,n,l)}function Sx(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),u=parseFloat(a.dataset.knownSize),d=t(a,n);if(d===0&&r("Zero-sized element, this should not happen",{child:a},Et.ERROR),d===u)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 Oc(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,Et.WARN),t==="normal"?0:parseInt(t??"0",10)}function Mc(e,t,n){const r=S.useRef(null),o=S.useCallback(l=>{if(!(l!=null&&l.offsetParent))return;const u=l.getBoundingClientRect(),d=u.width;let f,h;if(t){const p=t.getBoundingClientRect(),y=u.top-p.top;h=p.height-Math.max(0,y),f=y+t.scrollTop}else{const p=i.current.ownerDocument.defaultView;h=p.innerHeight-Math.max(0,u.top),f=u.top+p.scrollY}r.current={offsetTop:f,visibleHeight:h,visibleWidth:d},e(r.current)},[e,t]),{callbackRef:s,ref:i}=_i(o,!0,n),a=S.useCallback(()=>{o(i.current)},[o,i]);return S.useEffect(()=>{var l;if(t){t.addEventListener("scroll",a);const u=new ResizeObserver(()=>{requestAnimationFrame(a)});return u.observe(t),()=>{t.removeEventListener("scroll",a),u.unobserve(t)}}else{const u=(l=i.current)==null?void 0:l.ownerDocument.defaultView;return u==null||u.addEventListener("scroll",a),u==null||u.addEventListener("resize",a),()=>{u==null||u.removeEventListener("scroll",a),u==null||u.removeEventListener("resize",a)}}},[a,t,i]),s}const Ct=Ve(()=>{const e=He(),t=He(),n=Z(0),r=He(),o=Z(0),s=He(),i=He(),a=Z(0),l=Z(0),u=Z(0),d=Z(0),f=He(),h=He(),p=Z(!1),y=Z(!1),w=Z(!1);return we(V(e,ce(({scrollTop:x})=>x)),t),we(V(e,ce(({scrollHeight:x})=>x)),i),we(t,o),{deviation:n,fixedFooterHeight:u,fixedHeaderHeight:l,footerHeight:d,headerHeight:a,horizontalDirection:y,scrollBy:h,scrollContainerState:e,scrollHeight:i,scrollingInProgress:p,scrollTo:f,scrollTop:t,skipAnimationFrameInResizeObserver:w,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:s}},[],{singleton:!0}),Ur={lvl:0};function Dc(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 Ze(e){return e===Ur}function Wr(e,t){if(!Ze(e))return t===e.k?e.v:t<e.k?Wr(e.l,t):Wr(e.r,t)}function Kt(e,t,n="k"){if(Ze(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const r=Kt(e.r,t,n);return r[0]===-1/0?[e.k,e.v]:r}return Kt(e.l,t,n)}function Pt(e,t,n){return Ze(e)?$c(t,n,1):t===e.k?mt(e,{k:t,v:n}):t<e.k?zc(mt(e,{l:Pt(e.l,t,n)})):zc(mt(e,{r:Pt(e.r,t,n)}))}function xr(){return Ur}function $o(e,t,n){if(Ze(e))return[];const r=Kt(e,t)[0];return Cx(Ri(e,r,n))}function ji(e,t){if(Ze(e))return Ur;const{k:n,l:r,r:o}=e;if(t===n){if(Ze(r))return o;if(Ze(o))return r;{const[s,i]=Fc(r);return zo(mt(e,{k:s,l:Lc(r),v:i}))}}else return t<n?zo(mt(e,{l:ji(r,t)})):zo(mt(e,{r:ji(o,t)}))}function Kn(e){return Ze(e)?[]:[...Kn(e.l),{k:e.k,v:e.v},...Kn(e.r)]}function Ri(e,t,n){if(Ze(e))return[];const{k:r,l:o,r:s,v:i}=e;let a=[];return r>t&&(a=a.concat(Ri(o,t,n))),r>=t&&r<=n&&a.push({k:r,v:i}),r<=n&&(a=a.concat(Ri(s,t,n))),a}function zo(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(Pi(t))return Bc(mt(e,{lvl:n-1}));if(!Ze(t)&&!Ze(t.r))return mt(t.r,{l:mt(t,{r:t.r.l}),lvl:n,r:mt(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}else{if(Pi(e))return Oi(mt(e,{lvl:n-1}));if(!Ze(r)&&!Ze(r.l)){const o=r.l,s=Pi(o)?r.lvl-1:r.lvl;return mt(o,{l:mt(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:Oi(mt(r,{l:o.r,lvl:s}))})}else throw new Error("Unexpected empty nodes")}}function mt(e,t){return $c(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 Lc(e){return Ze(e.r)?e.l:zo(mt(e,{r:Lc(e.r)}))}function Pi(e){return Ze(e)||e.lvl>e.r.lvl}function Fc(e){return Ze(e.r)?[e.k,e.v]:Fc(e.r)}function $c(e,t,n,r=Ur,o=Ur){return{k:e,l:r,lvl:n,r:o,v:t}}function zc(e){return Oi(Bc(e))}function Bc(e){const{l:t}=e;return!Ze(t)&&t.lvl===e.lvl?mt(t,{r:mt(e,{l:t.r})}):e}function Oi(e){const{lvl:t,r:n}=e;return!Ze(n)&&!Ze(n.r)&&n.lvl===t&&n.r.lvl===t?mt(n,{l:mt(e,{r:n.l}),lvl:t+1}):e}function Cx(e){return Dc(e,({k:t,v:n})=>({index:t,value:n}))}function Hc(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}function Vr(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}const Mi=Ve(()=>({recalcInProgress:Z(!1)}),[],{singleton:!0});function Uc(e,t,n){return e[Bo(e,t,n)]}function Bo(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 kx(e,t,n,r){const o=Bo(e,t,r),s=Bo(e,n,r,o);return e.slice(o,s+1)}function En(e,t){return Math.round(e.getBoundingClientRect()[t])}function Ho(e){return!Ze(e.groupOffsetTree)}function Di({index:e},t){return t===e?0:t<e?-1:1}function Tx(){return{groupIndices:[],groupOffsetTree:xr(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:xr()}}function Ix(e,t){let n=Ze(e)?0:1/0;for(const r of t){const{endIndex:o,size:s,startIndex:i}=r;if(n=Math.min(n,i),Ze(e)){e=Pt(e,0,s);continue}const a=$o(e,i-1,o+1);if(a.some(Px(r)))continue;let l=!1,u=!1;for(const{end:d,start:f,value:h}of a)l?(o>=f||s===h)&&(e=ji(e,f)):(u=h!==s,l=!0),d>o&&o>=f&&h!==s&&(e=Pt(e,o+1,h));u&&(e=Pt(e,i,s))}return[e,n]}function Ex(e){return typeof e.groupIndex<"u"}function Nx({offset:e},t){return t===e?0:t<e?-1:1}function qr(e,t,n){if(t.length===0)return 0;const{index:r,offset:o,size:s}=Uc(t,e,Di),i=e-r,a=s*i+(i-1)*n+o;return a>0?a+n:a}function Wc(e,t){if(!Ho(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function Vc(e,t,n){if(Ex(e))return t.groupIndices[e.groupIndex]+1;{const r=e.index==="LAST"?n:e.index;let o=Wc(r,t);return o=Math.max(0,o,Math.min(n,o)),o}}function Ax(e,t,n,r=0){return r>0&&(t=Math.max(t,Uc(e,r,Di).offset)),Dc(kx(e,t,n,Nx),Rx)}function _x(e,[t,n,r,o]){t.length>0&&r("received item sizes",t,Et.DEBUG);const s=e.sizeTree;let i=s,a=0;if(n.length>0&&Ze(s)&&t.length===2){const h=t[0].size,p=t[1].size;i=n.reduce((y,w)=>Pt(Pt(y,w,h),w+1,p),i)}else[i,a]=Ix(i,t);if(i===s)return e;const{lastIndex:l,lastOffset:u,lastSize:d,offsetTree:f}=Li(e.offsetTree,a,i,o);return{groupIndices:n,groupOffsetTree:n.reduce((h,p)=>Pt(h,p,qr(p,f,o)),xr()),lastIndex:l,lastOffset:u,lastSize:d,offsetTree:f,sizeTree:i}}function jx(e){return Kn(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 qc(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 Li(e,t,n,r){let o=e,s=0,i=0,a=0,l=0;if(t!==0){l=Bo(o,t-1,Di),a=o[l].offset;const u=Kt(n,t-1);s=u[0],i=u[1],o.length&&o[l].size===Kt(n,t)[1]&&(l-=1),o=o.slice(0,l+1)}else o=[];for(const{start:u,value:d}of $o(n,t,1/0)){const f=u-s,h=f*i+a+f*r;o.push({index:u,offset:h,size:d}),s=u,a=h,i=d}return{lastIndex:s,lastOffset:a,lastSize:i,offsetTree:o}}function Rx(e){return{index:e.index,value:e}}function Px(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 Ox={offsetHeight:"height",offsetWidth:"width"},rn=Ve(([{log:e},{recalcInProgress:t}])=>{const n=He(),r=He(),o=yt(r,0),s=He(),i=He(),a=Z(0),l=Z([]),u=Z(void 0),d=Z(void 0),f=Z((k,T)=>En(k,Ox[T])),h=Z(void 0),p=Z(0),y=Tx(),w=yt(V(n,Fe(l,e,p),nn(_x,y),ot()),y),x=yt(V(l,ot(),nn((k,T)=>({current:T,prev:k.current}),{current:[],prev:[]}),ce(({prev:k})=>k)),[]);we(V(l,Ae(k=>k.length>0),Fe(w,p),ce(([k,T,N])=>{const A=k.reduce((j,M,F)=>Pt(j,M,qr(M,T.offsetTree,N)||F),xr());return{...T,groupIndices:k,groupOffsetTree:A}})),w),we(V(r,Fe(w),Ae(([k,{lastIndex:T}])=>k<T),ce(([k,{lastIndex:T,lastSize:N}])=>[{endIndex:T,size:N,startIndex:k}])),n),we(u,d);const v=yt(V(u,ce(k=>k===void 0)),!0);we(V(d,Ae(k=>k!==void 0&&Ze(ft(w).sizeTree)),ce(k=>[{endIndex:0,size:k,startIndex:0}])),n);const b=Rt(V(n,Fe(w),nn(({sizes:k},[T,N])=>({changed:N!==k,sizes:N}),{changed:!1,sizes:y}),ce(k=>k.changed)));Ke(V(a,nn((k,T)=>({diff:k.prev-T,prev:T}),{diff:0,prev:0}),ce(k=>k.diff)),k=>{const{groupIndices:T}=ft(w);if(k>0)Le(t,!0),Le(s,k+qc(k,T));else if(k<0){const N=ft(x);N.length>0&&(k-=qc(-k,N)),Le(i,k)}}),Ke(V(a,Fe(e)),([k,T])=>{k<0&&T("`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},Et.ERROR)});const C=Rt(s);we(V(s,Fe(w),ce(([k,T])=>{const N=T.groupIndices.length>0,A=[],j=T.lastSize;if(N){const M=Wr(T.sizeTree,0);let F=0,$=0;for(;F<k;){const _=T.groupIndices[$],H=T.groupIndices.length===$+1?1/0:T.groupIndices[$+1]-_-1;A.push({endIndex:_,size:M,startIndex:_}),A.push({endIndex:_+1+H-1,size:j,startIndex:_+1}),$++,F+=H+1}const q=Kn(T.sizeTree);return F!==k&&q.shift(),q.reduce((_,{k:H,v:B})=>{let U=_.ranges;return _.prevSize!==0&&(U=[..._.ranges,{endIndex:H+k-1,size:_.prevSize,startIndex:_.prevIndex}]),{prevIndex:H+k,prevSize:B,ranges:U}},{prevIndex:k,prevSize:0,ranges:A}).ranges}return Kn(T.sizeTree).reduce((M,{k:F,v:$})=>({prevIndex:F+k,prevSize:$,ranges:[...M.ranges,{endIndex:F+k-1,size:M.prevSize,startIndex:M.prevIndex}]}),{prevIndex:0,prevSize:j,ranges:[]}).ranges})),n);const E=Rt(V(i,Fe(w,p),ce(([k,{offsetTree:T},N])=>{const A=-k;return qr(A,T,N)})));return we(V(i,Fe(w,p),ce(([k,T,N])=>{if(T.groupIndices.length>0){if(Ze(T.sizeTree))return T;let A=xr();const j=ft(x);let M=0,F=0,$=0;for(;M<-k;){$=j[F];const q=j[F+1]-$-1;F++,M+=q+1}if(A=Kn(T.sizeTree).reduce((q,{k:_,v:H})=>Pt(q,Math.max(0,_+k),H),A),M!==-k){const q=Wr(T.sizeTree,$);A=Pt(A,0,q);const _=Kt(T.sizeTree,-k+1)[1];A=Pt(A,1,_)}return{...T,sizeTree:A,...Li(T.offsetTree,0,A,N)}}else{const A=Kn(T.sizeTree).reduce((j,{k:M,v:F})=>Pt(j,Math.max(0,M+k),F),xr());return{...T,sizeTree:A,...Li(T.offsetTree,0,A,N)}}})),w),{beforeUnshiftWith:C,data:h,defaultItemSize:d,firstItemIndex:a,fixedItemSize:u,gap:p,groupIndices:l,itemSize:f,listRefresh:b,shiftWith:i,shiftWithOffset:E,sizeRanges:n,sizes:w,statefulTotalCount:o,totalCount:r,trackItemSizes:v,unshiftWith:s}},rt(In,Mi),{singleton:!0});function Mx(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const Kc=Ve(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:r,scrollTop:o}])=>{const s=He(),i=He(),a=Rt(V(s,ce(Mx)));return we(V(a,ce(l=>l.totalCount)),n),we(V(a,ce(l=>l.groupIndices)),e),we(V(pt(o,t,r),Ae(([l,u])=>Ho(u)),ce(([l,u,d])=>Kt(u.groupOffsetTree,Math.max(l-d,0),"v")[0]),ot(),ce(l=>[l])),i),{groupCounts:s,topItemsIndexes:i}},rt(rn,Ct)),Nn=Ve(([{log:e}])=>{const t=Z(!1),n=Rt(V(t,Ae(r=>r),ot()));return Ke(t,r=>{r&&ft(e)("props updated",{},Et.DEBUG)}),{didMount:n,propsReady:t}},rt(In),{singleton:!0}),Dx=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function Gc(e){const t=typeof e=="number"?{index:e}:e;return t.align||(t.align="start"),(!t.behavior||!Dx)&&(t.behavior="auto"),t.offset||(t.offset=0),t}const Kr=Ve(([{gap:e,listRefresh:t,sizes:n,totalCount:r},{fixedFooterHeight:o,fixedHeaderHeight:s,footerHeight:i,headerHeight:a,scrollingInProgress:l,scrollTo:u,smoothScrollTargetReached:d,viewportHeight:f},{log:h}])=>{const p=He(),y=He(),w=Z(0);let x=null,v=null,b=null;function C(){x&&(x(),x=null),b&&(b(),b=null),v&&(clearTimeout(v),v=null),Le(l,!1)}return we(V(p,Fe(n,f,r,w,a,i,h),Fe(e,s,o),ce(([[E,k,T,N,A,j,M,F],$,q,_])=>{const H=Gc(E),{align:B,behavior:U,offset:D}=H,L=N-1,X=Vc(H,k,L);let R=qr(X,k.offsetTree,$)+j;B==="end"?(R+=q+Kt(k.sizeTree,X)[1]-T+_,X===L&&(R+=M)):B==="center"?R+=(q+Kt(k.sizeTree,X)[1]-T+_)/2:R-=A,D&&(R+=D);const G=de=>{C(),de?(F("retrying to scroll to",{location:E},Et.DEBUG),Le(p,E)):(Le(y,!0),F("list did not change, scroll successful",{},Et.DEBUG))};if(C(),U==="smooth"){let de=!1;b=Ke(t,ye=>{de=de||ye}),x=qt(d,()=>{G(de)})}else x=qt(V(t,Lx(150)),G);return v=setTimeout(()=>{C()},1200),Le(l,!0),F("scrolling from index to",{behavior:U,index:X,top:R},Et.DEBUG),{behavior:U,top:R}})),u),{scrollTargetReached:y,scrollToIndex:p,topListHeight:w}},rt(rn,Ct,In),{singleton:!0});function Lx(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return r=>{r&&(t(!0),clearTimeout(n))}}}function Fi(e,t){e==0?t():requestAnimationFrame(()=>{Fi(e-1,t)})}function $i(e,t){const n=t-1;return typeof e=="number"?e:e.index==="LAST"?n:e.index}const Gr=Ve(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:r},{scrollTargetReached:o,scrollToIndex:s},{didMount:i}])=>{const a=Z(!0),l=Z(0),u=Z(!0);return we(V(i,Fe(l),Ae(([d,f])=>!!f),tn(!1)),a),we(V(i,Fe(l),Ae(([d,f])=>!!f),tn(!1)),u),Ke(V(pt(t,i),Fe(a,n,e,u),Ae(([[,d],f,{sizeTree:h},p,y])=>d&&(!Ze(h)||Ei(p))&&!f&&!y),Fe(l)),([,d])=>{qt(o,()=>{Le(u,!0)}),Fi(4,()=>{qt(r,()=>{Le(a,!0)}),Le(s,d)})}),{initialItemFinalLocationReached:u,initialTopMostItemIndex:l,scrolledToInitialItem:a}},rt(rn,Ct,Kr,Nn),{singleton:!0});function Yc(e,t){return Math.abs(e-t)<1.01}const Yr="up",Xr="down",Fx="none",$x={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},zx=0,Jr=Ve(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:r,scrollTop:o,viewportHeight:s}])=>{const i=Z(!1),a=Z(!0),l=He(),u=He(),d=Z(4),f=Z(zx),h=yt(V(Ai(V(Ne(o),Vn(1),tn(!0)),V(Ne(o),Vn(1),tn(!1),Rc(100))),ot()),!1),p=yt(V(Ai(V(n,tn(!0)),V(n,tn(!1),Rc(200))),ot()),!1);we(V(pt(Ne(o),Ne(f)),ce(([b,C])=>b<=C),ot()),a),we(V(a,yn(50)),u);const y=Rt(V(pt(r,Ne(s),Ne(t),Ne(e),Ne(d)),nn((b,[{scrollHeight:C,scrollTop:E},k,T,N,A])=>{const j=E+k-C>-A,M={scrollHeight:C,scrollTop:E,viewportHeight:k};if(j){let $,q;return E>b.state.scrollTop?($="SCROLLED_DOWN",q=b.state.scrollTop-E):($="SIZE_DECREASED",q=b.state.scrollTop-E||b.scrollTopDelta),{atBottom:!0,atBottomBecause:$,scrollTopDelta:q,state:M}}let F;return M.scrollHeight>b.state.scrollHeight?F="SIZE_INCREASED":k<b.state.viewportHeight?F="VIEWPORT_HEIGHT_DECREASING":E<b.state.scrollTop?F="SCROLLING_UPWARDS":F="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:F,state:M}},$x),ot((b,C)=>b&&b.atBottom===C.atBottom))),w=yt(V(r,nn((b,{scrollHeight:C,scrollTop:E,viewportHeight:k})=>{if(Yc(b.scrollHeight,C))return{changed:!1,jump:0,scrollHeight:C,scrollTop:E};{const T=C-(E+k)<1;return b.scrollTop!==E&&T?{changed:!0,jump:b.scrollTop-E,scrollHeight:C,scrollTop:E}:{changed:!0,jump:0,scrollHeight:C,scrollTop:E}}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),Ae(b=>b.changed),ce(b=>b.jump)),0);we(V(y,ce(b=>b.atBottom)),i),we(V(i,yn(50)),l);const x=Z(Xr);we(V(r,ce(({scrollTop:b})=>b),ot(),nn((b,C)=>ft(p)?{direction:b.direction,prevScrollTop:C}:{direction:C<b.prevScrollTop?Yr:Xr,prevScrollTop:C},{direction:Xr,prevScrollTop:0}),ce(b=>b.direction)),x),we(V(r,yn(50),tn(Fx)),x);const v=Z(0);return we(V(h,Ae(b=>!b),tn(0)),v),we(V(o,yn(100),Fe(h),Ae(([b,C])=>!!C),nn(([b,C],[E])=>[C,E],[0,0]),ce(([b,C])=>C-b)),v),{atBottomState:y,atBottomStateChange:l,atBottomThreshold:d,atTopStateChange:u,atTopThreshold:f,isAtBottom:i,isAtTop:a,isScrolling:h,lastJumpDueToItemResize:w,scrollDirection:x,scrollVelocity:v}},rt(Ct)),Uo="top",Wo="bottom",Xc="none";function Jc(e,t,n){return typeof e=="number"?n===Yr&&t===Uo||n===Xr&&t===Wo?e:0:n===Yr?t===Uo?e.main:e.reverse:t===Wo?e.main:e.reverse}function Zc(e,t){var n;return typeof e=="number"?e:(n=e[t])!=null?n:0}const zi=Ve(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:r,viewportHeight:o}])=>{const s=He(),i=Z(0),a=Z(0),l=Z(0),u=yt(V(pt(Ne(r),Ne(o),Ne(n),Ne(s,Vr),Ne(l),Ne(i),Ne(t),Ne(e),Ne(a)),ce(([d,f,h,[p,y],w,x,v,b,C])=>{const E=d-b,k=x+v,T=Math.max(h-E,0);let N=Xc;const A=Zc(C,Uo),j=Zc(C,Wo);return p-=b,p+=h+v,y+=h+v,y-=b,p>d+k-A&&(N=Yr),y<d-T+f+j&&(N=Xr),N!==Xc?[Math.max(E-h-Jc(w,Uo,N)-A,0),E-T-v+f+Jc(w,Wo,N)+j]:null}),Ae(d=>d!=null),ot(Vr)),[0,0]);return{increaseViewportBy:a,listBoundary:s,overscan:l,topListHeight:i,visibleRange:u}},rt(Ct),{singleton:!0});function Bx(e,t,n){if(Ho(t)){const r=Wc(e,t);return[{index:Kt(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 Bi={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function Vo(e,t,n,r,o,s){const{lastIndex:i,lastOffset:a,lastSize:l}=o;let u=0,d=0;if(e.length>0){u=e[0].offset;const w=e[e.length-1];d=w.offset+w.size}const f=n-i,h=a+f*l+(f-1)*r,p=u,y=h-d;return{bottom:d,firstItemIndex:s,items:eu(e,o,s),offsetBottom:y,offsetTop:u,top:p,topItems:eu(t,o,s),topListHeight:t.reduce((w,x)=>x.size+w,0),totalCount:n}}function Qc(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=$i(t,a),u=Array.from({length:a}).map((d,f)=>({data:s[f+l],index:f+l,offset:0,size:0}));return Vo(u,[],a,o,n,r)}function eu(e,t,n){if(e.length===0)return[];if(!Ho(t))return e.map(u=>({...u,index:u.index+n,originalIndex:u.index}));const r=e[0].index,o=e[e.length-1].index,s=[],i=$o(t.groupOffsetTree,r,o);let a,l=0;for(const u of e){(!a||a.end<u.index)&&(a=i.shift(),l=t.groupIndices.indexOf(a.start));let d;u.index===a.start?d={index:l,type:"group"}:d={groupIndex:l,index:u.index-(l+1)+n},s.push({...d,data:u.data,offset:u.offset,originalIndex:u.index,size:u.size})}return s}const Gn=Ve(([{data:e,firstItemIndex:t,gap:n,sizes:r,totalCount:o},s,{listBoundary:i,topListHeight:a,visibleRange:l},{initialTopMostItemIndex:u,scrolledToInitialItem:d},{topListHeight:f},h,{didMount:p},{recalcInProgress:y}])=>{const w=Z([]),x=Z(0),v=He();we(s.topItemsIndexes,w);const b=yt(V(pt(p,y,Ne(l,Vr),Ne(o),Ne(r),Ne(u),d,Ne(w),Ne(t),Ne(n),e),Ae(([T,N,,A,,,,,,,j])=>{const M=j&&j.length!==A;return T&&!N&&!M}),ce(([,,[T,N],A,j,M,F,$,q,_,H])=>{const B=j,{offsetTree:U,sizeTree:D}=B,L=ft(x);if(A===0)return{...Bi,totalCount:A};if(T===0&&N===0)return L===0?{...Bi,totalCount:A}:Qc(L,M,j,q,_,H||[]);if(Ze(D))return L>0?null:Vo(Bx($i(M,A),B,H),[],A,_,B,q);const X=[];if($.length>0){const Ce=$[0],he=$[$.length-1];let K=0;for(const z of $o(D,Ce,he)){const Y=z.value,J=Math.max(z.start,Ce),ge=Math.min(z.end,he);for(let oe=J;oe<=ge;oe++)X.push({data:H==null?void 0:H[oe],index:oe,offset:K,size:Y}),K+=Y}}if(!F)return Vo([],X,A,_,B,q);const R=$.length>0?$[$.length-1]+1:0,G=Ax(U,T,N,R);if(G.length===0)return null;const de=A-1,ye=Fo([],Ce=>{for(const he of G){const K=he.value;let z=K.offset,Y=he.start;const J=K.size;if(K.offset<T){Y+=Math.floor((T-K.offset+_)/(J+_));const oe=Y-he.start;z+=oe*J+oe*_}Y<R&&(z+=(R-Y)*J,Y=R);const ge=Math.min(he.end,de);for(let oe=Y;oe<=ge&&!(z>=N);oe++)Ce.push({data:H==null?void 0:H[oe],index:oe,offset:z,size:J}),z+=J+_}});return Vo(ye,X,A,_,B,q)}),Ae(T=>T!==null),ot()),Bi);we(V(e,Ae(Ei),ce(T=>T==null?void 0:T.length)),o),we(V(b,ce(T=>T.topListHeight)),f),we(f,a),we(V(b,ce(T=>[T.top,T.bottom])),i),we(V(b,ce(T=>T.items)),v);const C=Rt(V(b,Ae(({items:T})=>T.length>0),Fe(o,e),Ae(([{items:T},N])=>T[T.length-1].originalIndex===N-1),ce(([,T,N])=>[T-1,N]),ot(Vr),ce(([T])=>T))),E=Rt(V(b,yn(200),Ae(({items:T,topItems:N})=>T.length>0&&T[0].originalIndex===N.length),ce(({items:T})=>T[0].index),ot())),k=Rt(V(b,Ae(({items:T})=>T.length>0),ce(({items:T})=>{let N=0,A=T.length-1;for(;T[N].type==="group"&&N<A;)N++;for(;T[A].type==="group"&&A>N;)A--;return{endIndex:T[A].index,startIndex:T[N].index}}),ot(Hc)));return{endReached:C,initialItemCount:x,itemsRendered:v,listState:b,rangeChanged:k,startReached:E,topItemsIndexes:w,...h}},rt(rn,Kc,zi,Gr,Kr,Jr,Nn,Mi),{singleton:!0}),tu=Ve(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:r},{listState:o}])=>{const s=He(),i=yt(V(pt(n,e,r,t,o),ce(([a,l,u,d,f])=>a+l+u+d+f.offsetBottom+f.bottom)),0);return we(Ne(i),s),{totalListHeight:i,totalListHeightChanged:s}},rt(Ct,Gn),{singleton:!0}),Hx=Ve(([{viewportHeight:e},{totalListHeight:t}])=>{const n=Z(!1),r=yt(V(pt(n,e,t),Ae(([o])=>o),ce(([,o,s])=>Math.max(0,o-s)),yn(0),ot()),0);return{alignToBottom:n,paddingTopAddition:r}},rt(Ct,tu),{singleton:!0}),nu=Ve(()=>({context:Z(null)})),Ux=({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,ru=Ve(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:s,scrollingInProgress:i,scrollTop:a,viewportHeight:l},{scrollToIndex:u}])=>{const d=He();return we(V(d,Fe(t,l,n,s,o,r,a),Fe(e),ce(([[f,h,p,y,w,x,v,b],C])=>{const{align:E,behavior:k,calculateViewLocation:T=Ux,done:N,...A}=f,j=Vc(f,h,y-1),M=qr(j,h.offsetTree,C)+w+x,F=M+Kt(h.sizeTree,j)[1],$=b+x,q=b+p-v,_=T({itemBottom:F,itemTop:M,locationParams:{align:E,behavior:k,...A},viewportBottom:q,viewportTop:$});return _?N&&qt(V(i,Ae(H=>!H),Vn(ft(i)?1:2)),N):N&&N(),_}),Ae(f=>f!==null)),u),{scrollIntoView:d}},rt(rn,Ct,Kr,Gn,In),{singleton:!0});function ou(e){return e?e==="smooth"?"smooth":"auto":!1}const Wx=(e,t)=>typeof e=="function"?ou(e(t)):t&&ou(e),Vx=Ve(([{listRefresh:e,totalCount:t,fixedItemSize:n,data:r},{atBottomState:o,isAtBottom:s},{scrollToIndex:i},{scrolledToInitialItem:a},{didMount:l,propsReady:u},{log:d},{scrollingInProgress:f},{context:h},{scrollIntoView:p}])=>{const y=Z(!1),w=He();let x=null;function v(k){Le(i,{align:"end",behavior:k,index:"LAST"})}Ke(V(pt(V(Ne(t),Vn(1)),l),Fe(Ne(y),s,a,f),ce(([[k,T],N,A,j,M])=>{let F=T&&j,$="auto";return F&&($=Wx(N,A||M),F=F&&!!$),{followOutputBehavior:$,shouldFollow:F,totalCount:k}}),Ae(({shouldFollow:k})=>k)),({followOutputBehavior:k,totalCount:T})=>{x&&(x(),x=null),ft(n)?requestAnimationFrame(()=>{ft(d)("following output to ",{totalCount:T},Et.DEBUG),v(k)}):x=qt(e,()=>{ft(d)("following output to ",{totalCount:T},Et.DEBUG),v(k),x=null})});function b(k){const T=qt(o,N=>{k&&!N.atBottom&&N.notAtBottomBecause==="SIZE_INCREASED"&&!x&&(ft(d)("scrolling to bottom due to increased size",{},Et.DEBUG),v("auto"))});setTimeout(T,100)}Ke(V(pt(Ne(y),t,u),Ae(([k,,T])=>k&&T),nn(({value:k},[,T])=>({refreshed:k===T,value:T}),{refreshed:!1,value:0}),Ae(({refreshed:k})=>k),Fe(y,t)),([,k])=>{ft(a)&&b(k!==!1)}),Ke(w,()=>{b(ft(y)!==!1)}),Ke(pt(Ne(y),o),([k,T])=>{k&&!T.atBottom&&T.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&v("auto")});const C=Z(null),E=He();return we(Ai(V(Ne(r),ce(k=>{var T;return(T=k==null?void 0:k.length)!=null?T:0})),V(Ne(t))),E),Ke(V(pt(V(E,Vn(1)),l),Fe(Ne(C),a,f,h),ce(([[k,T],N,A,j,M])=>T&&A&&(N==null?void 0:N({context:M,totalCount:k,scrollingInProgress:j}))),Ae(k=>!!k),yn(0)),k=>{x&&(x(),x=null),ft(n)?requestAnimationFrame(()=>{ft(d)("scrolling into view",{}),Le(p,k)}):x=qt(e,()=>{ft(d)("scrolling into view",{}),Le(p,k),x=null})}),{autoscrollToBottom:w,followOutput:y,scrollIntoViewOnChange:C}},rt(rn,Jr,Kr,Gr,Nn,In,Ct,nu,ru)),qx=Ve(([{data:e,firstItemIndex:t,gap:n,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:s,listState:i},{didMount:a}])=>(we(V(a,Fe(s),Ae(([,l])=>l!==0),Fe(o,r,t,n,e),ce(([[,l],u,d,f,h,p=[]])=>Qc(l,u,d,f,h,p))),i),{}),rt(rn,Gr,Gn,Nn),{singleton:!0}),Kx=Ve(([{didMount:e},{scrollTo:t},{listState:n}])=>{const r=Z(0);return Ke(V(e,Fe(r),Ae(([,o])=>o!==0),ce(([,o])=>({top:o}))),o=>{qt(V(n,Vn(1),Ae(s=>s.items.length>1)),()=>{requestAnimationFrame(()=>{Le(t,o)})})}),{initialScrollTop:r}},rt(Nn,Ct,Gn),{singleton:!0}),su=Ve(([{scrollVelocity:e}])=>{const t=Z(!1),n=He(),r=Z(!1);return we(V(e,Fe(r,t,n),Ae(([o,s])=>!!s),ce(([o,s,i,a])=>{const{enter:l,exit:u}=s;if(i){if(u(o,a))return!1}else if(l(o,a))return!0;return i}),ot()),t),Ke(V(pt(t,e,n),Fe(r)),([[o,s,i],a])=>{o&&a&&a.change&&a.change(s,i)}),{isSeeking:t,scrollSeekConfiguration:r,scrollSeekRangeChanged:n,scrollVelocity:e}},rt(Jr),{singleton:!0}),Hi=Ve(([{scrollContainerState:e,scrollTo:t}])=>{const n=He(),r=He(),o=He(),s=Z(!1),i=Z(void 0);return we(V(pt(n,r),ce(([{scrollHeight:a,scrollTop:l,viewportHeight:u},{offsetTop:d}])=>({scrollHeight:a,scrollTop:Math.max(0,l-d),viewportHeight:u}))),e),we(V(t,Fe(r),ce(([a,{offsetTop:l}])=>({...a,top:a.top+l}))),o),{customScrollParent:i,useWindowScroll:s,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:r}},rt(Ct)),Gx=Ve(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:r},{initialTopMostItemIndex:o},{didMount:s},{useWindowScroll:i,windowScrollContainerState:a,windowViewportRect:l}])=>{const u=He(),d=Z(void 0),f=Z(null),h=Z(null);return we(a,f),we(l,h),Ke(V(u,Fe(t,r,i,f,h,n)),([p,y,w,x,v,b,C])=>{const E=jx(y.sizeTree);x&&v!==null&&b!==null&&(w=v.scrollTop-b.offsetTop),w-=C,p({ranges:E,scrollTop:w})}),we(V(d,Ae(Ei),ce(Yx)),o),we(V(s,Fe(d),Ae(([,p])=>p!==void 0),ot(),ce(([,p])=>p.ranges)),e),{getState:u,restoreStateFrom:d}},rt(rn,Ct,Gr,Nn,Hi));function Yx(e){return{align:"start",index:0,offset:e.scrollTop}}const Xx=Ve(([{topItemsIndexes:e}])=>{const t=Z(0);return we(V(t,Ae(n=>n>=0),ce(n=>Array.from({length:n}).map((r,o)=>o))),e),{topItemCount:t}},rt(Gn));function iu(e){let t=!1,n;return()=>(t||(t=!0,n=e()),n)}const Jx=iu(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),Zx=Ve(([{deviation:e,scrollBy:t,scrollingInProgress:n,scrollTop:r},{isAtBottom:o,isScrolling:s,lastJumpDueToItemResize:i,scrollDirection:a},{listState:l},{beforeUnshiftWith:u,gap:d,shiftWithOffset:f,sizes:h},{log:p},{recalcInProgress:y}])=>{const w=Rt(V(l,Fe(i),nn(([,v,b,C],[{bottom:E,items:k,offsetBottom:T,totalCount:N},A])=>{const j=E+T;let M=0;return b===N&&v.length>0&&k.length>0&&(k[0].originalIndex===0&&v[0].originalIndex===0||(M=j-C,M!==0&&(M+=A))),[M,k,N,j]},[0,[],0,0]),Ae(([v])=>v!==0),Fe(r,a,n,o,p,y),Ae(([,v,b,C,,,E])=>!E&&!C&&v!==0&&b===Yr),ce(([[v],,,,,b])=>(b("Upward scrolling compensation",{amount:v},Et.DEBUG),v))));function x(v){v>0?(Le(t,{behavior:"auto",top:-v}),Le(e,0)):(Le(e,0),Le(t,{behavior:"auto",top:-v}))}return Ke(V(w,Fe(e,s)),([v,b,C])=>{C&&Jx()?Le(e,b-v):x(-v)}),Ke(V(pt(yt(s,!1),e,y),Ae(([v,b,C])=>!v&&!C&&b!==0),ce(([v,b])=>b),yn(1)),x),we(V(f,ce(v=>({top:-v}))),t),Ke(V(u,Fe(h,d),ce(([v,{groupIndices:b,lastSize:C,sizeTree:E},k])=>{function T(N){return N*(C+k)}if(b.length===0)return T(v);{let N=0;const A=Wr(E,0);let j=0,M=0;for(;j<v;){j++,N+=A;let F=b.length===M+1?1/0:b[M+1]-b[M]-1;j+F>v&&(N-=A,F=v-j+1),j+=F,N+=T(F),M++}return N}})),v=>{Le(e,v),requestAnimationFrame(()=>{Le(t,{top:v}),requestAnimationFrame(()=>{Le(e,0),Le(y,!1)})})}),{deviation:e}},rt(Ct,Jr,Gn,rn,In,Mi)),Qx=Ve(([e,t,n,r,o,s,i,a,l,u,d])=>({...e,...t,...n,...r,...o,...s,...i,...a,...l,...u,...d}),rt(zi,qx,Nn,su,tu,Kx,Hx,Hi,ru,In,nu)),au=Ve(([{data:e,defaultItemSize:t,firstItemIndex:n,fixedItemSize:r,gap:o,groupIndices:s,itemSize:i,sizeRanges:a,sizes:l,statefulTotalCount:u,totalCount:d,trackItemSizes:f},{initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:y},w,x,v,{listState:b,topItemsIndexes:C,...E},{scrollToIndex:k},T,{topItemCount:N},{groupCounts:A},j])=>(we(E.rangeChanged,j.scrollSeekRangeChanged),we(V(j.windowViewportRect,ce(M=>M.visibleHeight)),w.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:r,gap:o,groupCounts:A,initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:y,sizeRanges:a,topItemCount:N,topItemsIndexes:C,totalCount:d,...v,groupIndices:s,itemSize:i,listState:b,scrollToIndex:k,statefulTotalCount:u,trackItemSizes:f,...E,...j,...w,sizes:l,...x}),rt(rn,Gr,Ct,Gx,Vx,Gn,Kr,Zx,Xx,Kc,Qx));function ev(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 qo=typeof document<"u"?S.useLayoutEffect:S.useEffect;function lu(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=S.createContext({});function l(x,v){x.propsReady&&Le(x.propsReady,!1);for(const b of r){const C=x[t.required[b]];Le(C,v[b])}for(const b of o)if(b in v){const C=x[t.optional[b]];Le(C,v[b])}x.propsReady&&Le(x.propsReady,!0)}function u(x){return s.reduce((v,b)=>(v[b]=C=>{const E=x[t.methods[b]];Le(E,C)},v),{})}function d(x){return i.reduce((v,b)=>(v[b]=gx(x[t.events[b]]),v),{})}const f=S.forwardRef((x,v)=>{const{children:b,...C}=x,[E]=S.useState(()=>Fo(vx(e),N=>{l(N,C)})),[k]=S.useState(jc(d,E));qo(()=>{for(const N of i)N in C&&Ke(k[N],C[N]);return()=>{Object.values(k).map(Ni)}},[C,k,E]),qo(()=>{l(E,C)}),S.useImperativeHandle(v,Ac(u(E)));const T=n;return c.jsx(a.Provider,{value:E,children:n?c.jsx(T,{...ev([...r,...o,...i],C),children:b}):b})}),h=x=>{const v=S.useContext(a);return S.useCallback(b=>{Le(v[x],b)},[v,x])},p=x=>{const v=S.useContext(a)[x],b=S.useCallback(C=>Ke(v,C),[v]);return S.useSyncExternalStore(b,()=>ft(v),()=>ft(v))},y=x=>{const v=S.useContext(a)[x],[b,C]=S.useState(jc(ft,v));return qo(()=>Ke(v,E=>{E!==b&&C(Ac(E))}),[v,b]),b},w=S.version.startsWith("18")?p:y;return{Component:f,useEmitter:(x,v)=>{const b=S.useContext(a)[x];qo(()=>Ke(b,v),[v,b])},useEmitterValue:w,usePublisher:h}}const cu=S.createContext(void 0),uu=S.createContext(void 0),du=typeof document<"u"?S.useLayoutEffect:S.useEffect;function Ui(e){return"self"in e}function tv(e){return"body"in e}function fu(e,t,n,r=gr,o,s){const i=S.useRef(null),a=S.useRef(null),l=S.useRef(null),u=S.useCallback(h=>{let p,y,w;const x=h.target;if(tv(x)||Ui(x)){const b=Ui(x)?x:x.defaultView;w=s?b.scrollX:b.scrollY,p=s?b.document.documentElement.scrollWidth:b.document.documentElement.scrollHeight,y=s?b.innerWidth:b.innerHeight}else w=s?x.scrollLeft:x.scrollTop,p=s?x.scrollWidth:x.scrollHeight,y=s?x.offsetWidth:x.offsetHeight;const v=()=>{e({scrollHeight:p,scrollTop:Math.max(w,0),viewportHeight:y})};h.suppressFlushSync?v():Js.flushSync(v),a.current!==null&&(w===a.current||w<=0||w===p-y)&&(a.current=null,t(!0),l.current&&(clearTimeout(l.current),l.current=null))},[e,t,s]);S.useEffect(()=>{const h=o||i.current;return r(o||i.current),u({suppressFlushSync:!0,target:h}),h.addEventListener("scroll",u,{passive:!0}),()=>{r(null),h.removeEventListener("scroll",u)}},[i,u,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 y=h.behavior==="smooth";let w,x,v;Ui(p)?(x=Math.max(En(p.document.documentElement,s?"width":"height"),s?p.document.documentElement.scrollWidth:p.document.documentElement.scrollHeight),w=s?p.innerWidth:p.innerHeight,v=s?window.scrollX:window.scrollY):(x=p[s?"scrollWidth":"scrollHeight"],w=En(p,s?"width":"height"),v=p[s?"scrollLeft":"scrollTop"]);const b=x-w;if(h.top=Math.ceil(Math.max(Math.min(b,h.top),0)),Yc(w,x)||h.top===v){e({scrollHeight:x,scrollTop:v,viewportHeight:w}),y&&t(!0);return}y?(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 Wi="-webkit-sticky",hu="sticky",Vi=iu(()=>{if(typeof document>"u")return hu;const e=document.createElement("div");return e.style.position=Wi,e.style.position===Wi?Wi:hu});function qi(e){return e}const nv=Ve(()=>{const e=Z(a=>`Item ${a}`),t=Z(a=>`Group ${a}`),n=Z({}),r=Z(qi),o=Z("div"),s=Z(gr),i=(a,l=null)=>yt(V(n,ce(u=>u[a]),ot()),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")}}),rv=Ve(([e,t])=>({...e,...t}),rt(au,nv)),ov=({height:e})=>c.jsx("div",{style:{height:e}}),sv={overflowAnchor:"none",position:Vi(),zIndex:1},pu={overflowAnchor:"none"},iv={...pu,display:"inline-block",height:"100%"},mu=S.memo(function({showTopList:e=!1}){const t=Pe("listState"),n=zt("sizeRanges"),r=Pe("useWindowScroll"),o=Pe("customScrollParent"),s=zt("windowScrollContainerState"),i=zt("scrollContainerState"),a=o||r?s:i,l=Pe("itemContent"),u=Pe("context"),d=Pe("groupContent"),f=Pe("trackItemSizes"),h=Pe("itemSize"),p=Pe("log"),y=zt("gap"),w=Pe("horizontalDirection"),{callbackRef:x}=bx(n,h,f,e?gr:a,p,y,o,w,Pe("skipAnimationFrameInResizeObserver")),[v,b]=S.useState(0);Ki("deviation",_=>{v!==_&&b(_)});const C=Pe("EmptyPlaceholder"),E=Pe("ScrollSeekPlaceholder")||ov,k=Pe("ListComponent"),T=Pe("ItemComponent"),N=Pe("GroupComponent"),A=Pe("computeItemKey"),j=Pe("isSeeking"),M=Pe("groupIndices").length>0,F=Pe("alignToBottom"),$=Pe("initialItemFinalLocationReached"),q=e?{}:{boxSizing:"border-box",...w?{display:"inline-block",height:"100%",marginLeft:v!==0?v:F?"auto":0,paddingLeft:t.offsetTop,paddingRight:t.offsetBottom,whiteSpace:"nowrap"}:{marginTop:v!==0?v:F?"auto":0,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...$?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&C?c.jsx(C,{...bt(C,u)}):c.jsx(k,{...bt(k,u),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:x,style:q,children:(e?t.topItems:t.items).map(_=>{const H=_.originalIndex,B=A(H+t.firstItemIndex,_.data,u);return j?S.createElement(E,{...bt(E,u),height:_.size,index:_.index,key:B,type:_.type||"item",..._.type==="group"?{}:{groupIndex:_.groupIndex}}):_.type==="group"?S.createElement(N,{...bt(N,u),"data-index":H,"data-item-index":_.index,"data-known-size":_.size,key:B,style:sv},d(_.index,u)):S.createElement(T,{...bt(T,u),...uv(T,_.data),"data-index":H,"data-item-group-index":_.groupIndex,"data-item-index":_.index,"data-known-size":_.size,key:B,style:w?iv:pu},M?l(_.index,_.groupIndex,_.data,u):l(_.index,_.data,u))})})}),av={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},lv={outline:"none",overflowX:"auto",position:"relative"},Ko=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:{}}),cv={position:Vi(),top:0,width:"100%",zIndex:1};function bt(e,t){if(typeof e!="string")return{context:t}}function uv(e,t){return{item:typeof e=="string"?void 0:t}}const dv=S.memo(function(){const e=Pe("HeaderComponent"),t=zt("headerHeight"),n=Pe("HeaderFooterTag"),r=qn(S.useMemo(()=>s=>{t(En(s,"height"))},[t]),!0,Pe("skipAnimationFrameInResizeObserver")),o=Pe("context");return e?c.jsx(n,{ref:r,children:c.jsx(e,{...bt(e,o)})}):null}),fv=S.memo(function(){const e=Pe("FooterComponent"),t=zt("footerHeight"),n=Pe("HeaderFooterTag"),r=qn(S.useMemo(()=>s=>{t(En(s,"height"))},[t]),!0,Pe("skipAnimationFrameInResizeObserver")),o=Pe("context");return e?c.jsx(n,{ref:r,children:c.jsx(e,{...bt(e,o)})}):null});function gu({useEmitter:e,useEmitterValue:t,usePublisher:n}){return S.memo(function({children:r,style:o,context:s,...i}){const a=n("scrollContainerState"),l=t("ScrollerComponent"),u=n("smoothScrollTargetReached"),d=t("scrollerRef"),f=t("horizontalDirection")||!1,{scrollByCallback:h,scrollerRef:p,scrollToCallback:y}=fu(a,u,l,d,void 0,f);return e("scrollTo",y),e("scrollBy",h),c.jsx(l,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:p,style:{...f?lv:av,...o},tabIndex:0,...i,...bt(l,s),children:r})})}function xu({useEmitter:e,useEmitterValue:t,usePublisher:n}){return S.memo(function({children:r,style:o,context:s,...i}){const a=n("windowScrollContainerState"),l=t("ScrollerComponent"),u=n("smoothScrollTargetReached"),d=t("totalListHeight"),f=t("deviation"),h=t("customScrollParent"),p=S.useRef(null),y=t("scrollerRef"),{scrollByCallback:w,scrollerRef:x,scrollToCallback:v}=fu(a,u,l,y,h);return du(()=>{var b;return x.current=h||((b=p.current)==null?void 0:b.ownerDocument.defaultView),()=>{x.current=null}},[x,h]),e("windowScrollTo",v),e("scrollBy",w),c.jsx(l,{ref:p,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...d!==0?{height:d+f}:{}},...i,...bt(l,s),children:r})})}const hv=({children:e})=>{const t=S.useContext(cu),n=zt("viewportHeight"),r=zt("fixedItemHeight"),o=Pe("alignToBottom"),s=Pe("horizontalDirection"),i=S.useMemo(()=>_c(n,l=>En(l,s?"width":"height")),[n,s]),a=qn(i,!0,Pe("skipAnimationFrameInResizeObserver"));return S.useEffect(()=>{t&&(n(t.viewportHeight),r(t.itemHeight))},[t,n,r]),c.jsx("div",{"data-viewport-type":"element",ref:a,style:Ko(o),children:e})},pv=({children:e})=>{const t=S.useContext(cu),n=zt("windowViewportRect"),r=zt("fixedItemHeight"),o=Pe("customScrollParent"),s=Mc(n,o,Pe("skipAnimationFrameInResizeObserver")),i=Pe("alignToBottom");return S.useEffect(()=>{t&&(r(t.itemHeight),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:100}))},[t,n,r]),c.jsx("div",{"data-viewport-type":"window",ref:s,style:Ko(i),children:e})},mv=({children:e})=>{const t=Pe("TopItemListComponent")||"div",n=Pe("headerHeight"),r={...cv,marginTop:`${n}px`},o=Pe("context");return c.jsx(t,{style:r,...bt(t,o),children:e})},gv=S.memo(function(e){const t=Pe("useWindowScroll"),n=Pe("topItemsIndexes").length>0,r=Pe("customScrollParent"),o=Pe("context");return c.jsxs(r||t?wv:vv,{...e,context:o,children:[n&&c.jsx(mv,{children:c.jsx(mu,{showTopList:!0})}),c.jsxs(r||t?pv:hv,{children:[c.jsx(dv,{}),c.jsx(mu,{}),c.jsx(fv,{})]})]})}),{Component:xv,useEmitter:Ki,useEmitterValue:Pe,usePublisher:zt}=lu(rv,{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"}},gv),vv=gu({useEmitter:Ki,useEmitterValue:Pe,usePublisher:zt}),wv=xu({useEmitter:Ki,useEmitterValue:Pe,usePublisher:zt}),yv=xv;rt(au,Ve(()=>{const e=Z(u=>c.jsxs("td",{children:["Item $",u]})),t=Z(null),n=Z(u=>c.jsxs("td",{colSpan:1e3,children:["Group ",u]})),r=Z(null),o=Z(null),s=Z({}),i=Z(qi),a=Z(gr),l=(u,d=null)=>yt(V(s,ce(f=>f[u]),ot()),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")}})),Vi();const vu={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},bv={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:wu,floor:Go,max:Zr,min:Gi,round:yu}=Math;function bu(e,t,n){return Array.from({length:t-e+1}).map((r,o)=>({data:n===null?null:n[o+e],index:o+e}))}function Sv(e){return{...bv,items:e}}function Yo(e,t){return e&&e.width===t.width&&e.height===t.height}function Cv(e,t){return e&&e.column===t.column&&e.row===t.row}const kv=Ve(([{increaseViewportBy:e,listBoundary:t,overscan:n,visibleRange:r},{footerHeight:o,headerHeight:s,scrollBy:i,scrollContainerState:a,scrollTo:l,scrollTop:u,smoothScrollTargetReached:d,viewportHeight:f},h,p,{didMount:y,propsReady:w},{customScrollParent:x,useWindowScroll:v,windowScrollContainerState:b,windowScrollTo:C,windowViewportRect:E},k])=>{const T=Z(0),N=Z(0),A=Z(vu),j=Z({height:0,width:0}),M=Z({height:0,width:0}),F=He(),$=He(),q=Z(0),_=Z(null),H=Z({column:0,row:0}),B=He(),U=He(),D=Z(!1),L=Z(0),X=Z(!0),R=Z(!1),G=Z(!1);Ke(V(y,Fe(L),Ae(([z,Y])=>!!Y)),()=>{Le(X,!1)}),Ke(V(pt(y,X,M,j,L,R),Ae(([z,Y,J,ge,,oe])=>z&&!Y&&J.height!==0&&ge.height!==0&&!oe)),([,,,,z])=>{Le(R,!0),Fi(1,()=>{Le(F,z)}),qt(V(u),()=>{Le(t,[0,0]),Le(X,!0)})}),we(V(U,Ae(z=>z!=null&&z.scrollTop>0),tn(0)),N),Ke(V(y,Fe(U),Ae(([,z])=>z!=null)),([,z])=>{z&&(Le(j,z.viewport),Le(M,z.item),Le(H,z.gap),z.scrollTop>0&&(Le(D,!0),qt(V(u,Vn(1)),Y=>{Le(D,!1)}),Le(l,{top:z.scrollTop})))}),we(V(j,ce(({height:z})=>z)),f),we(V(pt(Ne(j,Yo),Ne(M,Yo),Ne(H,(z,Y)=>z&&z.column===Y.column&&z.row===Y.row),Ne(u)),ce(([z,Y,J,ge])=>({gap:J,item:Y,scrollTop:ge,viewport:z}))),B),we(V(pt(Ne(T),r,Ne(H,Cv),Ne(M,Yo),Ne(j,Yo),Ne(_),Ne(N),Ne(D),Ne(X),Ne(L)),Ae(([,,,,,,,z])=>!z),ce(([z,[Y,J],ge,oe,te,Ye,We,,Oe,$e])=>{const{column:st,row:Xe}=ge,{height:je,width:ht}=oe,{width:ne}=te;if(We===0&&(z===0||ne===0))return vu;if(ht===0){const ut=$i($e,z),Nt=ut+Math.max(We-1,0);return Sv(bu(ut,Nt,Ye))}const le=Su(ne,ht,st);let pe,be;Oe?Y===0&&J===0&&We>0?(pe=0,be=We-1):(pe=le*Go((Y+Xe)/(je+Xe)),be=le*wu((J+Xe)/(je+Xe))-1,be=Gi(z-1,Zr(be,le-1)),pe=Gi(be,Zr(0,pe))):(pe=0,be=-1);const me=bu(pe,be,Ye),{bottom:Ie,top:Je}=Cu(te,ge,oe,me),ze=wu(z/le),tt=ze*je+(ze-1)*Xe-Ie;return{bottom:Ie,itemHeight:je,items:me,itemWidth:ht,offsetBottom:tt,offsetTop:Je,top:Je}})),A),we(V(_,Ae(z=>z!==null),ce(z=>z.length)),T),we(V(pt(j,M,A,H),Ae(([z,Y,{items:J}])=>J.length>0&&Y.height!==0&&z.height!==0),ce(([z,Y,{items:J},ge])=>{const{bottom:oe,top:te}=Cu(z,ge,Y,J);return[te,oe]}),ot(Vr)),t);const de=Z(!1);we(V(u,Fe(de),ce(([z,Y])=>Y||z!==0)),de);const ye=Rt(V(pt(A,T),Ae(([{items:z}])=>z.length>0),Fe(de),Ae(([[z,Y],J])=>{const ge=z.items[z.items.length-1].index===Y-1;return(J||z.bottom>0&&z.itemHeight>0&&z.offsetBottom===0&&z.items.length===Y)&&ge}),ce(([[,z]])=>z-1),ot())),Ce=Rt(V(Ne(A),Ae(({items:z})=>z.length>0&&z[0].index===0),tn(0),ot())),he=Rt(V(Ne(A),Fe(D),Ae(([{items:z},Y])=>z.length>0&&!Y),ce(([{items:z}])=>({endIndex:z[z.length-1].index,startIndex:z[0].index})),ot(Hc),yn(0)));we(he,p.scrollSeekRangeChanged),we(V(F,Fe(j,M,T,H),ce(([z,Y,J,ge,oe])=>{const te=Gc(z),{align:Ye,behavior:We,offset:Oe}=te;let $e=te.index;$e==="LAST"&&($e=ge-1),$e=Zr(0,$e,Gi(ge-1,$e));let st=Yi(Y,oe,J,$e);return Ye==="end"?st=yu(st-Y.height+J.height):Ye==="center"&&(st=yu(st-Y.height/2+J.height/2)),Oe&&(st+=Oe),{behavior:We,top:st}})),l);const K=yt(V(A,ce(z=>z.offsetBottom+z.bottom)),0);return we(V(E,ce(z=>({height:z.visibleHeight,width:z.visibleWidth}))),j),{customScrollParent:x,data:_,deviation:q,footerHeight:o,gap:H,headerHeight:s,increaseViewportBy:e,initialItemCount:N,itemDimensions:M,overscan:n,restoreStateFrom:U,scrollBy:i,scrollContainerState:a,scrollHeight:$,scrollTo:l,scrollToIndex:F,scrollTop:u,smoothScrollTargetReached:d,totalCount:T,useWindowScroll:v,viewportDimensions:j,windowScrollContainerState:b,windowScrollTo:C,windowViewportRect:E,...p,gridState:A,horizontalDirection:G,initialTopMostItemIndex:L,totalListHeight:K,...h,endReached:ye,propsReady:w,rangeChanged:he,startReached:Ce,stateChanged:B,stateRestoreInProgress:D,...k}},rt(zi,Ct,Jr,su,Nn,Hi,In));function Su(e,t,n){return Zr(1,Go((e+n)/(Go(t)+n)))}function Cu(e,t,n,r){const{height:o}=n;if(o===void 0||r.length===0)return{bottom:0,top:0};const s=Yi(e,t,n,r[0].index);return{bottom:Yi(e,t,n,r[r.length-1].index)+o,top:s}}function Yi(e,t,n,r){const o=Su(e.width,n.width,t.column),s=Go(r/o),i=s*n.height+Zr(0,s-1)*t.row;return i>0?i+t.row:i}const Tv=Ve(()=>{const e=Z(f=>`Item ${f}`),t=Z({}),n=Z(null),r=Z("virtuoso-grid-item"),o=Z("virtuoso-grid-list"),s=Z(qi),i=Z("div"),a=Z(gr),l=(f,h=null)=>yt(V(t,ce(p=>p[f]),ot()),h),u=Z(!1),d=Z(!1);return we(Ne(d),u),{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:u,reportReadyState:d,ScrollerComponent:l("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder","div")}}),Iv=Ve(([e,t])=>({...e,...t}),rt(kv,Tv)),Ev=S.memo(function(){const e=it("gridState"),t=it("listClassName"),n=it("itemClassName"),r=it("itemContent"),o=it("computeItemKey"),s=it("isSeeking"),i=Bt("scrollHeight"),a=it("ItemComponent"),l=it("ListComponent"),u=it("ScrollSeekPlaceholder"),d=it("context"),f=Bt("itemDimensions"),h=Bt("gap"),p=it("log"),y=it("stateRestoreInProgress"),w=Bt("reportReadyState"),x=qn(S.useMemo(()=>v=>{const b=v.parentElement.parentElement.scrollHeight;i(b);const C=v.firstChild;if(C){const{height:E,width:k}=C.getBoundingClientRect();f({height:E,width:k})}h({column:Tu("column-gap",getComputedStyle(v).columnGap,p),row:Tu("row-gap",getComputedStyle(v).rowGap,p)})},[i,f,h,p]),!0,!1);return du(()=>{e.itemHeight>0&&e.itemWidth>0&&w(!0)},[e]),y?null:c.jsx(l,{className:t,ref:x,...bt(l,d),"data-testid":"virtuoso-item-list",style:{paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},children:e.items.map(v=>{const b=o(v.index,v.data,d);return s?c.jsx(u,{...bt(u,d),height:e.itemHeight,index:v.index,width:e.itemWidth},b):S.createElement(a,{...bt(a,d),className:n,"data-index":v.index,key:b},r(v.index,v.data,d))})})}),Nv=S.memo(function(){const e=it("HeaderComponent"),t=Bt("headerHeight"),n=it("headerFooterTag"),r=qn(S.useMemo(()=>s=>{t(En(s,"height"))},[t]),!0,!1),o=it("context");return e?c.jsx(n,{ref:r,children:c.jsx(e,{...bt(e,o)})}):null}),Av=S.memo(function(){const e=it("FooterComponent"),t=Bt("footerHeight"),n=it("headerFooterTag"),r=qn(S.useMemo(()=>s=>{t(En(s,"height"))},[t]),!0,!1),o=it("context");return e?c.jsx(n,{ref:r,children:c.jsx(e,{...bt(e,o)})}):null}),_v=({children:e})=>{const t=S.useContext(uu),n=Bt("itemDimensions"),r=Bt("viewportDimensions"),o=qn(S.useMemo(()=>s=>{r(s.getBoundingClientRect())},[r]),!0,!1);return S.useEffect(()=>{t&&(r({height:t.viewportHeight,width:t.viewportWidth}),n({height:t.itemHeight,width:t.itemWidth}))},[t,r,n]),c.jsx("div",{ref:o,style:Ko(!1),children:e})},jv=({children:e})=>{const t=S.useContext(uu),n=Bt("windowViewportRect"),r=Bt("itemDimensions"),o=it("customScrollParent"),s=Mc(n,o,!1);return S.useEffect(()=>{t&&(r({height:t.itemHeight,width:t.itemWidth}),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:t.viewportWidth}))},[t,n,r]),c.jsx("div",{ref:s,style:Ko(!1),children:e})},Rv=S.memo(function({...e}){const t=it("useWindowScroll"),n=it("customScrollParent"),r=n||t?Ov:Pv,o=n||t?jv:_v,s=it("context");return c.jsx(r,{...e,...bt(r,s),children:c.jsxs(o,{children:[c.jsx(Nv,{}),c.jsx(Ev,{}),c.jsx(Av,{})]})})}),{useEmitter:ku,useEmitterValue:it,usePublisher:Bt}=lu(Iv,{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"}},Rv),Pv=gu({useEmitter:ku,useEmitterValue:it,usePublisher:Bt}),Ov=xu({useEmitter:ku,useEmitterValue:it,usePublisher:Bt});function Tu(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,Et.WARN),t==="normal"?0:parseInt(t??"0",10)}const Mv=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 Xi({className:e,variant:t,...n}){return c.jsx("div",{className:re(Mv({variant:t}),e),...n})}function fe(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 Dv(e,t){const n=m.createContext(t),r=s=>{const{children:i,...a}=s,l=m.useMemo(()=>a,Object.values(a));return c.jsx(n.Provider,{value:l,children:i})};r.displayName=e+"Provider";function o(s){const i=m.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 on(e,t=[]){let n=[];function r(s,i){const a=m.createContext(i),l=n.length;n=[...n,i];const u=f=>{var v;const{scope:h,children:p,...y}=f,w=((v=h==null?void 0:h[e])==null?void 0:v[l])||a,x=m.useMemo(()=>y,Object.values(y));return c.jsx(w.Provider,{value:x,children:p})};u.displayName=s+"Provider";function d(f,h){var w;const p=((w=h==null?void 0:h[e])==null?void 0:w[l])||a,y=m.useContext(p);if(y)return y;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[u,d]}const o=()=>{const s=n.map(i=>m.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return m.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,Lv(o,...t)]}function Lv(...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:u})=>{const f=l(s)[`__scope${u}`];return{...a,...f}},{});return m.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var gt=globalThis!=null&&globalThis.document?m.useLayoutEffect:()=>{},Fv=m[" useInsertionEffect ".trim().toString()]||gt;function Yn({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=$v({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const d=m.useRef(e!==void 0);m.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 u=m.useCallback(d=>{var f;if(a){const h=zv(d)?d(e):d;h!==e&&((f=i.current)==null||f.call(i,h))}else s(d)},[a,e,s,i]);return[l,u]}function $v({defaultProp:e,onChange:t}){const[n,r]=m.useState(e),o=m.useRef(n),s=m.useRef(t);return Fv(()=>{s.current=t},[t]),m.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function zv(e){return typeof e=="function"}function Iu(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Ji(...e){return t=>{let n=!1;const r=e.map(o=>{const s=Iu(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():Iu(e[o],null)}}}}function Be(...e){return m.useCallback(Ji(...e),e)}var Bv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],_e=Bv.reduce((e,t)=>{const n=zn.createSlot(`Primitive.${t}`),r=m.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),c.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Eu(e,t){e&&xo.flushSync(()=>e.dispatchEvent(t))}function Hv(e,t){return m.useReducer((n,r)=>t[n][r]??n,e)}var Ot=e=>{const{present:t,children:n}=e,r=Uv(t),o=typeof n=="function"?n({present:r.isPresent}):m.Children.only(n),s=Be(r.ref,Wv(o));return typeof n=="function"||r.isPresent?m.cloneElement(o,{ref:s}):null};Ot.displayName="Presence";function Uv(e){const[t,n]=m.useState(),r=m.useRef(null),o=m.useRef(e),s=m.useRef("none"),i=e?"mounted":"unmounted",[a,l]=Hv(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return m.useEffect(()=>{const u=Xo(r.current);s.current=a==="mounted"?u:"none"},[a]),gt(()=>{const u=r.current,d=o.current;if(d!==e){const h=s.current,p=Xo(u);e?l("MOUNT"):p==="none"||(u==null?void 0:u.display)==="none"?l("UNMOUNT"):l(d&&h!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),gt(()=>{if(t){let u;const d=t.ownerDocument.defaultView??window,f=p=>{const w=Xo(r.current).includes(CSS.escape(p.animationName));if(p.target===t&&w&&(l("ANIMATION_END"),!o.current)){const x=t.style.animationFillMode;t.style.animationFillMode="forwards",u=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=x)})}},h=p=>{p.target===t&&(s.current=Xo(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{d.clearTimeout(u),t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:m.useCallback(u=>{r.current=u?getComputedStyle(u):null,n(u)},[])}}function Xo(e){return(e==null?void 0:e.animationName)||"none"}function Wv(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 Vv=m[" useId ".trim().toString()]||(()=>{}),qv=0;function sn(e){const[t,n]=m.useState(Vv());return gt(()=>{n(r=>r??String(qv++))},[e]),e||(t?`radix-${t}`:"")}var Jo="Collapsible",[Kv,_k]=on(Jo),[Gv,Zi]=Kv(Jo),Nu=m.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:o,disabled:s,onOpenChange:i,...a}=e,[l,u]=Yn({prop:r,defaultProp:o??!1,onChange:i,caller:Jo});return c.jsx(Gv,{scope:n,disabled:s,contentId:sn(),open:l,onOpenToggle:m.useCallback(()=>u(d=>!d),[u]),children:c.jsx(_e.div,{"data-state":ea(l),"data-disabled":s?"":void 0,...a,ref:t})})});Nu.displayName=Jo;var Au="CollapsibleTrigger",_u=m.forwardRef((e,t)=>{const{__scopeCollapsible:n,...r}=e,o=Zi(Au,n);return c.jsx(_e.button,{type:"button","aria-controls":o.contentId,"aria-expanded":o.open||!1,"data-state":ea(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...r,ref:t,onClick:fe(e.onClick,o.onOpenToggle)})});_u.displayName=Au;var Qi="CollapsibleContent",Yv=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Zi(Qi,e.__scopeCollapsible);return c.jsx(Ot,{present:n||o.open,children:({present:s})=>c.jsx(Xv,{...r,ref:t,present:s})})});Yv.displayName=Qi;var Xv=m.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:r,children:o,...s}=e,i=Zi(Qi,n),[a,l]=m.useState(r),u=m.useRef(null),d=Be(t,u),f=m.useRef(0),h=f.current,p=m.useRef(0),y=p.current,w=i.open||a,x=m.useRef(w),v=m.useRef(void 0);return m.useEffect(()=>{const b=requestAnimationFrame(()=>x.current=!1);return()=>cancelAnimationFrame(b)},[]),gt(()=>{const b=u.current;if(b){v.current=v.current||{transitionDuration:b.style.transitionDuration,animationName:b.style.animationName},b.style.transitionDuration="0s",b.style.animationName="none";const C=b.getBoundingClientRect();f.current=C.height,p.current=C.width,x.current||(b.style.transitionDuration=v.current.transitionDuration,b.style.animationName=v.current.animationName),l(r)}},[i.open,r]),c.jsx(_e.div,{"data-state":ea(i.open),"data-disabled":i.disabled?"":void 0,id:i.contentId,hidden:!w,...s,ref:d,style:{"--radix-collapsible-content-height":h?`${h}px`:void 0,"--radix-collapsible-content-width":y?`${y}px`:void 0,...e.style},children:w&&o})});function ea(e){return e?"open":"closed"}var Jv=Nu;const ju=Jv,Ru=_u,Qr=m.forwardRef(({className:e,...t},n)=>c.jsx("div",{ref:n,className:re("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));Qr.displayName="Card";const eo=m.forwardRef(({className:e,...t},n)=>c.jsx("div",{ref:n,className:re("flex flex-col space-y-1.5 p-6",e),...t}));eo.displayName="CardHeader";const to=m.forwardRef(({className:e,...t},n)=>c.jsx("h3",{ref:n,className:re("text-2xl font-semibold leading-none tracking-tight",e),...t}));to.displayName="CardTitle";const Pu=m.forwardRef(({className:e,...t},n)=>c.jsx("p",{ref:n,className:re("text-sm text-muted-foreground",e),...t}));Pu.displayName="CardDescription";const Zo=m.forwardRef(({className:e,...t},n)=>c.jsx("div",{ref:n,className:re("p-6 pt-0",e),...t}));Zo.displayName="CardContent";const Ou=m.forwardRef(({className:e,...t},n)=>c.jsx("div",{ref:n,className:re("flex items-center p-6 pt-0",e),...t}));Ou.displayName="CardFooter";function Mu(){return{async:!1,baseUrl:null,breaks:!1,extensions:null,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,hooks:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1}}let Xn=Mu();function Zv(e){Xn=e}const Du=/[&<>"']/,Qv=new RegExp(Du.source,"g"),Lu=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,ew=new RegExp(Lu.source,"g"),tw={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Fu=e=>tw[e];function St(e,t){if(t){if(Du.test(e))return e.replace(Qv,Fu)}else if(Lu.test(e))return e.replace(ew,Fu);return e}const nw=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function $u(e){return e.replace(nw,(t,n)=>(n=n.toLowerCase(),n==="colon"?":":n.charAt(0)==="#"?n.charAt(1)==="x"?String.fromCharCode(parseInt(n.substring(2),16)):String.fromCharCode(+n.substring(1)):""))}const rw=/(^|[^\[])\^/g;function Qe(e,t){e=typeof e=="string"?e:e.source,t=t||"";const n={replace:(r,o)=>(o=o.source||o,o=o.replace(rw,"$1"),e=e.replace(r,o),n),getRegex:()=>new RegExp(e,t)};return n}const ow=/[^\w:]/g,sw=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function zu(e,t,n){if(e){let r;try{r=decodeURIComponent($u(n)).replace(ow,"").toLowerCase()}catch{return null}if(r.indexOf("javascript:")===0||r.indexOf("vbscript:")===0||r.indexOf("data:")===0)return null}t&&!sw.test(n)&&(n=cw(t,n));try{n=encodeURI(n).replace(/%25/g,"%")}catch{return null}return n}const Qo={},iw=/^[^:]+:\/*[^/]*$/,aw=/^([^:]+:)[\s\S]*$/,lw=/^([^:]+:\/*[^/]*)[\s\S]*$/;function cw(e,t){Qo[" "+e]||(iw.test(e)?Qo[" "+e]=e+"/":Qo[" "+e]=ts(e,"/",!0)),e=Qo[" "+e];const n=e.indexOf(":")===-1;return t.substring(0,2)==="//"?n?t:e.replace(aw,"$1")+t:t.charAt(0)==="/"?n?t:e.replace(lw,"$1")+t:e+t}const es={exec:function(){}};function Bu(e,t){const n=e.replace(/\|/g,(s,i,a)=>{let l=!1,u=i;for(;--u>=0&&a[u]==="\\";)l=!l;return l?"|":" |"}),r=n.split(/ \|/);let o=0;if(r[0].trim()||r.shift(),r.length>0&&!r[r.length-1].trim()&&r.pop(),r.length>t)r.splice(t);else for(;r.length<t;)r.push("");for(;o<r.length;o++)r[o]=r[o].trim().replace(/\\\|/g,"|");return r}function ts(e,t,n){const r=e.length;if(r===0)return"";let o=0;for(;o<r;){const s=e.charAt(r-o-1);if(s===t&&!n)o++;else if(s!==t&&n)o++;else break}return e.slice(0,r-o)}function uw(e,t){if(e.indexOf(t[1])===-1)return-1;const n=e.length;let r=0,o=0;for(;o<n;o++)if(e[o]==="\\")o++;else if(e[o]===t[0])r++;else if(e[o]===t[1]&&(r--,r<0))return o;return-1}function dw(e){e&&e.sanitize&&!e.silent&&console.warn("marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options")}function Hu(e,t){if(t<1)return"";let n="";for(;t>1;)t&1&&(n+=e),t>>=1,e+=e;return n+e}function Uu(e,t,n,r){const o=t.href,s=t.title?St(t.title):null,i=e[1].replace(/\\([\[\]])/g,"$1");if(e[0].charAt(0)!=="!"){r.state.inLink=!0;const a={type:"link",raw:n,href:o,title:s,text:i,tokens:r.inlineTokens(i)};return r.state.inLink=!1,a}return{type:"image",raw:n,href:o,title:s,text:St(i)}}function fw(e,t){const n=e.match(/^(\s+)(?:```)/);if(n===null)return t;const r=n[1];return t.split(`
40
40
  `).map(o=>{const s=o.match(/^\s+/);if(s===null)return o;const[i]=s;return i.length>=r.length?o.slice(r.length):o}).join(`
41
41
  `)}class ta{constructor(t){this.options=t||Xn}space(t){const n=this.rules.block.newline.exec(t);if(n&&n[0].length>0)return{type:"space",raw:n[0]}}code(t){const n=this.rules.block.code.exec(t);if(n){const r=n[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:n[0],codeBlockStyle:"indented",text:this.options.pedantic?r:ts(r,`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "teodor-new-chat-ui",
3
- "version": "4.1.82",
3
+ "version": "4.1.83",
4
4
  "description": "React chat UI components with streaming support, tool calls, and modern design",
5
5
  "main": "dist/index.umd.js",
6
6
  "module": "dist/index.esm.js",