opencami 1.8.8 → 1.8.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/client/assets/{CSPContext-nHSyQniZ.js → CSPContext-DI-5GAnQ.js} +1 -1
  2. package/dist/client/assets/{DirectionContext-B1cuzwIr.js → DirectionContext-CrIsc5n9.js} +1 -1
  3. package/dist/client/assets/_sessionKey-B4NZmxf3.js +21 -0
  4. package/dist/client/assets/agents-bptidK8z.js +2 -0
  5. package/dist/client/assets/{agents-screen-DpNSh5Ok.js → agents-screen-6qdnPmx2.js} +1 -1
  6. package/dist/client/assets/bots-BWpbaQ-E.js +2 -0
  7. package/dist/client/assets/{bots-screen-Qh_IK9hC.js → bots-screen-BTKCOohV.js} +1 -1
  8. package/dist/client/assets/{button-DdG8c-XQ.js → button-8ab4wOwy.js} +1 -1
  9. package/dist/client/assets/{composite-Cx-QHT9o.js → composite-B2qsrzf3.js} +1 -1
  10. package/dist/client/assets/{connect-CSbeSBTn.js → connect-B3_p7C4I.js} +1 -1
  11. package/dist/client/assets/dashboard-BtClHYpn.js +1 -0
  12. package/dist/client/assets/{event-Dwf9IDxK.js → event-DG3RKJz8.js} +1 -1
  13. package/dist/client/assets/{file-explorer-screen-DzDX4HcB.js → file-explorer-screen-Djl8x-8P.js} +1 -1
  14. package/dist/client/assets/files-CjbCJDgC.js +2 -0
  15. package/dist/client/assets/{follow-up-suggestions-BYWq-d8P.js → follow-up-suggestions-BSCMXRXh.js} +1 -1
  16. package/dist/client/assets/{index-BxsgifDH.js → index-BXiha-Vz.js} +1 -1
  17. package/dist/client/assets/{index-B551ln24.js → index-CtlYu8Ug.js} +1 -1
  18. package/dist/client/assets/{keyboard-shortcuts-dialog-BX-hH4Wf.js → keyboard-shortcuts-dialog-HAufCn9C.js} +1 -1
  19. package/dist/client/assets/{main-DBmooBKx.js → main-CQKtcNr3.js} +2 -2
  20. package/dist/client/assets/{markdown-Bpat4kTr.js → markdown-DFJF-FsV.js} +1 -1
  21. package/dist/client/assets/memory-DnJOmcwU.js +2 -0
  22. package/dist/client/assets/{memory-screen-1DgDLyZf.js → memory-screen-Bm4NMAnU.js} +1 -1
  23. package/dist/client/assets/{menu-ByR1BVmq.js → menu-D26Vmgxl.js} +1 -1
  24. package/dist/client/assets/{opencami-logo-BV1uPYe6.js → opencami-logo-BSed2Wez.js} +1 -1
  25. package/dist/client/assets/{popupStateMapping-CGDLUl5Y.js → popupStateMapping-DkI2OCkW.js} +1 -1
  26. package/dist/client/assets/{proxy-DYrSkM35.js → proxy-CHQ-VCN1.js} +1 -1
  27. package/dist/client/assets/{react-dSDkXQu6.js → react-WkSlhZJd.js} +1 -1
  28. package/dist/client/assets/{search-dialog-B3XJLq-O.js → search-dialog-CCl4d0Pi.js} +1 -1
  29. package/dist/client/assets/{search-sources-badge-CTd0gLuz.js → search-sources-badge-Du8KpUEb.js} +1 -1
  30. package/dist/client/assets/{session-export-dialog-Cib97JLm.js → session-export-dialog-io9FvLKq.js} +1 -1
  31. package/dist/client/assets/{settings-dialog-B4NLq1ZS.js → settings-dialog-B93qswor.js} +1 -1
  32. package/dist/client/assets/skills-BNDGnHwM.js +2 -0
  33. package/dist/client/assets/{skills-panel-Cj7yHGbX.js → skills-panel-CVh1I-7D.js} +1 -1
  34. package/dist/client/assets/{switch-kXs1I0oW.js → switch-CSnzINDW.js} +1 -1
  35. package/dist/client/assets/{tabs-B6GW7TBf.js → tabs-CWfn44FL.js} +1 -1
  36. package/dist/client/assets/{thinking-DTP9JDQl.js → thinking-BmoLlbFC.js} +1 -1
  37. package/dist/client/assets/{tooltip-CtHpm-sQ.js → tooltip-CSGMH2t4.js} +1 -1
  38. package/dist/client/assets/{use-file-explorer-state-C-D2CShe.js → use-file-explorer-state-BYVzjwPA.js} +1 -1
  39. package/dist/client/assets/{useBaseUiId-Ckx_aJky.js → useBaseUiId-DiwX_3so.js} +1 -1
  40. package/dist/client/assets/{useCompositeItem-CkvfeGmG.js → useCompositeItem-UPIPwR9H.js} +1 -1
  41. package/dist/client/assets/{useControlled-8D4PSDAL.js → useControlled-CT2hRlcU.js} +1 -1
  42. package/dist/client/assets/{useMutation-DckvFKPC.js → useMutation-rx8UH99I.js} +1 -1
  43. package/dist/client/assets/{useQuery-CtUiG53w.js → useQuery-Boaa6oF3.js} +1 -1
  44. package/dist/server/assets/{_sessionKey-LV6xK9IM.js → _sessionKey-B6iYeyCS.js} +342 -257
  45. package/dist/server/assets/{_tanstack-start-manifest_v-qVhiIEVc.js → _tanstack-start-manifest_v-C9chPgNH.js} +1 -1
  46. package/dist/server/assets/{dashboard-GCKodTiJ.js → dashboard-UYRCu_mQ.js} +19 -3
  47. package/dist/server/assets/{follow-up-suggestions-CSSc4PDe.js → follow-up-suggestions-mzRQIB0k.js} +2 -2
  48. package/dist/server/assets/{index-DMKS4aeI.js → index-COElhwGA.js} +1 -1
  49. package/dist/server/assets/{router-Cr2xCvGA.js → router-BqLGFd4L.js} +3 -3
  50. package/dist/server/assets/{search-dialog-DR6zBnui.js → search-dialog-CmI7naPN.js} +2 -2
  51. package/dist/server/assets/{settings-dialog-DEMlCMCP.js → settings-dialog-BZ67gr9N.js} +2 -2
  52. package/dist/server/assets/{thinking-BpAc3itF.js → thinking-CA8PSwKJ.js} +2 -2
  53. package/dist/server/server.js +2 -2
  54. package/package.json +2 -2
  55. package/dist/client/assets/_sessionKey-CNw4O2rY.js +0 -19
  56. package/dist/client/assets/agents-C6Ev94B1.js +0 -2
  57. package/dist/client/assets/bots-B2_u-OmP.js +0 -2
  58. package/dist/client/assets/dashboard-DA1fTRcH.js +0 -1
  59. package/dist/client/assets/files-PsZnGOUx.js +0 -2
  60. package/dist/client/assets/memory-Bs8hOoEv.js +0 -2
  61. package/dist/client/assets/skills-pueagQNc.js +0 -2
