teodor-new-chat-ui 4.3.85 → 4.3.87

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.
File without changes
package/dist/index.esm.js CHANGED
@@ -8593,7 +8593,7 @@ function Xd(e) {
8593
8593
  }
8594
8594
  function wo(e) {
8595
8595
  if (typeof e == "string")
8596
- return e.length > 2e3 ? e.slice(0, 2e3) + "... [truncated]" : e;
8596
+ return e;
8597
8597
  if (e && typeof e == "object") {
8598
8598
  if (Array.isArray(e)) {
8599
8599
  const n = e.map(wo).filter((r) => r !== void 0);
@@ -11671,7 +11671,7 @@ const ru = U.memo(function({
11671
11671
  if (ne)
11672
11672
  return te(
11673
11673
  ie,
11674
- "w-full md:max-w-[95%]",
11674
+ "w-full",
11675
11675
  "bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]",
11676
11676
  "border border-border/60 dark:border-border/40 shadow-sm"
11677
11677
  );
@@ -12321,7 +12321,7 @@ const ou = (e, t) => (e == null ? void 0 : e.id) ?? `message-${t}`, Bf = U.forwa
12321
12321
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
12322
12322
  } : null;
12323
12323
  }, [p]);
12324
- return L.length === 0 ? fe ? /* @__PURE__ */ u.jsx("div", { className: f, style: h, children: /* @__PURE__ */ u.jsx("div", { className: "p-6 overflow-y-auto h-full flex items-start justify-center", children: /* @__PURE__ */ u.jsx("div", { className: "w-full max-w-2xl", children: /* @__PURE__ */ u.jsx(
12324
+ return L.length === 0 ? fe ? /* @__PURE__ */ u.jsx("div", { className: f, style: h, children: /* @__PURE__ */ u.jsx("div", { className: "p-6 overflow-y-auto h-full flex items-start justify-center", children: /* @__PURE__ */ u.jsx("div", { className: "w-full max-w-full", children: /* @__PURE__ */ u.jsx(
12325
12325
  ru,
12326
12326
  {
12327
12327
  message: fe,
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=ar(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&Uo.assertOptions(r,{silentJSONParsing:wn.transitional(wn.boolean),forcedJSONParsing:wn.transitional(wn.boolean),clarifyTimeoutError:wn.transitional(wn.boolean)},!1),o!=null&&(O.isFunction(o)?n.paramsSerializer={serialize:o}:Uo.assertOptions(o,{encode:wn.function,serialize:wn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Uo.assertOptions(n,{baseUrl:wn.spelling("baseURL"),withXsrfToken:wn.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"],g=>{delete s[g]}),n.headers=Bt.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(y){typeof y.runWhen=="function"&&y.runWhen(n)===!1||(l=l&&y.synchronous,a.unshift(y.fulfilled,y.rejected))});const c=[];this.interceptors.response.forEach(function(y){c.push(y.fulfilled,y.rejected)});let d,f=0,h;if(!l){const g=[lc.bind(this),void 0];for(g.unshift(...a),g.push(...c),h=g.length,d=Promise.resolve(n);f<h;)d=d.then(g[f++],g[f++]);return d}h=a.length;let p=n;for(;f<h;){const g=a[f++],y=a[f++];try{p=g(p)}catch(v){y.call(this,v);break}}try{d=lc.call(this,p)}catch(g){return Promise.reject(g)}for(f=0,h=c.length;f<h;)d=d.then(c[f++],c[f++]);return d}getUri(t){t=ar(this.defaults,t);const n=Jl(t.baseURL,t.url,t.allowAbsoluteUrls);return Hl(n,t.params,t.paramsSerializer)}};O.forEach(["delete","get","head","options"],function(t){lr.prototype[t]=function(n,r){return this.request(ar(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(ar(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}lr.prototype[t]=n(),lr.prototype[t+"Form"]=n(!0)});let Gg=class km{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 Nr(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 km(function(o){t=o}),cancel:t}}};function Yg(e){return function(n){return e.apply(null,n)}}function Xg(e){return O.isObject(e)&&e.isAxiosError===!0}const Ti={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(Ti).forEach(([e,t])=>{Ti[t]=e});function dc(e){const t=new lr(e),n=Il(lr.prototype.request,t);return O.extend(n,lr.prototype,t,{allOwnKeys:!0}),O.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return dc(ar(e,o))},n}const gt=dc(Jr);gt.Axios=lr,gt.CanceledError=Nr,gt.CancelToken=Gg,gt.isCancel=Kl,gt.VERSION=cc,gt.toFormData=Fo,gt.AxiosError=_e,gt.Cancel=gt.CanceledError,gt.all=function(t){return Promise.all(t)},gt.spread=Yg,gt.isAxiosError=Xg,gt.mergeConfig=ar,gt.AxiosHeaders=Bt,gt.formToJSON=e=>Vl(O.isHTMLForm(e)?new FormData(e):e),gt.getAdapter=ac.getAdapter,gt.HttpStatusCode=Ti,gt.default=gt;const{Axios:Jk,AxiosError:Zk,CanceledError:Qk,isCancel:eT,CancelToken:tT,VERSION:nT,all:rT,Cancel:oT,isAxiosError:sT,spread:iT,toFormData:aT,AxiosHeaders:lT,HttpStatusCode:cT,formToJSON:uT,getAdapter:dT,mergeConfig:fT}=gt,fc=typeof window<"u"?window.__API_BASE_URL__:void 0,hc=fc?$n(fc):void 0;function $n(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let Wo=null;const Ei=new Set;function pc(){return Wo}function Ii(e){Wo=e,Ei.forEach(t=>t(e))}function mc(e){return Ei.add(e),()=>Ei.delete(e)}const Zt=gt.create({...hc?{baseURL:hc}:{},timeout:3e4,withCredentials:!0});Zt.interceptors.request.use(e=>(Wo&&(e.headers.Authorization=`Bearer ${Wo}`),e)),Zt.interceptors.response.use(e=>e,e=>Promise.reject(e));async function cn(e,t){return Zt.defaults.baseURL?(await Zt.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function Ai(e,t,n){return Zt.defaults.baseURL?(await Zt.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function gc(e,t,n){return Zt.defaults.baseURL?(await Zt.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function xc(e,t){return Zt.defaults.baseURL?(await Zt.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function un(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class yc{get baseUrl(){const t=Zt.defaults.baseURL;return t?$n(String(t)):""}updateConfig(t){t.baseUrl&&(Zt.defaults.baseURL=$n(String(t.baseUrl))),t.authToken!==void 0&&Ii(t.authToken)}getAuthToken(){return pc()}setAuthToken(t){Ii(t)}onTokenChange(t){return mc(t)}async listThreads(){const t=await cn("/threads"),n=un(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await Ai("/threads",t?{title:t}:void 0);return un(r)}async updateThread(t,n){const r=await gc(`/threads/${t}`,{title:n});return un(r)}async deleteThread(t){const n=await xc(`/threads/${t}`);return un(n)}async threadInfo(t){const n=await cn(`/threads/${t}/info`);return un(n)}async listAgents(){const t=await cn("/agents"),n=un(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await cn(`/agents/${t}`);return un(n)}async getAgentSchema(t){const n=await cn(`/agents/${t}/schema`);return un(n)}async getState(t){const n=await cn(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return un(n)}async getStateHistory(t){const n=await cn(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return un(n)}async cancelRun(t){const n=await Ai("/runs/cancel",{threadId:t});return un(n)}}const Wn=new yc,vc=w.createContext(null);function Jg({children:e,apiConfig:t}){const n=Wn;if(t){const o=n.baseUrl,s=n.getAuthToken();t.baseUrl&&t.baseUrl!==o&&n.updateConfig({baseUrl:t.baseUrl}),t.apiKey!==void 0&&t.apiKey!==s&&n.updateConfig({authToken:t.apiKey})}const r={token:n.getAuthToken(),setToken:o=>n.setAuthToken(o),api:n,baseUrl:n.baseUrl};return u.jsx(vc.Provider,{value:r,children:e})}function Ni(){const e=w.useContext(vc);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function Zg(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 Qg(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const c=await Zg(l);a.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const ex={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function _i(e){if(!e||typeof e!="object")return!1;const t=e;return"values"in t&&"config"in t&&typeof t.values=="object"&&t.values!==null&&typeof t.config=="object"&&t.config!==null}function Qr(e,t){return`${e??""}::${t??""}`}function ji(e){const t=Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[],n=(e==null?void 0:e.threadId)??"",r=t[0];if(!_i(r))return{threadId:n,latest:null,checkpoints:[],interrupt:null,snapshots:{}};const{orderedSnapshots:o,snapshotMap:s}=nx(t),i=bc(r,0);return{threadId:n,latest:i,checkpoints:o,interrupt:(i==null?void 0:i.interrupt)??null,snapshots:s}}function bc(e,t){if(!_i(e))return null;const n=e.values??{messages:[]},r=Array.isArray(n==null?void 0:n.messages)?n.messages:[],{messages:o,...s}=n,i=Object.keys(s).length?s:null,a=e.tasks,l=Array.isArray(a)?a.filter(j=>!!j&&typeof j=="object").map(j=>({...j})):a===null?null:void 0,c=r.map((j,D)=>cx(j,D)).filter(j=>!!j),d=Ht(e.config),f=Ht(d==null?void 0:d.configurable),h=pt(f,["checkpoint_id","checkpointId"]),p=pt(f,["checkpoint_ns","checkpointNs"]),g=Ht(e==null?void 0:e.parentConfig),y=Ht(g==null?void 0:g.configurable),v=pt(y,["checkpoint_id","checkpointId"])??null,x=pt(y,["checkpoint_ns","checkpointNs"])??null,b=e==null?void 0:e.createdAt,S=typeof b=="string"&&b.trim()?b:new Date(Date.now()-t).toISOString(),T=c[c.length-1]??null,k=Ht(e==null?void 0:e.metadata),C=pt(k,["branch_label","branchLabel"]),E=pt(y,["checkpoint_id","checkpointId"]),_=Array.isArray(e.next)?[...e.next]:(e==null?void 0:e.next)===null?null:void 0;return{messages:c,checkpointId:h??null,checkpointNs:p??null,nextCursor:v,nextCursorNs:x,interrupt:tx(a,c,t),createdAt:S,parentId:E??null,branchLabel:C??null,lastMessageId:(T==null?void 0:T.id)??null,hasMessages:c.length>0,messagesLen:c.length,metadata:k??null,config:d??null,parentConfig:g??null,next:_??null,tasks:l??null,values:i??null}}function tx(e,t,n){const r=ax(e,n);return r||ix(t,n)}function nx(e){const t=new Map;e.forEach((o,s)=>{if(!_i(o))return;const i=bc(o,s);if(!(i!=null&&i.checkpointId))return;const a=Qr(i.checkpointId,i.checkpointNs??null),l=t.get(a);if(!l){t.set(a,i);return}t.set(a,rx(l,i))});const n=Array.from(t.values());n.sort((o,s)=>Sc(s.createdAt??"")-Sc(o.createdAt??""));const r={};for(const[o,s]of t.entries())r[o]=s;return{orderedSnapshots:n,snapshotMap:r}}function rx(e,t){return{...e,metadata:Vo(e.metadata,t.metadata)??null,config:Vo(e.config,t.config)??null,parentConfig:Vo(e.parentConfig,t.parentConfig)??null,next:ox(e.next,t.next)??null,tasks:sx(e.tasks,t.tasks)??null,values:Vo(e.values,t.values)??null}}function Vo(e,t){return t&&typeof t=="object"?{...e&&typeof e=="object"?e:{},...t}:t===null?e&&typeof e=="object"?{...e}:e??null:e&&typeof e=="object"?{...e}:e??void 0}function ox(e,t){return Array.isArray(t)?t.slice():t===null?Array.isArray(e)?e.slice():e??null:Array.isArray(e)?e.slice():e??void 0}function sx(e,t){return Array.isArray(t)?t.map(n=>({...n})):t===null?Array.isArray(e)?e.map(n=>({...n})):e??null:Array.isArray(e)?e.map(n=>({...n})):e??void 0}function ix(e,t){var n;for(let r=e.length-1;r>=0;r--){const o=((n=e[r])==null?void 0:n.content)??[];for(let s=o.length-1;s>=0;s--){const i=o[s];if((i==null?void 0:i.type)==="interrupt"){const a=i;return{id:typeof a.id=="string"&&a.id.trim()?a.id:`interrupt-${t}-${r}-${s}`,value:a.value}}}}return null}function ax(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=lx(e[n],`task-${t}-${n}`);if(!r)continue;const o=r.id||`task-${t}-${n}`;if(Array.isArray(r.interrupts)&&r.interrupts.length)for(let s=r.interrupts.length-1;s>=0;s--){const i=eo(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=eo(r.state,`${o}-state`);if(s)return s}}return null}function lx(e,t){if(!e)return null;if(Array.isArray(e)){const[a,l,c,,d,,f,...h]=e,p=typeof a=="string"&&a.trim()?a:t,g=typeof l=="string"&&l.trim()?l:Array.isArray(c)&&typeof c[0]=="string"?String(c[0]):"task",y=Array.isArray(d)?d:void 0,v=h.length?h[h.length-1]:void 0;return{id:p,name:g,interrupts:y,state:v!==void 0?v:f}}const n=Ht(e);if(!n)return null;const r=pt(n,["id","task_id","taskId"])??t,o=pt(n,["name"])??"task",s=Array.isArray(n.interrupts)?n.interrupts:void 0,i=Object.prototype.hasOwnProperty.call(n,"state")?n.state:void 0;return{id:r,name:o,interrupts:s,state:i}}function eo(e,t,n=0,r=new Set){if(n>6||e==null)return null;if(typeof e=="object"){if(r.has(e))return null;r.add(e)}const o=wc(e,t);if(o)return o;if(Array.isArray(e)){for(let s=e.length-1;s>=0;s--){const i=eo(e[s],t,n+1,r);if(i)return i}return null}if(typeof e=="object"){const s=e,i=["interrupt","pending_interrupt","pendingInterrupt","value","data","payload","result","response"];for(const a of i)if(a in s){const l=eo(s[a],t,n+1,r);if(l)return l}for(const[a,l]of Object.entries(s)){if(i.includes(a)||a==="messages"||a==="results")continue;const c=eo(l,t,n+1,r);if(c)return c}}return null}function wc(e,t){if(!e)return null;if(typeof e=="object"&&!Array.isArray(e)){const n=e,r=pt(n,["type","event","kind"]),o=pt(n,["id","interrupt_id","interruptId","value_id"])??(r&&r.toLowerCase().includes("interrupt")?t:void 0);if(!(Object.prototype.hasOwnProperty.call(n,"value")||Object.prototype.hasOwnProperty.call(n,"data")||Object.prototype.hasOwnProperty.call(n,"payload"))&&!(r&&r.toLowerCase().includes("interrupt")))return null;const i=Object.prototype.hasOwnProperty.call(n,"value")?n.value:Object.prototype.hasOwnProperty.call(n,"data")?n.data:Object.prototype.hasOwnProperty.call(n,"payload")?n.payload:n,a=o&&o.trim()?o:t;return a?{id:a,value:i}:null}if(Array.isArray(e)){for(let n=e.length-1;n>=0;n--){const r=wc(e[n],t);if(r)return r}return e.length>=2&&typeof e[0]=="string"&&e[0].trim()?{id:e[0],value:e[1]}:null}if(typeof e=="string"){const n=e.trim();return n?{id:t||n,value:n}:null}return null}function Sc(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function cx(e,t){if(!e||typeof e!="object")return null;const n=e,r=Ht(e)??{},o=Ht(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=ex[s];if(!i)return null;const a=o.id??o.message_id??o.run_id??null,l=typeof a=="string"&&a.trim()?a:`history-${i}-${t}`,c=Ht(o.additional_kwargs)??Ht(o.additionalKwargs),d=Ht(o.response_metadata)??Ht(o.responseMetadata),f=pt(c,["createdAt","created_at"])??pt(o,["created_at","createdAt"]),h=pt(c,["checkpointId","checkpoint_id"]),p=pt(c,["checkpointNs","checkpoint_ns"]),g=ux(o.content),y={id:l,role:i,content:g};f&&(y.createdAt=f),typeof o.name=="string"&&o.name.trim()&&(y.name=o.name),typeof(d==null?void 0:d.model_name)=="string"&&(y.model=String(d.model_name)),!y.model&&typeof o.model=="string"&&(y.model=o.model),h&&(y.checkpointId=h),p&&(y.checkpointNs=p);const v=mx(c,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),x=d?{...d}:void 0;v&&Object.keys(v).length&&(y.additionalKwargs=v),x&&Object.keys(x).length&&(y.responseMetadata=x);const b=dx((c==null?void 0:c.tool_calls)??o.tool_calls);if(b.length&&(y.content=[...y.content,...b]),i==="tool"){const S=fx(o,y.content);S&&(y.content=S)}return y}function ux(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>Cc(t)).filter(t=>!!t);if(typeof e=="string")return e.trim()?[{type:"text",text:e.trim()}]:[];if(typeof e=="object"){const t=Cc(e);return t?[t]:[]}return[]}function Cc(e){if(!e||typeof e!="object")return typeof e=="string"&&e.trim()?{type:"text",text:e}:null;const t=e,n=String(t.type??"").toLowerCase();if(!n||n==="text"){const o=typeof t.text=="string"?t.text:typeof t.value=="string"?t.value:"";return o.trim()?{type:"text",text:o}:null}if(n==="image"||n==="image_url"){const o=pt(t,["url","src"]);if(!o)return null;const s={type:"image_url",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.alt=="string"&&(s.alt=t.alt),s}if(n==="file"){const o=pt(t,["url"]);if(!o)return null;const s={type:"file",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.name=="string"&&(s.name=t.name),typeof t.size=="number"&&(s.size=t.size),typeof t.sourceType=="string"&&(s.sourceType=t.sourceType),s}if(n==="tool_call")return kc(t)??null;if(n==="tool_end"){const o=pt(t,["tool_call_id","toolCallId","id"]);if(!o)return null;const s={type:"tool_end",toolCallId:o,output:"output"in t?t.output:t.content};return typeof t.error=="string"&&(s.error=t.error),s}if(n==="interrupt")return{type:"interrupt",value:t.value,...t};if(n==="tool"){const o=pt(t,["text","content"]);if(o)return{type:"text",text:o}}const r=typeof t.content=="string"?t.content:typeof t.value=="string"?t.value:JSON.stringify(t);return r?{type:"text",text:r}:null}function kc(e,t){var s;const n=pt(e,["id","call_id"])??t,r=pt(e,["name"])??pt(Ht(e.function),["name"]);if(!n||!r)return null;const o=hx(e.args??e.arguments??((s=Ht(e.function))==null?void 0:s.arguments));return{type:"tool_call",id:n,name:r,args:o}}function dx(e){return Array.isArray(e)?e.map((t,n)=>kc(t,`tool_call_${n}`)).filter(t=>!!t):[]}function fx(e,t){const n=pt(e,["tool_call_id","toolCallId","id"]);if(!n)return t;const r=e.content??e.output,o=typeof r=="string"?px(r):r,s={type:"tool_end",toolCallId:n,output:o};return typeof e.error=="string"&&(s.error=e.error),[...t,s]}function hx(e){if(!e)return{};if(typeof e=="string")try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{raw:e}}catch{return{raw:e}}return typeof e=="object"&&!Array.isArray(e)?{...e}:{}}function px(e){try{return JSON.parse(e)}catch{return e}}function Ht(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function pt(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r}}function mx(e,t){if(!e)return;const n={};let r=!1;for(const[o,s]of Object.entries(e)){if(t.includes(o)){r=!0;continue}s!==void 0&&(n[o]=s)}return r?Object.keys(n).length?n:void 0:e}function gx(e){return e.type!=="thread_info"&&e.type!=="token"}const xx={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,messagesStreamMeta:{},pendingInterrupt:null};function yx(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:Ri(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,pendingInterrupt:null};return console.log("[MessageReducer] 📊 After reset - messages count:",r.messages.length),r}case"seed":{const r=Ri(t.payload.messages),o={...e,messages:r,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(o.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(o.lastCheckpointNs=t.payload.checkpointNs??null),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=Ri(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 Ec(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>Ec(o,s),e):e}case"interrupt_response":return{...e,messages:Ac(e.messages),pendingInterrupt:null};default:return e}}function Tc(e=[]){const[t,n]=w.useReducer(yx,{...xx,messages:e}),r=w.useRef([]),o=w.useRef(null),s=w.useRef(null),i=w.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=w.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=w.useCallback(d=>{r.current.push(d),a()},[a]);w.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const c=w.useMemo(()=>({reset:d=>n({type:"reset",payload:{messages:d}}),seed:(d,f)=>n({type:"seed",payload:{messages:d,...f??{}}}),prepend:d=>n({type:"prepend",payload:{messages:d}}),pushUser:d=>n({type:"user_message",payload:{message:d}}),onEvent:l}),[l]);return{state:t,dispatch:n,...c}}function Ec(e,t){var n,r,o,s;if(t.type==="message_start"&&t.role==="assistant"){const i=t.id,a=kx(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 c={id:i,role:"assistant",name:a||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:i,messages:[...e.messages,c]}}if(t.type==="message_delta"){const i=e.assemblingId??Nc(e.messages);if(!i)return e;const a=e.messages,l=a.findIndex(S=>S.id===i&&S.role==="assistant");if(l===-1)return e;const c=a[l],d=e.messagesStreamMeta??{},f=d[i]??{lastSeq:null,lastText:_c(c.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:g,changed:y}=Sx(c.content,t.delta,f,h);if(!y)return e;const v={...c,content:p},x=Ic(a,l,v),b={...d,[i]:g};return{...e,messages:x,messagesStreamMeta:b}}if(t.type==="message_end"){const i=e.assemblingId??Nc(e.messages);if(!i)return{...e,assemblingId:null};const a=e.messages,l=a.findIndex(c=>c.id===i&&c.role==="assistant");if(l>=0){const c=a[l];if(!((n=c.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:c.id,contentTypes:(r=c.content)==null?void 0:r.map(h=>h==null?void 0:h.type),contentPreview:(o=c.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}`,c={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:[c]};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},c=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=c?bx(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=Cx(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==="state_history"){const i=ji(t),a=i.interrupt,l=i.latest,c=a===null?Ac(e.messages):e.messages;return{...e,messages:c,pendingInterrupt:a,lastCheckpointId:(l==null?void 0:l.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(l==null?void 0:l.checkpointNs)??e.lastCheckpointNs}}return e}function Ri(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 Ic(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function Ac(e){let t=!1;const n=e.map(r=>{const o=(r.content??[]).filter(s=>s.type!=="interrupt");return o.length!==r.content.length?(t=!0,{...r,content:o}):r});return t?n:e}function Nc(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function vx(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 bx(e,t,n){return vx(e,t,r=>({...r,content:wx(r.content,n)}))}function wx(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 c=i(s),d=i(l);if(c.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(c.includes(d)){console.debug("[MessageReducer] incoming includes previous (normalized) - replacing",{incomingLength:s.length,previousLength:l.length}),a.text=s;continue}if(d.includes(c)&&c.length<=3){console.debug("[MessageReducer] previous includes incoming (normalized) - skipping trivial incoming",{incomingLength:s.length,previousLength:l.length});continue}const h=Rc(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 _c(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function Sx(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??_c(e);let l="",c=e.slice();if(s){const f=Rc(a,s);if(f===""?l="":f===s?l=s:l=f,l){const h=c[c.length-1];if((h==null?void 0:h.type)==="text"){const p=h.text??"",g={...h,text:p+l};c=[...c.slice(0,c.length-1),g]}else c=[...c,{type:"text",text:l}];o.lastText=a+l}else o.lastText=a}i.length&&(c=[...c,...i]);const d=!!(l||i.length);return{newParts:c,newMeta:o,changed:d}}function jc(e){return e.replace(/\s+/g," ").trim()}function Rc(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=jc(e),o=jc(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 Cx(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 Ic(e,r,s)}return e}function kx(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}function Pc(e={}){const t=w.useMemo(()=>$n(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=w.useState(e.token??null),s=w.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=w.useState(!1),[c,d]=w.useState(null),[f,h]=w.useState(""),[p,g]=w.useState(null),[y,v]=w.useState(0),[x,b]=w.useState(!1),S=w.useRef(null),T=w.useRef(!0),k=w.useRef(0),C=w.useRef(null),E=w.useCallback($=>{o($)},[]),_=w.useCallback(()=>{h(""),g(null),d(null)},[]),j=w.useCallback(()=>{var $;console.debug("[use-chat] stop() invoked - aborting stream"),($=S.current)==null||$.abort(),S.current=null,C.current=null,l(!1),b(!1),k.current=0,v(0)},[]),D=w.useCallback(($,K,P)=>{S.current&&(S.current.abort(),S.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&h("");const R=new AbortController;return S.current=R,C.current={threadId:$.threadId??null,headers:{}},(async()=>{var F,ne,q,B,pe,W,ce,H,Z;const L=be=>{var ye;try{const G=JSON.parse(JSON.stringify(be));return(ye=G==null?void 0:G.payload)!=null&&ye.files_info&&Array.isArray(G.payload.files_info)&&(G.payload.files_info=G.payload.files_info.map(M=>({...M,data:M!=null&&M.data?`<base64 ${String(M.data).length} chars>`:M==null?void 0:M.data}))),G}catch{return be}};try{let be={};try{if(r)be={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const lt=window.__AUTH_TOKEN__,yt=((F=window.localStorage)==null?void 0:F.getItem("authToken"))||null;let dt=null;try{const ie=(ne=window.localStorage)==null?void 0:ne.getItem("chat-settings");ie&&(dt=((q=JSON.parse(ie))==null?void 0:q.apiKey)||null)}catch{}const Je=lt||yt||dt||null;Je&&(be={Authorization:`Bearer ${Je}`})}}catch{}console.debug("[use-chat] POST",t+n,L($));let ye={};if(typeof window<"u")try{const We=(B=window.localStorage)==null?void 0:B.getItem("authSessionId");We&&(ye={"X-Session-Id":We})}catch{}const G={...be,...ye,...s.current},M={"Content-Type":"application/json",Accept:"text/event-stream",...G},X=await fetch(t+n,{method:"POST",headers:M,body:JSON.stringify($),signal:R.signal,credentials:i});if(C.current&&(C.current.headers=G),!X.ok||!X.body){const We=await X.text().catch(()=>"");throw console.debug("[use-chat] non-OK response",X.status,We==null?void 0:We.slice(0,500)),new Error(`stream ${X.status}${We?": "+We:""}`)}b(!0);const oe=X.body.getReader(),xe=new TextDecoder;let se="",re=[];k.current=0,v(0);let Ue=0,qe=null;const ot=()=>{if(re.length){const We=re.join("");re=[],T.current&&h(lt=>lt+We)}qe=null},at=()=>{typeof window<"u"&&qe==null&&(qe=requestAnimationFrame(ot))};let ht=Date.now();const tt=setInterval(()=>{var We;if(Date.now()-ht>6e4){const lt="Stream idle timeout";d(lt),R.abort(),(We=P==null?void 0:P.onError)==null||We.call(P,lt)}},5e3),Me=1024*1024;try{const We=X.headers.get("X-Thread-Id")||X.headers.get("x-thread-id"),lt=X.headers.get("X-Thread-Created")||X.headers.get("x-thread-created"),yt=We??null,dt=String(lt??"").toLowerCase()==="true";for(C.current&&!C.current.threadId&&(C.current={...C.current,threadId:yt}),(pe=P==null?void 0:P.onOpen)==null||pe.call(P,{threadId:yt,created:dt});;){const{value:Je,done:ie}=await oe.read();if(ie)break;se+=xe.decode(Je,{stream:!0}),se.length>Me&&(se="",console.warn("Stream buffer reset: exceeded 1MB"));let je;for(;(je=se.indexOf(`
36
36
 
37
37
  `))>=0;){const ke=se.slice(0,je);se=se.slice(je+2);const Ke=Ex(ke);if(!Ke)continue;let nt;try{nt=JSON.parse(Ke)}catch{console.debug("[use-chat] malformed SSE:",Ke.slice(0,200));continue}const Oe=Tx(nt)?nt.data:nt;ht=Date.now();const Xe=Oe.seq;if(Xe!==void 0){if(Xe<=Ue){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:Xe,lastProcessedSeq:Ue,type:Oe.type});continue}Ue>0&&Xe>Ue+1&&((W=P==null?void 0:P.onGap)==null||W.call(P,{from:Ue,to:Xe})),Ue=Xe,k.current=Xe,v(Xe)}console.debug("[use-chat] received event",{seq:Oe.seq,type:Oe.type,preview:(()=>{var Tt;try{return Oe.type==="message_delta"?{deltaTypes:(Tt=Oe.delta)==null?void 0:Tt.map(St=>St.type),textLen:(Oe.delta||[]).filter(St=>St.type==="text").map(St=>String(St.text||"").length)}:Oe.content||Oe.delta?{hasContent:!0}:{}}catch(St){return{err:String(St)}}})()});try{K==null||K(Oe)}catch(Tt){console.error("[use-chat] Error in onEvent callback:",Tt,"for event:",Oe.type)}if(Oe.type==="token"&&e.autoAppendAssistant!==!1)re.push(Oe.content),at();else if(Oe.type==="message_delta"){const Tt=Oe.delta.filter(St=>St.type==="text").map(St=>St.text).join("");Tt&&e.autoAppendAssistant!==!1&&(re.push(Tt),at())}else Oe.type==="heartbeat"?console.debug("[use-chat] heartbeat received"):(qe!==null&&cancelAnimationFrame(qe),ot(),Oe.type==="checkpoint"?g(Oe.checkpointId):Oe.type==="error"&&d(Oe.message))}}ot()}catch(We){if(We.name!=="AbortError"){const lt=We.message||String(We);d(lt),(ce=P==null?void 0:P.onError)==null||ce.call(P,lt)}}finally{try{await oe.cancel()}catch{}finally{(H=oe.releaseLock)==null||H.call(oe)}qe!==null&&typeof window<"u"&&window.cancelAnimationFrame(qe),clearInterval(tt),l(!1),b(!1),S.current=null,k.current=0,v(0),C.current=null}}catch(be){if(be.name!=="AbortError"){const ye=be.message||String(be);d(ye),(Z=P==null?void 0:P.onError)==null||Z.call(P,ye)}}finally{l(!1),b(!1),S.current=null,k.current=0,v(0),C.current=null}})(),{close:()=>R.abort()}},[t,n,r,e.autoAppendAssistant]);return w.useEffect(()=>()=>{var $;T.current=!1,($=S.current)==null||$.abort()},[]),{isStreaming:a,error:c,assistantText:f,lastCheckpointId:p,lastSeq:y,connected:x,stream:D,stop:j,clear:_,setToken:E}}function Tx(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function Ex(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 Ix({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onUnhandledEvent:r,onSequenceGap:o}){const s=w.useRef(null),i=w.useCallback(p=>{const g=p.seq??null;if(g!==null){const y=s.current;if(y!==null){if(g<=y)return;g>y+1&&(o==null||o({from:y,to:g}))}s.current=g}if(p.type==="thread_info"){console.log("[useChatStreamingService] 🎯 Received thread_info event:",p);try{t(p)}catch(y){console.error("[useChatStreamingService] Error in onThreadInfo handler:",y)}return}if(gx(p)){try{n(p)}catch(y){console.error("[useChatStreamingService] Error in onMessageEvent handler:",y)}return}try{r==null||r(p)}catch(y){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",y)}},[n,o,t,r]),{stream:a,stop:l,isStreaming:c,error:d,setToken:f}=Pc({baseUrl:e,token:null}),h=w.useCallback((p,g)=>{s.current=null,a(p,i,{onOpen:g==null?void 0:g.onOpen,onError:y=>{var v;(v=g==null?void 0:g.onError)==null||v.call(g,y)},onGap:(g==null?void 0:g.onGap)??o})},[i,o,a]);return w.useMemo(()=>({startStream:h,stop:l,isStreaming:c,error:d,setAuthToken:f}),[h,l,c,d,f])}function Pi(e){return e==null?e:{...e}}function Ax(e){return e==null?e:{...e}}function Nx(e){if(Array.isArray(e))return e.slice();if(e==null)return e}function _x(e){if(Array.isArray(e))return e.map(t=>({...t}));if(e==null)return e}function Qt(e,t={}){const n=t.cloneMessages??!1,r=Array.isArray(e==null?void 0:e.messages)?e.messages:[],o=Pi(e==null?void 0:e.metadata),s=Pi(e==null?void 0:e.config),i=Pi(e==null?void 0:e.parentConfig),a=Nx(e==null?void 0:e.next),l=_x(e==null?void 0:e.tasks),c=Ax(e==null?void 0:e.values),d={checkpointId:(e==null?void 0:e.checkpointId)??null,checkpointNs:(e==null?void 0:e.checkpointNs)??null,createdAt:(e==null?void 0:e.createdAt)??null,parentId:(e==null?void 0:e.parentId)??null,branchLabel:(e==null?void 0:e.branchLabel)??null,lastMessageId:(e==null?void 0:e.lastMessageId)??null,messagesLen:typeof(e==null?void 0:e.messagesLen)=="number"?e.messagesLen:r.length,hasMessages:typeof(e==null?void 0:e.hasMessages)=="boolean"?e.hasMessages:r.length>0,messages:n?r.slice():r,nextCursor:(e==null?void 0:e.nextCursor)??null,nextCursorNs:(e==null?void 0:e.nextCursorNs)??null,interrupt:(e==null?void 0:e.interrupt)??null};return o!==void 0&&(d.metadata=o),s!==void 0&&(d.config=s),i!==void 0&&(d.parentConfig=i),a!==void 0&&(d.next=a),l!==void 0&&(d.tasks=l),c!==void 0&&(d.values=c),d}function jx(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 Oc(e,t){if(!e&&!t)return!0;if(!e||!t||e.id!==t.id)return!1;try{return JSON.stringify(e.value)===JSON.stringify(t.value)}catch{return e.value===t.value}}const qo=300;function Mc(e,t=qo){if(typeof window<"u"&&"requestIdleCallback"in window)try{window.requestIdleCallback(e,{timeout:t});return}catch{}window.setTimeout(e,t)}function cr(){return typeof window<"u"&&typeof window.localStorage<"u"}function Oi(e){if(!cr())return null;try{return window.localStorage.getItem(e)}catch{return null}}function Mi(e,t){if(!cr())return!1;try{return window.localStorage.setItem(e,t),!0}catch{return!1}}function Di(e){if(cr())try{window.localStorage.removeItem(e)}catch{}}const Rx="cachedThreads",Px="v1",Li=200;function Ox(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 Fi(e,t){return`cachedThreads:v1:${e}:${Ox(t||"anon")}`}function Mx(){const e=Oi(Rx);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 Dx(e){const t=Oi(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 $i(e,t){Mi(e,JSON.stringify(t))}function zi(e){const t=Dx(e);if(t.length>0)return t;const n=Mx();if(n.length>0)try{$i(e,n.slice(0,Li))}catch{}return n}function Ko(e){const t={},n=[];for(const r of e)!r||typeof r.threadId!="string"||t[r.threadId]||(t[r.threadId]=r,n.push(r.threadId));return{byId:t,order:n}}function Bi(e){return e.order.map(t=>e.byId[t]).filter(Boolean)}function Hi(e,t){return`${e}${t}`}function Lx(e,t){const n=Oi(Hi(e,t));if(!n)return null;try{const r=JSON.parse(n);return typeof(r==null?void 0:r.threadId)!="string"?null:{threadId:r.threadId,snapshot:Qt(r.snapshot,{cloneMessages:!0}),updatedAt:typeof r.updatedAt=="number"?r.updatedAt:void 0}}catch{return null}}function Fx(e,t,n=100){if(!cr())return;const r=Qt(t.snapshot,{cloneMessages:!0}),o={threadId:t.threadId,snapshot:{...r,messages:r.messages.slice(-n)},updatedAt:Date.now()},s=Hi(e,t.threadId),i=JSON.stringify(o);if(!Mi(s,i))try{const a=[];for(let l=0;l<window.localStorage.length;l++){const c=window.localStorage.key(l);if(!c||c===s||!c.startsWith(e))continue;const d=window.localStorage.getItem(c);if(!d){a.push({key:c,updatedAt:0});continue}try{const f=JSON.parse(d),h=typeof(f==null?void 0:f.updatedAt)=="number"&&Number.isFinite(f.updatedAt)?f.updatedAt:0;a.push({key:c,updatedAt:h})}catch{a.push({key:c,updatedAt:0})}}a.sort((l,c)=>l.updatedAt-c.updatedAt);for(const l of a)if(window.localStorage.removeItem(l.key),Mi(s,i))break}catch{}}function $x(e,t){Di(Hi(e,t))}function zx(e){if(cr())try{for(let t=0;t<window.localStorage.length;t++){const n=window.localStorage.key(t);n&&n.startsWith(e)&&window.localStorage.removeItem(n)}}catch{}}const Dc=w.createContext(null),Lc=w.createContext(null),Fc=w.createContext(null),Bx=w.createContext(!1),$c=50,Hx=750;function zc(e,t,n){return`${e}__${t??""}__${n??""}`}function Go(e,t){return t&&typeof t=="object"?{...e&&typeof e=="object"?{...e}:{},...t}:t===null?e&&typeof e=="object"?{...e}:e??null:e&&typeof e=="object"?{...e}:e??void 0}function Ux(e,t){return Go(e,t)}function Wx(e,t){return Array.isArray(t)?t.slice():t===null?Array.isArray(e)?e.slice():e??null:Array.isArray(e)?e.slice():e??void 0}function Vx(e,t){return Array.isArray(t)?t.map(n=>({...n})):t===null?Array.isArray(e)?e.map(n=>({...n})):e??null:Array.isArray(e)?e.map(n=>({...n})):e??void 0}function Bc(e,t){const n=Go(e.metadata,t.metadata),r=Go(e.config,t.config),o=Go(e.parentConfig,t.parentConfig),s=Wx(e.next,t.next),i=Vx(e.tasks,t.tasks),a=Ux(e.values,t.values),l={};return n!==void 0&&(l.metadata=n??null),r!==void 0&&(l.config=r??null),o!==void 0&&(l.parentConfig=o??null),s!==void 0&&(l.next=s??null),i!==void 0&&(l.tasks=i??null),a!==void 0&&(l.values=a??null),l}function qx({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:c}=Ni(),d=w.useMemo(()=>$n(c),[c]),f=w.useMemo(()=>{try{return new URL(c).host}catch{return"unknown"}},[c]),h=w.useMemo(()=>`threadPayload:${Px}:${f}:`,[f]),p=w.useCallback(A=>Lx(h,A),[h]),g=w.useCallback((A,N=100)=>{Fx(h,A,N)},[h]),y=w.useCallback(A=>{$x(h,A)},[h]),v=w.useCallback(()=>{zx(h)},[h]),[x,b]=w.useState(()=>{var A;return Fi(f,(A=l.getAuthToken)==null?void 0:A.call(l))}),[S,T]=w.useState(()=>{var N;const A=zi(Fi(f,(N=l.getAuthToken)==null?void 0:N.call(l)));return Ko(A)}),k=w.useMemo(()=>Bi(S),[S]),[C,E]=w.useState(t),[_,j]=w.useState(!1),[D,$]=w.useState(!1),[K,P]=w.useState(null),[R,L]=w.useState(null),[F,ne]=w.useState(null),[q,B]=w.useState([]),pe=w.useCallback(()=>{const A=zi(x);w.startTransition(()=>{T(Ko(A))})},[x]),[W,ce]=w.useState(!1),[H,Z]=w.useState(!1),[be,ye]=w.useState(null),[G,M]=w.useState(void 0),[X,oe]=w.useState(void 0),[xe,se]=w.useState(void 0),{state:re,dispatch:Ue,seed:qe,prepend:ot,pushUser:at,onEvent:ht,reset:tt}=Tc(),Me=w.useRef(C);w.useEffect(()=>{Me.current=C},[C]);const We=w.useRef(!1),lt=w.useRef([]),yt=w.useRef(null),dt=w.useRef(null),Je=w.useRef(new Map),ie=w.useRef(C),je=w.useRef(!1),ke=w.useRef(null),Ke=w.useRef(new Map),nt=w.useRef(new Map),Oe=w.useRef(new Map),Xe=w.useRef(new Map),Tt=w.useCallback(A=>{if(!A){B([]);return}const N=Ke.current.get(A);if(!N||!N.length){B([]);return}B(N.map(Y=>Qt(Y,{cloneMessages:!0})))},[]);w.useEffect(()=>{Tt(C)},[C,Tt]);const St=w.useCallback(()=>{var te;const A=Xe.current;if(A.size<=$c)return;const N=Array.from(A.entries()).sort((ae,Q)=>ae[1].timestamp-Q[1].timestamp),Y=A.size-$c;for(let ae=0;ae<Y;ae++){const Q=(te=N[ae])==null?void 0:te[0];Q&&A.delete(Q)}},[]),Yt=w.useCallback((A,N,Y)=>{if(!A)return;const te=Y==="replace"?[]:Ke.current.get(A)??[],ae=Y==="replace"?N:[...N,...te];if(!ae.length){Y==="replace"&&Ke.current.set(A,[]);return}const Q=new Map;for(const Be of ae){if(!(Be!=null&&Be.checkpointId))continue;const De=`${Be.checkpointId}::${Be.checkpointNs??""}`,et=Qt(Be,{cloneMessages:!0}),vt=Q.get(De);if(!vt){Q.set(De,et);continue}const Nt=Bc(vt,et);Q.set(De,{...vt,...Nt})}const ze=Array.from(Q.values()).sort((Be,De)=>{const et=Number.isFinite(Date.parse(Be.createdAt??""))?Date.parse(Be.createdAt??""):0;return(Number.isFinite(Date.parse(De.createdAt??""))?Date.parse(De.createdAt??""):0)-et});Ke.current.set(A,ze),A===Me.current&&Tt(A)},[Tt]),Et=w.useCallback((A,N,Y)=>{if(!A)return;const te=nt.current.get(A),ae=Y==="replace"||!te?new Map:new Map(te);if(N&&typeof N=="object")for(const[Q,ze]of Object.entries(N)){if(!(ze!=null&&ze.checkpointId))continue;const Be=Q||Qr(ze.checkpointId,ze.checkpointNs??null);ae.set(Be,Qt(ze,{cloneMessages:!0}))}nt.current.set(A,ae)},[]),rr=w.useCallback((A,N)=>{const{threadId:Y,checkpointId:te=null,checkpointNs:ae=null}=A,Q=zc(Y,te,ae);if(N!=null&&N.force)Oe.current.delete(Q),Xe.current.delete(Q);else{if(N!=null&&N.preferCache){const et=Xe.current.get(Q);if(et)return Promise.resolve(et.payload)}const De=Oe.current.get(Q);if(De)return De}const Be=l.getStateHistory({threadId:Y,checkpointId:te??void 0,checkpointNs:ae??void 0}).then(De=>(Xe.current.set(Q,{payload:De,timestamp:Date.now()}),St(),De)).finally(()=>{Oe.current.get(Q)===Be&&Oe.current.delete(Q)});return Oe.current.set(Q,Be),Be},[l,St]),Xt=w.useCallback((A,N)=>new Promise((Y,te)=>{const ae=async()=>{We.current=!0;try{await A(),Y()}catch(Q){te(Q)}finally{We.current=!1;const Q=lt.current.shift();Q&&Q().catch(()=>{})}};We.current?lt.current.push(ae):ae().catch(Q=>{te(Q)})}),[]),xn=w.useRef(k.length),sn=w.useRef(!1);w.useEffect(()=>{xn.current=k.length},[k.length]),w.useEffect(()=>{const A=re.pendingInterrupt??jx(re.messages);Oc(F,A)||ne(A??null)},[F,re.messages,re.pendingInterrupt]);const Dt=w.useCallback(async()=>{const A=xn.current>0;A||j(!0);try{const N=await l.listThreads();w.startTransition(()=>{T(Y=>{const te=ze=>ze.map(Be=>`${Be.threadId}:${Be.updatedAt??""}:${Be.messageCount??""}`).join("|"),ae=Bi(Y);return te(ae)===te(N)||N.length===0&&ae.length>0&&!sn.current?Y:Ko(N)})}),P(null),sn.current||(sn.current=!0)}catch(N){i==null||i(String(N)),console.error("[ChatSessionProvider] Failed to refresh threads:",N),P(String(N))}finally{A||j(!1)}},[l,i]),Pn=w.useRef(!1),yn=w.useRef(null),mt=w.useRef(null),vn=w.useRef(""),On=w.useCallback((A,N)=>{if(!cr())return;mt.current!==null&&(window.clearTimeout(mt.current),mt.current=null);const Y=A.map(ae=>`${ae.threadId}:${ae.updatedAt??""}:${ae.messageCount??""}`).join("|");if(A.length===0){try{Di(x)}catch{}vn.current="";return}if(Y===vn.current)return;const te=()=>{try{const ae=A.slice(0,Li);$i(x,ae),vn.current=Y}catch{}finally{mt.current=null}};if(N!=null&&N.immediate){te();return}mt.current=window.setTimeout(()=>{Mc(te)},qo)},[x]),kr=w.useCallback(()=>{On(k,{immediate:!0})},[On,k]),Jt=w.useCallback((A,N,Y,te)=>{var Sm;const ae=Y??Me.current;if(!ae)return;const Q=Qt(A),ze=ae===Me.current,Be=(te==null?void 0:te.persist)!==!1;if(N==="replace"){if(Be){const It={threadId:ae,snapshot:Qt(A,{cloneMessages:!0})};Je.current.set(ae,It),ie.current=ae}if(!ze)return;qe(Q.messages,{checkpointId:Q.checkpointId??null,checkpointNs:Q.checkpointNs??null,pendingInterrupt:Q.interrupt??null}),ne(Q.interrupt??null),ye(Q.nextCursor??null),ce(!!Q.nextCursor),M(Q.checkpointId??void 0),oe(Q.checkpointNs??void 0),se(Q.nextCursorNs??void 0);return}const De=Je.current.get(ae),et=(De==null?void 0:De.snapshot)??null,vt=Array.isArray(et==null?void 0:et.messages)?et.messages:[],Nt=Qt(et),Dn=Array.isArray(A==null?void 0:A.messages)?A.messages:[],_t=new Set,jt=[...Dn,...vt].filter(It=>{const Cl=It==null?void 0:It.id;return Cl?_t.has(Cl)?!1:(_t.add(Cl),!0):!0}),No=Bc(Nt,Q),_o={checkpointId:Nt.checkpointId??Q.checkpointId??null,checkpointNs:Nt.checkpointNs??Q.checkpointNs??null,createdAt:Q.createdAt??Nt.createdAt??null,parentId:Q.parentId??Nt.parentId??null,branchLabel:Q.branchLabel??Nt.branchLabel??null,lastMessageId:((Sm=jt[jt.length-1])==null?void 0:Sm.id)??null,messagesLen:jt.length,hasMessages:jt.length>0,messages:jt,nextCursor:Q.nextCursor??Nt.nextCursor??null,nextCursorNs:Q.nextCursorNs??Nt.nextCursorNs??null,interrupt:Nt.interrupt??Q.interrupt??null,...No};if(Je.current.set(ae,{threadId:ae,snapshot:Qt(_o,{cloneMessages:!0})}),!ze)return;Dn.length&&ot(Dn);const Ln=A&&Object.prototype.hasOwnProperty.call(A,"checkpointId")?A.checkpointId:void 0,jo=A&&Object.prototype.hasOwnProperty.call(A,"checkpointNs")?A.checkpointNs:void 0,Fn=A&&Object.prototype.hasOwnProperty.call(A,"nextCursor")?A.nextCursor:void 0,Sl=A&&Object.prototype.hasOwnProperty.call(A,"nextCursorNs")?A.nextCursorNs:void 0;ye(It=>Fn!==void 0?Fn??It??null:It??null),ce(It=>Fn!==void 0?!!Fn:It),M(It=>Ln!==void 0?Ln??It??void 0:It??void 0),oe(It=>jo!==void 0?jo??It??void 0:It??void 0),se(It=>Sl!==void 0?Sl??void 0:It)},[ot,qe,ne]),Tr=w.useCallback(A=>{if(A.threadId!=null&&A.threadId!==Me.current)return;const N=Qt(A.snapshot,{cloneMessages:!0});qe(N.messages,{checkpointId:N.checkpointId??null,checkpointNs:N.checkpointNs??null,pendingInterrupt:N.interrupt??null}),ne(N.interrupt??null),ye(N.nextCursor??null),ce(!!N.nextCursor),M(N.checkpointId??void 0),oe(N.checkpointNs??void 0),se(N.nextCursorNs??void 0),ie.current=A.threadId,Tt(A.threadId??Me.current??null)},[qe,ne,Tt]),Mn=w.useCallback(A=>{if(!A)return;Je.current.delete(A),y(A),Ke.current.delete(A),nt.current.delete(A),A===Me.current&&B([]);const N=`${A}__`;for(const Y of Oe.current.keys())Y.startsWith(N)&&Oe.current.delete(Y);for(const Y of Xe.current.keys())Y.startsWith(N)&&Xe.current.delete(Y);ie.current===A&&(ie.current=null)},[y]),bn=w.useCallback(()=>{const A=Me.current;A&&Mn(A),tt([]),ce(!1),Z(!1),ye(null),M(void 0),oe(void 0),se(void 0)},[Mn,tt]),Un=w.useCallback(({from:A,to:N})=>{const Y=Me.current;Y&&console.warn(`[ChatSessionProvider] Stream sequence gap detected (${A} -> ${N}) for thread ${Y}`)},[]),Er=w.useCallback(A=>{const N=A.threadId;console.log("[ChatSessionProvider] 📥 Handling thread_info event:",{threadId:N,title:A.title,created:A.created,currentThreads:k.length});const Y={threadId:N,title:A.title||`Thread ${N.slice(0,8)}`,createdAt:A.createdAt||new Date().toISOString(),updatedAt:A.updatedAt||new Date().toISOString(),messageCount:A.messageCount||0};Me.current!==N&&(!Me.current&&re.messages.length<=1&&(dt.current=N),E(N)),w.startTransition(()=>{T(te=>{const ae=te.byId[N];return ae?ae.title===Y.title&&ae.updatedAt===Y.updatedAt&&ae.messageCount===Y.messageCount?te:{byId:{...te.byId,[N]:Y},order:te.order}:{byId:{...te.byId,[N]:Y},order:[N,...te.order]}})})},[re.messages.length]),{startStream:Wr,stop:Vr,isStreaming:or,error:I,setAuthToken:U}=Ix({baseUrl:d,onThreadInfo:Er,onMessageEvent:ht,onUnhandledEvent:A=>{console.warn(`[ChatSessionProvider] Unhandled stream event: ${A.type}`,A)},onSequenceGap:Un});w.useEffect(()=>{Pn.current=or},[or]),w.useEffect(()=>{if(!cr())return;mt.current!==null&&(window.clearTimeout(mt.current),mt.current=null);const A=k.map(Y=>`${Y.threadId}:${Y.updatedAt??""}:${Y.messageCount??""}`).join("|");if(k.length===0){try{Di(x)}catch{}vn.current="";return}if(A===vn.current)return;const N=()=>{try{const Y=k.slice(0,Li);$i(x,Y),vn.current=A}catch{}finally{mt.current=null}};return mt.current=window.setTimeout(()=>{Mc(N),mt.current=null},qo),()=>{mt.current!==null&&(window.clearTimeout(mt.current),mt.current=null)}},[k,On]),w.useEffect(()=>{var te;const A=l.getAuthToken();U(A);const N=ae=>{const Q=Fi(f,ae);ke.current!==Q&&(ke.current=Q,je.current=!1),b(Q);const ze=zi(Q);w.startTransition(()=>{T(Ko(ze))}),ae&&!je.current&&(je.current=!0)};N(A);const Y=(te=l.onTokenChange)==null?void 0:te.call(l,ae=>{ae!==A&&(U(ae),v(),Oe.current.clear(),Xe.current.clear(),N(ae))});return()=>{Y==null||Y()}},[l,f,U,v]);const le=w.useCallback(async A=>{var te;const N=`Thread ${(te=crypto.randomUUID)==null?void 0:te.call(crypto)}`,Y={threadId:N,title:A||"New Chat",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:0};T(ae=>({byId:{...ae.byId,[N]:Y},order:[N,...ae.order]})),E(N);try{const ae=await l.createThread(A),Q=typeof ae=="string"?ae:ae.threadId;return T(ze=>{const Be=ze.byId[N];if(!Be)return ze;const De={...ze.byId};delete De[N],De[Q]={...Be,threadId:Q};const et=ze.order.map(vt=>vt===N?Q:vt);return{byId:De,order:et}}),E(Q),setTimeout(()=>Dt(),10),P(null),Q}catch(ae){throw T(Q=>{if(!Q.byId[N])return Q;const ze={...Q.byId};delete ze[N];const Be=Q.order.filter(De=>De!==N);return{byId:ze,order:Be}}),E(null),P(String(ae)),ae}},[l,Dt]),Ce=w.useCallback(async A=>{try{await l.deleteThread(A);let N=null;T(Y=>{if(!Y.byId[A])return Y;const te={...Y.byId};delete te[A];const ae=Y.order.filter(ze=>ze!==A),Q={byId:te,order:ae};return N=Bi(Q),Q}),N&&On(N,{immediate:!0}),Mn(A),Me.current===A&&(dt.current=A,E(null),Me.current=null,ie.current=null,bn()),await Dt(),P(null)}catch(N){throw P(String(N)),N}},[l,bn,Mn,Dt,On]),Ge=w.useCallback(async(A,N)=>{try{await l.updateThread(A,N),T(Y=>{const te=Y.byId[A];return te?{byId:{...Y.byId,[A]:{...te,title:N}},order:Y.order}:Y}),P(null)}catch(Y){throw await Dt(),P(String(Y)),Y}},[l,Dt]),$e=w.useCallback(async(A,N,Y,te=!1)=>{await Xt(async()=>{if(dt.current===A&&!te){dt.current=null;return}if(yt.current===A&&!te)return;E(_t=>_t===A?_t:A),Me.current=A;const ze=zc(A,N??null,Y??null),Be=Xe.current.get(ze),De=!te&&!N&&!Y&&Be&&Date.now()-Be.timestamp<Hx,et=!te&&!N&&!Y;let vt=!1;if(et){const _t=Je.current.get(A);if(_t)Tr(_t),vt=!0;else{const jt=p(A);jt&&(Je.current.set(A,jt),Tr(jt),vt=!0)}}const Nt=te||!vt||!!N||!!Y,Dn=async _t=>{_t&&$(!0),yt.current=A;try{const jt=await rr({threadId:A,checkpointId:N,checkpointNs:Y},{force:te}),{latest:No,checkpoints:_o,snapshots:Ln}=ji(jt);Jt(No,"replace",A),Yt(A,_o,"replace"),Et(A,Ln,"replace"),L(null)}catch(jt){throw(!vt||te||_t)&&(i==null||i(String(jt))),L(String(jt)),jt}finally{yt.current=null,_t&&$(!1)}};Nt?await Dn(!0):et&&vt&&!De&&Dn(!1).catch(_t=>{console.warn("[ChatSessionProvider] Background refresh failed:",_t)})},`loadThread-${A}`)},[Tr,Jt,Xt,rr,i,Yt,Et]),Fe=w.useCallback(async()=>{await Xt(async()=>{const A=Me.current;A&&Mn(A),dt.current=null,E(null),Me.current=null,ie.current=null,bn(),M(void 0),oe(void 0),se(void 0),B([]);try{localStorage.removeItem("lastThreadId")}catch(N){console.warn("[ChatSessionProvider] Failed to clear lastThreadId:",N)}},"clearCurrentThread")},[bn,Mn,Xt]),z=w.useCallback(async(A,N)=>{var Q;const Y=Me.current;if(!Y)throw new Error("No active thread");const te=Qr(A,N??null),ae=(Q=nt.current.get(Y))==null?void 0:Q.get(te);if(ae){await Xt(async()=>{Jt(ae,"replace",Y,{persist:!1})},`navigateToCheckpoint-${Y}-${te}`);return}await $e(Y,A,N??void 0,!0)},[Jt,Xt,$e]),ue=w.useCallback(async()=>{if(!Me.current)throw new Error("No active thread");await $e(Me.current,void 0,void 0,!0)},[$e]),me=w.useCallback(async()=>{if(!Me.current)throw new Error("No active thread");if(H||!W)return;const A=be;if(A){Z(!0);try{const N=Me.current,Y=await rr({threadId:N,checkpointId:A??G??null,checkpointNs:xe??X??null}),{latest:te,checkpoints:ae,snapshots:Q}=ji(Y),ze=N?nt.current.get(N):null;let Be=ae.length>0;if(Be&&ze&&ze.size>0&&(Be=ae.some(De=>{if(!(De!=null&&De.checkpointId))return!1;const et=Qr(De.checkpointId,De.checkpointNs??null);return!ze.has(et)})),!Be){ye(null),se(void 0),ce(!1),L(null);return}Jt(te,"prepend",N??void 0),N&&(Yt(N,ae,"prepend"),Et(N,Q,"prepend")),L(null)}catch(N){throw L(String(N)),N}finally{Z(!1)}}},[Jt,rr,W,G,X,xe,be,H,Yt,Et]),Re=w.useCallback(A=>{if(A!=null&&A.threadId){if(A.checkpointId){const N=Qr(A.checkpointId,A.checkpointNs??null),Y=Qt({...A,interrupt:A.interrupt??null},{cloneMessages:!0});Et(A.threadId,{[N]:Y},"prepend")}Jt(A,"replace",A.threadId)}},[Jt,Et]),rt=w.useCallback(async(A,N)=>{var jo;const Y=Me.current,te=(A==null?void 0:A.text)??"",ae=(A==null?void 0:A.attachments)??[],Q=ae.length?ae:(N==null?void 0:N.attachments)??[],ze={...(N==null?void 0:N.payloadExtras)??{},...(A==null?void 0:A.payload)??{}};if(!Y&&!Object.keys(ze).length&&Q.length===0&&!te.trim()){console.warn("[ChatSessionProvider] Nothing to submit - skipping");return}!Y&&!ze.messages&&console.warn("[ChatSessionProvider] No thread ID - message will create new thread");const{contentParts:Be,filesInfo:De}=await Qg(l,Q),et=[...Be];te&&te.trim()&&et.push({type:"text",text:te.trim()});const vt=!!Y,Nt=vt?(N==null?void 0:N.checkpointId)??re.lastCheckpointId??void 0:void 0,Dn=vt?(N==null?void 0:N.checkpointNs)??re.lastCheckpointNs??void 0:void 0,_t={id:((jo=crypto.randomUUID)==null?void 0:jo.call(crypto))||`user-${Date.now()}`,role:"user",content:et,createdAt:new Date().toISOString(),...Nt!=null?{checkpointId:Nt}:{},...Dn!=null?{checkpointNs:Dn}:{}};et.length>0&&at(_t);const jt={..._t,content:et},No=Q.length>0,_o={messages:et.length>0?[jt]:[],files_info:De,...o&&No&&s?{active_agent:s}:{},...ze},Ln={threadId:Y??null,payload:_o,checkpointId:Nt??null,checkpointNs:Dn??null,nodeFilter:(N==null?void 0:N.nodeFilter)??null,config:N==null?void 0:N.config,command:(N==null?void 0:N.command)??null};Ln.threadId||delete Ln.threadId,Ln.command||delete Ln.command,Wr(Ln,{onError:Fn=>{console.warn("[ChatSessionProvider] Stream error:",Fn)},onOpen:({threadId:Fn})=>{!Me.current&&Fn&&(re.messages.length<=1&&(dt.current=Fn),E(Fn))},onGap:Un})},[l,o,s,Un,re.lastCheckpointId,re.lastCheckpointNs,re.messages.length,at,Wr]),Lt=w.useCallback(async(A,N,Y)=>{if(!Me.current)throw new Error("No active thread to handle interrupt");const ae=N?Y??!0:!1;try{try{Ue({type:"interrupt_response",payload:{interruptId:A}})}catch(Q){console.warn("[ChatSessionProvider] optimistic interrupt_response dispatch failed:",Q)}await rt({payload:{}},{checkpointId:re.lastCheckpointId??void 0,checkpointNs:re.lastCheckpointNs??void 0,command:{kind:"resume",value:ae}}),ne(null)}catch(Q){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${A}:`,Q),Q}},[Ue,re.lastCheckpointId,re.lastCheckpointNs,rt]);w.useEffect(()=>{if(a==null||a(C),C)try{localStorage.setItem("lastThreadId",C)}catch(A){console.warn("[ChatSessionProvider] Failed to persist lastThreadId:",A)}},[C,a]),w.useEffect(()=>((async()=>{try{if(Dt().catch(N=>{console.error("[ChatSessionProvider] Failed to refresh threads (background):",N),i==null||i(String(N))}),!r&&!t)try{const N=localStorage.getItem("lastThreadId");N&&(E(N),n&&await $e(N))}catch(N){console.warn("[ChatSessionProvider] Failed to restore last thread:",N)}else t&&n&&await $e(t)}catch(N){console.error("[ChatSessionProvider] Initialization failed:",N),i==null||i(String(N))}})(),()=>{}),[]),w.useEffect(()=>{const A=Me.current;if(!A||ie.current!==A)return;re.messages.length&&re.messages[re.messages.length-1];const N=Qt({checkpointId:re.lastCheckpointId??null,checkpointNs:re.lastCheckpointNs??null,messages:re.messages.slice(),nextCursor:be??null,nextCursorNs:xe??null,interrupt:re.pendingInterrupt??F??null}),Y=Je.current.get(A),te=Y==null?void 0:Y.snapshot,ae=!te||te.messages.length!==N.messages.length||te.messages.some((De,et)=>{var vt;return(De==null?void 0:De.id)!==((vt=N.messages[et])==null?void 0:vt.id)}),Q=((te==null?void 0:te.checkpointId)??null)!==N.checkpointId||((te==null?void 0:te.checkpointNs)??null)!==N.checkpointNs,ze=((te==null?void 0:te.nextCursor)??null)!==N.nextCursor||((te==null?void 0:te.nextCursorNs)??null)!==N.nextCursorNs,Be=!Oc((te==null?void 0:te.interrupt)??null,N.interrupt??null);if(ae||Q||ze||Be){const De={threadId:A,snapshot:N};Je.current.set(A,De),yn.current&&window.clearTimeout(yn.current),yn.current=window.setTimeout(()=>{try{g(De,100)}catch(et){console.warn("[ChatSessionProvider] Failed to persist thread payload:",et)}},qo)}},[be,xe,re.lastCheckpointId,re.lastCheckpointNs,re.messages,re.pendingInterrupt,F,g]);const an=w.useMemo(()=>({threads:k,currentThreadId:C,setCurrentThreadId:E,isLoading:_,error:K,actions:{createThread:le,deleteThread:Ce,renameThread:Ge,refreshThreads:()=>Dt()},persistThreadsCache:kr,hydrateFromCache:pe}),[k,C,_,K,le,Ce,Ge,Dt,kr,pe,E]),Ct=w.useMemo(()=>{const A=re.lastBranch??null,N=re.assemblingId??null,Y=A||N?{branchLabel:(A==null?void 0:A.branchLabel)??null,lastBranch:A,assemblingMessageId:N}:null;return{threadId:C,messages:re.messages,interrupt:F,checkpoint:{id:re.lastCheckpointId??null,namespace:re.lastCheckpointNs??null},checkpoints:q,metadata:Y,isLoading:D,isHistoryLoading:H,error:R,hasMore:W,loadOlder:me,seedFromSnapshot:Re,clearState:bn,navigateToCheckpoint:z,returnToLatest:ue,loadThread:$e,clearThread:Fe,respondToInterrupt:Lt}},[Fe,bn,C,F,W,H,D,me,$e,re.assemblingId,re.lastBranch,re.lastCheckpointId,re.lastCheckpointNs,re.messages,z,Lt,ue,Re,R,q]),Ao=w.useMemo(()=>({isStreaming:or,error:I,submit:rt,send:rt,stop:Vr,setAuthToken:U}),[or,I,rt,Vr,U]);return u.jsx(Bx.Provider,{value:!0,children:u.jsx(Fc.Provider,{value:Ao,children:u.jsx(Dc.Provider,{value:an,children:u.jsx(Lc.Provider,{value:Ct,children:e})})})})}function Yo(){const e=w.useContext(Dc);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function Xo(){const e=w.useContext(Lc);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function Hc(){const e=w.useContext(Fc);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function Jo({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 u.jsx(Jg,{apiConfig:t,children:u.jsx(qx,{initialThreadId:n,autoLoadInitial:r,disableAutoRestore:o,enableFileAgentRouting:s,fileAgentId:i,onError:a,onThreadChange:l,children:e})})}function ee(...e){return Em.twMerge(Tm.clsx(e))}const Kx=Ro.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"}}),Ze=m.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?sr.Slot:"button";return u.jsx(i,{className:ee(Kx({variant:t,size:n,className:e})),ref:s,...o})});Ze.displayName="Button";const Uc=m.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{className:ee("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}));Uc.displayName="Textarea";function Gx({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=2e4,value:i,onValueChange:a,onSend:l,onCancelEdit:c,onStop:d,className:f="",textareaClassName:h="",allowEmptySend:p=!1}){const g=i!==void 0,[y,v]=w.useState(e),x=(g?i:y)??"",[b,S]=w.useTransition(),T=w.useRef(null),k=w.useRef(0),C=w.useRef(null);w.useEffect(()=>{g||(v(e??""),C.current=null,T.current&&(T.current.style.height="auto",T.current.style.height=`${T.current.scrollHeight}px`))},[e,t,g]);const E=w.useCallback(()=>{const L=T.current;L&&(L.style.height="auto",L.style.height=`${L.scrollHeight}px`)},[]);w.useEffect(()=>{E()},[E,x]);const _=w.useCallback((L,{fromUser:F})=>{g||v(L),F&&(a==null||a(L))},[g,a]),j=w.useCallback(async L=>{L&&L.preventDefault();const F=(x??"").trim();if(!F&&!p)return;const ne=++k.current;C.current={id:ne,shouldClear:!0},S(()=>{var q,B,pe;try{const W=l(F);W&&typeof W.then=="function"?W.then(()=>{var ce,H;((ce=C.current)==null?void 0:ce.id)===ne&&C.current.shouldClear&&(g||(v(""),T.current&&(T.current.style.height="auto"),a==null||a(""))),((H=C.current)==null?void 0:H.id)===ne&&(C.current=null)}).catch(()=>{var ce;((ce=C.current)==null?void 0:ce.id)===ne&&(C.current=null)}):(((q=C.current)==null?void 0:q.id)===ne&&C.current.shouldClear&&(g||(v(""),T.current&&(T.current.style.height="auto"),a==null||a(""))),((B=C.current)==null?void 0:B.id)===ne&&(C.current=null))}catch{((pe=C.current)==null?void 0:pe.id)===ne&&(C.current=null)}})},[x,l,p,g,a]),D=w.useCallback(L=>{const F=L.target.value;_(F,{fromUser:!0}),C.current&&(C.current.shouldClear=!1),T.current&&(T.current.style.height="auto",T.current.style.height=`${T.current.scrollHeight}px`)},[_]),$=w.useCallback(L=>{L.key==="Enter"&&!L.shiftKey?(L.preventDefault(),j()):L.key==="Escape"&&t&&(L.preventDefault(),c==null||c())},[j,t,c]),R=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${t?"border-[hsl(var(--ring))] bg-[hsl(var(--card))] text-[hsl(var(--card-foreground))] dark:bg-[hsl(var(--card))] dark:text-[hsl(var(--card-foreground))]":""} ${h}`;return u.jsx("form",{onSubmit:L=>void j(L),className:`w-full ${f}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(Uc,{ref:T,value:x,onChange:D,onKeyDown:$,placeholder:t?"Edit your message...":n,className:R,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx(Ze,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:u.jsx(fe.Square,{size:16})}):u.jsx(Ze,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!x.trim()&&!p||b,children:u.jsx(fe.Send,{size:16})})})]})})}const Yx=w.memo(Gx),Zo=0,Vn=1,_r=2,Wc=4;function Vc(e){return()=>e}function Xx(e){e()}function qc(e,t){return n=>e(t(n))}function Kc(e,t){return()=>e(t)}function Jx(e,t){return n=>e(t,n)}function Ui(e){return e!==void 0}function Zx(...e){return()=>{e.map(Xx)}}function jr(){}function Qo(e,t){return t(e),e}function Qx(e,t){return t(e)}function ct(...e){return e}function Qe(e,t){return e(Vn,t)}function Pe(e,t){e(Zo,t)}function Wi(e){e(_r)}function xt(e){return e(Wc)}function ve(e,t){return Qe(e,Jx(t,Zo))}function dn(e,t){const n=e(Vn,r=>{n(),t(r)});return n}function Gc(e){let t,n;return r=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{r(t)},e)}}function Yc(e,t){return e===t}function ut(e=Yc){let t;return n=>r=>{e(t,r)||(t=r,n(r))}}function Ee(e){return t=>n=>{e(n)&&t(n)}}function de(e){return t=>qc(t,e)}function Sn(e){return t=>()=>{t(e)}}function V(e,...t){const n=ey(...t);return(r,o)=>{switch(r){case _r:Wi(e);return;case Vn:return Qe(e,n(o))}}}function Cn(e,t){return n=>r=>{n(t=e(t,r))}}function ur(e){return t=>n=>{e>0?e--:t(n)}}function zn(e){let t=null,n;return r=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,r(t)},e))}}function Le(...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);Qe(s,l=>{const c=n;n=n|a,t[i]=l,c!==o&&n===o&&r&&(r(),r=null)})}),s=>i=>{const a=()=>{s([i].concat(t))};n===o?a():r=a}}function ey(...e){return t=>e.reduceRight(Qx,t)}function ty(e){let t,n;const r=()=>t==null?void 0:t();return function(o,s){switch(o){case Vn:return s?n===s?void 0:(r(),n=s,t=Qe(e,s),t):(r(),jr);case _r:r(),n=null;return}}}function J(e){let t=e;const n=Ve();return(r,o)=>{switch(r){case Zo:t=o;break;case Vn:{o(t);break}case Wc:return t}return n(r,o)}}function Pt(e,t){return Qo(J(t),n=>ve(e,n))}function Ve(){const e=[];return(t,n)=>{switch(t){case Zo:e.slice().forEach(r=>{r(n)});return;case _r:e.splice(0,e.length);return;case Vn:return e.push(n),()=>{const r=e.indexOf(n);r>-1&&e.splice(r,1)}}}}function Wt(e){return Qo(Ve(),t=>ve(e,t))}function Ye(e,t=[],{singleton:n}={singleton:!0}){return{constructor:e,dependencies:t,id:ny(),singleton:n}}const ny=()=>Symbol();function ry(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 bt(...e){const t=Ve(),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);Qe(s,l=>{n[i]=l,r=r|a,r===o&&Pe(t,n)})}),function(s,i){switch(s){case _r:{Wi(t);return}case Vn:return r===o&&i(n),Qe(t,i)}}}function Te(e,t=Yc){return V(e,ut(t))}function Vi(...e){return function(t,n){switch(t){case _r:return;case Vn:return Zx(...e.map(r=>Qe(r,n)))}}}var Ut=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(Ut||{});const oy={0:"debug",3:"error",1:"log",2:"warn"},sy=()=>typeof globalThis>"u"?window:globalThis,qn=Ye(()=>{const e=J(3);return{log:J((t,n,r=1)=>{var o;const s=(o=sy().VIRTUOSO_LOG_LEVEL)!=null?o:xt(e);r>=s&&console[oy[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function dr(e,t,n){return qi(e,t,n).callbackRef}function qi(e,t,n){const r=w.useRef(null);let o=i=>{};const s=w.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 iy(e,t,n,r,o,s,i,a,l){const c=w.useCallback(d=>{const f=ay(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 g;p&&(g=h.ownerDocument.defaultView);const y=i?a?i.scrollLeft:i.scrollTop:p?a?g.scrollX||g.document.documentElement.scrollLeft:g.scrollY||g.document.documentElement.scrollTop:a?h.scrollLeft:h.scrollTop,v=i?a?i.scrollWidth:i.scrollHeight:p?a?g.document.documentElement.scrollWidth:g.document.documentElement.scrollHeight:a?h.scrollWidth:h.scrollHeight,x=i?a?i.offsetWidth:i.offsetHeight:p?a?g.innerWidth:g.innerHeight:a?h.offsetWidth:h.offsetHeight;r({scrollHeight:v,scrollTop:Math.max(y,0),viewportHeight:x}),s==null||s(a?Xc("column-gap",getComputedStyle(d).columnGap,o):Xc("row-gap",getComputedStyle(d).rowGap,o)),f!==null&&e(f)},[e,t,o,s,i,r,a]);return qi(c,n,l)}function ay(e,t,n,r){const o=e.length;if(o===0)return null;const s=[];for(let i=0;i<o;i++){const a=e.item(i);if(a.dataset.index===void 0)continue;const l=parseInt(a.dataset.index),c=parseFloat(a.dataset.knownSize),d=t(a,n);if(d===0&&r("Zero-sized element, this should not happen",{child:a},Ut.ERROR),d===c)continue;const f=s[s.length-1];s.length===0||f.size!==d||f.endIndex!==l-1?s.push({endIndex:l,size:d,startIndex:l}):s[s.length-1].endIndex++}return s}function Xc(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,Ut.WARN),t==="normal"?0:parseInt(t??"0",10)}function Jc(e,t,n){const r=w.useRef(null),o=w.useCallback(l=>{if(!(l!=null&&l.offsetParent))return;const c=l.getBoundingClientRect(),d=c.width;let f,h;if(t){const p=t.getBoundingClientRect(),g=c.top-p.top;h=p.height-Math.max(0,g),f=g+t.scrollTop}else{const p=i.current.ownerDocument.defaultView;h=p.innerHeight-Math.max(0,c.top),f=c.top+p.scrollY}r.current={offsetTop:f,visibleHeight:h,visibleWidth:d},e(r.current)},[e,t]),{callbackRef:s,ref:i}=qi(o,!0,n),a=w.useCallback(()=>{o(i.current)},[o,i]);return w.useEffect(()=>{var l;if(t){t.addEventListener("scroll",a);const c=new ResizeObserver(()=>{requestAnimationFrame(a)});return c.observe(t),()=>{t.removeEventListener("scroll",a),c.unobserve(t)}}else{const c=(l=i.current)==null?void 0:l.ownerDocument.defaultView;return c==null||c.addEventListener("scroll",a),c==null||c.addEventListener("resize",a),()=>{c==null||c.removeEventListener("scroll",a),c==null||c.removeEventListener("resize",a)}}},[a,t,i]),s}const Ft=Ye(()=>{const e=Ve(),t=Ve(),n=J(0),r=Ve(),o=J(0),s=Ve(),i=Ve(),a=J(0),l=J(0),c=J(0),d=J(0),f=Ve(),h=Ve(),p=J(!1),g=J(!1),y=J(!1);return ve(V(e,de(({scrollTop:v})=>v)),t),ve(V(e,de(({scrollHeight:v})=>v)),i),ve(t,o),{deviation:n,fixedFooterHeight:c,fixedHeaderHeight:l,footerHeight:d,headerHeight:a,horizontalDirection:g,scrollBy:h,scrollContainerState:e,scrollHeight:i,scrollingInProgress:p,scrollTo:f,scrollTop:t,skipAnimationFrameInResizeObserver:y,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:s}},[],{singleton:!0}),to={lvl:0};function Zc(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 st(e){return e===to}function no(e,t){if(!st(e))return t===e.k?e.v:t<e.k?no(e.l,t):no(e.r,t)}function fn(e,t,n="k"){if(st(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const r=fn(e.r,t,n);return r[0]===-1/0?[e.k,e.v]:r}return fn(e.l,t,n)}function Vt(e,t,n){return st(e)?tu(t,n,1):t===e.k?wt(e,{k:t,v:n}):t<e.k?nu(wt(e,{l:Vt(e.l,t,n)})):nu(wt(e,{r:Vt(e.r,t,n)}))}function Rr(){return to}function es(e,t,n){if(st(e))return[];const r=fn(e,t)[0];return ly(Gi(e,r,n))}function Ki(e,t){if(st(e))return to;const{k:n,l:r,r:o}=e;if(t===n){if(st(r))return o;if(st(o))return r;{const[s,i]=eu(r);return ts(wt(e,{k:s,l:Qc(r),v:i}))}}else return t<n?ts(wt(e,{l:Ki(r,t)})):ts(wt(e,{r:Ki(o,t)}))}function fr(e){return st(e)?[]:[...fr(e.l),{k:e.k,v:e.v},...fr(e.r)]}function Gi(e,t,n){if(st(e))return[];const{k:r,l:o,r:s,v:i}=e;let a=[];return r>t&&(a=a.concat(Gi(o,t,n))),r>=t&&r<=n&&a.push({k:r,v:i}),r<=n&&(a=a.concat(Gi(s,t,n))),a}function ts(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(Yi(t))return ru(wt(e,{lvl:n-1}));if(!st(t)&&!st(t.r))return wt(t.r,{l:wt(t,{r:t.r.l}),lvl:n,r:wt(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}else{if(Yi(e))return Xi(wt(e,{lvl:n-1}));if(!st(r)&&!st(r.l)){const o=r.l,s=Yi(o)?r.lvl-1:r.lvl;return wt(o,{l:wt(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:Xi(wt(r,{l:o.r,lvl:s}))})}else throw new Error("Unexpected empty nodes")}}function wt(e,t){return tu(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 Qc(e){return st(e.r)?e.l:ts(wt(e,{r:Qc(e.r)}))}function Yi(e){return st(e)||e.lvl>e.r.lvl}function eu(e){return st(e.r)?[e.k,e.v]:eu(e.r)}function tu(e,t,n,r=to,o=to){return{k:e,l:r,lvl:n,r:o,v:t}}function nu(e){return Xi(ru(e))}function ru(e){const{l:t}=e;return!st(t)&&t.lvl===e.lvl?wt(t,{r:wt(e,{l:t.r})}):e}function Xi(e){const{lvl:t,r:n}=e;return!st(n)&&!st(n.r)&&n.lvl===t&&n.r.lvl===t?wt(n,{l:wt(e,{r:n.l}),lvl:t+1}):e}function ly(e){return Zc(e,({k:t,v:n})=>({index:t,value:n}))}function ou(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}function ro(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}const Ji=Ye(()=>({recalcInProgress:J(!1)}),[],{singleton:!0});function su(e,t,n){return e[ns(e,t,n)]}function ns(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 cy(e,t,n,r){const o=ns(e,t,r),s=ns(e,n,r,o);return e.slice(o,s+1)}function Kn(e,t){return Math.round(e.getBoundingClientRect()[t])}function rs(e){return!st(e.groupOffsetTree)}function Zi({index:e},t){return t===e?0:t<e?-1:1}function uy(){return{groupIndices:[],groupOffsetTree:Rr(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:Rr()}}function dy(e,t){let n=st(e)?0:1/0;for(const r of t){const{endIndex:o,size:s,startIndex:i}=r;if(n=Math.min(n,i),st(e)){e=Vt(e,0,s);continue}const a=es(e,i-1,o+1);if(a.some(yy(r)))continue;let l=!1,c=!1;for(const{end:d,start:f,value:h}of a)l?(o>=f||s===h)&&(e=Ki(e,f)):(c=h!==s,l=!0),d>o&&o>=f&&h!==s&&(e=Vt(e,o+1,h));c&&(e=Vt(e,i,s))}return[e,n]}function fy(e){return typeof e.groupIndex<"u"}function hy({offset:e},t){return t===e?0:t<e?-1:1}function oo(e,t,n){if(t.length===0)return 0;const{index:r,offset:o,size:s}=su(t,e,Zi),i=e-r,a=s*i+(i-1)*n+o;return a>0?a+n:a}function iu(e,t){if(!rs(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function au(e,t,n){if(fy(e))return t.groupIndices[e.groupIndex]+1;{const r=e.index==="LAST"?n:e.index;let o=iu(r,t);return o=Math.max(0,o,Math.min(n,o)),o}}function py(e,t,n,r=0){return r>0&&(t=Math.max(t,su(e,r,Zi).offset)),Zc(cy(e,t,n,hy),xy)}function my(e,[t,n,r,o]){t.length>0&&r("received item sizes",t,Ut.DEBUG);const s=e.sizeTree;let i=s,a=0;if(n.length>0&&st(s)&&t.length===2){const h=t[0].size,p=t[1].size;i=n.reduce((g,y)=>Vt(Vt(g,y,h),y+1,p),i)}else[i,a]=dy(i,t);if(i===s)return e;const{lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f}=Qi(e.offsetTree,a,i,o);return{groupIndices:n,groupOffsetTree:n.reduce((h,p)=>Vt(h,p,oo(p,f,o)),Rr()),lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f,sizeTree:i}}function gy(e){return fr(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 lu(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 Qi(e,t,n,r){let o=e,s=0,i=0,a=0,l=0;if(t!==0){l=ns(o,t-1,Zi),a=o[l].offset;const c=fn(n,t-1);s=c[0],i=c[1],o.length&&o[l].size===fn(n,t)[1]&&(l-=1),o=o.slice(0,l+1)}else o=[];for(const{start:c,value:d}of es(n,t,1/0)){const f=c-s,h=f*i+a+f*r;o.push({index:c,offset:h,size:d}),s=c,a=h,i=d}return{lastIndex:s,lastOffset:a,lastSize:i,offsetTree:o}}function xy(e){return{index:e.index,value:e}}function yy(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 vy={offsetHeight:"height",offsetWidth:"width"},kn=Ye(([{log:e},{recalcInProgress:t}])=>{const n=Ve(),r=Ve(),o=Pt(r,0),s=Ve(),i=Ve(),a=J(0),l=J([]),c=J(void 0),d=J(void 0),f=J((k,C)=>Kn(k,vy[C])),h=J(void 0),p=J(0),g=uy(),y=Pt(V(n,Le(l,e,p),Cn(my,g),ut()),g),v=Pt(V(l,ut(),Cn((k,C)=>({current:C,prev:k.current}),{current:[],prev:[]}),de(({prev:k})=>k)),[]);ve(V(l,Ee(k=>k.length>0),Le(y,p),de(([k,C,E])=>{const _=k.reduce((j,D,$)=>Vt(j,D,oo(D,C.offsetTree,E)||$),Rr());return{...C,groupIndices:k,groupOffsetTree:_}})),y),ve(V(r,Le(y),Ee(([k,{lastIndex:C}])=>k<C),de(([k,{lastIndex:C,lastSize:E}])=>[{endIndex:C,size:E,startIndex:k}])),n),ve(c,d);const x=Pt(V(c,de(k=>k===void 0)),!0);ve(V(d,Ee(k=>k!==void 0&&st(xt(y).sizeTree)),de(k=>[{endIndex:0,size:k,startIndex:0}])),n);const b=Wt(V(n,Le(y),Cn(({sizes:k},[C,E])=>({changed:E!==k,sizes:E}),{changed:!1,sizes:g}),de(k=>k.changed)));Qe(V(a,Cn((k,C)=>({diff:k.prev-C,prev:C}),{diff:0,prev:0}),de(k=>k.diff)),k=>{const{groupIndices:C}=xt(y);if(k>0)Pe(t,!0),Pe(s,k+lu(k,C));else if(k<0){const E=xt(v);E.length>0&&(k-=lu(-k,E)),Pe(i,k)}}),Qe(V(a,Le(e)),([k,C])=>{k<0&&C("`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},Ut.ERROR)});const S=Wt(s);ve(V(s,Le(y),de(([k,C])=>{const E=C.groupIndices.length>0,_=[],j=C.lastSize;if(E){const D=no(C.sizeTree,0);let $=0,K=0;for(;$<k;){const R=C.groupIndices[K],L=C.groupIndices.length===K+1?1/0:C.groupIndices[K+1]-R-1;_.push({endIndex:R,size:D,startIndex:R}),_.push({endIndex:R+1+L-1,size:j,startIndex:R+1}),K++,$+=L+1}const P=fr(C.sizeTree);return $!==k&&P.shift(),P.reduce((R,{k:L,v:F})=>{let ne=R.ranges;return R.prevSize!==0&&(ne=[...R.ranges,{endIndex:L+k-1,size:R.prevSize,startIndex:R.prevIndex}]),{prevIndex:L+k,prevSize:F,ranges:ne}},{prevIndex:k,prevSize:0,ranges:_}).ranges}return fr(C.sizeTree).reduce((D,{k:$,v:K})=>({prevIndex:$+k,prevSize:K,ranges:[...D.ranges,{endIndex:$+k-1,size:D.prevSize,startIndex:D.prevIndex}]}),{prevIndex:0,prevSize:j,ranges:[]}).ranges})),n);const T=Wt(V(i,Le(y,p),de(([k,{offsetTree:C},E])=>{const _=-k;return oo(_,C,E)})));return ve(V(i,Le(y,p),de(([k,C,E])=>{if(C.groupIndices.length>0){if(st(C.sizeTree))return C;let _=Rr();const j=xt(v);let D=0,$=0,K=0;for(;D<-k;){K=j[$];const P=j[$+1]-K-1;$++,D+=P+1}if(_=fr(C.sizeTree).reduce((P,{k:R,v:L})=>Vt(P,Math.max(0,R+k),L),_),D!==-k){const P=no(C.sizeTree,K);_=Vt(_,0,P);const R=fn(C.sizeTree,-k+1)[1];_=Vt(_,1,R)}return{...C,sizeTree:_,...Qi(C.offsetTree,0,_,E)}}else{const _=fr(C.sizeTree).reduce((j,{k:D,v:$})=>Vt(j,Math.max(0,D+k),$),Rr());return{...C,sizeTree:_,...Qi(C.offsetTree,0,_,E)}}})),y),{beforeUnshiftWith:S,data:h,defaultItemSize:d,firstItemIndex:a,fixedItemSize:c,gap:p,groupIndices:l,itemSize:f,listRefresh:b,shiftWith:i,shiftWithOffset:T,sizeRanges:n,sizes:y,statefulTotalCount:o,totalCount:r,trackItemSizes:x,unshiftWith:s}},ct(qn,Ji),{singleton:!0});function by(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const cu=Ye(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:r,scrollTop:o}])=>{const s=Ve(),i=Ve(),a=Wt(V(s,de(by)));return ve(V(a,de(l=>l.totalCount)),n),ve(V(a,de(l=>l.groupIndices)),e),ve(V(bt(o,t,r),Ee(([l,c])=>rs(c)),de(([l,c,d])=>fn(c.groupOffsetTree,Math.max(l-d,0),"v")[0]),ut(),de(l=>[l])),i),{groupCounts:s,topItemsIndexes:i}},ct(kn,Ft)),Gn=Ye(([{log:e}])=>{const t=J(!1),n=Wt(V(t,Ee(r=>r),ut()));return Qe(t,r=>{r&&xt(e)("props updated",{},Ut.DEBUG)}),{didMount:n,propsReady:t}},ct(qn),{singleton:!0}),wy=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function uu(e){const t=typeof e=="number"?{index:e}:e;return t.align||(t.align="start"),(!t.behavior||!wy)&&(t.behavior="auto"),t.offset||(t.offset=0),t}const so=Ye(([{gap:e,listRefresh:t,sizes:n,totalCount:r},{fixedFooterHeight:o,fixedHeaderHeight:s,footerHeight:i,headerHeight:a,scrollingInProgress:l,scrollTo:c,smoothScrollTargetReached:d,viewportHeight:f},{log:h}])=>{const p=Ve(),g=Ve(),y=J(0);let v=null,x=null,b=null;function S(){v&&(v(),v=null),b&&(b(),b=null),x&&(clearTimeout(x),x=null),Pe(l,!1)}return ve(V(p,Le(n,f,r,y,a,i,h),Le(e,s,o),de(([[T,k,C,E,_,j,D,$],K,P,R])=>{const L=uu(T),{align:F,behavior:ne,offset:q}=L,B=E-1,pe=au(L,k,B);let W=oo(pe,k.offsetTree,K)+j;F==="end"?(W+=P+fn(k.sizeTree,pe)[1]-C+R,pe===B&&(W+=D)):F==="center"?W+=(P+fn(k.sizeTree,pe)[1]-C+R)/2:W-=_,q&&(W+=q);const ce=H=>{S(),H?($("retrying to scroll to",{location:T},Ut.DEBUG),Pe(p,T)):(Pe(g,!0),$("list did not change, scroll successful",{},Ut.DEBUG))};if(S(),ne==="smooth"){let H=!1;b=Qe(t,Z=>{H=H||Z}),v=dn(d,()=>{ce(H)})}else v=dn(V(t,Sy(150)),ce);return x=setTimeout(()=>{S()},1200),Pe(l,!0),$("scrolling from index to",{behavior:ne,index:pe,top:W},Ut.DEBUG),{behavior:ne,top:W}})),c),{scrollTargetReached:g,scrollToIndex:p,topListHeight:y}},ct(kn,Ft,qn),{singleton:!0});function Sy(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return r=>{r&&(t(!0),clearTimeout(n))}}}function ea(e,t){e==0?t():requestAnimationFrame(()=>{ea(e-1,t)})}function ta(e,t){const n=t-1;return typeof e=="number"?e:e.index==="LAST"?n:e.index}const io=Ye(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:r},{scrollTargetReached:o,scrollToIndex:s},{didMount:i}])=>{const a=J(!0),l=J(0),c=J(!0);return ve(V(i,Le(l),Ee(([d,f])=>!!f),Sn(!1)),a),ve(V(i,Le(l),Ee(([d,f])=>!!f),Sn(!1)),c),Qe(V(bt(t,i),Le(a,n,e,c),Ee(([[,d],f,{sizeTree:h},p,g])=>d&&(!st(h)||Ui(p))&&!f&&!g),Le(l)),([,d])=>{dn(o,()=>{Pe(c,!0)}),ea(4,()=>{dn(r,()=>{Pe(a,!0)}),Pe(s,d)})}),{initialItemFinalLocationReached:c,initialTopMostItemIndex:l,scrolledToInitialItem:a}},ct(kn,Ft,so,Gn),{singleton:!0});function du(e,t){return Math.abs(e-t)<1.01}const ao="up",lo="down",Cy="none",ky={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},Ty=0,co=Ye(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:r,scrollTop:o,viewportHeight:s}])=>{const i=J(!1),a=J(!0),l=Ve(),c=Ve(),d=J(4),f=J(Ty),h=Pt(V(Vi(V(Te(o),ur(1),Sn(!0)),V(Te(o),ur(1),Sn(!1),Gc(100))),ut()),!1),p=Pt(V(Vi(V(n,Sn(!0)),V(n,Sn(!1),Gc(200))),ut()),!1);ve(V(bt(Te(o),Te(f)),de(([b,S])=>b<=S),ut()),a),ve(V(a,zn(50)),c);const g=Wt(V(bt(r,Te(s),Te(t),Te(e),Te(d)),Cn((b,[{scrollHeight:S,scrollTop:T},k,C,E,_])=>{const j=T+k-S>-_,D={scrollHeight:S,scrollTop:T,viewportHeight:k};if(j){let K,P;return T>b.state.scrollTop?(K="SCROLLED_DOWN",P=b.state.scrollTop-T):(K="SIZE_DECREASED",P=b.state.scrollTop-T||b.scrollTopDelta),{atBottom:!0,atBottomBecause:K,scrollTopDelta:P,state:D}}let $;return D.scrollHeight>b.state.scrollHeight?$="SIZE_INCREASED":k<b.state.viewportHeight?$="VIEWPORT_HEIGHT_DECREASING":T<b.state.scrollTop?$="SCROLLING_UPWARDS":$="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:$,state:D}},ky),ut((b,S)=>b&&b.atBottom===S.atBottom))),y=Pt(V(r,Cn((b,{scrollHeight:S,scrollTop:T,viewportHeight:k})=>{if(du(b.scrollHeight,S))return{changed:!1,jump:0,scrollHeight:S,scrollTop:T};{const C=S-(T+k)<1;return b.scrollTop!==T&&C?{changed:!0,jump:b.scrollTop-T,scrollHeight:S,scrollTop:T}:{changed:!0,jump:0,scrollHeight:S,scrollTop:T}}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),Ee(b=>b.changed),de(b=>b.jump)),0);ve(V(g,de(b=>b.atBottom)),i),ve(V(i,zn(50)),l);const v=J(lo);ve(V(r,de(({scrollTop:b})=>b),ut(),Cn((b,S)=>xt(p)?{direction:b.direction,prevScrollTop:S}:{direction:S<b.prevScrollTop?ao:lo,prevScrollTop:S},{direction:lo,prevScrollTop:0}),de(b=>b.direction)),v),ve(V(r,zn(50),Sn(Cy)),v);const x=J(0);return ve(V(h,Ee(b=>!b),Sn(0)),x),ve(V(o,zn(100),Le(h),Ee(([b,S])=>!!S),Cn(([b,S],[T])=>[S,T],[0,0]),de(([b,S])=>S-b)),x),{atBottomState:g,atBottomStateChange:l,atBottomThreshold:d,atTopStateChange:c,atTopThreshold:f,isAtBottom:i,isAtTop:a,isScrolling:h,lastJumpDueToItemResize:y,scrollDirection:v,scrollVelocity:x}},ct(Ft)),os="top",ss="bottom",fu="none";function hu(e,t,n){return typeof e=="number"?n===ao&&t===os||n===lo&&t===ss?e:0:n===ao?t===os?e.main:e.reverse:t===ss?e.main:e.reverse}function pu(e,t){var n;return typeof e=="number"?e:(n=e[t])!=null?n:0}const na=Ye(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:r,viewportHeight:o}])=>{const s=Ve(),i=J(0),a=J(0),l=J(0),c=Pt(V(bt(Te(r),Te(o),Te(n),Te(s,ro),Te(l),Te(i),Te(t),Te(e),Te(a)),de(([d,f,h,[p,g],y,v,x,b,S])=>{const T=d-b,k=v+x,C=Math.max(h-T,0);let E=fu;const _=pu(S,os),j=pu(S,ss);return p-=b,p+=h+x,g+=h+x,g-=b,p>d+k-_&&(E=ao),g<d-C+f+j&&(E=lo),E!==fu?[Math.max(T-h-hu(y,os,E)-_,0),T-C-x+f+hu(y,ss,E)+j]:null}),Ee(d=>d!=null),ut(ro)),[0,0]);return{increaseViewportBy:a,listBoundary:s,overscan:l,topListHeight:i,visibleRange:c}},ct(Ft),{singleton:!0});function Ey(e,t,n){if(rs(t)){const r=iu(e,t);return[{index:fn(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 ra={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function is(e,t,n,r,o,s){const{lastIndex:i,lastOffset:a,lastSize:l}=o;let c=0,d=0;if(e.length>0){c=e[0].offset;const y=e[e.length-1];d=y.offset+y.size}const f=n-i,h=a+f*l+(f-1)*r,p=c,g=h-d;return{bottom:d,firstItemIndex:s,items:gu(e,o,s),offsetBottom:g,offsetTop:c,top:p,topItems:gu(t,o,s),topListHeight:t.reduce((y,v)=>v.size+y,0),totalCount:n}}function mu(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=ta(t,a),c=Array.from({length:a}).map((d,f)=>({data:s[f+l],index:f+l,offset:0,size:0}));return is(c,[],a,o,n,r)}function gu(e,t,n){if(e.length===0)return[];if(!rs(t))return e.map(c=>({...c,index:c.index+n,originalIndex:c.index}));const r=e[0].index,o=e[e.length-1].index,s=[],i=es(t.groupOffsetTree,r,o);let a,l=0;for(const c of e){(!a||a.end<c.index)&&(a=i.shift(),l=t.groupIndices.indexOf(a.start));let d;c.index===a.start?d={index:l,type:"group"}:d={groupIndex:l,index:c.index-(l+1)+n},s.push({...d,data:c.data,offset:c.offset,originalIndex:c.index,size:c.size})}return s}const hr=Ye(([{data:e,firstItemIndex:t,gap:n,sizes:r,totalCount:o},s,{listBoundary:i,topListHeight:a,visibleRange:l},{initialTopMostItemIndex:c,scrolledToInitialItem:d},{topListHeight:f},h,{didMount:p},{recalcInProgress:g}])=>{const y=J([]),v=J(0),x=Ve();ve(s.topItemsIndexes,y);const b=Pt(V(bt(p,g,Te(l,ro),Te(o),Te(r),Te(c),d,Te(y),Te(t),Te(n),e),Ee(([C,E,,_,,,,,,,j])=>{const D=j&&j.length!==_;return C&&!E&&!D}),de(([,,[C,E],_,j,D,$,K,P,R,L])=>{const F=j,{offsetTree:ne,sizeTree:q}=F,B=xt(v);if(_===0)return{...ra,totalCount:_};if(C===0&&E===0)return B===0?{...ra,totalCount:_}:mu(B,D,j,P,R,L||[]);if(st(q))return B>0?null:is(Ey(ta(D,_),F,L),[],_,R,F,P);const pe=[];if(K.length>0){const be=K[0],ye=K[K.length-1];let G=0;for(const M of es(q,be,ye)){const X=M.value,oe=Math.max(M.start,be),xe=Math.min(M.end,ye);for(let se=oe;se<=xe;se++)pe.push({data:L==null?void 0:L[se],index:se,offset:G,size:X}),G+=X}}if(!$)return is([],pe,_,R,F,P);const W=K.length>0?K[K.length-1]+1:0,ce=py(ne,C,E,W);if(ce.length===0)return null;const H=_-1,Z=Qo([],be=>{for(const ye of ce){const G=ye.value;let M=G.offset,X=ye.start;const oe=G.size;if(G.offset<C){X+=Math.floor((C-G.offset+R)/(oe+R));const se=X-ye.start;M+=se*oe+se*R}X<W&&(M+=(W-X)*oe,X=W);const xe=Math.min(ye.end,H);for(let se=X;se<=xe&&!(M>=E);se++)be.push({data:L==null?void 0:L[se],index:se,offset:M,size:oe}),M+=oe+R}});return is(Z,pe,_,R,F,P)}),Ee(C=>C!==null),ut()),ra);ve(V(e,Ee(Ui),de(C=>C==null?void 0:C.length)),o),ve(V(b,de(C=>C.topListHeight)),f),ve(f,a),ve(V(b,de(C=>[C.top,C.bottom])),i),ve(V(b,de(C=>C.items)),x);const S=Wt(V(b,Ee(({items:C})=>C.length>0),Le(o,e),Ee(([{items:C},E])=>C[C.length-1].originalIndex===E-1),de(([,C,E])=>[C-1,E]),ut(ro),de(([C])=>C))),T=Wt(V(b,zn(200),Ee(({items:C,topItems:E})=>C.length>0&&C[0].originalIndex===E.length),de(({items:C})=>C[0].index),ut())),k=Wt(V(b,Ee(({items:C})=>C.length>0),de(({items:C})=>{let E=0,_=C.length-1;for(;C[E].type==="group"&&E<_;)E++;for(;C[_].type==="group"&&_>E;)_--;return{endIndex:C[_].index,startIndex:C[E].index}}),ut(ou)));return{endReached:S,initialItemCount:v,itemsRendered:x,listState:b,rangeChanged:k,startReached:T,topItemsIndexes:y,...h}},ct(kn,cu,na,io,so,co,Gn,Ji),{singleton:!0}),xu=Ye(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:r},{listState:o}])=>{const s=Ve(),i=Pt(V(bt(n,e,r,t,o),de(([a,l,c,d,f])=>a+l+c+d+f.offsetBottom+f.bottom)),0);return ve(Te(i),s),{totalListHeight:i,totalListHeightChanged:s}},ct(Ft,hr),{singleton:!0}),Iy=Ye(([{viewportHeight:e},{totalListHeight:t}])=>{const n=J(!1),r=Pt(V(bt(n,e,t),Ee(([o])=>o),de(([,o,s])=>Math.max(0,o-s)),zn(0),ut()),0);return{alignToBottom:n,paddingTopAddition:r}},ct(Ft,xu),{singleton:!0}),yu=Ye(()=>({context:J(null)})),Ay=({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,vu=Ye(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:s,scrollingInProgress:i,scrollTop:a,viewportHeight:l},{scrollToIndex:c}])=>{const d=Ve();return ve(V(d,Le(t,l,n,s,o,r,a),Le(e),de(([[f,h,p,g,y,v,x,b],S])=>{const{align:T,behavior:k,calculateViewLocation:C=Ay,done:E,..._}=f,j=au(f,h,g-1),D=oo(j,h.offsetTree,S)+y+v,$=D+fn(h.sizeTree,j)[1],K=b+v,P=b+p-x,R=C({itemBottom:$,itemTop:D,locationParams:{align:T,behavior:k,..._},viewportBottom:P,viewportTop:K});return R?E&&dn(V(i,Ee(L=>!L),ur(xt(i)?1:2)),E):E&&E(),R}),Ee(f=>f!==null)),c),{scrollIntoView:d}},ct(kn,Ft,so,hr,qn),{singleton:!0});function bu(e){return e?e==="smooth"?"smooth":"auto":!1}const Ny=(e,t)=>typeof e=="function"?bu(e(t)):t&&bu(e),_y=Ye(([{listRefresh:e,totalCount:t,fixedItemSize:n,data:r},{atBottomState:o,isAtBottom:s},{scrollToIndex:i},{scrolledToInitialItem:a},{didMount:l,propsReady:c},{log:d},{scrollingInProgress:f},{context:h},{scrollIntoView:p}])=>{const g=J(!1),y=Ve();let v=null;function x(k){Pe(i,{align:"end",behavior:k,index:"LAST"})}Qe(V(bt(V(Te(t),ur(1)),l),Le(Te(g),s,a,f),de(([[k,C],E,_,j,D])=>{let $=C&&j,K="auto";return $&&(K=Ny(E,_||D),$=$&&!!K),{followOutputBehavior:K,shouldFollow:$,totalCount:k}}),Ee(({shouldFollow:k})=>k)),({followOutputBehavior:k,totalCount:C})=>{v&&(v(),v=null),xt(n)?requestAnimationFrame(()=>{xt(d)("following output to ",{totalCount:C},Ut.DEBUG),x(k)}):v=dn(e,()=>{xt(d)("following output to ",{totalCount:C},Ut.DEBUG),x(k),v=null})});function b(k){const C=dn(o,E=>{k&&!E.atBottom&&E.notAtBottomBecause==="SIZE_INCREASED"&&!v&&(xt(d)("scrolling to bottom due to increased size",{},Ut.DEBUG),x("auto"))});setTimeout(C,100)}Qe(V(bt(Te(g),t,c),Ee(([k,,C])=>k&&C),Cn(({value:k},[,C])=>({refreshed:k===C,value:C}),{refreshed:!1,value:0}),Ee(({refreshed:k})=>k),Le(g,t)),([,k])=>{xt(a)&&b(k!==!1)}),Qe(y,()=>{b(xt(g)!==!1)}),Qe(bt(Te(g),o),([k,C])=>{k&&!C.atBottom&&C.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&x("auto")});const S=J(null),T=Ve();return ve(Vi(V(Te(r),de(k=>{var C;return(C=k==null?void 0:k.length)!=null?C:0})),V(Te(t))),T),Qe(V(bt(V(T,ur(1)),l),Le(Te(S),a,f,h),de(([[k,C],E,_,j,D])=>C&&_&&(E==null?void 0:E({context:D,totalCount:k,scrollingInProgress:j}))),Ee(k=>!!k),zn(0)),k=>{v&&(v(),v=null),xt(n)?requestAnimationFrame(()=>{xt(d)("scrolling into view",{}),Pe(p,k)}):v=dn(e,()=>{xt(d)("scrolling into view",{}),Pe(p,k),v=null})}),{autoscrollToBottom:y,followOutput:g,scrollIntoViewOnChange:S}},ct(kn,co,so,io,Gn,qn,Ft,yu,vu)),jy=Ye(([{data:e,firstItemIndex:t,gap:n,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:s,listState:i},{didMount:a}])=>(ve(V(a,Le(s),Ee(([,l])=>l!==0),Le(o,r,t,n,e),de(([[,l],c,d,f,h,p=[]])=>mu(l,c,d,f,h,p))),i),{}),ct(kn,io,hr,Gn),{singleton:!0}),Ry=Ye(([{didMount:e},{scrollTo:t},{listState:n}])=>{const r=J(0);return Qe(V(e,Le(r),Ee(([,o])=>o!==0),de(([,o])=>({top:o}))),o=>{dn(V(n,ur(1),Ee(s=>s.items.length>1)),()=>{requestAnimationFrame(()=>{Pe(t,o)})})}),{initialScrollTop:r}},ct(Gn,Ft,hr),{singleton:!0}),wu=Ye(([{scrollVelocity:e}])=>{const t=J(!1),n=Ve(),r=J(!1);return ve(V(e,Le(r,t,n),Ee(([o,s])=>!!s),de(([o,s,i,a])=>{const{enter:l,exit:c}=s;if(i){if(c(o,a))return!1}else if(l(o,a))return!0;return i}),ut()),t),Qe(V(bt(t,e,n),Le(r)),([[o,s,i],a])=>{o&&a&&a.change&&a.change(s,i)}),{isSeeking:t,scrollSeekConfiguration:r,scrollSeekRangeChanged:n,scrollVelocity:e}},ct(co),{singleton:!0}),oa=Ye(([{scrollContainerState:e,scrollTo:t}])=>{const n=Ve(),r=Ve(),o=Ve(),s=J(!1),i=J(void 0);return ve(V(bt(n,r),de(([{scrollHeight:a,scrollTop:l,viewportHeight:c},{offsetTop:d}])=>({scrollHeight:a,scrollTop:Math.max(0,l-d),viewportHeight:c}))),e),ve(V(t,Le(r),de(([a,{offsetTop:l}])=>({...a,top:a.top+l}))),o),{customScrollParent:i,useWindowScroll:s,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:r}},ct(Ft)),Py=Ye(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:r},{initialTopMostItemIndex:o},{didMount:s},{useWindowScroll:i,windowScrollContainerState:a,windowViewportRect:l}])=>{const c=Ve(),d=J(void 0),f=J(null),h=J(null);return ve(a,f),ve(l,h),Qe(V(c,Le(t,r,i,f,h,n)),([p,g,y,v,x,b,S])=>{const T=gy(g.sizeTree);v&&x!==null&&b!==null&&(y=x.scrollTop-b.offsetTop),y-=S,p({ranges:T,scrollTop:y})}),ve(V(d,Ee(Ui),de(Oy)),o),ve(V(s,Le(d),Ee(([,p])=>p!==void 0),ut(),de(([,p])=>p.ranges)),e),{getState:c,restoreStateFrom:d}},ct(kn,Ft,io,Gn,oa));function Oy(e){return{align:"start",index:0,offset:e.scrollTop}}const My=Ye(([{topItemsIndexes:e}])=>{const t=J(0);return ve(V(t,Ee(n=>n>=0),de(n=>Array.from({length:n}).map((r,o)=>o))),e),{topItemCount:t}},ct(hr));function Su(e){let t=!1,n;return()=>(t||(t=!0,n=e()),n)}const Dy=Su(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),Ly=Ye(([{deviation:e,scrollBy:t,scrollingInProgress:n,scrollTop:r},{isAtBottom:o,isScrolling:s,lastJumpDueToItemResize:i,scrollDirection:a},{listState:l},{beforeUnshiftWith:c,gap:d,shiftWithOffset:f,sizes:h},{log:p},{recalcInProgress:g}])=>{const y=Wt(V(l,Le(i),Cn(([,x,b,S],[{bottom:T,items:k,offsetBottom:C,totalCount:E},_])=>{const j=T+C;let D=0;return b===E&&x.length>0&&k.length>0&&(k[0].originalIndex===0&&x[0].originalIndex===0||(D=j-S,D!==0&&(D+=_))),[D,k,E,j]},[0,[],0,0]),Ee(([x])=>x!==0),Le(r,a,n,o,p,g),Ee(([,x,b,S,,,T])=>!T&&!S&&x!==0&&b===ao),de(([[x],,,,,b])=>(b("Upward scrolling compensation",{amount:x},Ut.DEBUG),x))));function v(x){x>0?(Pe(t,{behavior:"auto",top:-x}),Pe(e,0)):(Pe(e,0),Pe(t,{behavior:"auto",top:-x}))}return Qe(V(y,Le(e,s)),([x,b,S])=>{S&&Dy()?Pe(e,b-x):v(-x)}),Qe(V(bt(Pt(s,!1),e,g),Ee(([x,b,S])=>!x&&!S&&b!==0),de(([x,b])=>b),zn(1)),v),ve(V(f,de(x=>({top:-x}))),t),Qe(V(c,Le(h,d),de(([x,{groupIndices:b,lastSize:S,sizeTree:T},k])=>{function C(E){return E*(S+k)}if(b.length===0)return C(x);{let E=0;const _=no(T,0);let j=0,D=0;for(;j<x;){j++,E+=_;let $=b.length===D+1?1/0:b[D+1]-b[D]-1;j+$>x&&(E-=_,$=x-j+1),j+=$,E+=C($),D++}return E}})),x=>{Pe(e,x),requestAnimationFrame(()=>{Pe(t,{top:x}),requestAnimationFrame(()=>{Pe(e,0),Pe(g,!1)})})}),{deviation:e}},ct(Ft,co,hr,kn,qn,Ji)),Fy=Ye(([e,t,n,r,o,s,i,a,l,c,d])=>({...e,...t,...n,...r,...o,...s,...i,...a,...l,...c,...d}),ct(na,jy,Gn,wu,xu,Ry,Iy,oa,vu,qn,yu)),Cu=Ye(([{data:e,defaultItemSize:t,firstItemIndex:n,fixedItemSize:r,gap:o,groupIndices:s,itemSize:i,sizeRanges:a,sizes:l,statefulTotalCount:c,totalCount:d,trackItemSizes:f},{initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:g},y,v,x,{listState:b,topItemsIndexes:S,...T},{scrollToIndex:k},C,{topItemCount:E},{groupCounts:_},j])=>(ve(T.rangeChanged,j.scrollSeekRangeChanged),ve(V(j.windowViewportRect,de(D=>D.visibleHeight)),y.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:r,gap:o,groupCounts:_,initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:g,sizeRanges:a,topItemCount:E,topItemsIndexes:S,totalCount:d,...x,groupIndices:s,itemSize:i,listState:b,scrollToIndex:k,statefulTotalCount:c,trackItemSizes:f,...T,...j,...y,sizes:l,...v}),ct(kn,io,Ft,Py,_y,hr,so,Ly,My,cu,Fy));function $y(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 as=typeof document<"u"?w.useLayoutEffect:w.useEffect;function ku(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=w.createContext({});function l(v,x){v.propsReady&&Pe(v.propsReady,!1);for(const b of r){const S=v[t.required[b]];Pe(S,x[b])}for(const b of o)if(b in x){const S=v[t.optional[b]];Pe(S,x[b])}v.propsReady&&Pe(v.propsReady,!0)}function c(v){return s.reduce((x,b)=>(x[b]=S=>{const T=v[t.methods[b]];Pe(T,S)},x),{})}function d(v){return i.reduce((x,b)=>(x[b]=ty(v[t.events[b]]),x),{})}const f=w.forwardRef((v,x)=>{const{children:b,...S}=v,[T]=w.useState(()=>Qo(ry(e),E=>{l(E,S)})),[k]=w.useState(Kc(d,T));as(()=>{for(const E of i)E in S&&Qe(k[E],S[E]);return()=>{Object.values(k).map(Wi)}},[S,k,T]),as(()=>{l(T,S)}),w.useImperativeHandle(x,Vc(c(T)));const C=n;return u.jsx(a.Provider,{value:T,children:n?u.jsx(C,{...$y([...r,...o,...i],S),children:b}):b})}),h=v=>{const x=w.useContext(a);return w.useCallback(b=>{Pe(x[v],b)},[x,v])},p=v=>{const x=w.useContext(a)[v],b=w.useCallback(S=>Qe(x,S),[x]);return w.useSyncExternalStore(b,()=>xt(x),()=>xt(x))},g=v=>{const x=w.useContext(a)[v],[b,S]=w.useState(Kc(xt,x));return as(()=>Qe(x,T=>{T!==b&&S(Vc(T))}),[x,b]),b},y=w.version.startsWith("18")?p:g;return{Component:f,useEmitter:(v,x)=>{const b=w.useContext(a)[v];as(()=>Qe(b,x),[x,b])},useEmitterValue:y,usePublisher:h}}const Tu=w.createContext(void 0),Eu=w.createContext(void 0),Iu=typeof document<"u"?w.useLayoutEffect:w.useEffect;function sa(e){return"self"in e}function zy(e){return"body"in e}function Au(e,t,n,r=jr,o,s){const i=w.useRef(null),a=w.useRef(null),l=w.useRef(null),c=w.useCallback(h=>{let p,g,y;const v=h.target;if(zy(v)||sa(v)){const b=sa(v)?v:v.defaultView;y=s?b.scrollX:b.scrollY,p=s?b.document.documentElement.scrollWidth:b.document.documentElement.scrollHeight,g=s?b.innerWidth:b.innerHeight}else y=s?v.scrollLeft:v.scrollTop,p=s?v.scrollWidth:v.scrollHeight,g=s?v.offsetWidth:v.offsetHeight;const x=()=>{e({scrollHeight:p,scrollTop:Math.max(y,0),viewportHeight:g})};h.suppressFlushSync?x():hi.flushSync(x),a.current!==null&&(y===a.current||y<=0||y===p-g)&&(a.current=null,t(!0),l.current&&(clearTimeout(l.current),l.current=null))},[e,t,s]);w.useEffect(()=>{const h=o||i.current;return r(o||i.current),c({suppressFlushSync:!0,target:h}),h.addEventListener("scroll",c,{passive:!0}),()=>{r(null),h.removeEventListener("scroll",c)}},[i,c,n,r,o]);function d(h){const p=i.current;if(!p||(s?"offsetWidth"in p&&p.offsetWidth===0:"offsetHeight"in p&&p.offsetHeight===0))return;const g=h.behavior==="smooth";let y,v,x;sa(p)?(v=Math.max(Kn(p.document.documentElement,s?"width":"height"),s?p.document.documentElement.scrollWidth:p.document.documentElement.scrollHeight),y=s?p.innerWidth:p.innerHeight,x=s?window.scrollX:window.scrollY):(v=p[s?"scrollWidth":"scrollHeight"],y=Kn(p,s?"width":"height"),x=p[s?"scrollLeft":"scrollTop"]);const b=v-y;if(h.top=Math.ceil(Math.max(Math.min(b,h.top),0)),du(y,v)||h.top===x){e({scrollHeight:v,scrollTop:x,viewportHeight:y}),g&&t(!0);return}g?(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 ia="-webkit-sticky",Nu="sticky",aa=Su(()=>{if(typeof document>"u")return Nu;const e=document.createElement("div");return e.style.position=ia,e.style.position===ia?ia:Nu});function la(e){return e}const By=Ye(()=>{const e=J(a=>`Item ${a}`),t=J(a=>`Group ${a}`),n=J({}),r=J(la),o=J("div"),s=J(jr),i=(a,l=null)=>Pt(V(n,de(c=>c[a]),ut()),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")}}),Hy=Ye(([e,t])=>({...e,...t}),ct(Cu,By)),Uy=({height:e})=>u.jsx("div",{style:{height:e}}),Wy={overflowAnchor:"none",position:aa(),zIndex:1},_u={overflowAnchor:"none"},Vy={..._u,display:"inline-block",height:"100%"},ju=w.memo(function({showTopList:e=!1}){const t=Ne("listState"),n=en("sizeRanges"),r=Ne("useWindowScroll"),o=Ne("customScrollParent"),s=en("windowScrollContainerState"),i=en("scrollContainerState"),a=o||r?s:i,l=Ne("itemContent"),c=Ne("context"),d=Ne("groupContent"),f=Ne("trackItemSizes"),h=Ne("itemSize"),p=Ne("log"),g=en("gap"),y=Ne("horizontalDirection"),{callbackRef:v}=iy(n,h,f,e?jr:a,p,g,o,y,Ne("skipAnimationFrameInResizeObserver")),[x,b]=w.useState(0);ca("deviation",R=>{x!==R&&b(R)});const S=Ne("EmptyPlaceholder"),T=Ne("ScrollSeekPlaceholder")||Uy,k=Ne("ListComponent"),C=Ne("ItemComponent"),E=Ne("GroupComponent"),_=Ne("computeItemKey"),j=Ne("isSeeking"),D=Ne("groupIndices").length>0,$=Ne("alignToBottom"),K=Ne("initialItemFinalLocationReached"),P=e?{}:{boxSizing:"border-box",...y?{display:"inline-block",height:"100%",marginLeft:x!==0?x:$?"auto":0,paddingLeft:t.offsetTop,paddingRight:t.offsetBottom,whiteSpace:"nowrap"}:{marginTop:x!==0?x:$?"auto":0,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...K?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&S?u.jsx(S,{...Ot(S,c)}):u.jsx(k,{...Ot(k,c),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:v,style:P,children:(e?t.topItems:t.items).map(R=>{const L=R.originalIndex,F=_(L+t.firstItemIndex,R.data,c);return j?w.createElement(T,{...Ot(T,c),height:R.size,index:R.index,key:F,type:R.type||"item",...R.type==="group"?{}:{groupIndex:R.groupIndex}}):R.type==="group"?w.createElement(E,{...Ot(E,c),"data-index":L,"data-item-index":R.index,"data-known-size":R.size,key:F,style:Wy},d(R.index,c)):w.createElement(C,{...Ot(C,c),...Yy(C,R.data),"data-index":L,"data-item-group-index":R.groupIndex,"data-item-index":R.index,"data-known-size":R.size,key:F,style:y?Vy:_u},D?l(R.index,R.groupIndex,R.data,c):l(R.index,R.data,c))})})}),qy={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},Ky={outline:"none",overflowX:"auto",position:"relative"},ls=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:{}}),Gy={position:aa(),top:0,width:"100%",zIndex:1};function Ot(e,t){if(typeof e!="string")return{context:t}}function Yy(e,t){return{item:typeof e=="string"?void 0:t}}const Xy=w.memo(function(){const e=Ne("HeaderComponent"),t=en("headerHeight"),n=Ne("HeaderFooterTag"),r=dr(w.useMemo(()=>s=>{t(Kn(s,"height"))},[t]),!0,Ne("skipAnimationFrameInResizeObserver")),o=Ne("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Ot(e,o)})}):null}),Jy=w.memo(function(){const e=Ne("FooterComponent"),t=en("footerHeight"),n=Ne("HeaderFooterTag"),r=dr(w.useMemo(()=>s=>{t(Kn(s,"height"))},[t]),!0,Ne("skipAnimationFrameInResizeObserver")),o=Ne("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Ot(e,o)})}):null});function Ru({useEmitter:e,useEmitterValue:t,usePublisher:n}){return w.memo(function({children:r,style:o,context:s,...i}){const a=n("scrollContainerState"),l=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=t("scrollerRef"),f=t("horizontalDirection")||!1,{scrollByCallback:h,scrollerRef:p,scrollToCallback:g}=Au(a,c,l,d,void 0,f);return e("scrollTo",g),e("scrollBy",h),u.jsx(l,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:p,style:{...f?Ky:qy,...o},tabIndex:0,...i,...Ot(l,s),children:r})})}function Pu({useEmitter:e,useEmitterValue:t,usePublisher:n}){return w.memo(function({children:r,style:o,context:s,...i}){const a=n("windowScrollContainerState"),l=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=t("totalListHeight"),f=t("deviation"),h=t("customScrollParent"),p=w.useRef(null),g=t("scrollerRef"),{scrollByCallback:y,scrollerRef:v,scrollToCallback:x}=Au(a,c,l,g,h);return Iu(()=>{var b;return v.current=h||((b=p.current)==null?void 0:b.ownerDocument.defaultView),()=>{v.current=null}},[v,h]),e("windowScrollTo",x),e("scrollBy",y),u.jsx(l,{ref:p,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...d!==0?{height:d+f}:{}},...i,...Ot(l,s),children:r})})}const Zy=({children:e})=>{const t=w.useContext(Tu),n=en("viewportHeight"),r=en("fixedItemHeight"),o=Ne("alignToBottom"),s=Ne("horizontalDirection"),i=w.useMemo(()=>qc(n,l=>Kn(l,s?"width":"height")),[n,s]),a=dr(i,!0,Ne("skipAnimationFrameInResizeObserver"));return w.useEffect(()=>{t&&(n(t.viewportHeight),r(t.itemHeight))},[t,n,r]),u.jsx("div",{"data-viewport-type":"element",ref:a,style:ls(o),children:e})},Qy=({children:e})=>{const t=w.useContext(Tu),n=en("windowViewportRect"),r=en("fixedItemHeight"),o=Ne("customScrollParent"),s=Jc(n,o,Ne("skipAnimationFrameInResizeObserver")),i=Ne("alignToBottom");return w.useEffect(()=>{t&&(r(t.itemHeight),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:100}))},[t,n,r]),u.jsx("div",{"data-viewport-type":"window",ref:s,style:ls(i),children:e})},ev=({children:e})=>{const t=Ne("TopItemListComponent")||"div",n=Ne("headerHeight"),r={...Gy,marginTop:`${n}px`},o=Ne("context");return u.jsx(t,{style:r,...Ot(t,o),children:e})},tv=w.memo(function(e){const t=Ne("useWindowScroll"),n=Ne("topItemsIndexes").length>0,r=Ne("customScrollParent"),o=Ne("context");return u.jsxs(r||t?ov:rv,{...e,context:o,children:[n&&u.jsx(ev,{children:u.jsx(ju,{showTopList:!0})}),u.jsxs(r||t?Qy:Zy,{children:[u.jsx(Xy,{}),u.jsx(ju,{}),u.jsx(Jy,{})]})]})}),{Component:nv,useEmitter:ca,useEmitterValue:Ne,usePublisher:en}=ku(Hy,{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"}},tv),rv=Ru({useEmitter:ca,useEmitterValue:Ne,usePublisher:en}),ov=Pu({useEmitter:ca,useEmitterValue:Ne,usePublisher:en}),sv=nv;ct(Cu,Ye(()=>{const e=J(c=>u.jsxs("td",{children:["Item $",c]})),t=J(null),n=J(c=>u.jsxs("td",{colSpan:1e3,children:["Group ",c]})),r=J(null),o=J(null),s=J({}),i=J(la),a=J(jr),l=(c,d=null)=>Pt(V(s,de(f=>f[c]),ut()),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")}})),aa();const Ou={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},iv={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:Mu,floor:cs,max:uo,min:ua,round:Du}=Math;function Lu(e,t,n){return Array.from({length:t-e+1}).map((r,o)=>({data:n===null?null:n[o+e],index:o+e}))}function av(e){return{...iv,items:e}}function us(e,t){return e&&e.width===t.width&&e.height===t.height}function lv(e,t){return e&&e.column===t.column&&e.row===t.row}const cv=Ye(([{increaseViewportBy:e,listBoundary:t,overscan:n,visibleRange:r},{footerHeight:o,headerHeight:s,scrollBy:i,scrollContainerState:a,scrollTo:l,scrollTop:c,smoothScrollTargetReached:d,viewportHeight:f},h,p,{didMount:g,propsReady:y},{customScrollParent:v,useWindowScroll:x,windowScrollContainerState:b,windowScrollTo:S,windowViewportRect:T},k])=>{const C=J(0),E=J(0),_=J(Ou),j=J({height:0,width:0}),D=J({height:0,width:0}),$=Ve(),K=Ve(),P=J(0),R=J(null),L=J({column:0,row:0}),F=Ve(),ne=Ve(),q=J(!1),B=J(0),pe=J(!0),W=J(!1),ce=J(!1);Qe(V(g,Le(B),Ee(([M,X])=>!!X)),()=>{Pe(pe,!1)}),Qe(V(bt(g,pe,D,j,B,W),Ee(([M,X,oe,xe,,se])=>M&&!X&&oe.height!==0&&xe.height!==0&&!se)),([,,,,M])=>{Pe(W,!0),ea(1,()=>{Pe($,M)}),dn(V(c),()=>{Pe(t,[0,0]),Pe(pe,!0)})}),ve(V(ne,Ee(M=>M!=null&&M.scrollTop>0),Sn(0)),E),Qe(V(g,Le(ne),Ee(([,M])=>M!=null)),([,M])=>{M&&(Pe(j,M.viewport),Pe(D,M.item),Pe(L,M.gap),M.scrollTop>0&&(Pe(q,!0),dn(V(c,ur(1)),X=>{Pe(q,!1)}),Pe(l,{top:M.scrollTop})))}),ve(V(j,de(({height:M})=>M)),f),ve(V(bt(Te(j,us),Te(D,us),Te(L,(M,X)=>M&&M.column===X.column&&M.row===X.row),Te(c)),de(([M,X,oe,xe])=>({gap:oe,item:X,scrollTop:xe,viewport:M}))),F),ve(V(bt(Te(C),r,Te(L,lv),Te(D,us),Te(j,us),Te(R),Te(E),Te(q),Te(pe),Te(B)),Ee(([,,,,,,,M])=>!M),de(([M,[X,oe],xe,se,re,Ue,qe,,ot,at])=>{const{column:ht,row:tt}=xe,{height:Me,width:We}=se,{width:lt}=re;if(qe===0&&(M===0||lt===0))return Ou;if(We===0){const Oe=ta(at,M),Xe=Oe+Math.max(qe-1,0);return av(Lu(Oe,Xe,Ue))}const yt=Fu(lt,We,ht);let dt,Je;ot?X===0&&oe===0&&qe>0?(dt=0,Je=qe-1):(dt=yt*cs((X+tt)/(Me+tt)),Je=yt*Mu((oe+tt)/(Me+tt))-1,Je=ua(M-1,uo(Je,yt-1)),dt=ua(Je,uo(0,dt))):(dt=0,Je=-1);const ie=Lu(dt,Je,Ue),{bottom:je,top:ke}=$u(re,xe,se,ie),Ke=Mu(M/yt),nt=Ke*Me+(Ke-1)*tt-je;return{bottom:je,itemHeight:Me,items:ie,itemWidth:We,offsetBottom:nt,offsetTop:ke,top:ke}})),_),ve(V(R,Ee(M=>M!==null),de(M=>M.length)),C),ve(V(bt(j,D,_,L),Ee(([M,X,{items:oe}])=>oe.length>0&&X.height!==0&&M.height!==0),de(([M,X,{items:oe},xe])=>{const{bottom:se,top:re}=$u(M,xe,X,oe);return[re,se]}),ut(ro)),t);const H=J(!1);ve(V(c,Le(H),de(([M,X])=>X||M!==0)),H);const Z=Wt(V(bt(_,C),Ee(([{items:M}])=>M.length>0),Le(H),Ee(([[M,X],oe])=>{const xe=M.items[M.items.length-1].index===X-1;return(oe||M.bottom>0&&M.itemHeight>0&&M.offsetBottom===0&&M.items.length===X)&&xe}),de(([[,M]])=>M-1),ut())),be=Wt(V(Te(_),Ee(({items:M})=>M.length>0&&M[0].index===0),Sn(0),ut())),ye=Wt(V(Te(_),Le(q),Ee(([{items:M},X])=>M.length>0&&!X),de(([{items:M}])=>({endIndex:M[M.length-1].index,startIndex:M[0].index})),ut(ou),zn(0)));ve(ye,p.scrollSeekRangeChanged),ve(V($,Le(j,D,C,L),de(([M,X,oe,xe,se])=>{const re=uu(M),{align:Ue,behavior:qe,offset:ot}=re;let at=re.index;at==="LAST"&&(at=xe-1),at=uo(0,at,ua(xe-1,at));let ht=da(X,se,oe,at);return Ue==="end"?ht=Du(ht-X.height+oe.height):Ue==="center"&&(ht=Du(ht-X.height/2+oe.height/2)),ot&&(ht+=ot),{behavior:qe,top:ht}})),l);const G=Pt(V(_,de(M=>M.offsetBottom+M.bottom)),0);return ve(V(T,de(M=>({height:M.visibleHeight,width:M.visibleWidth}))),j),{customScrollParent:v,data:R,deviation:P,footerHeight:o,gap:L,headerHeight:s,increaseViewportBy:e,initialItemCount:E,itemDimensions:D,overscan:n,restoreStateFrom:ne,scrollBy:i,scrollContainerState:a,scrollHeight:K,scrollTo:l,scrollToIndex:$,scrollTop:c,smoothScrollTargetReached:d,totalCount:C,useWindowScroll:x,viewportDimensions:j,windowScrollContainerState:b,windowScrollTo:S,windowViewportRect:T,...p,gridState:_,horizontalDirection:ce,initialTopMostItemIndex:B,totalListHeight:G,...h,endReached:Z,propsReady:y,rangeChanged:ye,startReached:be,stateChanged:F,stateRestoreInProgress:q,...k}},ct(na,Ft,co,wu,Gn,oa,qn));function Fu(e,t,n){return uo(1,cs((e+n)/(cs(t)+n)))}function $u(e,t,n,r){const{height:o}=n;if(o===void 0||r.length===0)return{bottom:0,top:0};const s=da(e,t,n,r[0].index);return{bottom:da(e,t,n,r[r.length-1].index)+o,top:s}}function da(e,t,n,r){const o=Fu(e.width,n.width,t.column),s=cs(r/o),i=s*n.height+uo(0,s-1)*t.row;return i>0?i+t.row:i}const uv=Ye(()=>{const e=J(f=>`Item ${f}`),t=J({}),n=J(null),r=J("virtuoso-grid-item"),o=J("virtuoso-grid-list"),s=J(la),i=J("div"),a=J(jr),l=(f,h=null)=>Pt(V(t,de(p=>p[f]),ut()),h),c=J(!1),d=J(!1);return ve(Te(d),c),{components:t,computeItemKey:s,context:n,FooterComponent:l("Footer"),HeaderComponent:l("Header"),headerFooterTag:i,itemClassName:r,ItemComponent:l("Item","div"),itemContent:e,listClassName:o,ListComponent:l("List","div"),readyStateChanged:c,reportReadyState:d,ScrollerComponent:l("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder","div")}}),dv=Ye(([e,t])=>({...e,...t}),ct(cv,uv)),fv=w.memo(function(){const e=ft("gridState"),t=ft("listClassName"),n=ft("itemClassName"),r=ft("itemContent"),o=ft("computeItemKey"),s=ft("isSeeking"),i=tn("scrollHeight"),a=ft("ItemComponent"),l=ft("ListComponent"),c=ft("ScrollSeekPlaceholder"),d=ft("context"),f=tn("itemDimensions"),h=tn("gap"),p=ft("log"),g=ft("stateRestoreInProgress"),y=tn("reportReadyState"),v=dr(w.useMemo(()=>x=>{const b=x.parentElement.parentElement.scrollHeight;i(b);const S=x.firstChild;if(S){const{height:T,width:k}=S.getBoundingClientRect();f({height:T,width:k})}h({column:Bu("column-gap",getComputedStyle(x).columnGap,p),row:Bu("row-gap",getComputedStyle(x).rowGap,p)})},[i,f,h,p]),!0,!1);return Iu(()=>{e.itemHeight>0&&e.itemWidth>0&&y(!0)},[e]),g?null:u.jsx(l,{className:t,ref:v,...Ot(l,d),"data-testid":"virtuoso-item-list",style:{paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},children:e.items.map(x=>{const b=o(x.index,x.data,d);return s?u.jsx(c,{...Ot(c,d),height:e.itemHeight,index:x.index,width:e.itemWidth},b):w.createElement(a,{...Ot(a,d),className:n,"data-index":x.index,key:b},r(x.index,x.data,d))})})}),hv=w.memo(function(){const e=ft("HeaderComponent"),t=tn("headerHeight"),n=ft("headerFooterTag"),r=dr(w.useMemo(()=>s=>{t(Kn(s,"height"))},[t]),!0,!1),o=ft("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Ot(e,o)})}):null}),pv=w.memo(function(){const e=ft("FooterComponent"),t=tn("footerHeight"),n=ft("headerFooterTag"),r=dr(w.useMemo(()=>s=>{t(Kn(s,"height"))},[t]),!0,!1),o=ft("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Ot(e,o)})}):null}),mv=({children:e})=>{const t=w.useContext(Eu),n=tn("itemDimensions"),r=tn("viewportDimensions"),o=dr(w.useMemo(()=>s=>{r(s.getBoundingClientRect())},[r]),!0,!1);return w.useEffect(()=>{t&&(r({height:t.viewportHeight,width:t.viewportWidth}),n({height:t.itemHeight,width:t.itemWidth}))},[t,r,n]),u.jsx("div",{ref:o,style:ls(!1),children:e})},gv=({children:e})=>{const t=w.useContext(Eu),n=tn("windowViewportRect"),r=tn("itemDimensions"),o=ft("customScrollParent"),s=Jc(n,o,!1);return w.useEffect(()=>{t&&(r({height:t.itemHeight,width:t.itemWidth}),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:t.viewportWidth}))},[t,n,r]),u.jsx("div",{ref:s,style:ls(!1),children:e})},xv=w.memo(function({...e}){const t=ft("useWindowScroll"),n=ft("customScrollParent"),r=n||t?vv:yv,o=n||t?gv:mv,s=ft("context");return u.jsx(r,{...e,...Ot(r,s),children:u.jsxs(o,{children:[u.jsx(hv,{}),u.jsx(fv,{}),u.jsx(pv,{})]})})}),{useEmitter:zu,useEmitterValue:ft,usePublisher:tn}=ku(dv,{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"}},xv),yv=Ru({useEmitter:zu,useEmitterValue:ft,usePublisher:tn}),vv=Pu({useEmitter:zu,useEmitterValue:ft,usePublisher:tn});function Bu(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,Ut.WARN),t==="normal"?0:parseInt(t??"0",10)}const bv=Ro.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 Hu({className:e,variant:t,...n}){return u.jsx("div",{className:ee(bv({variant:t}),e),...n})}const fo=m.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ee("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));fo.displayName="Card";const ho=m.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ee("flex flex-col space-y-1.5 p-6",e),...t}));ho.displayName="CardHeader";const po=m.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:ee("text-2xl font-semibold leading-none tracking-tight",e),...t}));po.displayName="CardTitle";const Uu=m.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:ee("text-sm text-muted-foreground",e),...t}));Uu.displayName="CardDescription";const mo=m.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ee("p-6 pt-0",e),...t}));mo.displayName="CardContent";const Wu=m.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ee("flex items-center p-6 pt-0",e),...t}));Wu.displayName="CardFooter";function ge(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function wv(e,t){const n=m.createContext(t),r=s=>{const{children:i,...a}=s,l=m.useMemo(()=>a,Object.values(a));return u.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 Tn(e,t=[]){let n=[];function r(s,i){const a=m.createContext(i),l=n.length;n=[...n,i];const c=f=>{var x;const{scope:h,children:p,...g}=f,y=((x=h==null?void 0:h[e])==null?void 0:x[l])||a,v=m.useMemo(()=>g,Object.values(g));return u.jsx(y.Provider,{value:v,children:p})};c.displayName=s+"Provider";function d(f,h){var y;const p=((y=h==null?void 0:h[e])==null?void 0:y[l])||a,g=m.useContext(p);if(g)return g;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>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,Sv(o,...t)]}function Sv(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const f=l(s)[`__scope${c}`];return{...a,...f}},{});return m.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var kt=globalThis!=null&&globalThis.document?m.useLayoutEffect:()=>{},Cv=m[" useInsertionEffect ".trim().toString()]||kt;function pr({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=kv({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 c=m.useCallback(d=>{var f;if(a){const h=Tv(d)?d(e):d;h!==e&&((f=i.current)==null||f.call(i,h))}else s(d)},[a,e,s,i]);return[l,c]}function kv({defaultProp:e,onChange:t}){const[n,r]=m.useState(e),o=m.useRef(n),s=m.useRef(t);return Cv(()=>{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 Tv(e){return typeof e=="function"}function Vu(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function fa(...e){return t=>{let n=!1;const r=e.map(o=>{const s=Vu(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():Vu(e[o],null)}}}}function He(...e){return m.useCallback(fa(...e),e)}var Ev=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ie=Ev.reduce((e,t)=>{const n=sr.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),u.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function qu(e,t){e&&Po.flushSync(()=>e.dispatchEvent(t))}function Iv(e,t){return m.useReducer((n,r)=>t[n][r]??n,e)}var qt=e=>{const{present:t,children:n}=e,r=Av(t),o=typeof n=="function"?n({present:r.isPresent}):m.Children.only(n),s=He(r.ref,Nv(o));return typeof n=="function"||r.isPresent?m.cloneElement(o,{ref:s}):null};qt.displayName="Presence";function Av(e){const[t,n]=m.useState(),r=m.useRef(null),o=m.useRef(e),s=m.useRef("none"),i=e?"mounted":"unmounted",[a,l]=Iv(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return m.useEffect(()=>{const c=ds(r.current);s.current=a==="mounted"?c:"none"},[a]),kt(()=>{const c=r.current,d=o.current;if(d!==e){const h=s.current,p=ds(c);e?l("MOUNT"):p==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(d&&h!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),kt(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,f=p=>{const y=ds(r.current).includes(CSS.escape(p.animationName));if(p.target===t&&y&&(l("ANIMATION_END"),!o.current)){const v=t.style.animationFillMode;t.style.animationFillMode="forwards",c=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=v)})}},h=p=>{p.target===t&&(s.current=ds(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{d.clearTimeout(c),t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:m.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function ds(e){return(e==null?void 0:e.animationName)||"none"}function Nv(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 _v=m[" useId ".trim().toString()]||(()=>{}),jv=0;function En(e){const[t,n]=m.useState(_v());return kt(()=>{n(r=>r??String(jv++))},[e]),e||(t?`radix-${t}`:"")}var fs="Collapsible",[Rv,pT]=Tn(fs),[Pv,ha]=Rv(fs),Ku=m.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:o,disabled:s,onOpenChange:i,...a}=e,[l,c]=pr({prop:r,defaultProp:o??!1,onChange:i,caller:fs});return u.jsx(Pv,{scope:n,disabled:s,contentId:En(),open:l,onOpenToggle:m.useCallback(()=>c(d=>!d),[c]),children:u.jsx(Ie.div,{"data-state":ma(l),"data-disabled":s?"":void 0,...a,ref:t})})});Ku.displayName=fs;var Gu="CollapsibleTrigger",Yu=m.forwardRef((e,t)=>{const{__scopeCollapsible:n,...r}=e,o=ha(Gu,n);return u.jsx(Ie.button,{type:"button","aria-controls":o.contentId,"aria-expanded":o.open||!1,"data-state":ma(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...r,ref:t,onClick:ge(e.onClick,o.onOpenToggle)})});Yu.displayName=Gu;var pa="CollapsibleContent",Ov=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=ha(pa,e.__scopeCollapsible);return u.jsx(qt,{present:n||o.open,children:({present:s})=>u.jsx(Mv,{...r,ref:t,present:s})})});Ov.displayName=pa;var Mv=m.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:r,children:o,...s}=e,i=ha(pa,n),[a,l]=m.useState(r),c=m.useRef(null),d=He(t,c),f=m.useRef(0),h=f.current,p=m.useRef(0),g=p.current,y=i.open||a,v=m.useRef(y),x=m.useRef(void 0);return m.useEffect(()=>{const b=requestAnimationFrame(()=>v.current=!1);return()=>cancelAnimationFrame(b)},[]),kt(()=>{const b=c.current;if(b){x.current=x.current||{transitionDuration:b.style.transitionDuration,animationName:b.style.animationName},b.style.transitionDuration="0s",b.style.animationName="none";const S=b.getBoundingClientRect();f.current=S.height,p.current=S.width,v.current||(b.style.transitionDuration=x.current.transitionDuration,b.style.animationName=x.current.animationName),l(r)}},[i.open,r]),u.jsx(Ie.div,{"data-state":ma(i.open),"data-disabled":i.disabled?"":void 0,id:i.contentId,hidden:!y,...s,ref:d,style:{"--radix-collapsible-content-height":h?`${h}px`:void 0,"--radix-collapsible-content-width":g?`${g}px`:void 0,...e.style},children:y&&o})});function ma(e){return e?"open":"closed"}var Dv=Ku;const Lv=Dv,Fv=Yu,$v=1,zv=1e6;let ga=0;function Bv(){return ga=(ga+1)%Number.MAX_SAFE_INTEGER,ga.toString()}const xa=new Map,Xu=e=>{if(xa.has(e))return;const t=setTimeout(()=>{xa.delete(e),go({type:"REMOVE_TOAST",toastId:e})},zv);xa.set(e,t)},Hv=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,$v)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?Xu(n):e.toasts.forEach(r=>{Xu(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},hs=[];let ps={toasts:[]};function go(e){ps=Hv(ps,e),hs.forEach(t=>{t(ps)})}function Uv({...e}){const t=Bv(),n=o=>go({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>go({type:"DISMISS_TOAST",toastId:t});return go({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function ya(){const[e,t]=m.useState(ps);return m.useEffect(()=>(hs.push(t),()=>{const n=hs.indexOf(t);n>-1&&hs.splice(n,1)}),[e]),{...e,toast:Uv,dismiss:n=>go({type:"DISMISS_TOAST",toastId:n})}}async function Ju(e,t){return await cn(e,{responseType:"blob",onDownloadProgress:r=>{try{t&&r.lengthComputable}catch{}},maxBodyLength:1/0})}async function Zu(e,t){return await(await Ju(`/files/${e}/view`,t)).text()}async function Wv(e,t){const n=await Ju(`/files/${e}/download`,t),r=URL.createObjectURL(n);let o=`file_${e}`;try{const i=await cn(`/files/${e}`);o=(i==null?void 0:i.filename)??o}catch{}const s=document.createElement("a");s.href=r,s.download=o,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}async function Vv(e,t=50,n=0){const r={limit:t,offset:n};return e&&(r.thread_id=e),await cn("/files",{params:r})}function Qu(e){const t=e==null?void 0:e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return null;try{return JSON.parse(t)}catch{return null}}function ed(e){return!!(e&&typeof e=="object"&&(e.type==="file"||e.mimeType||e.filename||e.sourceType==="base64"))}function xo(e){if(typeof e=="string")return e.length>2e3?e.slice(0,2e3)+"... [truncated]":e;if(e&&typeof e=="object"){if(Array.isArray(e)){const n=e.map(xo).filter(r=>r!==void 0);if(!n.length){console.debug("[message-utils] sanitizeForDisplay - array emptied -> returning undefined",{originalLength:e.length});return}return n}if(ed(e)){try{console.debug("[message-utils] sanitizeForDisplay - dropping file-like object",{sampleFilename:e&&(e.filename||e.name)?e.filename||e.name:void 0,keys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - dropped file-like (unable to inspect)",{err:String(n)})}return}const t={};for(const n of Object.keys(e)){const r=e[n];if(n==="data"&&typeof r=="string"&&r.length>100)t[n]=`[base64 ${r.length} chars omitted]`;else{const o=xo(r);o!==void 0&&(t[n]=o)}}if(Object.keys(t).length)return t;try{console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined",{originalKeys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined (inspect failed)",{err:String(n)})}return}return e}function ms(e){if(typeof e=="string")return e;if(ed(e))return"";try{const t=xo(e);return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}catch{return""}}function At(e){const t=m.useRef(e);return m.useEffect(()=>{t.current=e}),m.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function qv(e,t=globalThis==null?void 0:globalThis.document){const n=At(e);m.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var Kv="DismissableLayer",va="dismissableLayer.update",Gv="dismissableLayer.pointerDownOutside",Yv="dismissableLayer.focusOutside",td,nd=m.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),gs=m.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=m.useContext(nd),[d,f]=m.useState(null),h=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=m.useState({}),g=He(t,E=>f(E)),y=Array.from(c.layers),[v]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),x=y.indexOf(v),b=d?y.indexOf(d):-1,S=c.layersWithOutsidePointerEventsDisabled.size>0,T=b>=x,k=Zv(E=>{const _=E.target,j=[...c.branches].some(D=>D.contains(_));!T||j||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},h),C=Qv(E=>{const _=E.target;[...c.branches].some(D=>D.contains(_))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},h);return qv(E=>{b===c.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},h),m.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(td=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),rd(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=td)}},[d,h,n,c]),m.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),rd())},[d,c]),m.useEffect(()=>{const E=()=>p({});return document.addEventListener(va,E),()=>document.removeEventListener(va,E)},[]),u.jsx(Ie.div,{...l,ref:g,style:{pointerEvents:S?T?"auto":"none":void 0,...e.style},onFocusCapture:ge(e.onFocusCapture,C.onFocusCapture),onBlurCapture:ge(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:ge(e.onPointerDownCapture,k.onPointerDownCapture)})});gs.displayName=Kv;var Xv="DismissableLayerBranch",Jv=m.forwardRef((e,t)=>{const n=m.useContext(nd),r=m.useRef(null),o=He(t,r);return m.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(Ie.div,{...e,ref:o})});Jv.displayName=Xv;function Zv(e,t=globalThis==null?void 0:globalThis.document){const n=At(e),r=m.useRef(!1),o=m.useRef(()=>{});return m.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){od(Gv,n,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function Qv(e,t=globalThis==null?void 0:globalThis.document){const n=At(e),r=m.useRef(!1);return m.useEffect(()=>{const o=s=>{s.target&&!r.current&&od(Yv,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function rd(){const e=new CustomEvent(va);document.dispatchEvent(e)}function od(e,t,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?qu(o,s):o.dispatchEvent(s)}var ba="focusScope.autoFocusOnMount",wa="focusScope.autoFocusOnUnmount",sd={bubbles:!1,cancelable:!0},eb="FocusScope",xs=m.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=m.useState(null),c=At(o),d=At(s),f=m.useRef(null),h=He(t,y=>l(y)),p=m.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;m.useEffect(()=>{if(r){let y=function(S){if(p.paused||!a)return;const T=S.target;a.contains(T)?f.current=T:Yn(f.current,{select:!0})},v=function(S){if(p.paused||!a)return;const T=S.relatedTarget;T!==null&&(a.contains(T)||Yn(f.current,{select:!0}))},x=function(S){if(document.activeElement===document.body)for(const k of S)k.removedNodes.length>0&&Yn(a)};document.addEventListener("focusin",y),document.addEventListener("focusout",v);const b=new MutationObserver(x);return a&&b.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",y),document.removeEventListener("focusout",v),b.disconnect()}}},[r,a,p.paused]),m.useEffect(()=>{if(a){ld.add(p);const y=document.activeElement;if(!a.contains(y)){const x=new CustomEvent(ba,sd);a.addEventListener(ba,c),a.dispatchEvent(x),x.defaultPrevented||(tb(ib(id(a)),{select:!0}),document.activeElement===y&&Yn(a))}return()=>{a.removeEventListener(ba,c),setTimeout(()=>{const x=new CustomEvent(wa,sd);a.addEventListener(wa,d),a.dispatchEvent(x),x.defaultPrevented||Yn(y??document.body,{select:!0}),a.removeEventListener(wa,d),ld.remove(p)},0)}}},[a,c,d,p]);const g=m.useCallback(y=>{if(!n&&!r||p.paused)return;const v=y.key==="Tab"&&!y.altKey&&!y.ctrlKey&&!y.metaKey,x=document.activeElement;if(v&&x){const b=y.currentTarget,[S,T]=nb(b);S&&T?!y.shiftKey&&x===T?(y.preventDefault(),n&&Yn(S,{select:!0})):y.shiftKey&&x===S&&(y.preventDefault(),n&&Yn(T,{select:!0})):x===b&&y.preventDefault()}},[n,r,p.paused]);return u.jsx(Ie.div,{tabIndex:-1,...i,ref:h,onKeyDown:g})});xs.displayName=eb;function tb(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Yn(r,{select:t}),document.activeElement!==n)return}function nb(e){const t=id(e),n=ad(t,e),r=ad(t.reverse(),e);return[n,r]}function id(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function ad(e,t){for(const n of e)if(!rb(n,{upTo:t}))return n}function rb(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function ob(e){return e instanceof HTMLInputElement&&"select"in e}function Yn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&ob(e)&&t&&e.select()}}var ld=sb();function sb(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=cd(e,t),e.unshift(t)},remove(t){var n;e=cd(e,t),(n=e[0])==null||n.resume()}}}function cd(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function ib(e){return e.filter(t=>t.tagName!=="A")}var ab="Portal",ys=m.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=m.useState(!1);kt(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?hi.createPortal(u.jsx(Ie.div,{...r,ref:t}),i):null});ys.displayName=ab;var Sa=0;function Ca(){m.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??ud()),document.body.insertAdjacentElement("beforeend",e[1]??ud()),Sa++,()=>{Sa===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Sa--}},[])}function ud(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var In=function(){return In=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},In.apply(this,arguments)};function dd(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function lb(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}typeof SuppressedError=="function"&&SuppressedError;var vs="right-scroll-bar-position",bs="width-before-scroll-bar",cb="with-scroll-bars-hidden",ub="--removed-body-scroll-bar-size";function ka(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function db(e,t){var n=w.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var fb=typeof window<"u"?m.useLayoutEffect:m.useEffect,fd=new WeakMap;function hb(e,t){var n=db(null,function(r){return e.forEach(function(o){return ka(o,r)})});return fb(function(){var r=fd.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||ka(a,null)}),s.forEach(function(a){o.has(a)||ka(a,i)})}fd.set(n,e)},[e]),n}function pb(e){return e}function mb(e,t){t===void 0&&(t=pb);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(s){var i=t(s,r);return n.push(i),function(){n=n.filter(function(a){return a!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var a=n;n=[],a.forEach(s),i=n}var l=function(){var d=i;i=[],d.forEach(s)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(d){i.push(d),c()},filter:function(d){return i=i.filter(d),n}}}};return o}function gb(e){e===void 0&&(e={});var t=mb(null);return t.options=In({async:!0,ssr:!1},e),t}var hd=function(e){var t=e.sideCar,n=dd(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return m.createElement(r,In({},n))};hd.isSideCarExport=!0;function xb(e,t){return e.useMedium(t),hd}var pd=gb(),Ta=function(){},ws=m.forwardRef(function(e,t){var n=m.useRef(null),r=m.useState({onScrollCapture:Ta,onWheelCapture:Ta,onTouchMoveCapture:Ta}),o=r[0],s=r[1],i=e.forwardProps,a=e.children,l=e.className,c=e.removeScrollBar,d=e.enabled,f=e.shards,h=e.sideCar,p=e.noRelative,g=e.noIsolation,y=e.inert,v=e.allowPinchZoom,x=e.as,b=x===void 0?"div":x,S=e.gapMode,T=dd(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=h,C=hb([n,t]),E=In(In({},T),o);return m.createElement(m.Fragment,null,d&&m.createElement(k,{sideCar:pd,removeScrollBar:c,shards:f,noRelative:p,noIsolation:g,inert:y,setCallbacks:s,allowPinchZoom:!!v,lockRef:n,gapMode:S}),i?m.cloneElement(m.Children.only(a),In(In({},E),{ref:C})):m.createElement(b,In({},E,{className:l,ref:C}),a))});ws.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},ws.classNames={fullWidth:bs,zeroRight:vs};var yb=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function vb(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=yb();return t&&e.setAttribute("nonce",t),e}function bb(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function wb(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Sb=function(){var e=0,t=null;return{add:function(n){e==0&&(t=vb())&&(bb(t,n),wb(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Cb=function(){var e=Sb();return function(t,n){m.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},md=function(){var e=Cb(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},kb={left:0,top:0,right:0,gap:0},Ea=function(e){return parseInt(e||"",10)||0},Tb=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[Ea(n),Ea(r),Ea(o)]},Eb=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return kb;var t=Tb(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},Ib=md(),Pr="data-scroll-locked",Ab=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
38
+ `)}function Ix({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onUnhandledEvent:r,onSequenceGap:o}){const s=w.useRef(null),i=w.useCallback(p=>{const g=p.seq??null;if(g!==null){const y=s.current;if(y!==null){if(g<=y)return;g>y+1&&(o==null||o({from:y,to:g}))}s.current=g}if(p.type==="thread_info"){console.log("[useChatStreamingService] 🎯 Received thread_info event:",p);try{t(p)}catch(y){console.error("[useChatStreamingService] Error in onThreadInfo handler:",y)}return}if(gx(p)){try{n(p)}catch(y){console.error("[useChatStreamingService] Error in onMessageEvent handler:",y)}return}try{r==null||r(p)}catch(y){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",y)}},[n,o,t,r]),{stream:a,stop:l,isStreaming:c,error:d,setToken:f}=Pc({baseUrl:e,token:null}),h=w.useCallback((p,g)=>{s.current=null,a(p,i,{onOpen:g==null?void 0:g.onOpen,onError:y=>{var v;(v=g==null?void 0:g.onError)==null||v.call(g,y)},onGap:(g==null?void 0:g.onGap)??o})},[i,o,a]);return w.useMemo(()=>({startStream:h,stop:l,isStreaming:c,error:d,setAuthToken:f}),[h,l,c,d,f])}function Pi(e){return e==null?e:{...e}}function Ax(e){return e==null?e:{...e}}function Nx(e){if(Array.isArray(e))return e.slice();if(e==null)return e}function _x(e){if(Array.isArray(e))return e.map(t=>({...t}));if(e==null)return e}function Qt(e,t={}){const n=t.cloneMessages??!1,r=Array.isArray(e==null?void 0:e.messages)?e.messages:[],o=Pi(e==null?void 0:e.metadata),s=Pi(e==null?void 0:e.config),i=Pi(e==null?void 0:e.parentConfig),a=Nx(e==null?void 0:e.next),l=_x(e==null?void 0:e.tasks),c=Ax(e==null?void 0:e.values),d={checkpointId:(e==null?void 0:e.checkpointId)??null,checkpointNs:(e==null?void 0:e.checkpointNs)??null,createdAt:(e==null?void 0:e.createdAt)??null,parentId:(e==null?void 0:e.parentId)??null,branchLabel:(e==null?void 0:e.branchLabel)??null,lastMessageId:(e==null?void 0:e.lastMessageId)??null,messagesLen:typeof(e==null?void 0:e.messagesLen)=="number"?e.messagesLen:r.length,hasMessages:typeof(e==null?void 0:e.hasMessages)=="boolean"?e.hasMessages:r.length>0,messages:n?r.slice():r,nextCursor:(e==null?void 0:e.nextCursor)??null,nextCursorNs:(e==null?void 0:e.nextCursorNs)??null,interrupt:(e==null?void 0:e.interrupt)??null};return o!==void 0&&(d.metadata=o),s!==void 0&&(d.config=s),i!==void 0&&(d.parentConfig=i),a!==void 0&&(d.next=a),l!==void 0&&(d.tasks=l),c!==void 0&&(d.values=c),d}function jx(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 Oc(e,t){if(!e&&!t)return!0;if(!e||!t||e.id!==t.id)return!1;try{return JSON.stringify(e.value)===JSON.stringify(t.value)}catch{return e.value===t.value}}const qo=300;function Mc(e,t=qo){if(typeof window<"u"&&"requestIdleCallback"in window)try{window.requestIdleCallback(e,{timeout:t});return}catch{}window.setTimeout(e,t)}function cr(){return typeof window<"u"&&typeof window.localStorage<"u"}function Oi(e){if(!cr())return null;try{return window.localStorage.getItem(e)}catch{return null}}function Mi(e,t){if(!cr())return!1;try{return window.localStorage.setItem(e,t),!0}catch{return!1}}function Di(e){if(cr())try{window.localStorage.removeItem(e)}catch{}}const Rx="cachedThreads",Px="v1",Li=200;function Ox(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 Fi(e,t){return`cachedThreads:v1:${e}:${Ox(t||"anon")}`}function Mx(){const e=Oi(Rx);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 Dx(e){const t=Oi(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 $i(e,t){Mi(e,JSON.stringify(t))}function zi(e){const t=Dx(e);if(t.length>0)return t;const n=Mx();if(n.length>0)try{$i(e,n.slice(0,Li))}catch{}return n}function Ko(e){const t={},n=[];for(const r of e)!r||typeof r.threadId!="string"||t[r.threadId]||(t[r.threadId]=r,n.push(r.threadId));return{byId:t,order:n}}function Bi(e){return e.order.map(t=>e.byId[t]).filter(Boolean)}function Hi(e,t){return`${e}${t}`}function Lx(e,t){const n=Oi(Hi(e,t));if(!n)return null;try{const r=JSON.parse(n);return typeof(r==null?void 0:r.threadId)!="string"?null:{threadId:r.threadId,snapshot:Qt(r.snapshot,{cloneMessages:!0}),updatedAt:typeof r.updatedAt=="number"?r.updatedAt:void 0}}catch{return null}}function Fx(e,t,n=100){if(!cr())return;const r=Qt(t.snapshot,{cloneMessages:!0}),o={threadId:t.threadId,snapshot:{...r,messages:r.messages.slice(-n)},updatedAt:Date.now()},s=Hi(e,t.threadId),i=JSON.stringify(o);if(!Mi(s,i))try{const a=[];for(let l=0;l<window.localStorage.length;l++){const c=window.localStorage.key(l);if(!c||c===s||!c.startsWith(e))continue;const d=window.localStorage.getItem(c);if(!d){a.push({key:c,updatedAt:0});continue}try{const f=JSON.parse(d),h=typeof(f==null?void 0:f.updatedAt)=="number"&&Number.isFinite(f.updatedAt)?f.updatedAt:0;a.push({key:c,updatedAt:h})}catch{a.push({key:c,updatedAt:0})}}a.sort((l,c)=>l.updatedAt-c.updatedAt);for(const l of a)if(window.localStorage.removeItem(l.key),Mi(s,i))break}catch{}}function $x(e,t){Di(Hi(e,t))}function zx(e){if(cr())try{for(let t=0;t<window.localStorage.length;t++){const n=window.localStorage.key(t);n&&n.startsWith(e)&&window.localStorage.removeItem(n)}}catch{}}const Dc=w.createContext(null),Lc=w.createContext(null),Fc=w.createContext(null),Bx=w.createContext(!1),$c=50,Hx=750;function zc(e,t,n){return`${e}__${t??""}__${n??""}`}function Go(e,t){return t&&typeof t=="object"?{...e&&typeof e=="object"?{...e}:{},...t}:t===null?e&&typeof e=="object"?{...e}:e??null:e&&typeof e=="object"?{...e}:e??void 0}function Ux(e,t){return Go(e,t)}function Wx(e,t){return Array.isArray(t)?t.slice():t===null?Array.isArray(e)?e.slice():e??null:Array.isArray(e)?e.slice():e??void 0}function Vx(e,t){return Array.isArray(t)?t.map(n=>({...n})):t===null?Array.isArray(e)?e.map(n=>({...n})):e??null:Array.isArray(e)?e.map(n=>({...n})):e??void 0}function Bc(e,t){const n=Go(e.metadata,t.metadata),r=Go(e.config,t.config),o=Go(e.parentConfig,t.parentConfig),s=Wx(e.next,t.next),i=Vx(e.tasks,t.tasks),a=Ux(e.values,t.values),l={};return n!==void 0&&(l.metadata=n??null),r!==void 0&&(l.config=r??null),o!==void 0&&(l.parentConfig=o??null),s!==void 0&&(l.next=s??null),i!==void 0&&(l.tasks=i??null),a!==void 0&&(l.values=a??null),l}function qx({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:c}=Ni(),d=w.useMemo(()=>$n(c),[c]),f=w.useMemo(()=>{try{return new URL(c).host}catch{return"unknown"}},[c]),h=w.useMemo(()=>`threadPayload:${Px}:${f}:`,[f]),p=w.useCallback(A=>Lx(h,A),[h]),g=w.useCallback((A,N=100)=>{Fx(h,A,N)},[h]),y=w.useCallback(A=>{$x(h,A)},[h]),v=w.useCallback(()=>{zx(h)},[h]),[x,b]=w.useState(()=>{var A;return Fi(f,(A=l.getAuthToken)==null?void 0:A.call(l))}),[S,T]=w.useState(()=>{var N;const A=zi(Fi(f,(N=l.getAuthToken)==null?void 0:N.call(l)));return Ko(A)}),k=w.useMemo(()=>Bi(S),[S]),[C,E]=w.useState(t),[_,j]=w.useState(!1),[D,$]=w.useState(!1),[K,P]=w.useState(null),[R,L]=w.useState(null),[F,ne]=w.useState(null),[q,B]=w.useState([]),pe=w.useCallback(()=>{const A=zi(x);w.startTransition(()=>{T(Ko(A))})},[x]),[W,ce]=w.useState(!1),[H,Z]=w.useState(!1),[be,ye]=w.useState(null),[G,M]=w.useState(void 0),[X,oe]=w.useState(void 0),[xe,se]=w.useState(void 0),{state:re,dispatch:Ue,seed:qe,prepend:ot,pushUser:at,onEvent:ht,reset:tt}=Tc(),Me=w.useRef(C);w.useEffect(()=>{Me.current=C},[C]);const We=w.useRef(!1),lt=w.useRef([]),yt=w.useRef(null),dt=w.useRef(null),Je=w.useRef(new Map),ie=w.useRef(C),je=w.useRef(!1),ke=w.useRef(null),Ke=w.useRef(new Map),nt=w.useRef(new Map),Oe=w.useRef(new Map),Xe=w.useRef(new Map),Tt=w.useCallback(A=>{if(!A){B([]);return}const N=Ke.current.get(A);if(!N||!N.length){B([]);return}B(N.map(Y=>Qt(Y,{cloneMessages:!0})))},[]);w.useEffect(()=>{Tt(C)},[C,Tt]);const St=w.useCallback(()=>{var te;const A=Xe.current;if(A.size<=$c)return;const N=Array.from(A.entries()).sort((ae,Q)=>ae[1].timestamp-Q[1].timestamp),Y=A.size-$c;for(let ae=0;ae<Y;ae++){const Q=(te=N[ae])==null?void 0:te[0];Q&&A.delete(Q)}},[]),Yt=w.useCallback((A,N,Y)=>{if(!A)return;const te=Y==="replace"?[]:Ke.current.get(A)??[],ae=Y==="replace"?N:[...N,...te];if(!ae.length){Y==="replace"&&Ke.current.set(A,[]);return}const Q=new Map;for(const Be of ae){if(!(Be!=null&&Be.checkpointId))continue;const De=`${Be.checkpointId}::${Be.checkpointNs??""}`,et=Qt(Be,{cloneMessages:!0}),vt=Q.get(De);if(!vt){Q.set(De,et);continue}const Nt=Bc(vt,et);Q.set(De,{...vt,...Nt})}const ze=Array.from(Q.values()).sort((Be,De)=>{const et=Number.isFinite(Date.parse(Be.createdAt??""))?Date.parse(Be.createdAt??""):0;return(Number.isFinite(Date.parse(De.createdAt??""))?Date.parse(De.createdAt??""):0)-et});Ke.current.set(A,ze),A===Me.current&&Tt(A)},[Tt]),Et=w.useCallback((A,N,Y)=>{if(!A)return;const te=nt.current.get(A),ae=Y==="replace"||!te?new Map:new Map(te);if(N&&typeof N=="object")for(const[Q,ze]of Object.entries(N)){if(!(ze!=null&&ze.checkpointId))continue;const Be=Q||Qr(ze.checkpointId,ze.checkpointNs??null);ae.set(Be,Qt(ze,{cloneMessages:!0}))}nt.current.set(A,ae)},[]),rr=w.useCallback((A,N)=>{const{threadId:Y,checkpointId:te=null,checkpointNs:ae=null}=A,Q=zc(Y,te,ae);if(N!=null&&N.force)Oe.current.delete(Q),Xe.current.delete(Q);else{if(N!=null&&N.preferCache){const et=Xe.current.get(Q);if(et)return Promise.resolve(et.payload)}const De=Oe.current.get(Q);if(De)return De}const Be=l.getStateHistory({threadId:Y,checkpointId:te??void 0,checkpointNs:ae??void 0}).then(De=>(Xe.current.set(Q,{payload:De,timestamp:Date.now()}),St(),De)).finally(()=>{Oe.current.get(Q)===Be&&Oe.current.delete(Q)});return Oe.current.set(Q,Be),Be},[l,St]),Xt=w.useCallback((A,N)=>new Promise((Y,te)=>{const ae=async()=>{We.current=!0;try{await A(),Y()}catch(Q){te(Q)}finally{We.current=!1;const Q=lt.current.shift();Q&&Q().catch(()=>{})}};We.current?lt.current.push(ae):ae().catch(Q=>{te(Q)})}),[]),xn=w.useRef(k.length),sn=w.useRef(!1);w.useEffect(()=>{xn.current=k.length},[k.length]),w.useEffect(()=>{const A=re.pendingInterrupt??jx(re.messages);Oc(F,A)||ne(A??null)},[F,re.messages,re.pendingInterrupt]);const Dt=w.useCallback(async()=>{const A=xn.current>0;A||j(!0);try{const N=await l.listThreads();w.startTransition(()=>{T(Y=>{const te=ze=>ze.map(Be=>`${Be.threadId}:${Be.updatedAt??""}:${Be.messageCount??""}`).join("|"),ae=Bi(Y);return te(ae)===te(N)||N.length===0&&ae.length>0&&!sn.current?Y:Ko(N)})}),P(null),sn.current||(sn.current=!0)}catch(N){i==null||i(String(N)),console.error("[ChatSessionProvider] Failed to refresh threads:",N),P(String(N))}finally{A||j(!1)}},[l,i]),Pn=w.useRef(!1),yn=w.useRef(null),mt=w.useRef(null),vn=w.useRef(""),On=w.useCallback((A,N)=>{if(!cr())return;mt.current!==null&&(window.clearTimeout(mt.current),mt.current=null);const Y=A.map(ae=>`${ae.threadId}:${ae.updatedAt??""}:${ae.messageCount??""}`).join("|");if(A.length===0){try{Di(x)}catch{}vn.current="";return}if(Y===vn.current)return;const te=()=>{try{const ae=A.slice(0,Li);$i(x,ae),vn.current=Y}catch{}finally{mt.current=null}};if(N!=null&&N.immediate){te();return}mt.current=window.setTimeout(()=>{Mc(te)},qo)},[x]),kr=w.useCallback(()=>{On(k,{immediate:!0})},[On,k]),Jt=w.useCallback((A,N,Y,te)=>{var Sm;const ae=Y??Me.current;if(!ae)return;const Q=Qt(A),ze=ae===Me.current,Be=(te==null?void 0:te.persist)!==!1;if(N==="replace"){if(Be){const It={threadId:ae,snapshot:Qt(A,{cloneMessages:!0})};Je.current.set(ae,It),ie.current=ae}if(!ze)return;qe(Q.messages,{checkpointId:Q.checkpointId??null,checkpointNs:Q.checkpointNs??null,pendingInterrupt:Q.interrupt??null}),ne(Q.interrupt??null),ye(Q.nextCursor??null),ce(!!Q.nextCursor),M(Q.checkpointId??void 0),oe(Q.checkpointNs??void 0),se(Q.nextCursorNs??void 0);return}const De=Je.current.get(ae),et=(De==null?void 0:De.snapshot)??null,vt=Array.isArray(et==null?void 0:et.messages)?et.messages:[],Nt=Qt(et),Dn=Array.isArray(A==null?void 0:A.messages)?A.messages:[],_t=new Set,jt=[...Dn,...vt].filter(It=>{const Cl=It==null?void 0:It.id;return Cl?_t.has(Cl)?!1:(_t.add(Cl),!0):!0}),No=Bc(Nt,Q),_o={checkpointId:Nt.checkpointId??Q.checkpointId??null,checkpointNs:Nt.checkpointNs??Q.checkpointNs??null,createdAt:Q.createdAt??Nt.createdAt??null,parentId:Q.parentId??Nt.parentId??null,branchLabel:Q.branchLabel??Nt.branchLabel??null,lastMessageId:((Sm=jt[jt.length-1])==null?void 0:Sm.id)??null,messagesLen:jt.length,hasMessages:jt.length>0,messages:jt,nextCursor:Q.nextCursor??Nt.nextCursor??null,nextCursorNs:Q.nextCursorNs??Nt.nextCursorNs??null,interrupt:Nt.interrupt??Q.interrupt??null,...No};if(Je.current.set(ae,{threadId:ae,snapshot:Qt(_o,{cloneMessages:!0})}),!ze)return;Dn.length&&ot(Dn);const Ln=A&&Object.prototype.hasOwnProperty.call(A,"checkpointId")?A.checkpointId:void 0,jo=A&&Object.prototype.hasOwnProperty.call(A,"checkpointNs")?A.checkpointNs:void 0,Fn=A&&Object.prototype.hasOwnProperty.call(A,"nextCursor")?A.nextCursor:void 0,Sl=A&&Object.prototype.hasOwnProperty.call(A,"nextCursorNs")?A.nextCursorNs:void 0;ye(It=>Fn!==void 0?Fn??It??null:It??null),ce(It=>Fn!==void 0?!!Fn:It),M(It=>Ln!==void 0?Ln??It??void 0:It??void 0),oe(It=>jo!==void 0?jo??It??void 0:It??void 0),se(It=>Sl!==void 0?Sl??void 0:It)},[ot,qe,ne]),Tr=w.useCallback(A=>{if(A.threadId!=null&&A.threadId!==Me.current)return;const N=Qt(A.snapshot,{cloneMessages:!0});qe(N.messages,{checkpointId:N.checkpointId??null,checkpointNs:N.checkpointNs??null,pendingInterrupt:N.interrupt??null}),ne(N.interrupt??null),ye(N.nextCursor??null),ce(!!N.nextCursor),M(N.checkpointId??void 0),oe(N.checkpointNs??void 0),se(N.nextCursorNs??void 0),ie.current=A.threadId,Tt(A.threadId??Me.current??null)},[qe,ne,Tt]),Mn=w.useCallback(A=>{if(!A)return;Je.current.delete(A),y(A),Ke.current.delete(A),nt.current.delete(A),A===Me.current&&B([]);const N=`${A}__`;for(const Y of Oe.current.keys())Y.startsWith(N)&&Oe.current.delete(Y);for(const Y of Xe.current.keys())Y.startsWith(N)&&Xe.current.delete(Y);ie.current===A&&(ie.current=null)},[y]),bn=w.useCallback(()=>{const A=Me.current;A&&Mn(A),tt([]),ce(!1),Z(!1),ye(null),M(void 0),oe(void 0),se(void 0)},[Mn,tt]),Un=w.useCallback(({from:A,to:N})=>{const Y=Me.current;Y&&console.warn(`[ChatSessionProvider] Stream sequence gap detected (${A} -> ${N}) for thread ${Y}`)},[]),Er=w.useCallback(A=>{const N=A.threadId;console.log("[ChatSessionProvider] 📥 Handling thread_info event:",{threadId:N,title:A.title,created:A.created,currentThreads:k.length});const Y={threadId:N,title:A.title||`Thread ${N.slice(0,8)}`,createdAt:A.createdAt||new Date().toISOString(),updatedAt:A.updatedAt||new Date().toISOString(),messageCount:A.messageCount||0};Me.current!==N&&(!Me.current&&re.messages.length<=1&&(dt.current=N),E(N)),w.startTransition(()=>{T(te=>{const ae=te.byId[N];return ae?ae.title===Y.title&&ae.updatedAt===Y.updatedAt&&ae.messageCount===Y.messageCount?te:{byId:{...te.byId,[N]:Y},order:te.order}:{byId:{...te.byId,[N]:Y},order:[N,...te.order]}})})},[re.messages.length]),{startStream:Wr,stop:Vr,isStreaming:or,error:I,setAuthToken:U}=Ix({baseUrl:d,onThreadInfo:Er,onMessageEvent:ht,onUnhandledEvent:A=>{console.warn(`[ChatSessionProvider] Unhandled stream event: ${A.type}`,A)},onSequenceGap:Un});w.useEffect(()=>{Pn.current=or},[or]),w.useEffect(()=>{if(!cr())return;mt.current!==null&&(window.clearTimeout(mt.current),mt.current=null);const A=k.map(Y=>`${Y.threadId}:${Y.updatedAt??""}:${Y.messageCount??""}`).join("|");if(k.length===0){try{Di(x)}catch{}vn.current="";return}if(A===vn.current)return;const N=()=>{try{const Y=k.slice(0,Li);$i(x,Y),vn.current=A}catch{}finally{mt.current=null}};return mt.current=window.setTimeout(()=>{Mc(N),mt.current=null},qo),()=>{mt.current!==null&&(window.clearTimeout(mt.current),mt.current=null)}},[k,On]),w.useEffect(()=>{var te;const A=l.getAuthToken();U(A);const N=ae=>{const Q=Fi(f,ae);ke.current!==Q&&(ke.current=Q,je.current=!1),b(Q);const ze=zi(Q);w.startTransition(()=>{T(Ko(ze))}),ae&&!je.current&&(je.current=!0)};N(A);const Y=(te=l.onTokenChange)==null?void 0:te.call(l,ae=>{ae!==A&&(U(ae),v(),Oe.current.clear(),Xe.current.clear(),N(ae))});return()=>{Y==null||Y()}},[l,f,U,v]);const le=w.useCallback(async A=>{var te;const N=`Thread ${(te=crypto.randomUUID)==null?void 0:te.call(crypto)}`,Y={threadId:N,title:A||"New Chat",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:0};T(ae=>({byId:{...ae.byId,[N]:Y},order:[N,...ae.order]})),E(N);try{const ae=await l.createThread(A),Q=typeof ae=="string"?ae:ae.threadId;return T(ze=>{const Be=ze.byId[N];if(!Be)return ze;const De={...ze.byId};delete De[N],De[Q]={...Be,threadId:Q};const et=ze.order.map(vt=>vt===N?Q:vt);return{byId:De,order:et}}),E(Q),setTimeout(()=>Dt(),10),P(null),Q}catch(ae){throw T(Q=>{if(!Q.byId[N])return Q;const ze={...Q.byId};delete ze[N];const Be=Q.order.filter(De=>De!==N);return{byId:ze,order:Be}}),E(null),P(String(ae)),ae}},[l,Dt]),Ce=w.useCallback(async A=>{try{await l.deleteThread(A);let N=null;T(Y=>{if(!Y.byId[A])return Y;const te={...Y.byId};delete te[A];const ae=Y.order.filter(ze=>ze!==A),Q={byId:te,order:ae};return N=Bi(Q),Q}),N&&On(N,{immediate:!0}),Mn(A),Me.current===A&&(dt.current=A,E(null),Me.current=null,ie.current=null,bn()),await Dt(),P(null)}catch(N){throw P(String(N)),N}},[l,bn,Mn,Dt,On]),Ge=w.useCallback(async(A,N)=>{try{await l.updateThread(A,N),T(Y=>{const te=Y.byId[A];return te?{byId:{...Y.byId,[A]:{...te,title:N}},order:Y.order}:Y}),P(null)}catch(Y){throw await Dt(),P(String(Y)),Y}},[l,Dt]),$e=w.useCallback(async(A,N,Y,te=!1)=>{await Xt(async()=>{if(dt.current===A&&!te){dt.current=null;return}if(yt.current===A&&!te)return;E(_t=>_t===A?_t:A),Me.current=A;const ze=zc(A,N??null,Y??null),Be=Xe.current.get(ze),De=!te&&!N&&!Y&&Be&&Date.now()-Be.timestamp<Hx,et=!te&&!N&&!Y;let vt=!1;if(et){const _t=Je.current.get(A);if(_t)Tr(_t),vt=!0;else{const jt=p(A);jt&&(Je.current.set(A,jt),Tr(jt),vt=!0)}}const Nt=te||!vt||!!N||!!Y,Dn=async _t=>{_t&&$(!0),yt.current=A;try{const jt=await rr({threadId:A,checkpointId:N,checkpointNs:Y},{force:te}),{latest:No,checkpoints:_o,snapshots:Ln}=ji(jt);Jt(No,"replace",A),Yt(A,_o,"replace"),Et(A,Ln,"replace"),L(null)}catch(jt){throw(!vt||te||_t)&&(i==null||i(String(jt))),L(String(jt)),jt}finally{yt.current=null,_t&&$(!1)}};Nt?await Dn(!0):et&&vt&&!De&&Dn(!1).catch(_t=>{console.warn("[ChatSessionProvider] Background refresh failed:",_t)})},`loadThread-${A}`)},[Tr,Jt,Xt,rr,i,Yt,Et]),Fe=w.useCallback(async()=>{await Xt(async()=>{const A=Me.current;A&&Mn(A),dt.current=null,E(null),Me.current=null,ie.current=null,bn(),M(void 0),oe(void 0),se(void 0),B([]);try{localStorage.removeItem("lastThreadId")}catch(N){console.warn("[ChatSessionProvider] Failed to clear lastThreadId:",N)}},"clearCurrentThread")},[bn,Mn,Xt]),z=w.useCallback(async(A,N)=>{var Q;const Y=Me.current;if(!Y)throw new Error("No active thread");const te=Qr(A,N??null),ae=(Q=nt.current.get(Y))==null?void 0:Q.get(te);if(ae){await Xt(async()=>{Jt(ae,"replace",Y,{persist:!1})},`navigateToCheckpoint-${Y}-${te}`);return}await $e(Y,A,N??void 0,!0)},[Jt,Xt,$e]),ue=w.useCallback(async()=>{if(!Me.current)throw new Error("No active thread");await $e(Me.current,void 0,void 0,!0)},[$e]),me=w.useCallback(async()=>{if(!Me.current)throw new Error("No active thread");if(H||!W)return;const A=be;if(A){Z(!0);try{const N=Me.current,Y=await rr({threadId:N,checkpointId:A??G??null,checkpointNs:xe??X??null}),{latest:te,checkpoints:ae,snapshots:Q}=ji(Y),ze=N?nt.current.get(N):null;let Be=ae.length>0;if(Be&&ze&&ze.size>0&&(Be=ae.some(De=>{if(!(De!=null&&De.checkpointId))return!1;const et=Qr(De.checkpointId,De.checkpointNs??null);return!ze.has(et)})),!Be){ye(null),se(void 0),ce(!1),L(null);return}Jt(te,"prepend",N??void 0),N&&(Yt(N,ae,"prepend"),Et(N,Q,"prepend")),L(null)}catch(N){throw L(String(N)),N}finally{Z(!1)}}},[Jt,rr,W,G,X,xe,be,H,Yt,Et]),Re=w.useCallback(A=>{if(A!=null&&A.threadId){if(A.checkpointId){const N=Qr(A.checkpointId,A.checkpointNs??null),Y=Qt({...A,interrupt:A.interrupt??null},{cloneMessages:!0});Et(A.threadId,{[N]:Y},"prepend")}Jt(A,"replace",A.threadId)}},[Jt,Et]),rt=w.useCallback(async(A,N)=>{var jo;const Y=Me.current,te=(A==null?void 0:A.text)??"",ae=(A==null?void 0:A.attachments)??[],Q=ae.length?ae:(N==null?void 0:N.attachments)??[],ze={...(N==null?void 0:N.payloadExtras)??{},...(A==null?void 0:A.payload)??{}};if(!Y&&!Object.keys(ze).length&&Q.length===0&&!te.trim()){console.warn("[ChatSessionProvider] Nothing to submit - skipping");return}!Y&&!ze.messages&&console.warn("[ChatSessionProvider] No thread ID - message will create new thread");const{contentParts:Be,filesInfo:De}=await Qg(l,Q),et=[...Be];te&&te.trim()&&et.push({type:"text",text:te.trim()});const vt=!!Y,Nt=vt?(N==null?void 0:N.checkpointId)??re.lastCheckpointId??void 0:void 0,Dn=vt?(N==null?void 0:N.checkpointNs)??re.lastCheckpointNs??void 0:void 0,_t={id:((jo=crypto.randomUUID)==null?void 0:jo.call(crypto))||`user-${Date.now()}`,role:"user",content:et,createdAt:new Date().toISOString(),...Nt!=null?{checkpointId:Nt}:{},...Dn!=null?{checkpointNs:Dn}:{}};et.length>0&&at(_t);const jt={..._t,content:et},No=Q.length>0,_o={messages:et.length>0?[jt]:[],files_info:De,...o&&No&&s?{active_agent:s}:{},...ze},Ln={threadId:Y??null,payload:_o,checkpointId:Nt??null,checkpointNs:Dn??null,nodeFilter:(N==null?void 0:N.nodeFilter)??null,config:N==null?void 0:N.config,command:(N==null?void 0:N.command)??null};Ln.threadId||delete Ln.threadId,Ln.command||delete Ln.command,Wr(Ln,{onError:Fn=>{console.warn("[ChatSessionProvider] Stream error:",Fn)},onOpen:({threadId:Fn})=>{!Me.current&&Fn&&(re.messages.length<=1&&(dt.current=Fn),E(Fn))},onGap:Un})},[l,o,s,Un,re.lastCheckpointId,re.lastCheckpointNs,re.messages.length,at,Wr]),Lt=w.useCallback(async(A,N,Y)=>{if(!Me.current)throw new Error("No active thread to handle interrupt");const ae=N?Y??!0:!1;try{try{Ue({type:"interrupt_response",payload:{interruptId:A}})}catch(Q){console.warn("[ChatSessionProvider] optimistic interrupt_response dispatch failed:",Q)}await rt({payload:{}},{checkpointId:re.lastCheckpointId??void 0,checkpointNs:re.lastCheckpointNs??void 0,command:{kind:"resume",value:ae}}),ne(null)}catch(Q){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${A}:`,Q),Q}},[Ue,re.lastCheckpointId,re.lastCheckpointNs,rt]);w.useEffect(()=>{if(a==null||a(C),C)try{localStorage.setItem("lastThreadId",C)}catch(A){console.warn("[ChatSessionProvider] Failed to persist lastThreadId:",A)}},[C,a]),w.useEffect(()=>((async()=>{try{if(Dt().catch(N=>{console.error("[ChatSessionProvider] Failed to refresh threads (background):",N),i==null||i(String(N))}),!r&&!t)try{const N=localStorage.getItem("lastThreadId");N&&(E(N),n&&await $e(N))}catch(N){console.warn("[ChatSessionProvider] Failed to restore last thread:",N)}else t&&n&&await $e(t)}catch(N){console.error("[ChatSessionProvider] Initialization failed:",N),i==null||i(String(N))}})(),()=>{}),[]),w.useEffect(()=>{const A=Me.current;if(!A||ie.current!==A)return;re.messages.length&&re.messages[re.messages.length-1];const N=Qt({checkpointId:re.lastCheckpointId??null,checkpointNs:re.lastCheckpointNs??null,messages:re.messages.slice(),nextCursor:be??null,nextCursorNs:xe??null,interrupt:re.pendingInterrupt??F??null}),Y=Je.current.get(A),te=Y==null?void 0:Y.snapshot,ae=!te||te.messages.length!==N.messages.length||te.messages.some((De,et)=>{var vt;return(De==null?void 0:De.id)!==((vt=N.messages[et])==null?void 0:vt.id)}),Q=((te==null?void 0:te.checkpointId)??null)!==N.checkpointId||((te==null?void 0:te.checkpointNs)??null)!==N.checkpointNs,ze=((te==null?void 0:te.nextCursor)??null)!==N.nextCursor||((te==null?void 0:te.nextCursorNs)??null)!==N.nextCursorNs,Be=!Oc((te==null?void 0:te.interrupt)??null,N.interrupt??null);if(ae||Q||ze||Be){const De={threadId:A,snapshot:N};Je.current.set(A,De),yn.current&&window.clearTimeout(yn.current),yn.current=window.setTimeout(()=>{try{g(De,100)}catch(et){console.warn("[ChatSessionProvider] Failed to persist thread payload:",et)}},qo)}},[be,xe,re.lastCheckpointId,re.lastCheckpointNs,re.messages,re.pendingInterrupt,F,g]);const an=w.useMemo(()=>({threads:k,currentThreadId:C,setCurrentThreadId:E,isLoading:_,error:K,actions:{createThread:le,deleteThread:Ce,renameThread:Ge,refreshThreads:()=>Dt()},persistThreadsCache:kr,hydrateFromCache:pe}),[k,C,_,K,le,Ce,Ge,Dt,kr,pe,E]),Ct=w.useMemo(()=>{const A=re.lastBranch??null,N=re.assemblingId??null,Y=A||N?{branchLabel:(A==null?void 0:A.branchLabel)??null,lastBranch:A,assemblingMessageId:N}:null;return{threadId:C,messages:re.messages,interrupt:F,checkpoint:{id:re.lastCheckpointId??null,namespace:re.lastCheckpointNs??null},checkpoints:q,metadata:Y,isLoading:D,isHistoryLoading:H,error:R,hasMore:W,loadOlder:me,seedFromSnapshot:Re,clearState:bn,navigateToCheckpoint:z,returnToLatest:ue,loadThread:$e,clearThread:Fe,respondToInterrupt:Lt}},[Fe,bn,C,F,W,H,D,me,$e,re.assemblingId,re.lastBranch,re.lastCheckpointId,re.lastCheckpointNs,re.messages,z,Lt,ue,Re,R,q]),Ao=w.useMemo(()=>({isStreaming:or,error:I,submit:rt,send:rt,stop:Vr,setAuthToken:U}),[or,I,rt,Vr,U]);return u.jsx(Bx.Provider,{value:!0,children:u.jsx(Fc.Provider,{value:Ao,children:u.jsx(Dc.Provider,{value:an,children:u.jsx(Lc.Provider,{value:Ct,children:e})})})})}function Yo(){const e=w.useContext(Dc);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function Xo(){const e=w.useContext(Lc);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function Hc(){const e=w.useContext(Fc);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function Jo({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 u.jsx(Jg,{apiConfig:t,children:u.jsx(qx,{initialThreadId:n,autoLoadInitial:r,disableAutoRestore:o,enableFileAgentRouting:s,fileAgentId:i,onError:a,onThreadChange:l,children:e})})}function ee(...e){return Em.twMerge(Tm.clsx(e))}const Kx=Ro.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"}}),Ze=m.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?sr.Slot:"button";return u.jsx(i,{className:ee(Kx({variant:t,size:n,className:e})),ref:s,...o})});Ze.displayName="Button";const Uc=m.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{className:ee("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}));Uc.displayName="Textarea";function Gx({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=2e4,value:i,onValueChange:a,onSend:l,onCancelEdit:c,onStop:d,className:f="",textareaClassName:h="",allowEmptySend:p=!1}){const g=i!==void 0,[y,v]=w.useState(e),x=(g?i:y)??"",[b,S]=w.useTransition(),T=w.useRef(null),k=w.useRef(0),C=w.useRef(null);w.useEffect(()=>{g||(v(e??""),C.current=null,T.current&&(T.current.style.height="auto",T.current.style.height=`${T.current.scrollHeight}px`))},[e,t,g]);const E=w.useCallback(()=>{const L=T.current;L&&(L.style.height="auto",L.style.height=`${L.scrollHeight}px`)},[]);w.useEffect(()=>{E()},[E,x]);const _=w.useCallback((L,{fromUser:F})=>{g||v(L),F&&(a==null||a(L))},[g,a]),j=w.useCallback(async L=>{L&&L.preventDefault();const F=(x??"").trim();if(!F&&!p)return;const ne=++k.current;C.current={id:ne,shouldClear:!0},S(()=>{var q,B,pe;try{const W=l(F);W&&typeof W.then=="function"?W.then(()=>{var ce,H;((ce=C.current)==null?void 0:ce.id)===ne&&C.current.shouldClear&&(g||(v(""),T.current&&(T.current.style.height="auto"),a==null||a(""))),((H=C.current)==null?void 0:H.id)===ne&&(C.current=null)}).catch(()=>{var ce;((ce=C.current)==null?void 0:ce.id)===ne&&(C.current=null)}):(((q=C.current)==null?void 0:q.id)===ne&&C.current.shouldClear&&(g||(v(""),T.current&&(T.current.style.height="auto"),a==null||a(""))),((B=C.current)==null?void 0:B.id)===ne&&(C.current=null))}catch{((pe=C.current)==null?void 0:pe.id)===ne&&(C.current=null)}})},[x,l,p,g,a]),D=w.useCallback(L=>{const F=L.target.value;_(F,{fromUser:!0}),C.current&&(C.current.shouldClear=!1),T.current&&(T.current.style.height="auto",T.current.style.height=`${T.current.scrollHeight}px`)},[_]),$=w.useCallback(L=>{L.key==="Enter"&&!L.shiftKey?(L.preventDefault(),j()):L.key==="Escape"&&t&&(L.preventDefault(),c==null||c())},[j,t,c]),R=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${t?"border-[hsl(var(--ring))] bg-[hsl(var(--card))] text-[hsl(var(--card-foreground))] dark:bg-[hsl(var(--card))] dark:text-[hsl(var(--card-foreground))]":""} ${h}`;return u.jsx("form",{onSubmit:L=>void j(L),className:`w-full ${f}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(Uc,{ref:T,value:x,onChange:D,onKeyDown:$,placeholder:t?"Edit your message...":n,className:R,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx(Ze,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:u.jsx(fe.Square,{size:16})}):u.jsx(Ze,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!x.trim()&&!p||b,children:u.jsx(fe.Send,{size:16})})})]})})}const Yx=w.memo(Gx),Zo=0,Vn=1,_r=2,Wc=4;function Vc(e){return()=>e}function Xx(e){e()}function qc(e,t){return n=>e(t(n))}function Kc(e,t){return()=>e(t)}function Jx(e,t){return n=>e(t,n)}function Ui(e){return e!==void 0}function Zx(...e){return()=>{e.map(Xx)}}function jr(){}function Qo(e,t){return t(e),e}function Qx(e,t){return t(e)}function ct(...e){return e}function Qe(e,t){return e(Vn,t)}function Pe(e,t){e(Zo,t)}function Wi(e){e(_r)}function xt(e){return e(Wc)}function ve(e,t){return Qe(e,Jx(t,Zo))}function dn(e,t){const n=e(Vn,r=>{n(),t(r)});return n}function Gc(e){let t,n;return r=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{r(t)},e)}}function Yc(e,t){return e===t}function ut(e=Yc){let t;return n=>r=>{e(t,r)||(t=r,n(r))}}function Ee(e){return t=>n=>{e(n)&&t(n)}}function de(e){return t=>qc(t,e)}function Sn(e){return t=>()=>{t(e)}}function V(e,...t){const n=ey(...t);return(r,o)=>{switch(r){case _r:Wi(e);return;case Vn:return Qe(e,n(o))}}}function Cn(e,t){return n=>r=>{n(t=e(t,r))}}function ur(e){return t=>n=>{e>0?e--:t(n)}}function zn(e){let t=null,n;return r=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,r(t)},e))}}function Le(...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);Qe(s,l=>{const c=n;n=n|a,t[i]=l,c!==o&&n===o&&r&&(r(),r=null)})}),s=>i=>{const a=()=>{s([i].concat(t))};n===o?a():r=a}}function ey(...e){return t=>e.reduceRight(Qx,t)}function ty(e){let t,n;const r=()=>t==null?void 0:t();return function(o,s){switch(o){case Vn:return s?n===s?void 0:(r(),n=s,t=Qe(e,s),t):(r(),jr);case _r:r(),n=null;return}}}function J(e){let t=e;const n=Ve();return(r,o)=>{switch(r){case Zo:t=o;break;case Vn:{o(t);break}case Wc:return t}return n(r,o)}}function Pt(e,t){return Qo(J(t),n=>ve(e,n))}function Ve(){const e=[];return(t,n)=>{switch(t){case Zo:e.slice().forEach(r=>{r(n)});return;case _r:e.splice(0,e.length);return;case Vn:return e.push(n),()=>{const r=e.indexOf(n);r>-1&&e.splice(r,1)}}}}function Wt(e){return Qo(Ve(),t=>ve(e,t))}function Ye(e,t=[],{singleton:n}={singleton:!0}){return{constructor:e,dependencies:t,id:ny(),singleton:n}}const ny=()=>Symbol();function ry(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 bt(...e){const t=Ve(),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);Qe(s,l=>{n[i]=l,r=r|a,r===o&&Pe(t,n)})}),function(s,i){switch(s){case _r:{Wi(t);return}case Vn:return r===o&&i(n),Qe(t,i)}}}function Te(e,t=Yc){return V(e,ut(t))}function Vi(...e){return function(t,n){switch(t){case _r:return;case Vn:return Zx(...e.map(r=>Qe(r,n)))}}}var Ut=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(Ut||{});const oy={0:"debug",3:"error",1:"log",2:"warn"},sy=()=>typeof globalThis>"u"?window:globalThis,qn=Ye(()=>{const e=J(3);return{log:J((t,n,r=1)=>{var o;const s=(o=sy().VIRTUOSO_LOG_LEVEL)!=null?o:xt(e);r>=s&&console[oy[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function dr(e,t,n){return qi(e,t,n).callbackRef}function qi(e,t,n){const r=w.useRef(null);let o=i=>{};const s=w.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 iy(e,t,n,r,o,s,i,a,l){const c=w.useCallback(d=>{const f=ay(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 g;p&&(g=h.ownerDocument.defaultView);const y=i?a?i.scrollLeft:i.scrollTop:p?a?g.scrollX||g.document.documentElement.scrollLeft:g.scrollY||g.document.documentElement.scrollTop:a?h.scrollLeft:h.scrollTop,v=i?a?i.scrollWidth:i.scrollHeight:p?a?g.document.documentElement.scrollWidth:g.document.documentElement.scrollHeight:a?h.scrollWidth:h.scrollHeight,x=i?a?i.offsetWidth:i.offsetHeight:p?a?g.innerWidth:g.innerHeight:a?h.offsetWidth:h.offsetHeight;r({scrollHeight:v,scrollTop:Math.max(y,0),viewportHeight:x}),s==null||s(a?Xc("column-gap",getComputedStyle(d).columnGap,o):Xc("row-gap",getComputedStyle(d).rowGap,o)),f!==null&&e(f)},[e,t,o,s,i,r,a]);return qi(c,n,l)}function ay(e,t,n,r){const o=e.length;if(o===0)return null;const s=[];for(let i=0;i<o;i++){const a=e.item(i);if(a.dataset.index===void 0)continue;const l=parseInt(a.dataset.index),c=parseFloat(a.dataset.knownSize),d=t(a,n);if(d===0&&r("Zero-sized element, this should not happen",{child:a},Ut.ERROR),d===c)continue;const f=s[s.length-1];s.length===0||f.size!==d||f.endIndex!==l-1?s.push({endIndex:l,size:d,startIndex:l}):s[s.length-1].endIndex++}return s}function Xc(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,Ut.WARN),t==="normal"?0:parseInt(t??"0",10)}function Jc(e,t,n){const r=w.useRef(null),o=w.useCallback(l=>{if(!(l!=null&&l.offsetParent))return;const c=l.getBoundingClientRect(),d=c.width;let f,h;if(t){const p=t.getBoundingClientRect(),g=c.top-p.top;h=p.height-Math.max(0,g),f=g+t.scrollTop}else{const p=i.current.ownerDocument.defaultView;h=p.innerHeight-Math.max(0,c.top),f=c.top+p.scrollY}r.current={offsetTop:f,visibleHeight:h,visibleWidth:d},e(r.current)},[e,t]),{callbackRef:s,ref:i}=qi(o,!0,n),a=w.useCallback(()=>{o(i.current)},[o,i]);return w.useEffect(()=>{var l;if(t){t.addEventListener("scroll",a);const c=new ResizeObserver(()=>{requestAnimationFrame(a)});return c.observe(t),()=>{t.removeEventListener("scroll",a),c.unobserve(t)}}else{const c=(l=i.current)==null?void 0:l.ownerDocument.defaultView;return c==null||c.addEventListener("scroll",a),c==null||c.addEventListener("resize",a),()=>{c==null||c.removeEventListener("scroll",a),c==null||c.removeEventListener("resize",a)}}},[a,t,i]),s}const Ft=Ye(()=>{const e=Ve(),t=Ve(),n=J(0),r=Ve(),o=J(0),s=Ve(),i=Ve(),a=J(0),l=J(0),c=J(0),d=J(0),f=Ve(),h=Ve(),p=J(!1),g=J(!1),y=J(!1);return ve(V(e,de(({scrollTop:v})=>v)),t),ve(V(e,de(({scrollHeight:v})=>v)),i),ve(t,o),{deviation:n,fixedFooterHeight:c,fixedHeaderHeight:l,footerHeight:d,headerHeight:a,horizontalDirection:g,scrollBy:h,scrollContainerState:e,scrollHeight:i,scrollingInProgress:p,scrollTo:f,scrollTop:t,skipAnimationFrameInResizeObserver:y,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:s}},[],{singleton:!0}),to={lvl:0};function Zc(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 st(e){return e===to}function no(e,t){if(!st(e))return t===e.k?e.v:t<e.k?no(e.l,t):no(e.r,t)}function fn(e,t,n="k"){if(st(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const r=fn(e.r,t,n);return r[0]===-1/0?[e.k,e.v]:r}return fn(e.l,t,n)}function Vt(e,t,n){return st(e)?tu(t,n,1):t===e.k?wt(e,{k:t,v:n}):t<e.k?nu(wt(e,{l:Vt(e.l,t,n)})):nu(wt(e,{r:Vt(e.r,t,n)}))}function Rr(){return to}function es(e,t,n){if(st(e))return[];const r=fn(e,t)[0];return ly(Gi(e,r,n))}function Ki(e,t){if(st(e))return to;const{k:n,l:r,r:o}=e;if(t===n){if(st(r))return o;if(st(o))return r;{const[s,i]=eu(r);return ts(wt(e,{k:s,l:Qc(r),v:i}))}}else return t<n?ts(wt(e,{l:Ki(r,t)})):ts(wt(e,{r:Ki(o,t)}))}function fr(e){return st(e)?[]:[...fr(e.l),{k:e.k,v:e.v},...fr(e.r)]}function Gi(e,t,n){if(st(e))return[];const{k:r,l:o,r:s,v:i}=e;let a=[];return r>t&&(a=a.concat(Gi(o,t,n))),r>=t&&r<=n&&a.push({k:r,v:i}),r<=n&&(a=a.concat(Gi(s,t,n))),a}function ts(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(Yi(t))return ru(wt(e,{lvl:n-1}));if(!st(t)&&!st(t.r))return wt(t.r,{l:wt(t,{r:t.r.l}),lvl:n,r:wt(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}else{if(Yi(e))return Xi(wt(e,{lvl:n-1}));if(!st(r)&&!st(r.l)){const o=r.l,s=Yi(o)?r.lvl-1:r.lvl;return wt(o,{l:wt(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:Xi(wt(r,{l:o.r,lvl:s}))})}else throw new Error("Unexpected empty nodes")}}function wt(e,t){return tu(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 Qc(e){return st(e.r)?e.l:ts(wt(e,{r:Qc(e.r)}))}function Yi(e){return st(e)||e.lvl>e.r.lvl}function eu(e){return st(e.r)?[e.k,e.v]:eu(e.r)}function tu(e,t,n,r=to,o=to){return{k:e,l:r,lvl:n,r:o,v:t}}function nu(e){return Xi(ru(e))}function ru(e){const{l:t}=e;return!st(t)&&t.lvl===e.lvl?wt(t,{r:wt(e,{l:t.r})}):e}function Xi(e){const{lvl:t,r:n}=e;return!st(n)&&!st(n.r)&&n.lvl===t&&n.r.lvl===t?wt(n,{l:wt(e,{r:n.l}),lvl:t+1}):e}function ly(e){return Zc(e,({k:t,v:n})=>({index:t,value:n}))}function ou(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}function ro(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}const Ji=Ye(()=>({recalcInProgress:J(!1)}),[],{singleton:!0});function su(e,t,n){return e[ns(e,t,n)]}function ns(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 cy(e,t,n,r){const o=ns(e,t,r),s=ns(e,n,r,o);return e.slice(o,s+1)}function Kn(e,t){return Math.round(e.getBoundingClientRect()[t])}function rs(e){return!st(e.groupOffsetTree)}function Zi({index:e},t){return t===e?0:t<e?-1:1}function uy(){return{groupIndices:[],groupOffsetTree:Rr(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:Rr()}}function dy(e,t){let n=st(e)?0:1/0;for(const r of t){const{endIndex:o,size:s,startIndex:i}=r;if(n=Math.min(n,i),st(e)){e=Vt(e,0,s);continue}const a=es(e,i-1,o+1);if(a.some(yy(r)))continue;let l=!1,c=!1;for(const{end:d,start:f,value:h}of a)l?(o>=f||s===h)&&(e=Ki(e,f)):(c=h!==s,l=!0),d>o&&o>=f&&h!==s&&(e=Vt(e,o+1,h));c&&(e=Vt(e,i,s))}return[e,n]}function fy(e){return typeof e.groupIndex<"u"}function hy({offset:e},t){return t===e?0:t<e?-1:1}function oo(e,t,n){if(t.length===0)return 0;const{index:r,offset:o,size:s}=su(t,e,Zi),i=e-r,a=s*i+(i-1)*n+o;return a>0?a+n:a}function iu(e,t){if(!rs(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function au(e,t,n){if(fy(e))return t.groupIndices[e.groupIndex]+1;{const r=e.index==="LAST"?n:e.index;let o=iu(r,t);return o=Math.max(0,o,Math.min(n,o)),o}}function py(e,t,n,r=0){return r>0&&(t=Math.max(t,su(e,r,Zi).offset)),Zc(cy(e,t,n,hy),xy)}function my(e,[t,n,r,o]){t.length>0&&r("received item sizes",t,Ut.DEBUG);const s=e.sizeTree;let i=s,a=0;if(n.length>0&&st(s)&&t.length===2){const h=t[0].size,p=t[1].size;i=n.reduce((g,y)=>Vt(Vt(g,y,h),y+1,p),i)}else[i,a]=dy(i,t);if(i===s)return e;const{lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f}=Qi(e.offsetTree,a,i,o);return{groupIndices:n,groupOffsetTree:n.reduce((h,p)=>Vt(h,p,oo(p,f,o)),Rr()),lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f,sizeTree:i}}function gy(e){return fr(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 lu(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 Qi(e,t,n,r){let o=e,s=0,i=0,a=0,l=0;if(t!==0){l=ns(o,t-1,Zi),a=o[l].offset;const c=fn(n,t-1);s=c[0],i=c[1],o.length&&o[l].size===fn(n,t)[1]&&(l-=1),o=o.slice(0,l+1)}else o=[];for(const{start:c,value:d}of es(n,t,1/0)){const f=c-s,h=f*i+a+f*r;o.push({index:c,offset:h,size:d}),s=c,a=h,i=d}return{lastIndex:s,lastOffset:a,lastSize:i,offsetTree:o}}function xy(e){return{index:e.index,value:e}}function yy(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 vy={offsetHeight:"height",offsetWidth:"width"},kn=Ye(([{log:e},{recalcInProgress:t}])=>{const n=Ve(),r=Ve(),o=Pt(r,0),s=Ve(),i=Ve(),a=J(0),l=J([]),c=J(void 0),d=J(void 0),f=J((k,C)=>Kn(k,vy[C])),h=J(void 0),p=J(0),g=uy(),y=Pt(V(n,Le(l,e,p),Cn(my,g),ut()),g),v=Pt(V(l,ut(),Cn((k,C)=>({current:C,prev:k.current}),{current:[],prev:[]}),de(({prev:k})=>k)),[]);ve(V(l,Ee(k=>k.length>0),Le(y,p),de(([k,C,E])=>{const _=k.reduce((j,D,$)=>Vt(j,D,oo(D,C.offsetTree,E)||$),Rr());return{...C,groupIndices:k,groupOffsetTree:_}})),y),ve(V(r,Le(y),Ee(([k,{lastIndex:C}])=>k<C),de(([k,{lastIndex:C,lastSize:E}])=>[{endIndex:C,size:E,startIndex:k}])),n),ve(c,d);const x=Pt(V(c,de(k=>k===void 0)),!0);ve(V(d,Ee(k=>k!==void 0&&st(xt(y).sizeTree)),de(k=>[{endIndex:0,size:k,startIndex:0}])),n);const b=Wt(V(n,Le(y),Cn(({sizes:k},[C,E])=>({changed:E!==k,sizes:E}),{changed:!1,sizes:g}),de(k=>k.changed)));Qe(V(a,Cn((k,C)=>({diff:k.prev-C,prev:C}),{diff:0,prev:0}),de(k=>k.diff)),k=>{const{groupIndices:C}=xt(y);if(k>0)Pe(t,!0),Pe(s,k+lu(k,C));else if(k<0){const E=xt(v);E.length>0&&(k-=lu(-k,E)),Pe(i,k)}}),Qe(V(a,Le(e)),([k,C])=>{k<0&&C("`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},Ut.ERROR)});const S=Wt(s);ve(V(s,Le(y),de(([k,C])=>{const E=C.groupIndices.length>0,_=[],j=C.lastSize;if(E){const D=no(C.sizeTree,0);let $=0,K=0;for(;$<k;){const R=C.groupIndices[K],L=C.groupIndices.length===K+1?1/0:C.groupIndices[K+1]-R-1;_.push({endIndex:R,size:D,startIndex:R}),_.push({endIndex:R+1+L-1,size:j,startIndex:R+1}),K++,$+=L+1}const P=fr(C.sizeTree);return $!==k&&P.shift(),P.reduce((R,{k:L,v:F})=>{let ne=R.ranges;return R.prevSize!==0&&(ne=[...R.ranges,{endIndex:L+k-1,size:R.prevSize,startIndex:R.prevIndex}]),{prevIndex:L+k,prevSize:F,ranges:ne}},{prevIndex:k,prevSize:0,ranges:_}).ranges}return fr(C.sizeTree).reduce((D,{k:$,v:K})=>({prevIndex:$+k,prevSize:K,ranges:[...D.ranges,{endIndex:$+k-1,size:D.prevSize,startIndex:D.prevIndex}]}),{prevIndex:0,prevSize:j,ranges:[]}).ranges})),n);const T=Wt(V(i,Le(y,p),de(([k,{offsetTree:C},E])=>{const _=-k;return oo(_,C,E)})));return ve(V(i,Le(y,p),de(([k,C,E])=>{if(C.groupIndices.length>0){if(st(C.sizeTree))return C;let _=Rr();const j=xt(v);let D=0,$=0,K=0;for(;D<-k;){K=j[$];const P=j[$+1]-K-1;$++,D+=P+1}if(_=fr(C.sizeTree).reduce((P,{k:R,v:L})=>Vt(P,Math.max(0,R+k),L),_),D!==-k){const P=no(C.sizeTree,K);_=Vt(_,0,P);const R=fn(C.sizeTree,-k+1)[1];_=Vt(_,1,R)}return{...C,sizeTree:_,...Qi(C.offsetTree,0,_,E)}}else{const _=fr(C.sizeTree).reduce((j,{k:D,v:$})=>Vt(j,Math.max(0,D+k),$),Rr());return{...C,sizeTree:_,...Qi(C.offsetTree,0,_,E)}}})),y),{beforeUnshiftWith:S,data:h,defaultItemSize:d,firstItemIndex:a,fixedItemSize:c,gap:p,groupIndices:l,itemSize:f,listRefresh:b,shiftWith:i,shiftWithOffset:T,sizeRanges:n,sizes:y,statefulTotalCount:o,totalCount:r,trackItemSizes:x,unshiftWith:s}},ct(qn,Ji),{singleton:!0});function by(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const cu=Ye(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:r,scrollTop:o}])=>{const s=Ve(),i=Ve(),a=Wt(V(s,de(by)));return ve(V(a,de(l=>l.totalCount)),n),ve(V(a,de(l=>l.groupIndices)),e),ve(V(bt(o,t,r),Ee(([l,c])=>rs(c)),de(([l,c,d])=>fn(c.groupOffsetTree,Math.max(l-d,0),"v")[0]),ut(),de(l=>[l])),i),{groupCounts:s,topItemsIndexes:i}},ct(kn,Ft)),Gn=Ye(([{log:e}])=>{const t=J(!1),n=Wt(V(t,Ee(r=>r),ut()));return Qe(t,r=>{r&&xt(e)("props updated",{},Ut.DEBUG)}),{didMount:n,propsReady:t}},ct(qn),{singleton:!0}),wy=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function uu(e){const t=typeof e=="number"?{index:e}:e;return t.align||(t.align="start"),(!t.behavior||!wy)&&(t.behavior="auto"),t.offset||(t.offset=0),t}const so=Ye(([{gap:e,listRefresh:t,sizes:n,totalCount:r},{fixedFooterHeight:o,fixedHeaderHeight:s,footerHeight:i,headerHeight:a,scrollingInProgress:l,scrollTo:c,smoothScrollTargetReached:d,viewportHeight:f},{log:h}])=>{const p=Ve(),g=Ve(),y=J(0);let v=null,x=null,b=null;function S(){v&&(v(),v=null),b&&(b(),b=null),x&&(clearTimeout(x),x=null),Pe(l,!1)}return ve(V(p,Le(n,f,r,y,a,i,h),Le(e,s,o),de(([[T,k,C,E,_,j,D,$],K,P,R])=>{const L=uu(T),{align:F,behavior:ne,offset:q}=L,B=E-1,pe=au(L,k,B);let W=oo(pe,k.offsetTree,K)+j;F==="end"?(W+=P+fn(k.sizeTree,pe)[1]-C+R,pe===B&&(W+=D)):F==="center"?W+=(P+fn(k.sizeTree,pe)[1]-C+R)/2:W-=_,q&&(W+=q);const ce=H=>{S(),H?($("retrying to scroll to",{location:T},Ut.DEBUG),Pe(p,T)):(Pe(g,!0),$("list did not change, scroll successful",{},Ut.DEBUG))};if(S(),ne==="smooth"){let H=!1;b=Qe(t,Z=>{H=H||Z}),v=dn(d,()=>{ce(H)})}else v=dn(V(t,Sy(150)),ce);return x=setTimeout(()=>{S()},1200),Pe(l,!0),$("scrolling from index to",{behavior:ne,index:pe,top:W},Ut.DEBUG),{behavior:ne,top:W}})),c),{scrollTargetReached:g,scrollToIndex:p,topListHeight:y}},ct(kn,Ft,qn),{singleton:!0});function Sy(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return r=>{r&&(t(!0),clearTimeout(n))}}}function ea(e,t){e==0?t():requestAnimationFrame(()=>{ea(e-1,t)})}function ta(e,t){const n=t-1;return typeof e=="number"?e:e.index==="LAST"?n:e.index}const io=Ye(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:r},{scrollTargetReached:o,scrollToIndex:s},{didMount:i}])=>{const a=J(!0),l=J(0),c=J(!0);return ve(V(i,Le(l),Ee(([d,f])=>!!f),Sn(!1)),a),ve(V(i,Le(l),Ee(([d,f])=>!!f),Sn(!1)),c),Qe(V(bt(t,i),Le(a,n,e,c),Ee(([[,d],f,{sizeTree:h},p,g])=>d&&(!st(h)||Ui(p))&&!f&&!g),Le(l)),([,d])=>{dn(o,()=>{Pe(c,!0)}),ea(4,()=>{dn(r,()=>{Pe(a,!0)}),Pe(s,d)})}),{initialItemFinalLocationReached:c,initialTopMostItemIndex:l,scrolledToInitialItem:a}},ct(kn,Ft,so,Gn),{singleton:!0});function du(e,t){return Math.abs(e-t)<1.01}const ao="up",lo="down",Cy="none",ky={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},Ty=0,co=Ye(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:r,scrollTop:o,viewportHeight:s}])=>{const i=J(!1),a=J(!0),l=Ve(),c=Ve(),d=J(4),f=J(Ty),h=Pt(V(Vi(V(Te(o),ur(1),Sn(!0)),V(Te(o),ur(1),Sn(!1),Gc(100))),ut()),!1),p=Pt(V(Vi(V(n,Sn(!0)),V(n,Sn(!1),Gc(200))),ut()),!1);ve(V(bt(Te(o),Te(f)),de(([b,S])=>b<=S),ut()),a),ve(V(a,zn(50)),c);const g=Wt(V(bt(r,Te(s),Te(t),Te(e),Te(d)),Cn((b,[{scrollHeight:S,scrollTop:T},k,C,E,_])=>{const j=T+k-S>-_,D={scrollHeight:S,scrollTop:T,viewportHeight:k};if(j){let K,P;return T>b.state.scrollTop?(K="SCROLLED_DOWN",P=b.state.scrollTop-T):(K="SIZE_DECREASED",P=b.state.scrollTop-T||b.scrollTopDelta),{atBottom:!0,atBottomBecause:K,scrollTopDelta:P,state:D}}let $;return D.scrollHeight>b.state.scrollHeight?$="SIZE_INCREASED":k<b.state.viewportHeight?$="VIEWPORT_HEIGHT_DECREASING":T<b.state.scrollTop?$="SCROLLING_UPWARDS":$="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:$,state:D}},ky),ut((b,S)=>b&&b.atBottom===S.atBottom))),y=Pt(V(r,Cn((b,{scrollHeight:S,scrollTop:T,viewportHeight:k})=>{if(du(b.scrollHeight,S))return{changed:!1,jump:0,scrollHeight:S,scrollTop:T};{const C=S-(T+k)<1;return b.scrollTop!==T&&C?{changed:!0,jump:b.scrollTop-T,scrollHeight:S,scrollTop:T}:{changed:!0,jump:0,scrollHeight:S,scrollTop:T}}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),Ee(b=>b.changed),de(b=>b.jump)),0);ve(V(g,de(b=>b.atBottom)),i),ve(V(i,zn(50)),l);const v=J(lo);ve(V(r,de(({scrollTop:b})=>b),ut(),Cn((b,S)=>xt(p)?{direction:b.direction,prevScrollTop:S}:{direction:S<b.prevScrollTop?ao:lo,prevScrollTop:S},{direction:lo,prevScrollTop:0}),de(b=>b.direction)),v),ve(V(r,zn(50),Sn(Cy)),v);const x=J(0);return ve(V(h,Ee(b=>!b),Sn(0)),x),ve(V(o,zn(100),Le(h),Ee(([b,S])=>!!S),Cn(([b,S],[T])=>[S,T],[0,0]),de(([b,S])=>S-b)),x),{atBottomState:g,atBottomStateChange:l,atBottomThreshold:d,atTopStateChange:c,atTopThreshold:f,isAtBottom:i,isAtTop:a,isScrolling:h,lastJumpDueToItemResize:y,scrollDirection:v,scrollVelocity:x}},ct(Ft)),os="top",ss="bottom",fu="none";function hu(e,t,n){return typeof e=="number"?n===ao&&t===os||n===lo&&t===ss?e:0:n===ao?t===os?e.main:e.reverse:t===ss?e.main:e.reverse}function pu(e,t){var n;return typeof e=="number"?e:(n=e[t])!=null?n:0}const na=Ye(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:r,viewportHeight:o}])=>{const s=Ve(),i=J(0),a=J(0),l=J(0),c=Pt(V(bt(Te(r),Te(o),Te(n),Te(s,ro),Te(l),Te(i),Te(t),Te(e),Te(a)),de(([d,f,h,[p,g],y,v,x,b,S])=>{const T=d-b,k=v+x,C=Math.max(h-T,0);let E=fu;const _=pu(S,os),j=pu(S,ss);return p-=b,p+=h+x,g+=h+x,g-=b,p>d+k-_&&(E=ao),g<d-C+f+j&&(E=lo),E!==fu?[Math.max(T-h-hu(y,os,E)-_,0),T-C-x+f+hu(y,ss,E)+j]:null}),Ee(d=>d!=null),ut(ro)),[0,0]);return{increaseViewportBy:a,listBoundary:s,overscan:l,topListHeight:i,visibleRange:c}},ct(Ft),{singleton:!0});function Ey(e,t,n){if(rs(t)){const r=iu(e,t);return[{index:fn(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 ra={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function is(e,t,n,r,o,s){const{lastIndex:i,lastOffset:a,lastSize:l}=o;let c=0,d=0;if(e.length>0){c=e[0].offset;const y=e[e.length-1];d=y.offset+y.size}const f=n-i,h=a+f*l+(f-1)*r,p=c,g=h-d;return{bottom:d,firstItemIndex:s,items:gu(e,o,s),offsetBottom:g,offsetTop:c,top:p,topItems:gu(t,o,s),topListHeight:t.reduce((y,v)=>v.size+y,0),totalCount:n}}function mu(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=ta(t,a),c=Array.from({length:a}).map((d,f)=>({data:s[f+l],index:f+l,offset:0,size:0}));return is(c,[],a,o,n,r)}function gu(e,t,n){if(e.length===0)return[];if(!rs(t))return e.map(c=>({...c,index:c.index+n,originalIndex:c.index}));const r=e[0].index,o=e[e.length-1].index,s=[],i=es(t.groupOffsetTree,r,o);let a,l=0;for(const c of e){(!a||a.end<c.index)&&(a=i.shift(),l=t.groupIndices.indexOf(a.start));let d;c.index===a.start?d={index:l,type:"group"}:d={groupIndex:l,index:c.index-(l+1)+n},s.push({...d,data:c.data,offset:c.offset,originalIndex:c.index,size:c.size})}return s}const hr=Ye(([{data:e,firstItemIndex:t,gap:n,sizes:r,totalCount:o},s,{listBoundary:i,topListHeight:a,visibleRange:l},{initialTopMostItemIndex:c,scrolledToInitialItem:d},{topListHeight:f},h,{didMount:p},{recalcInProgress:g}])=>{const y=J([]),v=J(0),x=Ve();ve(s.topItemsIndexes,y);const b=Pt(V(bt(p,g,Te(l,ro),Te(o),Te(r),Te(c),d,Te(y),Te(t),Te(n),e),Ee(([C,E,,_,,,,,,,j])=>{const D=j&&j.length!==_;return C&&!E&&!D}),de(([,,[C,E],_,j,D,$,K,P,R,L])=>{const F=j,{offsetTree:ne,sizeTree:q}=F,B=xt(v);if(_===0)return{...ra,totalCount:_};if(C===0&&E===0)return B===0?{...ra,totalCount:_}:mu(B,D,j,P,R,L||[]);if(st(q))return B>0?null:is(Ey(ta(D,_),F,L),[],_,R,F,P);const pe=[];if(K.length>0){const be=K[0],ye=K[K.length-1];let G=0;for(const M of es(q,be,ye)){const X=M.value,oe=Math.max(M.start,be),xe=Math.min(M.end,ye);for(let se=oe;se<=xe;se++)pe.push({data:L==null?void 0:L[se],index:se,offset:G,size:X}),G+=X}}if(!$)return is([],pe,_,R,F,P);const W=K.length>0?K[K.length-1]+1:0,ce=py(ne,C,E,W);if(ce.length===0)return null;const H=_-1,Z=Qo([],be=>{for(const ye of ce){const G=ye.value;let M=G.offset,X=ye.start;const oe=G.size;if(G.offset<C){X+=Math.floor((C-G.offset+R)/(oe+R));const se=X-ye.start;M+=se*oe+se*R}X<W&&(M+=(W-X)*oe,X=W);const xe=Math.min(ye.end,H);for(let se=X;se<=xe&&!(M>=E);se++)be.push({data:L==null?void 0:L[se],index:se,offset:M,size:oe}),M+=oe+R}});return is(Z,pe,_,R,F,P)}),Ee(C=>C!==null),ut()),ra);ve(V(e,Ee(Ui),de(C=>C==null?void 0:C.length)),o),ve(V(b,de(C=>C.topListHeight)),f),ve(f,a),ve(V(b,de(C=>[C.top,C.bottom])),i),ve(V(b,de(C=>C.items)),x);const S=Wt(V(b,Ee(({items:C})=>C.length>0),Le(o,e),Ee(([{items:C},E])=>C[C.length-1].originalIndex===E-1),de(([,C,E])=>[C-1,E]),ut(ro),de(([C])=>C))),T=Wt(V(b,zn(200),Ee(({items:C,topItems:E})=>C.length>0&&C[0].originalIndex===E.length),de(({items:C})=>C[0].index),ut())),k=Wt(V(b,Ee(({items:C})=>C.length>0),de(({items:C})=>{let E=0,_=C.length-1;for(;C[E].type==="group"&&E<_;)E++;for(;C[_].type==="group"&&_>E;)_--;return{endIndex:C[_].index,startIndex:C[E].index}}),ut(ou)));return{endReached:S,initialItemCount:v,itemsRendered:x,listState:b,rangeChanged:k,startReached:T,topItemsIndexes:y,...h}},ct(kn,cu,na,io,so,co,Gn,Ji),{singleton:!0}),xu=Ye(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:r},{listState:o}])=>{const s=Ve(),i=Pt(V(bt(n,e,r,t,o),de(([a,l,c,d,f])=>a+l+c+d+f.offsetBottom+f.bottom)),0);return ve(Te(i),s),{totalListHeight:i,totalListHeightChanged:s}},ct(Ft,hr),{singleton:!0}),Iy=Ye(([{viewportHeight:e},{totalListHeight:t}])=>{const n=J(!1),r=Pt(V(bt(n,e,t),Ee(([o])=>o),de(([,o,s])=>Math.max(0,o-s)),zn(0),ut()),0);return{alignToBottom:n,paddingTopAddition:r}},ct(Ft,xu),{singleton:!0}),yu=Ye(()=>({context:J(null)})),Ay=({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,vu=Ye(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:s,scrollingInProgress:i,scrollTop:a,viewportHeight:l},{scrollToIndex:c}])=>{const d=Ve();return ve(V(d,Le(t,l,n,s,o,r,a),Le(e),de(([[f,h,p,g,y,v,x,b],S])=>{const{align:T,behavior:k,calculateViewLocation:C=Ay,done:E,..._}=f,j=au(f,h,g-1),D=oo(j,h.offsetTree,S)+y+v,$=D+fn(h.sizeTree,j)[1],K=b+v,P=b+p-x,R=C({itemBottom:$,itemTop:D,locationParams:{align:T,behavior:k,..._},viewportBottom:P,viewportTop:K});return R?E&&dn(V(i,Ee(L=>!L),ur(xt(i)?1:2)),E):E&&E(),R}),Ee(f=>f!==null)),c),{scrollIntoView:d}},ct(kn,Ft,so,hr,qn),{singleton:!0});function bu(e){return e?e==="smooth"?"smooth":"auto":!1}const Ny=(e,t)=>typeof e=="function"?bu(e(t)):t&&bu(e),_y=Ye(([{listRefresh:e,totalCount:t,fixedItemSize:n,data:r},{atBottomState:o,isAtBottom:s},{scrollToIndex:i},{scrolledToInitialItem:a},{didMount:l,propsReady:c},{log:d},{scrollingInProgress:f},{context:h},{scrollIntoView:p}])=>{const g=J(!1),y=Ve();let v=null;function x(k){Pe(i,{align:"end",behavior:k,index:"LAST"})}Qe(V(bt(V(Te(t),ur(1)),l),Le(Te(g),s,a,f),de(([[k,C],E,_,j,D])=>{let $=C&&j,K="auto";return $&&(K=Ny(E,_||D),$=$&&!!K),{followOutputBehavior:K,shouldFollow:$,totalCount:k}}),Ee(({shouldFollow:k})=>k)),({followOutputBehavior:k,totalCount:C})=>{v&&(v(),v=null),xt(n)?requestAnimationFrame(()=>{xt(d)("following output to ",{totalCount:C},Ut.DEBUG),x(k)}):v=dn(e,()=>{xt(d)("following output to ",{totalCount:C},Ut.DEBUG),x(k),v=null})});function b(k){const C=dn(o,E=>{k&&!E.atBottom&&E.notAtBottomBecause==="SIZE_INCREASED"&&!v&&(xt(d)("scrolling to bottom due to increased size",{},Ut.DEBUG),x("auto"))});setTimeout(C,100)}Qe(V(bt(Te(g),t,c),Ee(([k,,C])=>k&&C),Cn(({value:k},[,C])=>({refreshed:k===C,value:C}),{refreshed:!1,value:0}),Ee(({refreshed:k})=>k),Le(g,t)),([,k])=>{xt(a)&&b(k!==!1)}),Qe(y,()=>{b(xt(g)!==!1)}),Qe(bt(Te(g),o),([k,C])=>{k&&!C.atBottom&&C.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&x("auto")});const S=J(null),T=Ve();return ve(Vi(V(Te(r),de(k=>{var C;return(C=k==null?void 0:k.length)!=null?C:0})),V(Te(t))),T),Qe(V(bt(V(T,ur(1)),l),Le(Te(S),a,f,h),de(([[k,C],E,_,j,D])=>C&&_&&(E==null?void 0:E({context:D,totalCount:k,scrollingInProgress:j}))),Ee(k=>!!k),zn(0)),k=>{v&&(v(),v=null),xt(n)?requestAnimationFrame(()=>{xt(d)("scrolling into view",{}),Pe(p,k)}):v=dn(e,()=>{xt(d)("scrolling into view",{}),Pe(p,k),v=null})}),{autoscrollToBottom:y,followOutput:g,scrollIntoViewOnChange:S}},ct(kn,co,so,io,Gn,qn,Ft,yu,vu)),jy=Ye(([{data:e,firstItemIndex:t,gap:n,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:s,listState:i},{didMount:a}])=>(ve(V(a,Le(s),Ee(([,l])=>l!==0),Le(o,r,t,n,e),de(([[,l],c,d,f,h,p=[]])=>mu(l,c,d,f,h,p))),i),{}),ct(kn,io,hr,Gn),{singleton:!0}),Ry=Ye(([{didMount:e},{scrollTo:t},{listState:n}])=>{const r=J(0);return Qe(V(e,Le(r),Ee(([,o])=>o!==0),de(([,o])=>({top:o}))),o=>{dn(V(n,ur(1),Ee(s=>s.items.length>1)),()=>{requestAnimationFrame(()=>{Pe(t,o)})})}),{initialScrollTop:r}},ct(Gn,Ft,hr),{singleton:!0}),wu=Ye(([{scrollVelocity:e}])=>{const t=J(!1),n=Ve(),r=J(!1);return ve(V(e,Le(r,t,n),Ee(([o,s])=>!!s),de(([o,s,i,a])=>{const{enter:l,exit:c}=s;if(i){if(c(o,a))return!1}else if(l(o,a))return!0;return i}),ut()),t),Qe(V(bt(t,e,n),Le(r)),([[o,s,i],a])=>{o&&a&&a.change&&a.change(s,i)}),{isSeeking:t,scrollSeekConfiguration:r,scrollSeekRangeChanged:n,scrollVelocity:e}},ct(co),{singleton:!0}),oa=Ye(([{scrollContainerState:e,scrollTo:t}])=>{const n=Ve(),r=Ve(),o=Ve(),s=J(!1),i=J(void 0);return ve(V(bt(n,r),de(([{scrollHeight:a,scrollTop:l,viewportHeight:c},{offsetTop:d}])=>({scrollHeight:a,scrollTop:Math.max(0,l-d),viewportHeight:c}))),e),ve(V(t,Le(r),de(([a,{offsetTop:l}])=>({...a,top:a.top+l}))),o),{customScrollParent:i,useWindowScroll:s,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:r}},ct(Ft)),Py=Ye(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:r},{initialTopMostItemIndex:o},{didMount:s},{useWindowScroll:i,windowScrollContainerState:a,windowViewportRect:l}])=>{const c=Ve(),d=J(void 0),f=J(null),h=J(null);return ve(a,f),ve(l,h),Qe(V(c,Le(t,r,i,f,h,n)),([p,g,y,v,x,b,S])=>{const T=gy(g.sizeTree);v&&x!==null&&b!==null&&(y=x.scrollTop-b.offsetTop),y-=S,p({ranges:T,scrollTop:y})}),ve(V(d,Ee(Ui),de(Oy)),o),ve(V(s,Le(d),Ee(([,p])=>p!==void 0),ut(),de(([,p])=>p.ranges)),e),{getState:c,restoreStateFrom:d}},ct(kn,Ft,io,Gn,oa));function Oy(e){return{align:"start",index:0,offset:e.scrollTop}}const My=Ye(([{topItemsIndexes:e}])=>{const t=J(0);return ve(V(t,Ee(n=>n>=0),de(n=>Array.from({length:n}).map((r,o)=>o))),e),{topItemCount:t}},ct(hr));function Su(e){let t=!1,n;return()=>(t||(t=!0,n=e()),n)}const Dy=Su(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),Ly=Ye(([{deviation:e,scrollBy:t,scrollingInProgress:n,scrollTop:r},{isAtBottom:o,isScrolling:s,lastJumpDueToItemResize:i,scrollDirection:a},{listState:l},{beforeUnshiftWith:c,gap:d,shiftWithOffset:f,sizes:h},{log:p},{recalcInProgress:g}])=>{const y=Wt(V(l,Le(i),Cn(([,x,b,S],[{bottom:T,items:k,offsetBottom:C,totalCount:E},_])=>{const j=T+C;let D=0;return b===E&&x.length>0&&k.length>0&&(k[0].originalIndex===0&&x[0].originalIndex===0||(D=j-S,D!==0&&(D+=_))),[D,k,E,j]},[0,[],0,0]),Ee(([x])=>x!==0),Le(r,a,n,o,p,g),Ee(([,x,b,S,,,T])=>!T&&!S&&x!==0&&b===ao),de(([[x],,,,,b])=>(b("Upward scrolling compensation",{amount:x},Ut.DEBUG),x))));function v(x){x>0?(Pe(t,{behavior:"auto",top:-x}),Pe(e,0)):(Pe(e,0),Pe(t,{behavior:"auto",top:-x}))}return Qe(V(y,Le(e,s)),([x,b,S])=>{S&&Dy()?Pe(e,b-x):v(-x)}),Qe(V(bt(Pt(s,!1),e,g),Ee(([x,b,S])=>!x&&!S&&b!==0),de(([x,b])=>b),zn(1)),v),ve(V(f,de(x=>({top:-x}))),t),Qe(V(c,Le(h,d),de(([x,{groupIndices:b,lastSize:S,sizeTree:T},k])=>{function C(E){return E*(S+k)}if(b.length===0)return C(x);{let E=0;const _=no(T,0);let j=0,D=0;for(;j<x;){j++,E+=_;let $=b.length===D+1?1/0:b[D+1]-b[D]-1;j+$>x&&(E-=_,$=x-j+1),j+=$,E+=C($),D++}return E}})),x=>{Pe(e,x),requestAnimationFrame(()=>{Pe(t,{top:x}),requestAnimationFrame(()=>{Pe(e,0),Pe(g,!1)})})}),{deviation:e}},ct(Ft,co,hr,kn,qn,Ji)),Fy=Ye(([e,t,n,r,o,s,i,a,l,c,d])=>({...e,...t,...n,...r,...o,...s,...i,...a,...l,...c,...d}),ct(na,jy,Gn,wu,xu,Ry,Iy,oa,vu,qn,yu)),Cu=Ye(([{data:e,defaultItemSize:t,firstItemIndex:n,fixedItemSize:r,gap:o,groupIndices:s,itemSize:i,sizeRanges:a,sizes:l,statefulTotalCount:c,totalCount:d,trackItemSizes:f},{initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:g},y,v,x,{listState:b,topItemsIndexes:S,...T},{scrollToIndex:k},C,{topItemCount:E},{groupCounts:_},j])=>(ve(T.rangeChanged,j.scrollSeekRangeChanged),ve(V(j.windowViewportRect,de(D=>D.visibleHeight)),y.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:r,gap:o,groupCounts:_,initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:g,sizeRanges:a,topItemCount:E,topItemsIndexes:S,totalCount:d,...x,groupIndices:s,itemSize:i,listState:b,scrollToIndex:k,statefulTotalCount:c,trackItemSizes:f,...T,...j,...y,sizes:l,...v}),ct(kn,io,Ft,Py,_y,hr,so,Ly,My,cu,Fy));function $y(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 as=typeof document<"u"?w.useLayoutEffect:w.useEffect;function ku(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=w.createContext({});function l(v,x){v.propsReady&&Pe(v.propsReady,!1);for(const b of r){const S=v[t.required[b]];Pe(S,x[b])}for(const b of o)if(b in x){const S=v[t.optional[b]];Pe(S,x[b])}v.propsReady&&Pe(v.propsReady,!0)}function c(v){return s.reduce((x,b)=>(x[b]=S=>{const T=v[t.methods[b]];Pe(T,S)},x),{})}function d(v){return i.reduce((x,b)=>(x[b]=ty(v[t.events[b]]),x),{})}const f=w.forwardRef((v,x)=>{const{children:b,...S}=v,[T]=w.useState(()=>Qo(ry(e),E=>{l(E,S)})),[k]=w.useState(Kc(d,T));as(()=>{for(const E of i)E in S&&Qe(k[E],S[E]);return()=>{Object.values(k).map(Wi)}},[S,k,T]),as(()=>{l(T,S)}),w.useImperativeHandle(x,Vc(c(T)));const C=n;return u.jsx(a.Provider,{value:T,children:n?u.jsx(C,{...$y([...r,...o,...i],S),children:b}):b})}),h=v=>{const x=w.useContext(a);return w.useCallback(b=>{Pe(x[v],b)},[x,v])},p=v=>{const x=w.useContext(a)[v],b=w.useCallback(S=>Qe(x,S),[x]);return w.useSyncExternalStore(b,()=>xt(x),()=>xt(x))},g=v=>{const x=w.useContext(a)[v],[b,S]=w.useState(Kc(xt,x));return as(()=>Qe(x,T=>{T!==b&&S(Vc(T))}),[x,b]),b},y=w.version.startsWith("18")?p:g;return{Component:f,useEmitter:(v,x)=>{const b=w.useContext(a)[v];as(()=>Qe(b,x),[x,b])},useEmitterValue:y,usePublisher:h}}const Tu=w.createContext(void 0),Eu=w.createContext(void 0),Iu=typeof document<"u"?w.useLayoutEffect:w.useEffect;function sa(e){return"self"in e}function zy(e){return"body"in e}function Au(e,t,n,r=jr,o,s){const i=w.useRef(null),a=w.useRef(null),l=w.useRef(null),c=w.useCallback(h=>{let p,g,y;const v=h.target;if(zy(v)||sa(v)){const b=sa(v)?v:v.defaultView;y=s?b.scrollX:b.scrollY,p=s?b.document.documentElement.scrollWidth:b.document.documentElement.scrollHeight,g=s?b.innerWidth:b.innerHeight}else y=s?v.scrollLeft:v.scrollTop,p=s?v.scrollWidth:v.scrollHeight,g=s?v.offsetWidth:v.offsetHeight;const x=()=>{e({scrollHeight:p,scrollTop:Math.max(y,0),viewportHeight:g})};h.suppressFlushSync?x():hi.flushSync(x),a.current!==null&&(y===a.current||y<=0||y===p-g)&&(a.current=null,t(!0),l.current&&(clearTimeout(l.current),l.current=null))},[e,t,s]);w.useEffect(()=>{const h=o||i.current;return r(o||i.current),c({suppressFlushSync:!0,target:h}),h.addEventListener("scroll",c,{passive:!0}),()=>{r(null),h.removeEventListener("scroll",c)}},[i,c,n,r,o]);function d(h){const p=i.current;if(!p||(s?"offsetWidth"in p&&p.offsetWidth===0:"offsetHeight"in p&&p.offsetHeight===0))return;const g=h.behavior==="smooth";let y,v,x;sa(p)?(v=Math.max(Kn(p.document.documentElement,s?"width":"height"),s?p.document.documentElement.scrollWidth:p.document.documentElement.scrollHeight),y=s?p.innerWidth:p.innerHeight,x=s?window.scrollX:window.scrollY):(v=p[s?"scrollWidth":"scrollHeight"],y=Kn(p,s?"width":"height"),x=p[s?"scrollLeft":"scrollTop"]);const b=v-y;if(h.top=Math.ceil(Math.max(Math.min(b,h.top),0)),du(y,v)||h.top===x){e({scrollHeight:v,scrollTop:x,viewportHeight:y}),g&&t(!0);return}g?(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 ia="-webkit-sticky",Nu="sticky",aa=Su(()=>{if(typeof document>"u")return Nu;const e=document.createElement("div");return e.style.position=ia,e.style.position===ia?ia:Nu});function la(e){return e}const By=Ye(()=>{const e=J(a=>`Item ${a}`),t=J(a=>`Group ${a}`),n=J({}),r=J(la),o=J("div"),s=J(jr),i=(a,l=null)=>Pt(V(n,de(c=>c[a]),ut()),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")}}),Hy=Ye(([e,t])=>({...e,...t}),ct(Cu,By)),Uy=({height:e})=>u.jsx("div",{style:{height:e}}),Wy={overflowAnchor:"none",position:aa(),zIndex:1},_u={overflowAnchor:"none"},Vy={..._u,display:"inline-block",height:"100%"},ju=w.memo(function({showTopList:e=!1}){const t=Ne("listState"),n=en("sizeRanges"),r=Ne("useWindowScroll"),o=Ne("customScrollParent"),s=en("windowScrollContainerState"),i=en("scrollContainerState"),a=o||r?s:i,l=Ne("itemContent"),c=Ne("context"),d=Ne("groupContent"),f=Ne("trackItemSizes"),h=Ne("itemSize"),p=Ne("log"),g=en("gap"),y=Ne("horizontalDirection"),{callbackRef:v}=iy(n,h,f,e?jr:a,p,g,o,y,Ne("skipAnimationFrameInResizeObserver")),[x,b]=w.useState(0);ca("deviation",R=>{x!==R&&b(R)});const S=Ne("EmptyPlaceholder"),T=Ne("ScrollSeekPlaceholder")||Uy,k=Ne("ListComponent"),C=Ne("ItemComponent"),E=Ne("GroupComponent"),_=Ne("computeItemKey"),j=Ne("isSeeking"),D=Ne("groupIndices").length>0,$=Ne("alignToBottom"),K=Ne("initialItemFinalLocationReached"),P=e?{}:{boxSizing:"border-box",...y?{display:"inline-block",height:"100%",marginLeft:x!==0?x:$?"auto":0,paddingLeft:t.offsetTop,paddingRight:t.offsetBottom,whiteSpace:"nowrap"}:{marginTop:x!==0?x:$?"auto":0,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...K?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&S?u.jsx(S,{...Ot(S,c)}):u.jsx(k,{...Ot(k,c),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:v,style:P,children:(e?t.topItems:t.items).map(R=>{const L=R.originalIndex,F=_(L+t.firstItemIndex,R.data,c);return j?w.createElement(T,{...Ot(T,c),height:R.size,index:R.index,key:F,type:R.type||"item",...R.type==="group"?{}:{groupIndex:R.groupIndex}}):R.type==="group"?w.createElement(E,{...Ot(E,c),"data-index":L,"data-item-index":R.index,"data-known-size":R.size,key:F,style:Wy},d(R.index,c)):w.createElement(C,{...Ot(C,c),...Yy(C,R.data),"data-index":L,"data-item-group-index":R.groupIndex,"data-item-index":R.index,"data-known-size":R.size,key:F,style:y?Vy:_u},D?l(R.index,R.groupIndex,R.data,c):l(R.index,R.data,c))})})}),qy={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},Ky={outline:"none",overflowX:"auto",position:"relative"},ls=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:{}}),Gy={position:aa(),top:0,width:"100%",zIndex:1};function Ot(e,t){if(typeof e!="string")return{context:t}}function Yy(e,t){return{item:typeof e=="string"?void 0:t}}const Xy=w.memo(function(){const e=Ne("HeaderComponent"),t=en("headerHeight"),n=Ne("HeaderFooterTag"),r=dr(w.useMemo(()=>s=>{t(Kn(s,"height"))},[t]),!0,Ne("skipAnimationFrameInResizeObserver")),o=Ne("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Ot(e,o)})}):null}),Jy=w.memo(function(){const e=Ne("FooterComponent"),t=en("footerHeight"),n=Ne("HeaderFooterTag"),r=dr(w.useMemo(()=>s=>{t(Kn(s,"height"))},[t]),!0,Ne("skipAnimationFrameInResizeObserver")),o=Ne("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Ot(e,o)})}):null});function Ru({useEmitter:e,useEmitterValue:t,usePublisher:n}){return w.memo(function({children:r,style:o,context:s,...i}){const a=n("scrollContainerState"),l=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=t("scrollerRef"),f=t("horizontalDirection")||!1,{scrollByCallback:h,scrollerRef:p,scrollToCallback:g}=Au(a,c,l,d,void 0,f);return e("scrollTo",g),e("scrollBy",h),u.jsx(l,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:p,style:{...f?Ky:qy,...o},tabIndex:0,...i,...Ot(l,s),children:r})})}function Pu({useEmitter:e,useEmitterValue:t,usePublisher:n}){return w.memo(function({children:r,style:o,context:s,...i}){const a=n("windowScrollContainerState"),l=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=t("totalListHeight"),f=t("deviation"),h=t("customScrollParent"),p=w.useRef(null),g=t("scrollerRef"),{scrollByCallback:y,scrollerRef:v,scrollToCallback:x}=Au(a,c,l,g,h);return Iu(()=>{var b;return v.current=h||((b=p.current)==null?void 0:b.ownerDocument.defaultView),()=>{v.current=null}},[v,h]),e("windowScrollTo",x),e("scrollBy",y),u.jsx(l,{ref:p,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...d!==0?{height:d+f}:{}},...i,...Ot(l,s),children:r})})}const Zy=({children:e})=>{const t=w.useContext(Tu),n=en("viewportHeight"),r=en("fixedItemHeight"),o=Ne("alignToBottom"),s=Ne("horizontalDirection"),i=w.useMemo(()=>qc(n,l=>Kn(l,s?"width":"height")),[n,s]),a=dr(i,!0,Ne("skipAnimationFrameInResizeObserver"));return w.useEffect(()=>{t&&(n(t.viewportHeight),r(t.itemHeight))},[t,n,r]),u.jsx("div",{"data-viewport-type":"element",ref:a,style:ls(o),children:e})},Qy=({children:e})=>{const t=w.useContext(Tu),n=en("windowViewportRect"),r=en("fixedItemHeight"),o=Ne("customScrollParent"),s=Jc(n,o,Ne("skipAnimationFrameInResizeObserver")),i=Ne("alignToBottom");return w.useEffect(()=>{t&&(r(t.itemHeight),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:100}))},[t,n,r]),u.jsx("div",{"data-viewport-type":"window",ref:s,style:ls(i),children:e})},ev=({children:e})=>{const t=Ne("TopItemListComponent")||"div",n=Ne("headerHeight"),r={...Gy,marginTop:`${n}px`},o=Ne("context");return u.jsx(t,{style:r,...Ot(t,o),children:e})},tv=w.memo(function(e){const t=Ne("useWindowScroll"),n=Ne("topItemsIndexes").length>0,r=Ne("customScrollParent"),o=Ne("context");return u.jsxs(r||t?ov:rv,{...e,context:o,children:[n&&u.jsx(ev,{children:u.jsx(ju,{showTopList:!0})}),u.jsxs(r||t?Qy:Zy,{children:[u.jsx(Xy,{}),u.jsx(ju,{}),u.jsx(Jy,{})]})]})}),{Component:nv,useEmitter:ca,useEmitterValue:Ne,usePublisher:en}=ku(Hy,{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"}},tv),rv=Ru({useEmitter:ca,useEmitterValue:Ne,usePublisher:en}),ov=Pu({useEmitter:ca,useEmitterValue:Ne,usePublisher:en}),sv=nv;ct(Cu,Ye(()=>{const e=J(c=>u.jsxs("td",{children:["Item $",c]})),t=J(null),n=J(c=>u.jsxs("td",{colSpan:1e3,children:["Group ",c]})),r=J(null),o=J(null),s=J({}),i=J(la),a=J(jr),l=(c,d=null)=>Pt(V(s,de(f=>f[c]),ut()),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")}})),aa();const Ou={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},iv={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:Mu,floor:cs,max:uo,min:ua,round:Du}=Math;function Lu(e,t,n){return Array.from({length:t-e+1}).map((r,o)=>({data:n===null?null:n[o+e],index:o+e}))}function av(e){return{...iv,items:e}}function us(e,t){return e&&e.width===t.width&&e.height===t.height}function lv(e,t){return e&&e.column===t.column&&e.row===t.row}const cv=Ye(([{increaseViewportBy:e,listBoundary:t,overscan:n,visibleRange:r},{footerHeight:o,headerHeight:s,scrollBy:i,scrollContainerState:a,scrollTo:l,scrollTop:c,smoothScrollTargetReached:d,viewportHeight:f},h,p,{didMount:g,propsReady:y},{customScrollParent:v,useWindowScroll:x,windowScrollContainerState:b,windowScrollTo:S,windowViewportRect:T},k])=>{const C=J(0),E=J(0),_=J(Ou),j=J({height:0,width:0}),D=J({height:0,width:0}),$=Ve(),K=Ve(),P=J(0),R=J(null),L=J({column:0,row:0}),F=Ve(),ne=Ve(),q=J(!1),B=J(0),pe=J(!0),W=J(!1),ce=J(!1);Qe(V(g,Le(B),Ee(([M,X])=>!!X)),()=>{Pe(pe,!1)}),Qe(V(bt(g,pe,D,j,B,W),Ee(([M,X,oe,xe,,se])=>M&&!X&&oe.height!==0&&xe.height!==0&&!se)),([,,,,M])=>{Pe(W,!0),ea(1,()=>{Pe($,M)}),dn(V(c),()=>{Pe(t,[0,0]),Pe(pe,!0)})}),ve(V(ne,Ee(M=>M!=null&&M.scrollTop>0),Sn(0)),E),Qe(V(g,Le(ne),Ee(([,M])=>M!=null)),([,M])=>{M&&(Pe(j,M.viewport),Pe(D,M.item),Pe(L,M.gap),M.scrollTop>0&&(Pe(q,!0),dn(V(c,ur(1)),X=>{Pe(q,!1)}),Pe(l,{top:M.scrollTop})))}),ve(V(j,de(({height:M})=>M)),f),ve(V(bt(Te(j,us),Te(D,us),Te(L,(M,X)=>M&&M.column===X.column&&M.row===X.row),Te(c)),de(([M,X,oe,xe])=>({gap:oe,item:X,scrollTop:xe,viewport:M}))),F),ve(V(bt(Te(C),r,Te(L,lv),Te(D,us),Te(j,us),Te(R),Te(E),Te(q),Te(pe),Te(B)),Ee(([,,,,,,,M])=>!M),de(([M,[X,oe],xe,se,re,Ue,qe,,ot,at])=>{const{column:ht,row:tt}=xe,{height:Me,width:We}=se,{width:lt}=re;if(qe===0&&(M===0||lt===0))return Ou;if(We===0){const Oe=ta(at,M),Xe=Oe+Math.max(qe-1,0);return av(Lu(Oe,Xe,Ue))}const yt=Fu(lt,We,ht);let dt,Je;ot?X===0&&oe===0&&qe>0?(dt=0,Je=qe-1):(dt=yt*cs((X+tt)/(Me+tt)),Je=yt*Mu((oe+tt)/(Me+tt))-1,Je=ua(M-1,uo(Je,yt-1)),dt=ua(Je,uo(0,dt))):(dt=0,Je=-1);const ie=Lu(dt,Je,Ue),{bottom:je,top:ke}=$u(re,xe,se,ie),Ke=Mu(M/yt),nt=Ke*Me+(Ke-1)*tt-je;return{bottom:je,itemHeight:Me,items:ie,itemWidth:We,offsetBottom:nt,offsetTop:ke,top:ke}})),_),ve(V(R,Ee(M=>M!==null),de(M=>M.length)),C),ve(V(bt(j,D,_,L),Ee(([M,X,{items:oe}])=>oe.length>0&&X.height!==0&&M.height!==0),de(([M,X,{items:oe},xe])=>{const{bottom:se,top:re}=$u(M,xe,X,oe);return[re,se]}),ut(ro)),t);const H=J(!1);ve(V(c,Le(H),de(([M,X])=>X||M!==0)),H);const Z=Wt(V(bt(_,C),Ee(([{items:M}])=>M.length>0),Le(H),Ee(([[M,X],oe])=>{const xe=M.items[M.items.length-1].index===X-1;return(oe||M.bottom>0&&M.itemHeight>0&&M.offsetBottom===0&&M.items.length===X)&&xe}),de(([[,M]])=>M-1),ut())),be=Wt(V(Te(_),Ee(({items:M})=>M.length>0&&M[0].index===0),Sn(0),ut())),ye=Wt(V(Te(_),Le(q),Ee(([{items:M},X])=>M.length>0&&!X),de(([{items:M}])=>({endIndex:M[M.length-1].index,startIndex:M[0].index})),ut(ou),zn(0)));ve(ye,p.scrollSeekRangeChanged),ve(V($,Le(j,D,C,L),de(([M,X,oe,xe,se])=>{const re=uu(M),{align:Ue,behavior:qe,offset:ot}=re;let at=re.index;at==="LAST"&&(at=xe-1),at=uo(0,at,ua(xe-1,at));let ht=da(X,se,oe,at);return Ue==="end"?ht=Du(ht-X.height+oe.height):Ue==="center"&&(ht=Du(ht-X.height/2+oe.height/2)),ot&&(ht+=ot),{behavior:qe,top:ht}})),l);const G=Pt(V(_,de(M=>M.offsetBottom+M.bottom)),0);return ve(V(T,de(M=>({height:M.visibleHeight,width:M.visibleWidth}))),j),{customScrollParent:v,data:R,deviation:P,footerHeight:o,gap:L,headerHeight:s,increaseViewportBy:e,initialItemCount:E,itemDimensions:D,overscan:n,restoreStateFrom:ne,scrollBy:i,scrollContainerState:a,scrollHeight:K,scrollTo:l,scrollToIndex:$,scrollTop:c,smoothScrollTargetReached:d,totalCount:C,useWindowScroll:x,viewportDimensions:j,windowScrollContainerState:b,windowScrollTo:S,windowViewportRect:T,...p,gridState:_,horizontalDirection:ce,initialTopMostItemIndex:B,totalListHeight:G,...h,endReached:Z,propsReady:y,rangeChanged:ye,startReached:be,stateChanged:F,stateRestoreInProgress:q,...k}},ct(na,Ft,co,wu,Gn,oa,qn));function Fu(e,t,n){return uo(1,cs((e+n)/(cs(t)+n)))}function $u(e,t,n,r){const{height:o}=n;if(o===void 0||r.length===0)return{bottom:0,top:0};const s=da(e,t,n,r[0].index);return{bottom:da(e,t,n,r[r.length-1].index)+o,top:s}}function da(e,t,n,r){const o=Fu(e.width,n.width,t.column),s=cs(r/o),i=s*n.height+uo(0,s-1)*t.row;return i>0?i+t.row:i}const uv=Ye(()=>{const e=J(f=>`Item ${f}`),t=J({}),n=J(null),r=J("virtuoso-grid-item"),o=J("virtuoso-grid-list"),s=J(la),i=J("div"),a=J(jr),l=(f,h=null)=>Pt(V(t,de(p=>p[f]),ut()),h),c=J(!1),d=J(!1);return ve(Te(d),c),{components:t,computeItemKey:s,context:n,FooterComponent:l("Footer"),HeaderComponent:l("Header"),headerFooterTag:i,itemClassName:r,ItemComponent:l("Item","div"),itemContent:e,listClassName:o,ListComponent:l("List","div"),readyStateChanged:c,reportReadyState:d,ScrollerComponent:l("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder","div")}}),dv=Ye(([e,t])=>({...e,...t}),ct(cv,uv)),fv=w.memo(function(){const e=ft("gridState"),t=ft("listClassName"),n=ft("itemClassName"),r=ft("itemContent"),o=ft("computeItemKey"),s=ft("isSeeking"),i=tn("scrollHeight"),a=ft("ItemComponent"),l=ft("ListComponent"),c=ft("ScrollSeekPlaceholder"),d=ft("context"),f=tn("itemDimensions"),h=tn("gap"),p=ft("log"),g=ft("stateRestoreInProgress"),y=tn("reportReadyState"),v=dr(w.useMemo(()=>x=>{const b=x.parentElement.parentElement.scrollHeight;i(b);const S=x.firstChild;if(S){const{height:T,width:k}=S.getBoundingClientRect();f({height:T,width:k})}h({column:Bu("column-gap",getComputedStyle(x).columnGap,p),row:Bu("row-gap",getComputedStyle(x).rowGap,p)})},[i,f,h,p]),!0,!1);return Iu(()=>{e.itemHeight>0&&e.itemWidth>0&&y(!0)},[e]),g?null:u.jsx(l,{className:t,ref:v,...Ot(l,d),"data-testid":"virtuoso-item-list",style:{paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},children:e.items.map(x=>{const b=o(x.index,x.data,d);return s?u.jsx(c,{...Ot(c,d),height:e.itemHeight,index:x.index,width:e.itemWidth},b):w.createElement(a,{...Ot(a,d),className:n,"data-index":x.index,key:b},r(x.index,x.data,d))})})}),hv=w.memo(function(){const e=ft("HeaderComponent"),t=tn("headerHeight"),n=ft("headerFooterTag"),r=dr(w.useMemo(()=>s=>{t(Kn(s,"height"))},[t]),!0,!1),o=ft("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Ot(e,o)})}):null}),pv=w.memo(function(){const e=ft("FooterComponent"),t=tn("footerHeight"),n=ft("headerFooterTag"),r=dr(w.useMemo(()=>s=>{t(Kn(s,"height"))},[t]),!0,!1),o=ft("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Ot(e,o)})}):null}),mv=({children:e})=>{const t=w.useContext(Eu),n=tn("itemDimensions"),r=tn("viewportDimensions"),o=dr(w.useMemo(()=>s=>{r(s.getBoundingClientRect())},[r]),!0,!1);return w.useEffect(()=>{t&&(r({height:t.viewportHeight,width:t.viewportWidth}),n({height:t.itemHeight,width:t.itemWidth}))},[t,r,n]),u.jsx("div",{ref:o,style:ls(!1),children:e})},gv=({children:e})=>{const t=w.useContext(Eu),n=tn("windowViewportRect"),r=tn("itemDimensions"),o=ft("customScrollParent"),s=Jc(n,o,!1);return w.useEffect(()=>{t&&(r({height:t.itemHeight,width:t.itemWidth}),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:t.viewportWidth}))},[t,n,r]),u.jsx("div",{ref:s,style:ls(!1),children:e})},xv=w.memo(function({...e}){const t=ft("useWindowScroll"),n=ft("customScrollParent"),r=n||t?vv:yv,o=n||t?gv:mv,s=ft("context");return u.jsx(r,{...e,...Ot(r,s),children:u.jsxs(o,{children:[u.jsx(hv,{}),u.jsx(fv,{}),u.jsx(pv,{})]})})}),{useEmitter:zu,useEmitterValue:ft,usePublisher:tn}=ku(dv,{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"}},xv),yv=Ru({useEmitter:zu,useEmitterValue:ft,usePublisher:tn}),vv=Pu({useEmitter:zu,useEmitterValue:ft,usePublisher:tn});function Bu(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,Ut.WARN),t==="normal"?0:parseInt(t??"0",10)}const bv=Ro.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 Hu({className:e,variant:t,...n}){return u.jsx("div",{className:ee(bv({variant:t}),e),...n})}const fo=m.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ee("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));fo.displayName="Card";const ho=m.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ee("flex flex-col space-y-1.5 p-6",e),...t}));ho.displayName="CardHeader";const po=m.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:ee("text-2xl font-semibold leading-none tracking-tight",e),...t}));po.displayName="CardTitle";const Uu=m.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:ee("text-sm text-muted-foreground",e),...t}));Uu.displayName="CardDescription";const mo=m.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ee("p-6 pt-0",e),...t}));mo.displayName="CardContent";const Wu=m.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ee("flex items-center p-6 pt-0",e),...t}));Wu.displayName="CardFooter";function ge(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function wv(e,t){const n=m.createContext(t),r=s=>{const{children:i,...a}=s,l=m.useMemo(()=>a,Object.values(a));return u.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 Tn(e,t=[]){let n=[];function r(s,i){const a=m.createContext(i),l=n.length;n=[...n,i];const c=f=>{var x;const{scope:h,children:p,...g}=f,y=((x=h==null?void 0:h[e])==null?void 0:x[l])||a,v=m.useMemo(()=>g,Object.values(g));return u.jsx(y.Provider,{value:v,children:p})};c.displayName=s+"Provider";function d(f,h){var y;const p=((y=h==null?void 0:h[e])==null?void 0:y[l])||a,g=m.useContext(p);if(g)return g;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>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,Sv(o,...t)]}function Sv(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const f=l(s)[`__scope${c}`];return{...a,...f}},{});return m.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var kt=globalThis!=null&&globalThis.document?m.useLayoutEffect:()=>{},Cv=m[" useInsertionEffect ".trim().toString()]||kt;function pr({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=kv({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 c=m.useCallback(d=>{var f;if(a){const h=Tv(d)?d(e):d;h!==e&&((f=i.current)==null||f.call(i,h))}else s(d)},[a,e,s,i]);return[l,c]}function kv({defaultProp:e,onChange:t}){const[n,r]=m.useState(e),o=m.useRef(n),s=m.useRef(t);return Cv(()=>{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 Tv(e){return typeof e=="function"}function Vu(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function fa(...e){return t=>{let n=!1;const r=e.map(o=>{const s=Vu(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():Vu(e[o],null)}}}}function He(...e){return m.useCallback(fa(...e),e)}var Ev=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ie=Ev.reduce((e,t)=>{const n=sr.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),u.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function qu(e,t){e&&Po.flushSync(()=>e.dispatchEvent(t))}function Iv(e,t){return m.useReducer((n,r)=>t[n][r]??n,e)}var qt=e=>{const{present:t,children:n}=e,r=Av(t),o=typeof n=="function"?n({present:r.isPresent}):m.Children.only(n),s=He(r.ref,Nv(o));return typeof n=="function"||r.isPresent?m.cloneElement(o,{ref:s}):null};qt.displayName="Presence";function Av(e){const[t,n]=m.useState(),r=m.useRef(null),o=m.useRef(e),s=m.useRef("none"),i=e?"mounted":"unmounted",[a,l]=Iv(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return m.useEffect(()=>{const c=ds(r.current);s.current=a==="mounted"?c:"none"},[a]),kt(()=>{const c=r.current,d=o.current;if(d!==e){const h=s.current,p=ds(c);e?l("MOUNT"):p==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(d&&h!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),kt(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,f=p=>{const y=ds(r.current).includes(CSS.escape(p.animationName));if(p.target===t&&y&&(l("ANIMATION_END"),!o.current)){const v=t.style.animationFillMode;t.style.animationFillMode="forwards",c=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=v)})}},h=p=>{p.target===t&&(s.current=ds(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{d.clearTimeout(c),t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:m.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function ds(e){return(e==null?void 0:e.animationName)||"none"}function Nv(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 _v=m[" useId ".trim().toString()]||(()=>{}),jv=0;function En(e){const[t,n]=m.useState(_v());return kt(()=>{n(r=>r??String(jv++))},[e]),e||(t?`radix-${t}`:"")}var fs="Collapsible",[Rv,pT]=Tn(fs),[Pv,ha]=Rv(fs),Ku=m.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:o,disabled:s,onOpenChange:i,...a}=e,[l,c]=pr({prop:r,defaultProp:o??!1,onChange:i,caller:fs});return u.jsx(Pv,{scope:n,disabled:s,contentId:En(),open:l,onOpenToggle:m.useCallback(()=>c(d=>!d),[c]),children:u.jsx(Ie.div,{"data-state":ma(l),"data-disabled":s?"":void 0,...a,ref:t})})});Ku.displayName=fs;var Gu="CollapsibleTrigger",Yu=m.forwardRef((e,t)=>{const{__scopeCollapsible:n,...r}=e,o=ha(Gu,n);return u.jsx(Ie.button,{type:"button","aria-controls":o.contentId,"aria-expanded":o.open||!1,"data-state":ma(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...r,ref:t,onClick:ge(e.onClick,o.onOpenToggle)})});Yu.displayName=Gu;var pa="CollapsibleContent",Ov=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=ha(pa,e.__scopeCollapsible);return u.jsx(qt,{present:n||o.open,children:({present:s})=>u.jsx(Mv,{...r,ref:t,present:s})})});Ov.displayName=pa;var Mv=m.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:r,children:o,...s}=e,i=ha(pa,n),[a,l]=m.useState(r),c=m.useRef(null),d=He(t,c),f=m.useRef(0),h=f.current,p=m.useRef(0),g=p.current,y=i.open||a,v=m.useRef(y),x=m.useRef(void 0);return m.useEffect(()=>{const b=requestAnimationFrame(()=>v.current=!1);return()=>cancelAnimationFrame(b)},[]),kt(()=>{const b=c.current;if(b){x.current=x.current||{transitionDuration:b.style.transitionDuration,animationName:b.style.animationName},b.style.transitionDuration="0s",b.style.animationName="none";const S=b.getBoundingClientRect();f.current=S.height,p.current=S.width,v.current||(b.style.transitionDuration=x.current.transitionDuration,b.style.animationName=x.current.animationName),l(r)}},[i.open,r]),u.jsx(Ie.div,{"data-state":ma(i.open),"data-disabled":i.disabled?"":void 0,id:i.contentId,hidden:!y,...s,ref:d,style:{"--radix-collapsible-content-height":h?`${h}px`:void 0,"--radix-collapsible-content-width":g?`${g}px`:void 0,...e.style},children:y&&o})});function ma(e){return e?"open":"closed"}var Dv=Ku;const Lv=Dv,Fv=Yu,$v=1,zv=1e6;let ga=0;function Bv(){return ga=(ga+1)%Number.MAX_SAFE_INTEGER,ga.toString()}const xa=new Map,Xu=e=>{if(xa.has(e))return;const t=setTimeout(()=>{xa.delete(e),go({type:"REMOVE_TOAST",toastId:e})},zv);xa.set(e,t)},Hv=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,$v)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?Xu(n):e.toasts.forEach(r=>{Xu(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},hs=[];let ps={toasts:[]};function go(e){ps=Hv(ps,e),hs.forEach(t=>{t(ps)})}function Uv({...e}){const t=Bv(),n=o=>go({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>go({type:"DISMISS_TOAST",toastId:t});return go({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function ya(){const[e,t]=m.useState(ps);return m.useEffect(()=>(hs.push(t),()=>{const n=hs.indexOf(t);n>-1&&hs.splice(n,1)}),[e]),{...e,toast:Uv,dismiss:n=>go({type:"DISMISS_TOAST",toastId:n})}}async function Ju(e,t){return await cn(e,{responseType:"blob",onDownloadProgress:r=>{try{t&&r.lengthComputable}catch{}},maxBodyLength:1/0})}async function Zu(e,t){return await(await Ju(`/files/${e}/view`,t)).text()}async function Wv(e,t){const n=await Ju(`/files/${e}/download`,t),r=URL.createObjectURL(n);let o=`file_${e}`;try{const i=await cn(`/files/${e}`);o=(i==null?void 0:i.filename)??o}catch{}const s=document.createElement("a");s.href=r,s.download=o,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}async function Vv(e,t=50,n=0){const r={limit:t,offset:n};return e&&(r.thread_id=e),await cn("/files",{params:r})}function Qu(e){const t=e==null?void 0:e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return null;try{return JSON.parse(t)}catch{return null}}function ed(e){return!!(e&&typeof e=="object"&&(e.type==="file"||e.mimeType||e.filename||e.sourceType==="base64"))}function xo(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){if(Array.isArray(e)){const n=e.map(xo).filter(r=>r!==void 0);if(!n.length){console.debug("[message-utils] sanitizeForDisplay - array emptied -> returning undefined",{originalLength:e.length});return}return n}if(ed(e)){try{console.debug("[message-utils] sanitizeForDisplay - dropping file-like object",{sampleFilename:e&&(e.filename||e.name)?e.filename||e.name:void 0,keys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - dropped file-like (unable to inspect)",{err:String(n)})}return}const t={};for(const n of Object.keys(e)){const r=e[n];if(n==="data"&&typeof r=="string"&&r.length>100)t[n]=`[base64 ${r.length} chars omitted]`;else{const o=xo(r);o!==void 0&&(t[n]=o)}}if(Object.keys(t).length)return t;try{console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined",{originalKeys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined (inspect failed)",{err:String(n)})}return}return e}function ms(e){if(typeof e=="string")return e;if(ed(e))return"";try{const t=xo(e);return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}catch{return""}}function At(e){const t=m.useRef(e);return m.useEffect(()=>{t.current=e}),m.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function qv(e,t=globalThis==null?void 0:globalThis.document){const n=At(e);m.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var Kv="DismissableLayer",va="dismissableLayer.update",Gv="dismissableLayer.pointerDownOutside",Yv="dismissableLayer.focusOutside",td,nd=m.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),gs=m.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=m.useContext(nd),[d,f]=m.useState(null),h=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=m.useState({}),g=He(t,E=>f(E)),y=Array.from(c.layers),[v]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),x=y.indexOf(v),b=d?y.indexOf(d):-1,S=c.layersWithOutsidePointerEventsDisabled.size>0,T=b>=x,k=Zv(E=>{const _=E.target,j=[...c.branches].some(D=>D.contains(_));!T||j||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},h),C=Qv(E=>{const _=E.target;[...c.branches].some(D=>D.contains(_))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},h);return qv(E=>{b===c.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},h),m.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(td=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),rd(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=td)}},[d,h,n,c]),m.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),rd())},[d,c]),m.useEffect(()=>{const E=()=>p({});return document.addEventListener(va,E),()=>document.removeEventListener(va,E)},[]),u.jsx(Ie.div,{...l,ref:g,style:{pointerEvents:S?T?"auto":"none":void 0,...e.style},onFocusCapture:ge(e.onFocusCapture,C.onFocusCapture),onBlurCapture:ge(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:ge(e.onPointerDownCapture,k.onPointerDownCapture)})});gs.displayName=Kv;var Xv="DismissableLayerBranch",Jv=m.forwardRef((e,t)=>{const n=m.useContext(nd),r=m.useRef(null),o=He(t,r);return m.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(Ie.div,{...e,ref:o})});Jv.displayName=Xv;function Zv(e,t=globalThis==null?void 0:globalThis.document){const n=At(e),r=m.useRef(!1),o=m.useRef(()=>{});return m.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){od(Gv,n,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function Qv(e,t=globalThis==null?void 0:globalThis.document){const n=At(e),r=m.useRef(!1);return m.useEffect(()=>{const o=s=>{s.target&&!r.current&&od(Yv,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function rd(){const e=new CustomEvent(va);document.dispatchEvent(e)}function od(e,t,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?qu(o,s):o.dispatchEvent(s)}var ba="focusScope.autoFocusOnMount",wa="focusScope.autoFocusOnUnmount",sd={bubbles:!1,cancelable:!0},eb="FocusScope",xs=m.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=m.useState(null),c=At(o),d=At(s),f=m.useRef(null),h=He(t,y=>l(y)),p=m.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;m.useEffect(()=>{if(r){let y=function(S){if(p.paused||!a)return;const T=S.target;a.contains(T)?f.current=T:Yn(f.current,{select:!0})},v=function(S){if(p.paused||!a)return;const T=S.relatedTarget;T!==null&&(a.contains(T)||Yn(f.current,{select:!0}))},x=function(S){if(document.activeElement===document.body)for(const k of S)k.removedNodes.length>0&&Yn(a)};document.addEventListener("focusin",y),document.addEventListener("focusout",v);const b=new MutationObserver(x);return a&&b.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",y),document.removeEventListener("focusout",v),b.disconnect()}}},[r,a,p.paused]),m.useEffect(()=>{if(a){ld.add(p);const y=document.activeElement;if(!a.contains(y)){const x=new CustomEvent(ba,sd);a.addEventListener(ba,c),a.dispatchEvent(x),x.defaultPrevented||(tb(ib(id(a)),{select:!0}),document.activeElement===y&&Yn(a))}return()=>{a.removeEventListener(ba,c),setTimeout(()=>{const x=new CustomEvent(wa,sd);a.addEventListener(wa,d),a.dispatchEvent(x),x.defaultPrevented||Yn(y??document.body,{select:!0}),a.removeEventListener(wa,d),ld.remove(p)},0)}}},[a,c,d,p]);const g=m.useCallback(y=>{if(!n&&!r||p.paused)return;const v=y.key==="Tab"&&!y.altKey&&!y.ctrlKey&&!y.metaKey,x=document.activeElement;if(v&&x){const b=y.currentTarget,[S,T]=nb(b);S&&T?!y.shiftKey&&x===T?(y.preventDefault(),n&&Yn(S,{select:!0})):y.shiftKey&&x===S&&(y.preventDefault(),n&&Yn(T,{select:!0})):x===b&&y.preventDefault()}},[n,r,p.paused]);return u.jsx(Ie.div,{tabIndex:-1,...i,ref:h,onKeyDown:g})});xs.displayName=eb;function tb(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Yn(r,{select:t}),document.activeElement!==n)return}function nb(e){const t=id(e),n=ad(t,e),r=ad(t.reverse(),e);return[n,r]}function id(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function ad(e,t){for(const n of e)if(!rb(n,{upTo:t}))return n}function rb(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function ob(e){return e instanceof HTMLInputElement&&"select"in e}function Yn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&ob(e)&&t&&e.select()}}var ld=sb();function sb(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=cd(e,t),e.unshift(t)},remove(t){var n;e=cd(e,t),(n=e[0])==null||n.resume()}}}function cd(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function ib(e){return e.filter(t=>t.tagName!=="A")}var ab="Portal",ys=m.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=m.useState(!1);kt(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?hi.createPortal(u.jsx(Ie.div,{...r,ref:t}),i):null});ys.displayName=ab;var Sa=0;function Ca(){m.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??ud()),document.body.insertAdjacentElement("beforeend",e[1]??ud()),Sa++,()=>{Sa===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Sa--}},[])}function ud(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var In=function(){return In=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},In.apply(this,arguments)};function dd(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function lb(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}typeof SuppressedError=="function"&&SuppressedError;var vs="right-scroll-bar-position",bs="width-before-scroll-bar",cb="with-scroll-bars-hidden",ub="--removed-body-scroll-bar-size";function ka(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function db(e,t){var n=w.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var fb=typeof window<"u"?m.useLayoutEffect:m.useEffect,fd=new WeakMap;function hb(e,t){var n=db(null,function(r){return e.forEach(function(o){return ka(o,r)})});return fb(function(){var r=fd.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||ka(a,null)}),s.forEach(function(a){o.has(a)||ka(a,i)})}fd.set(n,e)},[e]),n}function pb(e){return e}function mb(e,t){t===void 0&&(t=pb);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(s){var i=t(s,r);return n.push(i),function(){n=n.filter(function(a){return a!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var a=n;n=[],a.forEach(s),i=n}var l=function(){var d=i;i=[],d.forEach(s)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(d){i.push(d),c()},filter:function(d){return i=i.filter(d),n}}}};return o}function gb(e){e===void 0&&(e={});var t=mb(null);return t.options=In({async:!0,ssr:!1},e),t}var hd=function(e){var t=e.sideCar,n=dd(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return m.createElement(r,In({},n))};hd.isSideCarExport=!0;function xb(e,t){return e.useMedium(t),hd}var pd=gb(),Ta=function(){},ws=m.forwardRef(function(e,t){var n=m.useRef(null),r=m.useState({onScrollCapture:Ta,onWheelCapture:Ta,onTouchMoveCapture:Ta}),o=r[0],s=r[1],i=e.forwardProps,a=e.children,l=e.className,c=e.removeScrollBar,d=e.enabled,f=e.shards,h=e.sideCar,p=e.noRelative,g=e.noIsolation,y=e.inert,v=e.allowPinchZoom,x=e.as,b=x===void 0?"div":x,S=e.gapMode,T=dd(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=h,C=hb([n,t]),E=In(In({},T),o);return m.createElement(m.Fragment,null,d&&m.createElement(k,{sideCar:pd,removeScrollBar:c,shards:f,noRelative:p,noIsolation:g,inert:y,setCallbacks:s,allowPinchZoom:!!v,lockRef:n,gapMode:S}),i?m.cloneElement(m.Children.only(a),In(In({},E),{ref:C})):m.createElement(b,In({},E,{className:l,ref:C}),a))});ws.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},ws.classNames={fullWidth:bs,zeroRight:vs};var yb=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function vb(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=yb();return t&&e.setAttribute("nonce",t),e}function bb(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function wb(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Sb=function(){var e=0,t=null;return{add:function(n){e==0&&(t=vb())&&(bb(t,n),wb(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Cb=function(){var e=Sb();return function(t,n){m.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},md=function(){var e=Cb(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},kb={left:0,top:0,right:0,gap:0},Ea=function(e){return parseInt(e||"",10)||0},Tb=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[Ea(n),Ea(r),Ea(o)]},Eb=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return kb;var t=Tb(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},Ib=md(),Pr="data-scroll-locked",Ab=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
39
39
  .`.concat(cb,` {
40
40
  overflow: hidden `).concat(r,`;
41
41
  padding-right: `).concat(a,"px ").concat(r,`;
@@ -124,8 +124,8 @@ ${t}</tr>
124
124
  `}tablecell(t,n){const r=n.header?"th":"td";return(n.align?`<${r} align="${n.align}">`:`<${r}>`)+t+`</${r}>
125
125
  `}strong(t){return`<strong>${t}</strong>`}em(t){return`<em>${t}</em>`}codespan(t){return`<code>${t}</code>`}br(){return this.options.xhtml?"<br/>":"<br>"}del(t){return`<del>${t}</del>`}link(t,n,r){if(t=Zd(this.options.sanitize,this.options.baseUrl,t),t===null)return r;let o='<a href="'+t+'"';return n&&(o+=' title="'+n+'"'),o+=">"+r+"</a>",o}image(t,n,r){if(t=Zd(this.options.sanitize,this.options.baseUrl,t),t===null)return r;let o=`<img src="${t}" alt="${r}"`;return n&&(o+=` title="${n}"`),o+=this.options.xhtml?"/>":">",o}text(t){return t}}class rf{strong(t){return t}em(t){return t}codespan(t){return t}del(t){return t}html(t){return t}text(t){return t}link(t,n,r){return""+r}image(t,n,r){return""+r}br(){return""}}class of{constructor(){this.seen={}}serialize(t){return t.toLowerCase().trim().replace(/<[!\/a-z].*?>/ig,"").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,"").replace(/\s/g,"-")}getNextSafeSlug(t,n){let r=t,o=0;if(this.seen.hasOwnProperty(r)){o=this.seen[t];do o++,r=t+"-"+o;while(this.seen.hasOwnProperty(r))}return n||(this.seen[t]=o,this.seen[r]=0),r}slug(t,n={}){const r=this.serialize(t);return this.getNextSafeSlug(r,n.dryrun)}}class Jn{constructor(t){this.options=t||xr,this.options.renderer=this.options.renderer||new Oa,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new rf,this.slugger=new of}static parse(t,n){return new Jn(n).parse(t)}static parseInline(t,n){return new Jn(n).parseInline(t)}parse(t,n=!0){let r="",o,s,i,a,l,c,d,f,h,p,g,y,v,x,b,S,T,k,C;const E=t.length;for(o=0;o<E;o++){if(p=t[o],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[p.type]&&(C=this.options.extensions.renderers[p.type].call({parser:this},p),C!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(p.type))){r+=C||"";continue}switch(p.type){case"space":continue;case"hr":{r+=this.renderer.hr();continue}case"heading":{r+=this.renderer.heading(this.parseInline(p.tokens),p.depth,Jd(this.parseInline(p.tokens,this.textRenderer)),this.slugger);continue}case"code":{r+=this.renderer.code(p.text,p.lang,p.escaped);continue}case"table":{for(f="",d="",a=p.header.length,s=0;s<a;s++)d+=this.renderer.tablecell(this.parseInline(p.header[s].tokens),{header:!0,align:p.align[s]});for(f+=this.renderer.tablerow(d),h="",a=p.rows.length,s=0;s<a;s++){for(c=p.rows[s],d="",l=c.length,i=0;i<l;i++)d+=this.renderer.tablecell(this.parseInline(c[i].tokens),{header:!1,align:p.align[i]});h+=this.renderer.tablerow(d)}r+=this.renderer.table(f,h);continue}case"blockquote":{h=this.parse(p.tokens),r+=this.renderer.blockquote(h);continue}case"list":{for(g=p.ordered,y=p.start,v=p.loose,a=p.items.length,h="",s=0;s<a;s++)b=p.items[s],S=b.checked,T=b.task,x="",b.task&&(k=this.renderer.checkbox(S),v?b.tokens.length>0&&b.tokens[0].type==="paragraph"?(b.tokens[0].text=k+" "+b.tokens[0].text,b.tokens[0].tokens&&b.tokens[0].tokens.length>0&&b.tokens[0].tokens[0].type==="text"&&(b.tokens[0].tokens[0].text=k+" "+b.tokens[0].tokens[0].text)):b.tokens.unshift({type:"text",text:k}):x+=k),x+=this.parse(b.tokens,v),h+=this.renderer.listitem(x,T,S);r+=this.renderer.list(h,g,y);continue}case"html":{r+=this.renderer.html(p.text);continue}case"paragraph":{r+=this.renderer.paragraph(this.parseInline(p.tokens));continue}case"text":{for(h=p.tokens?this.parseInline(p.tokens):p.text;o+1<E&&t[o+1].type==="text";)p=t[++o],h+=`
126
126
  `+(p.tokens?this.parseInline(p.tokens):p.text);r+=n?this.renderer.paragraph(h):h;continue}default:{const _='Token with "'+p.type+'" type was not found.';if(this.options.silent){console.error(_);return}else throw new Error(_)}}}return r}parseInline(t,n){n=n||this.renderer;let r="",o,s,i;const a=t.length;for(o=0;o<a;o++){if(s=t[o],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]&&(i=this.options.extensions.renderers[s.type].call({parser:this},s),i!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type))){r+=i||"";continue}switch(s.type){case"escape":{r+=n.text(s.text);break}case"html":{r+=n.html(s.text);break}case"link":{r+=n.link(s.href,s.title,this.parseInline(s.tokens,n));break}case"image":{r+=n.image(s.href,s.title,s.text);break}case"strong":{r+=n.strong(this.parseInline(s.tokens,n));break}case"em":{r+=n.em(this.parseInline(s.tokens,n));break}case"codespan":{r+=n.codespan(s.text);break}case"br":{r+=n.br();break}case"del":{r+=n.del(this.parseInline(s.tokens,n));break}case"text":{r+=n.text(s.text);break}default:{const l='Token with "'+s.type+'" type was not found.';if(this.options.silent){console.error(l);return}else throw new Error(l)}}}return r}}class Ms{constructor(t){this.options=t||xr}preprocess(t){return t}postprocess(t){return t}}Cm(Ms,"passThroughHooks",new Set(["preprocess","postprocess"]));function Cw(e,t,n){return r=>{if(r.message+=`
127
- Please report this to https://github.com/markedjs/marked.`,e){const o="<p>An error occurred:</p><pre>"+Mt(r.message+"",!0)+"</pre>";if(t)return Promise.resolve(o);if(n){n(null,o);return}return o}if(t)return Promise.reject(r);if(n){n(r);return}throw r}}function sf(e,t){return(n,r,o)=>{typeof r=="function"&&(o=r,r=null);const s={...r};r={...Se.defaults,...s};const i=Cw(r.silent,r.async,o);if(typeof n>"u"||n===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(bw(r),r.hooks&&(r.hooks.options=r),o){const a=r.highlight;let l;try{r.hooks&&(n=r.hooks.preprocess(n)),l=e(n,r)}catch(f){return i(f)}const c=function(f){let h;if(!f)try{r.walkTokens&&Se.walkTokens(l,r.walkTokens),h=t(l,r),r.hooks&&(h=r.hooks.postprocess(h))}catch(p){f=p}return r.highlight=a,f?i(f):o(null,h)};if(!a||a.length<3||(delete r.highlight,!l.length))return c();let d=0;Se.walkTokens(l,function(f){f.type==="code"&&(d++,setTimeout(()=>{a(f.text,f.lang,function(h,p){if(h)return c(h);p!=null&&p!==f.text&&(f.text=p,f.escaped=!0),d--,d===0&&c()})},0))}),d===0&&c();return}if(r.async)return Promise.resolve(r.hooks?r.hooks.preprocess(n):n).then(a=>e(a,r)).then(a=>r.walkTokens?Promise.all(Se.walkTokens(a,r.walkTokens)).then(()=>a):a).then(a=>t(a,r)).then(a=>r.hooks?r.hooks.postprocess(a):a).catch(i);try{r.hooks&&(n=r.hooks.preprocess(n));const a=e(n,r);r.walkTokens&&Se.walkTokens(a,r.walkTokens);let l=t(a,r);return r.hooks&&(l=r.hooks.postprocess(l)),l}catch(a){return i(a)}}}function Se(e,t,n){return sf(Xn.lex,Jn.parse)(e,t,n)}Se.options=Se.setOptions=function(e){return Se.defaults={...Se.defaults,...e},aw(Se.defaults),Se},Se.getDefaults=Kd,Se.defaults=xr,Se.use=function(...e){const t=Se.defaults.extensions||{renderers:{},childTokens:{}};e.forEach(n=>{const r={...n};if(r.async=Se.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if(o.renderer){const s=t.renderers[o.name];s?t.renderers[o.name]=function(...i){let a=o.renderer.apply(this,i);return a===!1&&(a=s.apply(this,i)),a}:t.renderers[o.name]=o.renderer}if(o.tokenizer){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");t[o.level]?t[o.level].unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),r.extensions=t),n.renderer){const o=Se.defaults.renderer||new Oa;for(const s in n.renderer){const i=o[s];o[s]=(...a)=>{let l=n.renderer[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.renderer=o}if(n.tokenizer){const o=Se.defaults.tokenizer||new Pa;for(const s in n.tokenizer){const i=o[s];o[s]=(...a)=>{let l=n.tokenizer[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.tokenizer=o}if(n.hooks){const o=Se.defaults.hooks||new Ms;for(const s in n.hooks){const i=o[s];Ms.passThroughHooks.has(s)?o[s]=a=>{if(Se.defaults.async)return Promise.resolve(n.hooks[s].call(o,a)).then(c=>i.call(o,c));const l=n.hooks[s].call(o,a);return i.call(o,l)}:o[s]=(...a)=>{let l=n.hooks[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.hooks=o}if(n.walkTokens){const o=Se.defaults.walkTokens;r.walkTokens=function(s){let i=[];return i.push(n.walkTokens.call(this,s)),o&&(i=i.concat(o.call(this,s))),i}}Se.setOptions(r)})},Se.walkTokens=function(e,t){let n=[];for(const r of e)switch(n=n.concat(t.call(Se,r)),r.type){case"table":{for(const o of r.header)n=n.concat(Se.walkTokens(o.tokens,t));for(const o of r.rows)for(const s of o)n=n.concat(Se.walkTokens(s.tokens,t));break}case"list":{n=n.concat(Se.walkTokens(r.items,t));break}default:Se.defaults.extensions&&Se.defaults.extensions.childTokens&&Se.defaults.extensions.childTokens[r.type]?Se.defaults.extensions.childTokens[r.type].forEach(function(o){n=n.concat(Se.walkTokens(r[o],t))}):r.tokens&&(n=n.concat(Se.walkTokens(r.tokens,t)))}return n},Se.parseInline=sf(Xn.lexInline,Jn.parseInline),Se.Parser=Jn,Se.parser=Jn.parse,Se.Renderer=Oa,Se.TextRenderer=rf,Se.Lexer=Xn,Se.lexer=Xn.lex,Se.Tokenizer=Pa,Se.Slugger=of,Se.Hooks=Ms,Se.parse=Se,Se.options,Se.setOptions,Se.use,Se.walkTokens,Se.parseInline,Jn.parse,Xn.lex;function Ds({content:e,className:t="",allowHtml:n=!1,style:r}){const o=w.useMemo(()=>{try{if(!n){const i=e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");return Se.parse(i)}return Se.parse(e)}catch(i){return console.error("[MarkdownContent] parse error",i),`<pre class="font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words">Error rendering markdown: ${String(i)}</pre>`}},[e,n]),s=w.useMemo(()=>{const i={color:"currentColor",...r};if(r&&r.color){const a=r.color;return{...i,"--tw-prose-body":a,"--tw-prose-headings":a,"--tw-prose-links":a,"--tw-prose-bold":a,"--tw-prose-counters":a,"--tw-prose-bullets":a,"--tw-prose-hr":a,"--tw-prose-quotes":a,"--tw-prose-quote-borders":a,"--tw-prose-captions":a,"--tw-prose-code":a,"--tw-prose-pre-code":a,"--tw-prose-pre-bg":"inherit","--tw-prose-th-borders":a,"--tw-prose-td-borders":a}}return i},[r]);return u.jsx("div",{className:ee("markdown prose prose-sm max-w-none break-words","dark:prose-invert","text-current","prose-headings:text-current prose-p:text-current prose-li:text-current prose-a:text-current prose-strong:text-current","prose-em:text-current prose-blockquote:text-current prose-table:text-current prose-td:text-current prose-th:text-current","prose-pre:font-mono prose-pre:text-xs prose-pre:bg-background/50 prose-pre:border prose-pre:rounded prose-pre:p-3 prose-pre:whitespace-pre prose-pre:overflow-x-auto","prose-code:font-mono prose-code:text-sm prose-code:bg-background/50 prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-current",t),style:s,dangerouslySetInnerHTML:{__html:o}})}const kw="prose prose-sm max-w-none break-words dark:prose-invert prose-headings:break-words prose-p:break-words prose-li:break-words prose-td:break-words prose-th:break-words prose-a:break-all prose-code:break-words prose-blockquote:break-words";function Tw(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}function af(e){const t=e.find(r=>r.type==="tool_call"),n=e.find(r=>r.type==="tool_end");return{name:t==null?void 0:t.name,toolCallId:(n==null?void 0:n.toolCallId)??(t==null?void 0:t.id)}}function Ls(e){if(e==null)return null;const t=String(e).trim();return t.length>0?t:null}function Ew(e){const t=o=>{try{const s=xo(o);return typeof s=="string"?s:JSON.stringify(s??"")}catch{return""}},n=e.filter(o=>o.type==="tool_end");let r="";if(n.length)try{n.length===1?r=t(n[0].output):r=t(n.map(o=>({toolCallId:o.toolCallId,output:o.output})))}catch{r=""}else r=t(e);return r||""}function Iw(e){return e.name&&e.name.trim()?e.name:e.model&&e.model.includes("/")?e.model.split("/").pop()||null:e.model||null}function lf(e){if("type"in e&&e.type==="default_message")return`default:${e.content.length}`;const t=e.updatedAt??e.createdAt??"",n=Array.isArray(e.content)?e.content.map(r=>{switch(r.type){case"text":return`t:${r.text.length}`;case"image_url":return"img";case"file":return"file";case"tool_call":return"call";case"tool_end":return"end";default:return"unknown"}}).join("|"):"";return`${e.id}:${t}:${n}`}function Aw({className:e}){const[t,n]=w.useState(0);return w.useEffect(()=>{const r=setInterval(()=>n(o=>(o+1)%4),500);return()=>clearInterval(r)},[]),u.jsxs("span",{"aria-live":"polite",className:ee("inline-block text-xs opacity-70 ml-1",e),children:["Is thinking",".".repeat(t)]})}const Ma=w.memo(function({message:t,messageIndex:n,isStreamingMessage:r=!1,isEditing:o=!1,showActions:s=!0,showTimestamp:i=!0,showAgentName:a=!0,layoutSize:l="desktop",truncateUserMessages:c=!0,userMessagePreviewLength:d=200,showToolMessages:f=!0,customStyles:h={},onEdit:p,onRegenerate:g,onCancelEdit:y,onCopy:v,activeInterrupt:x,disableInterruptActions:b=!1,onInterruptActionStart:S,onInterruptActionEnd:T}){const[k,C]=w.useState(!1),[E,_]=w.useState("preview"),[j,D]=w.useState(!1),{currentThreadId:$}=Yo(),{respondToInterrupt:K}=Xo(),P=l==="phone"||l==="half-screen",R=t.role,L=R==="tool",F=w.useMemo(()=>"type"in t&&t.type==="default_message"?t:null,[t]),ne=!!F,q=!(r&&R!=="user"),{uploadingFiles:B,handleFileClick:pe,fileViewerOpen:W,currentFileInfo:ce,closeFileViewer:H}=_w({allowFileOpen:q,currentThreadId:$}),Z=w.useMemo(()=>{switch(R){case"user":return"text-[hsl(var(--chat-bubble-user-text))]";case"assistant":return"text-[hsl(var(--chat-bubble-ai-text))]";case"tool":return"text-secondary-foreground";case"system":return"text-muted-foreground";default:return"text-[hsl(var(--chat-bubble-ai-text))]"}},[R]),be=w.useMemo(()=>F?"":Tw(t.content),[F,t]),ye=w.useMemo(()=>F?{}:af(t.content),[F,t]),G=w.useMemo(()=>F?[]:t.content.filter(ie=>ie.type==="image_url"),[F,t]),M=w.useMemo(()=>F?[]:t.content.filter(ie=>ie.type==="file"),[F,t]),X=w.useMemo(()=>F?[]:t.content.filter(ie=>ie.type==="interrupt"),[F,t]),oe=(x==null?void 0:x.id)??(x==null?void 0:x.interrupt_id),xe=Ls(oe),se=x==null?void 0:x.value,re=w.useMemo(()=>F?"":Ew(t.content),[F,t]),Ue=w.useCallback(async()=>{const ie=L?re:be;async function je(ke){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(ke);return}if(navigator.clipboard&&typeof navigator.clipboard.write=="function"&&typeof ClipboardItem<"u"){const Ke=new Blob([ke],{type:"text/plain"});await navigator.clipboard.write([new ClipboardItem({"text/plain":Ke})]);return}throw new Error("Clipboard API not supported in this context.")}try{await je(ie),C(!0),setTimeout(()=>C(!1),2e3),v==null||v(ie)}catch(ke){console.error("Failed to copy:",ke)}},[L,re,be,v]),qe=w.useCallback(()=>{if(!p)return;const ie=L?re:be;p(t.id,ie)},[p,t.id,L,re,be]),ot=w.useCallback(()=>{g==null||g(n)},[g,n]),at=w.useCallback(()=>{const je=ee(P?"h-3 w-3":"h-4 w-4","opacity-60 flex-shrink-0",Z);switch(R){case"user":return u.jsx(fe.User,{className:je});case"assistant":return u.jsx(fe.Bot,{className:je});case"tool":return u.jsx(fe.Wrench,{className:je});default:return u.jsx(fe.Bot,{className:je})}},[P,Z,R]),ht=w.useCallback(()=>{const ie="group relative mb-4 flex w-full";switch(R){case"user":return ee(ie,"justify-end");case"assistant":case"tool":case"system":return ee(ie,"justify-start");default:return ie}},[R]),tt=w.useCallback(()=>{const ie=ee("rounded-lg px-4 py-3 relative min-w-0 max-w-full break-words",P&&"px-3 py-2 text-sm");if(ne)return ee(ie,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40 shadow-sm");switch(R){case"user":return ee(ie,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-user))] text-[hsl(var(--chat-bubble-user-text))]","border border-transparent");case"assistant":return ee(ie,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40");case"tool":return ee(ie,"w-full md:max-w-[95%] bg-secondary/50 text-secondary-foreground border border-dashed");case"system":return ee(ie,"w-full md:max-w-[85%] bg-accent/40 text-muted-foreground border");default:return ee(ie,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40")}},[P,ne,R]);if(ne&&F)return u.jsx("div",{className:ee(ht(),h.container),children:u.jsxs("div",{className:ee(tt(),h.content),children:[u.jsxs("div",{className:"flex items-center gap-2 mb-2 pb-2 border-b border-current/10",children:[u.jsx(fe.Bot,{className:ee("h-4 w-4",Z)}),a&&u.jsx("span",{className:"font-medium text-sm",children:"Assistant"})]}),u.jsx(Ds,{content:F.content,className:"text-current"})]})});const Me=w.useCallback(async ie=>{if(b)return;const je=Ls((ie==null?void 0:ie.id)??(ie==null?void 0:ie.interrupt_id));if(!je){console.warn("Interrupt part missing id",ie);return}try{S==null||S(),await K(je,!0)}catch(ke){console.error("Failed to approve interrupt:",ke)}finally{T==null||T()}},[b,T,S,K]),We=w.useCallback(async ie=>{if(b)return;const je=Ls((ie==null?void 0:ie.id)??(ie==null?void 0:ie.interrupt_id));if(!je){console.warn("Interrupt part missing id",ie);return}try{S==null||S(),await K(je,!1)}catch(ke){console.error("Failed to reject interrupt:",ke)}finally{T==null||T()}},[b,T,S,K]),lt=w.useCallback(({part:ie,i:je})=>{if(ie.type==="text"){const ke=ie.text??"",Ke=ke.trim(),nt=Qu(Ke);return nt&&R!=="tool"?u.jsx(cf,{data:nt},je):R==="user"&&c&&Ke.length>d?u.jsx(jw,{text:Ke,expanded:j,onExpandedChange:D,previewLength:d,isCompact:P},je):u.jsx(Ds,{content:ke,allowHtml:!1},je)}if(ie.type==="image_url"){const ke=ie;return u.jsx("div",{className:"my-2",children:u.jsx("img",{src:ke.url,alt:ke.alt??"",loading:"lazy",className:"border rounded max-h-[420px] w-auto object-contain"})},je)}if(ie.type==="file"){const ke=ie,Ke=ke.name||"file";return u.jsxs("a",{href:ke.url,onClick:nt=>pe(nt,ke,je),className:`inline-flex items-center gap-2 rounded px-2 py-1 text-xs bg-gray-100 border hover:bg-gray-200
128
- dark:bg-background/10 dark:border-border/30 dark:hover:bg-background/20`,children:[B[je]?u.jsx(fe.Loader,{className:"h-4 w-4 animate-spin"}):null,u.jsxs("span",{className:"truncate max-w-[180px]",children:[Ke,B[je]?" (processing)":""]})]},je)}if(ie.type==="interrupt"){const ke=ie,Ke=Ls((ke==null?void 0:ke.id)??(ke==null?void 0:ke.interrupt_id)),nt=!!(xe&&Ke&&Ke===xe),Oe=nt?se??(ke==null?void 0:ke.value):ke==null?void 0:ke.value,Xe=Ke?{...ke,id:Ke,interrupt_id:Ke}:ke;return u.jsx(Nw,{interruptPart:Xe,onApprove:Me,onReject:We,disabled:b,isActive:nt,payload:Oe},je)}return null},[pe,B,Me,We,R,c,d,j,P,xe,se,x,b,X]),yt=w.useCallback(()=>u.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted/30 rounded",children:[u.jsx(fe.Paperclip,{className:"h-4 w-4 text-muted-foreground"}),u.jsx("span",{className:"text-sm text-muted-foreground",children:"File upload"})]}),[]),dt=w.useCallback(()=>{const ie=be.trim().length>0||G.length>0||M.length>0||X.length>0;if(!L&&M.length>0&&!r)return yt();if(!L&&!ie&&!r)return null;if(L)return u.jsx(Rw,{message:t,viewMode:E},t.id);if(!L&&!F){const je=t,ke=u.jsx("div",{className:"space-y-2",children:je.content.map((Ke,nt)=>u.jsx(lt,{part:Ke,i:nt},nt))});return r?u.jsxs("div",{"aria-busy":"true",role:"status",children:[ke,u.jsx(Aw,{className:Z})]}):ke}},[be,G.length,M.length,X.length,r,L,E,yt,Z]),Je=w.useMemo(()=>F?"Assistant":Iw(t),[F,t]);return L&&!f?null:u.jsxs(u.Fragment,{children:[u.jsx("div",{className:ee(ht(),h.container),children:u.jsxs("div",{className:ee(tt(),h.content),children:[(i||a||L)&&u.jsxs("div",{className:ee("flex items-center justify-between mb-2 pb-2 border-b border-current/10",P&&"mb-1 pb-1",Z,h.header),children:[u.jsxs("div",{className:"flex items-center gap-2",children:[at(),a&&Je&&u.jsx("span",{className:ee("font-medium",P?"text-xs":"text-sm"),children:Je}),L&&u.jsxs(Hu,{variant:"outline",className:ee("text-xs flex items-center gap-1 cursor-pointer select-none",Z,"border border-current/40",P&&"text-xs h-4"),role:"button",tabIndex:0,"aria-expanded":E==="expanded",onClick:()=>_(ie=>ie==="expanded"?"preview":"expanded"),onKeyDown:ie=>{(ie.key==="Enter"||ie.key===" ")&&(ie.preventDefault(),_(je=>je==="expanded"?"preview":"expanded"))},children:[u.jsx("span",{children:ye.name??"Tool Output"}),ye.toolCallId&&u.jsx("span",{className:"opacity-70",children:ye.toolCallId.slice(0,8)}),E==="expanded"?u.jsx(fe.ChevronUp,{className:"h-3 w-3"}):u.jsx(fe.ChevronDown,{className:"h-3 w-3"})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[i&&t.createdAt&&u.jsx("time",{className:ee("text-xs opacity-60",Z,P&&"text-xs"),dateTime:new Date(t.createdAt).toISOString(),title:new Date(t.createdAt).toLocaleString(),children:new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(new Date(t.createdAt))}),s&&!o&&u.jsxs("div",{className:ee("opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",h.actions),children:[u.jsx("div",{className:"relative",children:u.jsx(Ze,{variant:"ghost",size:"sm",onClick:()=>Ue(),className:ee("h-6 w-6 p-0 hover:bg-foreground/10",Z,P&&"h-5 w-5"),"aria-label":"Copy message",title:"Copy message",children:u.jsx(fe.Copy,{className:ee(k?"text-success":Z,P?"h-3 w-3":"h-4 w-4")})})}),R==="user"&&p&&u.jsx(Ze,{variant:"ghost",size:"sm",onClick:qe,className:ee("h-6 w-6 p-0 hover:bg-foreground/10",Z,P&&"h-5 w-5"),"aria-label":"Edit message",children:u.jsx(fe.Edit,{className:ee(Z,P?"h-3 w-3":"h-4 w-4")})}),R==="assistant"&&g&&u.jsx(Ze,{variant:"ghost",size:"sm",onClick:ot,className:ee("h-6 w-6 p-0 hover:bg-foreground/10",Z,P&&"h-5 w-5"),"aria-label":"Regenerate response",children:u.jsx(fe.RotateCcw,{className:ee(Z,P?"h-3 w-3":"h-4 w-4")})})]})]})]}),u.jsx("div",{className:"relative",children:dt()}),L&&E==="expanded"&&(ye.toolCallId||ye.name)&&u.jsxs("div",{className:ee("mt-2 pt-2 border-t border-current/10 text-xs opacity-60",P&&"text-xs"),children:[ye.name&&u.jsxs("div",{children:["Function: ",ye.name]}),ye.toolCallId&&u.jsxs("div",{children:["Call ID: ",ye.toolCallId]})]}),!(i||a||L)&&s&&!o&&u.jsxs("div",{className:ee("absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",h.actions),children:[u.jsx(Ze,{variant:"ghost",size:"sm",onClick:()=>Ue(),className:ee("h-6 w-6 p-0 hover:bg-background/50 text-current",P&&"h-5 w-5"),children:u.jsx(fe.Copy,{className:ee(k?"text-success":"text-current",P?"h-3 w-3":"h-4 w-4")})}),R==="user"&&p&&u.jsx(Ze,{variant:"ghost",size:"sm",onClick:qe,className:ee("h-6 w-6 p-0 hover:bg-background/50 text-current",P&&"h-5 w-5"),children:u.jsx(fe.Edit,{className:ee("text-current",P?"h-3 w-3":"h-4 w-4")})}),R==="assistant"&&g&&u.jsx(Ze,{variant:"ghost",size:"sm",onClick:ot,className:ee("h-6 w-6 p-0 hover:bg-background/50 text-current",P&&"h-5 w-5"),children:u.jsx(fe.RotateCcw,{className:ee("text-current",P?"h-3 w-3":"h-4 w-4")})})]})]})}),ce&&u.jsx(iw,{isOpen:W,onClose:H,fileId:ce.id,fileName:ce.name,mimeType:ce.mimeType})]})},(e,t)=>{var i,a,l,c,d,f,h,p;if(t.isStreamingMessage||e.isStreamingMessage||!(e.message.id===t.message.id&&lf(e.message)===lf(t.message)))return!1;const o=["isEditing","showActions","layoutSize","showTimestamp","showAgentName","truncateUserMessages","userMessagePreviewLength","showToolMessages"].every(g=>e[g]===t[g]),s=((i=e.customStyles)==null?void 0:i.container)===((a=t.customStyles)==null?void 0:a.container)&&((l=e.customStyles)==null?void 0:l.content)===((c=t.customStyles)==null?void 0:c.content)&&((d=e.customStyles)==null?void 0:d.actions)===((f=t.customStyles)==null?void 0:f.actions)&&((h=e.customStyles)==null?void 0:h.header)===((p=t.customStyles)==null?void 0:p.header);return o&&s});function cf({data:e}){return Array.isArray(e)?e.every(n=>n===null||["string","number","boolean"].includes(typeof n))?u.jsx("div",{className:kw,children:u.jsx("ul",{className:"list-disc pl-5",children:e.map((n,r)=>u.jsx("li",{children:String(n)},r))})}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:ms(e)}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:ms(e)})}function Nw({interruptPart:e,onApprove:t,onReject:n,disabled:r,isActive:o,payload:s}){const i=e.title??"Approve the result?";let a=null;if(s!=null)if(typeof s=="string")a=u.jsx("p",{className:"text-sm leading-relaxed text-blue-800/90 dark:text-blue-200/90 whitespace-pre-wrap",children:s});else{const c=ms(s);a=u.jsx("pre",{className:"max-h-48 overflow-auto rounded bg-blue-100/60 p-2 text-xs text-blue-900/90 dark:bg-blue-900/40 dark:text-blue-100/80",children:c})}const l=o?"Please approve or reject this action to resume the workflow.":"Waiting for approval from another participant.";return u.jsxs(fo,{className:ee("border-blue-200 dark:border-blue-800 bg-blue-50/50 dark:bg-blue-950/10 transition-shadow",o?"shadow-md ring-1 ring-blue-300 dark:ring-blue-500/70":"opacity-80"),children:[u.jsxs(ho,{className:"pb-3",children:[u.jsx(po,{className:"text-blue-900 dark:text-blue-100 text-base",children:i}),u.jsx(Uu,{className:"text-blue-700 dark:text-blue-300 text-sm",children:l})]}),a&&u.jsx(mo,{className:"pt-0 pb-3",children:a}),u.jsx(Wu,{className:"pt-0",children:u.jsxs("div",{className:"flex gap-2 ml-auto",children:[u.jsx(Ze,{size:"sm",variant:"outline",onClick:()=>n(e),className:"border-red-300 text-red-700 hover:bg-red-50 dark:border-red-700 dark:text-red-300 dark:hover:bg-red-950/50",disabled:r||!o,children:"Reject"}),u.jsx(Ze,{size:"sm",onClick:()=>t(e),className:"bg-blue-600 hover:bg-blue-700 text-white",disabled:r||!o,children:"Approve"})]})})]})}function _w(e){const{allowFileOpen:t,currentThreadId:n}=e,{toast:r}=ya(),[o,s]=w.useState({}),[i,a]=w.useState(null),[l,c]=w.useState(!1),d=w.useCallback(()=>{c(!1),a(null)},[]),f=w.useCallback(p=>{a(p),c(!0)},[]),h=w.useCallback(async(p,g,y)=>{var v,x;if(!t){p.preventDefault();return}if(o[y]){p.preventDefault();return}try{const b=String(g.url??""),S=b.match(/\/chat\/files\/([^/]+)(?:\/(view|download))?/);if(S){p.preventDefault();const T=S[1],k=g.name||`file_${T}`,C=g.mimeType||"application/octet-stream";f({id:T,name:k,mimeType:C});return}if(b.startsWith("data:")){p.preventDefault(),s(k=>({...k,[y]:!0}));const T=r({title:"Fetching file...",description:"",open:!0});try{const k=await Vv(n??void 0);if(!k||!Array.isArray(k))throw new Error("Invalid file list response");const C=k.find(E=>!E||typeof E!="object"||!((E.filename??"")===(g.name??""))?!1:typeof g.size=="number"&&typeof E.size=="number"?E.size===g.size:!0);if(!(C!=null&&C.id))throw new Error(`File "${g.name}" is not yet available on the server`);if(!C.id||!C.filename)throw new Error("Invalid file data received from server");f({id:C.id,name:g.name||C.filename||`file_${C.id}`,mimeType:g.mimeType||C.mime_type||"application/octet-stream"}),(v=T.update)==null||v.call(T,{id:T.id,title:"Success",description:`Opened ${g.name}`,open:!0})}catch(k){console.error("Failed to fetch server file:",k);const C=k instanceof Error?k.message:"Unknown error occurred";(x=T.update)==null||x.call(T,{id:T.id,title:"Failed",description:C}),r({title:"Failed to fetch file",description:C,open:!0})}finally{s(k=>({...k,[y]:!1}))}}}catch(b){console.error("File click error:",b),s(S=>({...S,[y]:!1}))}},[t,o,r,n,f]);return{uploadingFiles:o,handleFileClick:h,fileViewerOpen:l,currentFileInfo:i,closeFileViewer:d}}function jw({text:e,expanded:t,onExpandedChange:n,previewLength:r,isCompact:o}){return u.jsxs(Lv,{open:t,onOpenChange:n,children:[u.jsx("div",{className:ee("text-sm text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:t?u.jsx(Ds,{content:e,allowHtml:!1}):u.jsxs("pre",{className:ee("font-sans whitespace-pre-wrap break-words bg-transparent p-0 m-0 text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:[e.substring(0,r),"..."]})}),u.jsx(Fv,{asChild:!0,children:u.jsx(Ze,{variant:"ghost",size:"sm",className:"h-6 text-xs !text-[hsl(var(--chat-bubble-user-text))]",children:t?u.jsxs(u.Fragment,{children:[u.jsx(fe.ChevronUp,{className:"h-3 w-3 mr-1"})," Show less"]}):u.jsxs(u.Fragment,{children:[u.jsx(fe.ChevronDown,{className:"h-3 w-3 mr-1"})," Show more (",e.length-r," chars)"]})})})]})}function Rw({message:e,viewMode:t}){const r=af(e.content).name||"tool",o=a=>{if(a==null)return null;const l=typeof a=="string"?Qu(a)??a:a;if(l&&typeof l=="object")return u.jsx(cf,{data:l});const c=typeof l=="string"?l:(()=>{try{return ms(l)}catch{return String(l??"")}})();return u.jsx("pre",{className:"whitespace-pre-wrap break-words font-sans text-sm text-foreground/90",children:c})};if(t==="preview")return null;const s=e.content.find(a=>a.type!=="tool_call");if(!s)return u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(fe.Loader,{className:"h-4 w-4 animate-spin"}),u.jsxs("span",{children:["Waiting for ",r," output…"]})]});if(s.type==="text"){const l=(s.text??"").trim();return l?o(l):null}const i=xo(s);return o(i)}const uf=(e,t)=>(e==null?void 0:e.id)??`message-${t}`,Da=w.forwardRef(({messages:e,isStreaming:t,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onStartReached:a,onEdit:l,onRegenerate:c,onCancelEdit:d,className:f,style:h,emptyMessage:p,followNewMessages:g=!0,isNavigatingCheckpoint:y=!1,onScrollAway:v,onAtBottom:x,activeInterrupt:b,disableInterruptActions:S=!1,onInterruptActionStart:T,onInterruptActionEnd:k,showToolMessages:C=!0},E)=>{const _=w.useRef(null),j=w.useRef(null),D=w.useRef(!1),[$,K]=w.useState(!0),P=w.useMemo(()=>b?e.some(W=>"type"in W&&W.type==="default_message"?!1:Array.isArray(W==null?void 0:W.content)&&W.content.some(ce=>ce&&ce.type==="interrupt"&&(ce.id??ce.interrupt_id)===b.id)):!1,[b,e]),R=w.useMemo(()=>{if(!b||P)return null;const W=b.id&&String(b.id).trim()?String(b.id).trim():"pending-interrupt";let ce;const H=b.value;if(H&&typeof H=="object"&&!Array.isArray(H)){const Z=H.title;typeof Z=="string"&&Z.trim()&&(ce=Z.trim())}return{id:`interrupt-${W}`,role:"system",createdAt:new Date().toISOString(),content:[{type:"interrupt",id:W,value:H,title:ce}]}},[b,P]),L=w.useMemo(()=>R?[...e,R]:e,[e,R]),F=w.useMemo(()=>C?L:L.filter(W=>(W==null?void 0:W.role)!=="tool"),[L,C]),ne=w.useCallback(W=>{K(W),v&&v(!W),x&&x(W)},[v,x]),q=w.useMemo(()=>{if(a)return async()=>{if(!D.current){D.current=!0;try{await a()}finally{D.current=!1}}}},[a]),B=w.useMemo(()=>!g||y?!1:$?"auto":!1,[$,g,y]),pe=w.useMemo(()=>{if(typeof p!="string")return null;const W=p.trim();return W?{id:"default-message",role:"assistant",type:"default_message",content:W,createdAt:new Date().toISOString()}:null},[p]);return F.length===0?pe?u.jsx("div",{className:f,style:h,children:u.jsx("div",{className:"p-6 overflow-y-auto h-full flex items-start justify-center",children:u.jsx("div",{className:"w-full max-w-2xl",children:u.jsx(Ma,{message:pe,messageIndex:0,isStreamingMessage:!1,showActions:!1,showTimestamp:!1,showAgentName:!0,layoutSize:o,onEdit:()=>{},onRegenerate:()=>{},onCancelEdit:()=>{}})})})}):u.jsx("div",{className:f,style:h,children:u.jsx("div",{className:"flex items-center justify-center py-8 text-muted-foreground text-center max-w-2xl mx-auto",children:p||"No messages yet. Start a conversation!"})}):u.jsx("div",{className:f,style:h,children:u.jsx(sv,{ref:W=>{_.current=W},scrollerRef:W=>{j.current=W instanceof HTMLDivElement?W:null},data:F,followOutput:B,overscan:200,increaseViewportBy:{top:100,bottom:200},defaultItemHeight:80,atBottomThreshold:50,alignToBottom:!1,startReached:()=>{q&&q()},atBottomStateChange:ne,style:{height:"100%",overscrollBehavior:"contain"},computeItemKey:(W,ce)=>uf(ce,W),itemContent:(W,ce)=>{const H=uf(ce,W);return u.jsx("div",{className:"mb-4 last:mb-0","data-message-id":H,style:{minHeight:"60px",containIntrinsicSize:"auto 120px"},children:u.jsx(Ma,{message:ce,messageIndex:W,isStreamingMessage:t&&n===ce.id,streamingDebounceMs:r,isEditing:i===ce.id,showActions:s,showTimestamp:!1,showAgentName:!0,layoutSize:o,onEdit:l,onRegenerate:()=>c(W),onCancelEdit:d,activeInterrupt:b,disableInterruptActions:S,onInterruptActionStart:T,onInterruptActionEnd:k,showToolMessages:C})})}})})});Da.displayName="MessageList";const Fs=1e4;function Pw(e){if(typeof e!="string")return String(e);const t=[/<script[^>]*>.*?<\/script>/gi,/<iframe[^>]*>.*?<\/iframe>/gi,/javascript:/gi,/vbscript:/gi,/on\w+\s*=/gi,/<object[^>]*>.*?<\/object>/gi,/<embed[^>]*>.*?<\/embed>/gi,/<form[^>]*>.*?<\/form>/gi];let n=e;for(const o of t)n=n.replace(o,"");return/<[^>]+>/.test(n)&&!/<(?!\/?(?:code|strong|em|b|i|br|p|ul|ol|li|h[1-6])\b)[^>]+>/i.test(n)?n.replace(/<code>(.*?)<\/code>/gi,"`$1`").replace(/<strong>(.*?)<\/strong>/gi,"**$1**").replace(/<b>(.*?)<\/b>/gi,"**$1**").replace(/<em>(.*?)<\/em>/gi,"*$1*").replace(/<i>(.*?)<\/i>/gi,"*$1*").replace(/<br\s*\/?>/gi,`
127
+ Please report this to https://github.com/markedjs/marked.`,e){const o="<p>An error occurred:</p><pre>"+Mt(r.message+"",!0)+"</pre>";if(t)return Promise.resolve(o);if(n){n(null,o);return}return o}if(t)return Promise.reject(r);if(n){n(r);return}throw r}}function sf(e,t){return(n,r,o)=>{typeof r=="function"&&(o=r,r=null);const s={...r};r={...Se.defaults,...s};const i=Cw(r.silent,r.async,o);if(typeof n>"u"||n===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(bw(r),r.hooks&&(r.hooks.options=r),o){const a=r.highlight;let l;try{r.hooks&&(n=r.hooks.preprocess(n)),l=e(n,r)}catch(f){return i(f)}const c=function(f){let h;if(!f)try{r.walkTokens&&Se.walkTokens(l,r.walkTokens),h=t(l,r),r.hooks&&(h=r.hooks.postprocess(h))}catch(p){f=p}return r.highlight=a,f?i(f):o(null,h)};if(!a||a.length<3||(delete r.highlight,!l.length))return c();let d=0;Se.walkTokens(l,function(f){f.type==="code"&&(d++,setTimeout(()=>{a(f.text,f.lang,function(h,p){if(h)return c(h);p!=null&&p!==f.text&&(f.text=p,f.escaped=!0),d--,d===0&&c()})},0))}),d===0&&c();return}if(r.async)return Promise.resolve(r.hooks?r.hooks.preprocess(n):n).then(a=>e(a,r)).then(a=>r.walkTokens?Promise.all(Se.walkTokens(a,r.walkTokens)).then(()=>a):a).then(a=>t(a,r)).then(a=>r.hooks?r.hooks.postprocess(a):a).catch(i);try{r.hooks&&(n=r.hooks.preprocess(n));const a=e(n,r);r.walkTokens&&Se.walkTokens(a,r.walkTokens);let l=t(a,r);return r.hooks&&(l=r.hooks.postprocess(l)),l}catch(a){return i(a)}}}function Se(e,t,n){return sf(Xn.lex,Jn.parse)(e,t,n)}Se.options=Se.setOptions=function(e){return Se.defaults={...Se.defaults,...e},aw(Se.defaults),Se},Se.getDefaults=Kd,Se.defaults=xr,Se.use=function(...e){const t=Se.defaults.extensions||{renderers:{},childTokens:{}};e.forEach(n=>{const r={...n};if(r.async=Se.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if(o.renderer){const s=t.renderers[o.name];s?t.renderers[o.name]=function(...i){let a=o.renderer.apply(this,i);return a===!1&&(a=s.apply(this,i)),a}:t.renderers[o.name]=o.renderer}if(o.tokenizer){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");t[o.level]?t[o.level].unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),r.extensions=t),n.renderer){const o=Se.defaults.renderer||new Oa;for(const s in n.renderer){const i=o[s];o[s]=(...a)=>{let l=n.renderer[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.renderer=o}if(n.tokenizer){const o=Se.defaults.tokenizer||new Pa;for(const s in n.tokenizer){const i=o[s];o[s]=(...a)=>{let l=n.tokenizer[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.tokenizer=o}if(n.hooks){const o=Se.defaults.hooks||new Ms;for(const s in n.hooks){const i=o[s];Ms.passThroughHooks.has(s)?o[s]=a=>{if(Se.defaults.async)return Promise.resolve(n.hooks[s].call(o,a)).then(c=>i.call(o,c));const l=n.hooks[s].call(o,a);return i.call(o,l)}:o[s]=(...a)=>{let l=n.hooks[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.hooks=o}if(n.walkTokens){const o=Se.defaults.walkTokens;r.walkTokens=function(s){let i=[];return i.push(n.walkTokens.call(this,s)),o&&(i=i.concat(o.call(this,s))),i}}Se.setOptions(r)})},Se.walkTokens=function(e,t){let n=[];for(const r of e)switch(n=n.concat(t.call(Se,r)),r.type){case"table":{for(const o of r.header)n=n.concat(Se.walkTokens(o.tokens,t));for(const o of r.rows)for(const s of o)n=n.concat(Se.walkTokens(s.tokens,t));break}case"list":{n=n.concat(Se.walkTokens(r.items,t));break}default:Se.defaults.extensions&&Se.defaults.extensions.childTokens&&Se.defaults.extensions.childTokens[r.type]?Se.defaults.extensions.childTokens[r.type].forEach(function(o){n=n.concat(Se.walkTokens(r[o],t))}):r.tokens&&(n=n.concat(Se.walkTokens(r.tokens,t)))}return n},Se.parseInline=sf(Xn.lexInline,Jn.parseInline),Se.Parser=Jn,Se.parser=Jn.parse,Se.Renderer=Oa,Se.TextRenderer=rf,Se.Lexer=Xn,Se.lexer=Xn.lex,Se.Tokenizer=Pa,Se.Slugger=of,Se.Hooks=Ms,Se.parse=Se,Se.options,Se.setOptions,Se.use,Se.walkTokens,Se.parseInline,Jn.parse,Xn.lex;function Ds({content:e,className:t="",allowHtml:n=!1,style:r}){const o=w.useMemo(()=>{try{if(!n){const i=e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");return Se.parse(i)}return Se.parse(e)}catch(i){return console.error("[MarkdownContent] parse error",i),`<pre class="font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words">Error rendering markdown: ${String(i)}</pre>`}},[e,n]),s=w.useMemo(()=>{const i={color:"currentColor",...r};if(r&&r.color){const a=r.color;return{...i,"--tw-prose-body":a,"--tw-prose-headings":a,"--tw-prose-links":a,"--tw-prose-bold":a,"--tw-prose-counters":a,"--tw-prose-bullets":a,"--tw-prose-hr":a,"--tw-prose-quotes":a,"--tw-prose-quote-borders":a,"--tw-prose-captions":a,"--tw-prose-code":a,"--tw-prose-pre-code":a,"--tw-prose-pre-bg":"inherit","--tw-prose-th-borders":a,"--tw-prose-td-borders":a}}return i},[r]);return u.jsx("div",{className:ee("markdown prose prose-sm max-w-none break-words","dark:prose-invert","text-current","prose-headings:text-current prose-p:text-current prose-li:text-current prose-a:text-current prose-strong:text-current","prose-em:text-current prose-blockquote:text-current prose-table:text-current prose-td:text-current prose-th:text-current","prose-pre:font-mono prose-pre:text-xs prose-pre:bg-background/50 prose-pre:border prose-pre:rounded prose-pre:p-3 prose-pre:whitespace-pre prose-pre:overflow-x-auto","prose-code:font-mono prose-code:text-sm prose-code:bg-background/50 prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-current",t),style:s,dangerouslySetInnerHTML:{__html:o}})}const kw="prose prose-sm max-w-none break-words dark:prose-invert prose-headings:break-words prose-p:break-words prose-li:break-words prose-td:break-words prose-th:break-words prose-a:break-all prose-code:break-words prose-blockquote:break-words";function Tw(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}function af(e){const t=e.find(r=>r.type==="tool_call"),n=e.find(r=>r.type==="tool_end");return{name:t==null?void 0:t.name,toolCallId:(n==null?void 0:n.toolCallId)??(t==null?void 0:t.id)}}function Ls(e){if(e==null)return null;const t=String(e).trim();return t.length>0?t:null}function Ew(e){const t=o=>{try{const s=xo(o);return typeof s=="string"?s:JSON.stringify(s??"")}catch{return""}},n=e.filter(o=>o.type==="tool_end");let r="";if(n.length)try{n.length===1?r=t(n[0].output):r=t(n.map(o=>({toolCallId:o.toolCallId,output:o.output})))}catch{r=""}else r=t(e);return r||""}function Iw(e){return e.name&&e.name.trim()?e.name:e.model&&e.model.includes("/")?e.model.split("/").pop()||null:e.model||null}function lf(e){if("type"in e&&e.type==="default_message")return`default:${e.content.length}`;const t=e.updatedAt??e.createdAt??"",n=Array.isArray(e.content)?e.content.map(r=>{switch(r.type){case"text":return`t:${r.text.length}`;case"image_url":return"img";case"file":return"file";case"tool_call":return"call";case"tool_end":return"end";default:return"unknown"}}).join("|"):"";return`${e.id}:${t}:${n}`}function Aw({className:e}){const[t,n]=w.useState(0);return w.useEffect(()=>{const r=setInterval(()=>n(o=>(o+1)%4),500);return()=>clearInterval(r)},[]),u.jsxs("span",{"aria-live":"polite",className:ee("inline-block text-xs opacity-70 ml-1",e),children:["Is thinking",".".repeat(t)]})}const Ma=w.memo(function({message:t,messageIndex:n,isStreamingMessage:r=!1,isEditing:o=!1,showActions:s=!0,showTimestamp:i=!0,showAgentName:a=!0,layoutSize:l="desktop",truncateUserMessages:c=!0,userMessagePreviewLength:d=200,showToolMessages:f=!0,customStyles:h={},onEdit:p,onRegenerate:g,onCancelEdit:y,onCopy:v,activeInterrupt:x,disableInterruptActions:b=!1,onInterruptActionStart:S,onInterruptActionEnd:T}){const[k,C]=w.useState(!1),[E,_]=w.useState("preview"),[j,D]=w.useState(!1),{currentThreadId:$}=Yo(),{respondToInterrupt:K}=Xo(),P=l==="phone"||l==="half-screen",R=t.role,L=R==="tool",F=w.useMemo(()=>"type"in t&&t.type==="default_message"?t:null,[t]),ne=!!F,q=!(r&&R!=="user"),{uploadingFiles:B,handleFileClick:pe,fileViewerOpen:W,currentFileInfo:ce,closeFileViewer:H}=_w({allowFileOpen:q,currentThreadId:$}),Z=w.useMemo(()=>{switch(R){case"user":return"text-[hsl(var(--chat-bubble-user-text))]";case"assistant":return"text-[hsl(var(--chat-bubble-ai-text))]";case"tool":return"text-secondary-foreground";case"system":return"text-muted-foreground";default:return"text-[hsl(var(--chat-bubble-ai-text))]"}},[R]),be=w.useMemo(()=>F?"":Tw(t.content),[F,t]),ye=w.useMemo(()=>F?{}:af(t.content),[F,t]),G=w.useMemo(()=>F?[]:t.content.filter(ie=>ie.type==="image_url"),[F,t]),M=w.useMemo(()=>F?[]:t.content.filter(ie=>ie.type==="file"),[F,t]),X=w.useMemo(()=>F?[]:t.content.filter(ie=>ie.type==="interrupt"),[F,t]),oe=(x==null?void 0:x.id)??(x==null?void 0:x.interrupt_id),xe=Ls(oe),se=x==null?void 0:x.value,re=w.useMemo(()=>F?"":Ew(t.content),[F,t]),Ue=w.useCallback(async()=>{const ie=L?re:be;async function je(ke){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(ke);return}if(navigator.clipboard&&typeof navigator.clipboard.write=="function"&&typeof ClipboardItem<"u"){const Ke=new Blob([ke],{type:"text/plain"});await navigator.clipboard.write([new ClipboardItem({"text/plain":Ke})]);return}throw new Error("Clipboard API not supported in this context.")}try{await je(ie),C(!0),setTimeout(()=>C(!1),2e3),v==null||v(ie)}catch(ke){console.error("Failed to copy:",ke)}},[L,re,be,v]),qe=w.useCallback(()=>{if(!p)return;const ie=L?re:be;p(t.id,ie)},[p,t.id,L,re,be]),ot=w.useCallback(()=>{g==null||g(n)},[g,n]),at=w.useCallback(()=>{const je=ee(P?"h-3 w-3":"h-4 w-4","opacity-60 flex-shrink-0",Z);switch(R){case"user":return u.jsx(fe.User,{className:je});case"assistant":return u.jsx(fe.Bot,{className:je});case"tool":return u.jsx(fe.Wrench,{className:je});default:return u.jsx(fe.Bot,{className:je})}},[P,Z,R]),ht=w.useCallback(()=>{const ie="group relative mb-4 flex w-full";switch(R){case"user":return ee(ie,"justify-end");case"assistant":case"tool":case"system":return ee(ie,"justify-start");default:return ie}},[R]),tt=w.useCallback(()=>{const ie=ee("rounded-lg px-4 py-3 relative min-w-0 max-w-full break-words",P&&"px-3 py-2 text-sm");if(ne)return ee(ie,"w-full","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40 shadow-sm");switch(R){case"user":return ee(ie,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-user))] text-[hsl(var(--chat-bubble-user-text))]","border border-transparent");case"assistant":return ee(ie,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40");case"tool":return ee(ie,"w-full md:max-w-[95%] bg-secondary/50 text-secondary-foreground border border-dashed");case"system":return ee(ie,"w-full md:max-w-[85%] bg-accent/40 text-muted-foreground border");default:return ee(ie,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40")}},[P,ne,R]);if(ne&&F)return u.jsx("div",{className:ee(ht(),h.container),children:u.jsxs("div",{className:ee(tt(),h.content),children:[u.jsxs("div",{className:"flex items-center gap-2 mb-2 pb-2 border-b border-current/10",children:[u.jsx(fe.Bot,{className:ee("h-4 w-4",Z)}),a&&u.jsx("span",{className:"font-medium text-sm",children:"Assistant"})]}),u.jsx(Ds,{content:F.content,className:"text-current"})]})});const Me=w.useCallback(async ie=>{if(b)return;const je=Ls((ie==null?void 0:ie.id)??(ie==null?void 0:ie.interrupt_id));if(!je){console.warn("Interrupt part missing id",ie);return}try{S==null||S(),await K(je,!0)}catch(ke){console.error("Failed to approve interrupt:",ke)}finally{T==null||T()}},[b,T,S,K]),We=w.useCallback(async ie=>{if(b)return;const je=Ls((ie==null?void 0:ie.id)??(ie==null?void 0:ie.interrupt_id));if(!je){console.warn("Interrupt part missing id",ie);return}try{S==null||S(),await K(je,!1)}catch(ke){console.error("Failed to reject interrupt:",ke)}finally{T==null||T()}},[b,T,S,K]),lt=w.useCallback(({part:ie,i:je})=>{if(ie.type==="text"){const ke=ie.text??"",Ke=ke.trim(),nt=Qu(Ke);return nt&&R!=="tool"?u.jsx(cf,{data:nt},je):R==="user"&&c&&Ke.length>d?u.jsx(jw,{text:Ke,expanded:j,onExpandedChange:D,previewLength:d,isCompact:P},je):u.jsx(Ds,{content:ke,allowHtml:!1},je)}if(ie.type==="image_url"){const ke=ie;return u.jsx("div",{className:"my-2",children:u.jsx("img",{src:ke.url,alt:ke.alt??"",loading:"lazy",className:"border rounded max-h-[420px] w-auto object-contain"})},je)}if(ie.type==="file"){const ke=ie,Ke=ke.name||"file";return u.jsxs("a",{href:ke.url,onClick:nt=>pe(nt,ke,je),className:`inline-flex items-center gap-2 rounded px-2 py-1 text-xs bg-gray-100 border hover:bg-gray-200
128
+ dark:bg-background/10 dark:border-border/30 dark:hover:bg-background/20`,children:[B[je]?u.jsx(fe.Loader,{className:"h-4 w-4 animate-spin"}):null,u.jsxs("span",{className:"truncate max-w-[180px]",children:[Ke,B[je]?" (processing)":""]})]},je)}if(ie.type==="interrupt"){const ke=ie,Ke=Ls((ke==null?void 0:ke.id)??(ke==null?void 0:ke.interrupt_id)),nt=!!(xe&&Ke&&Ke===xe),Oe=nt?se??(ke==null?void 0:ke.value):ke==null?void 0:ke.value,Xe=Ke?{...ke,id:Ke,interrupt_id:Ke}:ke;return u.jsx(Nw,{interruptPart:Xe,onApprove:Me,onReject:We,disabled:b,isActive:nt,payload:Oe},je)}return null},[pe,B,Me,We,R,c,d,j,P,xe,se,x,b,X]),yt=w.useCallback(()=>u.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted/30 rounded",children:[u.jsx(fe.Paperclip,{className:"h-4 w-4 text-muted-foreground"}),u.jsx("span",{className:"text-sm text-muted-foreground",children:"File upload"})]}),[]),dt=w.useCallback(()=>{const ie=be.trim().length>0||G.length>0||M.length>0||X.length>0;if(!L&&M.length>0&&!r)return yt();if(!L&&!ie&&!r)return null;if(L)return u.jsx(Rw,{message:t,viewMode:E},t.id);if(!L&&!F){const je=t,ke=u.jsx("div",{className:"space-y-2",children:je.content.map((Ke,nt)=>u.jsx(lt,{part:Ke,i:nt},nt))});return r?u.jsxs("div",{"aria-busy":"true",role:"status",children:[ke,u.jsx(Aw,{className:Z})]}):ke}},[be,G.length,M.length,X.length,r,L,E,yt,Z]),Je=w.useMemo(()=>F?"Assistant":Iw(t),[F,t]);return L&&!f?null:u.jsxs(u.Fragment,{children:[u.jsx("div",{className:ee(ht(),h.container),children:u.jsxs("div",{className:ee(tt(),h.content),children:[(i||a||L)&&u.jsxs("div",{className:ee("flex items-center justify-between mb-2 pb-2 border-b border-current/10",P&&"mb-1 pb-1",Z,h.header),children:[u.jsxs("div",{className:"flex items-center gap-2",children:[at(),a&&Je&&u.jsx("span",{className:ee("font-medium",P?"text-xs":"text-sm"),children:Je}),L&&u.jsxs(Hu,{variant:"outline",className:ee("text-xs flex items-center gap-1 cursor-pointer select-none",Z,"border border-current/40",P&&"text-xs h-4"),role:"button",tabIndex:0,"aria-expanded":E==="expanded",onClick:()=>_(ie=>ie==="expanded"?"preview":"expanded"),onKeyDown:ie=>{(ie.key==="Enter"||ie.key===" ")&&(ie.preventDefault(),_(je=>je==="expanded"?"preview":"expanded"))},children:[u.jsx("span",{children:ye.name??"Tool Output"}),ye.toolCallId&&u.jsx("span",{className:"opacity-70",children:ye.toolCallId.slice(0,8)}),E==="expanded"?u.jsx(fe.ChevronUp,{className:"h-3 w-3"}):u.jsx(fe.ChevronDown,{className:"h-3 w-3"})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[i&&t.createdAt&&u.jsx("time",{className:ee("text-xs opacity-60",Z,P&&"text-xs"),dateTime:new Date(t.createdAt).toISOString(),title:new Date(t.createdAt).toLocaleString(),children:new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(new Date(t.createdAt))}),s&&!o&&u.jsxs("div",{className:ee("opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",h.actions),children:[u.jsx("div",{className:"relative",children:u.jsx(Ze,{variant:"ghost",size:"sm",onClick:()=>Ue(),className:ee("h-6 w-6 p-0 hover:bg-foreground/10",Z,P&&"h-5 w-5"),"aria-label":"Copy message",title:"Copy message",children:u.jsx(fe.Copy,{className:ee(k?"text-success":Z,P?"h-3 w-3":"h-4 w-4")})})}),R==="user"&&p&&u.jsx(Ze,{variant:"ghost",size:"sm",onClick:qe,className:ee("h-6 w-6 p-0 hover:bg-foreground/10",Z,P&&"h-5 w-5"),"aria-label":"Edit message",children:u.jsx(fe.Edit,{className:ee(Z,P?"h-3 w-3":"h-4 w-4")})}),R==="assistant"&&g&&u.jsx(Ze,{variant:"ghost",size:"sm",onClick:ot,className:ee("h-6 w-6 p-0 hover:bg-foreground/10",Z,P&&"h-5 w-5"),"aria-label":"Regenerate response",children:u.jsx(fe.RotateCcw,{className:ee(Z,P?"h-3 w-3":"h-4 w-4")})})]})]})]}),u.jsx("div",{className:"relative",children:dt()}),L&&E==="expanded"&&(ye.toolCallId||ye.name)&&u.jsxs("div",{className:ee("mt-2 pt-2 border-t border-current/10 text-xs opacity-60",P&&"text-xs"),children:[ye.name&&u.jsxs("div",{children:["Function: ",ye.name]}),ye.toolCallId&&u.jsxs("div",{children:["Call ID: ",ye.toolCallId]})]}),!(i||a||L)&&s&&!o&&u.jsxs("div",{className:ee("absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",h.actions),children:[u.jsx(Ze,{variant:"ghost",size:"sm",onClick:()=>Ue(),className:ee("h-6 w-6 p-0 hover:bg-background/50 text-current",P&&"h-5 w-5"),children:u.jsx(fe.Copy,{className:ee(k?"text-success":"text-current",P?"h-3 w-3":"h-4 w-4")})}),R==="user"&&p&&u.jsx(Ze,{variant:"ghost",size:"sm",onClick:qe,className:ee("h-6 w-6 p-0 hover:bg-background/50 text-current",P&&"h-5 w-5"),children:u.jsx(fe.Edit,{className:ee("text-current",P?"h-3 w-3":"h-4 w-4")})}),R==="assistant"&&g&&u.jsx(Ze,{variant:"ghost",size:"sm",onClick:ot,className:ee("h-6 w-6 p-0 hover:bg-background/50 text-current",P&&"h-5 w-5"),children:u.jsx(fe.RotateCcw,{className:ee("text-current",P?"h-3 w-3":"h-4 w-4")})})]})]})}),ce&&u.jsx(iw,{isOpen:W,onClose:H,fileId:ce.id,fileName:ce.name,mimeType:ce.mimeType})]})},(e,t)=>{var i,a,l,c,d,f,h,p;if(t.isStreamingMessage||e.isStreamingMessage||!(e.message.id===t.message.id&&lf(e.message)===lf(t.message)))return!1;const o=["isEditing","showActions","layoutSize","showTimestamp","showAgentName","truncateUserMessages","userMessagePreviewLength","showToolMessages"].every(g=>e[g]===t[g]),s=((i=e.customStyles)==null?void 0:i.container)===((a=t.customStyles)==null?void 0:a.container)&&((l=e.customStyles)==null?void 0:l.content)===((c=t.customStyles)==null?void 0:c.content)&&((d=e.customStyles)==null?void 0:d.actions)===((f=t.customStyles)==null?void 0:f.actions)&&((h=e.customStyles)==null?void 0:h.header)===((p=t.customStyles)==null?void 0:p.header);return o&&s});function cf({data:e}){return Array.isArray(e)?e.every(n=>n===null||["string","number","boolean"].includes(typeof n))?u.jsx("div",{className:kw,children:u.jsx("ul",{className:"list-disc pl-5",children:e.map((n,r)=>u.jsx("li",{children:String(n)},r))})}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:ms(e)}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:ms(e)})}function Nw({interruptPart:e,onApprove:t,onReject:n,disabled:r,isActive:o,payload:s}){const i=e.title??"Approve the result?";let a=null;if(s!=null)if(typeof s=="string")a=u.jsx("p",{className:"text-sm leading-relaxed text-blue-800/90 dark:text-blue-200/90 whitespace-pre-wrap",children:s});else{const c=ms(s);a=u.jsx("pre",{className:"max-h-48 overflow-auto rounded bg-blue-100/60 p-2 text-xs text-blue-900/90 dark:bg-blue-900/40 dark:text-blue-100/80",children:c})}const l=o?"Please approve or reject this action to resume the workflow.":"Waiting for approval from another participant.";return u.jsxs(fo,{className:ee("border-blue-200 dark:border-blue-800 bg-blue-50/50 dark:bg-blue-950/10 transition-shadow",o?"shadow-md ring-1 ring-blue-300 dark:ring-blue-500/70":"opacity-80"),children:[u.jsxs(ho,{className:"pb-3",children:[u.jsx(po,{className:"text-blue-900 dark:text-blue-100 text-base",children:i}),u.jsx(Uu,{className:"text-blue-700 dark:text-blue-300 text-sm",children:l})]}),a&&u.jsx(mo,{className:"pt-0 pb-3",children:a}),u.jsx(Wu,{className:"pt-0",children:u.jsxs("div",{className:"flex gap-2 ml-auto",children:[u.jsx(Ze,{size:"sm",variant:"outline",onClick:()=>n(e),className:"border-red-300 text-red-700 hover:bg-red-50 dark:border-red-700 dark:text-red-300 dark:hover:bg-red-950/50",disabled:r||!o,children:"Reject"}),u.jsx(Ze,{size:"sm",onClick:()=>t(e),className:"bg-blue-600 hover:bg-blue-700 text-white",disabled:r||!o,children:"Approve"})]})})]})}function _w(e){const{allowFileOpen:t,currentThreadId:n}=e,{toast:r}=ya(),[o,s]=w.useState({}),[i,a]=w.useState(null),[l,c]=w.useState(!1),d=w.useCallback(()=>{c(!1),a(null)},[]),f=w.useCallback(p=>{a(p),c(!0)},[]),h=w.useCallback(async(p,g,y)=>{var v,x;if(!t){p.preventDefault();return}if(o[y]){p.preventDefault();return}try{const b=String(g.url??""),S=b.match(/\/chat\/files\/([^/]+)(?:\/(view|download))?/);if(S){p.preventDefault();const T=S[1],k=g.name||`file_${T}`,C=g.mimeType||"application/octet-stream";f({id:T,name:k,mimeType:C});return}if(b.startsWith("data:")){p.preventDefault(),s(k=>({...k,[y]:!0}));const T=r({title:"Fetching file...",description:"",open:!0});try{const k=await Vv(n??void 0);if(!k||!Array.isArray(k))throw new Error("Invalid file list response");const C=k.find(E=>!E||typeof E!="object"||!((E.filename??"")===(g.name??""))?!1:typeof g.size=="number"&&typeof E.size=="number"?E.size===g.size:!0);if(!(C!=null&&C.id))throw new Error(`File "${g.name}" is not yet available on the server`);if(!C.id||!C.filename)throw new Error("Invalid file data received from server");f({id:C.id,name:g.name||C.filename||`file_${C.id}`,mimeType:g.mimeType||C.mime_type||"application/octet-stream"}),(v=T.update)==null||v.call(T,{id:T.id,title:"Success",description:`Opened ${g.name}`,open:!0})}catch(k){console.error("Failed to fetch server file:",k);const C=k instanceof Error?k.message:"Unknown error occurred";(x=T.update)==null||x.call(T,{id:T.id,title:"Failed",description:C}),r({title:"Failed to fetch file",description:C,open:!0})}finally{s(k=>({...k,[y]:!1}))}}}catch(b){console.error("File click error:",b),s(S=>({...S,[y]:!1}))}},[t,o,r,n,f]);return{uploadingFiles:o,handleFileClick:h,fileViewerOpen:l,currentFileInfo:i,closeFileViewer:d}}function jw({text:e,expanded:t,onExpandedChange:n,previewLength:r,isCompact:o}){return u.jsxs(Lv,{open:t,onOpenChange:n,children:[u.jsx("div",{className:ee("text-sm text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:t?u.jsx(Ds,{content:e,allowHtml:!1}):u.jsxs("pre",{className:ee("font-sans whitespace-pre-wrap break-words bg-transparent p-0 m-0 text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:[e.substring(0,r),"..."]})}),u.jsx(Fv,{asChild:!0,children:u.jsx(Ze,{variant:"ghost",size:"sm",className:"h-6 text-xs !text-[hsl(var(--chat-bubble-user-text))]",children:t?u.jsxs(u.Fragment,{children:[u.jsx(fe.ChevronUp,{className:"h-3 w-3 mr-1"})," Show less"]}):u.jsxs(u.Fragment,{children:[u.jsx(fe.ChevronDown,{className:"h-3 w-3 mr-1"})," Show more (",e.length-r," chars)"]})})})]})}function Rw({message:e,viewMode:t}){const r=af(e.content).name||"tool",o=a=>{if(a==null)return null;const l=typeof a=="string"?Qu(a)??a:a;if(l&&typeof l=="object")return u.jsx(cf,{data:l});const c=typeof l=="string"?l:(()=>{try{return ms(l)}catch{return String(l??"")}})();return u.jsx("pre",{className:"whitespace-pre-wrap break-words font-sans text-sm text-foreground/90",children:c})};if(t==="preview")return null;const s=e.content.find(a=>a.type!=="tool_call");if(!s)return u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(fe.Loader,{className:"h-4 w-4 animate-spin"}),u.jsxs("span",{children:["Waiting for ",r," output…"]})]});if(s.type==="text"){const l=(s.text??"").trim();return l?o(l):null}const i=xo(s);return o(i)}const uf=(e,t)=>(e==null?void 0:e.id)??`message-${t}`,Da=w.forwardRef(({messages:e,isStreaming:t,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onStartReached:a,onEdit:l,onRegenerate:c,onCancelEdit:d,className:f,style:h,emptyMessage:p,followNewMessages:g=!0,isNavigatingCheckpoint:y=!1,onScrollAway:v,onAtBottom:x,activeInterrupt:b,disableInterruptActions:S=!1,onInterruptActionStart:T,onInterruptActionEnd:k,showToolMessages:C=!0},E)=>{const _=w.useRef(null),j=w.useRef(null),D=w.useRef(!1),[$,K]=w.useState(!0),P=w.useMemo(()=>b?e.some(W=>"type"in W&&W.type==="default_message"?!1:Array.isArray(W==null?void 0:W.content)&&W.content.some(ce=>ce&&ce.type==="interrupt"&&(ce.id??ce.interrupt_id)===b.id)):!1,[b,e]),R=w.useMemo(()=>{if(!b||P)return null;const W=b.id&&String(b.id).trim()?String(b.id).trim():"pending-interrupt";let ce;const H=b.value;if(H&&typeof H=="object"&&!Array.isArray(H)){const Z=H.title;typeof Z=="string"&&Z.trim()&&(ce=Z.trim())}return{id:`interrupt-${W}`,role:"system",createdAt:new Date().toISOString(),content:[{type:"interrupt",id:W,value:H,title:ce}]}},[b,P]),L=w.useMemo(()=>R?[...e,R]:e,[e,R]),F=w.useMemo(()=>C?L:L.filter(W=>(W==null?void 0:W.role)!=="tool"),[L,C]),ne=w.useCallback(W=>{K(W),v&&v(!W),x&&x(W)},[v,x]),q=w.useMemo(()=>{if(a)return async()=>{if(!D.current){D.current=!0;try{await a()}finally{D.current=!1}}}},[a]),B=w.useMemo(()=>!g||y?!1:$?"auto":!1,[$,g,y]),pe=w.useMemo(()=>{if(typeof p!="string")return null;const W=p.trim();return W?{id:"default-message",role:"assistant",type:"default_message",content:W,createdAt:new Date().toISOString()}:null},[p]);return F.length===0?pe?u.jsx("div",{className:f,style:h,children:u.jsx("div",{className:"p-6 overflow-y-auto h-full flex items-start justify-center",children:u.jsx("div",{className:"w-full max-w-full",children:u.jsx(Ma,{message:pe,messageIndex:0,isStreamingMessage:!1,showActions:!1,showTimestamp:!1,showAgentName:!0,layoutSize:o,onEdit:()=>{},onRegenerate:()=>{},onCancelEdit:()=>{}})})})}):u.jsx("div",{className:f,style:h,children:u.jsx("div",{className:"flex items-center justify-center py-8 text-muted-foreground text-center max-w-2xl mx-auto",children:p||"No messages yet. Start a conversation!"})}):u.jsx("div",{className:f,style:h,children:u.jsx(sv,{ref:W=>{_.current=W},scrollerRef:W=>{j.current=W instanceof HTMLDivElement?W:null},data:F,followOutput:B,overscan:200,increaseViewportBy:{top:100,bottom:200},defaultItemHeight:80,atBottomThreshold:50,alignToBottom:!1,startReached:()=>{q&&q()},atBottomStateChange:ne,style:{height:"100%",overscrollBehavior:"contain"},computeItemKey:(W,ce)=>uf(ce,W),itemContent:(W,ce)=>{const H=uf(ce,W);return u.jsx("div",{className:"mb-4 last:mb-0","data-message-id":H,style:{minHeight:"60px",containIntrinsicSize:"auto 120px"},children:u.jsx(Ma,{message:ce,messageIndex:W,isStreamingMessage:t&&n===ce.id,streamingDebounceMs:r,isEditing:i===ce.id,showActions:s,showTimestamp:!1,showAgentName:!0,layoutSize:o,onEdit:l,onRegenerate:()=>c(W),onCancelEdit:d,activeInterrupt:b,disableInterruptActions:S,onInterruptActionStart:T,onInterruptActionEnd:k,showToolMessages:C})})}})})});Da.displayName="MessageList";const Fs=1e4;function Pw(e){if(typeof e!="string")return String(e);const t=[/<script[^>]*>.*?<\/script>/gi,/<iframe[^>]*>.*?<\/iframe>/gi,/javascript:/gi,/vbscript:/gi,/on\w+\s*=/gi,/<object[^>]*>.*?<\/object>/gi,/<embed[^>]*>.*?<\/embed>/gi,/<form[^>]*>.*?<\/form>/gi];let n=e;for(const o of t)n=n.replace(o,"");return/<[^>]+>/.test(n)&&!/<(?!\/?(?:code|strong|em|b|i|br|p|ul|ol|li|h[1-6])\b)[^>]+>/i.test(n)?n.replace(/<code>(.*?)<\/code>/gi,"`$1`").replace(/<strong>(.*?)<\/strong>/gi,"**$1**").replace(/<b>(.*?)<\/b>/gi,"**$1**").replace(/<em>(.*?)<\/em>/gi,"*$1*").replace(/<i>(.*?)<\/i>/gi,"*$1*").replace(/<br\s*\/?>/gi,`
129
129
  `).replace(/<p>(.*?)<\/p>/gi,`$1
130
130
 
131
131
  `).replace(/<h([1-6])>(.*?)<\/h[1-6]>/gi,(o,s,i)=>`${"#".repeat(parseInt(s))} ${i}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "teodor-new-chat-ui",
3
- "version": "4.3.85",
3
+ "version": "4.3.87",
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",