opencami 1.8.6 → 1.8.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{CSPContext-6t3O1emU.js → CSPContext-KDlbpvjX.js} +1 -1
- package/dist/client/assets/{DirectionContext-C6goXEY_.js → DirectionContext-DZNUWW6F.js} +1 -1
- package/dist/client/assets/_sessionKey-CPRycepq.js +19 -0
- package/dist/client/assets/agents-Bp6Cn1BH.js +2 -0
- package/dist/client/assets/{agents-screen-pHUzJxX5.js → agents-screen-Du8b4SRW.js} +1 -1
- package/dist/client/assets/bots-Dl65yZDx.js +2 -0
- package/dist/client/assets/bots-screen-CvbAVMk0.js +1 -0
- package/dist/client/assets/{button-CK8tKQ-Z.js → button-BxDVif49.js} +1 -1
- package/dist/client/assets/{composite-feK0c-xF.js → composite-t7Eu0qB0.js} +1 -1
- package/dist/client/assets/{connect-02tmQV_v.js → connect-Btonx7l6.js} +1 -1
- package/dist/client/assets/{dashboard-DQ0zDQKd.js → dashboard-Dz6Uyyke.js} +1 -1
- package/dist/client/assets/{event-BsD1rqGT.js → event-DeooaZzN.js} +1 -1
- package/dist/client/assets/{file-explorer-screen-Ds7LeJTd.js → file-explorer-screen-BnOINWSL.js} +1 -1
- package/dist/client/assets/files-Cf87gXsq.js +2 -0
- package/dist/client/assets/follow-up-suggestions-DP_84nA2.js +5 -0
- package/dist/client/assets/index-nheqha2z.js +3 -0
- package/dist/client/assets/{index-lK3yGoTI.js → index-yPOt98v7.js} +1 -1
- package/dist/client/assets/{keyboard-shortcuts-dialog-Bb_GOr9L.js → keyboard-shortcuts-dialog-BzL7ZJUb.js} +1 -1
- package/dist/client/assets/{main-Dq6jpr6-.js → main-DJgQwVqD.js} +3 -3
- package/dist/client/assets/{markdown-C7_Aipwd.js → markdown-CFbW7h0Q.js} +14 -14
- package/dist/client/assets/memory-kYdhgbRR.js +2 -0
- package/dist/client/assets/{memory-screen-CUFBWsq5.js → memory-screen-BKYBnY-V.js} +1 -1
- package/dist/client/assets/{menu-n6L--M9R.js → menu-CnihCZ4y.js} +1 -1
- package/dist/client/assets/{opencami-logo-zuSBm5Br.js → opencami-logo-CoCA2JIf.js} +1 -1
- package/dist/client/assets/{proxy-BU8Bw1Vt.js → proxy-C2vtPufK.js} +1 -1
- package/dist/client/assets/{react-BLyCEWpN.js → react-DzPMbcP8.js} +1 -1
- package/dist/client/assets/{search-dialog-yB4w5ajo.js → search-dialog-CDAdFAQI.js} +1 -1
- package/dist/client/assets/search-sources-badge-DOd5AI-i.js +1 -0
- package/dist/client/assets/{session-export-dialog-qbZgd2Zo.js → session-export-dialog-Cf8eisLM.js} +1 -1
- package/dist/client/assets/{settings-dialog-CHJbvpgk.js → settings-dialog-CB1OiRWU.js} +1 -1
- package/dist/client/assets/skills-D6MaebJh.js +2 -0
- package/dist/client/assets/{skills-panel-BH27r3nC.js → skills-panel-_M5k5dty.js} +1 -1
- package/dist/client/assets/styles-BNkOWk4R.css +1 -0
- package/dist/client/assets/{switch-BD3a0LRm.js → switch-LzFh8co4.js} +1 -1
- package/dist/client/assets/{tabs-DI1e-kzz.js → tabs-D9o7Irvl.js} +1 -1
- package/dist/client/assets/thinking-BqZoM6BP.js +1 -0
- package/dist/client/assets/{tooltip-BbH3QWvK.js → tooltip-D64CzFXa.js} +1 -1
- package/dist/client/assets/{use-file-explorer-state-DBfLeAyz.js → use-file-explorer-state-Tzex8EEL.js} +2 -2
- package/dist/client/assets/{useBaseUiId-MgM4ouhx.js → useBaseUiId-CMJ8I9al.js} +1 -1
- package/dist/client/assets/useCompositeItem-CSriPK0T.js +1 -0
- package/dist/client/assets/{useControlled-BQxTgsOd.js → useControlled-KFa25CcD.js} +1 -1
- package/dist/client/assets/{useMutation-12DyB3Ox.js → useMutation-Bd89JWif.js} +1 -1
- package/dist/client/assets/{useOnFirstRender-7qoaK5sI.js → useOnFirstRender-DqnUCnnL.js} +1 -1
- package/dist/client/assets/{useQuery-Ctiljcrr.js → useQuery-DhR_UXNX.js} +1 -1
- package/dist/server/assets/{_sessionKey-DzsJfprr.js → _sessionKey-BzM-igv7.js} +405 -703
- package/dist/server/assets/{_tanstack-start-manifest_v-C5HBDfQB.js → _tanstack-start-manifest_v-Bfnqdswf.js} +1 -1
- package/dist/server/assets/{connect-CbgijWz4.js → connect-BNabuqpW.js} +1 -1
- package/dist/server/assets/follow-up-suggestions-DhBZIszK.js +336 -0
- package/dist/server/assets/{index-Dl2BOKP7.js → index-BEWnDAH6.js} +24 -5
- package/dist/server/assets/{index-BFHEmXpN.js → index-DCMpnyEo.js} +1 -1
- package/dist/server/assets/{markdown-BFE5y9YH.js → markdown-DoX5Q7qh.js} +50 -26
- package/dist/server/assets/{memory-BqZOoD7Q.js → memory-Cxu7i8ej.js} +1 -1
- package/dist/server/assets/{memory-screen-BK5phS8K.js → memory-screen-B5l1NZRY.js} +2 -2
- package/dist/server/assets/{router-BZPatFG9.js → router-BqPDQeCx.js} +5 -5
- package/dist/server/assets/{search-dialog-DQRkARXw.js → search-dialog-DtYc9e4N.js} +4 -4
- package/dist/server/assets/search-sources-badge-B0rAEDs_.js +106 -0
- package/dist/server/assets/{settings-dialog-Bc1ta26X.js → settings-dialog-BQzn6fyF.js} +4 -4
- package/dist/server/assets/thinking-D6q1tJkk.js +92 -0
- package/dist/server/server.js +2 -2
- package/package.json +1 -1
- package/dist/client/assets/_sessionKey-B5Viv43f.js +0 -23
- package/dist/client/assets/agents-BmE6QOwl.js +0 -2
- package/dist/client/assets/bots-BeOkwrXr.js +0 -2
- package/dist/client/assets/bots-screen-B79bAYvf.js +0 -1
- package/dist/client/assets/files-e40B1zFy.js +0 -2
- package/dist/client/assets/index-rljDU_1M.js +0 -3
- package/dist/client/assets/memory-C7UG-1le.js +0 -2
- package/dist/client/assets/skills-DoKPPhNY.js +0 -2
- package/dist/client/assets/styles-CXV5jZiD.css +0 -1
- package/dist/client/assets/useCompositeItem-OhltNFdZ.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as t}from"./main-
|
|
1
|
+
import{r as t}from"./main-DJgQwVqD.js";const e=t.createContext(void 0),o={disableStyleElements:!1};function s(){return t.useContext(e)??o}export{s as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as l}from"./main-
|
|
1
|
+
import{r as l}from"./main-DJgQwVqD.js";const E=["top","right","bottom","left"],p=Math.min,h=Math.max,L=Math.round,k=Math.floor,q=t=>({x:t,y:t}),x={left:"right",right:"left",bottom:"top",top:"bottom"},d={start:"end",end:"start"};function R(t,e,n){return h(t,p(e,n))}function T(t,e){return typeof t=="function"?t(e):t}function m(t){return t.split("-")[0]}function g(t){return t.split("-")[1]}function b(t){return t==="x"?"y":"x"}function A(t){return t==="y"?"height":"width"}const P=new Set(["top","bottom"]);function y(t){return P.has(m(t))?"y":"x"}function M(t){return b(y(t))}function v(t,e,n){n===void 0&&(n=!1);const s=g(t),i=M(t),o=A(i);let r=i==="x"?s===(n?"end":"start")?"right":"left":s==="start"?"bottom":"top";return e.reference[o]>e.floating[o]&&(r=a(r)),[r,a(r)]}function z(t){const e=a(t);return[c(t),e,c(e)]}function c(t){return t.replace(/start|end/g,e=>d[e])}const u=["left","right"],f=["right","left"],O=["top","bottom"],S=["bottom","top"];function C(t,e,n){switch(t){case"top":case"bottom":return n?e?f:u:e?u:f;case"left":case"right":return e?O:S;default:return[]}}function B(t,e,n,s){const i=g(t);let o=C(m(t),n==="start",s);return i&&(o=o.map(r=>r+"-"+i),e&&(o=o.concat(o.map(c)))),o}function a(t){return t.replace(/left|right|bottom|top/g,e=>x[e])}function w(t){return{top:0,right:0,bottom:0,left:0,...t}}function F(t){return typeof t!="number"?w(t):{top:t,right:t,bottom:t,left:t}}function G(t){const{x:e,y:n,width:s,height:i}=t;return{width:s,height:i,top:n,left:e,right:e+s,bottom:n+i,x:e,y:n}}const j=l.createContext(void 0);function H(){return l.useContext(j)?.direction??"ltr"}export{y as a,a as b,z as c,B as d,T as e,k as f,m as g,v as h,g as i,h as j,M as k,F as l,p as m,G as n,A as o,R as p,b as q,L as r,E as s,q as t,H as u};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/settings-dialog-CB1OiRWU.js","assets/main-DJgQwVqD.js","assets/react-DzPMbcP8.js","assets/button-BxDVif49.js","assets/use-file-explorer-state-Tzex8EEL.js","assets/useOnFirstRender-DqnUCnnL.js","assets/useBaseUiId-CMJ8I9al.js","assets/event-DeooaZzN.js","assets/visuallyHidden-COI6QeQH.js","assets/composite-t7Eu0qB0.js","assets/switch-LzFh8co4.js","assets/useControlled-KFa25CcD.js","assets/tabs-D9o7Irvl.js","assets/useCompositeItem-CSriPK0T.js","assets/DirectionContext-DZNUWW6F.js","assets/CSPContext-KDlbpvjX.js","assets/index-nheqha2z.js","assets/useQuery-DhR_UXNX.js","assets/tooltip-D64CzFXa.js","assets/useMutation-Bd89JWif.js","assets/menu-CnihCZ4y.js","assets/opencami-logo-CoCA2JIf.js","assets/proxy-C2vtPufK.js","assets/markdown-CFbW7h0Q.js","assets/index-T4TOjvD0.js","assets/session-export-dialog-Cf8eisLM.js","assets/thinking-BqZoM6BP.js","assets/search-sources-badge-DOd5AI-i.js","assets/follow-up-suggestions-DP_84nA2.js","assets/keyboard-shortcuts-dialog-BzL7ZJUb.js","assets/search-dialog-CDAdFAQI.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as s,u as ut,j as n,L as He,_ as et,d as Lt,w as qr,a as Jr,z as Qr}from"./main-DJgQwVqD.js";import{u as Mt}from"./useQuery-DhR_UXNX.js";import{T as Te,a as Re,b as Me,c as Ie,s as We,d as Zr,g as En}from"./tooltip-D64CzFXa.js";import{C as es,c as D,B as be,ac as dn,ag as Ve,E as ts,H as V,J as Jn,V as Pt,aj as ns,ak as rs,al as ss,a as Qn,am as os,G as is,an as as,l as ls,b as Qe,I as cs,ao as us,a3 as ds,s as Zt,ap as fs,L as ms,aq as ps,A as hs,N as gs,Q as xs,X as fn,x as ys,h as ws,ar as Zn,as as bs,p as Ss,T as er,u as tr,at as Ft,au as kn,av as vs,aw as js,ax as Es}from"./button-BxDVif49.js";import{u as nr}from"./useMutation-Bd89JWif.js";import{j as ks,k as Cs,l as Ns,m as Ts,n as Rs,o as Ms,p as Is,q as As,r as Ds,s as rr,D as Os,a as Ls,b as Ps,c as _s,d as Ks,u as zs}from"./use-file-explorer-state-Tzex8EEL.js";import{e as sr,a as Ye,g as or,t as Us,u as Ae,f as $s,n as Fs}from"./useBaseUiId-CMJ8I9al.js";import{u as Hs}from"./useControlled-KFa25CcD.js";import{a2 as Ws,a3 as Xs,a4 as Cn,t as ir,u as Ys,J as ke,e as Bs,a as It}from"./useOnFirstRender-DqnUCnnL.js";import{u as Gs,e as Vs,p as qs}from"./event-DeooaZzN.js";import{u as Js}from"./CSPContext-KDlbpvjX.js";import{u as ar}from"./DirectionContext-DZNUWW6F.js";import{M as _t,a as Kt,b as zt,c as Be}from"./menu-CnihCZ4y.js";import{O as Qs,a as Zs}from"./opencami-logo-CoCA2JIf.js";import{m as ve,A as Ne}from"./proxy-C2vtPufK.js";import{M as eo}from"./markdown-CFbW7h0Q.js";import{u as to,p as lr}from"./index-nheqha2z.js";import{c as cr}from"./react-DzPMbcP8.js";function en(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 Nn=/^Conversation info \(untrusted metadata\):\s*```(?:json)?\s*[\s\S]*?```\s*/,Tn=/^Conversation info \(untrusted metadata\):\s*\{[\s\S]*?\}\s*/,no=/^\[(?:[A-Za-z]{3}\s+)?\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}\s+GMT[+-]?\d+\]\s*/;function ur(e){let t=e;const r=Nn.test(t),o=!r&&Tn.test(t);return r?t=t.replace(Nn,""):o&&(t=t.replace(Tn,"")),(r||o)&&(t=t.replace(no,"")),t.trim()}function De(e){const r=(Array.isArray(e.content)?e.content:[]).map(o=>o.type==="text"?String(o.text??""):"").join("").trim();return ur(r)}function Xe(e){return(Array.isArray(e.content)?e.content:[]).filter(r=>r.type==="toolCall")}function ro(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 tn(e){const t=[e.createdAt,e.created_at,e.timestamp,e.time,e.ts];for(const r of t){const o=ro(r);if(o)return o}return Date.now()}const so=["agent:main:main","main"];function nn(e){return so.includes(e)}const oo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function io(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 oo.test(t)?"webchat":"chat"}return"other"}function ao(e){return Array.isArray(e)?e.map(t=>{const r=typeof t.key=="string"&&t.key.trim().length>0?t.key.trim():en(t.friendlyId??t.key),o=typeof t.friendlyId=="string"&&t.friendlyId.trim().length>0?t.friendlyId.trim():en(r),a=io(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 _e(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 lo="Missing gateway auth. Set CLAWDBOT_GATEWAY_TOKEN (recommended) or CLAWDBOT_GATEWAY_PASSWORD in the server environment.";function Rn(e){return e.includes(lo)}function Mn(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 me={sessions:["chat","sessions"],history:function(t,r){return["chat","history",t,r]}};async function co(){const e=await fetch("/api/sessions");if(!e.ok)throw new Error(await _e(e));const t=await e.json();return ao(t.sessions)}async function uo(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 _e(r));return await r.json()}async function fo(){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 _e(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 mn(e,t,r,o){const a=me.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 Ht(e,t,r,o){mn(e,t,r,function(i){return[...i,o]})}function mo(e,t,r,o,a){const i=`opt-${o}`;mn(e,t,r,function(c){return c.map(u=>u.clientId===o||u.__optimisticId===o||u.__optimisticId===i?a(u):u)})}function po(e,t,r,o,a){mn(e,t,r,function(l){return l.filter(c=>!(c.clientId===o||c.__optimisticId===o||a&&c.__optimisticId===a))})}function rn(e,t,r){const o=me.history(t,r);e.setQueryData(o,{sessionKey:r,messages:[]})}function ho(e,t,r,o,a){const i=me.history(t,r),l=me.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 go(e,t,r,o){e.setQueryData(me.sessions,function(i){return Array.isArray(i)?i.map(l=>l.key!==t&&l.friendlyId!==r?l:{...l,lastMessage:o}):i})}function xo(e,t,r){e.setQueryData(me.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 yo(e,t,r,o){e.setQueryData(me.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 _e(a);console.error("[updateSessionLabel] Failed to persist:",i)}}catch(a){console.error("[updateSessionLabel] Network error:",a)}}function wo(){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 g=await fetch("/api/paths");if(!g.ok)throw new Error(await _e(g));const j=await g.json();c({agentId:String(j.agentId??"main"),stateDir:String(j.stateDir??""),sessionsDir:String(j.sessionsDir??""),storePath:String(j.storePath??"")})}catch(g){i(g instanceof Error?g.message:String(g))}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 je=null,pn=!1,Nt=null;function bo(e){je=e}function Wt(){return je!==null}function gt(e){pn=e}function Xt(){return pn}function At(){je=null,pn=!1}function So(e,t){if(je){if(e&&je.sessionKey===e){At();return}t&&je.friendlyId===t&&At()}}function vo(e){Nt={friendlyId:e,at:Date.now()}}function dr(e,t=15e3){return!(!Nt||Nt.friendlyId!==e||Date.now()-Nt.at>t)}function jo(e,t){if(!je)return null;if(e&&je.sessionKey===e){const r=je;return je=null,r}if(t&&je.friendlyId===t){const r=je;return je=null,r}return null}const Eo=8e3,Ze=new Map;function ko(e){e&&Ze.set(e,{id:e,expiresAt:Date.now()+Eo})}function Co(e){e&&Ze.delete(e)}function No(e){if(Ze.size===0)return e;const t=Date.now();let r=!1;const o=e.filter(a=>{const i=Ze.get(a.key),l=Ze.get(a.friendlyId);return i&&i.expiresAt<=t||l&&l.expiresAt<=t?(i&&i.expiresAt<=t&&Ze.delete(a.key),l&&l.expiresAt<=t&&Ze.delete(a.friendlyId),!0):i||l?(r=!0,!1):!0});return r?o:e}function To(){const e=ut(),[t,r]=s.useState(!1),[o,a]=s.useState(null),i=nr({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 _e(f));return u},onMutate:async function(u){a(null),ko(u.sessionKey||u.friendlyId),So(u.sessionKey,u.friendlyId),await e.cancelQueries({queryKey:me.sessions});const d=e.getQueryData(me.sessions);return xo(e,u.sessionKey,u.friendlyId),u.isActive&&(u.sessionKey||u.friendlyId)&&rn(e,u.friendlyId||u.sessionKey,u.sessionKey||u.friendlyId),{previousSessions:d,isActive:u.isActive}},onError:function(u,d,f){f?.previousSessions&&e.setQueryData(me.sessions,f.previousSessions),Co(d.sessionKey||d.friendlyId),a(u instanceof Error?u.message:String(u))},onSuccess:function(u){u.isActive&&At(),e.invalidateQueries({queryKey:me.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 Ro(){const e=ut(),[t,r]=s.useState(!1),[o,a]=s.useState(null),i=nr({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 _e(d));return u},onMutate:async function(u){a(null),await e.cancelQueries({queryKey:me.sessions});const d=e.getQueryData(me.sessions);return e.setQueryData(me.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(me.sessions,f.previousSessions),a(u instanceof Error?u.message:String(u))},onSuccess:function(){e.invalidateQueries({queryKey:me.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 fr(e){return!e.content||!Array.isArray(e.content)?"":e.content.filter(t=>t.type==="text").map(t=>t.text||"").join(`
|
|
3
|
+
`)}function Mo(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=fr(a);if(l){const c=i==="user"?"User":"Assistant";o.push(`## ${c}`),o.push(""),o.push(l),o.push("")}}return o.join(`
|
|
4
|
+
`)}function Io(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 Ao(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=fr(a);if(l){const c=i==="user"?"User":"Assistant";o.push(`${c}:`),o.push(l),o.push("")}}return o.join(`
|
|
5
|
+
`)}function Do(e,t,r){const o=new Date;let a,i,l;switch(r){case"markdown":a=Mo(e,t,o),i=`${Yt(e)}.md`,l="text/markdown";break;case"json":a=Io(e,t,o),i=`${Yt(e)}.json`,l="application/json";break;case"txt":a=Ao(e,t,o),i=`${Yt(e)}.txt`,l="text/plain";break;default:throw new Error(`Unsupported format: ${r}`)}Oo(a,i,l)}function Yt(e){return e.replace(/[^a-z0-9-_\s]/gi,"").replace(/\s+/g,"-").toLowerCase().slice(0,50)||"conversation"}function Oo(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 Lo(e){const{children:t,open:r,defaultOpen:o=!1,onOpenChange:a,onOpenChangeComplete:i,actionsRef:l,handle:c,triggerId:u,defaultTriggerId:d=null}=e,f=ks(),m=!!f,p=es(()=>c?.store??new Cs({open:o,openProp:r,activeTriggerId:d,triggerIdProp:u,modal:!0,disablePointerDismissal:!0,nested:m,role:"alertdialog"})).current;p.useControlledProp("openProp",r),p.useControlledProp("triggerIdProp",u),p.useSyncedValue("nested",m),p.useContextCallback("onOpenChange",a),p.useContextCallback("onOpenChangeComplete",i);const g=p.useState("payload");Ns({store:p,actionsRef:l,parentContext:f?.store.context});const j=s.useMemo(()=>({store:p}),[p]);return n.jsx(Ts.Provider,{value:j,children:typeof t=="function"?t({payload:g}):t})}function Po({children:e,...t}){return n.jsx(Lo,{...t,children:e})}function _o({className:e,children:t}){return n.jsxs(Rs,{children:[n.jsx(Ms,{className:"fixed inset-0 bg-primary-950/20 transition-all duration-150 data-[state=open]:opacity-100 data-[state=closed]:opacity-0"}),n.jsx(Is,{className:D("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 Ko({className:e,...t}){return n.jsx(As,{className:D("text-lg font-medium text-primary-900",e),...t})}function zo({className:e,...t}){return n.jsx(Ds,{className:D("text-sm text-primary-600",e),...t})}function Uo({className:e,...t}){return n.jsx(rr,{render:n.jsx(be,{variant:"outline",className:D(e)}),...t})}function $o({className:e,...t}){return n.jsx(rr,{render:n.jsx(be,{variant:"destructive",className:D(e)}),...t})}function Fo({open:e,onOpenChange:t,sessionTitle:r,onConfirm:o,onCancel:a}){return n.jsx(Po,{open:e,onOpenChange:t,children:n.jsx(_o,{children:n.jsxs("div",{className:"p-4",children:[n.jsx(Ko,{className:"mb-1",children:"Delete Session"}),n.jsxs(zo,{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(Uo,{onClick:a,children:"Cancel"}),n.jsx($o,{onClick:o,children:"Delete"})]})]})})})}function Ho({open:e,onOpenChange:t,sessionTitle:r,onSave:o,onCancel:a}){return n.jsx(Os,{open:e,onOpenChange:t,children:n.jsx(Ls,{children:n.jsxs("div",{className:"p-4",children:[n.jsx(Ps,{className:"mb-1",children:"Rename"}),n.jsx(_s,{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(Ks,{onClick:a,children:"Cancel"}),n.jsx(be,{onClick:i=>{const l=i.currentTarget.parentElement?.previousElementSibling;o(l.value)},children:"Save"})]})]})})})}function Wo(e){const{open:t,defaultOpen:r,onOpenChange:o,disabled:a}=e,i=t!==void 0,[l,c]=Hs({controlled:t,default:r,name:"Collapsible",state:"open"}),{mounted:u,setMounted:d,transitionStatus:f}=Ws(l,!0,!0),[m,p]=s.useState(l),[{height:g,width:j},h]=s.useState({height:void 0,width:void 0}),b=sr(),[y,x]=s.useState(),O=y??b,[R,P]=s.useState(!1),[T,X]=s.useState(!1),Y=s.useRef(null),_=s.useRef(null),te=s.useRef(null),B=s.useRef(null),k=Xs(B,!1),S=Ye(E=>{const N=!l,K=or(Us,E.nativeEvent);if(o(N,K),K.isCanceled)return;const $=B.current;_.current==="css-animation"&&$!=null&&$.style.removeProperty("animation-name"),!R&&!T&&(_.current!=null&&_.current!=="css-animation"&&!u&&N&&d(!0),_.current==="css-animation"&&(!m&&N&&p(!0),!u&&N&&d(!0))),c(N),_.current==="none"&&u&&!N&&d(!1)});return Ae(()=>{i&&_.current==="none"&&!T&&!l&&d(!1)},[i,T,l,t,d]),s.useMemo(()=>({abortControllerRef:Y,animationTypeRef:_,disabled:a,handleTrigger:S,height:g,mounted:u,open:l,panelId:O,panelRef:B,runOnceAnimationsFinish:k,setDimensions:h,setHiddenUntilFound:P,setKeepMounted:X,setMounted:d,setOpen:c,setPanelIdState:x,setVisible:p,transitionDimensionRef:te,transitionStatus:f,visible:m,width:j}),[Y,_,a,S,g,u,l,O,B,k,h,P,X,d,c,p,te,f,m,j])}const mr=s.createContext(void 0);function pr(){const e=s.useContext(mr);if(e===void 0)throw new Error(dn(15));return e}let xt=(function(e){return e.open="data-open",e.closed="data-closed",e[e.startingStyle=Cn.startingStyle]="startingStyle",e[e.endingStyle=Cn.endingStyle]="endingStyle",e})({}),Xo=(function(e){return e.panelOpen="data-panel-open",e})({});const Yo={[xt.open]:""},Bo={[xt.closed]:""},Go={open(e){return e?{[Xo.panelOpen]:""}:null}},Vo={open(e){return e?Yo:Bo}},hr={...Vo,...ir},qo=s.forwardRef(function(t,r){const{render:o,className:a,defaultOpen:i=!1,disabled:l=!1,onOpenChange:c,open:u,...d}=t,f=Ye(c),m=Wo({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]),g=s.useMemo(()=>({...m,onOpenChange:f,state:p}),[m,f,p]),j=Ve("div",t,{state:p,ref:r,props:d,stateAttributesMapping:hr});return n.jsx(mr.Provider,{value:g,children:j})}),Jo={...Go,...ir},Qo=s.forwardRef(function(t,r){const{panelId:o,open:a,handleTrigger:i,state:l,disabled:c}=pr(),{className:u,disabled:d=c,id:f,render:m,nativeButton:p=!0,...g}=t,{getButtonProps:j,buttonRef:h}=$s({disabled:d,focusableWhenDisabled:!0,native:p}),b=s.useMemo(()=>({"aria-controls":a?o:void 0,"aria-expanded":a,onClick:i}),[o,a,i]);return Ve("button",t,{state:l,ref:[r,h],props:[b,g,j],stateAttributesMapping:Jo})});let Zo=(function(e){return e.disabled="data-disabled",e.orientation="data-orientation",e})({});function ei(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:g,setMounted:j,setOpen:h,setVisible:b,transitionDimensionRef:y,visible:x,width:O}=e,R=s.useRef(!1),P=s.useRef(null),T=s.useRef(f),X=s.useRef(f),Y=Ys(),_=s.useMemo(()=>r.current==="css-animation"?!x:!f&&!u,[f,u,x,r]),te=Ye(k=>{if(!k)return;if(r.current==null||y.current==null){const N=getComputedStyle(k),K=N.animationName!=="none"&&N.animationName!=="",$=N.transitionDuration!=="0s"&&N.transitionDuration!=="";K&&$||(N.animationName==="none"&&N.transitionDuration!=="0s"?r.current="css-transition":N.animationName!=="none"&&N.transitionDuration==="0s"?r.current="css-animation":r.current="none"),k.getAttribute(Zo.orientation)==="horizontal"||N.transitionProperty.indexOf("width")>-1?y.current="width":y.current="height"}if(r.current!=="css-transition")return;(a===void 0||O===void 0)&&(g({height:k.scrollHeight,width:k.scrollWidth}),X.current&&k.style.setProperty("transition-duration","0s"));let S=-1,E=-1;return S=ke.request(()=>{X.current=!1,E=ke.request(()=>{setTimeout(()=>{k.style.removeProperty("transition-duration")})})}),()=>{ke.cancel(S),ke.cancel(E)}}),B=ts(o,m,te);return Ae(()=>{if(r.current!=="css-transition")return;const k=m.current;if(!k)return;let S=-1;if(t.current!=null&&(t.current.abort(),t.current=null),f){const E={"justify-content":k.style.justifyContent,"align-items":k.style.alignItems,"align-content":k.style.alignContent,"justify-items":k.style.justifyItems};Object.keys(E).forEach(N=>{k.style.setProperty(N,"initial","important")}),!X.current&&!l&&k.setAttribute(xt.startingStyle,""),g({height:k.scrollHeight,width:k.scrollWidth}),S=ke.request(()=>{Object.entries(E).forEach(([N,K])=>{K===""?k.style.removeProperty(N):k.style.setProperty(N,K)})})}else{if(k.scrollHeight===0&&k.scrollWidth===0)return;g({height:k.scrollHeight,width:k.scrollWidth});const E=new AbortController;t.current=E;const N=E.signal;let K=null;const $=xt.endingStyle;return K=new MutationObserver(q=>{q.some(L=>L.type==="attributes"&&L.attributeName===$)&&(K?.disconnect(),K=null,p(()=>{g({height:0,width:0}),k.style.removeProperty("content-visibility"),j(!1),t.current===E&&(t.current=null)},N))}),K.observe(k,{attributes:!0,attributeFilter:[$]}),()=>{K?.disconnect(),Y.cancel(),t.current===E&&(E.abort(),t.current=null)}}return()=>{ke.cancel(S)}},[t,r,Y,i,l,u,f,m,p,g,j]),Ae(()=>{if(r.current!=="css-animation")return;const k=m.current;k&&(P.current=k.style.animationName||P.current,k.style.setProperty("animation-name","none"),g({height:k.scrollHeight,width:k.scrollWidth}),!T.current&&!R.current&&k.style.removeProperty("animation-name"),f?(t.current!=null&&(t.current.abort(),t.current=null),j(!0),b(!0)):(t.current=new AbortController,p(()=>{j(!1),b(!1),t.current=null},t.current.signal)))},[t,r,f,m,p,g,j,b,x]),Gs(()=>{const k=ke.request(()=>{T.current=!1});return()=>ke.cancel(k)}),Ae(()=>{if(!i)return;const k=m.current;if(!k)return;let S=-1,E=-1;return f&&R.current&&(k.style.transitionDuration="0s",g({height:k.scrollHeight,width:k.scrollWidth}),S=ke.request(()=>{R.current=!1,E=ke.request(()=>{setTimeout(()=>{k.style.removeProperty("transition-duration")})})})),()=>{ke.cancel(S),ke.cancel(E)}},[i,f,m,g]),Ae(()=>{const k=m.current;k&&i&&_&&(k.setAttribute("hidden","until-found"),r.current==="css-transition"&&k.setAttribute(xt.startingStyle,""))},[i,_,r,m]),s.useEffect(function(){const S=m.current;if(!S)return;function E(N){R.current=!0,h(!0),d(!0,or(Fs,N))}return S.addEventListener("beforematch",E),()=>{S.removeEventListener("beforematch",E)}},[d,m,h]),s.useMemo(()=>({props:{hidden:_,id:c,ref:B}}),[_,c,B])}let In=(function(e){return e.collapsiblePanelHeight="--collapsible-panel-height",e.collapsiblePanelWidth="--collapsible-panel-width",e})({});const ti=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:g,open:j,panelId:h,panelRef:b,runOnceAnimationsFinish:y,setDimensions:x,setHiddenUntilFound:O,setKeepMounted:R,setMounted:P,setPanelIdState:T,setOpen:X,setVisible:Y,state:_,transitionDimensionRef:te,visible:B,width:k,transitionStatus:S}=pr(),E=a??!1,N=i??!1;Ae(()=>{if(c)return T(c),()=>{T(void 0)}},[c,T]),Ae(()=>{O(E)},[O,E]),Ae(()=>{R(N)},[R,N]);const{props:K}=ei({abortControllerRef:d,animationTypeRef:f,externalRef:r,height:m,hiddenUntilFound:E,id:h,keepMounted:N,mounted:p,onOpenChange:g,open:j,panelRef:b,runOnceAnimationsFinish:y,setDimensions:x,setMounted:P,setOpen:X,setVisible:Y,transitionDimensionRef:te,visible:B,width:k});Bs({open:j&&S==="idle",ref:b,onComplete(){j&&x({height:void 0,width:void 0})}});const $=s.useMemo(()=>({..._,transitionStatus:S}),[_,S]),q=Ve("div",t,{state:$,ref:[r,b],props:[K,{style:{[In.collapsiblePanelHeight]:m===void 0?"auto":`${m}px`,[In.collapsiblePanelWidth]:k===void 0?"auto":`${k}px`}},u],stateAttributesMapping:hr});return N||E||!N&&p?q:null});function sn(e){return n.jsx(qo,{...e})}function on({className:e,...t}){return n.jsx(Qo,{className:D("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 an({className:e,contentClassName:t,children:r,...o}){return n.jsx(ti,{className:D('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:D("pt-1",t),children:r})})}const gr=s.createContext(void 0);function Ut(){const e=s.useContext(gr);if(e===void 0)throw new Error(dn(53));return e}let Dt=(function(e){return e.scrollAreaCornerHeight="--scroll-area-corner-height",e.scrollAreaCornerWidth="--scroll-area-corner-width",e})({});const jt=500,An=16;function Ce(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 ni=(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",xr={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 st=(function(e){return 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 hn={hasOverflowX:e=>e?{[st.hasOverflowX]:""}:null,hasOverflowY:e=>e?{[st.hasOverflowY]:""}:null,overflowXStart:e=>e?{[st.overflowXStart]:""}:null,overflowXEnd:e=>e?{[st.overflowXEnd]:""}:null,overflowYStart:e=>e?{[st.overflowYStart]:""}:null,overflowYEnd:e=>e?{[st.overflowYEnd]:""}:null,cornerHidden:()=>null},ri={x:0,y:0},Dn={width:0,height:0},si={xStart:!1,xEnd:!1,yStart:!1,yEnd:!1},oi={x:!1,y:!1,corner:!1},ii=s.forwardRef(function(t,r){const{render:o,className:a,overflowEdgeThreshold:i,...l}=t,c=ai(i),u=sr(),d=It(),f=It(),{nonce:m,disableStyleElements:p}=Js(),[g,j]=s.useState(!1),[h,b]=s.useState(!1),[y,x]=s.useState(!1),[O,R]=s.useState(!1),[P,T]=s.useState(Dn),[X,Y]=s.useState(Dn),[_,te]=s.useState(si),[B,k]=s.useState(oi),S=s.useRef(null),E=s.useRef(null),N=s.useRef(null),K=s.useRef(null),$=s.useRef(null),q=s.useRef(null),C=s.useRef(null),L=s.useRef(!1),w=s.useRef(0),M=s.useRef(0),z=s.useRef(0),Q=s.useRef(0),J=s.useRef("vertical"),G=s.useRef(ri),W=Ye(I=>{const pe=I.x-G.current.x,A=I.y-G.current.y;G.current=I,A!==0&&(x(!0),d.start(jt,()=>{x(!1)})),pe!==0&&(b(!0),f.start(jt,()=>{b(!1)}))}),re=Ye(I=>{I.button===0&&(L.current=!0,w.current=I.clientY,M.current=I.clientX,J.current=I.currentTarget.getAttribute(ni.orientation),E.current&&(z.current=E.current.scrollTop,Q.current=E.current.scrollLeft),$.current&&J.current==="vertical"&&$.current.setPointerCapture(I.pointerId),q.current&&J.current==="horizontal"&&q.current.setPointerCapture(I.pointerId))}),le=Ye(I=>{if(!L.current)return;const pe=I.clientY-w.current,A=I.clientX-M.current;if(E.current){const F=E.current.scrollHeight,H=E.current.clientHeight,ce=E.current.scrollWidth,ue=E.current.clientWidth;if($.current&&N.current&&J.current==="vertical"){const se=Ce(N.current,"padding","y"),Se=Ce($.current,"margin","y"),Oe=$.current.offsetHeight,ye=N.current.offsetHeight-Oe-se-Se,Le=pe/ye;E.current.scrollTop=z.current+Le*(F-H),I.preventDefault(),x(!0),d.start(jt,()=>{x(!1)})}if(q.current&&K.current&&J.current==="horizontal"){const se=Ce(K.current,"padding","x"),Se=Ce(q.current,"margin","x"),Oe=q.current.offsetWidth,ye=K.current.offsetWidth-Oe-se-Se,Le=A/ye;E.current.scrollLeft=Q.current+Le*(ce-ue),I.preventDefault(),b(!0),f.start(jt,()=>{b(!1)})}}}),ne=Ye(I=>{L.current=!1,$.current&&J.current==="vertical"&&$.current.releasePointerCapture(I.pointerId),q.current&&J.current==="horizontal"&&q.current.releasePointerCapture(I.pointerId)});function Z(I){R(I.pointerType==="touch")}function ae(I){if(Z(I),I.pointerType!=="touch"){const pe=Vs(S.current,I.target);j(pe)}}const oe=s.useMemo(()=>({scrolling:h||y,hasOverflowX:!B.x,hasOverflowY:!B.y,overflowXStart:_.xStart,overflowXEnd:_.xEnd,overflowYStart:_.yStart,overflowYEnd:_.yEnd,cornerHidden:B.corner}),[h,y,B.x,B.y,B.corner,_]),ie={role:"presentation",onPointerEnter:ae,onPointerMove:ae,onPointerDown:Z,onPointerLeave(){j(!1)},style:{position:"relative",[Dt.scrollAreaCornerHeight]:`${P.height}px`,[Dt.scrollAreaCornerWidth]:`${P.width}px`}},he=Ve("div",t,{state:oe,ref:[r,S],props:[ie,l],stateAttributesMapping:hn}),ge=s.useMemo(()=>({handlePointerDown:re,handlePointerMove:le,handlePointerUp:ne,handleScroll:W,cornerSize:P,setCornerSize:T,thumbSize:X,setThumbSize:Y,touchModality:O,cornerRef:C,scrollingX:h,setScrollingX:b,scrollingY:y,setScrollingY:x,hovering:g,setHovering:j,viewportRef:E,rootRef:S,scrollbarYRef:N,scrollbarXRef:K,thumbYRef:$,thumbXRef:q,rootId:u,hiddenState:B,setHiddenState:k,overflowEdges:_,setOverflowEdges:te,viewportState:oe,overflowEdgeThreshold:c}),[re,le,ne,W,P,X,O,h,b,y,x,g,j,u,B,_,oe,c]);return n.jsxs(gr.Provider,{value:ge,children:[!p&&xr.getElement(m),he]})});function ai(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 li=s.createContext(void 0);function it(e,t=Number.MIN_SAFE_INTEGER,r=Number.MAX_SAFE_INTEGER){return Math.max(t,Math.min(e,r))}function ci(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 Ge=(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})({});const On=1;function Ln(e,t){if(t<=0)return 0;const r=it(e,0,t),o=r,a=t-r,i=o<=On,l=a<=On;return i&&l?o<=a?0:t:i?0:l?t:r}let Pn=!1;function ui(){Pn||qs||(typeof CSS<"u"&&"registerProperty"in CSS&&[Ge.scrollAreaOverflowXStart,Ge.scrollAreaOverflowXEnd,Ge.scrollAreaOverflowYStart,Ge.scrollAreaOverflowYEnd].forEach(e=>{try{CSS.registerProperty({name:e,syntax:"<length>",inherits:!1,initialValue:"0px"})}catch{}}),Pn=!0)}const di=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:g,setThumbSize:j,rootId:h,setHiddenState:b,hiddenState:y,handleScroll:x,setHovering:O,setOverflowEdges:R,overflowEdges:P,overflowEdgeThreshold:T,scrollingX:X,scrollingY:Y}=Ut(),_=ar(),te=s.useRef(!0),B=It(),k=It(),S=Ye(()=>{const C=l.current,L=c.current,w=u.current,M=d.current,z=f.current,Q=m.current;if(!C)return;const J=C.scrollHeight,G=C.scrollWidth,W=C.clientHeight,re=C.clientWidth,le=C.scrollTop,ne=C.scrollLeft;if(J===0||G===0)return;const Z=W>=J,ae=re>=G,oe=re/G,ie=W/J,he=Math.max(0,G-re),ge=Math.max(0,J-W);let I=0,pe=0;if(!ae){let ee=0;_==="rtl"?ee=it(-ne,0,he):ee=it(ne,0,he),I=Ln(ee,he),pe=he-I}const A=Z?0:it(le,0,ge),F=Z?0:Ln(A,ge),H=Z?0:ge-F,ce=ae?0:re,ue=Z?0:W;let se=0,Se=0;!ae&&!Z&&(se=L?.offsetWidth||0,Se=w?.offsetHeight||0);const Oe=p.width===0&&p.height===0,ye=Oe?se:0,Le=Oe?Se:0,dt=Ce(w,"padding","x"),yt=Ce(L,"padding","y"),qe=Ce(z,"margin","x"),Je=Ce(M,"margin","y"),ft=ce-dt-qe,mt=ue-yt-Je,wt=w?Math.min(w.offsetWidth-ye,ft):ft,bt=L?Math.min(L.offsetHeight-Le,mt):mt,pt=Math.max(An,wt*oe),ht=Math.max(An,bt*ie);if(j(ee=>ee.height===ht&&ee.width===pt?ee:{width:pt,height:ht}),L&&M){const ee=L.offsetHeight-ht-yt-Je,Ee=J-W,Ke=Ee===0?0:le/Ee,Ue=Math.min(ee,Math.max(0,Ke*ee));M.style.transform=`translate3d(0,${Ue}px,0)`}if(w&&z){const ee=w.offsetWidth-pt-dt-qe,Ee=G-re,Ke=Ee===0?0:ne/Ee,Ue=_==="rtl"?it(Ke*ee,-ee,0):it(Ke*ee,0,ee);z.style.transform=`translate3d(${Ue}px,0,0)`}const St=[[Ge.scrollAreaOverflowXStart,I],[Ge.scrollAreaOverflowXEnd,pe],[Ge.scrollAreaOverflowYStart,F],[Ge.scrollAreaOverflowYEnd,H]];for(const[ee,Ee]of St)C.style.setProperty(ee,`${Ee}px`);Q&&(ae||Z?g({width:0,height:0}):!ae&&!Z&&g({width:se,height:Se})),b(ee=>{const Ee=Z||ae;return ee.y===Z&&ee.x===ae&&ee.corner===Ee?ee:{y:Z,x:ae,corner:Ee}});const ze={xStart:!ae&&I>T.xStart,xEnd:!ae&&pe>T.xEnd,yStart:!Z&&F>T.yStart,yEnd:!Z&&H>T.yEnd};R(ee=>ee.xStart===ze.xStart&&ee.xEnd===ze.xEnd&&ee.yStart===ze.yStart&&ee.yEnd===ze.yEnd?ee:ze)});Ae(()=>{if(!l.current)return;ui();let C=!1;return ci(l.current,()=>{if(!C){C=!0;return}S()})},[S,l]),Ae(()=>{queueMicrotask(S)},[S,y,_]),Ae(()=>{l.current?.matches(":hover")&&O(!0)},[l,O]),s.useEffect(()=>{const C=l.current;if(typeof ResizeObserver>"u"||!C)return;let L=!1;const w=new ResizeObserver(()=>{if(!L){L=!0;return}S()});return w.observe(C),k.start(0,()=>{const M=C.getAnimations({subtree:!0});M.length!==0&&Promise.allSettled(M.map(z=>z.finished)).then(S).catch(()=>{})}),()=>{w.disconnect(),k.clear()}},[S,l,k]);function E(){te.current=!1}const N={role:"presentation",...h&&{"data-id":`${h}-viewport`},...(!y.x||!y.y)&&{tabIndex:0},className:xr.className,style:{overflow:"scroll"},onScroll(){l.current&&(S(),te.current||x({x:l.current.scrollLeft,y:l.current.scrollTop}),B.start(100,()=>{te.current=!0}))},onWheel:E,onTouchMove:E,onPointerMove:E,onPointerEnter:E,onKeyDown:E},K=s.useMemo(()=>({scrolling:X||Y,hasOverflowX:!y.x,hasOverflowY:!y.y,overflowXStart:P.xStart,overflowXEnd:P.xEnd,overflowYStart:P.yStart,overflowYEnd:P.yEnd,cornerHidden:y.corner}),[X,Y,y.x,y.y,y.corner,P]),$=Ve("div",t,{ref:[r,l],state:K,props:[N,i],stateAttributesMapping:hn}),q=s.useMemo(()=>({computeThumbPosition:S}),[S]);return n.jsx(li.Provider,{value:q,children:$})}),yr=s.createContext(void 0);function fi(){const e=s.useContext(yr);if(e===void 0)throw new Error(dn(54));return e}let Ot=(function(e){return e.scrollAreaThumbHeight="--scroll-area-thumb-height",e.scrollAreaThumbWidth="--scroll-area-thumb-width",e})({});const mi=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:g,scrollbarXRef:j,viewportRef:h,thumbYRef:b,thumbXRef:y,handlePointerDown:x,handlePointerUp:O,rootId:R,thumbSize:P}=Ut(),T={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},X=ar();s.useEffect(()=>{const S=h.current,E=i==="vertical"?g.current:j.current;if(!E)return;function N(K){if(!(!S||!E||K.ctrlKey)){if(K.preventDefault(),i==="vertical"){if(S.scrollTop===0&&K.deltaY<0)return}else if(S.scrollLeft===0&&K.deltaX<0)return;if(i==="vertical"){if(S.scrollTop===S.scrollHeight-S.clientHeight&&K.deltaY>0)return}else if(S.scrollLeft===S.scrollWidth-S.clientWidth&&K.deltaX>0)return;i==="vertical"?S.scrollTop+=K.deltaY:S.scrollLeft+=K.deltaX}}return E.addEventListener("wheel",N,{passive:!1}),()=>{E.removeEventListener("wheel",N)}},[i,j,g,h]);const Y={...R&&{"data-id":`${R}-scrollbar`},onPointerDown(S){if(S.button===0&&S.currentTarget===S.target&&h.current){if(b.current&&g.current&&i==="vertical"){const E=Ce(b.current,"margin","y"),N=Ce(g.current,"padding","y"),K=b.current.offsetHeight,$=g.current.getBoundingClientRect(),q=S.clientY-$.top-K/2-N+E/2,C=h.current.scrollHeight,L=h.current.clientHeight,w=g.current.offsetHeight-K-N-E,z=q/w*(C-L);h.current.scrollTop=z}if(y.current&&j.current&&i==="horizontal"){const E=Ce(y.current,"margin","x"),N=Ce(j.current,"padding","x"),K=y.current.offsetWidth,$=j.current.getBoundingClientRect(),q=S.clientX-$.left-K/2-N+E/2,C=h.current.scrollWidth,L=h.current.clientWidth,w=j.current.offsetWidth-K-N-E,M=q/w;let z;X==="rtl"?(z=(1-M)*(C-L),h.current.scrollLeft<=0&&(z=-z)):z=M*(C-L),h.current.scrollLeft=z}x(S)}},onPointerUp:O,style:{position:"absolute",touchAction:"none",WebkitUserSelect:"none",userSelect:"none",...i==="vertical"&&{top:0,bottom:`var(${Dt.scrollAreaCornerHeight})`,insetInlineEnd:0,[Ot.scrollAreaThumbHeight]:`${P.height}px`},...i==="horizontal"&&{insetInlineStart:0,insetInlineEnd:`var(${Dt.scrollAreaCornerWidth})`,bottom:0,[Ot.scrollAreaThumbWidth]:`${P.width}px`}}},_=Ve("div",t,{ref:[r,i==="vertical"?g:j],state:T,props:[Y,c],stateAttributesMapping:hn}),te=s.useMemo(()=>({orientation:i}),[i]),B=i==="vertical"?m.y:m.x;return l||!B?n.jsx(yr.Provider,{value:te,children:_}):null}),pi=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}=Ut(),{orientation:g}=fi();return Ve("div",t,{ref:[r,g==="vertical"?l:c],state:{orientation:g},props:[{onPointerDown:u,onPointerMove:d,onPointerUp(b){g==="vertical"&&p(!1),g==="horizontal"&&m(!1),f(b)},style:{...g==="vertical"&&{height:`var(${Ot.scrollAreaThumbHeight})`},...g==="horizontal"&&{width:`var(${Ot.scrollAreaThumbWidth})`}}},i]})}),hi=s.forwardRef(function(t,r){const{render:o,className:a,...i}=t,{cornerRef:l,cornerSize:c,hiddenState:u}=Ut(),d=Ve("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 wr({className:e,...t}){return n.jsx(ii,{className:D("group/scroll-area relative outline-none focus-visible:outline-none",e),...t})}function br({className:e,...t}){return n.jsx(di,{className:D("h-full w-full outline-none focus-visible:outline-none",e),...t})}function Sr({className:e,...t}){return n.jsx(mi,{className:D("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 vr({className:e,...t}){return n.jsx(pi,{className:D("flex-1 rounded-full bg-primary-500 outline-none focus-visible:outline-none",e),...t})}function gi({className:e,...t}){return n.jsx(hi,{className:D("bg-primary-100 outline-none focus-visible:outline-none",e),...t})}function xi(e){return e==="subagent"?os:e==="cron"?is:as}function yi(e){if(!e||!Array.isArray(e.content))return"";const t=e.content.map(o=>o.type==="text"?String(o.text??""):"").join(" ");return ur(t).replace(/\s+/g," ").trim()}function wi(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 bi(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=wi(r);if(o)return o}return null}function Si(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 vi(e){const t=String(e??"").toLowerCase().trim();return t?t==="error"||t==="failed"?"error":t==="completed"||t==="ended"||t==="done"?"success":null:null}function ji({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,g=xi(e.kind),j=e.kind==="subagent"&&(e.lastMessage?.role==="assistant"||e.lastMessage?.role==="toolResult")?yi(e.lastMessage):"",h=j.length>50?`${j.slice(0,50).trimEnd()}…`:j,b=e.kind==="subagent"?vi(e.status):null,y=e.kind==="cron"?bi(e.lastMessage):null;return n.jsxs(He,{to:"/chat/$sessionKey",params:{sessionKey:e.friendlyId},onClick:x=>{if(a){x.preventDefault(),x.stopPropagation(),l?.(e);return}c?.()},className:D("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:D("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(V,{icon:g,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"}):b==="success"?n.jsx(V,{icon:Jn,size:12,strokeWidth:1.8,className:"text-green-600/80 shrink-0"}):b==="error"?n.jsx(V,{icon:Pt,size:12,strokeWidth:1.8,className:"text-red-600/80 shrink-0"}):null:null]}),h?n.jsx("div",{className:"text-[11px] text-primary-600/80 line-clamp-1 mt-0.5 pl-[18px]",children:h}):null,e.kind==="cron"&&y?n.jsx("div",{className:"text-[10px] text-primary-500/75 line-clamp-1 mt-0.5 pl-[18px] font-mono",children:Si(y)}):null]})]}),a?null:n.jsxs(_t,{children:[n.jsx(Kt,{type:"button",onClick:x=>{x.preventDefault(),x.stopPropagation()},className:D("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(V,{icon:ns,size:20,strokeWidth:1.5})}),n.jsxs(zt,{side:"bottom",align:"end",children:[n.jsxs(Be,{onClick:x=>{x.preventDefault(),x.stopPropagation(),u(e)},className:"gap-2",children:[n.jsx("span",{className:"text-xs","aria-hidden":"true",children:"📌"})," ",o?"Unpin Session":"Pin Session"]}),n.jsxs(Be,{onClick:x=>{x.preventDefault(),x.stopPropagation(),d(e)},className:"gap-2",children:[n.jsx(V,{icon:rs,size:20,strokeWidth:1.5})," ","Rename"]}),n.jsxs(Be,{onClick:x=>{x.preventDefault(),x.stopPropagation(),m(e)},className:"gap-2",children:[n.jsx(V,{icon:ss,size:20,strokeWidth:1.5})," ","Export"]}),nn(e.key)?null:n.jsxs(Be,{onClick:x=>{x.preventDefault(),x.stopPropagation(),f(e)},className:"text-red-700 gap-2 hover:bg-red-50/80 data-highlighted:bg-red-50/80",children:[n.jsx(V,{icon:Qn,size:20,strokeWidth:1.5})," ","Delete"]})]})]})]})}function Ei(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 Bt=s.memo(ji,Ei),jr="opencami-pinned-sessions",Er="opencami-sidebar-folders",Fe={webchat:!1,subagent:!1,cron:!1,other:!1};async function ki(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 _e(r))}async function Ci(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 Ni(){if(typeof window>"u")return[];try{const e=localStorage.getItem(jr);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}catch{return[]}}function Ti(e){if(!(typeof window>"u"))try{const t=Array.from(new Set(e));localStorage.setItem(jr,JSON.stringify(t))}catch{}}function Ri(){if(typeof window>"u")return{...Fe};try{const e=localStorage.getItem(Er);if(!e)return{...Fe};const t=JSON.parse(e);return!t||typeof t!="object"?{...Fe}:{webchat:typeof t.webchat=="boolean"?t.webchat:Fe.webchat,subagent:typeof t.subagent=="boolean"?t.subagent:Fe.subagent,cron:typeof t.cron=="boolean"?t.cron:Fe.cron,other:typeof t.other=="boolean"?t.other:Fe.other}}catch{return{...Fe}}}function Mi(e){if(!(typeof window>"u"))try{localStorage.setItem(Er,JSON.stringify(e))}catch{}}function Tt(e,t,r){return r&&e.key?e.key===r:e.friendlyId===t}function Ii(e){if(!e)return!1;const t=e.toLowerCase();return t.includes("running")||t.includes("active")||t.includes("stream")||t.includes("generat")}function Gt(e,t,r,o){return Tt(e,t,r)&&o?!0:Ii(e.status)}const Ai=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=ut(),[p,g]=s.useState(()=>Ni()),[j,h]=s.useState(()=>Ri()),[b,y]=s.useState(!1),[x,O]=s.useState(()=>new Set),R=s.useMemo(()=>new Set(p),[p]),P=f.filter(C=>R.has(C.key)),T=f.filter(C=>!R.has(C.key)),X=P.length>0&&T.length>0,Y=s.useMemo(()=>{const C={chat:[],webchat:[],subagent:[],cron:[],other:[]};for(const L of T){const w=L.kind??"other";C[w].push(L)}return C},[T]),_=s.useMemo(()=>f.filter(C=>x.has(C.key)),[x,f]),te=_.length,B=s.useCallback(()=>{y(C=>(C&&O(new Set),!C))},[]),k=s.useCallback(C=>{nn(C.key)||O(L=>{const w=new Set(L);return w.has(C.key)?w.delete(C.key):w.add(C.key),w})},[]),S=s.useCallback(()=>{O(new Set(f.filter(C=>!nn(C.key)).map(C=>C.key)))},[f]),E=s.useCallback(()=>{y(!1),O(new Set)},[]),N=s.useCallback(async()=>{if(_.length===0||!window.confirm(`Delete ${_.length} sessions? This will archive them.`))return;const L=[];await Ci(_,10,async w=>{try{await ki(w.key)}catch(M){throw L.push(w.label||w.title||w.derivedTitle||w.friendlyId),M}}),L.length>0&&(console.error("[sidebar] Bulk delete failed for some sessions",L),window.alert(`Could not delete ${L.length} session${L.length!==1?"s":""}:
|
|
6
|
+
|
|
7
|
+
${L.join(`
|
|
8
|
+
`)}`)),y(!1),O(new Set),m.invalidateQueries({queryKey:me.sessions})},[m,_]),K=s.useCallback(C=>{g(L=>{const M=L.includes(C.key)?L.filter(z=>z!==C.key):[...L,C.key];return Ti(M),M})},[]),$=s.useCallback((C,L)=>{h(w=>{const M={...w,[C]:L};return Mi(M),M})},[]);function q(C,L,w){return w.length===0?null:n.jsxs(sn,{className:"flex flex-col",open:j[C],onOpenChange:M=>$(C,M),children:[n.jsxs(on,{className:D("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:L}),n.jsx("span",{className:D("rounded-full bg-primary-100 px-1.5 py-0.5 text-[10px] font-medium text-primary-700 tabular-nums"),children:w.length})]}),n.jsx(an,{contentClassName:"flex flex-col gap-px",children:w.map(M=>n.jsx(Bt,{session:M,active:Tt(M,r,o),isGenerating:Gt(M,r,o,a),isPinned:!1,selectionMode:b,selected:x.has(M.key),onToggleSelect:k,onSelect:l,onTogglePin:K,onRename:c,onDelete:u,onExport:d},M.key))})]})}return n.jsxs(sn,{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(on,{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(V,{icon:ls,className:"size-3 transition-transform duration-150 group-data-panel-open:rotate-90"})})]}),n.jsx("button",{type:"button",onClick:B,className:D("text-[11px] font-medium px-1.5 py-0.5 rounded-md transition-colors",b?"text-primary-900 bg-primary-200":"text-primary-500 hover:text-primary-700 hover:bg-primary-100"),children:b?"Done":"Select"})]}),n.jsx(an,{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(wr,{className:"flex-1 min-h-0",children:[n.jsx(br,{className:"min-h-0",children:n.jsxs("div",{className:"flex flex-col gap-2 pl-2 pr-2",children:[P.length>0?n.jsx("div",{className:"flex flex-col gap-px",children:P.map(C=>n.jsx(Bt,{session:C,active:Tt(C,r,o),isGenerating:Gt(C,r,o,a),isPinned:!0,selectionMode:b,selected:x.has(C.key),onToggleSelect:k,onSelect:l,onTogglePin:K,onRename:c,onDelete:u,onExport:d},C.key))}):null,X?n.jsx("div",{className:"my-1 border-t border-primary-200/80"}):null,Y.chat.length>0?n.jsxs("div",{className:"flex flex-col gap-px",children:[n.jsx("div",{className:D("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:Y.chat.map(C=>n.jsx(Bt,{session:C,active:Tt(C,r,o),isGenerating:Gt(C,r,o,a),isPinned:!1,selectionMode:b,selected:x.has(C.key),onToggleSelect:k,onSelect:l,onTogglePin:K,onRename:c,onDelete:u,onExport:d},C.key))})]}):null,q("webchat","🦎 OpenCami",Y.webchat),q("subagent","🤖 Sub-agents",Y.subagent),q("cron","⏰ Cron / Isolated",Y.cron),q("other","📁 Other",Y.other)]})}),n.jsx(Sr,{orientation:"vertical",children:n.jsx(vr,{})})]})}),b?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:S,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:N,disabled:te===0,className:D("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(V,{icon:Qn,size:14,strokeWidth:1.5}),"Delete"]}),n.jsx("button",{type:"button",onClick:E,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]})},Di);function Di(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 Oi=s.lazy(()=>et(()=>import("./settings-dialog-CB1OiRWU.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}))),Li=s.lazy(()=>et(()=>import("./session-export-dialog-Cf8eisLM.js"),__vite__mapDeps([25,1,4,3,5,6,7,8,9,2])).then(e=>({default:e.SessionExportDialog})));function Pi({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:g,pathsError:j,paths:h,handleOpenSettings:b,closeSettings:y,copySessionsDir:x,copyStorePath:O}=wo(),{deleteSession:R}=To(),{renameSession:P}=Ro(),T={duration:.15,ease:l?"easeIn":"easeOut"},[X,Y]=s.useState(!1),[_,te]=s.useState(null),[B,k]=s.useState(""),[S,E]=s.useState(!1),[N,K]=s.useState(null),[$,q]=s.useState(null),[C,L]=s.useState(""),[w,M]=s.useState(!1),[z,Q]=s.useState(null),[J,G]=s.useState(null),[W,re]=s.useState(""),le=ut();function ne(I){te(I.key),k(I.label||I.title||I.derivedTitle||""),Y(!0)}function Z(I){_&&P(_,I),Y(!1),te(null)}function ae(I){K(I.key),q(I.friendlyId),L(I.label||I.title||I.derivedTitle||I.friendlyId),E(!0)}function oe(){if(N&&$){const I=$===t;I&&d&&d(),R(N,$,I)}E(!1),K(null),q(null)}function ie(I){Q(I.key),G(I.friendlyId),re(I.label||I.title||I.derivedTitle||I.friendlyId),M(!0)}function he(I){if(z&&J){const pe=me.history(J,z),A=le.getQueryData(pe);A?.messages&&Do(W,A.messages,I)}M(!1),Q(null),G(null)}const ge={className:"border-r border-primary-200 h-full overflow-hidden bg-primary-100 flex flex-col"};return n.jsxs(ve.aside,{initial:!1,animate:{width:l?48:"var(--opencami-sidebar-width)"},transition:T,className:ge.className,children:[n.jsxs(ve.div,{layout:!0,transition:{layout:T},className:D("flex items-center h-12 px-2 justify-between"),children:[n.jsx(Ne,{initial:!1,children:l?null:n.jsx(ve.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,children:n.jsxs(He,{to:"/new",className:D(Qe({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),children:[n.jsx(Qs,{className:"size-5"}),n.jsx(Zs,{})]})})}),n.jsx(Te,{children:n.jsxs(Re,{children:[n.jsx(Me,{onClick:c,render:n.jsx(be,{size:"icon-sm",variant:"ghost",children:n.jsx(V,{icon:cs,size:20,strokeWidth:1.5})})}),n.jsx(Ie,{side:"right",children:l?"Open Sidebar":"Close Sidebar"})]})})]}),n.jsxs("div",{className:"px-2 mb-4 flex flex-col gap-1",children:[n.jsxs(ve.div,{layout:!0,transition:{layout:T},className:"w-full space-y-2",children:[n.jsxs(be,{disabled:a,variant:"ghost",size:"sm",onClick:i,onMouseUp:u,className:"w-full pl-1.5 justify-start",children:[n.jsx(V,{icon:us,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Ne,{initial:!1,mode:"wait",children:!l&&n.jsx(ve.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(Te,{children:n.jsxs(Re,{children:[n.jsx(Me,{asChild:!0,children:n.jsxs(He,{to:"/files",className:D(Qe({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(V,{icon:ds,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Ne,{initial:!1,mode:"wait",children:!l&&n.jsx(ve.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Files"})})]})}),l&&n.jsx(Ie,{side:"right",children:"Files"})]})}),(()=>{try{const I=localStorage.getItem("opencami-memory-viewer");return I===null?!0:I==="true"}catch{return!0}})()&&n.jsx(Te,{children:n.jsxs(Re,{children:[n.jsx(Me,{asChild:!0,children:n.jsxs(He,{to:"/memory",className:D(Qe({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(V,{icon:Zt,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Ne,{initial:!1,mode:"wait",children:!l&&n.jsx(ve.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Memory"})})]})}),l&&n.jsx(Ie,{side:"right",children:"Memory"})]})}),(()=>{try{return localStorage.getItem("opencami-skills-browser")==="true"}catch{return!1}})()&&n.jsx(Te,{children:n.jsxs(Re,{children:[n.jsx(Me,{asChild:!0,children:n.jsxs(He,{to:"/skills",className:D(Qe({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(V,{icon:fs,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Ne,{initial:!1,mode:"wait",children:!l&&n.jsx(ve.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Skills"})})]})}),l&&n.jsx(Ie,{side:"right",children:"Skills"})]})}),(()=>{try{return localStorage.getItem("opencami-agent-manager")==="true"}catch{return!1}})()&&n.jsx(Te,{children:n.jsxs(Re,{children:[n.jsx(Me,{asChild:!0,children:n.jsxs(He,{to:"/agents",className:D(Qe({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(V,{icon:Zt,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Ne,{initial:!1,mode:"wait",children:!l&&n.jsx(ve.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Agents"})})]})}),l&&n.jsx(Ie,{side:"right",children:"Agents"})]})}),(()=>{try{return localStorage.getItem("opencami-cron-manager")==="true"}catch{return!1}})()&&n.jsx(Te,{children:n.jsxs(Re,{children:[n.jsx(Me,{asChild:!0,children:n.jsxs(He,{to:"/bots",className:D(Qe({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(V,{icon:ms,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Ne,{initial:!1,mode:"wait",children:!l&&n.jsx(ve.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Cron Jobs"})})]})}),l&&n.jsx(Ie,{side:"right",children:"Cron Jobs"})]})}),(()=>{try{return localStorage.getItem("feature_dashboard")==="true"}catch{return!1}})()&&n.jsx(Te,{children:n.jsxs(Re,{children:[n.jsx(Me,{asChild:!0,children:n.jsxs(He,{to:"/dashboard",className:D(Qe({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(V,{icon:ps,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Ne,{initial:!1,mode:"wait",children:!l&&n.jsx(ve.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Dashboard"})})]})}),l&&n.jsx(Ie,{side:"right",children:"Dashboard"})]})})]}),n.jsx(ve.div,{layout:!0,transition:{layout:T},className:"w-full",children:n.jsxs(be,{variant:"ghost",size:"sm",onClick:f,className:"w-full pl-1.5 justify-start",children:[n.jsx(V,{icon:hs,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Ne,{initial:!1,mode:"wait",children:!l&&n.jsx(ve.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(Ne,{initial:!1,children:!l&&n.jsx(ve.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(Ai,{sessions:e,activeFriendlyId:t,activeSessionKey:r,isStreaming:o,onSelect:u,onRename:ne,onDelete:ae,onExport:ie})})},"content")})}),n.jsx("div",{className:"px-2 py-3 border-t border-primary-200 bg-primary-100",children:n.jsx(ve.div,{layout:!0,transition:{layout:T},className:"w-full",children:n.jsxs(be,{variant:"ghost",size:"sm",onClick:b,title:l?"Settings":void 0,className:"w-full justify-start pl-1.5",children:[n.jsx(V,{icon:gs,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Ne,{initial:!1,mode:"wait",children:!l&&n.jsx(ve.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(Oi,{open:m,onOpenChange:p,pathsLoading:g,pathsError:j,paths:h,onClose:y,onCopySessionsDir:x,onCopyStorePath:O})}),n.jsx(Ho,{open:X,onOpenChange:Y,sessionTitle:B,onSave:Z,onCancel:()=>Y(!1)}),n.jsx(Fo,{open:S,onOpenChange:E,sessionTitle:C,onConfirm:oe,onCancel:()=>E(!1)}),w&&n.jsx(s.Suspense,{fallback:null,children:n.jsx(Li,{open:w,onOpenChange:M,sessionTitle:W,onExport:he,onCancel:()=>M(!1)})})]})}function _i(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 Ki(e,t){return!(e.activeFriendlyId!==t.activeFriendlyId||e.activeSessionKey!==t.activeSessionKey||e.isStreaming!==t.isStreaming||e.creatingSession!==t.creatingSession||e.isCollapsed!==t.isCollapsed||!_i(e.sessions,t.sessions))}const zi=s.memo(Pi,Ki);function _n(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 Kn(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 Ui({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:Kn(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:_n(m),maxStr:_n(t),colors:Kn(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:D("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:D("h-full rounded-full transition-all duration-500 ease-out",l.bar,u&&"animate-pulse"),style:{width:`${o}%`}})}),n.jsx("span",{className:D("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:D("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:D("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:D("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:D("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(Ui);function Fi({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(be,{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(V,{icon:xs,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 Hi=s.memo(Fi);function Wi(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function Xi(e){const t=new Date(e);return Wi(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 Yi(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 Bi({timestamp:e}){const t=Xi(e),r=Yi(e);return n.jsx(Te,{children:n.jsxs(Re,{children:[n.jsx(Me,{className:"inline-flex items-center text-xs text-primary-600",children:t}),n.jsx(Ie,{side:"top",children:r})]})})}function Gi({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 y=localStorage.getItem("opencami-tts-enabled");return y===null?!0:y==="true"}catch{return!0}});s.useEffect(()=>{function y(x){x.key==="opencami-tts-enabled"&&p(x.newValue===null?!0:x.newValue==="true")}return window.addEventListener("storage",y),()=>window.removeEventListener("storage",y)},[]),s.useEffect(()=>()=>{f.current?.abort(),u.current&&(u.current.pause(),u.current=null),d.current&&(URL.revokeObjectURL(d.current),d.current=null)},[]);const g=async()=>{try{await navigator.clipboard.writeText(e),i(!0),window.setTimeout(()=>i(!1),1400)}catch{i(!1)}},j=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 y=new AbortController;f.current=y,c("loading");try{const x=await fetch("/api/tts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:e}),signal:y.signal});if(!x.ok)throw new Error("TTS failed");const O=await x.blob(),R=URL.createObjectURL(O);d.current=R;const P=new Audio(R);u.current=P,P.onended=()=>{c("idle"),d.current&&(URL.revokeObjectURL(d.current),d.current=null),u.current=null},P.onerror=()=>{c("idle"),d.current&&(URL.revokeObjectURL(d.current),d.current=null),u.current=null},await P.play(),c("playing")}catch(x){if(x instanceof Error&&x.name==="AbortError"){c("idle");return}c("idle"),d.current&&(URL.revokeObjectURL(d.current),d.current=null),u.current=null}},h=t==="end"?"justify-end":"justify-start",b=t==="start"&&m&&e.trim().length>0;return n.jsxs("div",{className:D("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",h),children:[n.jsx(Te,{children:n.jsxs(Re,{children:[n.jsx(Me,{type:"button",onClick:()=>{g().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(V,{icon:a?fn:ys,size:16,strokeWidth:1.6})}),n.jsx(Ie,{side:"top",children:"Copy"})]})}),b&&n.jsx(Te,{children:n.jsxs(Re,{children:[n.jsx(Me,{type:"button",onClick:()=>{j().catch(()=>{})},disabled:l==="loading",className:D("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(V,{icon:l==="loading"?ws:l==="playing"?Zn:bs,size:16,strokeWidth:1.6,className:D(l==="loading"&&"animate-spin")})}),n.jsx(Ie,{side:"top",children:l==="loading"?"Generating speech…":l==="playing"?"Stop":"Listen"})]})}),n.jsx(Bi,{timestamp:r})]})}function kr({children:e,className:t,...r}){return n.jsx("div",{className:D("flex gap-3 w-full",t),...r,children:e})}function Vi({children:e,markdown:t=!1,className:r,...o}){const a=D("rounded-[12px] break-words whitespace-normal min-w-0 max-w-full overflow-x-hidden",r);return t?n.jsx(eo,{className:a,...o,children:e}):n.jsx("div",{className:a,...o,children:e})}function qi({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"?Pt:r==="output-available"?Jn:Ss,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(sn,{defaultOpen:t,children:[n.jsxs(on,{render:n.jsx(be,{variant:"ghost",className:"h-auto w-full justify-start gap-1.5 rounded-md px-1.5 py-1"}),children:[n.jsx(V,{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(V,{icon:er,size:14,strokeWidth:1.5,className:"ml-auto text-primary-700/80 transition-transform duration-150 group-data-panel-open:rotate-180"})]}),n.jsx(an,{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 Ji=s.lazy(()=>et(()=>import("./thinking-BqZoM6BP.js"),__vite__mapDeps([26,1,3,17,18,5,6,7,8,14,19,4,9,2,11,15,20,13,21,22,23,16,24])).then(e=>({default:e.Thinking}))),Qi=s.lazy(()=>et(()=>import("./search-sources-badge-DOd5AI-i.js"),__vite__mapDeps([27,1,3])).then(e=>({default:e.SearchSourcesBadge})));function Zi(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 zn(e){return Xe(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 ea(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 Un(e,t){if(!t)return"";const r=Xe(e);return r.length===0?"":r.map(o=>o.id?ea(t.get(o.id)):"missing").join("||")}function ta(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 $n(e){const t=[e.createdAt,e.created_at,e.timestamp,e.time,e.ts];for(const r of t){const o=ta(r);if(o)return o}return null}function ln(e){const r=(Array.isArray(e.content)?e.content:[]).find(o=>o.type==="thinking");return r&&"thinking"in r?String(r.thinking??""):null}function na(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 at=/^📎 Uploaded file:\s*(\/uploads\/\S+)\s*$/;function ra(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 sa(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(at.test(i)){o.push(i);continue}if(o.length>0&&i.trim()===""){o.push(i);continue}break}const a=r[0]??"";return at.test(a)?o.filter(i=>at.test(i)):[]}function oa(e){const t=[],r=new Set;for(const o of sa(e)){const i=o.match(at)?.[1];!i||r.has(i)||(r.add(i),t.push({path:i,filename:i.split("/").pop()||i}))}return t}function ia(e){const t=e.split(`
|
|
11
|
+
`);if(!at.test(t[0]??""))return e.trim();let r=0;for(;r<t.length&&at.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 aa({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}=to(),p=e.role||"assistant",g=De(e),j=ln(e),h=na(e),b=p==="user",y=s.useMemo(()=>h.map(S=>`data:${S.source.media_type};base64,${S.source.data}`),[h]),x=tn(e),O=Lt(),R=zs(S=>S.openInEditor),P=s.useMemo(()=>oa(g),[g]),[T,X]=s.useState({}),Y=s.useMemo(()=>ia(g),[g]);s.useEffect(()=>{let S=!1;async function E(){const N={};await Promise.all(P.map(async K=>{try{const $=await fetch(`/api/files/info?path=${encodeURIComponent(K.path)}`);if(!$.ok){N[K.path]=null;return}const q=await $.json();N[K.path]=typeof q.size=="number"?q.size:null}catch{N[K.path]=null}})),S||X(N)}return P.length>0?E():X({}),()=>{S=!0}},[P]);const _=async S=>{R(S),await O({to:"/files"})},te=p==="assistant"?Xe(e):[],B=te.length>0,k=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:D("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",b?"items-end":"items-start"),children:[j&&m.showReasoningBlocks&&n.jsx("div",{className:"w-full max-w-[var(--opencami-chat-width)]",children:n.jsx(s.Suspense,{fallback:null,children:n.jsx(Ji,{content:j})})}),h.length>0&&n.jsx("div",{className:D("flex flex-wrap gap-2 mb-2",b?"justify-end":"justify-start"),children:h.map((S,E)=>n.jsx("img",{src:y[E],alt:`Attachment ${E+1}`,loading:"lazy",decoding:"async",fetchPriority:"low",className:"max-w-[300px] max-h-[300px] rounded-lg object-cover"},E))}),P.length>0&&n.jsx("div",{className:D("mb-2 flex w-full flex-col gap-2",b?"items-end":"items-start"),children:P.map(S=>n.jsxs("button",{type:"button",onClick:()=>{_(S.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(V,{icon:tr,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:S.filename}),n.jsx("p",{className:"text-xs text-primary-600",children:ra(T[S.path]??null)})]})]},S.path))}),n.jsx(kr,{className:D("min-w-0 max-w-full",b?"flex-row-reverse":""),children:n.jsx(Vi,{markdown:!b,isStreaming:!b&&o,className:D("text-primary-900 opencami-text-size min-w-0 max-w-full",b?"opencami-message-user bg-primary-100 px-4 py-[var(--opencami-user-bubble-py)] max-w-[85%]":"opencami-message-assistant bg-transparent w-full",!b&&o&&"stream-fade-in"),children:Y})}),B&&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(S=>{const E=S.id?t?.get(S.id):void 0,N=Zi(S,E);return n.jsx(qi,{toolPart:N,defaultOpen:!1},S.id||S.name)})}),k.length>0&&n.jsx("div",{className:"w-full max-w-[var(--opencami-chat-width)]",children:n.jsx(s.Suspense,{fallback:null,children:n.jsx(Qi,{sources:k})})}),!B&&n.jsx(Gi,{text:g,timestamp:x,align:b?"end":"start",forceVisible:r})]})}function la(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")||De(e.message)!==De(t.message)||ln(e.message)!==ln(t.message)||zn(e.message)!==zn(t.message)||Un(e.message,e.toolResultsByCallId)!==Un(t.message,t.toolResultsByCallId)||$n(e.message)!==$n(t.message))}const Vt=s.memo(aa,la);function ca({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(be,{variant:"secondary",size:"icon-sm",className:D("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(V,{icon:er,size:18,strokeWidth:1.8})})}function ua({className:e,viewportRef:t,scrollRef:r,viewportProps:o}){return n.jsxs(wr,{className:D("relative flex flex-1 min-h-0 flex-col",e),children:[n.jsx(br,{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(ca,{scrollRef:r})})}),n.jsx(Sr,{orientation:"vertical",children:n.jsx(vr,{})}),n.jsx(gi,{})]})}function da(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 fa(e,t){return!(e.className!==t.className||e.viewportRef!==t.viewportRef||e.scrollRef!==t.scrollRef||!da(e.viewportProps,t.viewportProps))}const ma=s.memo(ua,fa);function pa({viewportNode:e,children:t}){return e?qr.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 ha({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(ma,{className:t,viewportRef:c,scrollRef:a,viewportProps:o}),n.jsx(pa,{viewportNode:i,children:e})]})}const ga=s.memo(ha);function xa({children:e,className:t,...r}){return n.jsx("div",{className:D("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 ya({...e}){return n.jsx("div",{className:"h-px w-full shrink-0 scroll-mt-4 pt-6","aria-hidden":"true",...e})}function wa({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:D("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 ba({className:e}){return n.jsxs("div",{className:D("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(wa,{className:"text-sm",duration:2,children:"Generating..."})]})}const Fn=s.lazy(()=>et(()=>import("./follow-up-suggestions-DP_84nA2.js"),__vite__mapDeps([28,1,3,17,18,5,6,7,8,14,19,4,9,2,11,15,20,13,21,22,23,16,24])).then(e=>({default:e.FollowUpSuggestions})));function Sa({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:g,jumpToMessageId:j}){const h=s.useRef(null),b=s.useRef(null),y=s.useRef(!1),x=s.useRef(d),O=s.useRef(void 0),[R,P]=s.useState(null),T=s.useMemo(()=>e.filter(w=>w.role!=="toolResult"),[e]),X=s.useDeferredValue(T),Y=s.useMemo(()=>{const w=new Map;for(const M of e){if(M.role!=="toolResult")continue;const z=M.toolCallId;typeof z=="string"&&z.trim().length>0&&w.set(z,M)}return w},[e]),_=s.useDeferredValue(Y),te=s.useMemo(()=>{const w=[];for(const M of X){if(M.role!=="assistant")continue;const z=Xe(M);for(const Q of z){if(!Q.id)continue;const J=Q.name==="web_search",G=Q.name==="web_fetch",W=Q.name==="exec";if(!J&&!G&&!W)continue;const re=_.get(Q.id),le=re?.content?.map(ne=>ne.type==="text"?String(ne.text??""):"").join("").trim()??"";w.push([Q.id,Q.name??"",typeof Q.arguments?.url=="string"?Q.arguments.url:"",re?.isError?"1":"0",le].join("::"))}}return w.join("||")},[X,_]),B=s.useMemo(()=>{const w=J=>J?J.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():"",M=(J,G,W)=>{try{const re=JSON.parse(J),le=Array.isArray(re)?re:re?.results??re?.web?.results??[];if(!Array.isArray(le))return!1;let ne=!1;for(const Z of le)Z?.url&&Z?.title&&!W.has(Z.url)&&(W.add(Z.url),G.push({title:w(Z.title),url:Z.url,snippet:w(Z.description||Z.snippet||Z.content||"")}),ne=!0);return ne}catch{return!1}},z=[],Q=new Set;for(const J of X){if(J.role!=="assistant")continue;const G=Xe(J);for(const W of G){if(!W.id)continue;const re=W.name==="web_search",le=W.name==="web_fetch",ne=W.name==="exec";if(!re&&!le&&!ne)continue;const Z=_.get(W.id);if(!Z)continue;const ae=Z.content?.map(oe=>oe.type==="text"?String(oe.text??""):"").join("").trim();if(ae){if(re||ne){if(ne&&(!ae.includes('"results"')||!ae.includes('"url"')))continue;let oe=ae;const ie=ae.indexOf("{");ie>0&&(oe=ae.slice(ie));const he=oe.lastIndexOf("}");he>0&&(oe=oe.slice(0,he+1)),M(oe,z,Q)}else if(le){const oe=W.arguments?.url;if(oe&&!Q.has(oe)){Q.add(oe);let ie;try{ie=new URL(oe).hostname}catch{ie=oe}z.push({title:ie,url:oe})}}}}}return z},[te,X,_]),k=T.map((w,M)=>({message:w,index:M})).filter(({message:w})=>w.role!=="user").map(({index:w})=>w).pop(),S=T.map((w,M)=>({message:w,index:M})).filter(({message:w})=>w.role==="assistant").map(({index:w})=>w).pop(),E=T.map((w,M)=>({message:w,index:M})).filter(({message:w})=>w.role==="user").map(({index:w})=>w).pop(),N=l&&(typeof E!="number"||typeof k!="number"||k<E),K=typeof E=="number"?E:-1,$=d&&K>=0,q=typeof S=="number"?T[S]:void 0,C=q?De(q):"",L=!l&&!c&&C.length>0&&g!==void 0&&(typeof E!="number"||typeof S!="number"||S>E);return s.useLayoutEffect(()=>{if(!t){if(d){const w=!x.current||O.current!==E;x.current=!0,O.current=E,w&&b.current&&(y.current=!0,b.current.scrollIntoView({behavior:"auto",block:"start"}),window.setTimeout(()=>{y.current=!1},0));return}x.current=!1,O.current=E,h.current&&(y.current=!0,h.current.scrollIntoView({behavior:"auto",block:"end"}),window.setTimeout(()=>{y.current=!1},0))}},[t,T.length,u,d,E]),s.useEffect(()=>{if(!j||t)return;const w=document.getElementById(`message-${j}`);if(!w)return;w.scrollIntoView({behavior:"smooth",block:"center"}),P(j);const M=window.setTimeout(()=>{P(z=>z===j?null:z)},1800);return()=>window.clearTimeout(M)},[j,t,T]),n.jsx(ga,{className:"flex-1 min-h-0 -mb-4",children:n.jsxs(xa,{className:"pt-6",style:p,children:[a&&i==="start"?a:null,r&&!a?o??n.jsx("div",{"aria-hidden":!0}):$?n.jsxs(n.Fragment,{children:[T.slice(0,K).map((w,M)=>{const z=typeof w.id=="string"?w.id:void 0,Q=z||M,J=typeof k=="number"&&M===k,G=typeof k=="number"&&M===k,W=w.role==="assistant"&&Xe(w).length>0;return n.jsx(Vt,{message:w,toolResultsByCallId:W?Y:void 0,forceActionsVisible:J,isStreaming:G&&c,isLastAssistant:G,aggregatedSearchSources:G?B:void 0,messageDomId:z?`message-${z}`:void 0,highlighted:R===z},Q)}),n.jsxs("div",{className:"flex flex-col gap-[var(--opencami-msg-gap)]",style:{minHeight:`${Math.max(0,f)}px`},children:[T.slice(K).map((w,M)=>{const z=K+M,Q=typeof w.id=="string"?w.id:void 0,J=Q||z,G=typeof k=="number"&&z===k,W=typeof k=="number"&&z===k,re=z===E?b:void 0,le=z===E?"scroll-mt-0":void 0,ne=z===E?m:void 0,Z=w.role==="assistant"&&Xe(w).length>0;return n.jsx(Vt,{message:w,toolResultsByCallId:Z?Y:void 0,forceActionsVisible:G,isStreaming:W&&c,isLastAssistant:W,aggregatedSearchSources:W?B:void 0,wrapperRef:re,wrapperClassName:le,wrapperScrollMarginTop:ne,messageDomId:Q?`message-${Q}`:void 0,highlighted:R===Q},J)}),N?n.jsx("div",{className:"py-2",children:n.jsx(ba,{})}):null,L&&g?n.jsx(s.Suspense,{fallback:null,children:n.jsx(Fn,{responseText:C,onSuggestionClick:g,disabled:l})}):null]})]}):n.jsxs(n.Fragment,{children:[T.map((w,M)=>{const z=typeof w.id=="string"?w.id:void 0,Q=z||M,J=typeof k=="number"&&M===k,G=typeof k=="number"&&M===k,W=w.role==="assistant"&&Xe(w).length>0;return n.jsx(Vt,{message:w,toolResultsByCallId:W?Y:void 0,forceActionsVisible:J,isStreaming:G&&c,isLastAssistant:G,aggregatedSearchSources:G?B:void 0,messageDomId:z?`message-${z}`:void 0,highlighted:R===z},Q)}),L&&g?n.jsx(s.Suspense,{fallback:null,children:n.jsx(Fn,{responseText:C,onSuggestionClick:g,disabled:l})}):null]}),a&&i==="end"?a:null,n.jsx(ya,{ref:h})]})})}function va(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 ja=s.memo(Sa,va),Cr=s.createContext({isLoading:!1,value:"",setValue:()=>{},maxHeight:240,onSubmit:void 0,disabled:!1,textareaRef:Jr.createRef()});let lt=null,Hn=!1;function Ea(){Hn||typeof window>"u"||(Hn=!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||!lt||lt.disabled||lt.focus()}))}function Nr(){return s.useContext(Cr)}function ka({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);Ea();function g(h){m(h),a?.(h)}function j(h){c||p.current?.focus(),u?.(h)}return n.jsx(Te,{children:n.jsx(Cr.Provider,{value:{isLoading:t,value:o??f,setValue:a??g,maxHeight:r,onSubmit:i,disabled:c,textareaRef:p},children:n.jsx("div",{onClick:j,className:D("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 Ca({className:e,onKeyDown:t,disableAutosize:r=!1,inputRef:o,...a}){const{value:i,setValue:l,maxHeight:c,onSubmit:u,disabled:d,textareaRef:f}=Nr();function m(h){!h||r||(h.style.height="auto",typeof c=="number"?h.style.height=`${Math.min(h.scrollHeight,c)}px`:h.style.height=`min(${h.scrollHeight}px, ${c})`)}function p(h){f.current=h,typeof o=="function"?o(h):o&&"current"in o&&(o.current=h),h?lt=h:lt===h&&(lt=null),m(h)}s.useLayoutEffect(()=>{if(!f.current||r)return;const h=f.current;h.style.height="auto",typeof c=="number"?h.style.height=`${Math.min(h.scrollHeight,c)}px`:h.style.height=`min(${h.scrollHeight}px, ${c})`},[i,c,r]);function g(h){m(h.target),l(h.target.value)}function j(h){h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),u?.()),t?.(h)}return n.jsx("textarea",{ref:p,value:i,onChange:g,onKeyDown:j,className:D("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 Na({children:e,className:t,...r}){return n.jsx("div",{className:D("flex items-center gap-2",t),...r,children:e})}function Wn({tooltip:e,children:t,className:r,side:o="top",...a}){const{disabled:i}=Nr();return n.jsxs(Re,{...a,children:[n.jsx(Me,{disabled:i,onClick:l=>l.stopPropagation(),children:t}),n.jsx(Ie,{side:o,className:r,children:e})]})}const Tr="opencami-selected-model";function Ta(){if(typeof window>"u")return null;try{return localStorage.getItem(Tr)}catch{return null}}function Ra(e){if(!(typeof window>"u"))try{localStorage.setItem(Tr,e)}catch{}}function Ma({className:e,onModelChange:t}){const[r,o]=s.useState([]),[a,i]=s.useState(""),[l,c]=s.useState(!0),[u,d]=s.useState(null),f=s.useRef(null);s.useEffect(()=>{let h=!0;async function b(){f.current?.abort();const y=new AbortController;f.current=y;try{c(!0),d(null);const x=await fetch("/api/models",{signal:y.signal});if(!x.ok)throw new Error("Failed to fetch models");const O=await x.json();if(!h)return;if(O.ok&&O.models.length>0){o(O.models);const R=Ta(),P=R&&O.models.some(T=>T.id===R)?R:O.defaultModel;i(P),t?.(P)}else throw new Error("No models available")}catch(x){if(x instanceof Error&&x.name==="AbortError"||!h)return;console.error("[model-selector] Error fetching models:",x),d(x instanceof Error?x.message:"Failed to load models"),o([{id:"default",name:"Default Model"}]),i("default")}finally{h&&c(!1)}}return b(),()=>{h=!1,f.current?.abort()}},[t]);function m(h){i(h),Ra(h),t?.(h)}if(l)return n.jsxs("div",{className:D("flex items-center gap-2 text-xs text-primary-500",e),children:[n.jsx(V,{icon:Ft,size:14}),n.jsx("span",{children:"Loading..."})]});if(u||r.length===0)return null;const p=r.find(h=>h.id===a),g=p?.name||"Select Model",j=(()=>{if(!p?.name)return g;const b=p.name.replace(/\s*\([^)]*\)\s*$/,"").trim(),y=b.split(/\s+/);return y.length>3?y.slice(0,3).join(" "):b})();return r.length===1?n.jsxs("div",{className:D("flex items-center gap-2 text-xs text-primary-500",e),children:[n.jsx(V,{icon:Ft,size:14}),n.jsx("span",{className:"font-[450] md:hidden",children:j}),n.jsx("span",{className:"font-[450] hidden md:inline",children:g})]}):n.jsxs(_t,{children:[n.jsxs(Kt,{className:D("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(V,{icon:Ft,size:14}),n.jsx("span",{className:"md:hidden",children:j}),n.jsx("span",{className:"hidden md:inline",children:g})]}),n.jsx(zt,{side:"top",align:"start",children:r.map(h=>n.jsxs(Be,{onClick:()=>m(h.id),className:"justify-between min-w-[180px]",children:[n.jsx("span",{children:h.name}),a===h.id&&n.jsx(V,{icon:fn,size:14,className:"text-primary-600"})]},h.id))})]})}const Rr="opencami-personas-enabled",cn="opencami-active-persona";function Ia(){if(typeof window>"u")return!0;try{const e=localStorage.getItem(Rr);return e===null?!0:e==="true"}catch{return!0}}function Aa(){if(typeof window>"u")return null;try{const e=localStorage.getItem(cn);return e?JSON.parse(e):null}catch{return null}}function Xn(e){if(!(typeof window>"u"))try{e?localStorage.setItem(cn,JSON.stringify(e)):localStorage.removeItem(cn)}catch{}}const Da={core:"Core",creative:"Creative",curator:"Curator",learning:"Learning",lifestyle:"Lifestyle",professional:"Professional"};function Oa({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(Ia),p=s.useRef(null);s.useEffect(()=>{const b=y=>{y.key===Rr&&m(y.newValue===null?!0:y.newValue==="true")};return window.addEventListener("storage",b),()=>window.removeEventListener("storage",b)},[]),s.useEffect(()=>{let b=!0;async function y(){p.current?.abort();const x=new AbortController;p.current=x;try{c(!0);const O=await fetch("/api/personas",{signal:x.signal});if(!O.ok){d(!1);return}const R=await O.json();if(!b)return;R.ok&&R.available?(o(R.personas),d(!0),i(Aa())):d(!1)}catch(O){if(O instanceof Error&&O.name==="AbortError"||!b)return;d(!1)}finally{b&&c(!1)}}return y(),()=>{b=!1,p.current?.abort()}},[]);const g=s.useCallback(b=>{i(b),Xn(b),t(`/persona ${b.id}`)},[t]),j=s.useCallback(()=>{i(null),Xn(null),t("/persona exit")},[t]);if(l||!u||!f)return null;const h=Object.entries(r);return h.length===0?null:n.jsxs(_t,{children:[n.jsxs(Kt,{className:D("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(zt,{side:"top",align:"start",className:"w-[300px] max-h-[360px] overflow-y-auto",children:[a&&n.jsxs(n.Fragment,{children:[n.jsxs(Be,{onClick:j,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"})]}),h.map(([b,y])=>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:Da[b]??b}),y.map(x=>n.jsxs(Be,{onClick:()=>g(x),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:x.emoji}),n.jsx("span",{className:"truncate",children:x.name})]}),n.jsx("span",{className:"text-[11px] text-primary-400 truncate ml-2 max-w-[140px]",children:x.description})]},x.id))]},b))]})]})}const La=[{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 Pa({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(be,{variant:"ghost",size:"sm",onClick:()=>o(!0),className:D("h-7 w-7 p-0",e),title:"Show commands (Ctrl+/)",children:n.jsx(V,{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(V,{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(be,{variant:"ghost",size:"sm",onClick:()=>o(!1),className:"h-7 w-7 p-0",children:n.jsx(V,{icon:Pt,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"}),La.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 _a=10*1024*1024,ot=1280,Ka=.75,za=300*1024,Ua=["image/png","image/jpeg","image/gif","image/webp"],Mr=["pdf","txt","md","csv","json","xml","yaml","yml","log","py","js","ts","html","css"],$a=[".png",".jpg",".jpeg",".gif",".webp",...Mr.map(e=>`.${e}`)].join(",");function Fa(){if(typeof document>"u")return!1;try{const e=document.createElement("canvas");return!!(e.getContext&&e.getContext("2d"))}catch{return!1}}async function Ha(e){if(!Fa())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>ot||c>ot)&&(l>c?(c=Math.round(c*ot/l),l=ot):(l=Math.round(l*ot/c),c=ot));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=Ka,p=u.toDataURL(f,m);if(f==="image/jpeg"){const j=za*1.37;for(;p.length>j&&m>.3;)m-=.1,p=u.toDataURL(f,m)}const g=p.split(",")[1];if(!g){i(),r(new Error("Failed to encode image"));return}i(),t(g)}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 Ir(e){return Ua.includes(e.type)}function Wa(e){const t=e.name.includes(".")?e.name.split(".").pop()?.toLowerCase():"";return!!(t&&Mr.includes(t))}async function Xa(e){const t=crypto.randomUUID();if(!Ir(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>_a)return{id:t,file:e,preview:null,type:"image",base64:null,error:"Image is too large. Maximum size is 10MB."};try{const r=await Ha(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 Ya({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:$a,multiple:!0,onChange:i,className:"hidden","aria-hidden":"true"}),n.jsx(be,{variant:"ghost",size:"icon-sm",onClick:a,disabled:t,className:r,"aria-label":"Attach file",type:"button",children:n.jsx(V,{icon:vs,size:18,strokeWidth:1.8})})]})}function Yn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Ba(e){const t=e.split(".");return t.length>1&&t.pop()?.toUpperCase()||""}function Ga({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:D("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," (",Yn(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:D("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(V,{icon:tr,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:[Ba(e.file.name)," •"," ",Yn(e.file.size)]})]}),n.jsx(be,{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(V,{icon:Pt,size:14})})]})}function Va({attachments:e,onRemove:t,className:r}){return e.length===0?null:n.jsx("div",{className:D("flex flex-wrap gap-2 px-4",r),children:e.map(o=>n.jsx(Ga,{attachment:o,onRemove:t},o.id))})}function qa({commands:e,selectedIndex:t,onSelect:r,className:o}){return e.length===0?null:n.jsx("div",{className:D("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:D("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 Ja=s.memo(qa),un=cr()(lr(e=>({level:"low",setLevel:t=>e({level:t})}),{name:"thinking-level"}));function Qa(){const e=un(r=>r.level),t=un(r=>r.setLevel);return{level:e,setLevel:t}}const qt=[{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 Za({className:e}){const{level:t,setLevel:r}=Qa(),o=qt.find(a=>a.value===t)??qt[1];return n.jsxs(_t,{children:[n.jsxs(Kt,{className:D("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(V,{icon:Zt,size:20,strokeWidth:1.5,className:D(t==="off"?"text-primary-400":"text-primary-700")}),n.jsx("span",{className:"text-pretty",children:o.shortLabel})]}),n.jsx(zt,{side:"top",align:"start",className:"min-w-[190px]",children:qt.map(a=>n.jsxs(Be,{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(V,{icon:fn,size:20,strokeWidth:1.5,className:"text-primary-600"})]},a.value))})]})}const Bn=[{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 el({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),[g,j]=s.useState(!1),[h,b]=s.useState(!1),[y,x]=s.useState(!1),[O,R]=s.useState(0),[P,T]=s.useState(!1),X=s.useRef(null),Y=s.useRef([]),_=s.useRef(null),te=s.useRef(null),B=s.useRef(null),k=s.useRef(null),S=s.useMemo(()=>/^\/\S*$/.test(i)&&!g,[i,g]),E=s.useMemo(()=>S?i.slice(1).toLowerCase():"",[S,i]),N=s.useMemo(()=>S?E?Bn.filter(A=>A.command.slice(1).toLowerCase().startsWith(E)):Bn:[],[S,E]),K=s.useCallback(A=>{k.current=A,a&&(typeof a=="function"?a(A):a.current=A)},[a]),$=s.useCallback(()=>{typeof window>"u"||window.requestAnimationFrame(()=>{k.current?.focus()})},[]),q=s.useCallback(()=>{l(""),f([]),p(0),j(!1),$()},[$]),C=s.useCallback(A=>{l(F=>{const H=`📎 Uploaded file: ${A}
|
|
16
|
+
|
|
17
|
+
Please analyze this file.`;return F.trim()?`${F.trim()}
|
|
18
|
+
|
|
19
|
+
${H}`:H})},[]),L=s.useCallback(async()=>{await fetch("/api/files/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:"/uploads"})})},[]),w=s.useCallback(async A=>{const F=crypto.randomUUID();if(!Wa(A))return{id:F,file:A,preview:null,type:"file",base64:null,error:"Unsupported file type for upload."};try{await L();const H=new FormData;H.append("path","/uploads"),H.append("file",A);const ce=await fetch("/api/files/upload",{method:"POST",body:H});if(!ce.ok){const Se=await ce.text();throw new Error(Se||"File upload failed")}const se=(await ce.json()).files?.[0]?.path;if(!se)throw new Error("Upload succeeded but no path was returned");return C(se),{id:F,file:A,preview:null,type:"file",base64:null,uploadedPath:se}}catch(H){return{id:F,file:A,preview:null,type:"file",base64:null,error:H instanceof Error?H.message:"File upload failed"}}},[C,L]),M=s.useCallback(async A=>{if(A.length===0)return;const F=await Promise.all(A.map(H=>Ir(H)?Xa(H):w(H)));f(H=>[...H,...F]),$()},[$,w]),z=s.useCallback(A=>{f(F=>F.filter(H=>H.id!==A))},[]),Q=s.useCallback(A=>{Array.from(A.dataTransfer.types).includes("Files")&&(A.preventDefault(),A.dataTransfer.dropEffect="copy",b(!0))},[]),J=s.useCallback(A=>{A.preventDefault();const F=A.relatedTarget;F&&A.currentTarget.contains(F)||b(!1)},[]),G=s.useCallback(async A=>{A.preventDefault(),b(!1);const F=Array.from(A.dataTransfer.files??[]);F.length!==0&&await M(F)},[M]),W=s.useCallback(A=>{l(A),p(0),j(!1),$()},[$]),re=s.useCallback(A=>{l(A),p(0),j(!1)},[]),le=s.useCallback(A=>{l(`${A.command} `),p(0),j(!1),$()},[$]),ne=s.useCallback(()=>{if(r)return;if(S&&N.length>0){const H=Math.min(m,N.length-1);le(N[H]);return}const A=i.trim(),F=d.filter(H=>!H.error&&H.base64);A.length===0&&F.length===0||(e(A,{reset:q,setValue:W,model:c||void 0,attachments:F}),$())},[r,S,N,m,le,i,d,e,q,W,c,$]),Z=s.useCallback(A=>{e(A,{reset:q,setValue:W,model:c||void 0,attachments:[]}),$()},[$,e,q,W,c]),ae=s.useCallback(A=>{if(S){if(A.key==="Escape"){A.preventDefault(),j(!0),p(0);return}if(N.length!==0){if(A.key==="ArrowDown"){A.preventDefault(),p(F=>(F+1)%N.length);return}if(A.key==="ArrowUp"){A.preventDefault(),p(F=>(F-1+N.length)%N.length);return}if(A.key==="Tab"){A.preventDefault();const F=Math.min(m,N.length-1);le(N[F])}}}},[S,N,m,le]);s.useEffect(()=>()=>{te.current?.abort(),_.current&&clearInterval(_.current),X.current&&X.current.state!=="inactive"&&X.current.stop(),B.current&&B.current.abort()},[]);const oe=s.useCallback(()=>{if(typeof window>"u")return"auto";try{return localStorage.getItem("opencami-stt-provider")||"auto"}catch{return"auto"}},[]),ie=s.useCallback(()=>{X.current&&X.current.state!=="inactive"&&X.current.stop(),B.current&&B.current.stop(),_.current&&(clearInterval(_.current),_.current=null),x(!1),R(0)},[]),he=s.useCallback(async()=>{const A=oe();if(A==="browser"){const F=window.SpeechRecognition||window.webkitSpeechRecognition;if(!F){alert("Web Speech API is not supported in this browser.");return}const H=new F;H.continuous=!0,H.interimResults=!1,H.lang=navigator.language||"en-US",B.current=H,x(!0),R(0),_.current=setInterval(()=>{R(ue=>ue>=119?(ie(),0):ue+1)},1e3);let ce="";H.onresult=ue=>{for(let se=ue.resultIndex;se<ue.results.length;se++)ue.results[se].isFinal&&(ce+=ue.results[se][0].transcript)},H.onend=()=>{x(!1),R(0),_.current&&clearInterval(_.current),ce.trim()&&(l(ue=>ue+(ue?" ":"")+ce.trim()),$())},H.onerror=()=>{x(!1),R(0),_.current&&clearInterval(_.current)},H.start();return}try{const F=await navigator.mediaDevices.getUserMedia({audio:!0}),H=MediaRecorder.isTypeSupported("audio/webm")?"audio/webm":"audio/mp4",ce=new MediaRecorder(F,{mimeType:H});X.current=ce,Y.current=[],ce.ondataavailable=ue=>{ue.data.size>0&&Y.current.push(ue.data)},ce.onstop=async()=>{F.getTracks().forEach(se=>se.stop());const ue=new Blob(Y.current,{type:H});if(ue.size!==0){T(!0);try{const se=new FormData;se.append("audio",ue,`recording.${H==="audio/webm"?"webm":"mp4"}`),A!=="auto"&&se.append("provider",A),te.current?.abort();const Se=new AbortController;te.current=Se;const ye=await(await fetch("/api/stt",{method:"POST",body:se,signal:Se.signal})).json();ye.ok&&ye.text?(l(Le=>Le+(Le?" ":"")+ye.text),$()):ye.ok||(console.warn("STT failed:",ye.error),alert(ye.error||"Speech-to-text failed. Try the Browser provider in Settings."))}catch(se){if(se instanceof Error&&se.name==="AbortError")return;console.warn("STT request failed:",se),alert("Could not reach speech-to-text service.")}finally{T(!1)}}},x(!0),R(0),_.current=setInterval(()=>{R(ue=>ue>=119?(ie(),0):ue+1)},1e3),ce.start()}catch(F){const H=F instanceof Error?F.message:String(F);if(H.includes("NotAllowedError")||H.includes("Permission"))try{(await navigator.permissions.query({name:"microphone"})).state==="denied"?alert("Microphone access is blocked. Please enable it in your browser/app settings."):alert("Microphone permission was not granted. Please try again and allow access when prompted.")}catch{alert("Could not access microphone. Please check your browser settings and allow microphone access for this site.")}else alert("Could not access microphone: "+H)}},[oe,ie,$]),ge=s.useCallback(()=>{y?ie():he()},[y,ie,he]),I=d.filter(A=>!A.error&&A.base64),pe=r||i.trim().length===0&&I.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:J,onDrop:G,children:[h&&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(ka,{value:i,onValueChange:re,onSubmit:ne,isLoading:t,disabled:r,children:[n.jsx(Va,{attachments:d,onRemove:z}),S&&N.length>0&&n.jsx(Ja,{commands:N,selectedIndex:Math.min(m,N.length-1),onSelect:le}),n.jsx(Ca,{placeholder:"Type a message…",inputRef:K,onKeyDown:ae}),n.jsxs(Na,{className:"justify-between px-3",children:[n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(Ma,{onModelChange:u}),n.jsx(Za,{}),n.jsx(Oa,{onSelect:Z}),n.jsx(Pa,{onCommandSelect:A=>re(A+" ")})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(Ya,{onFilesSelect:M,disabled:r}),n.jsx(Wn,{tooltip:y?"Stop recording":"Voice input",children:n.jsx(be,{onClick:ge,disabled:r||P,size:"icon-sm",variant:y?"destructive":"ghost",className:`rounded-full ${y?"animate-pulse":""}`,"aria-label":y?"Stop recording":"Voice input",children:P?n.jsx("span",{className:"size-4 animate-spin rounded-full border-2 border-current border-t-transparent"}):y?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(O/60),":",String(O%60).padStart(2,"0")]}),n.jsx(V,{icon:Zn,size:14,strokeWidth:2})]}):n.jsx(V,{icon:js,size:18,strokeWidth:2})})}),n.jsx(Wn,{tooltip:"Send message",children:n.jsx(be,{onClick:ne,disabled:pe,size:"icon-sm",className:"rounded-full","aria-label":"Send message",children:n.jsx(V,{icon:Es,size:18,strokeWidth:2})})})]})]})]})]})}const tl=s.memo(el);function nl({title:e,description:t,detail:r,actionLabel:o,onAction:a,className:i}){return n.jsx("div",{className:D("w-full max-w-[var(--opencami-chat-width)]",i),children:n.jsx(kr,{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(be,{size:"sm",variant:"outline",onClick:a,children:o})}):null]})})})}function rl({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(nl,{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 sl(){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,g=u?.offsetHeight??0,j=d.clientHeight;d.style.setProperty("--chat-header-height",`${Math.max(0,p)}px`),d.style.setProperty("--chat-composer-height",`${Math.max(0,g)}px`),l(p),a(Math.max(0,j-p-g))};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 ol({activeFriendlyId:e,activeSessionKey:t,forcedSessionKey:r,isNewChat:o,isRedirecting:a,activeExists:i,sessionsReady:l,queryClient:c}){const u=r||t||e,d=me.history(e,u),f=Mt({queryKey:d,queryFn:async function(){const x=c.getQueryData(d),O=Array.isArray(x?.messages)?x.messages.filter(T=>T.status==="sending"||T.__optimisticId?!0:!!T.clientId):[],R=await uo({sessionKey:u,friendlyId:e});if(!O.length)return R;const P=il(R.messages,O);return{...R,messages:P}},enabled:!o&&!!e&&!a&&(!l||i),placeholderData:function(){return c.getQueryData(d)},gcTime:1e3*60*10}),m=s.useRef(""),p=s.useRef([]),g=s.useMemo(()=>{const y=Array.isArray(f.data?.messages)?f.data.messages:[],x=y[y.length-1],O=x&&typeof x.id=="string"?x.id:"",R=`${y.length}:${x?.role??""}:${O}:${De(x??{content:[]}).slice(-32)}`;return R===m.current?p.current:(m.current=R,p.current=y,y)},[f.data?.messages]),j=f.error instanceof Error?f.error.message:null,h=s.useMemo(()=>{if(r)return r;const y=f.data?.sessionKey;return typeof y=="string"&&y.trim().length>0?y.trim():t},[t,r,f.data?.sessionKey]);return{historyQuery:f,historyMessages:g,displayMessages:g,historyError:j,resolvedSessionKey:h,activeCanonicalKey:o?"new":h||e,sessionKeyForHistory:u}}function il(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=De(o);if(!l||l!==De(i))return!1;const c=tn(o),u=tn(i);return Math.abs(c-u)<=1e4})||r.push(o);return r}function al(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&&We(e,function(a){return{...a,isSidebarCollapsed:!0}})},[t,e]),{isMobile:t}}function ll({activeFriendlyId:e,isNewChat:t,forcedSessionKey:r}){const o=Mt({queryKey:me.sessions,queryFn:co,refetchInterval:3e4}),a=s.useMemo(()=>{const m=o.data??[];return No(m)},[o.data]),i=s.useMemo(()=>a.find(m=>m.friendlyId===e),[a,e]),l=s.useMemo(()=>t||r||dr(e)?!0:a.some(m=>m.friendlyId===e),[e,r,t,a]),c=i?.key??"",u=s.useMemo(()=>i?i.label||i.title||i.derivedTitle||i.friendlyId:e,[e,i]),d=o.error instanceof Error?o.error.message:null,f=s.useMemo(()=>({totalTokens:i?.totalTokens,contextTokens:i?.contextTokens}),[i?.totalTokens,i?.contextTokens]);return{sessionsQuery:o,sessions:a,activeSession:i,activeExists:l,activeSessionKey:c,activeTitle:u,activeTokens:f,sessionsError:d}}const cl={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:""}},Rt={useLlmTitles:!0,useLlmFollowUps:!0,llmProvider:"openai",llmBaseUrl:"",llmModel:"",llmApiKey:""};function Ar(e){return cl[e]}function ul(e){return e.llmBaseUrl.trim()?e.llmBaseUrl.trim():Ar(e.llmProvider).baseUrl}function dl(e){return e.llmModel.trim()?e.llmModel.trim():Ar(e.llmProvider).model}function Gn(e,t){return e.llmProvider==="ollama"?!0:e.llmProvider==="custom"?!!e.llmApiKey.trim()||!!(e.llmBaseUrl.trim()&&e.llmModel.trim()):t||!!e.llmApiKey.trim()}function fl(e){if(!e||typeof e!="object")return{settings:Rt};const{settings:t}=e;if(!t)return{settings:Rt};const{openaiApiKey:r,...o}=t,a=o.llmApiKey??r??"";return{settings:{...Rt,...o,llmApiKey:a}}}const ct=cr()(lr(e=>({settings:{...Rt},updateSettings:t=>e(r=>({settings:{...r.settings,...t}})),clearApiKey:()=>e(t=>({settings:{...t.settings,llmApiKey:""}}))}),{name:"llm-settings",version:2,migrate:e=>fl(e)}));function Wl(){const e=ct(l=>l.settings),t=ct(l=>l.updateSettings),r=ct(l=>l.clearApiKey),[o,a]=s.useState({hasEnvKey:!1,hasOpenRouterKey:!1,hasKilocodeKey:!1,hasUserKey:!!e.llmApiKey,isAvailable:Gn(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:Gn(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=Dr({...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 Dr(e){const t=e.llmApiKey,r=ul(e),o=dl(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 ml(){const e=ct.getState().settings;return Dr(e)}function pl(){const e=ct(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",...ml()},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 g=await p.json();if(f.signal.aborted)throw new Error("Aborted");const j=g.title||d.slice(0,50),h=j.length>64?j.slice(0,61)+"...":j,b=g.source||"heuristic";return a(h),l(b),{title:h,source:b,error:g.error}}catch(m){if(m instanceof Error&&m.name==="AbortError")throw m;const p=hl(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 hl(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 gl(){return ct(e=>e.settings.useLlmTitles)}const Jt={active:!1,text:"",tools:[],sessionKey:null};function xl(e){const[t,r]=s.useState(Jt),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(h,b){a.current||(a.current=window.setInterval(async()=>{try{const y=await fetch(`/api/history?sessionKey=${encodeURIComponent(h)}`);if(!y.ok)return;const x=await y.json();if(!(Array.isArray(x.messages)?x.messages:[]).some(P=>!P||P.role!=="assistant"||typeof P.timestamp!="number"?!1:P.timestamp>b-3e3))return;o.current&&(o.current.close(),o.current=null),m(),r(P=>({...P,active:!1})),u.current(h)}catch{}},2e3))}const g=s.useCallback(h=>{if(c.current=!0,m(),o.current&&(o.current.close(),o.current=null),h?.preserveState){r(b=>({...b,active:!1}));return}r(Jt)},[]),j=s.useCallback(function(b){c.current=!1,m(),l.current=Date.now(),o.current&&(o.current.close(),o.current=null),r({active:!0,text:"",tools:[],sessionKey:b});const y=new EventSource(`/api/stream?sessionKey=${encodeURIComponent(b)}`);o.current=y,y.addEventListener("delta",x=>{try{const O=JSON.parse(x.data);r(R=>({...R,text:R.text+O.text})),f.current?.({text:O.text,sessionKey:O.sessionKey})}catch{}}),y.addEventListener("tool",x=>{try{const O=JSON.parse(x.data);r(R=>{const P=R.tools.findIndex(X=>X.id===O.id),T=[...R.tools];return P>=0?T[P]={name:O.name,status:O.status,id:O.id}:T.push({name:O.name,status:O.status,id:O.id}),{...R,tools:T}})}catch{}}),y.addEventListener("done",x=>{try{const O=JSON.parse(x.data);c.current=!0,m(),y.close(),o.current=null,r(R=>({...R,active:!1})),u.current(O.sessionKey)}catch{}}),y.onerror=()=>{y.readyState===EventSource.CLOSED&&(y.close(),o.current=null,r(Jt),d.current?.("Stream connection lost"))},i.current=window.setTimeout(()=>{if(c.current)return;const x=l.current??Date.now();p(b,x)},3e3)},[]);return{streaming:t,startStream:j,stopStream:g}}function yl(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 Vn(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 g=p.touches[0];g&&(r!==void 0&&g.clientX>r||(u.current={startX:g.clientX,startY:g.clientY,tracking:!0,directionLocked:!1}))},[c,r]),f=s.useCallback(p=>{const g=u.current;if(!g.tracking)return;const j=p.touches[0];if(!j)return;const h=j.clientX-g.startX,b=j.clientY-g.startY,y=Math.abs(h),x=Math.abs(b);if(!g.directionLocked){if(y<5&&x<5)return;if(x>y){g.tracking=!1,i?.();return}g.directionLocked=!0}l==="left"&&h>0||l==="right"&&h<0||(p.preventDefault(),o?.(h))},[l,o,i]),m=s.useCallback(p=>{const g=u.current;if(!g.tracking)return;g.tracking=!1;const j=p.changedTouches[0];if(!j){i?.();return}const h=j.clientX-g.startX,b=Math.abs(h);if(!g.directionLocked||b<t){i?.();return}const y=h>0?"right":"left";if(l&&y!==l){i?.();return}a(y)},[l,i,a,t]);return{onTouchStart:d,onTouchMove:f,onTouchEnd:m}}const Or="opencami-browser-notifications-enabled",Qt="opencami-browser-notifications-permission-asked",wl=5e3;function kt(){return typeof window<"u"&&"Notification"in window}function qn(){if(typeof window>"u")return!1;try{return localStorage.getItem(Or)==="true"}catch{return!1}}function bl(){const e=Lt(),t=s.useRef(0),[r,o]=s.useState(()=>qn()),a=s.useCallback(async()=>{if(!kt())return"denied";try{return await Notification.requestPermission()}catch{return"denied"}},[]),i=s.useCallback(async c=>{o(c);try{localStorage.setItem(Or,String(c))}catch{}if(c&&kt()&&Notification.permission==="default"){await a();try{localStorage.setItem(Qt,"true")}catch{}}},[a]),l=s.useCallback(c=>{if(!r||!kt()||document.hidden!==!0||Notification.permission!=="granted")return;const u=Date.now();if(u-t.current<wl)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(!kt())return;const c=()=>{if(Notification.permission!=="default")return;let d=!1;try{d=localStorage.getItem(Qt)==="true"}catch{d=!1}d||a().finally(()=>{try{localStorage.setItem(Qt,"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(qn());return window.addEventListener("storage",c),()=>window.removeEventListener("storage",c)},[]),{notificationsEnabled:r,setNotificationsEnabled:i,requestNotificationPermission:a,maybeNotifyAssistantMessage:l}}const Sl=s.lazy(()=>et(()=>import("./keyboard-shortcuts-dialog-BzL7ZJUb.js"),__vite__mapDeps([29,1,4,3,5,6,7,8,9,2])).then(e=>({default:e.KeyboardShortcutsDialog}))),vl=s.lazy(()=>et(()=>import("./search-dialog-CDAdFAQI.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}))),Ct="opencami-search-jump-target";function jl({activeFriendlyId:e,isNewChat:t=!1,onSessionResolved:r,forcedSessionKey:o}){const a=Lt(),i=ut(),[l,c]=s.useState(!1),[u,d]=s.useState(!1),[f,m]=s.useState(null),[p,g]=s.useState(!1),{headerRef:j,composerRef:h,mainRef:b,pinGroupMinHeight:y,headerHeight:x}=sl(),[O,R]=s.useState(()=>Wt()||Xt()),[P,T]=s.useState(()=>Wt()||Xt()),[X,Y]=s.useState(!1),[_,te]=s.useState(!1),[B,k]=s.useState("global"),[S,E]=s.useState(null),[N,K]=s.useState(!1),$=un(v=>v.level),{maybeNotifyAssistantMessage:q}=bl(),C=s.useRef(null),L=s.useRef(null),w=s.useRef(null),M=s.useRef(""),z=s.useRef(()=>{}),Q=s.useRef(!1),J=s.useRef(""),{isMobile:G}=al(i),{sessionsQuery:W,sessions:re,activeExists:le,activeSessionKey:ne,activeTitle:Z,activeTokens:ae,sessionsError:oe}=ll({activeFriendlyId:e,isNewChat:t,forcedSessionKey:o}),{historyQuery:ie,historyMessages:he,displayMessages:ge,historyError:I,resolvedSessionKey:pe,activeCanonicalKey:A,sessionKeyForHistory:F}=ol({activeFriendlyId:e,activeSessionKey:ne,forcedSessionKey:o,isNewChat:t,isRedirecting:p,activeExists:le,sessionsReady:W.isSuccess,queryClient:i}),H=Mt({queryKey:Zr,queryFn:function(){return En(i)},initialData:function(){return En(i)},staleTime:1/0}),ce=Mt({queryKey:["gateway","status"],queryFn:fo,retry:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1,refetchOnMount:"always"}),ue=s.useRef(Date.now()),se=ce.error instanceof Error?ce.error.message:ce.data&&!ce.data.ok?ce.data.error||"Gateway unavailable":null,Se=se??oe??I,Oe=s.useCallback(()=>{ce.refetch()},[ce]),ye=H.data?.isSidebarCollapsed??!1,Le=Vn({enabled:G&&ye,edgeWidth:40,threshold:50,direction:"right",onSwipe:()=>{We(i,v=>({...v,isSidebarCollapsed:!1}))}}),dt=Vn({enabled:G&&!ye,threshold:50,direction:"left",onSwipe:()=>{We(i,v=>({...v,isSidebarCollapsed:!0}))}}),yt=s.useCallback(()=>{m(null),g(!0),a({to:"/new",replace:!0})},[a]),qe=s.useCallback(()=>{L.current&&(window.clearInterval(L.current),L.current=null),w.current&&(window.clearTimeout(w.current),w.current=null)},[]),Je=s.useCallback(()=>{qe(),gt(!1),R(!1),K(!1)},[qe]),ft=gl(),{generateTitle:mt}=pl(),wt=s.useRef(new Set),bt=2e3,pt=2e3,ht=s.useCallback(()=>{!e||t||(L.current&&window.clearInterval(L.current),K(!0),L.current=window.setInterval(()=>{z.current()},bt))},[e,t]),St=s.useRef(()=>{}),ze=s.useRef(()=>{}),{streaming:ee,startStream:Ee,stopStream:Ke}=xl({onDone:v=>St.current(v),onError:v=>ze.current(v),onAssistantDelta:({text:v})=>{J.current+=v,q({text:J.current,sessionFriendlyId:e})}});St.current=s.useCallback(async v=>{await ie.refetch(),Ke({preserveState:!0}),Je(),i.invalidateQueries({queryKey:me.sessions})},[ie,i,Ke,Je]),ze.current=s.useCallback(v=>{console.warn("[stream] SSE error, falling back to polling")},[]);const Ue=s.useMemo(()=>{if(!ee.text)return null;const v=[];for(const U of ee.tools)v.push({type:"toolCall",name:U.name,id:U.id});return v.push({type:"text",text:ee.text}),{role:"assistant",content:v,id:"__streaming__",__streaming:!0,timestamp:Date.now()}},[ee.text,ee.tools]),Lr=s.useMemo(()=>{if(!Ue)return ge;const v=[...ge].map((de,xe)=>({message:de,index:xe})).filter(({message:de})=>de.role==="assistant").map(({index:de})=>de).pop(),U=[...ge].map((de,xe)=>({message:de,index:xe})).filter(({message:de})=>de.role==="user").map(({index:de})=>de).pop();if(typeof v=="number"&&(typeof U!="number"||v>U)&&typeof v=="number"){const de=ge[v];if(De(de).length>=ee.text.length)return ge;const Pe=[...ge];return Pe[v]=Ue,Pe}return[...ge,Ue]},[ge,Ue,ee.text]),Pr=s.useMemo(()=>({}),[]);z.current=function(){ie.refetch()},s.useEffect(()=>{if(p){f&&m(null);return}if(tt){f&&m(null);return}if(W.isSuccess&&!le){f&&m(null);return}const v=oe??I??se;if(!v){f?.startsWith("Failed to load")&&m(null);return}Rn(v)&&a({to:"/connect",replace:!0});const U=oe?`Failed to load sessions. ${oe}`:I?`Failed to load history. ${I}`:se?`Gateway unavailable. ${se}`:null;U&&m(U)},[f,se,I,p,a,oe]);const tt=!t&&!o&&!dr(e)&&W.isSuccess&&re.length>0&&!re.some(v=>v.friendlyId===e)&&!ie.isFetching&&!ie.isSuccess;s.useEffect(()=>{if(p){if(t){g(!1);return}!tt&&W.isSuccess&&g(!1)}},[t,p,W.isSuccess,tt]),s.useEffect(()=>{t||W.isSuccess&&re.length!==0&&tt&&(At(),rn(i,e,F),a({to:"/new",replace:!0}))},[e,ie.isFetching,ie.isSuccess,t,a,i,F,re,W.isSuccess,tt]);const gn=tt||p,vt=s.useRef("fast");s.useEffect(()=>{const v=[...he].reverse().find(fe=>fe.role==="assistant");if(!v)return;const U=`${he.length}:${De(v).slice(-64)}`;U!==M.current&&(M.current=U,vt.current!=="fast"&&L.current&&(window.clearInterval(L.current),L.current=window.setInterval(()=>{z.current()},bt),vt.current="fast"),w.current&&window.clearTimeout(w.current),w.current=window.setTimeout(()=>{L.current&&(window.clearInterval(L.current),L.current=window.setInterval(()=>{z.current()},pt),vt.current="slow"),w.current=window.setTimeout(()=>{Je(),vt.current="fast"},3e3)},1500))},[he,Je]),s.useEffect(()=>{if(!ft||t||p)return;const v=o||pe||ne;if(!v||wt.current.has(v))return;const U=he.filter(xe=>xe.role==="user"),fe=he.filter(xe=>xe.role==="assistant");if(U.length===0||fe.length===0||U.length!==1)return;const de=De(U[0]);!de||de.length<5||(wt.current.add(v),(async()=>{try{const xe=await mt(de);xe.title&&await yo(i,v,e,xe.title)}catch(xe){console.error("[smart-title] Error generating title:",xe)}})())},[ft,t,p,o,pe,ne,e,he,mt,i]),s.useEffect(()=>{if(t||e){if(qe(),Ke(),M.current="",K(!1),Q.current){Q.current=!1;return}if(Wt()||Xt()){R(!0),T(!0);return}R(!1),T(!1)}},[e,t,qe,Ke]),s.useEffect(()=>{if(!(typeof window>"u"))try{const v=sessionStorage.getItem(Ct);if(!v){E(null);return}const U=JSON.parse(v);if(typeof U.at=="number"&&Date.now()-U.at>300*1e3){sessionStorage.removeItem(Ct),E(null);return}if(U.friendlyId===e&&typeof U.messageId=="string"&&U.messageId.length>0){E(U.messageId),sessionStorage.removeItem(Ct);return}E(null)}catch{E(null)}},[e]),s.useLayoutEffect(()=>{if(t)return;const v=jo(o||pe||ne,e);if(!v)return;Q.current=!0;const U=me.history(v.friendlyId,v.sessionKey),fe=i.getQueryData(U);(Array.isArray(fe?.messages)?fe.messages:[]).some(Pe=>!!(v.optimisticMessage.clientId&&(Pe.clientId===v.optimisticMessage.clientId||Pe.__optimisticId===v.optimisticMessage.clientId)||v.optimisticMessage.__optimisticId&&Pe.__optimisticId===v.optimisticMessage.__optimisticId))||Ht(i,v.friendlyId,v.sessionKey,v.optimisticMessage),R(!0),T(!0),$t(v.sessionKey,v.friendlyId,v.message,!0,v.attachments)},[e,ne,o,t,i,pe]);function $t(v,U,fe,de=!1,xe,Pe){let nt="";if(!de){const{clientId:we,optimisticMessage:rt}=Mn(fe,xe);nt=we,Ht(i,U,v,rt),go(i,v,U,rt)}gt(!0),c(!0),m(null),R(!0),T(!0);const $e=xe?.map(we=>({mimeType:we.file.type,content:we.base64}));J.current="",ht(),fetch("/api/send",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({sessionKey:v,friendlyId:U,message:fe,thinking:$,idempotencyKey:crypto.randomUUID(),attachments:$e,model:Pe||void 0})}).then(async we=>{if(!we.ok)throw new Error(await _e(we));const jn=(await we.json()).sessionKey||v||U;Ee(jn)}).catch(we=>{const rt=we instanceof Error?we.message:String(we);if(Rn(rt)){a({to:"/connect",replace:!0});return}nt&&mo(i,U,v,nt,function(Vr){return{...Vr,status:"error"}}),m(`Failed to send message. ${rt}`),gt(!1),R(!1),T(!1)}).finally(()=>{c(!1)})}const xn=s.useCallback(async()=>{d(!0);try{const v=await fetch("/api/sessions",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({})});if(!v.ok)throw new Error(await _e(v));const U=await v.json(),fe=typeof U.sessionKey=="string"?U.sessionKey:"",de=typeof U.friendlyId=="string"&&U.friendlyId.trim().length>0?U.friendlyId.trim():en(fe);if(!fe||!de)throw new Error("Invalid session response");return i.invalidateQueries({queryKey:me.sessions}),{sessionKey:fe,friendlyId:de}}finally{d(!1)}},[i]),_r=s.useCallback((v,U)=>{const fe=U.attachments;if(v.length===0&&(!fe||fe.length===0))return;if(U.reset(),t){const{clientId:xe,optimisticId:Pe,optimisticMessage:nt}=Mn(v,fe);Ht(i,"new","new",nt),gt(!0),c(!0),R(!0),T(!0),xn().then(({sessionKey:$e,friendlyId:we})=>{if(vo(we),bo({sessionKey:$e,friendlyId:we,message:v,optimisticMessage:nt,attachments:fe}),r){r({sessionKey:$e,friendlyId:we});return}a({to:"/chat/$sessionKey",params:{sessionKey:we},replace:!0})}).catch($e=>{po(i,"new","new",xe,Pe),U.setValue(v),m(`Failed to create session. ${$e instanceof Error?$e.message:String($e)}`),gt(!1),R(!1),T(!1),c(!1)});return}$t(o||pe||ne,e,v,!1,fe,U.model)},[e,ne,xn,o,t,a,r,i,pe]),yn=s.useCallback(()=>{R(!1),T(!1),rn(i,"new","new"),a({to:"/new"}),G&&We(i,function(U){return{...U,isSidebarCollapsed:!0}})},[G,a,i]),Kr=s.useCallback(()=>{We(i,function(U){return{...U,isSidebarCollapsed:!U.isSidebarCollapsed}})},[i]),zr=s.useCallback(()=>{G&&We(i,function(U){return{...U,isSidebarCollapsed:!0}})},[G,i]),Ur=s.useCallback(()=>{We(i,function(U){return{...U,isSidebarCollapsed:!1}})},[i]),$r=s.useCallback(v=>{if(t||!v.trim())return;const U=o||pe||ne;U&&$t(U,e,v.trim())},[e,ne,o,t,pe]),Fr=s.useCallback(()=>{C.current?.focus()},[]),Hr=s.useCallback(()=>{if(X){Y(!1);return}document.activeElement instanceof HTMLElement&&document.activeElement.blur()},[X]),Wr=s.useCallback(()=>{const v=[...ge].reverse().find(fe=>fe.role==="assistant");if(!v)return;const U=De(v);U&&navigator.clipboard.writeText(U).catch(()=>{})},[ge]),Xr=s.useCallback(()=>{Y(!0)},[]),Yr=s.useCallback(()=>{k(t?"global":"current"),te(!0)},[t]),wn=s.useCallback(()=>{k("global"),te(!0)},[]);yl({onNewChat:yn,onFocusInput:Fr,onEscape:Hr,onCopyLastResponse:Wr,onShowHelp:Xr,onSearch:Yr,onSearchGlobal:wn});const bn=ie.isLoading&&!ie.data||p,Sn=!!se&&ce.errorUpdatedAt>ue.current,Br=!bn&&ge.length===0,Gr=s.useMemo(()=>!Sn||!Se?null:n.jsx(rl,{state:"error",error:Se,onRetry:Oe}),[Se,Oe,Sn]),vn=n.jsx(zi,{sessions:re,activeFriendlyId:e,activeSessionKey:F,creatingSession:u,onCreateSession:yn,isCollapsed:G?!1:ye,onToggleCollapse:Kr,onSelectSession:zr,onActiveSessionDelete:yt,onOpenSearch:wn});return n.jsxs("div",{className:"h-screen bg-surface text-primary-900",children:[n.jsxs("div",{className:D("h-full overflow-hidden",G?"relative":"grid grid-cols-[auto_minmax(0,1fr)]"),children:[gn?null:G?n.jsxs(n.Fragment,{children:[!ye&&n.jsx("div",{className:"fixed inset-0 z-40 bg-black/40 transition-opacity duration-200",onClick:()=>We(i,v=>({...v,isSidebarCollapsed:!0})),...dt}),n.jsx("div",{className:D("fixed inset-y-0 left-0 z-50 w-[var(--opencami-sidebar-width)] transition-transform duration-150 safe-area-top",ye?"-translate-x-full":"translate-x-0"),...dt,children:vn})]}):vn,n.jsxs("main",{className:"flex flex-col h-full min-h-0 min-w-0 overflow-x-hidden",ref:b,...Le,children:[n.jsx(Hi,{activeTitle:Z,wrapperRef:j,showSidebarButton:G,onOpenSidebar:Ur,totalTokens:ae.totalTokens,contextTokens:ae.contextTokens}),gn?null:n.jsxs(n.Fragment,{children:[n.jsx(ja,{messages:Lr,loading:bn,empty:Br,notice:Gr,noticePosition:"end",waitingForResponse:O,isStreaming:N,sessionKey:A,pinToTop:P,pinGroupMinHeight:y,headerHeight:x,contentStyle:Pr,onFollowUpClick:$r,jumpToMessageId:S}),n.jsx(tl,{onSubmit:_r,isLoading:l,disabled:l,wrapperRef:h,inputRef:C})]})]})]}),X&&n.jsx(s.Suspense,{fallback:null,children:n.jsx(Sl,{open:X,onOpenChange:Y})}),_&&n.jsx(s.Suspense,{fallback:null,children:n.jsx(vl,{open:_,onOpenChange:te,sessions:re,currentFriendlyId:e,currentSessionKey:ne,mode:B,onJumpToMessage:v=>{if(te(!1),!!v.friendlyId){if(v.messageId&&v.friendlyId===e){E(v.messageId);return}if(v.messageId&&typeof window<"u")try{sessionStorage.setItem(Ct,JSON.stringify({friendlyId:v.friendlyId,messageId:v.messageId,at:Date.now()}))}catch{}a({to:"/chat/$sessionKey",params:{sessionKey:v.friendlyId}})}}})})]})}function El(){const e=ut(),t=Lt(),[r,o]=s.useState(null),a=Qr.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){ho(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(jl,{activeFriendlyId:i,isNewChat:l,forcedSessionKey:c,onSessionResolved:l?u:void 0})}const Xl=Object.freeze(Object.defineProperty({__proto__:null,component:El},Symbol.toStringTag,{value:"Module"}));export{Xl as $,sn as C,on as a,an as b,me as c,ct as d,ml as e,Ar as g,Wl as u};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/agents-screen-Du8b4SRW.js","assets/main-DJgQwVqD.js","assets/useQuery-DhR_UXNX.js","assets/button-BxDVif49.js","assets/switch-LzFh8co4.js","assets/useControlled-KFa25CcD.js","assets/useBaseUiId-CMJ8I9al.js","assets/visuallyHidden-COI6QeQH.js","assets/tooltip-D64CzFXa.js","assets/useOnFirstRender-DqnUCnnL.js","assets/event-DeooaZzN.js","assets/DirectionContext-DZNUWW6F.js","assets/opencami-logo-CoCA2JIf.js","assets/proxy-C2vtPufK.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{j as e,r as t,_ as r}from"./main-DJgQwVqD.js";const n=t.lazy(()=>r(()=>import("./agents-screen-Du8b4SRW.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 +1 @@
|
|
|
1
|
-
import{u as L,r as t,j as e,L as M}from"./main-Dq6jpr6-.js";import{u as q}from"./useQuery-Ctiljcrr.js";import{c as B,b as O,B as f,H as p,I as Q,r as K,w as R,h as I,U as V,a as H,V as G,q as J}from"./button-CK8tKQ-Z.js";import{S as _}from"./switch-BD3a0LRm.js";import{s as X,T as Y,a as Z,b as $,c as ee,d as se,g as P}from"./tooltip-BbH3QWvK.js";import{O as re,a as ae}from"./opencami-logo-zuSBm5Br.js";import{m as S,A as W}from"./proxy-BU8Bw1Vt.js";import"./useControlled-BQxTgsOd.js";import"./useBaseUiId-MgM4ouhx.js";import"./visuallyHidden-COI6QeQH.js";import"./useOnFirstRender-7qoaK5sI.js";import"./event-BsD1rqGT.js";import"./DirectionContext-C6goXEY_.js";async function te(){const s=await fetch("/api/agents");if(!s.ok)throw new Error("Failed to fetch agents");return(await s.json()).agents??[]}async function E(s){return await(await fetch("/api/agents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})).json()}function ie({agent:s,onEdit:d,onDelete:n}){const c=s.isDefault||s.id==="main",l=s.name||s.id.charAt(0).toUpperCase()+s.id.slice(1),m=s.model?s.model.split("/").pop():void 0;return e.jsx("div",{className:"group rounded-lg border border-primary-100 bg-surface p-4 transition-all duration-150 ease-out hover:border-primary-200 hover:shadow-sm",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("div",{className:"relative flex size-12 shrink-0 items-center justify-center rounded-lg bg-primary-50 text-xl",children:[s.emoji||"🤖",c&&e.jsx("span",{className:"absolute -top-1 -right-1 size-3 rounded-full bg-emerald-500 ring-2 ring-surface"})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("h4",{className:"text-[13px] font-semibold text-primary-900 leading-tight truncate",children:l}),l!==s.id&&e.jsx("span",{className:"text-[10px] font-mono text-primary-400 shrink-0",children:s.id})]}),c&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 text-[11px] font-medium rounded-full bg-emerald-50 text-emerald-600 border border-emerald-100 shrink-0",children:"Primary"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mb-3",children:[m&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 text-[10px] font-mono rounded-full bg-primary-50 text-primary-600 border border-primary-100 truncate max-w-[200px]",children:m}),s.sandbox!==void 0&&e.jsx("span",{className:B("inline-flex items-center px-2 py-0.5 text-[10px] font-medium rounded-full border",s.sandbox?"bg-amber-50 text-amber-600 border-amber-100":"bg-primary-50 text-primary-500 border-primary-100"),children:s.sandbox?"🔒 Sandbox":"🔓 Open"}),s.sessionScope&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 text-[10px] font-medium rounded-full bg-primary-50 text-primary-500 border border-primary-100",children:s.sessionScope==="per-sender"?"👤 Per-sender":"🌐 Global"})]}),s.tools&&s.tools.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1 mb-2",children:[s.tools.slice(0,6).map(i=>e.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 text-[10px] font-mono rounded bg-sky-50 text-sky-600 border border-sky-100",children:i},i)),s.tools.length>6&&e.jsxs("span",{className:"text-[10px] text-primary-400",children:["+",s.tools.length-6," more"]})]}),s.channelBindings&&s.channelBindings.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:s.channelBindings.map(i=>e.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 text-[10px] rounded bg-violet-50 text-violet-600 border border-violet-100",children:["#",i]},i))}),e.jsxs("div",{className:"flex items-center gap-3 pt-2 border-t border-primary-50",children:[s.workspace&&e.jsx("span",{className:"text-[11px] font-mono text-primary-400 truncate",title:s.workspace,children:s.workspace}),s.activeSessions!==void 0&&s.activeSessions>0&&e.jsxs("span",{className:"text-[11px] text-primary-400",children:[s.activeSessions," active session",s.activeSessions!==1?"s":""]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity duration-150",children:[e.jsx(f,{size:"icon-sm",variant:"ghost",onClick:d,"aria-label":"Edit agent",children:e.jsx(p,{icon:V,size:16,strokeWidth:1.5})}),!c&&e.jsx(f,{size:"icon-sm",variant:"ghost",onClick:n,"aria-label":"Delete agent",className:"text-red-500 hover:text-red-600",children:e.jsx(p,{icon:H,size:16,strokeWidth:1.5})})]})]})})}function D({label:s,placeholder:d,values:n,onChange:c}){const[l,m]=t.useState(""),i=o=>{(o.key==="Enter"||o.key===",")&&l.trim()&&(o.preventDefault(),n.includes(l.trim())||c([...n,l.trim()]),m("")),o.key==="Backspace"&&!l&&n.length>0&&c(n.slice(0,-1))};return e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:s}),e.jsxs("div",{className:"flex flex-wrap gap-1 p-2 rounded-md border border-primary-200 bg-surface min-h-[36px]",children:[n.map(o=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-primary-100 px-2 py-0.5 text-xs text-primary-700",children:[o,e.jsx("button",{onClick:()=>c(n.filter(x=>x!==o)),className:"text-primary-400 hover:text-primary-600",children:"×"})]},o)),e.jsx("input",{value:l,onChange:o=>m(o.target.value),onKeyDown:i,placeholder:n.length===0?d:"",className:"flex-1 min-w-[80px] bg-transparent text-sm outline-none"})]})]})}function F({agent:s,onSave:d,onCancel:n,saving:c}){const[l,m]=t.useState(s?.name??""),[i,o]=t.useState(s?.workspace??""),[x,g]=t.useState(s?.emoji??""),[u,v]=t.useState(s?.avatar??""),[b,N]=t.useState(s?.model??""),[w,U]=t.useState(s?.sandbox??!1),[h,z]=t.useState(s?.tools??[]),[j,y]=t.useState(s?.deniedTools??[]),[k,A]=t.useState(s?.channelBindings??[]),[C,T]=t.useState(s?.sessionScope??"per-sender"),r=!!s;return e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsx("h2",{className:"text-lg font-semibold text-primary-900",children:r?"Edit Agent":"Create Agent"}),e.jsx(f,{size:"icon-sm",variant:"ghost",onClick:n,children:e.jsx(p,{icon:G,size:18,strokeWidth:1.5})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"rounded-lg border border-primary-100 bg-surface p-4",children:[e.jsx("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3",children:"Basic Info"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"col-span-2 sm:col-span-1",children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Name"}),e.jsx("input",{value:l,onChange:a=>m(a.target.value),placeholder:"my-agent",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Emoji"}),e.jsx("input",{value:x,onChange:a=>g(a.target.value),placeholder:"🤖",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Avatar URL"}),e.jsx("input",{value:u,onChange:a=>v(a.target.value),placeholder:"https://...",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-500"})]})]})]}),e.jsxs("div",{className:"rounded-lg border border-primary-100 bg-surface p-4",children:[e.jsx("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3",children:"Model & Config"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Model"}),e.jsx("input",{value:b,onChange:a=>N(a.target.value),placeholder:"anthropic/claude-sonnet-4-20250514",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Workspace Path"}),e.jsx("input",{value:i,onChange:a=>o(a.target.value),placeholder:"/root/.openclaw/workspace-myagent",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-500"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-primary-800",children:"Sandbox Mode"}),e.jsx("div",{className:"text-xs text-primary-500",children:"Run agent in isolated sandbox"})]}),e.jsx(_,{checked:w,onCheckedChange:U})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Session Scope"}),e.jsxs("select",{value:C,onChange:a=>T(a.target.value),className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500",children:[e.jsx("option",{value:"per-sender",children:"Per-sender"}),e.jsx("option",{value:"global",children:"Global"})]})]})]})]}),e.jsxs("div",{className:"rounded-lg border border-primary-100 bg-surface p-4",children:[e.jsx("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3",children:"Tools"}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(D,{label:"Allowed Tools",placeholder:"Type tool name and press Enter",values:h,onChange:z}),e.jsx(D,{label:"Denied Tools",placeholder:"Type tool name and press Enter",values:j,onChange:y})]})]}),e.jsxs("div",{className:"rounded-lg border border-primary-100 bg-surface p-4",children:[e.jsx("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3",children:"Channel Bindings"}),e.jsx(D,{label:"Bound Channels",placeholder:"Type channel name and press Enter",values:k,onChange:A})]})]}),e.jsxs("div",{className:"mt-6 flex justify-end gap-2",children:[e.jsx(f,{size:"sm",variant:"outline",onClick:n,children:"Cancel"}),e.jsx(f,{size:"sm",onClick:()=>d({name:l,workspace:i,emoji:x,model:b,avatar:u,sandbox:w,tools:h,deniedTools:j,channelBindings:k,sessionScope:C}),disabled:!l.trim()||c,children:c?e.jsx(p,{icon:I,size:16,className:"animate-spin"}):r?"Save Changes":"Create Agent"})]})]})}function ne({agent:s,onConfirm:d,onCancel:n,deleting:c}){const[l,m]=t.useState(!1);return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onClick:n,children:e.jsxs("div",{className:"w-[min(380px,90vw)] rounded-xl border border-primary-200 bg-surface p-5 shadow-xl",onClick:i=>i.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(p,{icon:J,size:20,className:"text-red-500"}),e.jsx("h3",{className:"text-sm font-medium text-primary-900",children:"Delete Agent"})]}),e.jsxs("p",{className:"text-sm text-primary-600 mb-4",children:["Are you sure you want to delete ",e.jsx("strong",{children:s.name}),"? This cannot be undone."]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm text-primary-700 mb-4 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:l,onChange:i=>m(i.target.checked),className:"rounded border-primary-300"}),"Also delete workspace files"]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(f,{size:"sm",variant:"outline",onClick:n,children:"Cancel"}),e.jsx(f,{size:"sm",onClick:()=>d(l),disabled:c,className:"bg-red-600 text-white hover:bg-red-700",children:c?e.jsx(p,{icon:I,size:16,className:"animate-spin"}):"Delete"})]})]})})}function ge(){const s=L(),[d,n]=t.useState([]),[c,l]=t.useState(!0),[m,i]=t.useState(null),[o,x]=t.useState(!1),[g,u]=t.useState("list"),[v,b]=t.useState(null),[N,w]=t.useState(null),h=q({queryKey:se,queryFn:function(){return P(s)},initialData:function(){return P(s)},staleTime:1/0}).data?.isSidebarCollapsed??!1,z=t.useCallback(()=>{X(s,function(a){return{...a,isSidebarCollapsed:!a.isSidebarCollapsed}})},[s]),j=t.useMemo(()=>({duration:.15,ease:h?"easeIn":"easeOut"}),[h]),y=t.useCallback(async()=>{try{i(null);const r=await te();n(r)}catch(r){i(r instanceof Error?r.message:"Failed to load agents")}finally{l(!1)}},[]);t.useEffect(()=>{y()},[y]);const k=async r=>{x(!0);try{const a=await E({action:"create",name:r.name,workspace:r.workspace||void 0,emoji:r.emoji||void 0,avatar:r.avatar||void 0});if(a.error){i(a.error);return}u("list"),await y()}finally{x(!1)}},A=async r=>{if(v){x(!0);try{const a=await E({action:"update",agentId:v.id,name:r.name||void 0,workspace:r.workspace||void 0,model:r.model||void 0,avatar:r.avatar||void 0});if(a.error){i(a.error);return}b(null),u("list"),await y()}finally{x(!1)}}},C=async r=>{if(N){x(!0);try{const a=await E({action:"delete",agentId:N.id,deleteFiles:r});if(a.error){i(a.error);return}w(null),await y()}finally{x(!1)}}},T=e.jsxs(S.aside,{initial:!1,animate:{width:h?48:300},transition:j,className:"border-r border-primary-200 h-full overflow-hidden bg-primary-100 flex flex-col",children:[e.jsxs(S.div,{layout:!0,transition:{layout:j},className:"flex items-center h-12 px-2 justify-between",children:[e.jsx(W,{initial:!1,children:h?null:e.jsx(S.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:j,children:e.jsxs(M,{to:"/new",className:B(O({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),children:[e.jsx(re,{className:"size-5"}),e.jsx(ae,{})]})})}),e.jsx(Y,{children:e.jsxs(Z,{children:[e.jsx($,{onClick:z,render:e.jsx(f,{size:"icon-sm",variant:"ghost",children:e.jsx(p,{icon:Q,size:20,strokeWidth:1.5})})}),e.jsx(ee,{side:"right",children:h?"Open Sidebar":"Close Sidebar"})]})})]}),e.jsx("div",{className:"px-2 mb-4",children:e.jsxs(M,{to:"/",className:B(O({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),children:[e.jsx(p,{icon:K,size:20,strokeWidth:1.5,className:"min-w-5"}),e.jsx(W,{initial:!1,mode:"wait",children:!h&&e.jsx(S.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:j,className:"overflow-hidden whitespace-nowrap",children:"Back to Chat"})})]})})]});return e.jsx("div",{className:"h-screen bg-surface text-primary-900",children:e.jsxs("div",{className:"h-full overflow-hidden grid grid-cols-[auto_1fr]",children:[T,e.jsxs("main",{"aria-label":"Agent manager",className:"flex flex-col h-full min-h-0",children:[e.jsx("header",{className:"border-b border-primary-200 px-6 py-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg font-semibold text-primary-900",children:"Agents"}),e.jsxs("p",{className:"text-xs text-primary-500 mt-0.5",children:[d.length," agent",d.length!==1?"s":""," configured"]})]}),g==="list"&&e.jsxs(f,{size:"sm",onClick:()=>{b(null),u("create")},children:[e.jsx(p,{icon:R,size:16,strokeWidth:1.5}),e.jsx("span",{className:"ml-1",children:"Create Agent"})]})]})}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-6",children:[m&&e.jsx("div",{className:"mb-4 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 p-3 text-sm text-red-600 dark:text-red-400",children:m}),c?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(p,{icon:I,size:24,className:"animate-spin text-primary-400"})}):g==="list"?e.jsxs("div",{className:"max-w-3xl mx-auto space-y-3",children:[d.map(r=>e.jsx(ie,{agent:r,onEdit:()=>{b(r),u("edit")},onDelete:()=>w(r)},r.id)),d.length===0&&e.jsxs("div",{className:"py-12 text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-12 h-12 rounded-lg bg-primary-50 mb-3",children:e.jsx("span",{className:"text-2xl",children:"🤖"})}),e.jsx("p",{className:"text-sm text-primary-500",children:"No agents found"}),e.jsx("p",{className:"text-xs text-primary-400 mt-1",children:"Create one to get started"})]})]}):g==="create"?e.jsx(F,{onSave:k,onCancel:()=>u("list"),saving:o}):g==="edit"&&v?e.jsx(F,{agent:v,onSave:A,onCancel:()=>{b(null),u("list")},saving:o}):null]}),N&&e.jsx(ne,{agent:N,onConfirm:C,onCancel:()=>w(null),deleting:o})]})]})})}export{ge as AgentsScreen};
|
|
1
|
+
import{u as L,r as t,j as e,L as M}from"./main-DJgQwVqD.js";import{u as q}from"./useQuery-DhR_UXNX.js";import{c as B,b as O,B as f,H as p,I as Q,r as K,w as R,h as I,U as V,a as H,V as G,q as J}from"./button-BxDVif49.js";import{S as _}from"./switch-LzFh8co4.js";import{s as X,T as Y,a as Z,b as $,c as ee,d as se,g as P}from"./tooltip-D64CzFXa.js";import{O as re,a as ae}from"./opencami-logo-CoCA2JIf.js";import{m as S,A as W}from"./proxy-C2vtPufK.js";import"./useControlled-KFa25CcD.js";import"./useBaseUiId-CMJ8I9al.js";import"./visuallyHidden-COI6QeQH.js";import"./useOnFirstRender-DqnUCnnL.js";import"./event-DeooaZzN.js";import"./DirectionContext-DZNUWW6F.js";async function te(){const s=await fetch("/api/agents");if(!s.ok)throw new Error("Failed to fetch agents");return(await s.json()).agents??[]}async function E(s){return await(await fetch("/api/agents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})).json()}function ie({agent:s,onEdit:d,onDelete:n}){const c=s.isDefault||s.id==="main",l=s.name||s.id.charAt(0).toUpperCase()+s.id.slice(1),m=s.model?s.model.split("/").pop():void 0;return e.jsx("div",{className:"group rounded-lg border border-primary-100 bg-surface p-4 transition-all duration-150 ease-out hover:border-primary-200 hover:shadow-sm",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("div",{className:"relative flex size-12 shrink-0 items-center justify-center rounded-lg bg-primary-50 text-xl",children:[s.emoji||"🤖",c&&e.jsx("span",{className:"absolute -top-1 -right-1 size-3 rounded-full bg-emerald-500 ring-2 ring-surface"})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("h4",{className:"text-[13px] font-semibold text-primary-900 leading-tight truncate",children:l}),l!==s.id&&e.jsx("span",{className:"text-[10px] font-mono text-primary-400 shrink-0",children:s.id})]}),c&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 text-[11px] font-medium rounded-full bg-emerald-50 text-emerald-600 border border-emerald-100 shrink-0",children:"Primary"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mb-3",children:[m&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 text-[10px] font-mono rounded-full bg-primary-50 text-primary-600 border border-primary-100 truncate max-w-[200px]",children:m}),s.sandbox!==void 0&&e.jsx("span",{className:B("inline-flex items-center px-2 py-0.5 text-[10px] font-medium rounded-full border",s.sandbox?"bg-amber-50 text-amber-600 border-amber-100":"bg-primary-50 text-primary-500 border-primary-100"),children:s.sandbox?"🔒 Sandbox":"🔓 Open"}),s.sessionScope&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 text-[10px] font-medium rounded-full bg-primary-50 text-primary-500 border border-primary-100",children:s.sessionScope==="per-sender"?"👤 Per-sender":"🌐 Global"})]}),s.tools&&s.tools.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1 mb-2",children:[s.tools.slice(0,6).map(i=>e.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 text-[10px] font-mono rounded bg-sky-50 text-sky-600 border border-sky-100",children:i},i)),s.tools.length>6&&e.jsxs("span",{className:"text-[10px] text-primary-400",children:["+",s.tools.length-6," more"]})]}),s.channelBindings&&s.channelBindings.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:s.channelBindings.map(i=>e.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 text-[10px] rounded bg-violet-50 text-violet-600 border border-violet-100",children:["#",i]},i))}),e.jsxs("div",{className:"flex items-center gap-3 pt-2 border-t border-primary-50",children:[s.workspace&&e.jsx("span",{className:"text-[11px] font-mono text-primary-400 truncate",title:s.workspace,children:s.workspace}),s.activeSessions!==void 0&&s.activeSessions>0&&e.jsxs("span",{className:"text-[11px] text-primary-400",children:[s.activeSessions," active session",s.activeSessions!==1?"s":""]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity duration-150",children:[e.jsx(f,{size:"icon-sm",variant:"ghost",onClick:d,"aria-label":"Edit agent",children:e.jsx(p,{icon:V,size:16,strokeWidth:1.5})}),!c&&e.jsx(f,{size:"icon-sm",variant:"ghost",onClick:n,"aria-label":"Delete agent",className:"text-red-500 hover:text-red-600",children:e.jsx(p,{icon:H,size:16,strokeWidth:1.5})})]})]})})}function D({label:s,placeholder:d,values:n,onChange:c}){const[l,m]=t.useState(""),i=o=>{(o.key==="Enter"||o.key===",")&&l.trim()&&(o.preventDefault(),n.includes(l.trim())||c([...n,l.trim()]),m("")),o.key==="Backspace"&&!l&&n.length>0&&c(n.slice(0,-1))};return e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:s}),e.jsxs("div",{className:"flex flex-wrap gap-1 p-2 rounded-md border border-primary-200 bg-surface min-h-[36px]",children:[n.map(o=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-primary-100 px-2 py-0.5 text-xs text-primary-700",children:[o,e.jsx("button",{onClick:()=>c(n.filter(x=>x!==o)),className:"text-primary-400 hover:text-primary-600",children:"×"})]},o)),e.jsx("input",{value:l,onChange:o=>m(o.target.value),onKeyDown:i,placeholder:n.length===0?d:"",className:"flex-1 min-w-[80px] bg-transparent text-sm outline-none"})]})]})}function F({agent:s,onSave:d,onCancel:n,saving:c}){const[l,m]=t.useState(s?.name??""),[i,o]=t.useState(s?.workspace??""),[x,g]=t.useState(s?.emoji??""),[u,v]=t.useState(s?.avatar??""),[b,N]=t.useState(s?.model??""),[w,U]=t.useState(s?.sandbox??!1),[h,z]=t.useState(s?.tools??[]),[j,y]=t.useState(s?.deniedTools??[]),[k,A]=t.useState(s?.channelBindings??[]),[C,T]=t.useState(s?.sessionScope??"per-sender"),r=!!s;return e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsx("h2",{className:"text-lg font-semibold text-primary-900",children:r?"Edit Agent":"Create Agent"}),e.jsx(f,{size:"icon-sm",variant:"ghost",onClick:n,children:e.jsx(p,{icon:G,size:18,strokeWidth:1.5})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"rounded-lg border border-primary-100 bg-surface p-4",children:[e.jsx("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3",children:"Basic Info"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"col-span-2 sm:col-span-1",children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Name"}),e.jsx("input",{value:l,onChange:a=>m(a.target.value),placeholder:"my-agent",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Emoji"}),e.jsx("input",{value:x,onChange:a=>g(a.target.value),placeholder:"🤖",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Avatar URL"}),e.jsx("input",{value:u,onChange:a=>v(a.target.value),placeholder:"https://...",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-500"})]})]})]}),e.jsxs("div",{className:"rounded-lg border border-primary-100 bg-surface p-4",children:[e.jsx("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3",children:"Model & Config"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Model"}),e.jsx("input",{value:b,onChange:a=>N(a.target.value),placeholder:"anthropic/claude-sonnet-4-20250514",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Workspace Path"}),e.jsx("input",{value:i,onChange:a=>o(a.target.value),placeholder:"/root/.openclaw/workspace-myagent",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-500"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-primary-800",children:"Sandbox Mode"}),e.jsx("div",{className:"text-xs text-primary-500",children:"Run agent in isolated sandbox"})]}),e.jsx(_,{checked:w,onCheckedChange:U})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Session Scope"}),e.jsxs("select",{value:C,onChange:a=>T(a.target.value),className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500",children:[e.jsx("option",{value:"per-sender",children:"Per-sender"}),e.jsx("option",{value:"global",children:"Global"})]})]})]})]}),e.jsxs("div",{className:"rounded-lg border border-primary-100 bg-surface p-4",children:[e.jsx("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3",children:"Tools"}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(D,{label:"Allowed Tools",placeholder:"Type tool name and press Enter",values:h,onChange:z}),e.jsx(D,{label:"Denied Tools",placeholder:"Type tool name and press Enter",values:j,onChange:y})]})]}),e.jsxs("div",{className:"rounded-lg border border-primary-100 bg-surface p-4",children:[e.jsx("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3",children:"Channel Bindings"}),e.jsx(D,{label:"Bound Channels",placeholder:"Type channel name and press Enter",values:k,onChange:A})]})]}),e.jsxs("div",{className:"mt-6 flex justify-end gap-2",children:[e.jsx(f,{size:"sm",variant:"outline",onClick:n,children:"Cancel"}),e.jsx(f,{size:"sm",onClick:()=>d({name:l,workspace:i,emoji:x,model:b,avatar:u,sandbox:w,tools:h,deniedTools:j,channelBindings:k,sessionScope:C}),disabled:!l.trim()||c,children:c?e.jsx(p,{icon:I,size:16,className:"animate-spin"}):r?"Save Changes":"Create Agent"})]})]})}function ne({agent:s,onConfirm:d,onCancel:n,deleting:c}){const[l,m]=t.useState(!1);return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onClick:n,children:e.jsxs("div",{className:"w-[min(380px,90vw)] rounded-xl border border-primary-200 bg-surface p-5 shadow-xl",onClick:i=>i.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(p,{icon:J,size:20,className:"text-red-500"}),e.jsx("h3",{className:"text-sm font-medium text-primary-900",children:"Delete Agent"})]}),e.jsxs("p",{className:"text-sm text-primary-600 mb-4",children:["Are you sure you want to delete ",e.jsx("strong",{children:s.name}),"? This cannot be undone."]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm text-primary-700 mb-4 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:l,onChange:i=>m(i.target.checked),className:"rounded border-primary-300"}),"Also delete workspace files"]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(f,{size:"sm",variant:"outline",onClick:n,children:"Cancel"}),e.jsx(f,{size:"sm",onClick:()=>d(l),disabled:c,className:"bg-red-600 text-white hover:bg-red-700",children:c?e.jsx(p,{icon:I,size:16,className:"animate-spin"}):"Delete"})]})]})})}function ge(){const s=L(),[d,n]=t.useState([]),[c,l]=t.useState(!0),[m,i]=t.useState(null),[o,x]=t.useState(!1),[g,u]=t.useState("list"),[v,b]=t.useState(null),[N,w]=t.useState(null),h=q({queryKey:se,queryFn:function(){return P(s)},initialData:function(){return P(s)},staleTime:1/0}).data?.isSidebarCollapsed??!1,z=t.useCallback(()=>{X(s,function(a){return{...a,isSidebarCollapsed:!a.isSidebarCollapsed}})},[s]),j=t.useMemo(()=>({duration:.15,ease:h?"easeIn":"easeOut"}),[h]),y=t.useCallback(async()=>{try{i(null);const r=await te();n(r)}catch(r){i(r instanceof Error?r.message:"Failed to load agents")}finally{l(!1)}},[]);t.useEffect(()=>{y()},[y]);const k=async r=>{x(!0);try{const a=await E({action:"create",name:r.name,workspace:r.workspace||void 0,emoji:r.emoji||void 0,avatar:r.avatar||void 0});if(a.error){i(a.error);return}u("list"),await y()}finally{x(!1)}},A=async r=>{if(v){x(!0);try{const a=await E({action:"update",agentId:v.id,name:r.name||void 0,workspace:r.workspace||void 0,model:r.model||void 0,avatar:r.avatar||void 0});if(a.error){i(a.error);return}b(null),u("list"),await y()}finally{x(!1)}}},C=async r=>{if(N){x(!0);try{const a=await E({action:"delete",agentId:N.id,deleteFiles:r});if(a.error){i(a.error);return}w(null),await y()}finally{x(!1)}}},T=e.jsxs(S.aside,{initial:!1,animate:{width:h?48:300},transition:j,className:"border-r border-primary-200 h-full overflow-hidden bg-primary-100 flex flex-col",children:[e.jsxs(S.div,{layout:!0,transition:{layout:j},className:"flex items-center h-12 px-2 justify-between",children:[e.jsx(W,{initial:!1,children:h?null:e.jsx(S.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:j,children:e.jsxs(M,{to:"/new",className:B(O({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),children:[e.jsx(re,{className:"size-5"}),e.jsx(ae,{})]})})}),e.jsx(Y,{children:e.jsxs(Z,{children:[e.jsx($,{onClick:z,render:e.jsx(f,{size:"icon-sm",variant:"ghost",children:e.jsx(p,{icon:Q,size:20,strokeWidth:1.5})})}),e.jsx(ee,{side:"right",children:h?"Open Sidebar":"Close Sidebar"})]})})]}),e.jsx("div",{className:"px-2 mb-4",children:e.jsxs(M,{to:"/",className:B(O({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),children:[e.jsx(p,{icon:K,size:20,strokeWidth:1.5,className:"min-w-5"}),e.jsx(W,{initial:!1,mode:"wait",children:!h&&e.jsx(S.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:j,className:"overflow-hidden whitespace-nowrap",children:"Back to Chat"})})]})})]});return e.jsx("div",{className:"h-screen bg-surface text-primary-900",children:e.jsxs("div",{className:"h-full overflow-hidden grid grid-cols-[auto_1fr]",children:[T,e.jsxs("main",{"aria-label":"Agent manager",className:"flex flex-col h-full min-h-0",children:[e.jsx("header",{className:"border-b border-primary-200 px-6 py-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg font-semibold text-primary-900",children:"Agents"}),e.jsxs("p",{className:"text-xs text-primary-500 mt-0.5",children:[d.length," agent",d.length!==1?"s":""," configured"]})]}),g==="list"&&e.jsxs(f,{size:"sm",onClick:()=>{b(null),u("create")},children:[e.jsx(p,{icon:R,size:16,strokeWidth:1.5}),e.jsx("span",{className:"ml-1",children:"Create Agent"})]})]})}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-6",children:[m&&e.jsx("div",{className:"mb-4 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 p-3 text-sm text-red-600 dark:text-red-400",children:m}),c?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(p,{icon:I,size:24,className:"animate-spin text-primary-400"})}):g==="list"?e.jsxs("div",{className:"max-w-3xl mx-auto space-y-3",children:[d.map(r=>e.jsx(ie,{agent:r,onEdit:()=>{b(r),u("edit")},onDelete:()=>w(r)},r.id)),d.length===0&&e.jsxs("div",{className:"py-12 text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-12 h-12 rounded-lg bg-primary-50 mb-3",children:e.jsx("span",{className:"text-2xl",children:"🤖"})}),e.jsx("p",{className:"text-sm text-primary-500",children:"No agents found"}),e.jsx("p",{className:"text-xs text-primary-400 mt-1",children:"Create one to get started"})]})]}):g==="create"?e.jsx(F,{onSave:k,onCancel:()=>u("list"),saving:o}):g==="edit"&&v?e.jsx(F,{agent:v,onSave:A,onCancel:()=>{b(null),u("list")},saving:o}):null]}),N&&e.jsx(ne,{agent:N,onConfirm:C,onCancel:()=>w(null),deleting:o})]})]})})}export{ge as AgentsScreen};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/bots-screen-CvbAVMk0.js","assets/main-DJgQwVqD.js","assets/button-BxDVif49.js","assets/switch-LzFh8co4.js","assets/useControlled-KFa25CcD.js","assets/useBaseUiId-CMJ8I9al.js","assets/visuallyHidden-COI6QeQH.js","assets/useQuery-DhR_UXNX.js","assets/useMutation-Bd89JWif.js","assets/proxy-C2vtPufK.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{j as e,r as t,_ as r}from"./main-DJgQwVqD.js";const n=t.lazy(()=>r(()=>import("./bots-screen-CvbAVMk0.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{u as g,j as e,r as f,L as v}from"./main-DJgQwVqD.js";import{H as o,h,c as d,G as x,e as w,B as k,K as C,L as b,r as E}from"./button-BxDVif49.js";import{S}from"./switch-LzFh8co4.js";import{u as j}from"./useQuery-DhR_UXNX.js";import{u as N}from"./useMutation-Bd89JWif.js";import{m as M,A as $}from"./proxy-C2vtPufK.js";import"./useControlled-KFa25CcD.js";import"./useBaseUiId-CMJ8I9al.js";import"./visuallyHidden-COI6QeQH.js";const y=["cron-jobs"];function A(){return j({queryKey:y,queryFn:async({signal:r})=>{const t=new AbortController,n=()=>t.abort();r.addEventListener("abort",n);try{const s=await fetch("/api/cron",{signal:t.signal});if(!s.ok)throw new Error("Failed to fetch cron jobs");const i=await s.json();return Array.isArray(i.jobs)?i.jobs:[]}finally{r.removeEventListener("abort",n)}},refetchInterval:3e4})}function D(r){return j({queryKey:["cron-job-runs",r],queryFn:async({signal:t})=>{if(!r)return[];const n=new AbortController,s=()=>n.abort();t.addEventListener("abort",s);try{const i=await fetch(`/api/cron?jobId=${encodeURIComponent(r)}`,{signal:n.signal});if(!i.ok)throw new Error("Failed to fetch cron job runs");const l=await i.json();return Array.isArray(l.runs)?l.runs:[]}finally{t.removeEventListener("abort",s)}},enabled:!!r})}function L(){const r=g();return N({mutationFn:async t=>{const n=new AbortController,s=await fetch("/api/cron",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jobId:t}),signal:n.signal});if(!s.ok)throw new Error("Failed to run cron job");return s.json()},onSuccess:()=>{r.invalidateQueries({queryKey:y})}})}function R(){const r=g();return N({mutationFn:async({jobId:t,enabled:n})=>{const s=new AbortController,i=await fetch("/api/cron",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({jobId:t,patch:{enabled:n}}),signal:s.signal});if(!i.ok)throw new Error("Failed to update cron job");return i.json()},onSuccess:()=>{r.invalidateQueries({queryKey:y})}})}function J(r){return!r||r<=0?"—":r<1e3?`${r}ms`:r<6e4?`${(r/1e3).toFixed(1)}s`:`${(r/6e4).toFixed(1)}m`}function z(r){return r?new Date(r).toLocaleString():"—"}function F({job:r}){const t=D(r.id),n=t.data??[];return e.jsx(M.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.15},className:"overflow-hidden",children:e.jsxs("div",{className:"space-y-4 border-t border-primary-100 bg-primary-50/50 px-4 py-4",children:[(r.payload.message||r.payload.prompt)&&e.jsxs("div",{children:[e.jsx("h5",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-2",children:"Prompt / Message"}),e.jsx("p",{className:"whitespace-pre-wrap break-words rounded-lg bg-surface border border-primary-100 p-3 text-sm text-primary-700 leading-relaxed",children:r.payload.message??r.payload.prompt})]}),r.delivery&&e.jsxs("div",{children:[e.jsx("h5",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-2",children:"Delivery"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[r.delivery.mode&&e.jsxs("span",{className:"inline-flex items-center px-2 py-0.5 text-[11px] font-medium rounded-full bg-surface text-primary-600 border border-primary-100",children:["Mode: ",r.delivery.mode]}),r.delivery.channel&&e.jsxs("span",{className:"inline-flex items-center px-2 py-0.5 text-[11px] font-medium rounded-full bg-surface text-primary-600 border border-primary-100",children:["Channel: ",r.delivery.channel]}),r.delivery.to&&e.jsxs("span",{className:"inline-flex items-center px-2 py-0.5 text-[11px] font-medium rounded-full bg-surface text-primary-600 border border-primary-100",children:["To: ",r.delivery.to]})]})]}),r.payload.model&&e.jsxs("div",{children:[e.jsx("h5",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-2",children:"Model"}),e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 text-[10px] font-mono rounded-full bg-surface text-primary-600 border border-primary-100",children:r.payload.model})]}),r.state?.lastError&&e.jsxs("div",{children:[e.jsx("h5",{className:"text-xs font-medium text-red-500 uppercase tracking-wider mb-2",children:"Last Error"}),e.jsx("p",{className:"rounded-lg bg-red-50 border border-red-100 p-3 font-mono text-xs text-red-600 leading-relaxed",children:r.state.lastError})]}),e.jsxs("div",{children:[e.jsx("h5",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-2",children:"Recent Runs"}),t.isLoading?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-primary-500",children:[e.jsx(o,{icon:h,size:12,className:"animate-spin"}),"Loading..."]}):n.length===0?e.jsx("p",{className:"text-xs text-primary-400",children:"No run history available"}):e.jsx("div",{className:"space-y-1.5",children:n.slice(0,5).map(s=>e.jsxs("div",{className:"flex items-center gap-3 py-1.5 px-2 rounded-md bg-surface border border-primary-50",children:[e.jsx("span",{className:d("inline-block h-2 w-2 shrink-0 rounded-full",s.status==="ok"?"bg-emerald-500":"bg-red-500")}),e.jsx(o,{icon:x,size:11,strokeWidth:1.5,className:"text-primary-400"}),e.jsx("span",{className:"tabular-nums text-[11px] text-primary-600",children:z(s.ranAt)}),e.jsx("span",{className:"tabular-nums text-[11px] text-primary-400",children:J(s.durationMs)}),s.error&&e.jsx("span",{className:"truncate text-[11px] text-red-500 ml-auto",children:s.error})]},s.id))})]})]})})}function T(r){const t=r.trim().split(/\s+/);if(t.length<5)return r;const[n,s,i,l,c]=t,a=`${s.padStart(2,"0")}:${n.padStart(2,"0")}`;if(i==="*"&&l==="*"&&c==="*")return`Daily at ${a}`;if(i==="*"&&l==="*"&&c!=="*"){const m={0:"Sun",1:"Mon",2:"Tue",3:"Wed",4:"Thu",5:"Fri",6:"Sat",7:"Sun"};return`${c.split(",").map(u=>m[u]??u).join(", ")} at ${a}`}return r}function B(r){const t=r.schedule;return t.kind==="every"&&t.expr?`Every ${t.expr}`:t.kind==="at"&&t.expr?`Once at ${t.expr}`:t.kind==="cron"&&t.expr?T(t.expr):t.expr??"Unknown"}function W(r){if(!r)return"—";const t=Date.now()-r;return t<6e4?"just now":t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:new Date(r).toLocaleDateString()}function q(r){if(!r)return"—";const t=r-Date.now();return t<0?"overdue":t<6e4?"in <1m":t<36e5?`in ${Math.floor(t/6e4)}m`:t<864e5?`in ${Math.floor(t/36e5)}h`:new Date(r).toLocaleDateString()}function K({status:r}){return r==="ok"?e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 text-[11px] font-medium rounded-full bg-emerald-50 text-emerald-600 border border-emerald-100",children:"ok"}):r==="error"?e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 text-[11px] font-medium rounded-full bg-red-50 text-red-600 border border-red-100",children:"error"}):e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 text-[11px] font-medium rounded-full bg-primary-50 text-primary-400 border border-primary-100",children:"—"})}function O({jobs:r}){const[t,n]=f.useState(null),s=L(),i=R(),l=f.useCallback(a=>{i.mutate({jobId:a.id,enabled:!a.enabled})},[i]),c=f.useCallback(a=>{s.mutate(a)},[s]);return r.length===0?null:e.jsx("div",{className:"space-y-2",children:r.map(a=>{const m=t===a.id,p=s.isPending&&s.variables===a.id;return e.jsxs("div",{className:d("group rounded-lg border border-primary-100 bg-surface transition-all duration-150 ease-out",m?"border-primary-200 shadow-sm":"hover:border-primary-200 hover:shadow-sm"),children:[e.jsxs("button",{type:"button",onClick:()=>n(m?null:a.id),className:d("w-full p-4 text-left","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-300 focus-visible:rounded-lg"),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-2",children:[e.jsx("h4",{className:d("text-[13px] font-semibold leading-tight truncate",a.enabled?"text-primary-900":"text-primary-400"),children:a.name??a.id}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[!a.enabled&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 text-[11px] font-medium rounded-full bg-primary-50 text-primary-400 border border-primary-100",children:"Disabled"}),e.jsx(K,{status:a.state?.lastStatus})]})]}),e.jsx("p",{className:"text-xs text-primary-500 leading-relaxed mb-3",children:B(a)}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-primary-50",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("span",{className:"text-[11px] text-primary-400 flex items-center gap-1",children:[e.jsx(o,{icon:x,size:11,strokeWidth:1.5}),"Last: ",W(a.state?.lastRunAtMs)]}),e.jsxs("span",{className:"text-[11px] text-primary-400 flex items-center gap-1",children:[e.jsx(o,{icon:w,size:11,strokeWidth:1.5}),"Next: ",q(a.state?.nextRunAtMs)]})]}),e.jsxs("div",{className:"flex items-center gap-2",onClick:u=>u.stopPropagation(),children:[e.jsx(S,{checked:a.enabled,onCheckedChange:()=>l(a),"aria-label":`${a.enabled?"Disable":"Enable"} ${a.name??a.id}`,disabled:i.isPending}),e.jsx(k,{variant:"ghost",size:"icon-sm",onClick:()=>c(a.id),disabled:p,"aria-label":`Run ${a.name??a.id} now`,className:"text-primary-500 hover:text-primary-700",children:e.jsx(o,{icon:p?h:C,size:16,strokeWidth:1.5,className:d(p&&"animate-spin")})})]})]})]}),e.jsx($,{children:m&&e.jsx(F,{job:a})})]},a.id)})})}function P(r){if(!r)return"never";const t=Date.now()-r;return t<6e4?"just now":t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:new Date(r).toLocaleDateString()}function Q(r){for(const t of[" - "," | ",": "," / "]){const n=r.indexOf(t);if(n>0)return r.substring(0,n).trim()}return r}function I(r){const t=new Map;for(const n of r){const s=Q(n.name??n.id),i=t.get(s);i?i.push(n):t.set(s,[n])}return Array.from(t.entries()).map(([n,s])=>({name:n,jobs:s})).sort((n,s)=>n.name.localeCompare(s.name))}function H({bot:r}){const t=r.jobs.reduce((i,l)=>Math.max(i,l.state?.lastRunAtMs??0),0),n=r.jobs.some(i=>i.state?.lastStatus==="error"),s=r.jobs.filter(i=>i.enabled).length;return e.jsxs("div",{className:"group rounded-lg border border-primary-100 bg-surface p-4 transition-all duration-150 ease-out hover:border-primary-200 hover:shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:d("flex items-center justify-center w-10 h-10 rounded-lg",n?"bg-red-50":"bg-primary-50"),children:e.jsx(o,{icon:b,size:20,strokeWidth:1.5,className:n?"text-red-500":"text-primary-500"})}),e.jsx("h4",{className:"text-[13px] font-semibold text-primary-900 leading-tight truncate",children:r.name})]}),n&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 text-[11px] font-medium rounded-full bg-red-50 text-red-600 border border-red-100 shrink-0",children:"Error"})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-primary-50",children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("span",{className:"text-[11px] text-primary-400 flex items-center gap-1",children:[e.jsx(o,{icon:x,size:11,strokeWidth:1.5}),P(t||void 0)]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center px-2 py-0.5 text-[10px] font-medium rounded-full bg-primary-50 text-primary-500 border border-primary-100",children:[r.jobs.length," job",r.jobs.length!==1?"s":""]}),s<r.jobs.length&&e.jsxs("span",{className:"inline-flex items-center px-2 py-0.5 text-[10px] font-medium rounded-full bg-amber-50 text-amber-600 border border-amber-100",children:[r.jobs.length-s," disabled"]})]})]})]})}function te(){const r=A(),t=r.data??[],n=f.useMemo(()=>I(t),[t]);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.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx(v,{to:"/chat/$sessionKey",params:{sessionKey:"main"},className:"p-1.5 -ml-1.5 rounded-md text-primary-500 hover:text-primary-700 hover:bg-primary-50 transition-colors duration-150","aria-label":"Back to Chat",children:e.jsx(o,{icon:E,size:18,strokeWidth:2})}),e.jsx("h2",{className:"text-base font-semibold text-primary-900",children:"Cron Jobs"})]}),e.jsxs("p",{className:"text-xs text-primary-500",children:[t.length," job",t.length!==1?"s":""," configured"]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto px-4 pb-4 pt-4",children:r.isLoading?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(o,{icon:h,size:18,className:"animate-spin text-primary-300"})}):r.isError?e.jsxs("div",{className:"py-12 text-center",children:[e.jsx("p",{className:"text-sm text-red-500",children:r.error instanceof Error?r.error.message:"Failed to load cron jobs"}),e.jsx("button",{onClick:()=>{r.refetch()},className:"mt-2 text-xs font-medium text-primary-500 hover:text-primary-700 transition-colors duration-150",children:"Retry"})]}):t.length===0?e.jsxs("div",{className:"py-12 text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-12 h-12 rounded-lg bg-primary-50 mb-3",children:e.jsx(o,{icon:x,size:24,className:"text-primary-400"})}),e.jsx("p",{className:"text-sm text-primary-500",children:"No cron jobs configured"}),e.jsx("p",{className:"text-xs text-primary-400 mt-1",children:"Jobs will appear here once created"})]}):e.jsxs("div",{className:"space-y-6",children:[n.length>0&&e.jsxs("section",{children:[e.jsxs("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3 flex items-center gap-2",children:[e.jsx(o,{icon:b,size:14,strokeWidth:1.5}),"Bots (",n.length,")"]}),e.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3",children:n.map(s=>e.jsx(H,{bot:s},s.name))})]}),e.jsxs("section",{children:[e.jsxs("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3 flex items-center gap-2",children:[e.jsx(o,{icon:x,size:14,strokeWidth:1.5}),"All Jobs (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:e.jsx(O,{jobs:t})})]})]})})]})}export{te as BotsScreen};
|