@@ -1,19 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/settings-dialog-B4NLq1ZS.js","assets/main-DBmooBKx.js","assets/react-dSDkXQu6.js","assets/button-DdG8c-XQ.js","assets/use-file-explorer-state-C-D2CShe.js","assets/useBaseUiId-Ckx_aJky.js","assets/event-Dwf9IDxK.js","assets/popupStateMapping-CGDLUl5Y.js","assets/visuallyHidden-COI6QeQH.js","assets/composite-Cx-QHT9o.js","assets/switch-kXs1I0oW.js","assets/useControlled-8D4PSDAL.js","assets/tabs-B6GW7TBf.js","assets/useCompositeItem-CkvfeGmG.js","assets/DirectionContext-B1cuzwIr.js","assets/CSPContext-nHSyQniZ.js","assets/index-BxsgifDH.js","assets/useQuery-CtUiG53w.js","assets/tooltip-CtHpm-sQ.js","assets/useMutation-DckvFKPC.js","assets/menu-ByR1BVmq.js","assets/opencami-logo-BV1uPYe6.js","assets/proxy-DYrSkM35.js","assets/markdown-Bpat4kTr.js","assets/index-T4TOjvD0.js","assets/session-export-dialog-Cib97JLm.js","assets/thinking-DTP9JDQl.js","assets/search-sources-badge-CTd0gLuz.js","assets/follow-up-suggestions-BYWq-d8P.js","assets/keyboard-shortcuts-dialog-BX-hH4Wf.js","assets/search-dialog-B3XJLq-O.js"])))=>i.map(i=>d[i]);
2
- import{r as s,u as mt,j as n,L as Xe,_ as et,d as Pt,w as Br,a as Yr,z as Gr}from"./main-DBmooBKx.js";import{u as Mt}from"./useQuery-CtUiG53w.js";import{T as Ie,a as Me,b as Ae,c as De,s as Be,d as Vr,g as jn}from"./tooltip-CtHpm-sQ.js";import{C as qr,c as O,B as we,ac as ln,ag as qe,E as Jr,H as Z,J as Gn,V as _t,aj as Qr,ak as Zr,al as es,a as Vn,am as ts,G as ns,an as rs,l as ss,b as Je,I as os,ao as is,a3 as as,s as qt,ap as ls,L as cs,aq as us,A as ds,N as fs,Q as ms,X as qn,x as ps,h as hs,ar as Jn,as as gs,p as ys,T as Qn,u as Zn,at as kn,au as xs,av as ws,aw as bs}from"./button-DdG8c-XQ.js";import{u as er}from"./useMutation-DckvFKPC.js";import{j as Ss,k as vs,l as js,m as ks,n as Es,o as Cs,p as Ns,q as Ts,r as Rs,s as tr,D as Is,a as Ms,b as As,c as Ds,d as Os,u as Ls}from"./use-file-explorer-state-C-D2CShe.js";import{d as nr,a as Ge,g as rr,t as Ps,u as Oe,f as _s,n as Ks}from"./useBaseUiId-Ckx_aJky.js";import{u as zs}from"./useControlled-8D4PSDAL.js";import{_ as Us,$ as $s,a0 as En,t as sr,u as Hs,G as Ce,e as Fs,a as At}from"./popupStateMapping-CGDLUl5Y.js";import{u as Ws,e as Xs,q as Bs}from"./event-Dwf9IDxK.js";import{u as Ys}from"./CSPContext-nHSyQniZ.js";import{u as or}from"./DirectionContext-B1cuzwIr.js";import{M as cn,a as un,b as dn,c as Ze}from"./menu-ByR1BVmq.js";import{O as Gs,a as Vs}from"./opencami-logo-BV1uPYe6.js";import{m as be,A as Re}from"./proxy-DYrSkM35.js";import{M as qs}from"./markdown-Bpat4kTr.js";import{u as Js,p as ir}from"./index-BxsgifDH.js";import{c as ar}from"./react-dSDkXQu6.js";function Jt(e){if(!e)return"main";const t=e.trim();if(t.length===0)return"main";const r=t.split(":"),a=(r[r.length-1]??"").trim();return a.length>0?a:t}const Cn=/^Conversation info \(untrusted metadata\):\s*```(?:json)?\s*[\s\S]*?```\s*/,Nn=/^Conversation info \(untrusted metadata\):\s*\{[\s\S]*?\}\s*/,Qs=/^\[(?:[A-Za-z]{3}\s+)?\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}\s+GMT[+-]?\d+\]\s*/;function lr(e){let t=e;const r=Cn.test(t),o=!r&&Nn.test(t);return r?t=t.replace(Cn,""):o&&(t=t.replace(Nn,"")),(r||o)&&(t=t.replace(Qs,"")),t.trim()}function Le(e){const r=(Array.isArray(e.content)?e.content:[]).map(o=>o.type==="text"?String(o.text??""):"").join("").trim();return lr(r)}function Ye(e){return(Array.isArray(e.content)?e.content:[]).filter(r=>r.type==="toolCall")}function Zs(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e12?e*1e3:e;if(typeof e=="string"){const t=Date.parse(e);if(!Number.isNaN(t))return t}return null}function Qt(e){const t=[e.createdAt,e.created_at,e.timestamp,e.time,e.ts];for(const r of t){const o=Zs(r);if(o)return o}return Date.now()}const eo=["agent:main:main","main"];function Zt(e){return eo.includes(e)}const to=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function no(e){if(e.includes(":subagent:")||e.startsWith("agent:codex:")||e.includes(":openai:"))return"subagent";if(e.startsWith("isolated:")||e.includes(":cron:"))return"cron";if(e.startsWith("agent:")&&!e.startsWith("agent:main:"))return"other";if(e.startsWith("agent:main:")){const t=e.slice(11);return to.test(t)?"webchat":"chat"}return"other"}function ro(e){return Array.isArray(e)?e.map(t=>{const r=typeof t.key=="string"&&t.key.trim().length>0?t.key.trim():Jt(t.friendlyId??t.key),o=typeof t.friendlyId=="string"&&t.friendlyId.trim().length>0?t.friendlyId.trim():Jt(r),a=no(r),i=t,l=typeof i.totalTokens=="number"?i.totalTokens:void 0,c=typeof i.contextTokens=="number"?i.contextTokens:void 0,u=typeof i.status=="string"?i.status:void 0;return{key:r,friendlyId:o,title:typeof t.title=="string"?t.title:void 0,derivedTitle:typeof t.derivedTitle=="string"?t.derivedTitle:void 0,label:typeof t.label=="string"?t.label:void 0,updatedAt:typeof t.updatedAt=="number"?t.updatedAt:void 0,lastMessage:t.lastMessage??null,kind:a,status:u,totalTokens:l,contextTokens:c}}):[]}async function Ke(e){try{const t=await e.json();return t?.error?String(t.error):t?.message?String(t.message):JSON.stringify(t)}catch{try{return await e.text()}catch{return e.statusText||"Request failed"}}}const so="Missing gateway auth. Set CLAWDBOT_GATEWAY_TOKEN (recommended) or CLAWDBOT_GATEWAY_PASSWORD in the server environment.";function Tn(e){return e.includes(so)}function Rn(e,t){const r=crypto.randomUUID(),o=`opt-${r}`,a=Date.now(),i=[];if(t&&t.length>0)for(const c of t)c.type==="image"&&c.base64&&i.push({type:"image",source:{type:"base64",media_type:c.file.type,data:c.base64}});return e.trim()?i.push({type:"text",text:e}):t&&t.length>0&&i.push({type:"text",text:""}),{clientId:r,optimisticId:o,optimisticMessage:{role:"user",content:i,__optimisticId:o,clientId:r,status:"sending",timestamp:a}}}const fe={sessions:["chat","sessions"],history:function(t,r){return["chat","history",t,r]}};async function oo(){const e=await fetch("/api/sessions");if(!e.ok)throw new Error(await Ke(e));const t=await e.json();return ro(t.sessions)}async function io(e){const t=new URLSearchParams({limit:"200"});e.sessionKey&&t.set("sessionKey",e.sessionKey),e.friendlyId&&t.set("friendlyId",e.friendlyId);const r=await fetch(`/api/history?${t.toString()}`);if(!r.ok)throw new Error(await Ke(r));return await r.json()}async function ao(){const e=new AbortController,t=window.setTimeout(()=>e.abort(),2500);try{const r=await fetch("/api/ping",{signal:e.signal});if(!r.ok)throw new Error(await Ke(r));return await r.json()}catch(r){throw r instanceof DOMException&&r.name==="AbortError"?new Error("Gateway check timed out"):r}finally{window.clearTimeout(t)}}function fn(e,t,r,o){const a=fe.history(t,r);e.setQueryData(a,function(l){const c=l,u=Array.isArray(c?.messages)?c.messages:[],d=o(u);return{sessionKey:c?.sessionKey??r,sessionId:c?.sessionId,messages:d}})}function Ut(e,t,r,o){fn(e,t,r,function(i){return[...i,o]})}function lo(e,t,r,o,a){const i=`opt-${o}`;fn(e,t,r,function(c){return c.map(u=>u.clientId===o||u.__optimisticId===o||u.__optimisticId===i?a(u):u)})}function co(e,t,r,o,a){fn(e,t,r,function(l){return l.filter(c=>!(c.clientId===o||c.__optimisticId===o||a&&c.__optimisticId===a))})}function en(e,t,r){const o=fe.history(t,r);e.setQueryData(o,{sessionKey:r,messages:[]})}function uo(e,t,r,o,a){const i=fe.history(t,r),l=fe.history(o,a),c=e.getQueryData(i);if(!c)return;const u=Array.isArray(c.messages)?c.messages:[];e.setQueryData(l,{sessionKey:a,sessionId:c.sessionId,messages:u}),e.removeQueries({queryKey:i,exact:!0})}function fo(e,t,r,o){e.setQueryData(fe.sessions,function(i){return Array.isArray(i)?i.map(l=>l.key!==t&&l.friendlyId!==r?l:{...l,lastMessage:o}):i})}function mo(e,t,r){e.setQueryData(fe.sessions,function(a){return Array.isArray(a)?a.filter(i=>i.key!==t&&i.friendlyId!==r):a}),e.removeQueries({queryKey:["chat","history",r],exact:!1}),t&&t!==r&&e.removeQueries({queryKey:["chat","history",t],exact:!1})}async function po(e,t,r,o){e.setQueryData(fe.sessions,function(i){return Array.isArray(i)?i.map(l=>l.key===t||l.friendlyId===r?{...l,label:o}:l):i});try{const a=await fetch("/api/sessions",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionKey:t,friendlyId:r,label:o})});if(!a.ok){const i=await Ke(a);console.error("[updateSessionLabel] Failed to persist:",i)}}catch(a){console.error("[updateSessionLabel] Network error:",a)}}function ho(){const[e,t]=s.useState(!1),[r,o]=s.useState(!1),[a,i]=s.useState(null),[l,c]=s.useState(null),u=s.useCallback(async()=>{if(t(!0),i(null),!(r||l)){o(!0);try{const h=await fetch("/api/paths");if(!h.ok)throw new Error(await Ke(h));const v=await h.json();c({agentId:String(v.agentId??"main"),stateDir:String(v.stateDir??""),sessionsDir:String(v.sessionsDir??""),storePath:String(v.storePath??"")})}catch(h){i(h instanceof Error?h.message:String(h))}finally{o(!1)}}},[l,r]),d=s.useCallback(()=>{u()},[u]),f=s.useCallback(()=>{t(!1)},[]),m=s.useCallback(()=>{if(l?.sessionsDir)try{navigator.clipboard.writeText(l.sessionsDir)}catch{}},[l]),p=s.useCallback(()=>{if(l?.storePath)try{navigator.clipboard.writeText(l.storePath)}catch{}},[l]);return{settingsOpen:e,setSettingsOpen:t,pathsLoading:r,pathsError:a,paths:l,handleOpenSettings:d,closeSettings:f,copySessionsDir:m,copyStorePath:p}}let ke=null,mn=!1,Tt=null;function go(e){ke=e}function $t(){return ke!==null}function yt(e){mn=e}function Ht(){return mn}function Dt(){ke=null,mn=!1}function yo(e,t){if(ke){if(e&&ke.sessionKey===e){Dt();return}t&&ke.friendlyId===t&&Dt()}}function xo(e){Tt={friendlyId:e,at:Date.now()}}function cr(e,t=15e3){return!(!Tt||Tt.friendlyId!==e||Date.now()-Tt.at>t)}function wo(e,t){if(!ke)return null;if(e&&ke.sessionKey===e){const r=ke;return ke=null,r}if(t&&ke.friendlyId===t){const r=ke;return ke=null,r}return null}const bo=8e3,Qe=new Map;function So(e){e&&Qe.set(e,{id:e,expiresAt:Date.now()+bo})}function vo(e){e&&Qe.delete(e)}function jo(e){if(Qe.size===0)return e;const t=Date.now();let r=!1;const o=e.filter(a=>{const i=Qe.get(a.key),l=Qe.get(a.friendlyId);return i&&i.expiresAt<=t||l&&l.expiresAt<=t?(i&&i.expiresAt<=t&&Qe.delete(a.key),l&&l.expiresAt<=t&&Qe.delete(a.friendlyId),!0):i||l?(r=!0,!1):!0});return r?o:e}function ko(){const e=mt(),[t,r]=s.useState(!1),[o,a]=s.useState(null),i=er({mutationFn:async function(u){const d=new URLSearchParams;u.sessionKey&&d.set("sessionKey",u.sessionKey),u.friendlyId&&d.set("friendlyId",u.friendlyId);const f=await fetch(`/api/sessions?${d.toString()}`,{method:"DELETE"});if(!f.ok)throw new Error(await Ke(f));return u},onMutate:async function(u){a(null),So(u.sessionKey||u.friendlyId),yo(u.sessionKey,u.friendlyId),await e.cancelQueries({queryKey:fe.sessions});const d=e.getQueryData(fe.sessions);return mo(e,u.sessionKey,u.friendlyId),u.isActive&&(u.sessionKey||u.friendlyId)&&en(e,u.friendlyId||u.sessionKey,u.sessionKey||u.friendlyId),{previousSessions:d,isActive:u.isActive}},onError:function(u,d,f){f?.previousSessions&&e.setQueryData(fe.sessions,f.previousSessions),vo(d.sessionKey||d.friendlyId),a(u instanceof Error?u.message:String(u))},onSuccess:function(u){u.isActive&&Dt(),e.invalidateQueries({queryKey:fe.sessions})},onSettled:function(){r(!1)}});return{deleteSession:s.useCallback(async(c,u,d)=>{!c&&!u||(r(!0),await i.mutateAsync({sessionKey:c,friendlyId:u,isActive:d}))},[i]),deleting:t,error:o}}function Eo(){const e=mt(),[t,r]=s.useState(!1),[o,a]=s.useState(null),i=er({mutationFn:async function(u){const d=await fetch("/api/sessions",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({sessionKey:u.sessionKey,label:u.newTitle})});if(!d.ok)throw new Error(await Ke(d));return u},onMutate:async function(u){a(null),await e.cancelQueries({queryKey:fe.sessions});const d=e.getQueryData(fe.sessions);return e.setQueryData(fe.sessions,function(m){return Array.isArray(m)?m.map(p=>p.key!==u.sessionKey?p:{...p,label:u.newTitle,title:u.newTitle}):m}),{previousSessions:d}},onError:function(u,d,f){f?.previousSessions&&e.setQueryData(fe.sessions,f.previousSessions),a(u instanceof Error?u.message:String(u))},onSuccess:function(){e.invalidateQueries({queryKey:fe.sessions})},onSettled:function(){r(!1)}});return{renameSession:s.useCallback(async(c,u)=>{!c||!u.trim()||(r(!0),await i.mutateAsync({sessionKey:c,newTitle:u.trim()}))},[i]),renaming:t,error:o}}function ur(e){return!e.content||!Array.isArray(e.content)?"":e.content.filter(t=>t.type==="text").map(t=>t.text||"").join(`
3
- `)}function Co(e,t,r){const o=[];o.push(`# Conversation: ${e}`),o.push(`Date: ${r.toLocaleString()}`),o.push("");for(const a of t){const i=a.role||"unknown",l=ur(a);if(l){const c=i==="user"?"User":"Assistant";o.push(`## ${c}`),o.push(""),o.push(l),o.push("")}}return o.join(`
4
- `)}function No(e,t,r){const o={title:e,exportDate:r.toISOString(),messages:t.map(a=>({role:a.role,content:a.content,timestamp:a.timestamp}))};return JSON.stringify(o,null,2)}function To(e,t,r){const o=[];o.push(`Conversation: ${e}`),o.push(`Date: ${r.toLocaleString()}`),o.push("─".repeat(60)),o.push("");for(const a of t){const i=a.role||"unknown",l=ur(a);if(l){const c=i==="user"?"User":"Assistant";o.push(`${c}:`),o.push(l),o.push("")}}return o.join(`
5
- `)}function Ro(e,t,r){const o=new Date;let a,i,l;switch(r){case"markdown":a=Co(e,t,o),i=`${Ft(e)}.md`,l="text/markdown";break;case"json":a=No(e,t,o),i=`${Ft(e)}.json`,l="application/json";break;case"txt":a=To(e,t,o),i=`${Ft(e)}.txt`,l="text/plain";break;default:throw new Error(`Unsupported format: ${r}`)}Io(a,i,l)}function Ft(e){return e.replace(/[^a-z0-9-_\s]/gi,"").replace(/\s+/g,"-").toLowerCase().slice(0,50)||"conversation"}function Io(e,t,r){const o=new Blob([e],{type:r}),a=URL.createObjectURL(o),i=document.createElement("a");i.href=a,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(a)}function Mo(e){const{children:t,open:r,defaultOpen:o=!1,onOpenChange:a,onOpenChangeComplete:i,actionsRef:l,handle:c,triggerId:u,defaultTriggerId:d=null}=e,f=Ss(),m=!!f,p=qr(()=>c?.store??new vs({open:r??o,activeTriggerId:u!==void 0?u:d,modal:!0,disablePointerDismissal:!0,nested:m,role:"alertdialog"})).current;p.useControlledProp("open",r,o),p.useControlledProp("activeTriggerId",u,d),p.useSyncedValue("nested",m),p.useContextCallback("onOpenChange",a),p.useContextCallback("onOpenChangeComplete",i);const h=p.useState("payload");js({store:p,actionsRef:l,parentContext:f?.store.context});const v=s.useMemo(()=>({store:p}),[p]);return n.jsx(ks.Provider,{value:v,children:typeof t=="function"?t({payload:h}):t})}function Ao({children:e,...t}){return n.jsx(Mo,{...t,children:e})}function Do({className:e,children:t}){return n.jsxs(Es,{children:[n.jsx(Cs,{className:"fixed inset-0 bg-primary-950/20 transition-all duration-150 data-[state=open]:opacity-100 data-[state=closed]:opacity-0"}),n.jsx(Ns,{className:O("fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2","w-[min(400px,92vw)] rounded-xl border border-primary-200 bg-primary-50 p-0 shadow-xl","transition-all duration-150","data-[state=open]:opacity-100 data-[state=closed]:opacity-0","data-[state=open]:scale-100 data-[state=closed]:scale-95",e),children:t})]})}function Oo({className:e,...t}){return n.jsx(Ts,{className:O("text-lg font-medium text-primary-900",e),...t})}function Lo({className:e,...t}){return n.jsx(Rs,{className:O("text-sm text-primary-600",e),...t})}function Po({className:e,...t}){return n.jsx(tr,{render:n.jsx(we,{variant:"outline",className:O(e)}),...t})}function _o({className:e,...t}){return n.jsx(tr,{render:n.jsx(we,{variant:"destructive",className:O(e)}),...t})}function Ko({open:e,onOpenChange:t,sessionTitle:r,onConfirm:o,onCancel:a}){return n.jsx(Ao,{open:e,onOpenChange:t,children:n.jsx(Do,{children:n.jsxs("div",{className:"p-4",children:[n.jsx(Oo,{className:"mb-1",children:"Delete Session"}),n.jsxs(Lo,{className:"mb-4",children:['Are you sure you want to delete "',r,'"? This action cannot be undone.']}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx(Po,{onClick:a,children:"Cancel"}),n.jsx(_o,{onClick:o,children:"Delete"})]})]})})})}function zo({open:e,onOpenChange:t,sessionTitle:r,onSave:o,onCancel:a}){return n.jsx(Is,{open:e,onOpenChange:t,children:n.jsx(Ms,{children:n.jsxs("div",{className:"p-4",children:[n.jsx(As,{className:"mb-1",children:"Rename"}),n.jsx(Ds,{className:"mb-4",children:"Enter a new name for this session."}),n.jsx("input",{type:"text",defaultValue:r,onKeyDown:i=>{i.key==="Enter"&&(i.preventDefault(),o(i.currentTarget.value))},className:"w-full rounded-lg border border-primary-200 bg-primary-50 px-3 py-2 text-sm text-primary-900 outline-none focus:border-primary-400",placeholder:"Session name",autoFocus:!0}),n.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[n.jsx(Os,{onClick:a,children:"Cancel"}),n.jsx(we,{onClick:i=>{const l=i.currentTarget.parentElement?.previousElementSibling;o(l.value)},children:"Save"})]})]})})})}function Uo(e){const{open:t,defaultOpen:r,onOpenChange:o,disabled:a}=e,i=t!==void 0,[l,c]=zs({controlled:t,default:r,name:"Collapsible",state:"open"}),{mounted:u,setMounted:d,transitionStatus:f}=Us(l,!0,!0),[m,p]=s.useState(l),[{height:h,width:v},g]=s.useState({height:void 0,width:void 0}),j=nr(),[w,y]=s.useState(),P=w??j,[M,z]=s.useState(!1),[T,J]=s.useState(!1),X=s.useRef(null),H=s.useRef(null),te=s.useRef(null),U=s.useRef(null),S=$s(U,!1),C=Ge(k=>{const R=!l,_=rr(Ps,k.nativeEvent);if(o(R,_),_.isCanceled)return;const A=U.current;H.current==="css-animation"&&A!=null&&A.style.removeProperty("animation-name"),!M&&!T&&(H.current!=null&&H.current!=="css-animation"&&!u&&R&&d(!0),H.current==="css-animation"&&(!m&&R&&p(!0),!u&&R&&d(!0))),c(R),H.current==="none"&&u&&!R&&d(!1)});return Oe(()=>{i&&H.current==="none"&&!T&&!l&&d(!1)},[i,T,l,t,d]),s.useMemo(()=>({abortControllerRef:X,animationTypeRef:H,disabled:a,handleTrigger:C,height:h,mounted:u,open:l,panelId:P,panelRef:U,runOnceAnimationsFinish:S,setDimensions:g,setHiddenUntilFound:z,setKeepMounted:J,setMounted:d,setOpen:c,setPanelIdState:y,setVisible:p,transitionDimensionRef:te,transitionStatus:f,visible:m,width:v}),[X,H,a,C,h,u,l,P,U,S,g,z,J,d,c,p,te,f,m,v])}const dr=s.createContext(void 0);function fr(){const e=s.useContext(dr);if(e===void 0)throw new Error(ln(15));return e}let xt=(function(e){return e.open="data-open",e.closed="data-closed",e[e.startingStyle=En.startingStyle]="startingStyle",e[e.endingStyle=En.endingStyle]="endingStyle",e})({}),$o=(function(e){return e.panelOpen="data-panel-open",e})({});const Ho={[xt.open]:""},Fo={[xt.closed]:""},Wo={open(e){return e?{[$o.panelOpen]:""}:null}},Xo={open(e){return e?Ho:Fo}},mr={...Xo,...sr},Bo=s.forwardRef(function(t,r){const{render:o,className:a,defaultOpen:i=!1,disabled:l=!1,onOpenChange:c,open:u,...d}=t,f=Ge(c),m=Uo({open:u,defaultOpen:i,onOpenChange:f,disabled:l}),p=s.useMemo(()=>({open:m.open,disabled:m.disabled,transitionStatus:m.transitionStatus}),[m.open,m.disabled,m.transitionStatus]),h=s.useMemo(()=>({...m,onOpenChange:f,state:p}),[m,f,p]),v=qe("div",t,{state:p,ref:r,props:d,stateAttributesMapping:mr});return n.jsx(dr.Provider,{value:h,children:v})}),Yo={...Wo,...sr},Go=s.forwardRef(function(t,r){const{panelId:o,open:a,handleTrigger:i,state:l,disabled:c}=fr(),{className:u,disabled:d=c,id:f,render:m,nativeButton:p=!0,...h}=t,{getButtonProps:v,buttonRef:g}=_s({disabled:d,focusableWhenDisabled:!0,native:p}),j=s.useMemo(()=>({"aria-controls":a?o:void 0,"aria-expanded":a,onClick:i}),[o,a,i]);return qe("button",t,{state:l,ref:[r,g],props:[j,h,v],stateAttributesMapping:Yo})});let Vo=(function(e){return e.disabled="data-disabled",e.orientation="data-orientation",e})({});function qo(e){const{abortControllerRef:t,animationTypeRef:r,externalRef:o,height:a,hiddenUntilFound:i,keepMounted:l,id:c,mounted:u,onOpenChange:d,open:f,panelRef:m,runOnceAnimationsFinish:p,setDimensions:h,setMounted:v,setOpen:g,setVisible:j,transitionDimensionRef:w,visible:y,width:P}=e,M=s.useRef(!1),z=s.useRef(null),T=s.useRef(f),J=s.useRef(f),X=Hs(),H=s.useMemo(()=>r.current==="css-animation"?!y:!f&&!u,[f,u,y,r]),te=Ge(S=>{if(!S)return;if(r.current==null||w.current==null){const R=getComputedStyle(S),_=R.animationName!=="none"&&R.animationName!=="",A=R.transitionDuration!=="0s"&&R.transitionDuration!=="";_&&A||(R.animationName==="none"&&R.transitionDuration!=="0s"?r.current="css-transition":R.animationName!=="none"&&R.transitionDuration==="0s"?r.current="css-animation":r.current="none"),S.getAttribute(Vo.orientation)==="horizontal"||R.transitionProperty.indexOf("width")>-1?w.current="width":w.current="height"}if(r.current!=="css-transition")return;(a===void 0||P===void 0)&&(h({height:S.scrollHeight,width:S.scrollWidth}),J.current&&S.style.setProperty("transition-duration","0s"));let C=-1,k=-1;return C=Ce.request(()=>{J.current=!1,k=Ce.request(()=>{setTimeout(()=>{S.style.removeProperty("transition-duration")})})}),()=>{Ce.cancel(C),Ce.cancel(k)}}),U=Jr(o,m,te);return Oe(()=>{if(r.current!=="css-transition")return;const S=m.current;if(!S)return;let C=-1;if(t.current!=null&&(t.current.abort(),t.current=null),f){const k={"justify-content":S.style.justifyContent,"align-items":S.style.alignItems,"align-content":S.style.alignContent,"justify-items":S.style.justifyItems};Object.keys(k).forEach(R=>{S.style.setProperty(R,"initial","important")}),!J.current&&!l&&S.setAttribute(xt.startingStyle,""),h({height:S.scrollHeight,width:S.scrollWidth}),C=Ce.request(()=>{Object.entries(k).forEach(([R,_])=>{_===""?S.style.removeProperty(R):S.style.setProperty(R,_)})})}else{if(S.scrollHeight===0&&S.scrollWidth===0)return;h({height:S.scrollHeight,width:S.scrollWidth});const k=new AbortController;t.current=k;const R=k.signal;let _=null;const A=xt.endingStyle;return _=new MutationObserver(W=>{W.some(D=>D.type==="attributes"&&D.attributeName===A)&&(_?.disconnect(),_=null,p(()=>{h({height:0,width:0}),S.style.removeProperty("content-visibility"),v(!1),t.current===k&&(t.current=null)},R))}),_.observe(S,{attributes:!0,attributeFilter:[A]}),()=>{_?.disconnect(),X.cancel(),t.current===k&&(k.abort(),t.current=null)}}return()=>{Ce.cancel(C)}},[t,r,X,i,l,u,f,m,p,h,v]),Oe(()=>{if(r.current!=="css-animation")return;const S=m.current;S&&(z.current=S.style.animationName||z.current,S.style.setProperty("animation-name","none"),h({height:S.scrollHeight,width:S.scrollWidth}),!T.current&&!M.current&&S.style.removeProperty("animation-name"),f?(t.current!=null&&(t.current.abort(),t.current=null),v(!0),j(!0)):(t.current=new AbortController,p(()=>{v(!1),j(!1),t.current=null},t.current.signal)))},[t,r,f,m,p,h,v,j,y]),Ws(()=>{const S=Ce.request(()=>{T.current=!1});return()=>Ce.cancel(S)}),Oe(()=>{if(!i)return;const S=m.current;if(!S)return;let C=-1,k=-1;return f&&M.current&&(S.style.transitionDuration="0s",h({height:S.scrollHeight,width:S.scrollWidth}),C=Ce.request(()=>{M.current=!1,k=Ce.request(()=>{setTimeout(()=>{S.style.removeProperty("transition-duration")})})})),()=>{Ce.cancel(C),Ce.cancel(k)}},[i,f,m,h]),Oe(()=>{const S=m.current;S&&i&&H&&(S.setAttribute("hidden","until-found"),r.current==="css-transition"&&S.setAttribute(xt.startingStyle,""))},[i,H,r,m]),s.useEffect(function(){const C=m.current;if(!C)return;function k(R){M.current=!0,g(!0),d(!0,rr(Ks,R))}return C.addEventListener("beforematch",k),()=>{C.removeEventListener("beforematch",k)}},[d,m,g]),s.useMemo(()=>({props:{hidden:H,id:c,ref:U}}),[H,c,U])}let In=(function(e){return e.collapsiblePanelHeight="--collapsible-panel-height",e.collapsiblePanelWidth="--collapsible-panel-width",e})({});const Jo=s.forwardRef(function(t,r){const{className:o,hiddenUntilFound:a,keepMounted:i,render:l,id:c,...u}=t,{abortControllerRef:d,animationTypeRef:f,height:m,mounted:p,onOpenChange:h,open:v,panelId:g,panelRef:j,runOnceAnimationsFinish:w,setDimensions:y,setHiddenUntilFound:P,setKeepMounted:M,setMounted:z,setPanelIdState:T,setOpen:J,setVisible:X,state:H,transitionDimensionRef:te,visible:U,width:S,transitionStatus:C}=fr(),k=a??!1,R=i??!1;Oe(()=>{if(c)return T(c),()=>{T(void 0)}},[c,T]),Oe(()=>{P(k)},[P,k]),Oe(()=>{M(R)},[M,R]);const{props:_}=qo({abortControllerRef:d,animationTypeRef:f,externalRef:r,height:m,hiddenUntilFound:k,id:g,keepMounted:R,mounted:p,onOpenChange:h,open:v,panelRef:j,runOnceAnimationsFinish:w,setDimensions:y,setMounted:z,setOpen:J,setVisible:X,transitionDimensionRef:te,visible:U,width:S});Fs({open:v&&C==="idle",ref:j,onComplete(){v&&y({height:void 0,width:void 0})}});const A=s.useMemo(()=>({...H,transitionStatus:C}),[H,C]),W=qe("div",t,{state:A,ref:[r,j],props:[_,{style:{[In.collapsiblePanelHeight]:m===void 0?"auto":`${m}px`,[In.collapsiblePanelWidth]:S===void 0?"auto":`${S}px`}},u],stateAttributesMapping:mr});return R||k||!R&&p?W:null});function tn(e){return n.jsx(Bo,{...e})}function nn({className:e,...t}){return n.jsx(Go,{className:O("group inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-left text-xs font-medium text-primary-500 transition-colors hover:bg-primary-100 hover:text-primary-700 data-panel-open:text-primary-700",e),...t})}function rn({className:e,contentClassName:t,children:r,...o}){return n.jsx(Jo,{className:O('flex h-(--collapsible-panel-height) flex-col overflow-hidden text-sm transition-all duration-150 ease-out data-ending-style:h-0 data-starting-style:h-0 [&[hidden]:not([hidden="until-found"])]:hidden',e),...o,children:n.jsx("div",{className:O("pt-1",t),children:r})})}const pr=s.createContext(void 0);function Kt(){const e=s.useContext(pr);if(e===void 0)throw new Error(ln(53));return e}let Ot=(function(e){return e.scrollAreaCornerHeight="--scroll-area-corner-height",e.scrollAreaCornerWidth="--scroll-area-corner-width",e})({});const kt=500,Mn=16;function Ne(e,t,r){if(!e)return 0;const o=getComputedStyle(e),a=r==="x"?"Inline":"Block";return r==="x"&&t==="margin"?parseFloat(o[`${t}InlineStart`])*2:parseFloat(o[`${t}${a}Start`])+parseFloat(o[`${t}${a}End`])}let Qo=(function(e){return e.orientation="data-orientation",e.hovering="data-hovering",e.scrolling="data-scrolling",e.hasOverflowX="data-has-overflow-x",e.hasOverflowY="data-has-overflow-y",e.overflowXStart="data-overflow-x-start",e.overflowXEnd="data-overflow-x-end",e.overflowYStart="data-overflow-y-start",e.overflowYEnd="data-overflow-y-end",e})({});const Et="base-ui-disable-scrollbar",hr={className:Et,getElement(e){return n.jsx("style",{nonce:e,href:Et,precedence:"base-ui:low",children:`.${Et}{scrollbar-width:none}.${Et}::-webkit-scrollbar{display:none}`})}};let lt=(function(e){return e.hasOverflowX="data-has-overflow-x",e.hasOverflowY="data-has-overflow-y",e.overflowXStart="data-overflow-x-start",e.overflowXEnd="data-overflow-x-end",e.overflowYStart="data-overflow-y-start",e.overflowYEnd="data-overflow-y-end",e})({});const pn={hasOverflowX:e=>e?{[lt.hasOverflowX]:""}:null,hasOverflowY:e=>e?{[lt.hasOverflowY]:""}:null,overflowXStart:e=>e?{[lt.overflowXStart]:""}:null,overflowXEnd:e=>e?{[lt.overflowXEnd]:""}:null,overflowYStart:e=>e?{[lt.overflowYStart]:""}:null,overflowYEnd:e=>e?{[lt.overflowYEnd]:""}:null,cornerHidden:()=>null},Zo={x:0,y:0},An={width:0,height:0},ei={xStart:!1,xEnd:!1,yStart:!1,yEnd:!1},ti={x:!1,y:!1,corner:!1},ni=s.forwardRef(function(t,r){const{render:o,className:a,overflowEdgeThreshold:i,...l}=t,c=ri(i),u=nr(),d=At(),f=At(),{nonce:m,disableStyleElements:p}=Ys(),[h,v]=s.useState(!1),[g,j]=s.useState(!1),[w,y]=s.useState(!1),[P,M]=s.useState(!1),[z,T]=s.useState(An),[J,X]=s.useState(An),[H,te]=s.useState(ei),[U,S]=s.useState(ti),C=s.useRef(null),k=s.useRef(null),R=s.useRef(null),_=s.useRef(null),A=s.useRef(null),W=s.useRef(null),E=s.useRef(null),D=s.useRef(!1),x=s.useRef(0),L=s.useRef(0),K=s.useRef(0),G=s.useRef(0),q=s.useRef("vertical"),V=s.useRef(Zo),Q=Ge(I=>{const he=I.x-V.current.x,Ee=I.y-V.current.y;V.current=I,Ee!==0&&(y(!0),d.start(kt,()=>{y(!1)})),he!==0&&(j(!0),f.start(kt,()=>{j(!1)}))}),se=Ge(I=>{I.button===0&&(D.current=!0,x.current=I.clientY,L.current=I.clientX,q.current=I.currentTarget.getAttribute(Qo.orientation),k.current&&(K.current=k.current.scrollTop,G.current=k.current.scrollLeft),A.current&&q.current==="vertical"&&A.current.setPointerCapture(I.pointerId),W.current&&q.current==="horizontal"&&W.current.setPointerCapture(I.pointerId))}),ne=Ge(I=>{if(!D.current)return;const he=I.clientY-x.current,Ee=I.clientX-L.current;if(k.current){const ze=k.current.scrollHeight,Ue=k.current.clientHeight,N=k.current.scrollWidth,Y=k.current.clientWidth;if(A.current&&R.current&&q.current==="vertical"){const F=Ne(R.current,"padding","y"),ue=Ne(A.current,"margin","y"),oe=A.current.offsetHeight,re=R.current.offsetHeight-oe-F-ue,ve=he/re;k.current.scrollTop=K.current+ve*(ze-Ue),I.preventDefault(),y(!0),d.start(kt,()=>{y(!1)})}if(W.current&&_.current&&q.current==="horizontal"){const F=Ne(_.current,"padding","x"),ue=Ne(W.current,"margin","x"),oe=W.current.offsetWidth,re=_.current.offsetWidth-oe-F-ue,ve=Ee/re;k.current.scrollLeft=G.current+ve*(N-Y),I.preventDefault(),j(!0),f.start(kt,()=>{j(!1)})}}}),B=Ge(I=>{D.current=!1,A.current&&q.current==="vertical"&&A.current.releasePointerCapture(I.pointerId),W.current&&q.current==="horizontal"&&W.current.releasePointerCapture(I.pointerId)});function ae(I){M(I.pointerType==="touch")}function me(I){if(ae(I),I.pointerType!=="touch"){const he=Xs(C.current,I.target);v(he)}}const ee=s.useMemo(()=>({hasOverflowX:!U.x,hasOverflowY:!U.y,overflowXStart:H.xStart,overflowXEnd:H.xEnd,overflowYStart:H.yStart,overflowYEnd:H.yEnd,cornerHidden:U.corner}),[U.x,U.y,U.corner,H]),ie={role:"presentation",onPointerEnter:me,onPointerMove:me,onPointerDown:ae,onPointerLeave(){v(!1)},style:{position:"relative",[Ot.scrollAreaCornerHeight]:`${z.height}px`,[Ot.scrollAreaCornerWidth]:`${z.width}px`}},ge=qe("div",t,{state:ee,ref:[r,C],props:[ie,l],stateAttributesMapping:pn}),pe=s.useMemo(()=>({handlePointerDown:se,handlePointerMove:ne,handlePointerUp:B,handleScroll:Q,cornerSize:z,setCornerSize:T,thumbSize:J,setThumbSize:X,touchModality:P,cornerRef:E,scrollingX:g,setScrollingX:j,scrollingY:w,setScrollingY:y,hovering:h,setHovering:v,viewportRef:k,rootRef:C,scrollbarYRef:R,scrollbarXRef:_,thumbYRef:A,thumbXRef:W,rootId:u,hiddenState:U,setHiddenState:S,overflowEdges:H,setOverflowEdges:te,viewportState:ee,overflowEdgeThreshold:c}),[se,ne,B,Q,z,J,P,g,j,w,y,h,v,u,U,H,ee,c]);return n.jsxs(pr.Provider,{value:pe,children:[!p&&hr.getElement(m),ge]})});function ri(e){if(typeof e=="number"){const t=Math.max(0,e);return{xStart:t,xEnd:t,yStart:t,yEnd:t}}return{xStart:Math.max(0,e?.xStart||0),xEnd:Math.max(0,e?.xEnd||0),yStart:Math.max(0,e?.yStart||0),yEnd:Math.max(0,e?.yEnd||0)}}const si=s.createContext(void 0);function He(e,t=Number.MIN_SAFE_INTEGER,r=Number.MAX_SAFE_INTEGER){return Math.max(t,Math.min(e,r))}function oi(e,t){if(typeof IntersectionObserver>"u")return()=>{};const r=new IntersectionObserver(o=>{o.forEach(a=>{a.intersectionRatio>0&&(t(),r.disconnect())})});return r.observe(e),()=>{r.disconnect()}}let Ve=(function(e){return e.scrollAreaOverflowXStart="--scroll-area-overflow-x-start",e.scrollAreaOverflowXEnd="--scroll-area-overflow-x-end",e.scrollAreaOverflowYStart="--scroll-area-overflow-y-start",e.scrollAreaOverflowYEnd="--scroll-area-overflow-y-end",e})({}),Dn=!1;function ii(){Dn||Bs||(typeof CSS<"u"&&"registerProperty"in CSS&&[Ve.scrollAreaOverflowXStart,Ve.scrollAreaOverflowXEnd,Ve.scrollAreaOverflowYStart,Ve.scrollAreaOverflowYEnd].forEach(e=>{try{CSS.registerProperty({name:e,syntax:"<length>",inherits:!1,initialValue:"0px"})}catch{}}),Dn=!0)}const ai=s.forwardRef(function(t,r){const{render:o,className:a,...i}=t,{viewportRef:l,scrollbarYRef:c,scrollbarXRef:u,thumbYRef:d,thumbXRef:f,cornerRef:m,cornerSize:p,setCornerSize:h,setThumbSize:v,rootId:g,setHiddenState:j,hiddenState:w,handleScroll:y,setHovering:P,setOverflowEdges:M,overflowEdges:z,overflowEdgeThreshold:T}=Kt(),J=or(),X=s.useRef(!0),H=At(),te=At(),U=Ge(()=>{const A=l.current,W=c.current,E=u.current,D=d.current,x=f.current,L=m.current;if(!A)return;const K=A.scrollHeight,G=A.scrollWidth,q=A.clientHeight,V=A.clientWidth,Q=A.scrollTop,se=A.scrollLeft;if(K===0||G===0)return;const ne=q>=K,B=V>=G,ae=V/G,me=q/K,ee=Math.max(0,G-V),ie=Math.max(0,K-q);let ge=0,pe=0;B||(J==="rtl"?ge=He(-se,0,ee):ge=He(se,0,ee),pe=ee-ge);const I=ne?0:He(Q,0,ie),he=ne?0:ie-I,Ee=B?0:V,ze=ne?0:q;let Ue=0,N=0;!B&&!ne&&(Ue=W?.offsetWidth||0,N=E?.offsetHeight||0);const Y=p.width===0&&p.height===0,F=Y?Ue:0,ue=Y?N:0,oe=Ne(E,"padding","x"),re=Ne(W,"padding","y"),ve=Ne(x,"margin","x"),tt=Ne(D,"margin","y"),Te=Ee-oe-ve,Pe=ze-re-tt,nt=E?Math.min(E.offsetWidth-F,Te):Te,wt=W?Math.min(W.offsetHeight-ue,Pe):Pe,rt=Math.max(Mn,nt*ae),st=Math.max(Mn,wt*me);if(v(le=>le.height===st&&le.width===rt?le:{width:rt,height:st}),W&&D){const le=W.offsetHeight-st-re-tt,Se=K-q,$e=Se===0?0:Q/Se,gt=Math.min(le,Math.max(0,$e*le));D.style.transform=`translate3d(0,${gt}px,0)`}if(E&&x){const le=E.offsetWidth-rt-oe-ve,Se=G-V,$e=Se===0?0:se/Se,gt=J==="rtl"?He($e*le,-le,0):He($e*le,0,le);x.style.transform=`translate3d(${gt}px,0,0)`}const pt=He(ge,0,ee),bt=He(pe,0,ee),St=He(I,0,ie),ht=He(he,0,ie),vt=[[Ve.scrollAreaOverflowXStart,pt],[Ve.scrollAreaOverflowXEnd,bt],[Ve.scrollAreaOverflowYStart,St],[Ve.scrollAreaOverflowYEnd,ht]];for(const[le,Se]of vt)A.style.setProperty(le,`${Se}px`);L&&(B||ne?h({width:0,height:0}):!B&&!ne&&h({width:Ue,height:N})),j(le=>{const Se=ne||B;return le.y===ne&&le.x===B&&le.corner===Se?le:{y:ne,x:B,corner:Se}});const je={xStart:!B&&pt>T.xStart,xEnd:!B&&bt>T.xEnd,yStart:!ne&&St>T.yStart,yEnd:!ne&&ht>T.yEnd};M(le=>le.xStart===je.xStart&&le.xEnd===je.xEnd&&le.yStart===je.yStart&&le.yEnd===je.yEnd?le:je)});Oe(()=>{if(!l.current)return;ii();let A=!1;return oi(l.current,()=>{if(!A){A=!0;return}U()})},[U,l]),Oe(()=>{queueMicrotask(U)},[U,w,J]),Oe(()=>{l.current?.matches(":hover")&&P(!0)},[l,P]),s.useEffect(()=>{const A=l.current;if(typeof ResizeObserver>"u"||!A)return;let W=!1;const E=new ResizeObserver(()=>{if(!W){W=!0;return}U()});return E.observe(A),te.start(0,()=>{const D=A.getAnimations({subtree:!0});D.length!==0&&Promise.all(D.map(x=>x.finished)).then(U).catch(()=>{})}),()=>{E.disconnect(),te.clear()}},[U,l,te]);function S(){X.current=!1}const C={role:"presentation",...g&&{"data-id":`${g}-viewport`},...(!w.x||!w.y)&&{tabIndex:0},className:hr.className,style:{overflow:"scroll"},onScroll(){l.current&&(U(),X.current||y({x:l.current.scrollLeft,y:l.current.scrollTop}),H.start(100,()=>{X.current=!0}))},onWheel:S,onTouchMove:S,onPointerMove:S,onPointerEnter:S,onKeyDown:S},k=s.useMemo(()=>({hasOverflowX:!w.x,hasOverflowY:!w.y,overflowXStart:z.xStart,overflowXEnd:z.xEnd,overflowYStart:z.yStart,overflowYEnd:z.yEnd,cornerHidden:w.corner}),[w.x,w.y,w.corner,z]),R=qe("div",t,{ref:[r,l],state:k,props:[C,i],stateAttributesMapping:pn}),_=s.useMemo(()=>({computeThumbPosition:U}),[U]);return n.jsx(si.Provider,{value:_,children:R})}),gr=s.createContext(void 0);function li(){const e=s.useContext(gr);if(e===void 0)throw new Error(ln(54));return e}let Lt=(function(e){return e.scrollAreaThumbHeight="--scroll-area-thumb-height",e.scrollAreaThumbWidth="--scroll-area-thumb-width",e})({});const ci=s.forwardRef(function(t,r){const{render:o,className:a,orientation:i="vertical",keepMounted:l=!1,...c}=t,{hovering:u,scrollingX:d,scrollingY:f,hiddenState:m,overflowEdges:p,scrollbarYRef:h,scrollbarXRef:v,viewportRef:g,thumbYRef:j,thumbXRef:w,handlePointerDown:y,handlePointerUp:P,rootId:M,thumbSize:z}=Kt(),T=s.useMemo(()=>({hovering:u,scrolling:{horizontal:d,vertical:f}[i],orientation:i,hasOverflowX:!m.x,hasOverflowY:!m.y,overflowXStart:p.xStart,overflowXEnd:p.xEnd,overflowYStart:p.yStart,overflowYEnd:p.yEnd,cornerHidden:m.corner}),[u,d,f,i,m,p]),J=or();s.useEffect(()=>{const C=g.current,k=i==="vertical"?h.current:v.current;if(!k)return;function R(_){if(!(!C||!k||_.ctrlKey)){if(_.preventDefault(),i==="vertical"){if(C.scrollTop===0&&_.deltaY<0)return}else if(C.scrollLeft===0&&_.deltaX<0)return;if(i==="vertical"){if(C.scrollTop===C.scrollHeight-C.clientHeight&&_.deltaY>0)return}else if(C.scrollLeft===C.scrollWidth-C.clientWidth&&_.deltaX>0)return;i==="vertical"?C.scrollTop+=_.deltaY:C.scrollLeft+=_.deltaX}}return k.addEventListener("wheel",R,{passive:!1}),()=>{k.removeEventListener("wheel",R)}},[i,v,h,g]);const X={...M&&{"data-id":`${M}-scrollbar`},onPointerDown(C){if(C.button===0&&C.currentTarget===C.target&&g.current){if(j.current&&h.current&&i==="vertical"){const k=Ne(j.current,"margin","y"),R=Ne(h.current,"padding","y"),_=j.current.offsetHeight,A=h.current.getBoundingClientRect(),W=C.clientY-A.top-_/2-R+k/2,E=g.current.scrollHeight,D=g.current.clientHeight,x=h.current.offsetHeight-_-R-k,K=W/x*(E-D);g.current.scrollTop=K}if(w.current&&v.current&&i==="horizontal"){const k=Ne(w.current,"margin","x"),R=Ne(v.current,"padding","x"),_=w.current.offsetWidth,A=v.current.getBoundingClientRect(),W=C.clientX-A.left-_/2-R+k/2,E=g.current.scrollWidth,D=g.current.clientWidth,x=v.current.offsetWidth-_-R-k,L=W/x;let K;J==="rtl"?(K=(1-L)*(E-D),g.current.scrollLeft<=0&&(K=-K)):K=L*(E-D),g.current.scrollLeft=K}y(C)}},onPointerUp:P,style:{position:"absolute",touchAction:"none",WebkitUserSelect:"none",userSelect:"none",...i==="vertical"&&{top:0,bottom:`var(${Ot.scrollAreaCornerHeight})`,insetInlineEnd:0,[Lt.scrollAreaThumbHeight]:`${z.height}px`},...i==="horizontal"&&{insetInlineStart:0,insetInlineEnd:`var(${Ot.scrollAreaCornerWidth})`,bottom:0,[Lt.scrollAreaThumbWidth]:`${z.width}px`}}},H=qe("div",t,{ref:[r,i==="vertical"?h:v],state:T,props:[X,c],stateAttributesMapping:pn}),te=s.useMemo(()=>({orientation:i}),[i]),U=i==="vertical"?m.y:m.x;return l||!U?n.jsx(gr.Provider,{value:te,children:H}):null}),ui=s.forwardRef(function(t,r){const{render:o,className:a,...i}=t,{thumbYRef:l,thumbXRef:c,handlePointerDown:u,handlePointerMove:d,handlePointerUp:f,setScrollingX:m,setScrollingY:p}=Kt(),{orientation:h}=li(),v=s.useMemo(()=>({orientation:h}),[h]);return qe("div",t,{ref:[r,h==="vertical"?l:c],state:v,props:[{onPointerDown:u,onPointerMove:d,onPointerUp(j){h==="vertical"&&p(!1),h==="horizontal"&&m(!1),f(j)},style:{...h==="vertical"&&{height:`var(${Lt.scrollAreaThumbHeight})`},...h==="horizontal"&&{width:`var(${Lt.scrollAreaThumbWidth})`}}},i]})}),di=s.forwardRef(function(t,r){const{render:o,className:a,...i}=t,{cornerRef:l,cornerSize:c,hiddenState:u}=Kt(),d=qe("div",t,{ref:[r,l],props:[{style:{position:"absolute",bottom:0,insetInlineEnd:0,width:c.width,height:c.height}},i]});return u.corner?null:d});function yr({className:e,...t}){return n.jsx(ni,{className:O("group/scroll-area relative outline-none focus-visible:outline-none",e),...t})}function xr({className:e,...t}){return n.jsx(ai,{className:O("h-full w-full outline-none focus-visible:outline-none",e),...t})}function wr({className:e,...t}){return n.jsx(ci,{className:O("flex w-2 touch-none select-none p-0.5 outline-none focus-visible:outline-none","opacity-0 transition-opacity duration-150","data-hovering:opacity-100 data-scrolling:opacity-100 group-hover/scroll-area:opacity-100",e),...t})}function br({className:e,...t}){return n.jsx(ui,{className:O("flex-1 rounded-full bg-primary-500 outline-none focus-visible:outline-none",e),...t})}function fi({className:e,...t}){return n.jsx(di,{className:O("bg-primary-100 outline-none focus-visible:outline-none",e),...t})}function mi(e){return e==="subagent"?ts:e==="cron"?ns:rs}function pi(e){if(!e||!Array.isArray(e.content))return"";const t=e.content.map(o=>o.type==="text"?String(o.text??""):"").join(" ");return lr(t).replace(/\s+/g," ").trim()}function hi(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e12?e*1e3:e;if(typeof e=="string"){const t=Date.parse(e);if(!Number.isNaN(t))return t}return null}function gi(e){if(!e)return null;const t=[e.createdAt,e.created_at,e.timestamp,e.time,e.ts];for(const r of t){const o=hi(r);if(o)return o}return null}function yi(e){const t=e-Date.now(),r=Math.abs(t),o=[["minute",6e4],["hour",36e5],["day",864e5]];let a="minute",i=6e4;r>=o[2][1]?[a,i]=o[2]:r>=o[1][1]&&([a,i]=o[1]);const l=Math.round(t/i);return new Intl.RelativeTimeFormat("en",{numeric:"auto"}).format(l,a)}function xi(e){const t=String(e??"").toLowerCase().trim();return t?t==="error"||t==="failed"?"error":t==="completed"||t==="ended"||t==="done"?"success":null:null}function wi({session:e,active:t,isGenerating:r=!1,isPinned:o,selectionMode:a=!1,selected:i=!1,onToggleSelect:l,onSelect:c,onTogglePin:u,onRename:d,onDelete:f,onExport:m}){const p=e.label||e.title||e.derivedTitle||e.friendlyId,h=mi(e.kind),v=e.kind==="subagent"&&(e.lastMessage?.role==="assistant"||e.lastMessage?.role==="toolResult")?pi(e.lastMessage):"",g=v.length>50?`${v.slice(0,50).trimEnd()}…`:v,j=e.kind==="subagent"?xi(e.status):null,w=e.kind==="cron"?gi(e.lastMessage):null;return n.jsxs(Xe,{to:"/chat/$sessionKey",params:{sessionKey:e.friendlyId},onClick:y=>{if(a){y.preventDefault(),y.stopPropagation(),l?.(e);return}c?.()},className:O("group inline-flex items-center justify-between","w-full text-left pl-1.5 pr-0.5 min-h-8 py-1 rounded-lg transition-colors duration-0","select-none",t?"bg-[var(--opencami-accent-light)] text-[var(--opencami-accent)]":"bg-transparent text-primary-950 [&:hover:not(:has(button:hover))]:bg-primary-200"),children:[n.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[a?n.jsx("span",{"aria-hidden":"true",className:O("inline-flex items-center justify-center size-4 shrink-0 rounded border transition-colors",i?"bg-primary-700 border-primary-700 text-white":"border-primary-300 bg-surface"),children:i?n.jsx("svg",{viewBox:"0 0 12 12",className:"size-3",fill:"none",stroke:"currentColor",strokeWidth:2,children:n.jsx("path",{d:"M2.5 6l2.5 2.5 4.5-5"})}):null}):null,n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[n.jsx(Z,{icon:h,size:12,strokeWidth:1.75,className:"text-primary-500/70 shrink-0"}),n.jsxs("div",{className:"min-w-0 truncate text-sm font-[450]",title:p,children:[o?n.jsx("span",{className:"mr-1 text-xs text-primary-700","aria-hidden":"true",children:"📌"}):null,p]}),e.kind==="subagent"?r?n.jsx("span",{"aria-label":"Session active",className:"size-1.5 rounded-full bg-green-500 shrink-0"}):j==="success"?n.jsx(Z,{icon:Gn,size:12,strokeWidth:1.8,className:"text-green-600/80 shrink-0"}):j==="error"?n.jsx(Z,{icon:_t,size:12,strokeWidth:1.8,className:"text-red-600/80 shrink-0"}):null:null]}),g?n.jsx("div",{className:"text-[11px] text-primary-600/80 line-clamp-1 mt-0.5 pl-[18px]",children:g}):null,e.kind==="cron"&&w?n.jsx("div",{className:"text-[10px] text-primary-500/75 line-clamp-1 mt-0.5 pl-[18px] font-mono",children:yi(w)}):null]})]}),a?null:n.jsxs(cn,{children:[n.jsx(un,{type:"button",onClick:y=>{y.preventDefault(),y.stopPropagation()},className:O("ml-2 inline-flex size-7 items-center justify-center rounded-md text-primary-700","opacity-0 transition-opacity group-hover:opacity-100 hover:bg-primary-200","aria-expanded:opacity-100 aria-expanded:bg-primary-200"),children:n.jsx(Z,{icon:Qr,size:20,strokeWidth:1.5})}),n.jsxs(dn,{side:"bottom",align:"end",children:[n.jsxs(Ze,{onClick:y=>{y.preventDefault(),y.stopPropagation(),u(e)},className:"gap-2",children:[n.jsx("span",{className:"text-xs","aria-hidden":"true",children:"📌"})," ",o?"Unpin Session":"Pin Session"]}),n.jsxs(Ze,{onClick:y=>{y.preventDefault(),y.stopPropagation(),d(e)},className:"gap-2",children:[n.jsx(Z,{icon:Zr,size:20,strokeWidth:1.5})," ","Rename"]}),n.jsxs(Ze,{onClick:y=>{y.preventDefault(),y.stopPropagation(),m(e)},className:"gap-2",children:[n.jsx(Z,{icon:es,size:20,strokeWidth:1.5})," ","Export"]}),Zt(e.key)?null:n.jsxs(Ze,{onClick:y=>{y.preventDefault(),y.stopPropagation(),f(e)},className:"text-red-700 gap-2 hover:bg-red-50/80 data-highlighted:bg-red-50/80",children:[n.jsx(Z,{icon:Vn,size:20,strokeWidth:1.5})," ","Delete"]})]})]})]})}function bi(e,t){return e.active!==t.active||e.isGenerating!==t.isGenerating||e.isPinned!==t.isPinned||e.selectionMode!==t.selectionMode||e.selected!==t.selected||e.onToggleSelect!==t.onToggleSelect||e.onSelect!==t.onSelect||e.onTogglePin!==t.onTogglePin||e.onRename!==t.onRename||e.onDelete!==t.onDelete||e.onExport!==t.onExport?!1:e.session===t.session?!0:e.session.key===t.session.key&&e.session.friendlyId===t.session.friendlyId&&e.session.label===t.session.label&&e.session.title===t.session.title&&e.session.derivedTitle===t.session.derivedTitle&&e.session.updatedAt===t.session.updatedAt&&e.session.kind===t.session.kind&&e.session.status===t.session.status&&e.session.lastMessage===t.session.lastMessage}const Wt=s.memo(wi,bi),Sr="opencami-pinned-sessions",vr="opencami-sidebar-folders",We={webchat:!1,subagent:!1,cron:!1,other:!1};async function Si(e){const t=new URLSearchParams;e&&t.set("sessionKey",e);const r=await fetch(`/api/sessions?${t.toString()}`,{method:"DELETE"});if(!r.ok)throw new Error(await Ke(r))}async function vi(e,t,r){const o=[];let a=0;const i=Array.from({length:Math.min(t,e.length)},async function(){for(;a<e.length;){const c=a;a+=1;try{await r(e[c])}catch(u){o.push(u)}}});return await Promise.all(i),o}function ji(){if(typeof window>"u")return[];try{const e=localStorage.getItem(Sr);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}catch{return[]}}function ki(e){if(!(typeof window>"u"))try{const t=Array.from(new Set(e));localStorage.setItem(Sr,JSON.stringify(t))}catch{}}function Ei(){if(typeof window>"u")return{...We};try{const e=localStorage.getItem(vr);if(!e)return{...We};const t=JSON.parse(e);return!t||typeof t!="object"?{...We}:{webchat:typeof t.webchat=="boolean"?t.webchat:We.webchat,subagent:typeof t.subagent=="boolean"?t.subagent:We.subagent,cron:typeof t.cron=="boolean"?t.cron:We.cron,other:typeof t.other=="boolean"?t.other:We.other}}catch{return{...We}}}function Ci(e){if(!(typeof window>"u"))try{localStorage.setItem(vr,JSON.stringify(e))}catch{}}function Rt(e,t,r){return r&&e.key?e.key===r:e.friendlyId===t}function Ni(e){if(!e)return!1;const t=e.toLowerCase();return t.includes("running")||t.includes("active")||t.includes("stream")||t.includes("generat")}function Xt(e,t,r,o){return Rt(e,t,r)&&o?!0:Ni(e.status)}const Ti=s.memo(function({sessions:t,activeFriendlyId:r,activeSessionKey:o,isStreaming:a=!1,defaultOpen:i=!0,onSelect:l,onRename:c,onDelete:u,onExport:d}){const f=s.useDeferredValue(t),m=mt(),[p,h]=s.useState(()=>ji()),[v,g]=s.useState(()=>Ei()),[j,w]=s.useState(!1),[y,P]=s.useState(()=>new Set),M=s.useMemo(()=>new Set(p),[p]),z=f.filter(E=>M.has(E.key)),T=f.filter(E=>!M.has(E.key)),J=z.length>0&&T.length>0,X=s.useMemo(()=>{const E={chat:[],webchat:[],subagent:[],cron:[],other:[]};for(const D of T){const x=D.kind??"other";E[x].push(D)}return E},[T]),H=s.useMemo(()=>f.filter(E=>y.has(E.key)),[y,f]),te=H.length,U=s.useCallback(()=>{w(E=>(E&&P(new Set),!E))},[]),S=s.useCallback(E=>{Zt(E.key)||P(D=>{const x=new Set(D);return x.has(E.key)?x.delete(E.key):x.add(E.key),x})},[]),C=s.useCallback(()=>{P(new Set(f.filter(E=>!Zt(E.key)).map(E=>E.key)))},[f]),k=s.useCallback(()=>{w(!1),P(new Set)},[]),R=s.useCallback(async()=>{if(H.length===0||!window.confirm(`Delete ${H.length} sessions? This will archive them.`))return;const D=[];await vi(H,10,async x=>{try{await Si(x.key)}catch(L){throw D.push(x.label||x.title||x.derivedTitle||x.friendlyId),L}}),D.length>0&&(console.error("[sidebar] Bulk delete failed for some sessions",D),window.alert(`Could not delete ${D.length} session${D.length!==1?"s":""}:
6
-
7
- ${D.join(`
8
- `)}`)),w(!1),P(new Set),m.invalidateQueries({queryKey:fe.sessions})},[m,H]),_=s.useCallback(E=>{h(D=>{const L=D.includes(E.key)?D.filter(K=>K!==E.key):[...D,E.key];return ki(L),L})},[]),A=s.useCallback((E,D)=>{g(x=>{const L={...x,[E]:D};return Ci(L),L})},[]);function W(E,D,x){return x.length===0?null:n.jsxs(tn,{className:"flex flex-col",open:v[E],onOpenChange:L=>A(E,L),children:[n.jsxs(nn,{className:O("w-full justify-between border-l-2 border-primary-200/70 px-2 py-1 text-[11px] font-medium text-primary-500/80 text-balance"),children:[n.jsx("span",{className:"truncate",children:D}),n.jsx("span",{className:O("rounded-full bg-primary-100 px-1.5 py-0.5 text-[10px] font-medium text-primary-700 tabular-nums"),children:x.length})]}),n.jsx(rn,{contentClassName:"flex flex-col gap-px",children:x.map(L=>n.jsx(Wt,{session:L,active:Rt(L,r,o),isGenerating:Xt(L,r,o,a),isPinned:!1,selectionMode:j,selected:y.has(L.key),onToggleSelect:S,onSelect:l,onTogglePin:_,onRename:c,onDelete:u,onExport:d},L.key))})]})}return n.jsxs(tn,{className:"flex h-full flex-col flex-1 min-h-0 w-full",defaultOpen:i,children:[n.jsxs("div",{className:"flex items-center justify-between pr-2 shrink-0",children:[n.jsxs(nn,{className:"w-fit pl-1.5 text-balance",children:["Sessions",n.jsx("span",{className:"opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:n.jsx(Z,{icon:ss,className:"size-3 transition-transform duration-150 group-data-panel-open:rotate-90"})})]}),n.jsx("button",{type:"button",onClick:U,className:O("text-[11px] font-medium px-1.5 py-0.5 rounded-md transition-colors",j?"text-primary-900 bg-primary-200":"text-primary-500 hover:text-primary-700 hover:bg-primary-100"),children:j?"Done":"Select"})]}),n.jsx(rn,{className:"w-full flex-1 min-h-0 h-auto data-starting-style:h-0 data-ending-style:h-0",contentClassName:"flex flex-1 min-h-0 flex-col overflow-y-auto",children:n.jsxs(yr,{className:"flex-1 min-h-0",children:[n.jsx(xr,{className:"min-h-0",children:n.jsxs("div",{className:"flex flex-col gap-2 pl-2 pr-2",children:[z.length>0?n.jsx("div",{className:"flex flex-col gap-px",children:z.map(E=>n.jsx(Wt,{session:E,active:Rt(E,r,o),isGenerating:Xt(E,r,o,a),isPinned:!0,selectionMode:j,selected:y.has(E.key),onToggleSelect:S,onSelect:l,onTogglePin:_,onRename:c,onDelete:u,onExport:d},E.key))}):null,J?n.jsx("div",{className:"my-1 border-t border-primary-200/80"}):null,X.chat.length>0?n.jsxs("div",{className:"flex flex-col gap-px",children:[n.jsx("div",{className:O("border-l-2 border-primary-200/70 px-2 py-1 text-[11px] font-medium text-primary-500/80 text-balance"),children:"💬 Chats"}),n.jsx("div",{className:"flex flex-col gap-px",children:X.chat.map(E=>n.jsx(Wt,{session:E,active:Rt(E,r,o),isGenerating:Xt(E,r,o,a),isPinned:!1,selectionMode:j,selected:y.has(E.key),onToggleSelect:S,onSelect:l,onTogglePin:_,onRename:c,onDelete:u,onExport:d},E.key))})]}):null,W("webchat","🦎 OpenCami",X.webchat),W("subagent","🤖 Sub-agents",X.subagent),W("cron","⏰ Cron / Isolated",X.cron),W("other","📁 Other",X.other)]})}),n.jsx(wr,{orientation:"vertical",children:n.jsx(br,{})})]})}),j?n.jsxs("div",{className:"shrink-0 border-t border-primary-200 bg-surface px-2 py-2 flex flex-col gap-1.5",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("span",{className:"text-xs text-primary-600 font-medium",children:[te," selected"]}),n.jsx("button",{type:"button",onClick:C,className:"text-[11px] font-medium text-primary-600 hover:text-primary-800",children:"Select all"})]}),n.jsxs("div",{className:"flex gap-1.5",children:[n.jsxs("button",{type:"button",onClick:R,disabled:te===0,className:O("flex-1 inline-flex items-center justify-center gap-1.5 rounded-md px-2 py-1.5 text-xs font-medium transition-colors",te>0?"bg-red-100 text-red-700 hover:bg-red-200":"bg-primary-100 text-primary-400 cursor-not-allowed"),children:[n.jsx(Z,{icon:Vn,size:14,strokeWidth:1.5}),"Delete"]}),n.jsx("button",{type:"button",onClick:k,className:"flex-1 inline-flex items-center justify-center rounded-md px-2 py-1.5 text-xs font-medium bg-primary-100 text-primary-700 hover:bg-primary-200 transition-colors",children:"Cancel"})]})]}):null]})},Ri);function Ri(e,t){if(e.activeFriendlyId!==t.activeFriendlyId||e.activeSessionKey!==t.activeSessionKey||e.isStreaming!==t.isStreaming||e.defaultOpen!==t.defaultOpen||e.onSelect!==t.onSelect||e.onRename!==t.onRename||e.onDelete!==t.onDelete||e.onExport!==t.onExport)return!1;if(e.sessions===t.sessions)return!0;if(e.sessions.length!==t.sessions.length)return!1;for(let r=0;r<e.sessions.length;r+=1){const o=e.sessions[r],a=t.sessions[r];if(o.key!==a.key||o.friendlyId!==a.friendlyId||o.label!==a.label||o.title!==a.title||o.derivedTitle!==a.derivedTitle||o.updatedAt!==a.updatedAt||o.kind!==a.kind||o.status!==a.status||o.lastMessage!==a.lastMessage)return!1}return!0}const Ii=s.lazy(()=>et(()=>import("./settings-dialog-B4NLq1ZS.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24])).then(e=>({default:e.SettingsDialog}))),Mi=s.lazy(()=>et(()=>import("./session-export-dialog-Cib97JLm.js"),__vite__mapDeps([25,1,4,3,5,6,7,8,9,2])).then(e=>({default:e.SessionExportDialog})));function Ai({sessions:e,activeFriendlyId:t,activeSessionKey:r,isStreaming:o=!1,creatingSession:a,onCreateSession:i,isCollapsed:l,onToggleCollapse:c,onSelectSession:u,onActiveSessionDelete:d,onOpenSearch:f}){const{settingsOpen:m,setSettingsOpen:p,pathsLoading:h,pathsError:v,paths:g,handleOpenSettings:j,closeSettings:w,copySessionsDir:y,copyStorePath:P}=ho(),{deleteSession:M}=ko(),{renameSession:z}=Eo(),T={duration:.15,ease:l?"easeIn":"easeOut"},[J,X]=s.useState(!1),[H,te]=s.useState(null),[U,S]=s.useState(""),[C,k]=s.useState(!1),[R,_]=s.useState(null),[A,W]=s.useState(null),[E,D]=s.useState(""),[x,L]=s.useState(!1),[K,G]=s.useState(null),[q,V]=s.useState(null),[Q,se]=s.useState(""),ne=mt();function B(I){te(I.key),S(I.label||I.title||I.derivedTitle||""),X(!0)}function ae(I){H&&z(H,I),X(!1),te(null)}function me(I){_(I.key),W(I.friendlyId),D(I.label||I.title||I.derivedTitle||I.friendlyId),k(!0)}function ee(){if(R&&A){const I=A===t;I&&d&&d(),M(R,A,I)}k(!1),_(null),W(null)}function ie(I){G(I.key),V(I.friendlyId),se(I.label||I.title||I.derivedTitle||I.friendlyId),L(!0)}function ge(I){if(K&&q){const he=fe.history(q,K),Ee=ne.getQueryData(he);Ee?.messages&&Ro(Q,Ee.messages,I)}L(!1),G(null),V(null)}const pe={className:"border-r border-primary-200 h-full overflow-hidden bg-primary-100 flex flex-col"};return n.jsxs(be.aside,{initial:!1,animate:{width:l?48:"var(--opencami-sidebar-width)"},transition:T,className:pe.className,children:[n.jsxs(be.div,{layout:!0,transition:{layout:T},className:O("flex items-center h-12 px-2 justify-between"),children:[n.jsx(Re,{initial:!1,children:l?null:n.jsx(be.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,children:n.jsxs(Xe,{to:"/new",className:O(Je({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),children:[n.jsx(Gs,{className:"size-5"}),n.jsx(Vs,{})]})})}),n.jsx(Ie,{children:n.jsxs(Me,{children:[n.jsx(Ae,{onClick:c,render:n.jsx(we,{size:"icon-sm",variant:"ghost",children:n.jsx(Z,{icon:os,size:20,strokeWidth:1.5})})}),n.jsx(De,{side:"right",children:l?"Open Sidebar":"Close Sidebar"})]})})]}),n.jsxs("div",{className:"px-2 mb-4 flex flex-col gap-1",children:[n.jsxs(be.div,{layout:!0,transition:{layout:T},className:"w-full space-y-2",children:[n.jsxs(we,{disabled:a,variant:"ghost",size:"sm",onClick:i,onMouseUp:u,className:"w-full pl-1.5 justify-start",children:[n.jsx(Z,{icon:is,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Re,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"New Session"})})]}),(()=>{try{const I=localStorage.getItem("opencami-file-explorer");return I===null?!0:I==="true"}catch{return!0}})()&&n.jsx(Ie,{children:n.jsxs(Me,{children:[n.jsx(Ae,{asChild:!0,children:n.jsxs(Xe,{to:"/files",className:O(Je({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(Z,{icon:as,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Re,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Files"})})]})}),l&&n.jsx(De,{side:"right",children:"Files"})]})}),(()=>{try{const I=localStorage.getItem("opencami-memory-viewer");return I===null?!0:I==="true"}catch{return!0}})()&&n.jsx(Ie,{children:n.jsxs(Me,{children:[n.jsx(Ae,{asChild:!0,children:n.jsxs(Xe,{to:"/memory",className:O(Je({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(Z,{icon:qt,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Re,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Memory"})})]})}),l&&n.jsx(De,{side:"right",children:"Memory"})]})}),(()=>{try{return localStorage.getItem("opencami-skills-browser")==="true"}catch{return!1}})()&&n.jsx(Ie,{children:n.jsxs(Me,{children:[n.jsx(Ae,{asChild:!0,children:n.jsxs(Xe,{to:"/skills",className:O(Je({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(Z,{icon:ls,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Re,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Skills"})})]})}),l&&n.jsx(De,{side:"right",children:"Skills"})]})}),(()=>{try{return localStorage.getItem("opencami-agent-manager")==="true"}catch{return!1}})()&&n.jsx(Ie,{children:n.jsxs(Me,{children:[n.jsx(Ae,{asChild:!0,children:n.jsxs(Xe,{to:"/agents",className:O(Je({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(Z,{icon:qt,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Re,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Agents"})})]})}),l&&n.jsx(De,{side:"right",children:"Agents"})]})}),(()=>{try{return localStorage.getItem("opencami-cron-manager")==="true"}catch{return!1}})()&&n.jsx(Ie,{children:n.jsxs(Me,{children:[n.jsx(Ae,{asChild:!0,children:n.jsxs(Xe,{to:"/bots",className:O(Je({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(Z,{icon:cs,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Re,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Cron Jobs"})})]})}),l&&n.jsx(De,{side:"right",children:"Cron Jobs"})]})}),(()=>{try{return localStorage.getItem("feature_dashboard")==="true"}catch{return!1}})()&&n.jsx(Ie,{children:n.jsxs(Me,{children:[n.jsx(Ae,{asChild:!0,children:n.jsxs(Xe,{to:"/dashboard",className:O(Je({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(Z,{icon:us,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Re,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Dashboard"})})]})}),l&&n.jsx(De,{side:"right",children:"Dashboard"})]})})]}),n.jsx(be.div,{layout:!0,transition:{layout:T},className:"w-full",children:n.jsxs(we,{variant:"ghost",size:"sm",onClick:f,className:"w-full pl-1.5 justify-start",children:[n.jsx(Z,{icon:ds,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Re,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Search"})})]})})]}),n.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:n.jsx(Re,{initial:!1,children:!l&&n.jsx(be.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"pt-0 flex flex-col w-full min-h-0 h-full",children:n.jsx("div",{className:"flex-1 min-h-0",children:n.jsx(Ti,{sessions:e,activeFriendlyId:t,activeSessionKey:r,isStreaming:o,onSelect:u,onRename:B,onDelete:me,onExport:ie})})},"content")})}),n.jsx("div",{className:"px-2 py-3 border-t border-primary-200 bg-primary-100",children:n.jsx(be.div,{layout:!0,transition:{layout:T},className:"w-full",children:n.jsxs(we,{variant:"ghost",size:"sm",onClick:j,title:l?"Settings":void 0,className:"w-full justify-start pl-1.5",children:[n.jsx(Z,{icon:fs,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Re,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Settings"})})]})})}),m&&n.jsx(s.Suspense,{fallback:null,children:n.jsx(Ii,{open:m,onOpenChange:p,pathsLoading:h,pathsError:v,paths:g,onClose:w,onCopySessionsDir:y,onCopyStorePath:P})}),n.jsx(zo,{open:J,onOpenChange:X,sessionTitle:U,onSave:ae,onCancel:()=>X(!1)}),n.jsx(Ko,{open:C,onOpenChange:k,sessionTitle:E,onConfirm:ee,onCancel:()=>k(!1)}),x&&n.jsx(s.Suspense,{fallback:null,children:n.jsx(Mi,{open:x,onOpenChange:L,sessionTitle:Q,onExport:ge,onCancel:()=>L(!1)})})]})}function Di(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){const o=e[r],a=t[r];if(o.key!==a.key||o.friendlyId!==a.friendlyId||o.label!==a.label||o.title!==a.title||o.derivedTitle!==a.derivedTitle||o.updatedAt!==a.updatedAt||o.kind!==a.kind||o.status!==a.status||o.lastMessage!==a.lastMessage)return!1}return!0}function Oi(e,t){return!(e.activeFriendlyId!==t.activeFriendlyId||e.activeSessionKey!==t.activeSessionKey||e.isStreaming!==t.isStreaming||e.creatingSession!==t.creatingSession||e.isCollapsed!==t.isCollapsed||!Di(e.sessions,t.sessions))}const Li=s.memo(Ai,Oi);function On(e){if(e<=0)return"0";if(e>=1e6){const t=e/1e6,r=t.toFixed(1);return r.endsWith(".0")?`${Math.round(t)}M`:`${r}M`}if(e>=1e5)return`${Math.round(e/1e3)}K`;if(e>=1e4)return`${Math.round(e/1e3)}K`;if(e>=1e3){const t=e/1e3,r=t.toFixed(1);return r.endsWith(".0")?`${Math.round(t)}K`:`${r}K`}return String(Math.round(e))}function Ln(e){return e>=90?{bar:"bg-red-500",text:"text-red-600 dark:text-red-400"}:e>=70?{bar:"bg-yellow-500",text:"text-yellow-600 dark:text-yellow-400"}:{bar:"bg-emerald-500",text:"text-emerald-600 dark:text-emerald-400"}}function Pi({totalTokens:e,contextTokens:t,className:r}){const{percentage:o,usedStr:a,maxStr:i,colors:l,hasData:c,isNearlyFull:u}=s.useMemo(()=>{if(typeof t!="number"||t<=0)return{percentage:0,usedStr:"",maxStr:"",colors:Ln(0),hasData:!1,isNearlyFull:!1};const m=typeof e=="number"&&e>0?e:0,p=Math.min(100,Math.round(m/t*100));return{percentage:p,usedStr:On(m),maxStr:On(t),colors:Ln(p),hasData:!0,isNearlyFull:p>=95}},[e,t]);if(!c)return null;const d=typeof e=="number"&&e>0?e.toLocaleString():"0",f=typeof t=="number"?t.toLocaleString():"0";return n.jsxs("div",{className:O("group relative flex items-center gap-1.5",r),title:`Context: ${d} / ${f} tokens (${o}%)`,children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("div",{className:"w-12 h-1.5 rounded-full bg-primary-200 dark:bg-primary-700 overflow-hidden shrink-0 group-hover:h-2 transition-all",children:n.jsx("div",{className:O("h-full rounded-full transition-all duration-500 ease-out",l.bar,u&&"animate-pulse"),style:{width:`${o}%`}})}),n.jsx("span",{className:O("text-[10px] leading-none font-medium tabular-nums whitespace-nowrap",u?l.text:"text-primary-500 dark:text-primary-400"),children:a})]}),n.jsx("div",{className:O("absolute right-0 top-full mt-1 z-50","pointer-events-none opacity-0 scale-95","group-hover:pointer-events-auto group-hover:opacity-100 group-hover:scale-100","transition-all duration-150 origin-top-right"),children:n.jsxs("div",{className:O("rounded-md border border-primary-200 dark:border-primary-700","bg-surface shadow-lg px-3 py-2","text-xs whitespace-nowrap"),children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[n.jsx("span",{className:"text-primary-500 dark:text-primary-400",children:"Context window"}),n.jsxs("span",{className:O("font-semibold",l.text),children:[o,"%"]})]}),n.jsxs("div",{className:"flex items-center gap-1.5 text-primary-700 dark:text-primary-300",children:[n.jsx("span",{className:"font-medium",children:a}),n.jsx("span",{className:"text-primary-400",children:"/"}),n.jsx("span",{children:i}),n.jsx("span",{className:"text-primary-400",children:"tokens"})]}),n.jsx("div",{className:"w-full h-1.5 rounded-full bg-primary-200 dark:bg-primary-700 overflow-hidden mt-1.5",children:n.jsx("div",{className:O("h-full rounded-full transition-all duration-500 ease-out",l.bar),style:{width:`${o}%`}})}),u&&n.jsx("div",{className:"mt-1.5 text-[10px] text-red-500 dark:text-red-400 font-medium",children:"⚠ Context nearly full — consider /compact"})]})})]})}const _i=s.memo(Pi);function Ki({activeTitle:e,wrapperRef:t,showSidebarButton:r=!1,onOpenSidebar:o,totalTokens:a,contextTokens:i}){return n.jsxs("div",{ref:t,"data-tauri-drag-region":!0,className:"border-b border-primary-200 px-4 h-12 flex min-w-0 items-center overflow-x-hidden bg-surface tauri-drag-header",children:[r?n.jsx(we,{size:"icon-sm",variant:"ghost",onClick:o,className:"mr-2 text-primary-800 hover:bg-primary-100",style:{WebkitAppRegion:"no-drag"},"aria-label":"Open sidebar",children:n.jsx(Z,{icon:ms,size:18,strokeWidth:1.6})}):null,n.jsx("div",{className:"flex-1 min-w-0 overflow-hidden",children:n.jsx("div",{className:"truncate text-sm font-medium",children:e})}),n.jsx(_i,{totalTokens:a,contextTokens:i,className:"ml-3 hidden sm:flex"})]})}const zi=s.memo(Ki);function Ui(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function $i(e){const t=new Date(e);return Ui(t,new Date)?new Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit"}).format(t):new Intl.DateTimeFormat("en-GB",{day:"2-digit",month:"short"}).format(t)}function Hi(e){return new Intl.DateTimeFormat("en-GB",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(new Date(e))}function Fi({timestamp:e}){const t=$i(e),r=Hi(e);return n.jsx(Ie,{children:n.jsxs(Me,{children:[n.jsx(Ae,{className:"inline-flex items-center text-xs text-primary-600",children:t}),n.jsx(De,{side:"top",children:r})]})})}function Wi({text:e,align:t,timestamp:r,forceVisible:o=!1}){const[a,i]=s.useState(!1),[l,c]=s.useState("idle"),u=s.useRef(null),d=s.useRef(null),f=s.useRef(null),[m,p]=s.useState(()=>{if(typeof window>"u")return!0;try{const w=localStorage.getItem("opencami-tts-enabled");return w===null?!0:w==="true"}catch{return!0}});s.useEffect(()=>{function w(y){y.key==="opencami-tts-enabled"&&p(y.newValue===null?!0:y.newValue==="true")}return window.addEventListener("storage",w),()=>window.removeEventListener("storage",w)},[]),s.useEffect(()=>()=>{f.current?.abort(),u.current&&(u.current.pause(),u.current=null),d.current&&(URL.revokeObjectURL(d.current),d.current=null)},[]);const h=async()=>{try{await navigator.clipboard.writeText(e),i(!0),window.setTimeout(()=>i(!1),1400)}catch{i(!1)}},v=async()=>{if(l==="playing"){f.current?.abort(),u.current&&(u.current.pause(),u.current=null),d.current&&(URL.revokeObjectURL(d.current),d.current=null),c("idle");return}f.current?.abort();const w=new AbortController;f.current=w,c("loading");try{const y=await fetch("/api/tts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:e}),signal:w.signal});if(!y.ok)throw new Error("TTS failed");const P=await y.blob(),M=URL.createObjectURL(P);d.current=M;const z=new Audio(M);u.current=z,z.onended=()=>{c("idle"),d.current&&(URL.revokeObjectURL(d.current),d.current=null),u.current=null},z.onerror=()=>{c("idle"),d.current&&(URL.revokeObjectURL(d.current),d.current=null),u.current=null},await z.play(),c("playing")}catch(y){if(y instanceof Error&&y.name==="AbortError"){c("idle");return}c("idle"),d.current&&(URL.revokeObjectURL(d.current),d.current=null),u.current=null}},g=t==="end"?"justify-end":"justify-start",j=t==="start"&&m&&e.trim().length>0;return n.jsxs("div",{className:O("flex items-center gap-2 text-xs text-primary-600 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100 duration-100 ease-out",o?"opacity-100":"opacity-0",g),children:[n.jsx(Ie,{children:n.jsxs(Me,{children:[n.jsx(Ae,{type:"button",onClick:()=>{h().catch(()=>{})},className:"inline-flex items-center justify-center rounded border border-transparent bg-transparent p-1 text-primary-700 hover:text-primary-900 hover:bg-primary-100",children:n.jsx(Z,{icon:a?qn:ps,size:16,strokeWidth:1.6})}),n.jsx(De,{side:"top",children:"Copy"})]})}),j&&n.jsx(Ie,{children:n.jsxs(Me,{children:[n.jsx(Ae,{type:"button",onClick:()=>{v().catch(()=>{})},disabled:l==="loading",className:O("inline-flex items-center justify-center rounded border border-transparent bg-transparent p-1 text-primary-700 hover:text-primary-900 hover:bg-primary-100",l==="loading"&&"opacity-60 cursor-wait"),children:n.jsx(Z,{icon:l==="loading"?hs:l==="playing"?Jn:gs,size:16,strokeWidth:1.6,className:O(l==="loading"&&"animate-spin")})}),n.jsx(De,{side:"top",children:l==="loading"?"Generating speech…":l==="playing"?"Stop":"Listen"})]})}),n.jsx(Fi,{timestamp:r})]})}function jr({children:e,className:t,...r}){return n.jsx("div",{className:O("flex gap-3 w-full",t),...r,children:e})}function Xi({children:e,markdown:t=!1,className:r,...o}){const a=O("rounded-[12px] break-words whitespace-normal min-w-0 max-w-full overflow-x-hidden",r);return t?n.jsx(qs,{className:a,...o,children:e}):n.jsx("div",{className:a,...o,children:e})}function Bi({toolPart:e,defaultOpen:t=!1}){const{state:r,input:o,output:a,toolCallId:i}=e,l=(d,f=3200)=>{const m=d===void 0?"undefined":d;let p;if(typeof m=="string")try{p=JSON.stringify(JSON.parse(m),null,2)}catch{p=m}else p=JSON.stringify(m,null,2);return p.length<=f?p:`${p.slice(0,f).trimEnd()}
9
- …[truncated]`},c=r==="output-error"?_t:r==="output-available"?Gn:ys,u=r==="output-error"?"text-red-600/80":r==="output-available"?"text-green-600/80":"text-primary-500/80";return n.jsx("div",{className:"inline-flex flex-col w-full",children:n.jsxs(tn,{defaultOpen:t,children:[n.jsxs(nn,{render:n.jsx(we,{variant:"ghost",className:"h-auto w-full justify-start gap-1.5 rounded-md px-1.5 py-1"}),children:[n.jsx(Z,{icon:c,size:12,strokeWidth:1.7,className:u}),n.jsx("span",{className:"text-sm font-medium text-primary-900",children:e.type}),n.jsx(Z,{icon:Qn,size:14,strokeWidth:1.5,className:"ml-auto text-primary-700/80 transition-transform duration-150 group-data-panel-open:rotate-180"})]}),n.jsx(rn,{className:"mt-1",children:n.jsxs("div",{className:"space-y-2 rounded-md border border-primary-200 bg-primary-100/70 p-2",children:[n.jsxs("div",{className:"rounded border border-primary-200 bg-primary-50 px-2 py-1.5",children:[n.jsx("div",{className:"text-[11px] font-medium text-primary-600",children:"Tool"}),n.jsx("div",{className:"font-mono text-xs text-primary-800 break-all",children:e.type})]}),o&&Object.keys(o).length>0&&n.jsxs("div",{className:"rounded border border-primary-200 bg-primary-50 px-2 py-1.5",children:[n.jsx("h4",{className:"mb-1 text-[11px] font-medium text-primary-600",children:"Input"}),n.jsx("pre",{className:"max-h-44 overflow-auto whitespace-pre-wrap break-all font-mono text-xs leading-relaxed text-primary-800",children:l(o)})]}),a!=null&&n.jsxs("div",{className:"rounded border border-primary-200 bg-primary-50 px-2 py-1.5",children:[n.jsx("h4",{className:"mb-1 text-[11px] font-medium text-primary-600",children:"Output"}),n.jsx("pre",{className:"max-h-44 overflow-auto whitespace-pre-wrap break-all font-mono text-xs leading-relaxed text-primary-800",children:l(a)})]}),r==="output-error"&&e.errorText&&n.jsxs("div",{className:"rounded border border-red-200 bg-red-50 px-2 py-1.5",children:[n.jsx("h4",{className:"mb-1 text-[11px] font-medium text-red-600",children:"Error"}),n.jsx("div",{className:"text-xs text-red-700",children:e.errorText})]}),i&&n.jsxs("div",{className:"text-[11px] text-primary-500/80 font-mono tabular-nums",children:["ID: ",i.slice(0,16),"..."]})]})})]})})}const Yi=s.lazy(()=>et(()=>import("./thinking-DTP9JDQl.js"),__vite__mapDeps([26,1,3,17,18,7,5,6,8,14,19,4,9,2,11,15,20,13,21,22,23,16,24])).then(e=>({default:e.Thinking}))),Gi=s.lazy(()=>et(()=>import("./search-sources-badge-CTd0gLuz.js"),__vite__mapDeps([27,1,3])).then(e=>({default:e.SearchSourcesBadge})));function Vi(e,t){const r=t!==void 0,o=t?.isError??!1;let a;r?o?a="output-error":a="output-available":a="input-available";let i;o&&t?.content?.[0]?.type==="text"&&(i=t.content[0].text||"Unknown error");const l=t?.content?.map(u=>u.type==="text"?String(u.text??""):"").join("").trim(),c=t?.details??(l&&l.length>0?l:void 0);return{type:e.name||"unknown",state:a,input:e.arguments,output:c,toolCallId:e.id,errorText:i}}function Pn(e){return Ye(e).map(r=>{const o=r.id??"",a=r.name??"",i=r.partialJson??"",l=r.arguments?JSON.stringify(r.arguments):"";return`${o}|${a}|${i}|${l}`}).join("||")}function qi(e){if(!e)return"missing";const r=(Array.isArray(e.content)?e.content:[]).map(a=>a.type==="text"?String(a.text??""):"").join("").trim(),o=e.details?JSON.stringify(e.details):"";return`${e.toolCallId??""}|${e.toolName??""}|${e.isError?"1":"0"}|${r}|${o}`}function _n(e,t){if(!t)return"";const r=Ye(e);return r.length===0?"":r.map(o=>o.id?qi(t.get(o.id)):"missing").join("||")}function Ji(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e12?e*1e3:e;if(typeof e=="string"){const t=Date.parse(e);if(!Number.isNaN(t))return t}return null}function Kn(e){const t=[e.createdAt,e.created_at,e.timestamp,e.time,e.ts];for(const r of t){const o=Ji(r);if(o)return o}return null}function sn(e){const r=(Array.isArray(e.content)?e.content:[]).find(o=>o.type==="thinking");return r&&"thinking"in r?String(r.thinking??""):null}function Qi(e){const t=Array.isArray(e.content)?e.content:[],r=[];for(const o of t)o.type==="image"&&"source"in o&&typeof o.source?.data=="string"&&r.push(o);return r}const ut=/^📎 Uploaded file:\s*(\/uploads\/\S+)\s*$/;function Zi(e){if(e===null||Number.isNaN(e))return"Unknown size";if(e<1024)return`${e} B`;const t=["KB","MB","GB","TB"];let r=e/1024,o=0;for(;r>=1024&&o<t.length-1;)r/=1024,o++;return`${r.toFixed(1)} ${t[o]}`}function ea(e){if(!e)return[];const t=e.trimStart();if(t.startsWith(">")||t.startsWith("```"))return[];const r=e.split(`
10
- `),o=[];for(const i of r){if(ut.test(i)){o.push(i);continue}if(o.length>0&&i.trim()===""){o.push(i);continue}break}const a=r[0]??"";return ut.test(a)?o.filter(i=>ut.test(i)):[]}function ta(e){const t=[],r=new Set;for(const o of ea(e)){const i=o.match(ut)?.[1];!i||r.has(i)||(r.add(i),t.push({path:i,filename:i.split("/").pop()||i}))}return t}function na(e){const t=e.split(`
11
- `);if(!ut.test(t[0]??""))return e.trim();let r=0;for(;r<t.length&&ut.test(t[r]);)r++;for(;r<t.length&&t[r].trim()==="";)r++;return t.slice(r).join(`
12
- `).replace(/\n{3,}/g,`
13
-
14
- `).trim()}function ra({message:e,toolResultsByCallId:t,forceActionsVisible:r=!1,isStreaming:o=!1,isLastAssistant:a=!1,aggregatedSearchSources:i,wrapperRef:l,wrapperClassName:c,wrapperScrollMarginTop:u,messageDomId:d,highlighted:f=!1}){const{settings:m}=Js(),p=e.role||"assistant",h=Le(e),v=sn(e),g=Qi(e),j=p==="user",w=s.useMemo(()=>g.map(C=>`data:${C.source.media_type};base64,${C.source.data}`),[g]),y=Qt(e),P=Pt(),M=Ls(C=>C.openInEditor),z=s.useMemo(()=>ta(h),[h]),[T,J]=s.useState({}),X=s.useMemo(()=>na(h),[h]);s.useEffect(()=>{let C=!1;async function k(){const R={};await Promise.all(z.map(async _=>{try{const A=await fetch(`/api/files/info?path=${encodeURIComponent(_.path)}`);if(!A.ok){R[_.path]=null;return}const W=await A.json();R[_.path]=typeof W.size=="number"?W.size:null}catch{R[_.path]=null}})),C||J(R)}return z.length>0?k():J({}),()=>{C=!0}},[z]);const H=async C=>{M(C),await P({to:"/files"})},te=p==="assistant"?Ye(e):[],U=te.length>0,S=a&&!o&&m.showSearchSources&&i?i:[];return n.jsxs("div",{ref:l,id:d,"data-message-id":d,style:{contentVisibility:"auto",containIntrinsicSize:"auto 120px",...typeof u=="number"?{scrollMarginTop:`${u}px`}:void 0},className:O("opencami-message-item group mx-auto flex w-full max-w-[var(--opencami-chat-width)] flex-col gap-1 py-[var(--opencami-msg-padding-y)]",c,f&&"opencami-message-highlight",j?"items-end":"items-start"),children:[v&&m.showReasoningBlocks&&n.jsx("div",{className:"w-full max-w-[var(--opencami-chat-width)]",children:n.jsx(s.Suspense,{fallback:null,children:n.jsx(Yi,{content:v})})}),g.length>0&&n.jsx("div",{className:O("flex flex-wrap gap-2 mb-2",j?"justify-end":"justify-start"),children:g.map((C,k)=>n.jsx("img",{src:w[k],alt:`Attachment ${k+1}`,loading:"lazy",decoding:"async",fetchPriority:"low",className:"max-w-[300px] max-h-[300px] rounded-lg object-cover"},k))}),z.length>0&&n.jsx("div",{className:O("mb-2 flex w-full flex-col gap-2",j?"items-end":"items-start"),children:z.map(C=>n.jsxs("button",{type:"button",onClick:()=>{H(C.path)},className:"flex max-w-full items-center gap-3 rounded-xl border border-primary-200 bg-primary-50 px-3 py-2 text-left hover:bg-primary-100",children:[n.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-primary-100",children:n.jsx(Z,{icon:Zn,size:18,className:"text-primary-600"})}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"truncate text-sm font-medium text-primary-900",children:C.filename}),n.jsx("p",{className:"text-xs text-primary-600",children:Zi(T[C.path]??null)})]})]},C.path))}),n.jsx(jr,{className:O("min-w-0 max-w-full",j?"flex-row-reverse":""),children:n.jsx(Xi,{markdown:!j,isStreaming:!j&&o,className:O("text-primary-900 opencami-text-size min-w-0 max-w-full",j?"opencami-message-user bg-primary-100 px-4 py-[var(--opencami-user-bubble-py)] max-w-[85%]":"opencami-message-assistant bg-transparent w-full",!j&&o&&"stream-fade-in"),children:X})}),U&&m.showToolMessages&&n.jsx("div",{className:"mt-2 flex w-full min-w-0 max-w-[var(--opencami-chat-width)] flex-col gap-3 overflow-x-hidden",children:te.map(C=>{const k=C.id?t?.get(C.id):void 0,R=Vi(C,k);return n.jsx(Bi,{toolPart:R,defaultOpen:!1},C.id||C.name)})}),S.length>0&&n.jsx("div",{className:"w-full max-w-[var(--opencami-chat-width)]",children:n.jsx(s.Suspense,{fallback:null,children:n.jsx(Gi,{sources:S})})}),!U&&n.jsx(Wi,{text:h,timestamp:y,align:j?"end":"start",forceVisible:r})]})}function sa(e,t){return!(e.forceActionsVisible!==t.forceActionsVisible||e.isStreaming!==t.isStreaming||e.isLastAssistant!==t.isLastAssistant||e.aggregatedSearchSources!==t.aggregatedSearchSources||e.wrapperClassName!==t.wrapperClassName||e.wrapperRef!==t.wrapperRef||e.wrapperScrollMarginTop!==t.wrapperScrollMarginTop||e.messageDomId!==t.messageDomId||e.highlighted!==t.highlighted||(e.message.role||"assistant")!==(t.message.role||"assistant")||Le(e.message)!==Le(t.message)||sn(e.message)!==sn(t.message)||Pn(e.message)!==Pn(t.message)||_n(e.message,e.toolResultsByCallId)!==_n(t.message,t.toolResultsByCallId)||Kn(e.message)!==Kn(t.message))}const Bt=s.memo(ra,sa);function oa({className:e,variant:t="outline",scrollRef:r,...o}){const[a,i]=s.useState(!0),[l,c]=s.useState(!1),u=s.useRef(0),d=s.useCallback(()=>{const f=r.current;if(!f)return;const m=Math.abs(f.scrollHeight-f.scrollTop-f.clientHeight)<100;i(m)},[r]);return s.useLayoutEffect(()=>{const f=r.current;if(!f)return;const m=()=>{u.current=f.scrollTop,d()},p=new MutationObserver(()=>{f&&(f.scrollTop!==u.current&&(u.current=f.scrollTop),d())});return d(),f.addEventListener("scroll",m),p.observe(f,{childList:!0,subtree:!0}),()=>{f.removeEventListener("scroll",m),p.disconnect()}},[d,r]),s.useLayoutEffect(()=>{if(a){c(!1);return}const f=window.setTimeout(()=>{c(!0)},200);return()=>window.clearTimeout(f)},[a]),n.jsx(we,{variant:"secondary",size:"icon-sm",className:O("pointer-events-auto rounded-full shadow-md","transition-all duration-100 ease-in-out",!a&&l?"translate-y-0 scale-100 opacity-100":"pointer-events-none translate-y-4 scale-98 opacity-0",e),onClick:()=>{const f=r.current;f&&(f.scrollTop=f.scrollHeight,i(!0))},...o,children:n.jsx(Z,{icon:Qn,size:18,strokeWidth:1.8})})}function ia({className:e,viewportRef:t,scrollRef:r,viewportProps:o}){return n.jsxs(yr,{className:O("relative flex flex-1 min-h-0 flex-col",e),children:[n.jsx(xr,{className:"relative will-change-transform overflow-x-hidden",ref:t,...o}),n.jsx("div",{className:"relative mx-auto w-full min-w-0 max-w-full px-5 sm:max-w-[768px]",children:n.jsx("div",{className:"pointer-events-none absolute bottom-10 right-10 z-50",children:n.jsx(oa,{scrollRef:r})})}),n.jsx(wr,{orientation:"vertical",children:n.jsx(br,{})}),n.jsx(fi,{})]})}function aa(e,t){if(e===t)return!0;const r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(const a of r)if(e[a]!==t[a])return!1;return!0}function la(e,t){return!(e.className!==t.className||e.viewportRef!==t.viewportRef||e.scrollRef!==t.scrollRef||!aa(e.viewportProps,t.viewportProps))}const ca=s.memo(ia,la);function ua({viewportNode:e,children:t}){return e?Br.createPortal(n.jsx("div",{className:"relative flex w-full min-w-0 max-w-full flex-col overflow-x-hidden",children:t}),e):null}function da({children:e,className:t,onUserScroll:r,...o}){const a=s.useRef(null),[i,l]=s.useState(null),c=s.useCallback(function(d){a.current=d,l(d)},[]);return s.useLayoutEffect(()=>{const u=a.current;if(!u)return;const d=()=>{r?.(u.scrollTop)};return u.addEventListener("scroll",d),()=>u.removeEventListener("scroll",d)},[r]),n.jsxs(n.Fragment,{children:[n.jsx(ca,{className:t,viewportRef:c,scrollRef:a,viewportProps:o}),n.jsx(ua,{viewportNode:i,children:e})]})}const fa=s.memo(da);function ma({children:e,className:t,...r}){return n.jsx("div",{className:O("flex w-full min-w-0 max-w-full flex-col min-h-full overflow-x-hidden",t),...r,children:n.jsx("div",{className:"mx-auto w-full min-w-0 max-w-full px-2 md:px-5 sm:max-w-[768px] flex flex-col flex-1 min-h-full overflow-x-hidden",children:n.jsx("div",{className:"flex min-w-0 max-w-full flex-col space-y-3 md:space-y-6",children:e})})})}function pa({...e}){return n.jsx("div",{className:"h-px w-full shrink-0 scroll-mt-4 pt-6","aria-hidden":"true",...e})}function ha({as:e="span",className:t,duration:r=4,spread:o=20,children:a,...i}){const l=Math.min(Math.max(o,5),45),c=e;return n.jsx(c,{className:O("bg-size-[200%_auto] bg-clip-text font-medium text-transparent","animate-[shimmer_4s_infinite_linear]",t),style:{backgroundImage:`linear-gradient(to right, var(--color-primary-600) ${50-l}%, var(--color-primary-950) 50%, var(--color-primary-600) ${50+l}%)`,animationDuration:`${r}s`},...i,children:a})}function ga({className:e}){return n.jsxs("div",{className:O("flex items-center gap-2",e),children:[n.jsxs("div",{className:"relative flex h-1.5 w-1.5",children:[n.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-primary-400 opacity-75"}),n.jsx("span",{className:"relative inline-flex rounded-full h-1.5 w-1.5 bg-size-[200%_auto] animate-[shimmer_2s_infinite_linear]",style:{backgroundImage:"linear-gradient(to right, var(--color-primary-600) 0%, var(--color-primary-950) 50%, var(--color-primary-600) 100%)"}})]}),n.jsx(ha,{className:"text-sm",duration:2,children:"Generating..."})]})}const zn=s.lazy(()=>et(()=>import("./follow-up-suggestions-BYWq-d8P.js"),__vite__mapDeps([28,1,3,17,18,7,5,6,8,14,19,4,9,2,11,15,20,13,21,22,23,16,24])).then(e=>({default:e.FollowUpSuggestions})));function ya({messages:e,loading:t,empty:r,emptyState:o,notice:a,noticePosition:i="start",waitingForResponse:l,isStreaming:c=!1,sessionKey:u,pinToTop:d,pinGroupMinHeight:f,headerHeight:m,contentStyle:p,onFollowUpClick:h,jumpToMessageId:v}){const g=s.useRef(null),j=s.useRef(null),w=s.useRef(!1),y=s.useRef(d),P=s.useRef(void 0),[M,z]=s.useState(null),T=s.useMemo(()=>e.filter(x=>x.role!=="toolResult"),[e]),J=s.useDeferredValue(T),X=s.useMemo(()=>{const x=new Map;for(const L of e){if(L.role!=="toolResult")continue;const K=L.toolCallId;typeof K=="string"&&K.trim().length>0&&x.set(K,L)}return x},[e]),H=s.useDeferredValue(X),te=s.useMemo(()=>{const x=[];for(const L of J){if(L.role!=="assistant")continue;const K=Ye(L);for(const G of K){if(!G.id)continue;const q=G.name==="web_search",V=G.name==="web_fetch",Q=G.name==="exec";if(!q&&!V&&!Q)continue;const se=H.get(G.id),ne=se?.content?.map(B=>B.type==="text"?String(B.text??""):"").join("").trim()??"";x.push([G.id,G.name??"",typeof G.arguments?.url=="string"?G.arguments.url:"",se?.isError?"1":"0",ne].join("::"))}}return x.join("||")},[J,H]),U=s.useMemo(()=>{const x=q=>q?q.replace(/SECURITY NOTICE:[\s\S]*?<<<EXTERNAL_UNTRUSTED_CONTENT>>>/g,"").replace(/<<<\/?EXTERNAL_UNTRUSTED_CONTENT>>>/g,"").replace(/<<<\/?END_EXTERNAL_UNTRUSTED_CONTENT>>>/g,"").replace(/Source: Web (?:Search|Fetch)\n---/g,"").replace(/\n{2,}/g,`
15
- `).trim():"",L=(q,V,Q)=>{try{const se=JSON.parse(q),ne=Array.isArray(se)?se:se?.results??se?.web?.results??[];if(!Array.isArray(ne))return!1;let B=!1;for(const ae of ne)ae?.url&&ae?.title&&!Q.has(ae.url)&&(Q.add(ae.url),V.push({title:x(ae.title),url:ae.url,snippet:x(ae.description||ae.snippet||ae.content||"")}),B=!0);return B}catch{return!1}},K=[],G=new Set;for(const q of J){if(q.role!=="assistant")continue;const V=Ye(q);for(const Q of V){if(!Q.id)continue;const se=Q.name==="web_search",ne=Q.name==="web_fetch",B=Q.name==="exec";if(!se&&!ne&&!B)continue;const ae=H.get(Q.id);if(!ae)continue;const me=ae.content?.map(ee=>ee.type==="text"?String(ee.text??""):"").join("").trim();if(me){if(se||B){if(B&&(!me.includes('"results"')||!me.includes('"url"')))continue;let ee=me;const ie=me.indexOf("{");ie>0&&(ee=me.slice(ie));const ge=ee.lastIndexOf("}");ge>0&&(ee=ee.slice(0,ge+1)),L(ee,K,G)}else if(ne){const ee=Q.arguments?.url;if(ee&&!G.has(ee)){G.add(ee);let ie;try{ie=new URL(ee).hostname}catch{ie=ee}K.push({title:ie,url:ee})}}}}}return K},[te,J,H]),S=T.map((x,L)=>({message:x,index:L})).filter(({message:x})=>x.role!=="user").map(({index:x})=>x).pop(),C=T.map((x,L)=>({message:x,index:L})).filter(({message:x})=>x.role==="assistant").map(({index:x})=>x).pop(),k=T.map((x,L)=>({message:x,index:L})).filter(({message:x})=>x.role==="user").map(({index:x})=>x).pop(),R=l&&(typeof k!="number"||typeof S!="number"||S<k),_=typeof k=="number"?k:-1,A=d&&_>=0,W=typeof C=="number"?T[C]:void 0,E=W?Le(W):"",D=!l&&!c&&E.length>0&&h!==void 0&&(typeof k!="number"||typeof C!="number"||C>k);return s.useLayoutEffect(()=>{if(!t){if(d){const x=!y.current||P.current!==k;y.current=!0,P.current=k,x&&j.current&&(w.current=!0,j.current.scrollIntoView({behavior:"auto",block:"start"}),window.setTimeout(()=>{w.current=!1},0));return}y.current=!1,P.current=k,g.current&&(w.current=!0,g.current.scrollIntoView({behavior:"auto",block:"end"}),window.setTimeout(()=>{w.current=!1},0))}},[t,T.length,u,d,k]),s.useEffect(()=>{if(!v||t)return;const x=document.getElementById(`message-${v}`);if(!x)return;x.scrollIntoView({behavior:"smooth",block:"center"}),z(v);const L=window.setTimeout(()=>{z(K=>K===v?null:K)},1800);return()=>window.clearTimeout(L)},[v,t,T]),n.jsx(fa,{className:"flex-1 min-h-0 -mb-4",children:n.jsxs(ma,{className:"pt-6",style:p,children:[a&&i==="start"?a:null,r&&!a?o??n.jsx("div",{"aria-hidden":!0}):A?n.jsxs(n.Fragment,{children:[T.slice(0,_).map((x,L)=>{const K=typeof x.id=="string"?x.id:void 0,G=K||L,q=typeof S=="number"&&L===S,V=typeof S=="number"&&L===S,Q=x.role==="assistant"&&Ye(x).length>0;return n.jsx(Bt,{message:x,toolResultsByCallId:Q?X:void 0,forceActionsVisible:q,isStreaming:V&&c,isLastAssistant:V,aggregatedSearchSources:V?U:void 0,messageDomId:K?`message-${K}`:void 0,highlighted:M===K},G)}),n.jsxs("div",{className:"flex flex-col gap-[var(--opencami-msg-gap)]",style:{minHeight:`${Math.max(0,f)}px`},children:[T.slice(_).map((x,L)=>{const K=_+L,G=typeof x.id=="string"?x.id:void 0,q=G||K,V=typeof S=="number"&&K===S,Q=typeof S=="number"&&K===S,se=K===k?j:void 0,ne=K===k?"scroll-mt-0":void 0,B=K===k?m:void 0,ae=x.role==="assistant"&&Ye(x).length>0;return n.jsx(Bt,{message:x,toolResultsByCallId:ae?X:void 0,forceActionsVisible:V,isStreaming:Q&&c,isLastAssistant:Q,aggregatedSearchSources:Q?U:void 0,wrapperRef:se,wrapperClassName:ne,wrapperScrollMarginTop:B,messageDomId:G?`message-${G}`:void 0,highlighted:M===G},q)}),R?n.jsx("div",{className:"py-2",children:n.jsx(ga,{})}):null,D&&h?n.jsx(s.Suspense,{fallback:null,children:n.jsx(zn,{responseText:E,onSuggestionClick:h,disabled:l})}):null]})]}):n.jsxs(n.Fragment,{children:[T.map((x,L)=>{const K=typeof x.id=="string"?x.id:void 0,G=K||L,q=typeof S=="number"&&L===S,V=typeof S=="number"&&L===S,Q=x.role==="assistant"&&Ye(x).length>0;return n.jsx(Bt,{message:x,toolResultsByCallId:Q?X:void 0,forceActionsVisible:q,isStreaming:V&&c,isLastAssistant:V,aggregatedSearchSources:V?U:void 0,messageDomId:K?`message-${K}`:void 0,highlighted:M===K},G)}),D&&h?n.jsx(s.Suspense,{fallback:null,children:n.jsx(zn,{responseText:E,onSuggestionClick:h,disabled:l})}):null]}),a&&i==="end"?a:null,n.jsx(pa,{ref:g})]})})}function xa(e,t){return e.messages===t.messages&&e.loading===t.loading&&e.empty===t.empty&&e.emptyState===t.emptyState&&e.notice===t.notice&&e.noticePosition===t.noticePosition&&e.waitingForResponse===t.waitingForResponse&&e.isStreaming===t.isStreaming&&e.sessionKey===t.sessionKey&&e.pinToTop===t.pinToTop&&e.pinGroupMinHeight===t.pinGroupMinHeight&&e.headerHeight===t.headerHeight&&e.contentStyle===t.contentStyle&&e.onFollowUpClick===t.onFollowUpClick&&e.jumpToMessageId===t.jumpToMessageId}const wa=s.memo(ya,xa),kr=s.createContext({isLoading:!1,value:"",setValue:()=>{},maxHeight:240,onSubmit:void 0,disabled:!1,textareaRef:Yr.createRef()});let dt=null,Un=!1;function ba(){Un||typeof window>"u"||(Un=!0,window.addEventListener("keydown",e=>{if(e.defaultPrevented||e.metaKey||e.ctrlKey||e.altKey)return;const t=e.target;if(!t)return;const r=t.tagName.toLowerCase();if(r==="input"||r==="textarea"||r==="select"||t.isContentEditable)return;const o=e.key.length===1,a=e.key==="Backspace";!o&&!a||!dt||dt.disabled||dt.focus()}))}function Er(){return s.useContext(kr)}function Sa({className:e,isLoading:t=!1,maxHeight:r=240,value:o,onValueChange:a,onSubmit:i,children:l,disabled:c=!1,onClick:u,...d}){const[f,m]=s.useState(o||""),p=s.useRef(null);ba();function h(g){m(g),a?.(g)}function v(g){c||p.current?.focus(),u?.(g)}return n.jsx(Ie,{children:n.jsx(kr.Provider,{value:{isLoading:t,value:o??f,setValue:a??h,maxHeight:r,onSubmit:i,disabled:c,textareaRef:p},children:n.jsx("div",{onClick:v,className:O("bg-surface cursor-text rounded-[22px] outline outline-ink/10 shadow-[0px_12px_32px_0px_rgba(0,0,0,0.05)] py-3 gap-3 flex flex-col",c&&"cursor-not-allowed opacity-60",e),...d,children:l})})})}function va({className:e,onKeyDown:t,disableAutosize:r=!1,inputRef:o,...a}){const{value:i,setValue:l,maxHeight:c,onSubmit:u,disabled:d,textareaRef:f}=Er();function m(g){!g||r||(g.style.height="auto",typeof c=="number"?g.style.height=`${Math.min(g.scrollHeight,c)}px`:g.style.height=`min(${g.scrollHeight}px, ${c})`)}function p(g){f.current=g,typeof o=="function"?o(g):o&&"current"in o&&(o.current=g),g?dt=g:dt===g&&(dt=null),m(g)}s.useLayoutEffect(()=>{if(!f.current||r)return;const g=f.current;g.style.height="auto",typeof c=="number"?g.style.height=`${Math.min(g.scrollHeight,c)}px`:g.style.height=`min(${g.scrollHeight}px, ${c})`},[i,c,r]);function h(g){m(g.target),l(g.target.value)}function v(g){g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),u?.()),t?.(g)}return n.jsx("textarea",{ref:p,value:i,onChange:h,onKeyDown:v,className:O("text-primary-950 opencami-text-size min-h-[28px] w-full resize-none border-none bg-transparent shadow-none outline-none focus-visible:ring-0 pl-4 pr-1 placeholder:text-primary-500",e),rows:1,readOnly:d,"aria-disabled":d,...a})}function ja({children:e,className:t,...r}){return n.jsx("div",{className:O("flex items-center gap-2",t),...r,children:e})}function $n({tooltip:e,children:t,className:r,side:o="top",...a}){const{disabled:i}=Er();return n.jsxs(Me,{...a,children:[n.jsx(Ae,{disabled:i,onClick:l=>l.stopPropagation(),children:t}),n.jsx(De,{side:o,className:r,children:e})]})}const Cr="opencami-personas-enabled",on="opencami-active-persona";function ka(){if(typeof window>"u")return!0;try{const e=localStorage.getItem(Cr);return e===null?!0:e==="true"}catch{return!0}}function Ea(){if(typeof window>"u")return null;try{const e=localStorage.getItem(on);return e?JSON.parse(e):null}catch{return null}}function Hn(e){if(!(typeof window>"u"))try{e?localStorage.setItem(on,JSON.stringify(e)):localStorage.removeItem(on)}catch{}}const Ca={core:"Core",creative:"Creative",curator:"Curator",learning:"Learning",lifestyle:"Lifestyle",professional:"Professional"};function Na({className:e,onSelect:t}){const[r,o]=s.useState({}),[a,i]=s.useState(null),[l,c]=s.useState(!0),[u,d]=s.useState(!1),[f,m]=s.useState(ka),p=s.useRef(null);s.useEffect(()=>{const j=w=>{w.key===Cr&&m(w.newValue===null?!0:w.newValue==="true")};return window.addEventListener("storage",j),()=>window.removeEventListener("storage",j)},[]),s.useEffect(()=>{let j=!0;async function w(){p.current?.abort();const y=new AbortController;p.current=y;try{c(!0);const P=await fetch("/api/personas",{signal:y.signal});if(!P.ok){d(!1);return}const M=await P.json();if(!j)return;M.ok&&M.available?(o(M.personas),d(!0),i(Ea())):d(!1)}catch(P){if(P instanceof Error&&P.name==="AbortError"||!j)return;d(!1)}finally{j&&c(!1)}}return w(),()=>{j=!1,p.current?.abort()}},[]);const h=s.useCallback(j=>{i(j),Hn(j),t(`/persona ${j.id}`)},[t]),v=s.useCallback(()=>{i(null),Hn(null),t("/persona exit")},[t]);if(l||!u||!f)return null;const g=Object.entries(r);return g.length===0?null:n.jsxs(cn,{children:[n.jsxs(un,{className:O("inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-xs font-[450] text-primary-600 hover:text-primary-900 hover:bg-primary-100",e),children:[n.jsx("span",{className:"text-sm","aria-hidden":"true",children:"🎭"}),a?n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx("span",{children:a.emoji}),n.jsx("span",{children:a.name})]}):n.jsx("span",{children:"Persona"})]}),n.jsxs(dn,{side:"top",align:"start",className:"w-[300px] max-h-[360px] overflow-y-auto",children:[a&&n.jsxs(n.Fragment,{children:[n.jsxs(Ze,{onClick:v,className:"text-red-600 hover:bg-red-50",children:[n.jsx("span",{className:"text-sm",children:"✕"}),n.jsx("span",{children:"Exit Persona"}),n.jsxs("span",{className:"ml-auto text-[10px] text-primary-400",children:[a.emoji," ",a.name]})]}),n.jsx("div",{className:"my-1 h-px bg-primary-200"})]}),g.map(([j,w])=>n.jsxs("div",{children:[n.jsx("div",{className:"px-2 pb-0.5 pt-2 text-[10px] font-semibold uppercase tracking-wider text-primary-400",children:Ca[j]??j}),w.map(y=>n.jsxs(Ze,{onClick:()=>h(y),className:"justify-between",children:[n.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("span",{className:"text-sm flex-shrink-0",children:y.emoji}),n.jsx("span",{className:"truncate",children:y.name})]}),n.jsx("span",{className:"text-[11px] text-primary-400 truncate ml-2 max-w-[140px]",children:y.description})]},y.id))]},j))]})]})}const Ta=[{command:"/new",description:"Start a new conversation",usage:"/new"},{command:"/reset",description:"Reset conversation context",usage:"/reset"},{command:"/abort",description:"Abort current generation",usage:"/abort"},{command:"/status",description:"Show session status card",usage:"/status"},{command:"/usage",description:"Show token usage",usage:"/usage [off|tokens|full]"},{command:"/models",description:"List available models",usage:"/models"},{command:"/agents",description:"List available agents",usage:"/agents"},{command:"/sessions",description:"List active sessions",usage:"/sessions"},{command:"/model",description:"Switch model for this session",usage:"/model <alias>"},{command:"/reasoning",description:"Toggle reasoning mode",usage:"/reasoning [on|off|stream]"},{command:"/think",description:"Set thinking budget",usage:"/think [off|minimal|low|medium|high]"},{command:"/verbose",description:"Toggle verbose output",usage:"/verbose [on|full|off]"},{command:"/tts",description:"Text-to-speech controls",usage:"/tts [status|off|always]"},{command:"/settings",description:"Show current settings",usage:"/settings"},{command:"/help",description:"Show help",usage:"/help"}];function Ra({className:e,onCommandSelect:t}){const[r,o]=s.useState(!1);function a(i){t?.(i),o(!1)}return n.jsxs(n.Fragment,{children:[n.jsx(we,{variant:"ghost",size:"sm",onClick:()=>o(!0),className:O("h-7 w-7 p-0",e),title:"Show commands (Ctrl+/)",children:n.jsx(Z,{icon:kn,size:16,className:"text-primary-500"})}),r&&n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm",children:n.jsxs("div",{className:"bg-white dark:bg-neutral-900 border border-primary-200 dark:border-neutral-700 rounded-xl shadow-2xl w-full max-w-lg max-h-[80vh] overflow-hidden",children:[n.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-primary-200 dark:border-neutral-700 bg-neutral-50 dark:bg-neutral-800",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Z,{icon:kn,size:18,className:"text-primary-600 dark:text-primary-400"}),n.jsx("h2",{className:"font-semibold text-primary-900 dark:text-white",children:"Slash Commands"})]}),n.jsx(we,{variant:"ghost",size:"sm",onClick:()=>o(!1),className:"h-7 w-7 p-0",children:n.jsx(Z,{icon:_t,size:16})})]}),n.jsxs("div",{className:"overflow-y-auto max-h-[60vh] p-2 bg-white dark:bg-neutral-900",children:[n.jsx("div",{className:"text-xs text-primary-500 dark:text-neutral-400 px-2 py-1 mb-2",children:"Type these commands in the chat input"}),Ta.map(i=>n.jsxs("button",{onClick:()=>a(i.command),className:"w-full flex items-start gap-3 px-3 py-2 rounded-lg hover:bg-primary-100 dark:hover:bg-neutral-800 transition-colors text-left",children:[n.jsx("code",{className:"text-sm font-mono font-medium text-primary-700 dark:text-primary-300 bg-primary-100 dark:bg-neutral-800 px-1.5 py-0.5 rounded min-w-[80px]",children:i.command}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm text-primary-900 dark:text-neutral-100",children:i.description}),i.usage&&i.usage!==i.command&&n.jsx("div",{className:"text-xs text-primary-500 dark:text-neutral-500 font-mono mt-0.5",children:i.usage})]})]},i.command))]}),n.jsx("div",{className:"px-4 py-2 border-t border-primary-200 dark:border-neutral-700 bg-neutral-50 dark:bg-neutral-800",children:n.jsxs("div",{className:"text-xs text-primary-500 dark:text-neutral-400",children:["Press ",n.jsx("kbd",{className:"px-1 py-0.5 bg-primary-200 dark:bg-neutral-700 rounded text-primary-700 dark:text-neutral-300",children:"Esc"})," to close"]})})]})})]})}const Ia=10*1024*1024,ct=1280,Ma=.75,Aa=300*1024,Da=["image/png","image/jpeg","image/gif","image/webp"],Nr=["pdf","txt","md","csv","json","xml","yaml","yml","log","py","js","ts","html","css"],Oa=[".png",".jpg",".jpeg",".gif",".webp",...Nr.map(e=>`.${e}`)].join(",");function La(){if(typeof document>"u")return!1;try{const e=document.createElement("canvas");return!!(e.getContext&&e.getContext("2d"))}catch{return!1}}async function Pa(e){if(!La())throw new Error("Image compression not available in this browser");return new Promise((t,r)=>{const o=new Image,a=URL.createObjectURL(e),i=()=>{URL.revokeObjectURL(a)};o.onload=()=>{try{let l=o.width,c=o.height;(l>ct||c>ct)&&(l>c?(c=Math.round(c*ct/l),l=ct):(l=Math.round(l*ct/c),c=ct));const u=document.createElement("canvas");u.width=l,u.height=c;const d=u.getContext("2d");if(!d){i(),r(new Error("Failed to get canvas context"));return}d.drawImage(o,0,0,l,c);const f=e.type==="image/png"?"image/png":"image/jpeg";let m=Ma,p=u.toDataURL(f,m);if(f==="image/jpeg"){const v=Aa*1.37;for(;p.length>v&&m>.3;)m-=.1,p=u.toDataURL(f,m)}const h=p.split(",")[1];if(!h){i(),r(new Error("Failed to encode image"));return}i(),t(h)}catch(l){i(),r(l instanceof Error?l:new Error("Image compression failed"))}},o.onerror=()=>{i(),r(new Error("Failed to load image"))},o.src=a})}function Tr(e){return Da.includes(e.type)}function _a(e){const t=e.name.includes(".")?e.name.split(".").pop()?.toLowerCase():"";return!!(t&&Nr.includes(t))}async function Ka(e){const t=crypto.randomUUID();if(!Tr(e))return{id:t,file:e,preview:null,type:"file",base64:null,error:"Unsupported image type. Please use PNG, JPG, GIF, or WebP images."};if(e.size>Ia)return{id:t,file:e,preview:null,type:"image",base64:null,error:"Image is too large. Maximum size is 10MB."};try{const r=await Pa(e),o=URL.createObjectURL(e);return{id:t,file:e,preview:o,type:"image",base64:r}}catch(r){return{id:t,file:e,preview:null,type:"image",base64:null,error:r instanceof Error?r.message:"Failed to process image"}}}function za({onFilesSelect:e,disabled:t=!1,className:r}){const o=s.useRef(null),a=s.useCallback(()=>{o.current?.click()},[]),i=s.useCallback(async l=>{const c=Array.from(l.target.files??[]);c.length!==0&&(l.target.value="",e(c))},[e]);return n.jsxs(n.Fragment,{children:[n.jsx("input",{ref:o,type:"file",accept:Oa,multiple:!0,onChange:i,className:"hidden","aria-hidden":"true"}),n.jsx(we,{variant:"ghost",size:"icon-sm",onClick:a,disabled:t,className:r,"aria-label":"Attach file",type:"button",children:n.jsx(Z,{icon:xs,size:18,strokeWidth:1.8})})]})}function Fn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Ua(e){const t=e.split(".");return t.length>1&&t.pop()?.toUpperCase()||""}function $a({attachment:e,onRemove:t,className:r}){s.useEffect(()=>()=>{e.preview&&URL.revokeObjectURL(e.preview)},[e.preview]);const o=!!e.error;return e.type==="file"&&!o?n.jsxs("div",{className:O("inline-flex max-w-full items-center gap-2 rounded-full border border-primary-200 bg-primary-50 px-3 py-1.5 text-xs text-primary-800",r),children:[n.jsxs("span",{className:"truncate",children:["📄 ",e.file.name," (",Fn(e.file.size),")"]}),n.jsx("button",{onClick:()=>t(e.id),className:"shrink-0 text-primary-500 hover:text-primary-800","aria-label":"Remove attachment",type:"button",children:"✕"})]}):n.jsxs("div",{className:O("relative flex items-center gap-3 rounded-xl border p-2 pr-3",o?"border-red-300 bg-red-50":"border-primary-200 bg-primary-50",r),children:[n.jsx("div",{className:"relative shrink-0",children:e.type==="image"&&e.preview?n.jsx("img",{src:e.preview,alt:e.file.name,className:"h-12 w-12 rounded-lg object-cover"}):n.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-lg bg-primary-100",children:n.jsx(Z,{icon:Zn,size:24,className:"text-primary-500"})})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"truncate text-sm font-medium text-primary-900",children:e.file.name}),o?n.jsx("p",{className:"text-xs text-red-600",children:e.error}):n.jsxs("p",{className:"text-xs text-primary-500",children:[Ua(e.file.name)," •"," ",Fn(e.file.size)]})]}),n.jsx(we,{variant:"ghost",size:"icon-sm",onClick:()=>t(e.id),className:"h-6 w-6 shrink-0 rounded-full hover:bg-primary-200","aria-label":"Remove attachment",type:"button",children:n.jsx(Z,{icon:_t,size:14})})]})}function Ha({attachments:e,onRemove:t,className:r}){return e.length===0?null:n.jsx("div",{className:O("flex flex-wrap gap-2 px-4",r),children:e.map(o=>n.jsx($a,{attachment:o,onRemove:t},o.id))})}function Fa({commands:e,selectedIndex:t,onSelect:r,className:o}){return e.length===0?null:n.jsx("div",{className:O("absolute left-2 right-2 md:left-5 md:right-5 bottom-full mb-2 z-20 rounded-xl border border-white/10 bg-neutral-900/95 shadow-2xl backdrop-blur-sm overflow-hidden",o),role:"listbox","aria-label":"Slash commands",children:n.jsx("div",{className:"max-h-56 overflow-y-auto p-1",children:e.map((a,i)=>{const l=i===t;return n.jsx("button",{type:"button",role:"option","aria-selected":l,onMouseDown:c=>{c.preventDefault(),r(a)},className:O("w-full rounded-md px-3 py-2 text-left transition-colors",l?"bg-neutral-800":"hover:bg-neutral-800/80"),children:n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx("code",{className:"min-w-[90px] font-mono text-xs text-primary-300",children:a.command}),n.jsx("span",{className:"text-xs text-neutral-300",children:a.description})]})},a.command)})})})}const Wa=s.memo(Fa),an=ar()(ir(e=>({level:"low",setLevel:t=>e({level:t})}),{name:"thinking-level"}));function Xa(){const e=an(r=>r.level),t=an(r=>r.setLevel);return{level:e,setLevel:t}}const Yt=[{value:"off",label:"Off",description:"No reasoning",shortLabel:"Off"},{value:"low",label:"Low",description:"Think",shortLabel:"Low"},{value:"medium",label:"Medium",description:"Think harder",shortLabel:"Medium"},{value:"high",label:"High",description:"Ultrathink",shortLabel:"High"}];function Ba({className:e}){const{level:t,setLevel:r}=Xa(),o=Yt.find(a=>a.value===t)??Yt[1];return n.jsxs(cn,{children:[n.jsxs(un,{className:O("inline-flex h-7 items-center gap-2 rounded-md px-2 text-xs font-[450] text-primary-600 hover:text-primary-900 hover:bg-primary-100",e),children:[n.jsx(Z,{icon:qt,size:20,strokeWidth:1.5,className:O(t==="off"?"text-primary-400":"text-primary-700")}),n.jsx("span",{className:"text-pretty",children:o.shortLabel})]}),n.jsx(dn,{side:"top",align:"start",className:"min-w-[190px]",children:Yt.map(a=>n.jsxs(Ze,{onClick:()=>r(a.value),className:"justify-between",children:[n.jsxs("span",{className:"flex flex-col text-pretty",children:[n.jsx("span",{className:"text-sm text-primary-900",children:a.label}),n.jsx("span",{className:"text-xs text-primary-500",children:a.description})]}),t===a.value&&n.jsx(Z,{icon:qn,size:20,strokeWidth:1.5,className:"text-primary-600"})]},a.value))})]})}const Wn=[{command:"/haiku",description:"Switch to Claude Haiku 4.5"},{command:"/sonnet",description:"Switch to Claude Sonnet 4.5"},{command:"/opus",description:"Switch to Claude Opus 4.5"},{command:"/opus46",description:"Switch to Claude Opus 4.6"},{command:"/codex",description:"Switch to GPT 5.3 Codex"},{command:"/glm",description:"Switch to GLM 4.7"},{command:"/kimi",description:"Switch to Kimi K2.5"},{command:"/minimax",description:"Switch to MiniMax M2.1"},{command:"/grok",description:"Switch to Grok 4.1 Fast"},{command:"/model",description:"Show model picker or switch model"},{command:"/new",description:"New chat (optional: /new model)"},{command:"/reset",description:"Reset session"},{command:"/stop",description:"Stop current generation"},{command:"/compact",description:"Compact conversation context"},{command:"/help",description:"Show available commands"},{command:"/commands",description:"List all commands"},{command:"/status",description:"Show session status & usage"},{command:"/whoami",description:"Show your sender ID"},{command:"/context",description:"Show context window details"},{command:"/usage",description:"Toggle usage footer (off/tokens/full/cost)"},{command:"/think",description:"Set thinking level (off/low/medium/high)"},{command:"/reasoning",description:"Toggle reasoning (on/off/stream)"},{command:"/verbose",description:"Toggle verbose mode (on/full/off)"},{command:"/elevated",description:"Toggle elevated permissions (on/off/ask)"},{command:"/exec",description:"Configure exec settings"},{command:"/queue",description:"Show/configure message queue"},{command:"/tts",description:"Text-to-speech (off/always/tagged/status)"},{command:"/subagents",description:"List/stop/log sub-agent runs"},{command:"/followups",description:"Show follow-up suggestions"},{command:"/skill",description:"Run a skill by name"},{command:"/allowlist",description:"List/add/remove allowlist entries"},{command:"/approve",description:"Resolve exec approval (allow/deny)"},{command:"/config",description:"Show/get/set config (owner-only)"},{command:"/debug",description:"Runtime overrides (owner-only)"},{command:"/send",description:"Toggle message sending (on/off)"},{command:"/restart",description:"Restart gateway"},{command:"/activation",description:"Set activation mode (mention/always)"},{command:"/dock-telegram",description:"Switch replies to Telegram"},{command:"/dock-discord",description:"Switch replies to Discord"},{command:"/bash",description:"Run host shell command"}];function Ya({onSubmit:e,isLoading:t,disabled:r,wrapperRef:o,inputRef:a}){const[i,l]=s.useState(""),[c,u]=s.useState(""),[d,f]=s.useState([]),[m,p]=s.useState(0),[h,v]=s.useState(!1),[g,j]=s.useState(!1),[w,y]=s.useState(!1),[P,M]=s.useState(0),[z,T]=s.useState(!1),[J,X]=s.useState(null),H=s.useRef(null),te=s.useRef([]),U=s.useRef(null),S=s.useRef(null),C=s.useRef(null),k=s.useRef(null),R=s.useMemo(()=>/^\/\S*$/.test(i)&&!h,[i,h]),_=s.useMemo(()=>R?i.slice(1).toLowerCase():"",[R,i]),A=s.useMemo(()=>R?_?Wn.filter(N=>N.command.slice(1).toLowerCase().startsWith(_)):Wn:[],[R,_]),W=s.useCallback(N=>{k.current=N,a&&(typeof a=="function"?a(N):a.current=N)},[a]),E=s.useCallback(()=>{typeof window>"u"||window.requestAnimationFrame(()=>{k.current?.focus()})},[]),D=s.useCallback(N=>{X(N)},[]),x=s.useCallback(()=>{l(""),f([]),p(0),v(!1),E()},[E]),L=s.useCallback(N=>{l(Y=>{const F=`📎 Uploaded file: ${N}
16
-
17
- Please analyze this file.`;return Y.trim()?`${Y.trim()}
18
-
19
- ${F}`:F})},[]),K=s.useCallback(async()=>{await fetch("/api/files/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:"/uploads"})})},[]),G=s.useCallback(async N=>{const Y=crypto.randomUUID();if(!_a(N))return{id:Y,file:N,preview:null,type:"file",base64:null,error:"Unsupported file type for upload."};try{await K();const F=new FormData;F.append("path","/uploads"),F.append("file",N);const ue=await fetch("/api/files/upload",{method:"POST",body:F});if(!ue.ok){const ve=await ue.text();throw new Error(ve||"File upload failed")}const re=(await ue.json()).files?.[0]?.path;if(!re)throw new Error("Upload succeeded but no path was returned");return L(re),{id:Y,file:N,preview:null,type:"file",base64:null,uploadedPath:re}}catch(F){return{id:Y,file:N,preview:null,type:"file",base64:null,error:F instanceof Error?F.message:"File upload failed"}}},[L,K]),q=s.useCallback(async N=>{if(N.length===0)return;const Y=await Promise.all(N.map(F=>Tr(F)?Ka(F):G(F)));f(F=>[...F,...Y]),E()},[E,G]),V=s.useCallback(N=>{f(Y=>Y.filter(F=>F.id!==N))},[]),Q=s.useCallback(N=>{Array.from(N.dataTransfer.types).includes("Files")&&(N.preventDefault(),N.dataTransfer.dropEffect="copy",j(!0))},[]),se=s.useCallback(N=>{N.preventDefault();const Y=N.relatedTarget;Y&&N.currentTarget.contains(Y)||j(!1)},[]),ne=s.useCallback(async N=>{N.preventDefault(),j(!1);const Y=Array.from(N.dataTransfer.files??[]);Y.length!==0&&await q(Y)},[q]),B=s.useCallback(N=>{l(N),p(0),v(!1),E()},[E]),ae=s.useCallback(N=>{l(N),p(0),v(!1)},[]),me=s.useCallback(N=>{l(`${N.command} `),p(0),v(!1),E()},[E]),ee=s.useCallback(()=>{if(r)return;if(R&&A.length>0){const F=Math.min(m,A.length-1);me(A[F]);return}const N=i.trim(),Y=d.filter(F=>!F.error&&F.base64);N.length===0&&Y.length===0||(e(N,{reset:x,setValue:B,model:c||void 0,attachments:Y}),E())},[r,R,A,m,me,i,d,e,x,B,c,E]),ie=s.useCallback(N=>{e(N,{reset:x,setValue:B,model:c||void 0,attachments:[]}),E()},[E,e,x,B,c]),ge=s.useCallback(N=>{if(R){if(N.key==="Escape"){N.preventDefault(),v(!0),p(0);return}if(A.length!==0){if(N.key==="ArrowDown"){N.preventDefault(),p(Y=>(Y+1)%A.length);return}if(N.key==="ArrowUp"){N.preventDefault(),p(Y=>(Y-1+A.length)%A.length);return}if(N.key==="Tab"){N.preventDefault();const Y=Math.min(m,A.length-1);me(A[Y])}}}},[R,A,m,me]);s.useEffect(()=>()=>{S.current?.abort(),U.current&&clearInterval(U.current),H.current&&H.current.state!=="inactive"&&H.current.stop(),C.current&&C.current.abort()},[]);const pe=s.useCallback(()=>{if(typeof window>"u")return"auto";try{return localStorage.getItem("opencami-stt-provider")||"auto"}catch{return"auto"}},[]),I=s.useCallback(()=>{H.current&&H.current.state!=="inactive"&&H.current.stop(),C.current&&C.current.stop(),U.current&&(clearInterval(U.current),U.current=null),y(!1),M(0)},[]),he=s.useCallback(async()=>{X(null);const N=pe();if(N==="browser"){const Y=window.SpeechRecognition||window.webkitSpeechRecognition;if(!Y){D("Web Speech API is not supported in this browser.");return}const F=new Y;F.continuous=!0,F.interimResults=!1,F.lang=navigator.language||"en-US",C.current=F,y(!0),M(0),U.current=setInterval(()=>{M(oe=>oe>=119?(I(),0):oe+1)},1e3);let ue="";F.onresult=oe=>{for(let re=oe.resultIndex;re<oe.results.length;re++)oe.results[re].isFinal&&(ue+=oe.results[re][0].transcript)},F.onend=()=>{y(!1),M(0),U.current&&clearInterval(U.current),ue.trim()&&(X(null),l(oe=>oe+(oe?" ":"")+ue.trim()),E())},F.onerror=()=>{y(!1),M(0),U.current&&clearInterval(U.current),D("Speech recognition failed. Try the Browser provider again or switch providers in Settings.")},F.start();return}try{const Y=await navigator.mediaDevices.getUserMedia({audio:!0}),F=MediaRecorder.isTypeSupported("audio/webm")?"audio/webm":"audio/mp4",ue=new MediaRecorder(Y,{mimeType:F});H.current=ue,te.current=[],ue.ondataavailable=oe=>{oe.data.size>0&&te.current.push(oe.data)},ue.onstop=async()=>{Y.getTracks().forEach(re=>re.stop());const oe=new Blob(te.current,{type:F});if(oe.size!==0){T(!0);try{const re=new FormData;re.append("audio",oe,`recording.${F==="audio/webm"?"webm":"mp4"}`),N!=="auto"&&re.append("provider",N),S.current?.abort();const ve=new AbortController;S.current=ve;const Te=await(await fetch("/api/stt",{method:"POST",body:re,signal:ve.signal})).json();Te.ok&&Te.text?(X(null),l(Pe=>Pe+(Pe?" ":"")+Te.text),E()):Te.ok||(console.warn("STT failed:",Te.error),D(Te.error||"Speech-to-text failed. Try the Browser provider in Settings."))}catch(re){if(re instanceof Error&&re.name==="AbortError")return;console.warn("STT request failed:",re),D("Could not reach speech-to-text service.")}finally{T(!1)}}},y(!0),M(0),U.current=setInterval(()=>{M(oe=>oe>=119?(I(),0):oe+1)},1e3),ue.start()}catch(Y){const F=Y instanceof Error?Y.message:String(Y);if(F.includes("NotAllowedError")||F.includes("Permission"))try{(await navigator.permissions.query({name:"microphone"})).state==="denied"?D("Microphone access is blocked. Please enable it in your browser/app settings."):D("Microphone permission was not granted. Please try again and allow access when prompted.")}catch{D("Could not access microphone. Please check your browser settings and allow microphone access for this site.")}else D("Could not access microphone: "+F)}},[pe,I,E,D]),Ee=s.useCallback(()=>{w?I():he()},[w,I,he]),ze=d.filter(N=>!N.error&&N.base64),Ue=r||i.trim().length===0&&ze.length===0;return n.jsxs("div",{className:"mx-auto w-full max-w-[var(--opencami-chat-width)] px-2 md:px-5 relative pb-1 md:pb-3",ref:o,onDragOver:Q,onDragLeave:se,onDrop:ne,children:[g&&n.jsx("div",{className:"pointer-events-none absolute inset-2 z-20 flex items-center justify-center rounded-2xl border-2 border-dashed border-primary-400 bg-primary-50/90 text-sm font-medium text-primary-700",children:"Drop files here"}),n.jsxs(Sa,{value:i,onValueChange:ae,onSubmit:ee,isLoading:t,disabled:r,children:[n.jsx(Ha,{attachments:d,onRemove:V}),J&&n.jsx("div",{className:"mx-3 mt-3 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-900/40 dark:bg-red-950/40 dark:text-red-200",role:"alert","aria-live":"polite",children:J}),R&&A.length>0&&n.jsx(Wa,{commands:A,selectedIndex:Math.min(m,A.length-1),onSelect:me}),n.jsx(va,{placeholder:"Type a message…",inputRef:W,onKeyDown:ge}),n.jsxs(ja,{className:"justify-between px-3",children:[n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(Ba,{}),n.jsx(Na,{onSelect:ie}),n.jsx(Ra,{onCommandSelect:N=>ae(N+" ")})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(za,{onFilesSelect:q,disabled:r}),n.jsx($n,{tooltip:w?"Stop recording":"Voice input",children:n.jsx(we,{onClick:Ee,disabled:r||z,size:"icon-sm",variant:w?"destructive":"ghost",className:`rounded-full ${w?"animate-pulse":""}`,"aria-label":w?"Stop recording":"Voice input",children:z?n.jsx("span",{className:"size-4 animate-spin rounded-full border-2 border-current border-t-transparent"}):w?n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx("span",{className:"size-2 rounded-full bg-red-500"}),n.jsxs("span",{className:"text-xs tabular-nums",children:[Math.floor(P/60),":",String(P%60).padStart(2,"0")]}),n.jsx(Z,{icon:Jn,size:14,strokeWidth:2})]}):n.jsx(Z,{icon:ws,size:18,strokeWidth:2})})}),n.jsx($n,{tooltip:"Send message",children:n.jsx(we,{onClick:ee,disabled:Ue,size:"icon-sm",className:"rounded-full","aria-label":"Send message",children:n.jsx(Z,{icon:bs,size:18,strokeWidth:2})})})]})]})]})]})}const Ga=s.memo(Ya);function Va({title:e,description:t,detail:r,actionLabel:o,onAction:a,className:i}){return n.jsx("div",{className:O("w-full max-w-[var(--opencami-chat-width)]",i),children:n.jsx(jr,{children:n.jsxs("div",{className:"w-full rounded-xl border border-primary-200 bg-primary-50 p-4 text-primary-900",children:[n.jsx("div",{className:"text-balance font-medium",children:e}),n.jsx("div",{className:"mt-2 text-pretty text-primary-700",children:t}),r?n.jsx("div",{className:"mt-2 text-xs text-primary-600",children:r}):null,o&&a?n.jsx("div",{className:"mt-3",children:n.jsx(we,{size:"sm",variant:"outline",onClick:a,children:o})}):null]})})})}function qa({state:e,error:t,onRetry:r,className:o}){const a=e==="checking",i=a?"Checking gateway connection...":"OpenClaw gateway is unreachable",l=a?"This dashboard needs access to the OpenClaw gateway configured by your server environment variables.":"";return n.jsx(Va,{title:i,description:a?l:n.jsxs(n.Fragment,{children:["We could not reach the gateway from the dashboard server. Start the gateway and confirm your server environment has"," ",n.jsx("span",{className:"font-mono",children:"CLAWDBOT_GATEWAY_URL"})," plus"," ",n.jsx("span",{className:"font-mono",children:"CLAWDBOT_GATEWAY_TOKEN"})," (or"," ",n.jsx("span",{className:"font-mono",children:"CLAWDBOT_GATEWAY_PASSWORD"}),")."]}),detail:a?null:t,actionLabel:a?void 0:"Retry",onAction:a?void 0:r,className:o})}function Ja(){const e=s.useRef(null),t=s.useRef(null),r=s.useRef(null),[o,a]=s.useState(0),[i,l]=s.useState(0);return s.useLayoutEffect(()=>{const c=e.current,u=t.current,d=r.current;if(!d)return;const f=()=>{const p=c?.offsetHeight??0,h=u?.offsetHeight??0,v=d.clientHeight;d.style.setProperty("--chat-header-height",`${Math.max(0,p)}px`),d.style.setProperty("--chat-composer-height",`${Math.max(0,h)}px`),l(p),a(Math.max(0,v-p-h))};f();const m=new ResizeObserver(()=>f());return c&&m.observe(c),u&&m.observe(u),()=>m.disconnect()},[]),{headerRef:e,composerRef:t,mainRef:r,pinGroupMinHeight:o,headerHeight:i}}function Qa({activeFriendlyId:e,activeSessionKey:t,forcedSessionKey:r,isNewChat:o,isRedirecting:a,activeExists:i,sessionsReady:l,queryClient:c}){const u=r||t||e,d=fe.history(e,u),f=Mt({queryKey:d,queryFn:async function(){const y=c.getQueryData(d),P=Array.isArray(y?.messages)?y.messages.filter(T=>T.status==="sending"||T.__optimisticId?!0:!!T.clientId):[],M=await io({sessionKey:u,friendlyId:e});if(!P.length)return M;const z=Za(M.messages,P);return{...M,messages:z}},enabled:!o&&!!e&&!a&&(!l||i),placeholderData:function(){return c.getQueryData(d)},gcTime:1e3*60*10}),m=s.useRef(""),p=s.useRef([]),h=s.useMemo(()=>{const w=Array.isArray(f.data?.messages)?f.data.messages:[],y=w[w.length-1],P=y&&typeof y.id=="string"?y.id:"",M=`${w.length}:${y?.role??""}:${P}:${Le(y??{content:[]}).slice(-32)}`;return M===m.current?p.current:(m.current=M,p.current=w,w)},[f.data?.messages]),v=f.error instanceof Error?f.error.message:null,g=s.useMemo(()=>{if(r)return r;const w=f.data?.sessionKey;return typeof w=="string"&&w.trim().length>0?w.trim():t},[t,r,f.data?.sessionKey]);return{historyQuery:f,historyMessages:h,displayMessages:h,historyError:v,resolvedSessionKey:g,activeCanonicalKey:o?"new":g||e,sessionKeyForHistory:u}}function Za(e,t){if(!t.length)return e;const r=[...e];for(const o of t)e.some(i=>{if(o.clientId&&i.clientId&&o.clientId===i.clientId||o.__optimisticId&&i.__optimisticId&&o.__optimisticId===i.__optimisticId)return!0;if(o.role&&i.role&&o.role!==i.role)return!1;const l=Le(o);if(!l||l!==Le(i))return!1;const c=Qt(o),u=Qt(i);return Math.abs(c-u)<=1e4})||r.push(o);return r}function el(e){const[t,r]=s.useState(!1);return s.useLayoutEffect(()=>{const o=window.matchMedia("(max-width: 768px)"),a=()=>r(o.matches);return a(),o.addEventListener("change",a),()=>o.removeEventListener("change",a)},[]),s.useLayoutEffect(()=>{t&&Be(e,function(a){return{...a,isSidebarCollapsed:!0}})},[t,e]),{isMobile:t}}function tl({activeFriendlyId:e,isNewChat:t,forcedSessionKey:r}){const[o,a]=s.useState(()=>typeof document>"u"?!0:document.visibilityState==="visible");s.useEffect(()=>{if(typeof document>"u")return;const h=()=>{a(document.visibilityState==="visible")};return h(),document.addEventListener("visibilitychange",h),()=>{document.removeEventListener("visibilitychange",h)}},[]);const i=Mt({queryKey:fe.sessions,queryFn:oo,refetchInterval:o?3e4:!1}),l=s.useMemo(()=>{const h=i.data??[];return jo(h)},[i.data]),c=s.useMemo(()=>l.find(h=>h.friendlyId===e),[l,e]),u=s.useMemo(()=>t||r||cr(e)?!0:l.some(h=>h.friendlyId===e),[e,r,t,l]),d=c?.key??"",f=s.useMemo(()=>c?c.label||c.title||c.derivedTitle||c.friendlyId:e,[e,c]),m=i.error instanceof Error?i.error.message:null,p=s.useMemo(()=>({totalTokens:c?.totalTokens,contextTokens:c?.contextTokens}),[c?.totalTokens,c?.contextTokens]);return{sessionsQuery:i,sessions:l,activeSession:c,activeExists:u,activeSessionKey:d,activeTitle:f,activeTokens:p,sessionsError:m}}const nl={openai:{baseUrl:"https://api.openai.com/v1",model:"gpt-4.1-nano"},openrouter:{baseUrl:"https://openrouter.ai/api/v1",model:"openai/gpt-oss-120b"},kilocode:{baseUrl:"https://api.kilo.ai/api/gateway",model:"google/gemini-2.5-flash"},ollama:{baseUrl:"http://localhost:11434/v1",model:"llama3.2"},custom:{baseUrl:"",model:""}},It={useLlmTitles:!0,useLlmFollowUps:!0,llmProvider:"openai",llmBaseUrl:"",llmModel:"",llmApiKey:""};function Rr(e){return nl[e]}function rl(e){return e.llmBaseUrl.trim()?e.llmBaseUrl.trim():Rr(e.llmProvider).baseUrl}function sl(e){return e.llmModel.trim()?e.llmModel.trim():Rr(e.llmProvider).model}function Xn(e,t){return e.llmProvider==="ollama"?!0:e.llmProvider==="custom"?!!e.llmApiKey.trim()||!!(e.llmBaseUrl.trim()&&e.llmModel.trim()):t||!!e.llmApiKey.trim()}function ol(e){if(!e||typeof e!="object")return{settings:It};const{settings:t}=e;if(!t)return{settings:It};const{openaiApiKey:r,...o}=t,a=o.llmApiKey??r??"";return{settings:{...It,...o,llmApiKey:a}}}const ft=ar()(ir(e=>({settings:{...It},updateSettings:t=>e(r=>({settings:{...r.settings,...t}})),clearApiKey:()=>e(t=>({settings:{...t.settings,llmApiKey:""}}))}),{name:"llm-settings",version:2,migrate:e=>ol(e)}));function _l(){const e=ft(l=>l.settings),t=ft(l=>l.updateSettings),r=ft(l=>l.clearApiKey),[o,a]=s.useState({hasEnvKey:!1,hasOpenRouterKey:!1,hasKilocodeKey:!1,hasUserKey:!!e.llmApiKey,isAvailable:Xn(e,!1),isLoading:!0,error:null});s.useEffect(()=>{let l=!1;async function c(){try{const u=await fetch("/api/llm-features");if(!u.ok)throw new Error("Failed to check LLM status");const d=await u.json();if(l)return;const f=!!e.llmApiKey,m=e.llmProvider==="openrouter"?!!d.hasOpenRouterKey:e.llmProvider==="kilocode"?!!d.hasKilocodeKey:d.hasEnvKey;a({hasEnvKey:d.hasEnvKey,hasOpenRouterKey:!!d.hasOpenRouterKey,hasKilocodeKey:!!d.hasKilocodeKey,hasUserKey:f,isAvailable:Xn(e,m),isLoading:!1,error:null})}catch(u){if(l)return;a(d=>({...d,isLoading:!1,error:u instanceof Error?u.message:"Failed to check status"}))}}return c(),()=>{l=!0}},[e.llmApiKey,e.llmProvider,e.llmBaseUrl,e.llmModel]);const i=s.useCallback(async l=>{try{const c=Ir({...e,llmApiKey:l}),d=await(await fetch("/api/llm-features",{method:"POST",headers:{"Content-Type":"application/json",...c},body:JSON.stringify({action:"test"})})).json();return d.ok?{valid:d.valid??!1,error:d.error}:{valid:!1,error:d.error||"Test failed"}}catch(c){return{valid:!1,error:c instanceof Error?c.message:"Network error"}}},[e]);return{settings:e,updateSettings:t,clearApiKey:r,status:o,testApiKey:i}}function Ir(e){const t=e.llmApiKey,r=rl(e),o=sl(e);return t?{"X-OpenAI-API-Key":t,...r?{"X-LLM-Base-URL":r}:{},...o?{"X-LLM-Model":o}:{}}:{...r?{"X-LLM-Base-URL":r}:{},...o?{"X-LLM-Model":o}:{}}}function il(){const e=ft.getState().settings;return Ir(e)}function al(){const e=ft(d=>d.settings),[t,r]=s.useState(!1),[o,a]=s.useState(null),[i,l]=s.useState(null),c=s.useRef(null);return{generateTitle:s.useCallback(async d=>{c.current&&c.current.abort();const f=new AbortController;c.current=f,r(!0);try{const m={"Content-Type":"application/json",...il()},p=await fetch("/api/llm-features",{method:"POST",headers:m,body:JSON.stringify({action:"title",message:d}),signal:f.signal});if(!p.ok)throw new Error(`API error: ${p.status}`);const h=await p.json();if(f.signal.aborted)throw new Error("Aborted");const v=h.title||d.slice(0,50),g=v.length>64?v.slice(0,61)+"...":v,j=h.source||"heuristic";return a(g),l(j),{title:g,source:j,error:h.error}}catch(m){if(m instanceof Error&&m.name==="AbortError")throw m;const p=ll(d);return a(p),l("heuristic"),{title:p,source:"heuristic",error:m instanceof Error?m.message:"Unknown error"}}finally{r(!1),c.current===f&&(c.current=null)}},[e.llmApiKey,e.llmBaseUrl,e.llmModel,e.llmProvider]),isGenerating:t,lastTitle:o,lastSource:i}}function ll(e){let t=e.replace(/```[\s\S]*?```/g," ");t=t.replace(/`[^`]+`/g," "),t=t.replace(/https?:\/\/[^\s]+/g," "),t=t.replace(/[^\w\s.,!?'-]/g," "),t=t.replace(/\s+/g," ").trim();let a=t.split(/\s+/).filter(i=>{if(i.length<=2){const l=i.toUpperCase();return["AI","ML","UI","UX","API","CSS","JS"].includes(l)}return!0}).slice(0,6).join(" ");return a=a.replace(/[.,!?]+$/,""),a.length>60&&(a=a.slice(0,57)+"..."),a||e.slice(0,50)}function cl(){return ft(e=>e.settings.useLlmTitles)}const Gt={active:!1,text:"",tools:[],sessionKey:null};function ul(e){const[t,r]=s.useState(Gt),o=s.useRef(null),a=s.useRef(null),i=s.useRef(null),l=s.useRef(null),c=s.useRef(!1),u=s.useRef(e.onDone),d=s.useRef(e.onError),f=s.useRef(e.onAssistantDelta);u.current=e.onDone,d.current=e.onError,f.current=e.onAssistantDelta;function m(){i.current&&(window.clearTimeout(i.current),i.current=null),a.current&&(window.clearInterval(a.current),a.current=null)}function p(g,j){a.current||(a.current=window.setInterval(async()=>{try{const w=await fetch(`/api/history?sessionKey=${encodeURIComponent(g)}`);if(!w.ok)return;const y=await w.json();if(!(Array.isArray(y.messages)?y.messages:[]).some(z=>!z||z.role!=="assistant"||typeof z.timestamp!="number"?!1:z.timestamp>j-3e3))return;o.current&&(o.current.close(),o.current=null),m(),r(z=>({...z,active:!1})),u.current(g)}catch{}},2e3))}const h=s.useCallback(g=>{if(c.current=!0,m(),o.current&&(o.current.close(),o.current=null),g?.preserveState){r(j=>({...j,active:!1}));return}r(Gt)},[]),v=s.useCallback(function(j){c.current=!1,m(),l.current=Date.now(),o.current&&(o.current.close(),o.current=null),r({active:!0,text:"",tools:[],sessionKey:j});const w=new EventSource(`/api/stream?sessionKey=${encodeURIComponent(j)}`);o.current=w,w.addEventListener("delta",y=>{try{const P=JSON.parse(y.data);r(M=>({...M,text:M.text+P.text})),f.current?.({text:P.text,sessionKey:P.sessionKey})}catch{}}),w.addEventListener("tool",y=>{try{const P=JSON.parse(y.data);r(M=>{const z=M.tools.findIndex(J=>J.id===P.id),T=[...M.tools];return z>=0?T[z]={name:P.name,status:P.status,id:P.id}:T.push({name:P.name,status:P.status,id:P.id}),{...M,tools:T}})}catch{}}),w.addEventListener("done",y=>{try{const P=JSON.parse(y.data);c.current=!0,m(),w.close(),o.current=null,r(M=>({...M,active:!1})),u.current(P.sessionKey)}catch{}}),w.onerror=()=>{w.readyState===EventSource.CLOSED&&(w.close(),o.current=null,r(Gt),d.current?.("Stream connection lost"))},i.current=window.setTimeout(()=>{if(c.current)return;const y=l.current??Date.now();p(j,y)},3e3)},[]);return{streaming:t,startStream:v,stopStream:h}}function dl(e){const t=s.useCallback(r=>{const o=r.target,a=o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable;if(r.key==="Escape"){e.onEscape?.();return}if(r.key==="?"&&!a&&!r.metaKey&&!r.ctrlKey){r.preventDefault(),e.onShowHelp?.();return}if(a)return;const l=navigator.platform.toUpperCase().indexOf("MAC")>=0?r.metaKey:r.ctrlKey;if(l&&r.key==="k"&&!r.shiftKey){r.preventDefault(),e.onNewChat?.();return}if(l&&r.key==="/"){r.preventDefault(),e.onFocusInput?.();return}if(l&&r.shiftKey&&r.key==="C"){r.preventDefault(),e.onCopyLastResponse?.();return}if(l&&r.key==="f"&&!r.shiftKey){r.preventDefault(),e.onSearch?.();return}if(l&&r.shiftKey&&r.key==="F"){r.preventDefault(),e.onSearchGlobal?.();return}},[e]);s.useEffect(()=>(window.addEventListener("keydown",t),()=>{window.removeEventListener("keydown",t)}),[t])}function Bn(e){const{threshold:t=50,edgeWidth:r,onMove:o,onSwipe:a,onCancel:i,direction:l,enabled:c=!0}=e,u=s.useRef({startX:0,startY:0,tracking:!1,directionLocked:!1}),d=s.useCallback(p=>{if(!c)return;const h=p.touches[0];h&&(r!==void 0&&h.clientX>r||(u.current={startX:h.clientX,startY:h.clientY,tracking:!0,directionLocked:!1}))},[c,r]),f=s.useCallback(p=>{const h=u.current;if(!h.tracking)return;const v=p.touches[0];if(!v)return;const g=v.clientX-h.startX,j=v.clientY-h.startY,w=Math.abs(g),y=Math.abs(j);if(!h.directionLocked){if(w<5&&y<5)return;if(y>w){h.tracking=!1,i?.();return}h.directionLocked=!0}l==="left"&&g>0||l==="right"&&g<0||(p.preventDefault(),o?.(g))},[l,o,i]),m=s.useCallback(p=>{const h=u.current;if(!h.tracking)return;h.tracking=!1;const v=p.changedTouches[0];if(!v){i?.();return}const g=v.clientX-h.startX,j=Math.abs(g);if(!h.directionLocked||j<t){i?.();return}const w=g>0?"right":"left";if(l&&w!==l){i?.();return}a(w)},[l,i,a,t]);return{onTouchStart:d,onTouchMove:f,onTouchEnd:m}}const Mr="opencami-browser-notifications-enabled",Vt="opencami-browser-notifications-permission-asked",fl=5e3;function Ct(){return typeof window<"u"&&"Notification"in window}function Yn(){if(typeof window>"u")return!1;try{return localStorage.getItem(Mr)==="true"}catch{return!1}}function ml(){const e=Pt(),t=s.useRef(0),[r,o]=s.useState(()=>Yn()),a=s.useCallback(async()=>{if(!Ct())return"denied";try{return await Notification.requestPermission()}catch{return"denied"}},[]),i=s.useCallback(async c=>{o(c);try{localStorage.setItem(Mr,String(c))}catch{}if(c&&Ct()&&Notification.permission==="default"){await a();try{localStorage.setItem(Vt,"true")}catch{}}},[a]),l=s.useCallback(c=>{if(!r||!Ct()||document.hidden!==!0||Notification.permission!=="granted")return;const u=Date.now();if(u-t.current<fl)return;t.current=u;const d=c.text.slice(0,100),f=new Notification("OpenCami",{body:d,icon:"/pwa-192x192.png"});f.onclick=()=>{window.focus(),e({to:"/chat/$sessionKey",params:{sessionKey:c.sessionFriendlyId}}),f.close()}},[r,e]);return s.useEffect(()=>{if(!Ct())return;const c=()=>{if(Notification.permission!=="default")return;let d=!1;try{d=localStorage.getItem(Vt)==="true"}catch{d=!1}d||a().finally(()=>{try{localStorage.setItem(Vt,"true")}catch{}})},u={once:!0,passive:!0};return window.addEventListener("pointerdown",c,u),window.addEventListener("keydown",c,{once:!0}),()=>{window.removeEventListener("pointerdown",c),window.removeEventListener("keydown",c)}},[a]),s.useEffect(()=>{const c=()=>o(Yn());return window.addEventListener("storage",c),()=>window.removeEventListener("storage",c)},[]),{notificationsEnabled:r,setNotificationsEnabled:i,requestNotificationPermission:a,maybeNotifyAssistantMessage:l}}const pl=s.lazy(()=>et(()=>import("./keyboard-shortcuts-dialog-BX-hH4Wf.js"),__vite__mapDeps([29,1,4,3,5,6,7,8,9,2])).then(e=>({default:e.KeyboardShortcutsDialog}))),hl=s.lazy(()=>et(()=>import("./search-dialog-B3XJLq-O.js"),__vite__mapDeps([30,1,3,4,5,6,7,8,9,2,17,18,14,19,11,15,20,13,21,22,23,16,24])).then(e=>({default:e.SearchDialog}))),Nt="opencami-search-jump-target";function gl({activeFriendlyId:e,isNewChat:t=!1,onSessionResolved:r,forcedSessionKey:o}){const a=Pt(),i=mt(),[l,c]=s.useState(!1),[u,d]=s.useState(!1),[f,m]=s.useState(null),[p,h]=s.useState(!1),{headerRef:v,composerRef:g,mainRef:j,pinGroupMinHeight:w,headerHeight:y}=Ja(),[P,M]=s.useState(()=>$t()||Ht()),[z,T]=s.useState(()=>$t()||Ht()),[J,X]=s.useState(!1),[H,te]=s.useState(!1),[U,S]=s.useState("global"),[C,k]=s.useState(null),[R,_]=s.useState(!1),A=an(b=>b.level),{maybeNotifyAssistantMessage:W}=ml(),E=s.useRef(null),D=s.useRef(null),x=s.useRef(null),L=s.useRef(""),K=s.useRef(()=>{}),G=s.useRef(!1),q=s.useRef(""),{isMobile:V}=el(i),{sessionsQuery:Q,sessions:se,activeExists:ne,activeSessionKey:B,activeTitle:ae,activeTokens:me,sessionsError:ee}=tl({activeFriendlyId:e,isNewChat:t,forcedSessionKey:o}),{historyQuery:ie,historyMessages:ge,displayMessages:pe,historyError:I,resolvedSessionKey:he,activeCanonicalKey:Ee,sessionKeyForHistory:ze}=Qa({activeFriendlyId:e,activeSessionKey:B,forcedSessionKey:o,isNewChat:t,isRedirecting:p,activeExists:ne,sessionsReady:Q.isSuccess,queryClient:i}),Ue=Mt({queryKey:Vr,queryFn:function(){return jn(i)},initialData:function(){return jn(i)},staleTime:1/0}),N=Mt({queryKey:["gateway","status"],queryFn:ao,retry:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1,refetchOnMount:"always"}),Y=s.useRef(Date.now()),F=N.error instanceof Error?N.error.message:N.data&&!N.data.ok?N.data.error||"Gateway unavailable":null,ue=F??ee??I,oe=s.useCallback(()=>{N.refetch()},[N]),re=Ue.data?.isSidebarCollapsed??!1,ve=Bn({enabled:V&&re,edgeWidth:40,threshold:50,direction:"right",onSwipe:()=>{Be(i,b=>({...b,isSidebarCollapsed:!1}))}}),tt=Bn({enabled:V&&!re,threshold:50,direction:"left",onSwipe:()=>{Be(i,b=>({...b,isSidebarCollapsed:!0}))}}),Te=s.useCallback(()=>{m(null),h(!0),a({to:"/new",replace:!0})},[a]),Pe=s.useCallback(()=>{D.current&&(window.clearInterval(D.current),D.current=null),x.current&&(window.clearTimeout(x.current),x.current=null)},[]),nt=s.useCallback(()=>{Pe(),yt(!1),M(!1),_(!1)},[Pe]),wt=cl(),{generateTitle:rt}=al(),st=s.useRef(new Set),pt=2e3,bt=2e3,St=s.useCallback(()=>{!e||t||(D.current&&window.clearInterval(D.current),_(!0),D.current=window.setInterval(()=>{K.current()},pt))},[e,t]),ht=s.useRef(()=>{}),vt=s.useRef(()=>{}),{streaming:je,startStream:le,stopStream:Se}=ul({onDone:b=>ht.current(b),onError:b=>vt.current(b),onAssistantDelta:({text:b})=>{q.current+=b,W({text:q.current,sessionFriendlyId:e})}});ht.current=s.useCallback(async b=>{await ie.refetch(),Se({preserveState:!0}),nt(),i.invalidateQueries({queryKey:fe.sessions})},[ie,i,Se,nt]),vt.current=s.useCallback(b=>{console.warn("[stream] SSE error, falling back to polling")},[]);const $e=s.useMemo(()=>{if(!je.text)return null;const b=[];for(const $ of je.tools)b.push({type:"toolCall",name:$.name,id:$.id});return b.push({type:"text",text:je.text}),{role:"assistant",content:b,id:"__streaming__",__streaming:!0,timestamp:Date.now()}},[je.text,je.tools]),gt=s.useMemo(()=>{if(!$e)return pe;const b=[...pe].map((ce,ye)=>({message:ce,index:ye})).filter(({message:ce})=>ce.role==="assistant").map(({index:ce})=>ce).pop(),$=[...pe].map((ce,ye)=>({message:ce,index:ye})).filter(({message:ce})=>ce.role==="user").map(({index:ce})=>ce).pop();if(typeof b=="number"&&(typeof $!="number"||b>$)&&typeof b=="number"){const ce=pe[b];if(Le(ce).length>=je.text.length)return pe;const _e=[...pe];return _e[b]=$e,_e}return[...pe,$e]},[pe,$e,je.text]),Ar=s.useMemo(()=>({}),[]);K.current=function(){ie.refetch()},s.useEffect(()=>{if(p){f&&m(null);return}if(ot){f&&m(null);return}if(Q.isSuccess&&!ne){f&&m(null);return}const b=ee??I??F;if(!b){f?.startsWith("Failed to load")&&m(null);return}Tn(b)&&a({to:"/connect",replace:!0});const $=ee?`Failed to load sessions. ${ee}`:I?`Failed to load history. ${I}`:F?`Gateway unavailable. ${F}`:null;$&&m($)},[f,F,I,p,a,ee]);const ot=!t&&!o&&!cr(e)&&Q.isSuccess&&se.length>0&&!se.some(b=>b.friendlyId===e)&&!ie.isFetching&&!ie.isSuccess;s.useEffect(()=>{if(p){if(t){h(!1);return}!ot&&Q.isSuccess&&h(!1)}},[t,p,Q.isSuccess,ot]),s.useEffect(()=>{t||Q.isSuccess&&se.length!==0&&ot&&(Dt(),en(i,e,ze),a({to:"/new",replace:!0}))},[e,ie.isFetching,ie.isSuccess,t,a,i,ze,se,Q.isSuccess,ot]);const hn=ot||p,jt=s.useRef("fast");s.useEffect(()=>{const b=[...ge].reverse().find(de=>de.role==="assistant");if(!b)return;const $=`${ge.length}:${Le(b).slice(-64)}`;$!==L.current&&(L.current=$,jt.current!=="fast"&&D.current&&(window.clearInterval(D.current),D.current=window.setInterval(()=>{K.current()},pt),jt.current="fast"),x.current&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{D.current&&(window.clearInterval(D.current),D.current=window.setInterval(()=>{K.current()},bt),jt.current="slow"),x.current=window.setTimeout(()=>{nt(),jt.current="fast"},3e3)},1500))},[ge,nt]),s.useEffect(()=>{if(!wt||t||p)return;const b=o||he||B;if(!b||st.current.has(b))return;const $=ge.filter(ye=>ye.role==="user"),de=ge.filter(ye=>ye.role==="assistant");if($.length===0||de.length===0||$.length!==1)return;const ce=Le($[0]);!ce||ce.length<5||(st.current.add(b),(async()=>{try{const ye=await rt(ce);ye.title&&await po(i,b,e,ye.title)}catch(ye){console.error("[smart-title] Error generating title:",ye)}})())},[wt,t,p,o,he,B,e,ge,rt,i]),s.useEffect(()=>{if(t||e){if(Pe(),Se(),L.current="",_(!1),G.current){G.current=!1;return}if($t()||Ht()){M(!0),T(!0);return}M(!1),T(!1)}},[e,t,Pe,Se]),s.useEffect(()=>{if(!(typeof window>"u"))try{const b=sessionStorage.getItem(Nt);if(!b){k(null);return}const $=JSON.parse(b);if(typeof $.at=="number"&&Date.now()-$.at>300*1e3){sessionStorage.removeItem(Nt),k(null);return}if($.friendlyId===e&&typeof $.messageId=="string"&&$.messageId.length>0){k($.messageId),sessionStorage.removeItem(Nt);return}k(null)}catch{k(null)}},[e]),s.useLayoutEffect(()=>{if(t)return;const b=wo(o||he||B,e);if(!b)return;G.current=!0;const $=fe.history(b.friendlyId,b.sessionKey),de=i.getQueryData($);(Array.isArray(de?.messages)?de.messages:[]).some(_e=>!!(b.optimisticMessage.clientId&&(_e.clientId===b.optimisticMessage.clientId||_e.__optimisticId===b.optimisticMessage.clientId)||b.optimisticMessage.__optimisticId&&_e.__optimisticId===b.optimisticMessage.__optimisticId))||Ut(i,b.friendlyId,b.sessionKey,b.optimisticMessage),M(!0),T(!0),zt(b.sessionKey,b.friendlyId,b.message,!0,b.attachments)},[e,B,o,t,i,he]);function zt(b,$,de,ce=!1,ye,_e){let it="";if(!ce){const{clientId:xe,optimisticMessage:at}=Rn(de,ye);it=xe,Ut(i,$,b,at),fo(i,b,$,at)}yt(!0),c(!0),m(null),M(!0),T(!0);const Fe=ye?.map(xe=>({mimeType:xe.file.type,content:xe.base64}));q.current="",St(),fetch("/api/send",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({sessionKey:b,friendlyId:$,message:de,thinking:A,idempotencyKey:crypto.randomUUID(),attachments:Fe,model:_e||void 0})}).then(async xe=>{if(!xe.ok)throw new Error(await Ke(xe));const vn=(await xe.json()).sessionKey||b||$;le(vn)}).catch(xe=>{const at=xe instanceof Error?xe.message:String(xe);if(Tn(at)){a({to:"/connect",replace:!0});return}it&&lo(i,$,b,it,function(Xr){return{...Xr,status:"error"}}),m(`Failed to send message. ${at}`),yt(!1),M(!1),T(!1)}).finally(()=>{c(!1)})}const gn=s.useCallback(async()=>{d(!0);try{const b=await fetch("/api/sessions",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({})});if(!b.ok)throw new Error(await Ke(b));const $=await b.json(),de=typeof $.sessionKey=="string"?$.sessionKey:"",ce=typeof $.friendlyId=="string"&&$.friendlyId.trim().length>0?$.friendlyId.trim():Jt(de);if(!de||!ce)throw new Error("Invalid session response");return i.invalidateQueries({queryKey:fe.sessions}),{sessionKey:de,friendlyId:ce}}finally{d(!1)}},[i]),Dr=s.useCallback((b,$)=>{const de=$.attachments;if(b.length===0&&(!de||de.length===0))return;if($.reset(),t){const{clientId:ye,optimisticId:_e,optimisticMessage:it}=Rn(b,de);Ut(i,"new","new",it),yt(!0),c(!0),M(!0),T(!0),gn().then(({sessionKey:Fe,friendlyId:xe})=>{if(xo(xe),go({sessionKey:Fe,friendlyId:xe,message:b,optimisticMessage:it,attachments:de}),r){r({sessionKey:Fe,friendlyId:xe});return}a({to:"/chat/$sessionKey",params:{sessionKey:xe},replace:!0})}).catch(Fe=>{co(i,"new","new",ye,_e),$.setValue(b),m(`Failed to create session. ${Fe instanceof Error?Fe.message:String(Fe)}`),yt(!1),M(!1),T(!1),c(!1)});return}zt(o||he||B,e,b,!1,de,$.model)},[e,B,gn,o,t,a,r,i,he]),yn=s.useCallback(()=>{M(!1),T(!1),en(i,"new","new"),a({to:"/new"}),V&&Be(i,function($){return{...$,isSidebarCollapsed:!0}})},[V,a,i]),Or=s.useCallback(()=>{Be(i,function($){return{...$,isSidebarCollapsed:!$.isSidebarCollapsed}})},[i]),Lr=s.useCallback(()=>{V&&Be(i,function($){return{...$,isSidebarCollapsed:!0}})},[V,i]),Pr=s.useCallback(()=>{Be(i,function($){return{...$,isSidebarCollapsed:!1}})},[i]),_r=s.useCallback(b=>{if(t||!b.trim())return;const $=o||he||B;$&&zt($,e,b.trim())},[e,B,o,t,he]),Kr=s.useCallback(()=>{E.current?.focus()},[]),zr=s.useCallback(()=>{if(J){X(!1);return}document.activeElement instanceof HTMLElement&&document.activeElement.blur()},[J]),Ur=s.useCallback(()=>{const b=[...pe].reverse().find(de=>de.role==="assistant");if(!b)return;const $=Le(b);$&&navigator.clipboard.writeText($).catch(()=>{})},[pe]),$r=s.useCallback(()=>{X(!0)},[]),Hr=s.useCallback(()=>{S(t?"global":"current"),te(!0)},[t]),xn=s.useCallback(()=>{S("global"),te(!0)},[]);dl({onNewChat:yn,onFocusInput:Kr,onEscape:zr,onCopyLastResponse:Ur,onShowHelp:$r,onSearch:Hr,onSearchGlobal:xn});const wn=ie.isLoading&&!ie.data||p,bn=!!F&&N.errorUpdatedAt>Y.current,Fr=!wn&&pe.length===0,Wr=s.useMemo(()=>!bn||!ue?null:n.jsx(qa,{state:"error",error:ue,onRetry:oe}),[ue,oe,bn]),Sn=n.jsx(Li,{sessions:se,activeFriendlyId:e,activeSessionKey:ze,creatingSession:u,onCreateSession:yn,isCollapsed:V?!1:re,onToggleCollapse:Or,onSelectSession:Lr,onActiveSessionDelete:Te,onOpenSearch:xn});return n.jsxs("div",{className:"h-screen bg-surface text-primary-900",children:[n.jsxs("div",{className:O("h-full overflow-hidden",V?"relative":"grid grid-cols-[auto_minmax(0,1fr)]"),children:[hn?null:V?n.jsxs(n.Fragment,{children:[!re&&n.jsx("div",{className:"fixed inset-0 z-40 bg-black/40 transition-opacity duration-200",onClick:()=>Be(i,b=>({...b,isSidebarCollapsed:!0})),...tt}),n.jsx("div",{className:O("fixed inset-y-0 left-0 z-50 w-[var(--opencami-sidebar-width)] transition-transform duration-150 safe-area-top",re?"-translate-x-full":"translate-x-0"),...tt,children:Sn})]}):Sn,n.jsxs("main",{className:"flex flex-col h-full min-h-0 min-w-0 overflow-x-hidden",ref:j,...ve,children:[n.jsx(zi,{activeTitle:ae,wrapperRef:v,showSidebarButton:V,onOpenSidebar:Pr,totalTokens:me.totalTokens,contextTokens:me.contextTokens}),hn?null:n.jsxs(n.Fragment,{children:[n.jsx(wa,{messages:gt,loading:wn,empty:Fr,notice:Wr,noticePosition:"end",waitingForResponse:P,isStreaming:R,sessionKey:Ee,pinToTop:z,pinGroupMinHeight:w,headerHeight:y,contentStyle:Ar,onFollowUpClick:_r,jumpToMessageId:C}),n.jsx(Ga,{onSubmit:Dr,isLoading:l,disabled:l,wrapperRef:g,inputRef:E})]})]})]}),J&&n.jsx(s.Suspense,{fallback:null,children:n.jsx(pl,{open:J,onOpenChange:X})}),H&&n.jsx(s.Suspense,{fallback:null,children:n.jsx(hl,{open:H,onOpenChange:te,sessions:se,currentFriendlyId:e,currentSessionKey:B,mode:U,onJumpToMessage:b=>{if(te(!1),!!b.friendlyId){if(b.messageId&&b.friendlyId===e){k(b.messageId);return}if(b.messageId&&typeof window<"u")try{sessionStorage.setItem(Nt,JSON.stringify({friendlyId:b.friendlyId,messageId:b.messageId,at:Date.now()}))}catch{}a({to:"/chat/$sessionKey",params:{sessionKey:b.friendlyId}})}}})})]})}function yl(){const e=mt(),t=Pt(),[r,o]=s.useState(null),a=Gr.useParams(),i=typeof a.sessionKey=="string"?a.sessionKey:"main",l=i==="new",c=r?.friendlyId===i?r.sessionKey:void 0,u=s.useCallback(function(f){uo(e,"new","new",f.friendlyId,f.sessionKey),o({friendlyId:f.friendlyId,sessionKey:f.sessionKey}),t({to:"/chat/$sessionKey",params:{sessionKey:f.friendlyId},replace:!0})},[t,e]);return n.jsx(gl,{activeFriendlyId:i,isNewChat:l,forcedSessionKey:c,onSessionResolved:l?u:void 0})}const Kl=Object.freeze(Object.defineProperty({__proto__:null,component:yl},Symbol.toStringTag,{value:"Module"}));export{Kl as $,tn as C,nn as a,rn as b,fe as c,ft as d,il as e,Rr as g,_l as u};
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/agents-screen-DpNSh5Ok.js","assets/main-DBmooBKx.js","assets/useQuery-CtUiG53w.js","assets/button-DdG8c-XQ.js","assets/switch-kXs1I0oW.js","assets/useControlled-8D4PSDAL.js","assets/useBaseUiId-Ckx_aJky.js","assets/visuallyHidden-COI6QeQH.js","assets/tooltip-CtHpm-sQ.js","assets/popupStateMapping-CGDLUl5Y.js","assets/event-Dwf9IDxK.js","assets/DirectionContext-B1cuzwIr.js","assets/opencami-logo-BV1uPYe6.js","assets/proxy-DYrSkM35.js"])))=>i.map(i=>d[i]);
2
- import{j as e,r as t,_ as r}from"./main-DBmooBKx.js";const n=t.lazy(()=>r(()=>import("./agents-screen-DpNSh5Ok.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13])).then(s=>({default:s.AgentsScreen})));function o(){return e.jsx(t.Suspense,{fallback:e.jsx("div",{className:"flex h-screen items-center justify-center text-primary-500 text-sm",children:"Loading…"}),children:e.jsx(n,{})})}export{o as component};
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/bots-screen-Qh_IK9hC.js","assets/main-DBmooBKx.js","assets/button-DdG8c-XQ.js","assets/switch-kXs1I0oW.js","assets/useControlled-8D4PSDAL.js","assets/useBaseUiId-Ckx_aJky.js","assets/visuallyHidden-COI6QeQH.js","assets/useQuery-CtUiG53w.js","assets/useMutation-DckvFKPC.js","assets/proxy-DYrSkM35.js"])))=>i.map(i=>d[i]);
2
- import{j as e,r as t,_ as r}from"./main-DBmooBKx.js";const n=t.lazy(()=>r(()=>import("./bots-screen-Qh_IK9hC.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])).then(s=>({default:s.BotsScreen})));function a(){return e.jsx(t.Suspense,{fallback:e.jsx("div",{className:"flex h-screen items-center justify-center text-sm text-primary-500",children:"Loading…"}),children:e.jsx(n,{})})}export{a as component};
@@ -1 +0,0 @@
1
- import{j as e}from"./main-DBmooBKx.js";import{u as d}from"./useQuery-CtUiG53w.js";async function n(s){const a=await fetch(s);if(!a.ok){const t=await a.json().catch(()=>({}));throw new Error(t.error||`Request failed: ${a.status}`)}return await a.json()}function i(s){return`${(s/1024**3).toFixed(1)} GB`}function u(s){return new Intl.NumberFormat(void 0,{notation:"compact",maximumFractionDigits:1}).format(s)}function y(s){return`$${s.toFixed(3)}`}function j(s){if(!s)return"—";const a=new Date(s);return Number.isNaN(a.getTime())?"—":a.toLocaleString()}function f(s){return s<60?"#10b981":s<=80?"#f59e0b":"#ef4444"}function c({percent:s}){const a=Math.max(0,Math.min(100,s));return e.jsx("div",{className:"h-2 w-full rounded-full bg-primary-200 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all duration-300",style:{width:`${a}%`,backgroundColor:f(a)}})})}function l(){return e.jsxs("div",{className:"rounded-xl border border-primary-200 bg-primary-100 p-4 animate-pulse space-y-3",children:[e.jsx("div",{className:"h-4 w-32 bg-primary-200 rounded"}),e.jsx("div",{className:"h-10 bg-primary-200 rounded"}),e.jsx("div",{className:"h-10 bg-primary-200 rounded"}),e.jsx("div",{className:"h-10 bg-primary-200 rounded"})]})}function v(){const s=d({queryKey:["dashboard","system"],queryFn:()=>n("/api/dashboard/system"),refetchInterval:1e4}),a=d({queryKey:["dashboard","gateway"],queryFn:()=>n("/api/dashboard/gateway"),refetchInterval:1e4}),t=d({queryKey:["dashboard","crons"],queryFn:async()=>(await n("/api/dashboard/crons")).jobs,refetchInterval:1e4}),m=s.isError||a.isError||t.isError,o=s.data?.cpu??0,x=(s.data?.ram.total??0)>0?(s.data?.ram.used??0)/(s.data?.ram.total??1)*100:0,p=(s.data?.disk.total??0)>0?(s.data?.disk.used??0)/(s.data?.disk.total??1)*100:0;return e.jsxs("div",{className:"flex h-screen flex-col bg-surface text-primary-900",children:[e.jsxs("div",{className:"px-4 pt-4 pb-3 border-b border-primary-100",children:[e.jsx("h2",{className:"text-base font-semibold text-primary-900",children:"Dashboard"}),e.jsx("p",{className:"text-xs text-primary-500",children:"Live system and gateway overview (refreshes every 10s)"})]}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-auto p-4",children:[m&&e.jsx("div",{className:"mb-4 rounded-lg border border-red-300/40 bg-red-500/10 px-3 py-2 text-sm text-red-400",children:"Failed to load one or more widgets. Retrying automatically…"}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 lg:grid-cols-3",children:[s.isLoading?e.jsx(l,{}):e.jsxs("div",{className:"rounded-xl border border-primary-200 bg-primary-100 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"💻 System Stats"}),e.jsx("span",{className:"text-xs text-primary-500",children:"↻ auto-refresh"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-primary-500",children:[e.jsx("span",{children:"CPU"}),e.jsxs("span",{children:[o.toFixed(1),"% · ",s.data?.cores??0," ","cores"]})]}),e.jsx(c,{percent:o})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-primary-500",children:[e.jsx("span",{children:"RAM"}),e.jsxs("span",{children:[i(s.data?.ram.used??0)," /"," ",i(s.data?.ram.total??0)]})]}),e.jsx(c,{percent:x})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-primary-500",children:[e.jsx("span",{children:"Disk"}),e.jsxs("span",{children:[i(s.data?.disk.used??0)," /"," ",i(s.data?.disk.total??0)]})]}),e.jsx(c,{percent:p})]}),e.jsxs("div",{className:"border-t border-primary-200 pt-3 space-y-1.5 text-xs text-primary-500",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{children:"Load (1m/5m/15m)"}),e.jsxs("span",{children:[(s.data?.load?.[0]??0).toFixed(2)," ·"," ",(s.data?.load?.[1]??0).toFixed(2)," ·"," ",(s.data?.load?.[2]??0).toFixed(2)]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{children:"Uptime"}),e.jsx("span",{children:s.data?.uptime??"0m"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{children:"Net ↓ / ↑"}),e.jsxs("span",{children:[s.data?.network.rx??"0 MB"," /"," ",s.data?.network.tx??"0 MB"]})]}),e.jsxs("div",{className:"truncate",title:s.data?.cpuModel??"",children:["CPU: ",s.data?.cpuModel??"Unknown CPU"]})]}),e.jsxs("div",{className:"border-t border-primary-200 pt-3",children:[e.jsx("div",{className:"text-xs font-semibold text-primary-700 mb-2",children:"Top Processes"}),e.jsxs("div",{className:"space-y-1 text-xs",children:[(s.data?.topProcesses??[]).map((r,h)=>e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"truncate text-primary-700",children:r.name}),e.jsxs("span",{className:"text-primary-500 shrink-0",children:[r.cpu.toFixed(1),"% CPU · ",r.mem.toFixed(1),"% MEM"]})]},`${r.name}-${h}`)),(s.data?.topProcesses.length??0)===0&&e.jsx("div",{className:"text-primary-500",children:"No process data."})]})]})]}),a.isLoading?e.jsx(l,{}):e.jsxs("div",{className:"rounded-xl border border-primary-200 bg-primary-100 p-4 space-y-4",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Gateway Status"}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-primary-500",children:"Active sessions"}),e.jsx("span",{children:a.data?.activeSessions??0})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-primary-500",children:"Tokens today"}),e.jsx("span",{children:u(a.data?.tokensToday??0)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-primary-500",children:"Estimated cost"}),e.jsx("span",{children:y(a.data?.costToday??0)})]})]})]}),t.isLoading?e.jsx(l,{}):e.jsxs("div",{className:"rounded-xl border border-primary-200 bg-primary-100 p-4 flex flex-col min-h-[340px] max-h-[70vh]",children:[e.jsxs("h3",{className:"text-sm font-semibold mb-3",children:["🕐 Cron Jobs (",t.data?.length??0,")"]}),e.jsxs("div",{className:"space-y-2 overflow-auto pr-1",children:[(t.data??[]).map(r=>e.jsxs("div",{className:`rounded-md border border-primary-200 px-2.5 py-2 ${r.enabled?"opacity-100":"opacity-50 grayscale"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-sm truncate",children:r.name}),e.jsx("div",{className:"text-xs",children:r.enabled?r.lastStatus==="ok"?"✅":r.lastStatus==="error"?"❌":"—":"⏸️"})]}),e.jsxs("div",{className:"mt-1 text-xs text-primary-500",children:["Next: ",j(r.nextRun)]})]},r.id)),(t.data?.length??0)===0&&e.jsx("div",{className:"text-xs text-primary-500",children:"No cron jobs found."})]})]})]})]})]})}export{v as component};
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/file-explorer-screen-DzDX4HcB.js","assets/main-DBmooBKx.js","assets/useQuery-CtUiG53w.js","assets/button-DdG8c-XQ.js","assets/tooltip-CtHpm-sQ.js","assets/popupStateMapping-CGDLUl5Y.js","assets/useBaseUiId-Ckx_aJky.js","assets/event-Dwf9IDxK.js","assets/visuallyHidden-COI6QeQH.js","assets/DirectionContext-B1cuzwIr.js","assets/use-file-explorer-state-C-D2CShe.js","assets/composite-Cx-QHT9o.js","assets/react-dSDkXQu6.js","assets/proxy-DYrSkM35.js","assets/menu-ByR1BVmq.js","assets/useCompositeItem-CkvfeGmG.js","assets/useMutation-DckvFKPC.js"])))=>i.map(i=>d[i]);
2
- import{j as e,r,_ as s}from"./main-DBmooBKx.js";const n=r.lazy(()=>s(()=>import("./file-explorer-screen-DzDX4HcB.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])).then(t=>({default:t.FileExplorerScreen})));function o(){return e.jsx(r.Suspense,{fallback:e.jsx("div",{className:"flex h-screen items-center justify-center text-primary-500 text-sm",children:"Loading…"}),children:e.jsx(n,{})})}export{o as component};
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/memory-screen-1DgDLyZf.js","assets/main-DBmooBKx.js","assets/useQuery-CtUiG53w.js","assets/useMutation-DckvFKPC.js","assets/button-DdG8c-XQ.js","assets/markdown-Bpat4kTr.js","assets/index-BxsgifDH.js","assets/react-dSDkXQu6.js","assets/use-file-explorer-state-C-D2CShe.js","assets/useBaseUiId-Ckx_aJky.js","assets/event-Dwf9IDxK.js","assets/popupStateMapping-CGDLUl5Y.js","assets/visuallyHidden-COI6QeQH.js","assets/composite-Cx-QHT9o.js","assets/index-T4TOjvD0.js"])))=>i.map(i=>d[i]);
2
- import{j as e,r,_ as s}from"./main-DBmooBKx.js";const n=r.lazy(()=>s(()=>import("./memory-screen-1DgDLyZf.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14])).then(t=>({default:t.MemoryScreen})));function a(){return e.jsx(r.Suspense,{fallback:e.jsx("div",{className:"flex h-screen items-center justify-center text-primary-500 text-sm",children:"Loading…"}),children:e.jsx(n,{})})}export{a as component};
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/skills-panel-Cj7yHGbX.js","assets/main-DBmooBKx.js","assets/button-DdG8c-XQ.js","assets/tabs-B6GW7TBf.js","assets/useControlled-8D4PSDAL.js","assets/useBaseUiId-Ckx_aJky.js","assets/useCompositeItem-CkvfeGmG.js","assets/DirectionContext-B1cuzwIr.js","assets/event-Dwf9IDxK.js","assets/composite-Cx-QHT9o.js","assets/CSPContext-nHSyQniZ.js"])))=>i.map(i=>d[i]);
2
- import{j as e,r as t,_ as r}from"./main-DBmooBKx.js";const l=t.lazy(()=>r(()=>import("./skills-panel-Cj7yHGbX.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10])).then(s=>({default:s.SkillsPanel})));function a(){return e.jsx(t.Suspense,{fallback:e.jsx("div",{className:"flex h-screen items-center justify-center text-primary-500 text-sm",children:"Loading…"}),children:e.jsx(l,{})})}export{a as component};