opencami 1.8.9 → 1.8.13
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-DI-5GAnQ.js → CSPContext-DATmz4sz.js} +1 -1
- package/dist/client/assets/{DirectionContext-CrIsc5n9.js → DirectionContext-FHFKdJq_.js} +1 -1
- package/dist/client/assets/_sessionKey-D2ZMdqJ0.js +23 -0
- package/dist/client/assets/agents-9A0buuwT.js +2 -0
- package/dist/client/assets/agents-screen-C58VLjES.js +1 -0
- package/dist/client/assets/bots-Lqt92ma0.js +2 -0
- package/dist/client/assets/{bots-screen-BTKCOohV.js → bots-screen-B8h4Y1VL.js} +1 -1
- package/dist/client/assets/{button-8ab4wOwy.js → button-BcUmP7JL.js} +1 -1
- package/dist/client/assets/{composite-B2qsrzf3.js → composite--BBbKdxm.js} +1 -1
- package/dist/client/assets/{connect-B3_p7C4I.js → connect-BmwKnEFP.js} +1 -1
- package/dist/client/assets/{dashboard-BtClHYpn.js → dashboard-BWQl_-2-.js} +1 -1
- package/dist/client/assets/event-BxzjTPjG.js +1 -0
- package/dist/client/assets/file-explorer-screen-BAbbb_R4.js +1 -0
- package/dist/client/assets/files-DvIFms9G.js +2 -0
- package/dist/client/assets/follow-up-suggestions-Bq-xR5GV.js +5 -0
- package/dist/client/assets/{index-BXiha-Vz.js → index-BTtT4Vbb.js} +1 -1
- package/dist/client/assets/{index-CtlYu8Ug.js → index-rOr2i8gW.js} +1 -1
- package/dist/client/assets/keyboard-shortcuts-dialog-BA8cBwWm.js +1 -0
- package/dist/client/assets/main-_1IghVZn.js +212 -0
- package/dist/client/assets/markdown-CqIcraPO.js +87 -0
- package/dist/client/assets/memory-B3LyVZwO.js +2 -0
- package/dist/client/assets/memory-screen-GBzowsnE.js +1 -0
- package/dist/client/assets/menu--FXN_JCl.js +1 -0
- package/dist/client/assets/{opencami-logo-BSed2Wez.js → opencami-logo-BFo87CeM.js} +1 -1
- package/dist/client/assets/proxy-CJ6-TEKD.js +9 -0
- package/dist/client/assets/{react-WkSlhZJd.js → react-BRYbnjMp.js} +1 -1
- package/dist/client/assets/search-dialog-CJS2GUnE.js +1 -0
- package/dist/client/assets/{search-sources-badge-Du8KpUEb.js → search-sources-badge-D0YArqfp.js} +1 -1
- package/dist/client/assets/session-export-dialog-Bc9YEPLs.js +1 -0
- package/dist/client/assets/settings-dialog-SDzqDXsx.js +1 -0
- package/dist/client/assets/skills-BVLjvrPU.js +2 -0
- package/dist/client/assets/{skills-panel-CVh1I-7D.js → skills-panel-DIalYvpW.js} +1 -1
- package/dist/client/assets/styles-b2XYKZYx.css +1 -0
- package/dist/client/assets/switch-BwmDNR0d.js +1 -0
- package/dist/client/assets/tabs-T1fJbUsm.js +1 -0
- package/dist/client/assets/thinking-DUdE6Iej.js +1 -0
- package/dist/client/assets/tooltip-DexBPu8g.js +1 -0
- package/dist/client/assets/use-file-explorer-state-eXs92yKN.js +12 -0
- package/dist/client/assets/{useBaseUiId-DiwX_3so.js → useBaseUiId-DN9cOflS.js} +1 -1
- package/dist/client/assets/{useCompositeItem-UPIPwR9H.js → useCompositeItem-B_J-cnZX.js} +1 -1
- package/dist/client/assets/{useControlled-CT2hRlcU.js → useControlled-DeDLOsPR.js} +1 -1
- package/dist/client/assets/{useMutation-rx8UH99I.js → useMutation-TzgejsE_.js} +1 -1
- package/dist/client/assets/useOnFirstRender-S4-xcV93.js +1 -0
- package/dist/client/assets/{useQuery-Boaa6oF3.js → useQuery-BdjM5kzn.js} +1 -1
- package/dist/server/assets/{_sessionKey-B6iYeyCS.js → _sessionKey-DBzlGMo3.js} +147 -129
- package/dist/server/assets/{_tanstack-start-manifest_v-C9chPgNH.js → _tanstack-start-manifest_v-CX4xb59U.js} +1 -1
- package/dist/server/assets/{agents-CmQ4vvXm.js → agents-BuE0Yum3.js} +1 -1
- package/dist/server/assets/{agents-screen-bmrIyFbk.js → agents-screen-CEQhbEwf.js} +3 -3
- package/dist/server/assets/{bots-Byt6jv0a.js → bots-BDHeSvSQ.js} +1 -1
- package/dist/server/assets/{bots-screen-C2TGFv42.js → bots-screen-C0NRS526.js} +2 -2
- package/dist/server/assets/{button-CwY2OHFj.js → button-kI8fEIZQ.js} +1 -1
- package/dist/server/assets/{connect-BNabuqpW.js → connect-CTVBm0Vc.js} +2 -2
- package/dist/server/assets/{file-explorer-screen-DH4UFK03.js → file-explorer-screen-FU_NhZmS.js} +4 -4
- package/dist/server/assets/{files-DYdXlQDr.js → files-DLxqp-h5.js} +1 -1
- package/dist/server/assets/{follow-up-suggestions-mzRQIB0k.js → follow-up-suggestions-BmSFSY87.js} +8 -8
- package/dist/server/assets/{index-BEWnDAH6.js → index-B_F4DTUu.js} +1 -1
- package/dist/server/assets/{index-COElhwGA.js → index-C1dylvu-.js} +1 -1
- package/dist/server/assets/{keyboard-shortcuts-dialog-Cr6fOqHz.js → keyboard-shortcuts-dialog-Cp3ECNNi.js} +2 -2
- package/dist/server/assets/{markdown-DoX5Q7qh.js → markdown-CFdYXCRQ.js} +3 -3
- package/dist/server/assets/{memory-Cxu7i8ej.js → memory-rBB015W-.js} +1 -1
- package/dist/server/assets/{memory-screen-B5l1NZRY.js → memory-screen-vqXczcVo.js} +4 -4
- package/dist/server/assets/{menu-D90CDTi2.js → menu-D8cKTpmN.js} +1 -1
- package/dist/server/assets/{router-BqLGFd4L.js → router-CL6A11qi.js} +305 -85
- package/dist/server/assets/{search-dialog-CmI7naPN.js → search-dialog-D8DvpPZw.js} +8 -8
- package/dist/server/assets/{search-sources-badge-B0rAEDs_.js → search-sources-badge-B0t8Qffy.js} +1 -1
- package/dist/server/assets/{session-export-dialog-C53RRAah.js → session-export-dialog-CgtlOnwf.js} +2 -2
- package/dist/server/assets/{settings-dialog-BZ67gr9N.js → settings-dialog-CeP-J_NJ.js} +35 -18
- package/dist/server/assets/{skills-Cy8xclXY.js → skills-BXUivxuo.js} +1 -1
- package/dist/server/assets/{skills-panel-BnRNb7u9.js → skills-panel-CDUp4jvw.js} +2 -2
- package/dist/server/assets/{switch-BbkUeVDV.js → switch-BZzwkgAQ.js} +1 -1
- package/dist/server/assets/{tabs-DDFZob0m.js → tabs-CWbp3mT4.js} +1 -1
- package/dist/server/assets/{thinking-CA8PSwKJ.js → thinking-ClIWjSbx.js} +8 -8
- package/dist/server/assets/{tooltip-DgsSPocE.js → tooltip-DOvOrSSS.js} +1 -1
- package/dist/server/assets/{use-file-explorer-state-s7CS50ho.js → use-file-explorer-state-E6cUvMva.js} +1 -1
- package/dist/server/server.js +195 -38
- package/package.json +1 -1
- package/dist/client/assets/_sessionKey-B4NZmxf3.js +0 -21
- package/dist/client/assets/agents-bptidK8z.js +0 -2
- package/dist/client/assets/agents-screen-6qdnPmx2.js +0 -1
- package/dist/client/assets/bots-BWpbaQ-E.js +0 -2
- package/dist/client/assets/event-DG3RKJz8.js +0 -1
- package/dist/client/assets/file-explorer-screen-Djl8x-8P.js +0 -1
- package/dist/client/assets/files-CjbCJDgC.js +0 -2
- package/dist/client/assets/follow-up-suggestions-BSCMXRXh.js +0 -5
- package/dist/client/assets/keyboard-shortcuts-dialog-HAufCn9C.js +0 -1
- package/dist/client/assets/main-CQKtcNr3.js +0 -210
- package/dist/client/assets/markdown-DFJF-FsV.js +0 -87
- package/dist/client/assets/memory-DnJOmcwU.js +0 -2
- package/dist/client/assets/memory-screen-Bm4NMAnU.js +0 -1
- package/dist/client/assets/menu-D26Vmgxl.js +0 -1
- package/dist/client/assets/popupStateMapping-DkI2OCkW.js +0 -1
- package/dist/client/assets/proxy-CHQ-VCN1.js +0 -9
- package/dist/client/assets/search-dialog-CCl4d0Pi.js +0 -1
- package/dist/client/assets/session-export-dialog-io9FvLKq.js +0 -1
- package/dist/client/assets/settings-dialog-B93qswor.js +0 -1
- package/dist/client/assets/skills-BNDGnHwM.js +0 -2
- package/dist/client/assets/styles-Ce2xZzc4.css +0 -1
- package/dist/client/assets/switch-CSnzINDW.js +0 -1
- package/dist/client/assets/tabs-CWfn44FL.js +0 -1
- package/dist/client/assets/thinking-BmoLlbFC.js +0 -1
- package/dist/client/assets/tooltip-CSGMH2t4.js +0 -1
- package/dist/client/assets/use-file-explorer-state-BYVzjwPA.js +0 -12
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as t}from"./main-
|
|
1
|
+
import{r as t}from"./main-_1IghVZn.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-_1IghVZn.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,23 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/settings-dialog-SDzqDXsx.js","assets/main-_1IghVZn.js","assets/react-BRYbnjMp.js","assets/button-BcUmP7JL.js","assets/use-file-explorer-state-eXs92yKN.js","assets/useOnFirstRender-S4-xcV93.js","assets/useBaseUiId-DN9cOflS.js","assets/event-BxzjTPjG.js","assets/visuallyHidden-COI6QeQH.js","assets/composite--BBbKdxm.js","assets/switch-BwmDNR0d.js","assets/useControlled-DeDLOsPR.js","assets/tabs-T1fJbUsm.js","assets/useCompositeItem-B_J-cnZX.js","assets/DirectionContext-FHFKdJq_.js","assets/CSPContext-DATmz4sz.js","assets/index-BTtT4Vbb.js","assets/useQuery-BdjM5kzn.js","assets/tooltip-DexBPu8g.js","assets/useMutation-TzgejsE_.js","assets/menu--FXN_JCl.js","assets/opencami-logo-BFo87CeM.js","assets/proxy-CJ6-TEKD.js","assets/markdown-CqIcraPO.js","assets/index-T4TOjvD0.js","assets/session-export-dialog-Bc9YEPLs.js","assets/thinking-DUdE6Iej.js","assets/search-sources-badge-D0YArqfp.js","assets/follow-up-suggestions-Bq-xR5GV.js","assets/keyboard-shortcuts-dialog-BA8cBwWm.js","assets/search-dialog-CJS2GUnE.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as s,u as pt,j as n,L as Be,_ as rt,d as _t,w as Zr,a as es,z as ts}from"./main-_1IghVZn.js";import{u as Mt}from"./useQuery-BdjM5kzn.js";import{T as Me,a as Ae,b as De,c as Oe,s as Ye,d as ns,g as jn}from"./tooltip-DexBPu8g.js";import{C as rs,c as D,B as we,ac as ln,ag as Je,E as ss,H as J,J as er,V as Pt,aj as os,ak as is,al as as,a as tr,am as ls,G as cs,an as us,l as ds,b as et,I as fs,ao as ms,a3 as ps,s as Vt,ap as hs,L as gs,aq as ys,A as xs,N as ws,Q as bs,X as nr,x as Ss,h as vs,ar as rr,as as js,p as Es,T as sr,u as or,at as En,au as Cs,av as ks,aw as Ns}from"./button-BcUmP7JL.js";import{u as ir}from"./useMutation-TzgejsE_.js";import{j as Ts,k as Rs,l as Is,m as Ms,n as As,o as Ds,p as Os,q as Ls,r as _s,s as ar,D as Ps,a as Ks,b as zs,c as Us,d as $s,u as Fs}from"./use-file-explorer-state-eXs92yKN.js";import{e as lr,a as Ve,g as cr,t as Hs,u as Le,f as Ws,n as Xs}from"./useBaseUiId-DN9cOflS.js";import{u as Bs}from"./useControlled-DeDLOsPR.js";import{a2 as Ys,a3 as Gs,a4 as Cn,t as ur,u as Vs,J as ke,e as qs,a as At}from"./useOnFirstRender-S4-xcV93.js";import{u as Js,e as Qs,p as Zs}from"./event-BxzjTPjG.js";import{u as eo}from"./CSPContext-DATmz4sz.js";import{u as dr}from"./DirectionContext-FHFKdJq_.js";import{M as cn,a as un,b as dn,c as nt}from"./menu--FXN_JCl.js";import{O as to,a as no}from"./opencami-logo-BFo87CeM.js";import{m as be,A as Ie}from"./proxy-CJ6-TEKD.js";import{M as ro}from"./markdown-CqIcraPO.js";import{u as so,p as fr}from"./index-BTtT4Vbb.js";import{c as mr}from"./react-BRYbnjMp.js";function qt(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 kn=/^Conversation info \(untrusted metadata\):\s*```(?:json)?\s*[\s\S]*?```\s*/,Nn=/^Conversation info \(untrusted metadata\):\s*\{[\s\S]*?\}\s*/,Tn=/^Sender \(untrusted metadata\):\s*```(?:[a-zA-Z0-9_-]+)?\s*[\s\S]*?```\s*/gm,oo=/^Sender \(untrusted metadata\):\s*\{[^\n]*\}\s*$/gm,Rn=/<supermemory-context\b[^>]*>[\s\S]*?<\/supermemory-context>/gi,In=/<supermemory-containers\b[^>]*>[\s\S]*?<\/supermemory-containers>/gi,io=/<workspace-critical-rules\b[^>]*>[\s\S]*?<\/workspace-critical-rules>/gi,ao=/^\[(?:[A-Za-z]{3}\s+)?\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}\s+GMT[+-]?\d+\]\s*/gm,lo=/\n{3,}/g;function pr(e){let t=e;t=t.replace(Rn,"").replace(In,"").replace(io,"").replace(Tn,"");const r=kn.test(t),o=!r&&Nn.test(t);return r?t=t.replace(kn,""):o&&(t=t.replace(Nn,"")),t=t.replace(Rn,"").replace(In,"").replace(Tn,"").replace(oo,"").replace(ao,"").replace(lo,`
|
|
3
|
+
|
|
4
|
+
`),t.trim()}function _e(e){const r=(Array.isArray(e.content)?e.content:[]).map(o=>o.type==="text"?String(o.text??""):"").join("").trim();return pr(r)}function Ge(e){return(Array.isArray(e.content)?e.content:[]).filter(r=>r.type==="toolCall")}function co(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 Jt(e){const t=[e.createdAt,e.created_at,e.timestamp,e.time,e.ts];for(const r of t){const o=co(r);if(o)return o}return Date.now()}const uo=["agent:main:main","main"];function Qt(e){return uo.includes(e)}const fo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function mo(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 fo.test(t)?"webchat":"chat"}return"other"}function po(e){return Array.isArray(e)?e.map(t=>{const r=typeof t.key=="string"&&t.key.trim().length>0?t.key.trim():qt(t.friendlyId??t.key),o=typeof t.friendlyId=="string"&&t.friendlyId.trim().length>0?t.friendlyId.trim():qt(r),a=mo(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 ze(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 ho="Missing gateway auth. Set CLAWDBOT_GATEWAY_TOKEN (recommended) or CLAWDBOT_GATEWAY_PASSWORD in the server environment.";function Mn(e){return e.includes(ho)}function An(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 go(){const e=await fetch("/api/sessions");if(!e.ok)throw new Error(await ze(e));const t=await e.json();return po(t.sessions)}async function yo(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 ze(r));return await r.json()}async function xo(){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 ze(r));return await r.json()}catch(r){throw r instanceof DOMException&&r.name==="AbortError"?new Error("Gateway check timed out"):r}finally{window.clearTimeout(t)}}function fn(e,t,r,o){const a=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 Ut(e,t,r,o){fn(e,t,r,function(i){return[...i,o]})}function wo(e,t,r,o,a){const i=`opt-${o}`;fn(e,t,r,function(c){return c.map(u=>u.clientId===o||u.__optimisticId===o||u.__optimisticId===i?a(u):u)})}function bo(e,t,r,o,a){fn(e,t,r,function(l){return l.filter(c=>!(c.clientId===o||c.__optimisticId===o||a&&c.__optimisticId===a))})}function Zt(e,t,r){const o=me.history(t,r);e.setQueryData(o,{sessionKey:r,messages:[]})}function So(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 vo(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 jo(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 Eo(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 ze(a);console.error("[updateSessionLabel] Failed to persist:",i)}}catch(a){console.error("[updateSessionLabel] Network error:",a)}}function Co(){const[e,t]=s.useState(!1),[r,o]=s.useState(!1),[a,i]=s.useState(null),[l,c]=s.useState(null),u=s.useCallback(async()=>{if(t(!0),i(null),!(r||l)){o(!0);try{const h=await fetch("/api/paths");if(!h.ok)throw new Error(await ze(h));const x=await h.json();c({agentId:String(x.agentId??"main"),stateDir:String(x.stateDir??""),sessionsDir:String(x.sessionsDir??""),storePath:String(x.storePath??"")})}catch(h){i(h instanceof Error?h.message:String(h))}finally{o(!1)}}},[l,r]),d=s.useCallback(()=>{u()},[u]),f=s.useCallback(()=>{t(!1)},[]),m=s.useCallback(()=>{if(l?.sessionsDir)try{navigator.clipboard.writeText(l.sessionsDir)}catch{}},[l]),p=s.useCallback(()=>{if(l?.storePath)try{navigator.clipboard.writeText(l.storePath)}catch{}},[l]);return{settingsOpen:e,setSettingsOpen:t,pathsLoading:r,pathsError:a,paths:l,handleOpenSettings:d,closeSettings:f,copySessionsDir:m,copyStorePath:p}}let ve=null,mn=!1,Tt=null;function ko(e){ve=e}function $t(){return ve!==null}function wt(e){mn=e}function Ft(){return mn}function Dt(){ve=null,mn=!1}function No(e,t){if(ve){if(e&&ve.sessionKey===e){Dt();return}t&&ve.friendlyId===t&&Dt()}}function To(e){Tt={friendlyId:e,at:Date.now()}}function hr(e,t=15e3){return!(!Tt||Tt.friendlyId!==e||Date.now()-Tt.at>t)}function Ro(e,t){if(!ve)return null;if(e&&ve.sessionKey===e){const r=ve;return ve=null,r}if(t&&ve.friendlyId===t){const r=ve;return ve=null,r}return null}const Io=8e3,tt=new Map;function Mo(e){e&&tt.set(e,{id:e,expiresAt:Date.now()+Io})}function Ao(e){e&&tt.delete(e)}function Do(e){if(tt.size===0)return e;const t=Date.now();let r=!1;const o=e.filter(a=>{const i=tt.get(a.key),l=tt.get(a.friendlyId);return i&&i.expiresAt<=t||l&&l.expiresAt<=t?(i&&i.expiresAt<=t&&tt.delete(a.key),l&&l.expiresAt<=t&&tt.delete(a.friendlyId),!0):i||l?(r=!0,!1):!0});return r?o:e}function Oo(){const e=pt(),[t,r]=s.useState(!1),[o,a]=s.useState(null),i=ir({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 ze(f));return u},onMutate:async function(u){a(null),Mo(u.sessionKey||u.friendlyId),No(u.sessionKey,u.friendlyId),await e.cancelQueries({queryKey:me.sessions});const d=e.getQueryData(me.sessions);return jo(e,u.sessionKey,u.friendlyId),u.isActive&&(u.sessionKey||u.friendlyId)&&Zt(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),Ao(d.sessionKey||d.friendlyId),a(u instanceof Error?u.message:String(u))},onSuccess:function(u){u.isActive&&Dt(),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 Lo(){const e=pt(),[t,r]=s.useState(!1),[o,a]=s.useState(null),i=ir({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 ze(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 gr(e){return!e.content||!Array.isArray(e.content)?"":e.content.filter(t=>t.type==="text").map(t=>t.text||"").join(`
|
|
5
|
+
`)}function _o(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=gr(a);if(l){const c=i==="user"?"User":"Assistant";o.push(`## ${c}`),o.push(""),o.push(l),o.push("")}}return o.join(`
|
|
6
|
+
`)}function Po(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 Ko(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=gr(a);if(l){const c=i==="user"?"User":"Assistant";o.push(`${c}:`),o.push(l),o.push("")}}return o.join(`
|
|
7
|
+
`)}function zo(e,t,r){const o=new Date;let a,i,l;switch(r){case"markdown":a=_o(e,t,o),i=`${Ht(e)}.md`,l="text/markdown";break;case"json":a=Po(e,t,o),i=`${Ht(e)}.json`,l="application/json";break;case"txt":a=Ko(e,t,o),i=`${Ht(e)}.txt`,l="text/plain";break;default:throw new Error(`Unsupported format: ${r}`)}Uo(a,i,l)}function Ht(e){return e.replace(/[^a-z0-9-_\s]/gi,"").replace(/\s+/g,"-").toLowerCase().slice(0,50)||"conversation"}function Uo(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 $o(e){const{children:t,open:r,defaultOpen:o=!1,onOpenChange:a,onOpenChangeComplete:i,actionsRef:l,handle:c,triggerId:u,defaultTriggerId:d=null}=e,f=Ts(),m=!!f,p=rs(()=>c?.store??new Rs({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 h=p.useState("payload");Is({store:p,actionsRef:l,parentContext:f?.store.context});const x=s.useMemo(()=>({store:p}),[p]);return n.jsx(Ms.Provider,{value:x,children:typeof t=="function"?t({payload:h}):t})}function Fo({children:e,...t}){return n.jsx($o,{...t,children:e})}function Ho({className:e,children:t}){return n.jsxs(As,{children:[n.jsx(Ds,{className:"fixed inset-0 bg-primary-950/20 transition-all duration-150 data-[state=open]:opacity-100 data-[state=closed]:opacity-0"}),n.jsx(Os,{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 Wo({className:e,...t}){return n.jsx(Ls,{className:D("text-lg font-medium text-primary-900",e),...t})}function Xo({className:e,...t}){return n.jsx(_s,{className:D("text-sm text-primary-600",e),...t})}function Bo({className:e,...t}){return n.jsx(ar,{render:n.jsx(we,{variant:"outline",className:D(e)}),...t})}function Yo({className:e,...t}){return n.jsx(ar,{render:n.jsx(we,{variant:"destructive",className:D(e)}),...t})}function Go({open:e,onOpenChange:t,sessionTitle:r,onConfirm:o,onCancel:a}){return n.jsx(Fo,{open:e,onOpenChange:t,children:n.jsx(Ho,{children:n.jsxs("div",{className:"p-4",children:[n.jsx(Wo,{className:"mb-1",children:"Delete Session"}),n.jsxs(Xo,{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(Bo,{onClick:a,children:"Cancel"}),n.jsx(Yo,{onClick:o,children:"Delete"})]})]})})})}function Vo({open:e,onOpenChange:t,sessionTitle:r,onSave:o,onCancel:a}){return n.jsx(Ps,{open:e,onOpenChange:t,children:n.jsx(Ks,{children:n.jsxs("div",{className:"p-4",children:[n.jsx(zs,{className:"mb-1",children:"Rename"}),n.jsx(Us,{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($s,{onClick:a,children:"Cancel"}),n.jsx(we,{onClick:i=>{const l=i.currentTarget.parentElement?.previousElementSibling;o(l.value)},children:"Save"})]})]})})})}function qo(e){const{open:t,defaultOpen:r,onOpenChange:o,disabled:a}=e,i=t!==void 0,[l,c]=Bs({controlled:t,default:r,name:"Collapsible",state:"open"}),{mounted:u,setMounted:d,transitionStatus:f}=Ys(l,!0,!0),[m,p]=s.useState(l),[{height:h,width:x},g]=s.useState({height:void 0,width:void 0}),S=lr(),[b,v]=s.useState(),$=b??S,[L,F]=s.useState(!1),[I,Q]=s.useState(!1),X=s.useRef(null),P=s.useRef(null),ne=s.useRef(null),H=s.useRef(null),k=Gs(H,!1),j=Ve(E=>{const T=!l,O=cr(Hs,E.nativeEvent);if(o(T,O),O.isCanceled)return;const U=H.current;P.current==="css-animation"&&U!=null&&U.style.removeProperty("animation-name"),!L&&!I&&(P.current!=null&&P.current!=="css-animation"&&!u&&T&&d(!0),P.current==="css-animation"&&(!m&&T&&p(!0),!u&&T&&d(!0))),c(T),P.current==="none"&&u&&!T&&d(!1)});return Le(()=>{i&&P.current==="none"&&!I&&!l&&d(!1)},[i,I,l,t,d]),s.useMemo(()=>({abortControllerRef:X,animationTypeRef:P,disabled:a,handleTrigger:j,height:h,mounted:u,open:l,panelId:$,panelRef:H,runOnceAnimationsFinish:k,setDimensions:g,setHiddenUntilFound:F,setKeepMounted:Q,setMounted:d,setOpen:c,setPanelIdState:v,setVisible:p,transitionDimensionRef:ne,transitionStatus:f,visible:m,width:x}),[X,P,a,j,h,u,l,$,H,k,g,F,Q,d,c,p,ne,f,m,x])}const yr=s.createContext(void 0);function xr(){const e=s.useContext(yr);if(e===void 0)throw new Error(ln(15));return e}let bt=(function(e){return e.open="data-open",e.closed="data-closed",e[e.startingStyle=Cn.startingStyle]="startingStyle",e[e.endingStyle=Cn.endingStyle]="endingStyle",e})({}),Jo=(function(e){return e.panelOpen="data-panel-open",e})({});const Qo={[bt.open]:""},Zo={[bt.closed]:""},ei={open(e){return e?{[Jo.panelOpen]:""}:null}},ti={open(e){return e?Qo:Zo}},wr={...ti,...ur},ni=s.forwardRef(function(t,r){const{render:o,className:a,defaultOpen:i=!1,disabled:l=!1,onOpenChange:c,open:u,...d}=t,f=Ve(c),m=qo({open:u,defaultOpen:i,onOpenChange:f,disabled:l}),p=s.useMemo(()=>({open:m.open,disabled:m.disabled,transitionStatus:m.transitionStatus}),[m.open,m.disabled,m.transitionStatus]),h=s.useMemo(()=>({...m,onOpenChange:f,state:p}),[m,f,p]),x=Je("div",t,{state:p,ref:r,props:d,stateAttributesMapping:wr});return n.jsx(yr.Provider,{value:h,children:x})}),ri={...ei,...ur},si=s.forwardRef(function(t,r){const{panelId:o,open:a,handleTrigger:i,state:l,disabled:c}=xr(),{className:u,disabled:d=c,id:f,render:m,nativeButton:p=!0,...h}=t,{getButtonProps:x,buttonRef:g}=Ws({disabled:d,focusableWhenDisabled:!0,native:p}),S=s.useMemo(()=>({"aria-controls":a?o:void 0,"aria-expanded":a,onClick:i}),[o,a,i]);return Je("button",t,{state:l,ref:[r,g],props:[S,h,x],stateAttributesMapping:ri})});let oi=(function(e){return e.disabled="data-disabled",e.orientation="data-orientation",e})({});function ii(e){const{abortControllerRef:t,animationTypeRef:r,externalRef:o,height:a,hiddenUntilFound:i,keepMounted:l,id:c,mounted:u,onOpenChange:d,open:f,panelRef:m,runOnceAnimationsFinish:p,setDimensions:h,setMounted:x,setOpen:g,setVisible:S,transitionDimensionRef:b,visible:v,width:$}=e,L=s.useRef(!1),F=s.useRef(null),I=s.useRef(f),Q=s.useRef(f),X=Vs(),P=s.useMemo(()=>r.current==="css-animation"?!v:!f&&!u,[f,u,v,r]),ne=Ve(k=>{if(!k)return;if(r.current==null||b.current==null){const T=getComputedStyle(k),O=T.animationName!=="none"&&T.animationName!=="",U=T.transitionDuration!=="0s"&&T.transitionDuration!=="";O&&U||(T.animationName==="none"&&T.transitionDuration!=="0s"?r.current="css-transition":T.animationName!=="none"&&T.transitionDuration==="0s"?r.current="css-animation":r.current="none"),k.getAttribute(oi.orientation)==="horizontal"||T.transitionProperty.indexOf("width")>-1?b.current="width":b.current="height"}if(r.current!=="css-transition")return;(a===void 0||$===void 0)&&(h({height:k.scrollHeight,width:k.scrollWidth}),Q.current&&k.style.setProperty("transition-duration","0s"));let j=-1,E=-1;return j=ke.request(()=>{Q.current=!1,E=ke.request(()=>{setTimeout(()=>{k.style.removeProperty("transition-duration")})})}),()=>{ke.cancel(j),ke.cancel(E)}}),H=ss(o,m,ne);return Le(()=>{if(r.current!=="css-transition")return;const k=m.current;if(!k)return;let j=-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(T=>{k.style.setProperty(T,"initial","important")}),!Q.current&&!l&&k.setAttribute(bt.startingStyle,""),h({height:k.scrollHeight,width:k.scrollWidth}),j=ke.request(()=>{Object.entries(E).forEach(([T,O])=>{O===""?k.style.removeProperty(T):k.style.setProperty(T,O)})})}else{if(k.scrollHeight===0&&k.scrollWidth===0)return;h({height:k.scrollHeight,width:k.scrollWidth});const E=new AbortController;t.current=E;const T=E.signal;let O=null;const U=bt.endingStyle;return O=new MutationObserver(Z=>{Z.some(M=>M.type==="attributes"&&M.attributeName===U)&&(O?.disconnect(),O=null,p(()=>{h({height:0,width:0}),k.style.removeProperty("content-visibility"),x(!1),t.current===E&&(t.current=null)},T))}),O.observe(k,{attributes:!0,attributeFilter:[U]}),()=>{O?.disconnect(),X.cancel(),t.current===E&&(E.abort(),t.current=null)}}return()=>{ke.cancel(j)}},[t,r,X,i,l,u,f,m,p,h,x]),Le(()=>{if(r.current!=="css-animation")return;const k=m.current;k&&(F.current=k.style.animationName||F.current,k.style.setProperty("animation-name","none"),h({height:k.scrollHeight,width:k.scrollWidth}),!I.current&&!L.current&&k.style.removeProperty("animation-name"),f?(t.current!=null&&(t.current.abort(),t.current=null),x(!0),S(!0)):(t.current=new AbortController,p(()=>{x(!1),S(!1),t.current=null},t.current.signal)))},[t,r,f,m,p,h,x,S,v]),Js(()=>{const k=ke.request(()=>{I.current=!1});return()=>ke.cancel(k)}),Le(()=>{if(!i)return;const k=m.current;if(!k)return;let j=-1,E=-1;return f&&L.current&&(k.style.transitionDuration="0s",h({height:k.scrollHeight,width:k.scrollWidth}),j=ke.request(()=>{L.current=!1,E=ke.request(()=>{setTimeout(()=>{k.style.removeProperty("transition-duration")})})})),()=>{ke.cancel(j),ke.cancel(E)}},[i,f,m,h]),Le(()=>{const k=m.current;k&&i&&P&&(k.setAttribute("hidden","until-found"),r.current==="css-transition"&&k.setAttribute(bt.startingStyle,""))},[i,P,r,m]),s.useEffect(function(){const j=m.current;if(!j)return;function E(T){L.current=!0,g(!0),d(!0,cr(Xs,T))}return j.addEventListener("beforematch",E),()=>{j.removeEventListener("beforematch",E)}},[d,m,g]),s.useMemo(()=>({props:{hidden:P,id:c,ref:H}}),[P,c,H])}let Dn=(function(e){return e.collapsiblePanelHeight="--collapsible-panel-height",e.collapsiblePanelWidth="--collapsible-panel-width",e})({});const ai=s.forwardRef(function(t,r){const{className:o,hiddenUntilFound:a,keepMounted:i,render:l,id:c,...u}=t,{abortControllerRef:d,animationTypeRef:f,height:m,mounted:p,onOpenChange:h,open:x,panelId:g,panelRef:S,runOnceAnimationsFinish:b,setDimensions:v,setHiddenUntilFound:$,setKeepMounted:L,setMounted:F,setPanelIdState:I,setOpen:Q,setVisible:X,state:P,transitionDimensionRef:ne,visible:H,width:k,transitionStatus:j}=xr(),E=a??!1,T=i??!1;Le(()=>{if(c)return I(c),()=>{I(void 0)}},[c,I]),Le(()=>{$(E)},[$,E]),Le(()=>{L(T)},[L,T]);const{props:O}=ii({abortControllerRef:d,animationTypeRef:f,externalRef:r,height:m,hiddenUntilFound:E,id:g,keepMounted:T,mounted:p,onOpenChange:h,open:x,panelRef:S,runOnceAnimationsFinish:b,setDimensions:v,setMounted:F,setOpen:Q,setVisible:X,transitionDimensionRef:ne,visible:H,width:k});qs({open:x&&j==="idle",ref:S,onComplete(){x&&v({height:void 0,width:void 0})}});const U=s.useMemo(()=>({...P,transitionStatus:j}),[P,j]),Z=Je("div",t,{state:U,ref:[r,S],props:[O,{style:{[Dn.collapsiblePanelHeight]:m===void 0?"auto":`${m}px`,[Dn.collapsiblePanelWidth]:k===void 0?"auto":`${k}px`}},u],stateAttributesMapping:wr});return T||E||!T&&p?Z:null});function en(e){return n.jsx(ni,{...e})}function tn({className:e,...t}){return n.jsx(si,{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 nn({className:e,contentClassName:t,children:r,...o}){return n.jsx(ai,{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 br=s.createContext(void 0);function Kt(){const e=s.useContext(br);if(e===void 0)throw new Error(ln(53));return e}let Ot=(function(e){return e.scrollAreaCornerHeight="--scroll-area-corner-height",e.scrollAreaCornerWidth="--scroll-area-corner-width",e})({});const Ct=500,On=16;function Ne(e,t,r){if(!e)return 0;const o=getComputedStyle(e),a=r==="x"?"Inline":"Block";return r==="x"&&t==="margin"?parseFloat(o[`${t}InlineStart`])*2:parseFloat(o[`${t}${a}Start`])+parseFloat(o[`${t}${a}End`])}let li=(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 kt="base-ui-disable-scrollbar",Sr={className:kt,getElement(e){return n.jsx("style",{nonce:e,href:kt,precedence:"base-ui:low",children:`.${kt}{scrollbar-width:none}.${kt}::-webkit-scrollbar{display:none}`})}};let lt=(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 pn={hasOverflowX:e=>e?{[lt.hasOverflowX]:""}:null,hasOverflowY:e=>e?{[lt.hasOverflowY]:""}:null,overflowXStart:e=>e?{[lt.overflowXStart]:""}:null,overflowXEnd:e=>e?{[lt.overflowXEnd]:""}:null,overflowYStart:e=>e?{[lt.overflowYStart]:""}:null,overflowYEnd:e=>e?{[lt.overflowYEnd]:""}:null,cornerHidden:()=>null},ci={x:0,y:0},Ln={width:0,height:0},ui={xStart:!1,xEnd:!1,yStart:!1,yEnd:!1},di={x:!1,y:!1,corner:!1},fi=s.forwardRef(function(t,r){const{render:o,className:a,overflowEdgeThreshold:i,...l}=t,c=mi(i),u=lr(),d=At(),f=At(),{nonce:m,disableStyleElements:p}=eo(),[h,x]=s.useState(!1),[g,S]=s.useState(!1),[b,v]=s.useState(!1),[$,L]=s.useState(!1),[F,I]=s.useState(Ln),[Q,X]=s.useState(Ln),[P,ne]=s.useState(ui),[H,k]=s.useState(di),j=s.useRef(null),E=s.useRef(null),T=s.useRef(null),O=s.useRef(null),U=s.useRef(null),Z=s.useRef(null),C=s.useRef(null),M=s.useRef(!1),y=s.useRef(0),A=s.useRef(0),_=s.useRef(0),V=s.useRef(0),G=s.useRef("vertical"),B=s.useRef(ci),Y=Ve(R=>{const de=R.x-B.current.x,je=R.y-B.current.y;B.current=R,je!==0&&(v(!0),d.start(Ct,()=>{v(!1)})),de!==0&&(S(!0),f.start(Ct,()=>{S(!1)}))}),se=Ve(R=>{R.button===0&&(M.current=!0,y.current=R.clientY,A.current=R.clientX,G.current=R.currentTarget.getAttribute(li.orientation),E.current&&(_.current=E.current.scrollTop,V.current=E.current.scrollLeft),U.current&&G.current==="vertical"&&U.current.setPointerCapture(R.pointerId),Z.current&&G.current==="horizontal"&&Z.current.setPointerCapture(R.pointerId))}),pe=Ve(R=>{if(!M.current)return;const de=R.clientY-y.current,je=R.clientX-A.current;if(E.current){const Te=E.current.scrollHeight,$e=E.current.clientHeight,N=E.current.scrollWidth,W=E.current.clientWidth;if(U.current&&T.current&&G.current==="vertical"){const K=Ne(T.current,"padding","y"),le=Ne(U.current,"margin","y"),re=U.current.offsetHeight,ae=T.current.offsetHeight-re-K-le,Ee=de/ae;E.current.scrollTop=_.current+Ee*(Te-$e),R.preventDefault(),v(!0),d.start(Ct,()=>{v(!1)})}if(Z.current&&O.current&&G.current==="horizontal"){const K=Ne(O.current,"padding","x"),le=Ne(Z.current,"margin","x"),re=Z.current.offsetWidth,ae=O.current.offsetWidth-re-K-le,Ee=je/ae;E.current.scrollLeft=V.current+Ee*(N-W),R.preventDefault(),S(!0),f.start(Ct,()=>{S(!1)})}}}),ee=Ve(R=>{M.current=!1,U.current&&G.current==="vertical"&&U.current.releasePointerCapture(R.pointerId),Z.current&&G.current==="horizontal"&&Z.current.releasePointerCapture(R.pointerId)});function q(R){L(R.pointerType==="touch")}function ie(R){if(q(R),R.pointerType!=="touch"){const de=Qs(j.current,R.target);x(de)}}const oe=s.useMemo(()=>({scrolling:g||b,hasOverflowX:!H.x,hasOverflowY:!H.y,overflowXStart:P.xStart,overflowXEnd:P.xEnd,overflowYStart:P.yStart,overflowYEnd:P.yEnd,cornerHidden:H.corner}),[g,b,H.x,H.y,H.corner,P]),ce={role:"presentation",onPointerEnter:ie,onPointerMove:ie,onPointerDown:q,onPointerLeave(){x(!1)},style:{position:"relative",[Ot.scrollAreaCornerHeight]:`${F.height}px`,[Ot.scrollAreaCornerWidth]:`${F.width}px`}},ge=Je("div",t,{state:oe,ref:[r,j],props:[ce,l],stateAttributesMapping:pn}),he=s.useMemo(()=>({handlePointerDown:se,handlePointerMove:pe,handlePointerUp:ee,handleScroll:Y,cornerSize:F,setCornerSize:I,thumbSize:Q,setThumbSize:X,touchModality:$,cornerRef:C,scrollingX:g,setScrollingX:S,scrollingY:b,setScrollingY:v,hovering:h,setHovering:x,viewportRef:E,rootRef:j,scrollbarYRef:T,scrollbarXRef:O,thumbYRef:U,thumbXRef:Z,rootId:u,hiddenState:H,setHiddenState:k,overflowEdges:P,setOverflowEdges:ne,viewportState:oe,overflowEdgeThreshold:c}),[se,pe,ee,Y,F,Q,$,g,S,b,v,h,x,u,H,P,oe,c]);return n.jsxs(br.Provider,{value:he,children:[!p&&Sr.getElement(m),ge]})});function mi(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 pi=s.createContext(void 0);function ut(e,t=Number.MIN_SAFE_INTEGER,r=Number.MAX_SAFE_INTEGER){return Math.max(t,Math.min(e,r))}function hi(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 qe=(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 _n=1;function Pn(e,t){if(t<=0)return 0;const r=ut(e,0,t),o=r,a=t-r,i=o<=_n,l=a<=_n;return i&&l?o<=a?0:t:i?0:l?t:r}let Kn=!1;function gi(){Kn||Zs||(typeof CSS<"u"&&"registerProperty"in CSS&&[qe.scrollAreaOverflowXStart,qe.scrollAreaOverflowXEnd,qe.scrollAreaOverflowYStart,qe.scrollAreaOverflowYEnd].forEach(e=>{try{CSS.registerProperty({name:e,syntax:"<length>",inherits:!1,initialValue:"0px"})}catch{}}),Kn=!0)}const yi=s.forwardRef(function(t,r){const{render:o,className:a,...i}=t,{viewportRef:l,scrollbarYRef:c,scrollbarXRef:u,thumbYRef:d,thumbXRef:f,cornerRef:m,cornerSize:p,setCornerSize:h,setThumbSize:x,rootId:g,setHiddenState:S,hiddenState:b,handleScroll:v,setHovering:$,setOverflowEdges:L,overflowEdges:F,overflowEdgeThreshold:I,scrollingX:Q,scrollingY:X}=Kt(),P=dr(),ne=s.useRef(!0),H=At(),k=At(),j=Ve(()=>{const C=l.current,M=c.current,y=u.current,A=d.current,_=f.current,V=m.current;if(!C)return;const G=C.scrollHeight,B=C.scrollWidth,Y=C.clientHeight,se=C.clientWidth,pe=C.scrollTop,ee=C.scrollLeft;if(G===0||B===0)return;const q=Y>=G,ie=se>=B,oe=se/B,ce=Y/G,ge=Math.max(0,B-se),he=Math.max(0,G-Y);let R=0,de=0;if(!ie){let te=0;P==="rtl"?te=ut(-ee,0,ge):te=ut(ee,0,ge),R=Pn(te,ge),de=ge-R}const je=q?0:ut(pe,0,he),Te=q?0:Pn(je,he),$e=q?0:he-Te,N=ie?0:se,W=q?0:Y;let K=0,le=0;!ie&&!q&&(K=M?.offsetWidth||0,le=y?.offsetHeight||0);const re=p.width===0&&p.height===0,ae=re?K:0,Ee=re?le:0,st=Ne(y,"padding","x"),Re=Ne(M,"padding","y"),Pe=Ne(_,"margin","x"),Qe=Ne(A,"margin","y"),ht=N-st-Pe,gt=W-Re-Qe,St=y?Math.min(y.offsetWidth-ae,ht):ht,vt=M?Math.min(M.offsetHeight-Ee,gt):gt,yt=Math.max(On,St*oe),xt=Math.max(On,vt*ce);if(x(te=>te.height===xt&&te.width===yt?te:{width:yt,height:xt}),M&&A){const te=M.offsetHeight-xt-Re-Qe,Se=G-Y,Ue=Se===0?0:pe/Se,He=Math.min(te,Math.max(0,Ue*te));A.style.transform=`translate3d(0,${He}px,0)`}if(y&&_){const te=y.offsetWidth-yt-st-Pe,Se=B-se,Ue=Se===0?0:ee/Se,He=P==="rtl"?ut(Ue*te,-te,0):ut(Ue*te,0,te);_.style.transform=`translate3d(${He}px,0,0)`}const jt=[[qe.scrollAreaOverflowXStart,R],[qe.scrollAreaOverflowXEnd,de],[qe.scrollAreaOverflowYStart,Te],[qe.scrollAreaOverflowYEnd,$e]];for(const[te,Se]of jt)C.style.setProperty(te,`${Se}px`);V&&(ie||q?h({width:0,height:0}):!ie&&!q&&h({width:K,height:le})),S(te=>{const Se=q||ie;return te.y===q&&te.x===ie&&te.corner===Se?te:{y:q,x:ie,corner:Se}});const Fe={xStart:!ie&&R>I.xStart,xEnd:!ie&&de>I.xEnd,yStart:!q&&Te>I.yStart,yEnd:!q&&$e>I.yEnd};L(te=>te.xStart===Fe.xStart&&te.xEnd===Fe.xEnd&&te.yStart===Fe.yStart&&te.yEnd===Fe.yEnd?te:Fe)});Le(()=>{if(!l.current)return;gi();let C=!1;return hi(l.current,()=>{if(!C){C=!0;return}j()})},[j,l]),Le(()=>{queueMicrotask(j)},[j,b,P]),Le(()=>{l.current?.matches(":hover")&&$(!0)},[l,$]),s.useEffect(()=>{const C=l.current;if(typeof ResizeObserver>"u"||!C)return;let M=!1;const y=new ResizeObserver(()=>{if(!M){M=!0;return}j()});return y.observe(C),k.start(0,()=>{const A=C.getAnimations({subtree:!0});A.length!==0&&Promise.allSettled(A.map(_=>_.finished)).then(j).catch(()=>{})}),()=>{y.disconnect(),k.clear()}},[j,l,k]);function E(){ne.current=!1}const T={role:"presentation",...g&&{"data-id":`${g}-viewport`},...(!b.x||!b.y)&&{tabIndex:0},className:Sr.className,style:{overflow:"scroll"},onScroll(){l.current&&(j(),ne.current||v({x:l.current.scrollLeft,y:l.current.scrollTop}),H.start(100,()=>{ne.current=!0}))},onWheel:E,onTouchMove:E,onPointerMove:E,onPointerEnter:E,onKeyDown:E},O=s.useMemo(()=>({scrolling:Q||X,hasOverflowX:!b.x,hasOverflowY:!b.y,overflowXStart:F.xStart,overflowXEnd:F.xEnd,overflowYStart:F.yStart,overflowYEnd:F.yEnd,cornerHidden:b.corner}),[Q,X,b.x,b.y,b.corner,F]),U=Je("div",t,{ref:[r,l],state:O,props:[T,i],stateAttributesMapping:pn}),Z=s.useMemo(()=>({computeThumbPosition:j}),[j]);return n.jsx(pi.Provider,{value:Z,children:U})}),vr=s.createContext(void 0);function xi(){const e=s.useContext(vr);if(e===void 0)throw new Error(ln(54));return e}let Lt=(function(e){return e.scrollAreaThumbHeight="--scroll-area-thumb-height",e.scrollAreaThumbWidth="--scroll-area-thumb-width",e})({});const wi=s.forwardRef(function(t,r){const{render:o,className:a,orientation:i="vertical",keepMounted:l=!1,...c}=t,{hovering:u,scrollingX:d,scrollingY:f,hiddenState:m,overflowEdges:p,scrollbarYRef:h,scrollbarXRef:x,viewportRef:g,thumbYRef:S,thumbXRef:b,handlePointerDown:v,handlePointerUp:$,rootId:L,thumbSize:F}=Kt(),I={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},Q=dr();s.useEffect(()=>{const j=g.current,E=i==="vertical"?h.current:x.current;if(!E)return;function T(O){if(!(!j||!E||O.ctrlKey)){if(O.preventDefault(),i==="vertical"){if(j.scrollTop===0&&O.deltaY<0)return}else if(j.scrollLeft===0&&O.deltaX<0)return;if(i==="vertical"){if(j.scrollTop===j.scrollHeight-j.clientHeight&&O.deltaY>0)return}else if(j.scrollLeft===j.scrollWidth-j.clientWidth&&O.deltaX>0)return;i==="vertical"?j.scrollTop+=O.deltaY:j.scrollLeft+=O.deltaX}}return E.addEventListener("wheel",T,{passive:!1}),()=>{E.removeEventListener("wheel",T)}},[i,x,h,g]);const X={...L&&{"data-id":`${L}-scrollbar`},onPointerDown(j){if(j.button===0&&j.currentTarget===j.target&&g.current){if(S.current&&h.current&&i==="vertical"){const E=Ne(S.current,"margin","y"),T=Ne(h.current,"padding","y"),O=S.current.offsetHeight,U=h.current.getBoundingClientRect(),Z=j.clientY-U.top-O/2-T+E/2,C=g.current.scrollHeight,M=g.current.clientHeight,y=h.current.offsetHeight-O-T-E,_=Z/y*(C-M);g.current.scrollTop=_}if(b.current&&x.current&&i==="horizontal"){const E=Ne(b.current,"margin","x"),T=Ne(x.current,"padding","x"),O=b.current.offsetWidth,U=x.current.getBoundingClientRect(),Z=j.clientX-U.left-O/2-T+E/2,C=g.current.scrollWidth,M=g.current.clientWidth,y=x.current.offsetWidth-O-T-E,A=Z/y;let _;Q==="rtl"?(_=(1-A)*(C-M),g.current.scrollLeft<=0&&(_=-_)):_=A*(C-M),g.current.scrollLeft=_}v(j)}},onPointerUp:$,style:{position:"absolute",touchAction:"none",WebkitUserSelect:"none",userSelect:"none",...i==="vertical"&&{top:0,bottom:`var(${Ot.scrollAreaCornerHeight})`,insetInlineEnd:0,[Lt.scrollAreaThumbHeight]:`${F.height}px`},...i==="horizontal"&&{insetInlineStart:0,insetInlineEnd:`var(${Ot.scrollAreaCornerWidth})`,bottom:0,[Lt.scrollAreaThumbWidth]:`${F.width}px`}}},P=Je("div",t,{ref:[r,i==="vertical"?h:x],state:I,props:[X,c],stateAttributesMapping:pn}),ne=s.useMemo(()=>({orientation:i}),[i]),H=i==="vertical"?m.y:m.x;return l||!H?n.jsx(vr.Provider,{value:ne,children:P}):null}),bi=s.forwardRef(function(t,r){const{render:o,className:a,...i}=t,{thumbYRef:l,thumbXRef:c,handlePointerDown:u,handlePointerMove:d,handlePointerUp:f,setScrollingX:m,setScrollingY:p}=Kt(),{orientation:h}=xi();return Je("div",t,{ref:[r,h==="vertical"?l:c],state:{orientation:h},props:[{onPointerDown:u,onPointerMove:d,onPointerUp(S){h==="vertical"&&p(!1),h==="horizontal"&&m(!1),f(S)},style:{...h==="vertical"&&{height:`var(${Lt.scrollAreaThumbHeight})`},...h==="horizontal"&&{width:`var(${Lt.scrollAreaThumbWidth})`}}},i]})}),Si=s.forwardRef(function(t,r){const{render:o,className:a,...i}=t,{cornerRef:l,cornerSize:c,hiddenState:u}=Kt(),d=Je("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 jr({className:e,...t}){return n.jsx(fi,{className:D("group/scroll-area relative outline-none focus-visible:outline-none",e),...t})}function Er({className:e,...t}){return n.jsx(yi,{className:D("h-full w-full outline-none focus-visible:outline-none",e),...t})}function Cr({className:e,...t}){return n.jsx(wi,{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 kr({className:e,...t}){return n.jsx(bi,{className:D("flex-1 rounded-full bg-primary-500 outline-none focus-visible:outline-none",e),...t})}function vi({className:e,...t}){return n.jsx(Si,{className:D("bg-primary-100 outline-none focus-visible:outline-none",e),...t})}function ji(e){return e==="subagent"?ls:e==="cron"?cs:us}function Ei(e){if(!e||!Array.isArray(e.content))return"";const t=e.content.map(o=>o.type==="text"?String(o.text??""):"").join(" ");return pr(t).replace(/\s+/g," ").trim()}function Ci(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 ki(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=Ci(r);if(o)return o}return null}function Ni(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 Ti(e){const t=String(e??"").toLowerCase().trim();return t?t==="error"||t==="failed"?"error":t==="completed"||t==="ended"||t==="done"?"success":null:null}function Ri({session:e,active:t,isGenerating:r=!1,isPinned:o,selectionMode:a=!1,selected:i=!1,onToggleSelect:l,onSelect:c,onTogglePin:u,onRename:d,onDelete:f,onExport:m}){const p=e.label||e.title||e.derivedTitle||e.friendlyId,h=ji(e.kind),x=e.kind==="subagent"&&(e.lastMessage?.role==="assistant"||e.lastMessage?.role==="toolResult")?Ei(e.lastMessage):"",g=x.length>50?`${x.slice(0,50).trimEnd()}…`:x,S=e.kind==="subagent"?Ti(e.status):null,b=e.kind==="cron"?ki(e.lastMessage):null;return n.jsxs(Be,{to:"/chat/$sessionKey",params:{sessionKey:e.friendlyId},onClick:v=>{if(a){v.preventDefault(),v.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(J,{icon:h,size:12,strokeWidth:1.75,className:"text-primary-500/70 shrink-0"}),n.jsxs("div",{className:"min-w-0 truncate text-sm font-[450]",title:p,children:[o?n.jsx("span",{className:"mr-1 text-xs text-primary-700","aria-hidden":"true",children:"📌"}):null,p]}),e.kind==="subagent"?r?n.jsx("span",{"aria-label":"Session active",className:"size-1.5 rounded-full bg-green-500 shrink-0"}):S==="success"?n.jsx(J,{icon:er,size:12,strokeWidth:1.8,className:"text-green-600/80 shrink-0"}):S==="error"?n.jsx(J,{icon:Pt,size:12,strokeWidth:1.8,className:"text-red-600/80 shrink-0"}):null:null]}),g?n.jsx("div",{className:"text-[11px] text-primary-600/80 line-clamp-1 mt-0.5 pl-[18px]",children:g}):null,e.kind==="cron"&&b?n.jsx("div",{className:"text-[10px] text-primary-500/75 line-clamp-1 mt-0.5 pl-[18px] font-mono",children:Ni(b)}):null]})]}),a?null:n.jsxs(cn,{children:[n.jsx(un,{type:"button",onClick:v=>{v.preventDefault(),v.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(J,{icon:os,size:20,strokeWidth:1.5})}),n.jsxs(dn,{side:"bottom",align:"end",children:[n.jsxs(nt,{onClick:v=>{v.preventDefault(),v.stopPropagation(),u(e)},className:"gap-2",children:[n.jsx("span",{className:"text-xs","aria-hidden":"true",children:"📌"})," ",o?"Unpin Session":"Pin Session"]}),n.jsxs(nt,{onClick:v=>{v.preventDefault(),v.stopPropagation(),d(e)},className:"gap-2",children:[n.jsx(J,{icon:is,size:20,strokeWidth:1.5})," ","Rename"]}),n.jsxs(nt,{onClick:v=>{v.preventDefault(),v.stopPropagation(),m(e)},className:"gap-2",children:[n.jsx(J,{icon:as,size:20,strokeWidth:1.5})," ","Export"]}),Qt(e.key)?null:n.jsxs(nt,{onClick:v=>{v.preventDefault(),v.stopPropagation(),f(e)},className:"text-red-700 gap-2 hover:bg-red-50/80 data-highlighted:bg-red-50/80",children:[n.jsx(J,{icon:tr,size:20,strokeWidth:1.5})," ","Delete"]})]})]})]})}function Ii(e,t){return e.active!==t.active||e.isGenerating!==t.isGenerating||e.isPinned!==t.isPinned||e.selectionMode!==t.selectionMode||e.selected!==t.selected||e.onToggleSelect!==t.onToggleSelect||e.onSelect!==t.onSelect||e.onTogglePin!==t.onTogglePin||e.onRename!==t.onRename||e.onDelete!==t.onDelete||e.onExport!==t.onExport?!1:e.session===t.session?!0:e.session.key===t.session.key&&e.session.friendlyId===t.session.friendlyId&&e.session.label===t.session.label&&e.session.title===t.session.title&&e.session.derivedTitle===t.session.derivedTitle&&e.session.updatedAt===t.session.updatedAt&&e.session.kind===t.session.kind&&e.session.status===t.session.status&&e.session.lastMessage===t.session.lastMessage}const Wt=s.memo(Ri,Ii),Nr="opencami-pinned-sessions",Tr="opencami-sidebar-folders",Xe={webchat:!1,subagent:!1,cron:!1,other:!1};async function Mi(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 ze(r))}async function Ai(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 Di(){if(typeof window>"u")return[];try{const e=localStorage.getItem(Nr);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}catch{return[]}}function Oi(e){if(!(typeof window>"u"))try{const t=Array.from(new Set(e));localStorage.setItem(Nr,JSON.stringify(t))}catch{}}function Li(){if(typeof window>"u")return{...Xe};try{const e=localStorage.getItem(Tr);if(!e)return{...Xe};const t=JSON.parse(e);return!t||typeof t!="object"?{...Xe}:{webchat:typeof t.webchat=="boolean"?t.webchat:Xe.webchat,subagent:typeof t.subagent=="boolean"?t.subagent:Xe.subagent,cron:typeof t.cron=="boolean"?t.cron:Xe.cron,other:typeof t.other=="boolean"?t.other:Xe.other}}catch{return{...Xe}}}function _i(e){if(!(typeof window>"u"))try{localStorage.setItem(Tr,JSON.stringify(e))}catch{}}function Rt(e,t,r){return r&&e.key?e.key===r:e.friendlyId===t}function Pi(e){if(!e)return!1;const t=e.toLowerCase();return t.includes("running")||t.includes("active")||t.includes("stream")||t.includes("generat")}function Xt(e,t,r,o){return Rt(e,t,r)&&o?!0:Pi(e.status)}const Ki=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=pt(),[p,h]=s.useState(()=>Di()),[x,g]=s.useState(()=>Li()),[S,b]=s.useState(!1),[v,$]=s.useState(()=>new Set),L=s.useMemo(()=>new Set(p),[p]),F=f.filter(C=>L.has(C.key)),I=f.filter(C=>!L.has(C.key)),Q=F.length>0&&I.length>0,X=s.useMemo(()=>{const C={chat:[],webchat:[],subagent:[],cron:[],other:[]};for(const M of I){const y=M.kind??"other";C[y].push(M)}return C},[I]),P=s.useMemo(()=>f.filter(C=>v.has(C.key)),[v,f]),ne=P.length,H=s.useCallback(()=>{b(C=>(C&&$(new Set),!C))},[]),k=s.useCallback(C=>{Qt(C.key)||$(M=>{const y=new Set(M);return y.has(C.key)?y.delete(C.key):y.add(C.key),y})},[]),j=s.useCallback(()=>{$(new Set(f.filter(C=>!Qt(C.key)).map(C=>C.key)))},[f]),E=s.useCallback(()=>{b(!1),$(new Set)},[]),T=s.useCallback(async()=>{if(P.length===0||!window.confirm(`Delete ${P.length} sessions? This will archive them.`))return;const M=[];await Ai(P,10,async y=>{try{await Mi(y.key)}catch(A){throw M.push(y.label||y.title||y.derivedTitle||y.friendlyId),A}}),M.length>0&&(console.error("[sidebar] Bulk delete failed for some sessions",M),window.alert(`Could not delete ${M.length} session${M.length!==1?"s":""}:
|
|
8
|
+
|
|
9
|
+
${M.join(`
|
|
10
|
+
`)}`)),b(!1),$(new Set),m.invalidateQueries({queryKey:me.sessions})},[m,P]),O=s.useCallback(C=>{h(M=>{const A=M.includes(C.key)?M.filter(_=>_!==C.key):[...M,C.key];return Oi(A),A})},[]),U=s.useCallback((C,M)=>{g(y=>{const A={...y,[C]:M};return _i(A),A})},[]);function Z(C,M,y){return y.length===0?null:n.jsxs(en,{className:"flex flex-col",open:x[C],onOpenChange:A=>U(C,A),children:[n.jsxs(tn,{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:M}),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:y.length})]}),n.jsx(nn,{contentClassName:"flex flex-col gap-px",children:y.map(A=>n.jsx(Wt,{session:A,active:Rt(A,r,o),isGenerating:Xt(A,r,o,a),isPinned:!1,selectionMode:S,selected:v.has(A.key),onToggleSelect:k,onSelect:l,onTogglePin:O,onRename:c,onDelete:u,onExport:d},A.key))})]})}return n.jsxs(en,{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(tn,{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(J,{icon:ds,className:"size-3 transition-transform duration-150 group-data-panel-open:rotate-90"})})]}),n.jsx("button",{type:"button",onClick:H,className:D("text-[11px] font-medium px-1.5 py-0.5 rounded-md transition-colors",S?"text-primary-900 bg-primary-200":"text-primary-500 hover:text-primary-700 hover:bg-primary-100"),children:S?"Done":"Select"})]}),n.jsx(nn,{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(jr,{className:"flex-1 min-h-0",children:[n.jsx(Er,{className:"min-h-0",children:n.jsxs("div",{className:"flex flex-col gap-2 pl-2 pr-2",children:[F.length>0?n.jsx("div",{className:"flex flex-col gap-px",children:F.map(C=>n.jsx(Wt,{session:C,active:Rt(C,r,o),isGenerating:Xt(C,r,o,a),isPinned:!0,selectionMode:S,selected:v.has(C.key),onToggleSelect:k,onSelect:l,onTogglePin:O,onRename:c,onDelete:u,onExport:d},C.key))}):null,Q?n.jsx("div",{className:"my-1 border-t border-primary-200/80"}):null,X.chat.length>0?n.jsxs("div",{className:"flex flex-col gap-px",children:[n.jsx("div",{className: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:X.chat.map(C=>n.jsx(Wt,{session:C,active:Rt(C,r,o),isGenerating:Xt(C,r,o,a),isPinned:!1,selectionMode:S,selected:v.has(C.key),onToggleSelect:k,onSelect:l,onTogglePin:O,onRename:c,onDelete:u,onExport:d},C.key))})]}):null,Z("webchat","🦎 OpenCami",X.webchat),Z("subagent","🤖 Sub-agents",X.subagent),Z("cron","⏰ Cron / Isolated",X.cron),Z("other","📁 Other",X.other)]})}),n.jsx(Cr,{orientation:"vertical",children:n.jsx(kr,{})})]})}),S?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:[ne," selected"]}),n.jsx("button",{type:"button",onClick:j,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:T,disabled:ne===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",ne>0?"bg-red-100 text-red-700 hover:bg-red-200":"bg-primary-100 text-primary-400 cursor-not-allowed"),children:[n.jsx(J,{icon:tr,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]})},zi);function zi(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 Ui=s.lazy(()=>rt(()=>import("./settings-dialog-SDzqDXsx.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}))),$i=s.lazy(()=>rt(()=>import("./session-export-dialog-Bc9YEPLs.js"),__vite__mapDeps([25,1,4,3,5,6,7,8,9,2])).then(e=>({default:e.SessionExportDialog})));function Fi({sessions:e,activeFriendlyId:t,activeSessionKey:r,isStreaming:o=!1,creatingSession:a,onCreateSession:i,isCollapsed:l,onToggleCollapse:c,onSelectSession:u,onActiveSessionDelete:d,onOpenSearch:f}){const{settingsOpen:m,setSettingsOpen:p,pathsLoading:h,pathsError:x,paths:g,handleOpenSettings:S,closeSettings:b,copySessionsDir:v,copyStorePath:$}=Co(),{deleteSession:L}=Oo(),{renameSession:F}=Lo(),I={duration:.15,ease:l?"easeIn":"easeOut"},[Q,X]=s.useState(!1),[P,ne]=s.useState(null),[H,k]=s.useState(""),[j,E]=s.useState(!1),[T,O]=s.useState(null),[U,Z]=s.useState(null),[C,M]=s.useState(""),[y,A]=s.useState(!1),[_,V]=s.useState(null),[G,B]=s.useState(null),[Y,se]=s.useState(""),pe=pt();function ee(R){ne(R.key),k(R.label||R.title||R.derivedTitle||""),X(!0)}function q(R){P&&F(P,R),X(!1),ne(null)}function ie(R){O(R.key),Z(R.friendlyId),M(R.label||R.title||R.derivedTitle||R.friendlyId),E(!0)}function oe(){if(T&&U){const R=U===t;R&&d&&d(),L(T,U,R)}E(!1),O(null),Z(null)}function ce(R){V(R.key),B(R.friendlyId),se(R.label||R.title||R.derivedTitle||R.friendlyId),A(!0)}function ge(R){if(_&&G){const de=me.history(G,_),je=pe.getQueryData(de);je?.messages&&zo(Y,je.messages,R)}A(!1),V(null),B(null)}const he={className:"border-r border-primary-200 h-full overflow-hidden bg-primary-100 flex flex-col"};return n.jsxs(be.aside,{initial:!1,animate:{width:l?48:"var(--opencami-sidebar-width)"},transition:I,className:he.className,children:[n.jsxs(be.div,{layout:!0,transition:{layout:I},className:D("flex items-center h-12 px-2 justify-between"),children:[n.jsx(Ie,{initial:!1,children:l?null:n.jsx(be.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:I,children:n.jsxs(Be,{to:"/new",className:D(et({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),children:[n.jsx(to,{className:"size-5"}),n.jsx(no,{})]})})}),n.jsx(Me,{children:n.jsxs(Ae,{children:[n.jsx(De,{onClick:c,render:n.jsx(we,{size:"icon-sm",variant:"ghost",children:n.jsx(J,{icon:fs,size:20,strokeWidth:1.5})})}),n.jsx(Oe,{side:"right",children:l?"Open Sidebar":"Close Sidebar"})]})})]}),n.jsxs("div",{className:"px-2 mb-4 flex flex-col gap-1",children:[n.jsxs(be.div,{layout:!0,transition:{layout:I},className:"w-full space-y-2",children:[n.jsxs(we,{disabled:a,variant:"ghost",size:"sm",onClick:i,onMouseUp:u,className:"w-full pl-1.5 justify-start",children:[n.jsx(J,{icon:ms,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Ie,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:I,className:"overflow-hidden whitespace-nowrap",children:"New Session"})})]}),(()=>{try{const R=localStorage.getItem("opencami-file-explorer");return R===null?!0:R==="true"}catch{return!0}})()&&n.jsx(Me,{children:n.jsxs(Ae,{children:[n.jsx(De,{asChild:!0,children:n.jsxs(Be,{to:"/files",className:D(et({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(J,{icon:ps,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Ie,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:I,className:"overflow-hidden whitespace-nowrap",children:"Files"})})]})}),l&&n.jsx(Oe,{side:"right",children:"Files"})]})}),(()=>{try{const R=localStorage.getItem("opencami-memory-viewer");return R===null?!0:R==="true"}catch{return!0}})()&&n.jsx(Me,{children:n.jsxs(Ae,{children:[n.jsx(De,{asChild:!0,children:n.jsxs(Be,{to:"/memory",className:D(et({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(J,{icon:Vt,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Ie,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:I,className:"overflow-hidden whitespace-nowrap",children:"Memory"})})]})}),l&&n.jsx(Oe,{side:"right",children:"Memory"})]})}),(()=>{try{return localStorage.getItem("opencami-skills-browser")==="true"}catch{return!1}})()&&n.jsx(Me,{children:n.jsxs(Ae,{children:[n.jsx(De,{asChild:!0,children:n.jsxs(Be,{to:"/skills",className:D(et({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(J,{icon:hs,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Ie,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:I,className:"overflow-hidden whitespace-nowrap",children:"Skills"})})]})}),l&&n.jsx(Oe,{side:"right",children:"Skills"})]})}),(()=>{try{return localStorage.getItem("opencami-agent-manager")==="true"}catch{return!1}})()&&n.jsx(Me,{children:n.jsxs(Ae,{children:[n.jsx(De,{asChild:!0,children:n.jsxs(Be,{to:"/agents",className:D(et({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(J,{icon:Vt,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Ie,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:I,className:"overflow-hidden whitespace-nowrap",children:"Agents"})})]})}),l&&n.jsx(Oe,{side:"right",children:"Agents"})]})}),(()=>{try{return localStorage.getItem("opencami-cron-manager")==="true"}catch{return!1}})()&&n.jsx(Me,{children:n.jsxs(Ae,{children:[n.jsx(De,{asChild:!0,children:n.jsxs(Be,{to:"/bots",className:D(et({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(J,{icon:gs,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Ie,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:I,className:"overflow-hidden whitespace-nowrap",children:"Cron Jobs"})})]})}),l&&n.jsx(Oe,{side:"right",children:"Cron Jobs"})]})}),(()=>{try{return localStorage.getItem("feature_dashboard")==="true"}catch{return!1}})()&&n.jsx(Me,{children:n.jsxs(Ae,{children:[n.jsx(De,{asChild:!0,children:n.jsxs(Be,{to:"/dashboard",className:D(et({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(J,{icon:ys,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Ie,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:I,className:"overflow-hidden whitespace-nowrap",children:"Dashboard"})})]})}),l&&n.jsx(Oe,{side:"right",children:"Dashboard"})]})})]}),n.jsx(be.div,{layout:!0,transition:{layout:I},className:"w-full",children:n.jsxs(we,{variant:"ghost",size:"sm",onClick:f,className:"w-full pl-1.5 justify-start",children:[n.jsx(J,{icon:xs,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Ie,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:I,className:"overflow-hidden whitespace-nowrap",children:"Search"})})]})})]}),n.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:n.jsx(Ie,{initial:!1,children:!l&&n.jsx(be.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:I,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(Ki,{sessions:e,activeFriendlyId:t,activeSessionKey:r,isStreaming:o,onSelect:u,onRename:ee,onDelete:ie,onExport:ce})})},"content")})}),n.jsx("div",{className:"px-2 py-3 border-t border-primary-200 bg-primary-100",children:n.jsx(be.div,{layout:!0,transition:{layout:I},className:"w-full",children:n.jsxs(we,{variant:"ghost",size:"sm",onClick:S,title:l?"Settings":void 0,className:"w-full justify-start pl-1.5",children:[n.jsx(J,{icon:ws,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Ie,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:I,className:"overflow-hidden whitespace-nowrap",children:"Settings"})})]})})}),m&&n.jsx(s.Suspense,{fallback:null,children:n.jsx(Ui,{open:m,onOpenChange:p,pathsLoading:h,pathsError:x,paths:g,onClose:b,onCopySessionsDir:v,onCopyStorePath:$})}),n.jsx(Vo,{open:Q,onOpenChange:X,sessionTitle:H,onSave:q,onCancel:()=>X(!1)}),n.jsx(Go,{open:j,onOpenChange:E,sessionTitle:C,onConfirm:oe,onCancel:()=>E(!1)}),y&&n.jsx(s.Suspense,{fallback:null,children:n.jsx($i,{open:y,onOpenChange:A,sessionTitle:Y,onExport:ge,onCancel:()=>A(!1)})})]})}function Hi(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 Wi(e,t){return!(e.activeFriendlyId!==t.activeFriendlyId||e.activeSessionKey!==t.activeSessionKey||e.isStreaming!==t.isStreaming||e.creatingSession!==t.creatingSession||e.isCollapsed!==t.isCollapsed||!Hi(e.sessions,t.sessions))}const Xi=s.memo(Fi,Wi);function zn(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 Un(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 Bi({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:Un(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:zn(m),maxStr:zn(t),colors:Un(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 Yi=s.memo(Bi);function Gi({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 pr-4 h-12 flex shrink-0 min-w-0 items-center bg-surface tauri-drag-header",children:[r?n.jsx(we,{size:"icon-sm",variant:"ghost",onClick:o,className:"mr-2 text-primary-800 hover:bg-primary-100",style:{WebkitAppRegion:"no-drag"},"aria-label":"Open sidebar",children:n.jsx(J,{icon:bs,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(Yi,{totalTokens:a,contextTokens:i,className:"ml-3 hidden sm:flex"})]})}const Vi=s.memo(Gi);function qi(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function Ji(e){const t=new Date(e);return qi(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 Qi(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 Zi({timestamp:e}){const t=Ji(e),r=Qi(e);return n.jsx(Me,{children:n.jsxs(Ae,{children:[n.jsx(De,{className:"inline-flex items-center text-xs text-primary-600",children:t}),n.jsx(Oe,{side:"top",children:r})]})})}function ea({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 b=localStorage.getItem("opencami-tts-enabled");return b===null?!0:b==="true"}catch{return!0}});s.useEffect(()=>{function b(v){v.key==="opencami-tts-enabled"&&p(v.newValue===null?!0:v.newValue==="true")}return window.addEventListener("storage",b),()=>window.removeEventListener("storage",b)},[]),s.useEffect(()=>()=>{f.current?.abort(),u.current&&(u.current.pause(),u.current=null),d.current&&(URL.revokeObjectURL(d.current),d.current=null)},[]);const h=async()=>{try{await navigator.clipboard.writeText(e),i(!0),window.setTimeout(()=>i(!1),1400)}catch{i(!1)}},x=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 b=new AbortController;f.current=b,c("loading");try{const v=await fetch("/api/tts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:e}),signal:b.signal});if(!v.ok)throw new Error("TTS failed");const $=await v.blob(),L=URL.createObjectURL($);d.current=L;const F=new Audio(L);u.current=F,F.onended=()=>{c("idle"),d.current&&(URL.revokeObjectURL(d.current),d.current=null),u.current=null},F.onerror=()=>{c("idle"),d.current&&(URL.revokeObjectURL(d.current),d.current=null),u.current=null},await F.play(),c("playing")}catch(v){if(v instanceof Error&&v.name==="AbortError"){c("idle");return}c("idle"),d.current&&(URL.revokeObjectURL(d.current),d.current=null),u.current=null}},g=t==="end"?"justify-end":"justify-start",S=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",g),children:[n.jsx(Me,{children:n.jsxs(Ae,{children:[n.jsx(De,{type:"button",onClick:()=>{h().catch(()=>{})},className:"inline-flex items-center justify-center rounded border border-transparent bg-transparent p-1 text-primary-700 hover:text-primary-900 hover:bg-primary-100",children:n.jsx(J,{icon:a?nr:Ss,size:16,strokeWidth:1.6})}),n.jsx(Oe,{side:"top",children:"Copy"})]})}),S&&n.jsx(Me,{children:n.jsxs(Ae,{children:[n.jsx(De,{type:"button",onClick:()=>{x().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(J,{icon:l==="loading"?vs:l==="playing"?rr:js,size:16,strokeWidth:1.6,className:D(l==="loading"&&"animate-spin")})}),n.jsx(Oe,{side:"top",children:l==="loading"?"Generating speech…":l==="playing"?"Stop":"Listen"})]})}),n.jsx(Zi,{timestamp:r})]})}function Rr({children:e,className:t,...r}){return n.jsx("div",{className:D("flex gap-3 w-full",t),...r,children:e})}function ta({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(ro,{className:a,...o,children:e}):n.jsx("div",{className:a,...o,children:e})}function na({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()}
|
|
11
|
+
…[truncated]`},c=r==="output-error"?Pt:r==="output-available"?er:Es,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(en,{defaultOpen:t,children:[n.jsxs(tn,{render:n.jsx(we,{variant:"ghost",className:"h-auto w-full justify-start gap-1.5 rounded-md px-1.5 py-1"}),children:[n.jsx(J,{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(J,{icon:sr,size:14,strokeWidth:1.5,className:"ml-auto text-primary-700/80 transition-transform duration-150 group-data-panel-open:rotate-180"})]}),n.jsx(nn,{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 ra=s.lazy(()=>rt(()=>import("./thinking-DUdE6Iej.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}))),sa=s.lazy(()=>rt(()=>import("./search-sources-badge-D0YArqfp.js"),__vite__mapDeps([27,1,3])).then(e=>({default:e.SearchSourcesBadge})));function oa(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 $n(e){return Ge(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 ia(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 Fn(e,t){if(!t)return"";const r=Ge(e);return r.length===0?"":r.map(o=>o.id?ia(t.get(o.id)):"missing").join("||")}function aa(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 Hn(e){const t=[e.createdAt,e.created_at,e.timestamp,e.time,e.ts];for(const r of t){const o=aa(r);if(o)return o}return null}function rn(e){const r=(Array.isArray(e.content)?e.content:[]).find(o=>o.type==="thinking");return r&&"thinking"in r?String(r.thinking??""):null}function la(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 dt=/^📎 Uploaded file:\s*(\/uploads\/\S+)\s*$/;function ca(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 ua(e){if(!e)return[];const t=e.trimStart();if(t.startsWith(">")||t.startsWith("```"))return[];const r=e.split(`
|
|
12
|
+
`),o=[];for(const i of r){if(dt.test(i)){o.push(i);continue}if(o.length>0&&i.trim()===""){o.push(i);continue}break}const a=r[0]??"";return dt.test(a)?o.filter(i=>dt.test(i)):[]}function da(e){const t=[],r=new Set;for(const o of ua(e)){const i=o.match(dt)?.[1];!i||r.has(i)||(r.add(i),t.push({path:i,filename:i.split("/").pop()||i}))}return t}function fa(e){const t=e.split(`
|
|
13
|
+
`);if(!dt.test(t[0]??""))return e.trim();let r=0;for(;r<t.length&&dt.test(t[r]);)r++;for(;r<t.length&&t[r].trim()==="";)r++;return t.slice(r).join(`
|
|
14
|
+
`).replace(/\n{3,}/g,`
|
|
15
|
+
|
|
16
|
+
`).trim()}function ma({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}=so(),p=e.role||"assistant",h=_e(e),x=rn(e),g=la(e),S=p==="user",b=s.useMemo(()=>g.map(j=>`data:${j.source.media_type};base64,${j.source.data}`),[g]),v=Jt(e),$=_t(),L=Fs(j=>j.openInEditor),F=s.useMemo(()=>da(h),[h]),[I,Q]=s.useState({}),X=s.useMemo(()=>fa(h),[h]);s.useEffect(()=>{let j=!1;async function E(){const T={};await Promise.all(F.map(async O=>{try{const U=await fetch(`/api/files/info?path=${encodeURIComponent(O.path)}`);if(!U.ok){T[O.path]=null;return}const Z=await U.json();T[O.path]=typeof Z.size=="number"?Z.size:null}catch{T[O.path]=null}})),j||Q(T)}return F.length>0?E():Q({}),()=>{j=!0}},[F]);const P=async j=>{L(j),await $({to:"/files"})},ne=p==="assistant"?Ge(e):[],H=ne.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",S?"items-end":"items-start"),children:[x&&m.showReasoningBlocks&&n.jsx("div",{className:"w-full max-w-[var(--opencami-chat-width)]",children:n.jsx(s.Suspense,{fallback:null,children:n.jsx(ra,{content:x})})}),g.length>0&&n.jsx("div",{className:D("flex flex-wrap gap-2 mb-2",S?"justify-end":"justify-start"),children:g.map((j,E)=>n.jsx("img",{src:b[E],alt:`Attachment ${E+1}`,loading:"lazy",decoding:"async",fetchPriority:"low",className:"max-w-[300px] max-h-[300px] rounded-lg object-cover"},E))}),F.length>0&&n.jsx("div",{className:D("mb-2 flex w-full flex-col gap-2",S?"items-end":"items-start"),children:F.map(j=>n.jsxs("button",{type:"button",onClick:()=>{P(j.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(J,{icon:or,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:j.filename}),n.jsx("p",{className:"text-xs text-primary-600",children:ca(I[j.path]??null)})]})]},j.path))}),n.jsx(Rr,{className:D("min-w-0 max-w-full",S?"flex-row-reverse":""),children:n.jsx(ta,{markdown:!S,isStreaming:!S&&o,className:D("text-primary-900 opencami-text-size min-w-0 max-w-full",S?"opencami-message-user bg-primary-100 px-4 py-[var(--opencami-user-bubble-py)] max-w-[85%]":"opencami-message-assistant bg-transparent w-full",!S&&o&&"stream-fade-in"),children:X})}),H&&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:ne.map(j=>{const E=j.id?t?.get(j.id):void 0,T=oa(j,E);return n.jsx(na,{toolPart:T,defaultOpen:!1},j.id||j.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(sa,{sources:k})})}),!H&&n.jsx(ea,{text:h,timestamp:v,align:S?"end":"start",forceVisible:r})]})}function pa(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")||_e(e.message)!==_e(t.message)||rn(e.message)!==rn(t.message)||$n(e.message)!==$n(t.message)||Fn(e.message,e.toolResultsByCallId)!==Fn(t.message,t.toolResultsByCallId)||Hn(e.message)!==Hn(t.message))}const Bt=s.memo(ma,pa);function ha({className:e,variant:t="outline",scrollRef:r,...o}){const[a,i]=s.useState(!0),[l,c]=s.useState(!1),u=s.useRef(0),d=s.useCallback(()=>{const f=r.current;if(!f)return;const m=Math.abs(f.scrollHeight-f.scrollTop-f.clientHeight)<100;i(m)},[r]);return s.useLayoutEffect(()=>{const f=r.current;if(!f)return;const m=()=>{u.current=f.scrollTop,d()},p=new MutationObserver(()=>{f&&(f.scrollTop!==u.current&&(u.current=f.scrollTop),d())});return d(),f.addEventListener("scroll",m),p.observe(f,{childList:!0,subtree:!0}),()=>{f.removeEventListener("scroll",m),p.disconnect()}},[d,r]),s.useLayoutEffect(()=>{if(a){c(!1);return}const f=window.setTimeout(()=>{c(!0)},200);return()=>window.clearTimeout(f)},[a]),n.jsx(we,{variant:"secondary",size:"icon-sm",className: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(J,{icon:sr,size:18,strokeWidth:1.8})})}function ga({className:e,viewportRef:t,scrollRef:r,viewportProps:o}){return n.jsxs(jr,{className:D("relative flex flex-1 min-h-0 flex-col",e),children:[n.jsx(Er,{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(ha,{scrollRef:r})})}),n.jsx(Cr,{orientation:"vertical",children:n.jsx(kr,{})}),n.jsx(vi,{})]})}function ya(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 xa(e,t){return!(e.className!==t.className||e.viewportRef!==t.viewportRef||e.scrollRef!==t.scrollRef||!ya(e.viewportProps,t.viewportProps))}const wa=s.memo(ga,xa);function ba({viewportNode:e,children:t}){return e?Zr.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 Sa({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(wa,{className:t,viewportRef:c,scrollRef:a,viewportProps:o}),n.jsx(ba,{viewportNode:i,children:e})]})}const va=s.memo(Sa);function ja({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 Ea({...e}){return n.jsx("div",{className:"h-px w-full shrink-0 scroll-mt-4 pt-6","aria-hidden":"true",...e})}function Ca({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 ka({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(Ca,{className:"text-sm",duration:2,children:"Generating..."})]})}const Wn=s.lazy(()=>rt(()=>import("./follow-up-suggestions-Bq-xR5GV.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 Na({messages:e,loading:t,empty:r,emptyState:o,notice:a,noticePosition:i="start",waitingForResponse:l,isStreaming:c=!1,sessionKey:u,pinToTop:d,pinGroupMinHeight:f,headerHeight:m,contentStyle:p,onFollowUpClick:h,jumpToMessageId:x}){const g=s.useRef(null),S=s.useRef(null),b=s.useRef(!1),v=s.useRef(d),$=s.useRef(void 0),[L,F]=s.useState(null),I=s.useMemo(()=>e.filter(y=>y.role!=="toolResult"),[e]),Q=s.useDeferredValue(I),X=s.useMemo(()=>{const y=new Map;for(const A of e){if(A.role!=="toolResult")continue;const _=A.toolCallId;typeof _=="string"&&_.trim().length>0&&y.set(_,A)}return y},[e]),P=s.useDeferredValue(X),ne=s.useMemo(()=>{const y=[];for(const A of Q){if(A.role!=="assistant")continue;const _=Ge(A);for(const V of _){if(!V.id)continue;const G=V.name==="web_search",B=V.name==="web_fetch",Y=V.name==="exec";if(!G&&!B&&!Y)continue;const se=P.get(V.id),pe=se?.content?.map(ee=>ee.type==="text"?String(ee.text??""):"").join("").trim()??"";y.push([V.id,V.name??"",typeof V.arguments?.url=="string"?V.arguments.url:"",se?.isError?"1":"0",pe].join("::"))}}return y.join("||")},[Q,P]),H=s.useMemo(()=>{const y=G=>G?G.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,`
|
|
17
|
+
`).trim():"",A=(G,B,Y)=>{try{const se=JSON.parse(G),pe=Array.isArray(se)?se:se?.results??se?.web?.results??[];if(!Array.isArray(pe))return!1;let ee=!1;for(const q of pe)q?.url&&q?.title&&!Y.has(q.url)&&(Y.add(q.url),B.push({title:y(q.title),url:q.url,snippet:y(q.description||q.snippet||q.content||"")}),ee=!0);return ee}catch{return!1}},_=[],V=new Set;for(const G of Q){if(G.role!=="assistant")continue;const B=Ge(G);for(const Y of B){if(!Y.id)continue;const se=Y.name==="web_search",pe=Y.name==="web_fetch",ee=Y.name==="exec";if(!se&&!pe&&!ee)continue;const q=P.get(Y.id);if(!q)continue;const ie=q.content?.map(oe=>oe.type==="text"?String(oe.text??""):"").join("").trim();if(ie){if(se||ee){if(ee&&(!ie.includes('"results"')||!ie.includes('"url"')))continue;let oe=ie;const ce=ie.indexOf("{");ce>0&&(oe=ie.slice(ce));const ge=oe.lastIndexOf("}");ge>0&&(oe=oe.slice(0,ge+1)),A(oe,_,V)}else if(pe){const oe=Y.arguments?.url;if(oe&&!V.has(oe)){V.add(oe);let ce;try{ce=new URL(oe).hostname}catch{ce=oe}_.push({title:ce,url:oe})}}}}}return _},[ne,Q,P]),k=I.map((y,A)=>({message:y,index:A})).filter(({message:y})=>y.role!=="user").map(({index:y})=>y).pop(),j=I.map((y,A)=>({message:y,index:A})).filter(({message:y})=>y.role==="assistant").map(({index:y})=>y).pop(),E=I.map((y,A)=>({message:y,index:A})).filter(({message:y})=>y.role==="user").map(({index:y})=>y).pop(),T=l&&(typeof E!="number"||typeof k!="number"||k<E),O=typeof E=="number"?E:-1,U=d&&O>=0,Z=typeof j=="number"?I[j]:void 0,C=Z?_e(Z):"",M=!l&&!c&&C.length>0&&h!==void 0&&(typeof E!="number"||typeof j!="number"||j>E);return s.useLayoutEffect(()=>{if(!t){if(d){const y=!v.current||$.current!==E;v.current=!0,$.current=E,y&&S.current&&(b.current=!0,S.current.scrollIntoView({behavior:"auto",block:"start"}),window.setTimeout(()=>{b.current=!1},0));return}v.current=!1,$.current=E,g.current&&(b.current=!0,g.current.scrollIntoView({behavior:"auto",block:"end"}),window.setTimeout(()=>{b.current=!1},0))}},[t,I.length,u,d,E]),s.useEffect(()=>{if(!x||t)return;const y=document.getElementById(`message-${x}`);if(!y)return;y.scrollIntoView({behavior:"smooth",block:"center"}),F(x);const A=window.setTimeout(()=>{F(_=>_===x?null:_)},1800);return()=>window.clearTimeout(A)},[x,t,I]),n.jsx(va,{className:"flex-1 min-h-0 -mb-4",children:n.jsxs(ja,{className:"pt-6",style:p,children:[a&&i==="start"?a:null,r&&!a?o??n.jsx("div",{"aria-hidden":!0}):U?n.jsxs(n.Fragment,{children:[I.slice(0,O).map((y,A)=>{const _=typeof y.id=="string"?y.id:void 0,V=_||A,G=typeof k=="number"&&A===k,B=typeof k=="number"&&A===k,Y=y.role==="assistant"&&Ge(y).length>0;return n.jsx(Bt,{message:y,toolResultsByCallId:Y?X:void 0,forceActionsVisible:G,isStreaming:B&&c,isLastAssistant:B,aggregatedSearchSources:B?H:void 0,messageDomId:_?`message-${_}`:void 0,highlighted:L===_},V)}),n.jsxs("div",{className:"flex flex-col gap-[var(--opencami-msg-gap)]",style:{minHeight:`${Math.max(0,f)}px`},children:[I.slice(O).map((y,A)=>{const _=O+A,V=typeof y.id=="string"?y.id:void 0,G=V||_,B=typeof k=="number"&&_===k,Y=typeof k=="number"&&_===k,se=_===E?S:void 0,pe=_===E?"scroll-mt-0":void 0,ee=_===E?m:void 0,q=y.role==="assistant"&&Ge(y).length>0;return n.jsx(Bt,{message:y,toolResultsByCallId:q?X:void 0,forceActionsVisible:B,isStreaming:Y&&c,isLastAssistant:Y,aggregatedSearchSources:Y?H:void 0,wrapperRef:se,wrapperClassName:pe,wrapperScrollMarginTop:ee,messageDomId:V?`message-${V}`:void 0,highlighted:L===V},G)}),T?n.jsx("div",{className:"py-2",children:n.jsx(ka,{})}):null,M&&h?n.jsx(s.Suspense,{fallback:null,children:n.jsx(Wn,{responseText:C,onSuggestionClick:h,disabled:l})}):null]})]}):n.jsxs(n.Fragment,{children:[I.map((y,A)=>{const _=typeof y.id=="string"?y.id:void 0,V=_||A,G=typeof k=="number"&&A===k,B=typeof k=="number"&&A===k,Y=y.role==="assistant"&&Ge(y).length>0;return n.jsx(Bt,{message:y,toolResultsByCallId:Y?X:void 0,forceActionsVisible:G,isStreaming:B&&c,isLastAssistant:B,aggregatedSearchSources:B?H:void 0,messageDomId:_?`message-${_}`:void 0,highlighted:L===_},V)}),M&&h?n.jsx(s.Suspense,{fallback:null,children:n.jsx(Wn,{responseText:C,onSuggestionClick:h,disabled:l})}):null]}),a&&i==="end"?a:null,n.jsx(Ea,{ref:g})]})})}function Ta(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 Ra=s.memo(Na,Ta),sn=mr()(fr(e=>({level:"low",setLevel:t=>e({level:t})}),{name:"thinking-level"}));function Ia(){const e=sn(r=>r.level),t=sn(r=>r.setLevel);return{level:e,setLevel:t}}const Yt=[{value:"off",label:"Off",description:"No reasoning",shortLabel:"Off"},{value:"low",label:"Low",description:"Think",shortLabel:"Low"},{value:"medium",label:"Medium",description:"Think harder",shortLabel:"Medium"},{value:"high",label:"High",description:"Ultrathink",shortLabel:"High"}];function Ma({className:e}){const{level:t,setLevel:r}=Ia(),o=Yt.find(a=>a.value===t)??Yt[1];return n.jsxs(cn,{children:[n.jsxs(un,{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(J,{icon:Vt,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(dn,{side:"top",align:"start",className:"min-w-[190px]",children:Yt.map(a=>n.jsxs(nt,{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(J,{icon:nr,size:20,strokeWidth:1.5,className:"text-primary-600"})]},a.value))})]})}function Aa({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 Da=s.memo(Aa),Ir=s.createContext({isLoading:!1,value:"",setValue:()=>{},maxHeight:240,onSubmit:void 0,disabled:!1,textareaRef:es.createRef()});let ft=null,Xn=!1;function Oa(){Xn||typeof window>"u"||(Xn=!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||!ft||ft.disabled||ft.focus()}))}function Mr(){return s.useContext(Ir)}function La({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);Oa();function h(g){m(g),a?.(g)}function x(g){c||p.current?.focus(),u?.(g)}return n.jsx(Me,{children:n.jsx(Ir.Provider,{value:{isLoading:t,value:o??f,setValue:a??h,maxHeight:r,onSubmit:i,disabled:c,textareaRef:p},children:n.jsx("div",{onClick:x,className:D("bg-surface dark:bg-primary-200 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 _a({className:e,onKeyDown:t,disableAutosize:r=!1,inputRef:o,...a}){const{value:i,setValue:l,maxHeight:c,onSubmit:u,disabled:d,textareaRef:f}=Mr();function m(g){!g||r||(g.style.height="auto",typeof c=="number"?g.style.height=`${Math.min(g.scrollHeight,c)}px`:g.style.height=`min(${g.scrollHeight}px, ${c})`)}function p(g){f.current=g,typeof o=="function"?o(g):o&&"current"in o&&(o.current=g),g?ft=g:ft===g&&(ft=null),m(g)}s.useLayoutEffect(()=>{if(!f.current||r)return;const g=f.current;g.style.height="auto",typeof c=="number"?g.style.height=`${Math.min(g.scrollHeight,c)}px`:g.style.height=`min(${g.scrollHeight}px, ${c})`},[i,c,r]);function h(g){m(g.target),l(g.target.value)}function x(g){g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),u?.()),t?.(g)}return n.jsx("textarea",{ref:p,value:i,onChange:h,onKeyDown:x,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 Pa({children:e,className:t,...r}){return n.jsx("div",{className:D("flex items-center gap-2",t),...r,children:e})}function Bn({tooltip:e,children:t,className:r,side:o="top",...a}){const{disabled:i}=Mr();return n.jsxs(Ae,{...a,children:[n.jsx(De,{disabled:i,onClick:l=>l.stopPropagation(),children:t}),n.jsx(Oe,{side:o,className:r,children:e})]})}const Ar="opencami-personas-enabled",on="opencami-active-persona";function Ka(){if(typeof window>"u")return!0;try{const e=localStorage.getItem(Ar);return e===null?!0:e==="true"}catch{return!0}}function za(){if(typeof window>"u")return null;try{const e=localStorage.getItem(on);return e?JSON.parse(e):null}catch{return null}}function Yn(e){if(!(typeof window>"u"))try{e?localStorage.setItem(on,JSON.stringify(e)):localStorage.removeItem(on)}catch{}}const Ua={core:"Core",creative:"Creative",curator:"Curator",learning:"Learning",lifestyle:"Lifestyle",professional:"Professional"};function $a({className:e,onSelect:t}){const[r,o]=s.useState({}),[a,i]=s.useState(null),[l,c]=s.useState(!0),[u,d]=s.useState(!1),[f,m]=s.useState(Ka),p=s.useRef(null);s.useEffect(()=>{const S=b=>{b.key===Ar&&m(b.newValue===null?!0:b.newValue==="true")};return window.addEventListener("storage",S),()=>window.removeEventListener("storage",S)},[]),s.useEffect(()=>{let S=!0;async function b(){p.current?.abort();const v=new AbortController;p.current=v;try{c(!0);const $=await fetch("/api/personas",{signal:v.signal});if(!$.ok){d(!1);return}const L=await $.json();if(!S)return;L.ok&&L.available?(o(L.personas),d(!0),i(za())):d(!1)}catch($){if($ instanceof Error&&$.name==="AbortError"||!S)return;d(!1)}finally{S&&c(!1)}}return b(),()=>{S=!1,p.current?.abort()}},[]);const h=s.useCallback(S=>{i(S),Yn(S),t(`/persona ${S.id}`)},[t]),x=s.useCallback(()=>{i(null),Yn(null),t("/persona exit")},[t]);if(l||!u||!f)return null;const g=Object.entries(r);return g.length===0?null:n.jsxs(cn,{children:[n.jsxs(un,{className: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(dn,{side:"top",align:"start",className:"w-[300px] max-h-[360px] overflow-y-auto",children:[a&&n.jsxs(n.Fragment,{children:[n.jsxs(nt,{onClick:x,className:"text-red-600 hover:bg-red-50",children:[n.jsx("span",{className:"text-sm",children:"✕"}),n.jsx("span",{children:"Exit Persona"}),n.jsxs("span",{className:"ml-auto text-[10px] text-primary-400",children:[a.emoji," ",a.name]})]}),n.jsx("div",{className:"my-1 h-px bg-primary-200"})]}),g.map(([S,b])=>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:Ua[S]??S}),b.map(v=>n.jsxs(nt,{onClick:()=>h(v),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:v.emoji}),n.jsx("span",{className:"truncate",children:v.name})]}),n.jsx("span",{className:"text-[11px] text-primary-400 truncate ml-2 max-w-[140px]",children:v.description})]},v.id))]},S))]})]})}const Fa=[{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 Ha({className:e,onCommandSelect:t}){const[r,o]=s.useState(!1);function a(i){t?.(i),o(!1)}return n.jsxs(n.Fragment,{children:[n.jsx(we,{variant:"ghost",size:"sm",onClick:()=>o(!0),className:D("h-7 w-7 p-0",e),title:"Show commands (Ctrl+/)",children:n.jsx(J,{icon:En,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(J,{icon:En,size:18,className:"text-primary-600 dark:text-primary-400"}),n.jsx("h2",{className:"font-semibold text-primary-900 dark:text-white",children:"Slash Commands"})]}),n.jsx(we,{variant:"ghost",size:"sm",onClick:()=>o(!1),className:"h-7 w-7 p-0",children:n.jsx(J,{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"}),Fa.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 Wa=10*1024*1024,ct=1280,Xa=.75,Ba=300*1024,Ya=["image/png","image/jpeg","image/gif","image/webp"],Dr=["pdf","txt","md","csv","json","xml","yaml","yml","log","py","js","ts","html","css"],Ga=[".png",".jpg",".jpeg",".gif",".webp",...Dr.map(e=>`.${e}`)].join(",");function Va(){if(typeof document>"u")return!1;try{const e=document.createElement("canvas");return!!(e.getContext&&e.getContext("2d"))}catch{return!1}}async function qa(e){if(!Va())throw new Error("Image compression not available in this browser");return new Promise((t,r)=>{const o=new Image,a=URL.createObjectURL(e),i=()=>{URL.revokeObjectURL(a)};o.onload=()=>{try{let l=o.width,c=o.height;(l>ct||c>ct)&&(l>c?(c=Math.round(c*ct/l),l=ct):(l=Math.round(l*ct/c),c=ct));const u=document.createElement("canvas");u.width=l,u.height=c;const d=u.getContext("2d");if(!d){i(),r(new Error("Failed to get canvas context"));return}d.drawImage(o,0,0,l,c);const f=e.type==="image/png"?"image/png":"image/jpeg";let m=Xa,p=u.toDataURL(f,m);if(f==="image/jpeg"){const x=Ba*1.37;for(;p.length>x&&m>.3;)m-=.1,p=u.toDataURL(f,m)}const h=p.split(",")[1];if(!h){i(),r(new Error("Failed to encode image"));return}i(),t(h)}catch(l){i(),r(l instanceof Error?l:new Error("Image compression failed"))}},o.onerror=()=>{i(),r(new Error("Failed to load image"))},o.src=a})}function Or(e){return Ya.includes(e.type)}function Ja(e){const t=e.name.includes(".")?e.name.split(".").pop()?.toLowerCase():"";return!!(t&&Dr.includes(t))}async function Qa(e){const t=crypto.randomUUID();if(!Or(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>Wa)return{id:t,file:e,preview:null,type:"image",base64:null,error:"Image is too large. Maximum size is 10MB."};try{const r=await qa(e),o=URL.createObjectURL(e);return{id:t,file:e,preview:o,type:"image",base64:r}}catch(r){return{id:t,file:e,preview:null,type:"image",base64:null,error:r instanceof Error?r.message:"Failed to process image"}}}function Za({onFilesSelect:e,disabled:t=!1,className:r}){const o=s.useRef(null),a=s.useCallback(()=>{o.current?.click()},[]),i=s.useCallback(async l=>{const c=Array.from(l.target.files??[]);c.length!==0&&(l.target.value="",e(c))},[e]);return n.jsxs(n.Fragment,{children:[n.jsx("input",{ref:o,type:"file",accept:Ga,multiple:!0,onChange:i,className:"hidden","aria-hidden":"true"}),n.jsx(we,{variant:"ghost",size:"icon-sm",onClick:a,disabled:t,className:r,"aria-label":"Attach file",type:"button",children:n.jsx(J,{icon:Cs,size:18,strokeWidth:1.8})})]})}function Gn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function el(e){const t=e.split(".");return t.length>1&&t.pop()?.toUpperCase()||""}function tl({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," (",Gn(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(J,{icon:or,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:[el(e.file.name)," •"," ",Gn(e.file.size)]})]}),n.jsx(we,{variant:"ghost",size:"icon-sm",onClick:()=>t(e.id),className:"h-6 w-6 shrink-0 rounded-full hover:bg-primary-200","aria-label":"Remove attachment",type:"button",children:n.jsx(J,{icon:Pt,size:14})})]})}function nl({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(tl,{attachment:o,onRemove:t},o.id))})}const Vn=[{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 rl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function sl(e,t){const r=rl(t),o=new RegExp(`(?:^|\\n\\n)📎 Uploaded file: ${r}\\n\\nPlease analyze this file\\.(?=\\n\\n|$)`);return e.replace(o,(a,i)=>i===0?"":`
|
|
18
|
+
|
|
19
|
+
`).trim()}function ol({onSubmit:e,isLoading:t,disabled:r,wrapperRef:o,inputRef:a}){const[i,l]=s.useState(""),[c,u]=s.useState(""),[d,f]=s.useState([]),[m,p]=s.useState(0),[h,x]=s.useState(!1),[g,S]=s.useState(!1),[b,v]=s.useState(!1),[$,L]=s.useState(0),[F,I]=s.useState(!1),[Q,X]=s.useState(null),P=s.useRef(null),ne=s.useRef([]),H=s.useRef(null),k=s.useRef(null),j=s.useRef(null),E=s.useRef(null),T=s.useMemo(()=>/^\/\S*$/.test(i)&&!h,[i,h]),O=s.useMemo(()=>T?i.slice(1).toLowerCase():"",[T,i]),U=s.useMemo(()=>T?O?Vn.filter(N=>N.command.slice(1).toLowerCase().startsWith(O)):Vn:[],[T,O]),Z=s.useCallback(N=>{E.current=N,a&&(typeof a=="function"?a(N):a.current=N)},[a]),C=s.useCallback(()=>{typeof window>"u"||window.requestAnimationFrame(()=>{E.current?.focus()})},[]),M=s.useCallback(N=>{X(N)},[]),y=s.useCallback(()=>{l(""),f([]),p(0),x(!1),C()},[C]),A=s.useCallback(N=>{l(W=>{const K=`📎 Uploaded file: ${N}
|
|
20
|
+
|
|
21
|
+
Please analyze this file.`;return W.trim()?`${W.trim()}
|
|
22
|
+
|
|
23
|
+
${K}`:K})},[]),_=s.useCallback(async()=>{await fetch("/api/files/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:"/uploads"})})},[]),V=s.useCallback(async N=>{const W=crypto.randomUUID();if(!Ja(N))return{id:W,file:N,preview:null,type:"file",base64:null,error:"Unsupported file type for upload."};try{await _();const K=new FormData;K.append("path","/uploads"),K.append("file",N);const le=await fetch("/api/files/upload",{method:"POST",body:K});if(!le.ok){const Ee=await le.text();throw new Error(Ee||"File upload failed")}const ae=(await le.json()).files?.[0]?.path;if(!ae)throw new Error("Upload succeeded but no path was returned");return A(ae),{id:W,file:N,preview:null,type:"file",base64:null,uploadedPath:ae}}catch(K){return{id:W,file:N,preview:null,type:"file",base64:null,error:K instanceof Error?K.message:"File upload failed"}}},[A,_]),G=s.useCallback(async N=>{if(N.length===0)return;const W=await Promise.all(N.map(K=>Or(K)?Qa(K):V(K)));f(K=>[...K,...W]),C()},[C,V]),B=s.useCallback(N=>{let W;f(K=>{const le=K.find(re=>re.id===N);return le?.uploadedPath&&(W=le.uploadedPath),K.filter(re=>re.id!==N)}),W&&l(K=>sl(K,W))},[]),Y=s.useCallback(N=>{Array.from(N.dataTransfer.types).includes("Files")&&(N.preventDefault(),N.dataTransfer.dropEffect="copy",S(!0))},[]),se=s.useCallback(N=>{N.preventDefault();const W=N.relatedTarget;W&&N.currentTarget.contains(W)||S(!1)},[]),pe=s.useCallback(async N=>{N.preventDefault(),S(!1);const W=Array.from(N.dataTransfer.files);W.length!==0&&await G(W)},[G]),ee=s.useCallback(N=>{l(N),p(0),x(!1),C()},[C]),q=s.useCallback(N=>{l(N),p(0),x(!1)},[]),ie=s.useCallback(N=>{l(`${N.command} `),p(0),x(!1),C()},[C]),oe=s.useCallback(()=>{if(r)return;if(T&&U.length>0){const K=Math.min(m,U.length-1);ie(U[K]);return}const N=i.trim(),W=d.filter(K=>!K.error&&K.base64);N.length===0&&W.length===0||(e(N,{reset:y,setValue:ee,model:c||void 0,attachments:W}),C())},[r,T,U,m,ie,i,d,e,y,ee,c,C]),ce=s.useCallback(N=>{e(N,{reset:y,setValue:ee,model:c||void 0,attachments:[]}),C()},[C,e,y,ee,c]),ge=s.useCallback(N=>{if(T){if(N.key==="Escape"){N.preventDefault(),x(!0),p(0);return}if(U.length!==0){if(N.key==="ArrowDown"){N.preventDefault(),p(W=>(W+1)%U.length);return}if(N.key==="ArrowUp"){N.preventDefault(),p(W=>(W-1+U.length)%U.length);return}if(N.key==="Tab"){N.preventDefault();const W=Math.min(m,U.length-1);ie(U[W])}}}},[T,U,m,ie]);s.useEffect(()=>()=>{k.current?.abort(),H.current&&clearInterval(H.current),P.current&&P.current.state!=="inactive"&&P.current.stop(),j.current&&j.current.abort()},[]);const he=s.useCallback(()=>{if(typeof window>"u")return"auto";try{return localStorage.getItem("opencami-stt-provider")||"auto"}catch{return"auto"}},[]),R=s.useCallback(()=>{P.current&&P.current.state!=="inactive"&&P.current.stop(),j.current&&j.current.stop(),H.current&&(clearInterval(H.current),H.current=null),v(!1),L(0)},[]),de=s.useCallback(async()=>{X(null);const N=he();if(N==="browser"){const W=window.SpeechRecognition||window.webkitSpeechRecognition;if(!W){M("Web Speech API is not supported in this browser.");return}const K=new W;K.continuous=!0,K.interimResults=!1,K.lang=navigator.language||"en-US",j.current=K,v(!0),L(0),H.current=setInterval(()=>{L(re=>re>=119?(R(),0):re+1)},1e3);let le="";K.onresult=re=>{for(let ae=re.resultIndex;ae<re.results.length;ae++)re.results[ae].isFinal&&(le+=re.results[ae][0].transcript)},K.onend=()=>{v(!1),L(0),H.current&&clearInterval(H.current),le.trim()&&(X(null),l(re=>re+(re?" ":"")+le.trim()),C())},K.onerror=()=>{v(!1),L(0),H.current&&clearInterval(H.current),M("Speech recognition failed. Try the Browser provider again or switch providers in Settings.")},K.start();return}try{const W=await navigator.mediaDevices.getUserMedia({audio:!0}),K=MediaRecorder.isTypeSupported("audio/webm")?"audio/webm":"audio/mp4",le=new MediaRecorder(W,{mimeType:K});P.current=le,ne.current=[],le.ondataavailable=re=>{re.data.size>0&&ne.current.push(re.data)},le.onstop=async()=>{W.getTracks().forEach(ae=>ae.stop());const re=new Blob(ne.current,{type:K});if(re.size!==0){I(!0);try{const ae=new FormData;ae.append("audio",re,`recording.${K==="audio/webm"?"webm":"mp4"}`),N!=="auto"&&ae.append("provider",N),k.current?.abort();const Ee=new AbortController;k.current=Ee;const Re=await(await fetch("/api/stt",{method:"POST",body:ae,signal:Ee.signal})).json();Re.ok&&Re.text?(X(null),l(Pe=>Pe+(Pe?" ":"")+Re.text),C()):Re.ok||(console.warn("STT failed:",Re.error),M(Re.error||"Speech-to-text failed. Try the Browser provider in Settings."))}catch(ae){if(ae instanceof Error&&ae.name==="AbortError")return;console.warn("STT request failed:",ae),M("Could not reach speech-to-text service.")}finally{I(!1)}}},v(!0),L(0),H.current=setInterval(()=>{L(re=>re>=119?(R(),0):re+1)},1e3),le.start()}catch(W){const K=W instanceof Error?W.message:String(W);if(K.includes("NotAllowedError")||K.includes("Permission"))try{(await navigator.permissions.query({name:"microphone"})).state==="denied"?M("Microphone access is blocked. Please enable it in your browser/app settings."):M("Microphone permission was not granted. Please try again and allow access when prompted.")}catch{M("Could not access microphone. Please check your browser settings and allow microphone access for this site.")}else M("Could not access microphone: "+K)}},[he,R,C,M]),je=s.useCallback(()=>{b?R():de()},[b,R,de]),Te=d.filter(N=>!N.error&&N.base64),$e=r||i.trim().length===0&&Te.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:Y,onDragLeave:se,onDrop:pe,children:[g&&n.jsx("div",{className:"pointer-events-none absolute inset-2 z-20 flex items-center justify-center rounded-2xl border-2 border-dashed border-primary-400 bg-primary-50/90 text-sm font-medium text-primary-700",children:"Drop files here"}),n.jsxs(La,{value:i,onValueChange:q,onSubmit:oe,isLoading:t,disabled:r,children:[n.jsx(nl,{attachments:d,onRemove:B}),Q&&n.jsx("div",{className:"mx-3 mt-3 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-900/40 dark:bg-red-950/40 dark:text-red-200",role:"alert","aria-live":"polite",children:Q}),T&&U.length>0&&n.jsx(Da,{commands:U,selectedIndex:Math.min(m,U.length-1),onSelect:ie}),n.jsx(_a,{placeholder:"Type a message…",inputRef:Z,onKeyDown:ge}),n.jsxs(Pa,{className:"justify-between px-3",children:[n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(Ma,{}),n.jsx($a,{onSelect:ce}),n.jsx(Ha,{onCommandSelect:N=>q(N+" ")})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(Za,{onFilesSelect:G,disabled:r}),n.jsx(Bn,{tooltip:b?"Stop recording":"Voice input",children:n.jsx(we,{onClick:je,disabled:r||F,size:"icon-sm",variant:b?"destructive":"ghost",className:`rounded-full ${b?"animate-pulse":""}`,"aria-label":b?"Stop recording":"Voice input",children:F?n.jsx("span",{className:"size-4 animate-spin rounded-full border-2 border-current border-t-transparent"}):b?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($/60),":",String($%60).padStart(2,"0")]}),n.jsx(J,{icon:rr,size:14,strokeWidth:2})]}):n.jsx(J,{icon:ks,size:18,strokeWidth:2})})}),n.jsx(Bn,{tooltip:"Send message",children:n.jsx(we,{onClick:oe,disabled:$e,size:"icon-sm",className:"rounded-full","aria-label":"Send message",children:n.jsx(J,{icon:Ns,size:18,strokeWidth:2})})})]})]})]})]})}const il=s.memo(ol);function al({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(Rr,{children:n.jsxs("div",{className:"w-full rounded-xl border border-primary-200 bg-primary-50 p-4 text-primary-900",children:[n.jsx("div",{className:"text-balance font-medium",children:e}),n.jsx("div",{className:"mt-2 text-pretty text-primary-700",children:t}),r?n.jsx("div",{className:"mt-2 text-xs text-primary-600",children:r}):null,o&&a?n.jsx("div",{className:"mt-3",children:n.jsx(we,{size:"sm",variant:"outline",onClick:a,children:o})}):null]})})})}function ll({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(al,{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 cl(){const e=s.useRef(null),t=s.useRef(null),r=s.useRef(null),[o,a]=s.useState(0),[i,l]=s.useState(0);return s.useLayoutEffect(()=>{const c=e.current,u=t.current,d=r.current;if(!d)return;const f=()=>{const p=c?.offsetHeight??0,h=u?.offsetHeight??0,x=d.clientHeight;d.style.setProperty("--chat-header-height",`${Math.max(0,p)}px`),d.style.setProperty("--chat-composer-height",`${Math.max(0,h)}px`),l(p),a(Math.max(0,x-p-h))};f();const m=new ResizeObserver(()=>f());return c&&m.observe(c),u&&m.observe(u),()=>m.disconnect()},[]),{headerRef:e,composerRef:t,mainRef:r,pinGroupMinHeight:o,headerHeight:i}}function ul({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 v=c.getQueryData(d),$=Array.isArray(v?.messages)?v.messages.filter(I=>I.status==="sending"||I.__optimisticId?!0:!!I.clientId):[],L=await yo({sessionKey:u,friendlyId:e});if(!$.length)return L;const F=dl(L.messages,$);return{...L,messages:F}},enabled:!o&&!!e&&!a&&(!l||i),placeholderData:function(){return c.getQueryData(d)},gcTime:1e3*60*10}),m=s.useRef(""),p=s.useRef([]),h=s.useMemo(()=>{const b=Array.isArray(f.data?.messages)?f.data.messages:[],v=b[b.length-1],$=v&&typeof v.id=="string"?v.id:"",L=`${b.length}:${v?.role??""}:${$}:${_e(v??{content:[]}).slice(-32)}`;return L===m.current?p.current:(m.current=L,p.current=b,b)},[f.data?.messages]),x=f.error instanceof Error?f.error.message:null,g=s.useMemo(()=>{if(r)return r;const b=f.data?.sessionKey;return typeof b=="string"&&b.trim().length>0?b.trim():t},[t,r,f.data?.sessionKey]);return{historyQuery:f,historyMessages:h,displayMessages:h,historyError:x,resolvedSessionKey:g,activeCanonicalKey:o?"new":g||e,sessionKeyForHistory:u}}function dl(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=_e(o);if(!l||l!==_e(i))return!1;const c=Jt(o),u=Jt(i);return Math.abs(c-u)<=1e4})||r.push(o);return r}function fl(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&&Ye(e,function(a){return{...a,isSidebarCollapsed:!0}})},[t,e]),{isMobile:t}}function ml({activeFriendlyId:e,isNewChat:t,forcedSessionKey:r}){const[o,a]=s.useState(()=>typeof document>"u"?!0:document.visibilityState==="visible");s.useEffect(()=>{if(typeof document>"u")return;const h=()=>{a(document.visibilityState==="visible")};return h(),document.addEventListener("visibilitychange",h),()=>{document.removeEventListener("visibilitychange",h)}},[]);const i=Mt({queryKey:me.sessions,queryFn:go,refetchInterval:o?3e4:!1}),l=s.useMemo(()=>{const h=i.data??[];return Do(h)},[i.data]),c=s.useMemo(()=>l.find(h=>h.friendlyId===e),[l,e]),u=s.useMemo(()=>t||r||hr(e)?!0:l.some(h=>h.friendlyId===e),[e,r,t,l]),d=c?.key??"",f=s.useMemo(()=>c?c.label||c.title||c.derivedTitle||c.friendlyId:e,[e,c]),m=i.error instanceof Error?i.error.message:null,p=s.useMemo(()=>({totalTokens:c?.totalTokens,contextTokens:c?.contextTokens}),[c?.totalTokens,c?.contextTokens]);return{sessionsQuery:i,sessions:l,activeSession:c,activeExists:u,activeSessionKey:d,activeTitle:f,activeTokens:p,sessionsError:m}}const pl={openai:{baseUrl:"https://api.openai.com/v1",model:"gpt-4.1-nano"},openrouter:{baseUrl:"https://openrouter.ai/api/v1",model:"openai/gpt-oss-120b"},kilocode:{baseUrl:"https://api.kilo.ai/api/gateway",model:"google/gemini-2.5-flash"},ollama:{baseUrl:"http://localhost:11434/v1",model:"llama3.2"},custom:{baseUrl:"",model:""}},It={useLlmTitles:!0,useLlmFollowUps:!0,llmProvider:"openai",llmBaseUrl:"",llmModel:"",llmApiKey:""};function Lr(e){return pl[e]}function hl(e){return e.llmBaseUrl.trim()?e.llmBaseUrl.trim():Lr(e.llmProvider).baseUrl}function gl(e){return e.llmModel.trim()?e.llmModel.trim():Lr(e.llmProvider).model}function qn(e,t){return e.llmProvider==="ollama"?!0:e.llmProvider==="custom"?!!e.llmApiKey.trim()||!!(e.llmBaseUrl.trim()&&e.llmModel.trim()):t||!!e.llmApiKey.trim()}function yl(e){if(!e||typeof e!="object")return{settings:It};const{settings:t}=e;if(!t)return{settings:It};const{openaiApiKey:r,...o}=t,a=o.llmApiKey??r??"";return{settings:{...It,...o,llmApiKey:a}}}const mt=mr()(fr(e=>({settings:{...It},updateSettings:t=>e(r=>({settings:{...r.settings,...t}})),clearApiKey:()=>e(t=>({settings:{...t.settings,llmApiKey:""}}))}),{name:"llm-settings",version:2,migrate:e=>yl(e)}));function Jl(){const e=mt(l=>l.settings),t=mt(l=>l.updateSettings),r=mt(l=>l.clearApiKey),[o,a]=s.useState({hasEnvKey:!1,hasOpenRouterKey:!1,hasKilocodeKey:!1,hasUserKey:!!e.llmApiKey,isAvailable:qn(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:qn(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=_r({...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 _r(e){const t=e.llmApiKey,r=hl(e),o=gl(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 xl(){const e=mt.getState().settings;return _r(e)}function wl(){const e=mt(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",...xl()},p=await fetch("/api/llm-features",{method:"POST",headers:m,body:JSON.stringify({action:"title",message:d}),signal:f.signal});if(!p.ok)throw new Error(`API error: ${p.status}`);const h=await p.json();if(f.signal.aborted)throw new Error("Aborted");const x=h.title||d.slice(0,50),g=x.length>64?x.slice(0,61)+"...":x,S=h.source||"heuristic";return a(g),l(S),{title:g,source:S,error:h.error}}catch(m){if(m instanceof Error&&m.name==="AbortError")throw m;const p=bl(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 bl(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 Sl(){return mt(e=>e.settings.useLlmTitles)}const Jn={active:!1,text:"",tools:[],sessionKey:null};function vl(e){const[t,r]=s.useState(Jn),o=s.useRef(null),a=s.useRef(!1),i=s.useRef(!1),l=s.useRef(new Set),c=s.useRef(e.onDone),u=s.useRef(e.onError),d=s.useRef(e.onAssistantDelta);c.current=e.onDone,u.current=e.onError,d.current=e.onAssistantDelta;const f=s.useCallback(p=>{if(a.current=!0,i.current=!1,l.current.clear(),o.current&&(o.current.close(),o.current=null),p?.preserveState){r(h=>({...h,active:!1}));return}r(Jn)},[]),m=s.useCallback(function(h){if(a.current=!1,i.current=!1,l.current.clear(),r({active:!0,text:"",tools:[],sessionKey:h}),o.current)return;const x=new EventSource(`/api/stream?sessionKey=${encodeURIComponent(h)}`);o.current=x,x.addEventListener("message",g=>{try{const S=JSON.parse(g.data);if(S.event==="agent"){jl(S.payload,h,{setState:r,onAssistantDelta:d.current,activeRuns:l.current});return}if(S.event==="chat"){const b=an(S.payload),v=xe(b?.sessionKey)||h,$=xe(b?.state);$==="final"&&(i.current=!0),!a.current&&i.current&&($==="final"||l.current.size===0)&&(a.current=!0,r(L=>({...L,active:!1})),c.current(v));return}if(S.event==="error"){const b=typeof S.payload=="string"?S.payload:"Stream connection lost";u.current?.(b)}}catch{}}),x.onerror=()=>{a.current||x.readyState===EventSource.CLOSED&&(o.current=null,r(g=>({...g,active:!1})),u.current?.("Stream connection lost"))}},[]);return{streaming:t,startStream:m,stopStream:f}}function jl(e,t,r){const o=an(e),a=xe(o?.stream),i=xe(o?.runId),l=xe(o?.sessionKey)||t,c=an(o?.data);if(i)if(a==="lifecycle"){const m=xe(c?.phase);m==="end"||m==="error"||m==="abort"?r.activeRuns.delete(i):m&&r.activeRuns.add(i)}else r.activeRuns.add(i);if(a==="assistant"){const m=xe(c?.delta)||xe(c?.text);if(!m)return;r.setState(p=>({...p,sessionKey:l,text:p.text+m})),r.onAssistantDelta?.({text:m,sessionKey:l});return}if(!a.includes("tool"))return;const u=xe(c?.toolCallId)||xe(c?.id)||xe(c?.callId)||`${i||"tool"}:${xe(c?.toolName)||xe(c?.name)||"unknown"}`,d=xe(c?.toolName)||xe(c?.name)||"Tool",f=El(a,c);r.setState(m=>{const p=[...m.tools],h=p.findIndex(g=>g.id===u),x={id:u,name:d,status:f};return h>=0?p[h]=x:p.push(x),{...m,sessionKey:l,tools:p}})}function El(e,t){const r=xe(t?.phase)||xe(t?.status)||xe(t?.state);return r||(e.includes("result")||e.includes("output")?"done":(e.includes("call"),"running"))}function an(e){return e&&typeof e=="object"?e:null}function xe(e){return typeof e=="string"?e.trim():""}function Cl(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 Qn(e){const{threshold:t=50,edgeWidth:r,onMove:o,onSwipe:a,onCancel:i,direction:l,enabled:c=!0}=e,u=s.useRef({startX:0,startY:0,tracking:!1,directionLocked:!1}),d=s.useCallback(p=>{if(!c)return;const h=p.touches[0];h&&(r!==void 0&&h.clientX>r||(u.current={startX:h.clientX,startY:h.clientY,tracking:!0,directionLocked:!1}))},[c,r]),f=s.useCallback(p=>{const h=u.current;if(!h.tracking)return;const x=p.touches[0];if(!x)return;const g=x.clientX-h.startX,S=x.clientY-h.startY,b=Math.abs(g),v=Math.abs(S);if(!h.directionLocked){if(b<5&&v<5)return;if(v>b){h.tracking=!1,i?.();return}h.directionLocked=!0}l==="left"&&g>0||l==="right"&&g<0||(p.preventDefault(),o?.(g))},[l,o,i]),m=s.useCallback(p=>{const h=u.current;if(!h.tracking)return;h.tracking=!1;const x=p.changedTouches[0];if(!x){i?.();return}const g=x.clientX-h.startX,S=Math.abs(g);if(!h.directionLocked||S<t){i?.();return}const b=g>0?"right":"left";if(l&&b!==l){i?.();return}a(b)},[l,i,a,t]);return{onTouchStart:d,onTouchMove:f,onTouchEnd:m}}const Pr="opencami-browser-notifications-enabled",kl=5e3;function Gt(){return typeof window<"u"&&"Notification"in window}function Zn(){if(typeof window>"u")return!1;try{return localStorage.getItem(Pr)==="true"}catch{return!1}}function Nl(){const e=_t(),t=s.useRef(0),[r,o]=s.useState(()=>Zn()),a=s.useCallback(async()=>{if(!Gt())return"denied";try{return await Notification.requestPermission()}catch{return"denied"}},[]),i=s.useCallback(async c=>{o(c);try{localStorage.setItem(Pr,String(c))}catch{}c&&Gt()&&Notification.permission==="default"&&await a()},[a]),l=s.useCallback(c=>{if(!r||!Gt()||document.hidden!==!0||Notification.permission!=="granted")return;const u=Date.now();if(u-t.current<kl)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(()=>{const c=()=>o(Zn());return window.addEventListener("storage",c),()=>window.removeEventListener("storage",c)},[]),{notificationsEnabled:r,setNotificationsEnabled:i,requestNotificationPermission:a,maybeNotifyAssistantMessage:l}}const Tl=s.lazy(()=>rt(()=>import("./keyboard-shortcuts-dialog-BA8cBwWm.js"),__vite__mapDeps([29,1,4,3,5,6,7,8,9,2])).then(e=>({default:e.KeyboardShortcutsDialog}))),Rl=s.lazy(()=>rt(()=>import("./search-dialog-CJS2GUnE.js"),__vite__mapDeps([30,1,3,4,5,6,7,8,9,2,17,18,14,19,11,15,20,13,21,22,23,16,24])).then(e=>({default:e.SearchDialog}))),Nt="opencami-search-jump-target";function Il({activeFriendlyId:e,isNewChat:t=!1,onSessionResolved:r,forcedSessionKey:o}){const a=_t(),i=pt(),[l,c]=s.useState(!1),[u,d]=s.useState(!1),[f,m]=s.useState(null),[p,h]=s.useState(!1),{headerRef:x,composerRef:g,mainRef:S,pinGroupMinHeight:b,headerHeight:v}=cl(),[$,L]=s.useState(()=>$t()||Ft()),[F,I]=s.useState(()=>$t()||Ft()),[Q,X]=s.useState(!1),[P,ne]=s.useState(!1),[H,k]=s.useState("global"),[j,E]=s.useState(null),[T,O]=s.useState(!1),U=sn(w=>w.level),{maybeNotifyAssistantMessage:Z}=Nl(),C=s.useRef(null),M=s.useRef(null),y=s.useRef(null),A=s.useRef(""),_=s.useRef(()=>{}),V=s.useRef(!1),G=s.useRef(""),{isMobile:B}=fl(i),{sessionsQuery:Y,sessions:se,activeExists:pe,activeSessionKey:ee,activeTitle:q,activeTokens:ie,sessionsError:oe}=ml({activeFriendlyId:e,isNewChat:t,forcedSessionKey:o}),{historyQuery:ce,historyMessages:ge,displayMessages:he,historyError:R,resolvedSessionKey:de,activeCanonicalKey:je,sessionKeyForHistory:Te}=ul({activeFriendlyId:e,activeSessionKey:ee,forcedSessionKey:o,isNewChat:t,isRedirecting:p,activeExists:pe,sessionsReady:Y.isSuccess,queryClient:i}),$e=Mt({queryKey:ns,queryFn:function(){return jn(i)},initialData:function(){return jn(i)},staleTime:1/0}),N=Mt({queryKey:["gateway","status"],queryFn:xo,retry:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1,refetchOnMount:"always"}),W=s.useRef(Date.now()),K=N.error instanceof Error?N.error.message:N.data&&!N.data.ok?N.data.error||"Gateway unavailable":null,le=K??oe??R,re=s.useCallback(()=>{N.refetch()},[N]),ae=$e.data?.isSidebarCollapsed??!1,Ee=Qn({enabled:B&&ae,edgeWidth:40,threshold:50,direction:"right",onSwipe:()=>{Ye(i,w=>({...w,isSidebarCollapsed:!1}))}}),st=Qn({enabled:B&&!ae,threshold:50,direction:"left",onSwipe:()=>{Ye(i,w=>({...w,isSidebarCollapsed:!0}))}}),Re=s.useCallback(()=>{m(null),h(!0),a({to:"/new",replace:!0})},[a]),Pe=s.useCallback(()=>{M.current&&(window.clearInterval(M.current),M.current=null),y.current&&(window.clearTimeout(y.current),y.current=null)},[]),Qe=s.useCallback(()=>{Pe(),wt(!1),L(!1),O(!1)},[Pe]),ht=Sl(),{generateTitle:gt}=wl(),St=s.useRef(new Set),vt=2e3,yt=2e3,xt=s.useCallback(()=>{!e||t||(M.current&&window.clearInterval(M.current),O(!0),M.current=window.setInterval(()=>{_.current()},vt))},[e,t]),jt=s.useRef(()=>{}),Fe=s.useRef(()=>{}),{streaming:te,startStream:Se,stopStream:Ue}=vl({onDone:w=>jt.current(w),onError:w=>Fe.current(w),onAssistantDelta:({text:w})=>{G.current+=w,Z({text:G.current,sessionFriendlyId:e})}});jt.current=s.useCallback(async w=>{await ce.refetch(),Ue({preserveState:!0}),Qe(),i.invalidateQueries({queryKey:me.sessions})},[ce,i,Ue,Qe]),Fe.current=s.useCallback(w=>{console.warn("[stream] SSE error, falling back to polling")},[]);const He=s.useMemo(()=>{if(!te.text)return null;const w=[];for(const z of te.tools)w.push({type:"toolCall",name:z.name,id:z.id});return w.push({type:"text",text:te.text}),{role:"assistant",content:w,id:"__streaming__",__streaming:!0,timestamp:Date.now()}},[te.text,te.tools]),Kr=s.useMemo(()=>{if(!He)return he;const w=[...he].map((ue,ye)=>({message:ue,index:ye})).filter(({message:ue})=>ue.role==="assistant").map(({index:ue})=>ue).pop(),z=[...he].map((ue,ye)=>({message:ue,index:ye})).filter(({message:ue})=>ue.role==="user").map(({index:ue})=>ue).pop();if(typeof w=="number"&&(typeof z!="number"||w>z)&&typeof w=="number"){const ue=he[w];if(_e(ue).length>=te.text.length)return he;const Ke=[...he];return Ke[w]=He,Ke}return[...he,He]},[he,He,te.text]),zr=s.useMemo(()=>({}),[]);_.current=function(){ce.refetch()},s.useEffect(()=>{if(p){f&&m(null);return}if(ot){f&&m(null);return}if(Y.isSuccess&&!pe){f&&m(null);return}const w=oe??R??K;if(!w){f?.startsWith("Failed to load")&&m(null);return}Mn(w)&&a({to:"/connect",replace:!0});const z=oe?`Failed to load sessions. ${oe}`:R?`Failed to load history. ${R}`:K?`Gateway unavailable. ${K}`:null;z&&m(z)},[f,K,R,p,a,oe]);const ot=!t&&!o&&!hr(e)&&Y.isSuccess&&se.length>0&&!se.some(w=>w.friendlyId===e)&&!ce.isFetching&&!ce.isSuccess;s.useEffect(()=>{if(p){if(t){h(!1);return}!ot&&Y.isSuccess&&h(!1)}},[t,p,Y.isSuccess,ot]),s.useEffect(()=>{t||Y.isSuccess&&se.length!==0&&ot&&(Dt(),Zt(i,e,Te),a({to:"/new",replace:!0}))},[e,ce.isFetching,ce.isSuccess,t,a,i,Te,se,Y.isSuccess,ot]);const hn=ot||p,Et=s.useRef("fast");s.useEffect(()=>{const w=[...ge].reverse().find(fe=>fe.role==="assistant");if(!w)return;const z=`${ge.length}:${_e(w).slice(-64)}`;z!==A.current&&(A.current=z,Et.current!=="fast"&&M.current&&(window.clearInterval(M.current),M.current=window.setInterval(()=>{_.current()},vt),Et.current="fast"),y.current&&window.clearTimeout(y.current),y.current=window.setTimeout(()=>{M.current&&(window.clearInterval(M.current),M.current=window.setInterval(()=>{_.current()},yt),Et.current="slow"),y.current=window.setTimeout(()=>{Qe(),Et.current="fast"},3e3)},1500))},[ge,Qe]),s.useEffect(()=>{if(!ht||t||p)return;const w=o||de||ee;if(!w||St.current.has(w))return;const z=ge.filter(ye=>ye.role==="user"),fe=ge.filter(ye=>ye.role==="assistant");if(z.length===0||fe.length===0||z.length!==1)return;const ue=_e(z[0]);!ue||ue.length<5||(St.current.add(w),(async()=>{try{const ye=await gt(ue);ye.title&&await Eo(i,w,e,ye.title)}catch(ye){console.error("[smart-title] Error generating title:",ye)}})())},[ht,t,p,o,de,ee,e,ge,gt,i]),s.useEffect(()=>{if(t||e){if(Pe(),Ue(),A.current="",O(!1),V.current){V.current=!1;return}if($t()||Ft()){L(!0),I(!0);return}L(!1),I(!1)}},[e,t,Pe,Ue]),s.useEffect(()=>{if(!(typeof window>"u"))try{const w=sessionStorage.getItem(Nt);if(!w){E(null);return}const z=JSON.parse(w);if(typeof z.at=="number"&&Date.now()-z.at>300*1e3){sessionStorage.removeItem(Nt),E(null);return}if(z.friendlyId===e&&typeof z.messageId=="string"&&z.messageId.length>0){E(z.messageId),sessionStorage.removeItem(Nt);return}E(null)}catch{E(null)}},[e]),s.useLayoutEffect(()=>{if(t)return;const w=Ro(o||de||ee,e);if(!w)return;V.current=!0;const z=me.history(w.friendlyId,w.sessionKey),fe=i.getQueryData(z);(Array.isArray(fe?.messages)?fe.messages:[]).some(Ke=>!!(w.optimisticMessage.clientId&&(Ke.clientId===w.optimisticMessage.clientId||Ke.__optimisticId===w.optimisticMessage.clientId)||w.optimisticMessage.__optimisticId&&Ke.__optimisticId===w.optimisticMessage.__optimisticId))||Ut(i,w.friendlyId,w.sessionKey,w.optimisticMessage),L(!0),I(!0),zt(w.sessionKey,w.friendlyId,w.message,!0,w.attachments)},[e,ee,o,t,i,de]);function zt(w,z,fe,ue=!1,ye,Ke){let it="";if(!ue){const{clientId:Ce,optimisticMessage:at}=An(fe,ye);it=Ce,Ut(i,z,w,at),vo(i,w,z,at)}wt(!0),c(!0),m(null),L(!0),I(!0);const We=ye?.map(Ce=>({mimeType:Ce.file.type,content:Ce.base64}));G.current="",xt();const Ze=w||z;Ze&&Se(Ze),fetch("/api/send",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({sessionKey:w,friendlyId:z,message:fe,thinking:U,idempotencyKey:crypto.randomUUID(),attachments:We,model:Ke||void 0})}).then(async Ce=>{if(!Ce.ok)throw new Error(await ze(Ce));const vn=(await Ce.json()).sessionKey||w||z;Se(vn)}).catch(Ce=>{const at=Ce instanceof Error?Ce.message:String(Ce);if(Mn(at)){a({to:"/connect",replace:!0});return}it&&wo(i,z,w,it,function(Qr){return{...Qr,status:"error"}}),m(`Failed to send message. ${at}`),wt(!1),L(!1),I(!1)}).finally(()=>{c(!1)})}const gn=s.useCallback(async()=>{d(!0);try{const w=await fetch("/api/sessions",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({})});if(!w.ok)throw new Error(await ze(w));const z=await w.json(),fe=typeof z.sessionKey=="string"?z.sessionKey:"",ue=typeof z.friendlyId=="string"&&z.friendlyId.trim().length>0?z.friendlyId.trim():qt(fe);if(!fe||!ue)throw new Error("Invalid session response");return i.invalidateQueries({queryKey:me.sessions}),{sessionKey:fe,friendlyId:ue}}finally{d(!1)}},[i]),Ur=s.useCallback((w,z)=>{const fe=z.attachments;if(w.length===0&&(!fe||fe.length===0))return;if(z.reset(),t){const{clientId:ye,optimisticId:Ke,optimisticMessage:it}=An(w,fe);Ut(i,"new","new",it),wt(!0),c(!0),L(!0),I(!0),gn().then(({sessionKey:We,friendlyId:Ze})=>{if(To(Ze),ko({sessionKey:We,friendlyId:Ze,message:w,optimisticMessage:it,attachments:fe}),r){r({sessionKey:We,friendlyId:Ze});return}a({to:"/chat/$sessionKey",params:{sessionKey:Ze},replace:!0})}).catch(We=>{bo(i,"new","new",ye,Ke),z.setValue(w),m(`Failed to create session. ${We instanceof Error?We.message:String(We)}`),wt(!1),L(!1),I(!1),c(!1)});return}zt(o||de||ee,e,w,!1,fe,z.model)},[e,ee,gn,o,t,a,r,i,de]),yn=s.useCallback(()=>{L(!1),I(!1),Zt(i,"new","new"),a({to:"/new"}),B&&Ye(i,function(z){return{...z,isSidebarCollapsed:!0}})},[B,a,i]),$r=s.useCallback(()=>{Ye(i,function(z){return{...z,isSidebarCollapsed:!z.isSidebarCollapsed}})},[i]),Fr=s.useCallback(()=>{B&&Ye(i,function(z){return{...z,isSidebarCollapsed:!0}})},[B,i]),Hr=s.useCallback(()=>{Ye(i,function(z){return{...z,isSidebarCollapsed:!1}})},[i]),Wr=s.useCallback(w=>{if(t||!w.trim())return;const z=o||de||ee;z&&zt(z,e,w.trim())},[e,ee,o,t,de]),Xr=s.useCallback(()=>{C.current?.focus()},[]),Br=s.useCallback(()=>{if(Q){X(!1);return}document.activeElement instanceof HTMLElement&&document.activeElement.blur()},[Q]),Yr=s.useCallback(()=>{const w=[...he].reverse().find(fe=>fe.role==="assistant");if(!w)return;const z=_e(w);z&&navigator.clipboard.writeText(z).catch(()=>{})},[he]),Gr=s.useCallback(()=>{X(!0)},[]),Vr=s.useCallback(()=>{k(t?"global":"current"),ne(!0)},[t]),xn=s.useCallback(()=>{k("global"),ne(!0)},[]);Cl({onNewChat:yn,onFocusInput:Xr,onEscape:Br,onCopyLastResponse:Yr,onShowHelp:Gr,onSearch:Vr,onSearchGlobal:xn});const wn=ce.isLoading&&!ce.data||p,bn=!!K&&N.errorUpdatedAt>W.current,qr=!wn&&he.length===0,Jr=s.useMemo(()=>!bn||!le?null:n.jsx(ll,{state:"error",error:le,onRetry:re}),[le,re,bn]),Sn=n.jsx(Xi,{sessions:se,activeFriendlyId:e,activeSessionKey:Te,creatingSession:u,onCreateSession:yn,isCollapsed:B?!1:ae,onToggleCollapse:$r,onSelectSession:Fr,onActiveSessionDelete:Re,onOpenSearch:xn});return n.jsxs("div",{className:"h-screen bg-surface text-primary-900",children:[n.jsxs("div",{className:D("h-full overflow-hidden",B?"relative":"grid grid-cols-[auto_minmax(0,1fr)]"),children:[hn?null:B?n.jsxs(n.Fragment,{children:[!ae&&n.jsx("div",{className:"fixed inset-0 z-40 bg-black/40 transition-opacity duration-200",onClick:()=>Ye(i,w=>({...w,isSidebarCollapsed:!0})),...st}),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",ae?"-translate-x-full":"translate-x-0"),...st,children:Sn})]}):Sn,n.jsxs("main",{className:"flex flex-col h-full min-h-0 min-w-0 overflow-x-hidden",ref:S,...Ee,children:[n.jsx(Vi,{activeTitle:q,wrapperRef:x,showSidebarButton:B,onOpenSidebar:Hr,totalTokens:ie.totalTokens,contextTokens:ie.contextTokens}),hn?null:n.jsxs(n.Fragment,{children:[n.jsx(Ra,{messages:Kr,loading:wn,empty:qr,notice:Jr,noticePosition:"end",waitingForResponse:$,isStreaming:T,sessionKey:je,pinToTop:F,pinGroupMinHeight:b,headerHeight:v,contentStyle:zr,onFollowUpClick:Wr,jumpToMessageId:j}),n.jsx(il,{onSubmit:Ur,isLoading:l,disabled:l,wrapperRef:g,inputRef:C})]})]})]}),Q&&n.jsx(s.Suspense,{fallback:null,children:n.jsx(Tl,{open:Q,onOpenChange:X})}),P&&n.jsx(s.Suspense,{fallback:null,children:n.jsx(Rl,{open:P,onOpenChange:ne,sessions:se,currentFriendlyId:e,currentSessionKey:ee,mode:H,onJumpToMessage:w=>{if(ne(!1),!!w.friendlyId){if(w.messageId&&w.friendlyId===e){E(w.messageId);return}if(w.messageId&&typeof window<"u")try{sessionStorage.setItem(Nt,JSON.stringify({friendlyId:w.friendlyId,messageId:w.messageId,at:Date.now()}))}catch{}a({to:"/chat/$sessionKey",params:{sessionKey:w.friendlyId}})}}})})]})}function Ml(){const e=pt(),t=_t(),[r,o]=s.useState(null),a=ts.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){So(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(Il,{activeFriendlyId:i,isNewChat:l,forcedSessionKey:c,onSessionResolved:l?u:void 0})}const Ql=Object.freeze(Object.defineProperty({__proto__:null,component:Ml},Symbol.toStringTag,{value:"Module"}));export{Ql as $,en as C,tn as a,nn as b,me as c,mt as d,xl as e,Lr as g,Jl as u};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/agents-screen-C58VLjES.js","assets/main-_1IghVZn.js","assets/useQuery-BdjM5kzn.js","assets/button-BcUmP7JL.js","assets/switch-BwmDNR0d.js","assets/useControlled-DeDLOsPR.js","assets/useBaseUiId-DN9cOflS.js","assets/visuallyHidden-COI6QeQH.js","assets/tooltip-DexBPu8g.js","assets/useOnFirstRender-S4-xcV93.js","assets/event-BxzjTPjG.js","assets/DirectionContext-FHFKdJq_.js","assets/opencami-logo-BFo87CeM.js","assets/proxy-CJ6-TEKD.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{j as e,r as t,_ as r}from"./main-_1IghVZn.js";const n=t.lazy(()=>r(()=>import("./agents-screen-C58VLjES.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{u as L,r as t,j as e,L as M}from"./main-_1IghVZn.js";import{u as q}from"./useQuery-BdjM5kzn.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-BcUmP7JL.js";import{S as _}from"./switch-BwmDNR0d.js";import{s as X,T as Y,a as Z,b as $,c as ee,d as se,g as P}from"./tooltip-DexBPu8g.js";import{O as re,a as ae}from"./opencami-logo-BFo87CeM.js";import{m as S,A as W}from"./proxy-CJ6-TEKD.js";import"./useControlled-DeDLOsPR.js";import"./useBaseUiId-DN9cOflS.js";import"./visuallyHidden-COI6QeQH.js";import"./useOnFirstRender-S4-xcV93.js";import"./event-BxzjTPjG.js";import"./DirectionContext-FHFKdJq_.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-B8h4Y1VL.js","assets/main-_1IghVZn.js","assets/button-BcUmP7JL.js","assets/switch-BwmDNR0d.js","assets/useControlled-DeDLOsPR.js","assets/useBaseUiId-DN9cOflS.js","assets/visuallyHidden-COI6QeQH.js","assets/useQuery-BdjM5kzn.js","assets/useMutation-TzgejsE_.js","assets/proxy-CJ6-TEKD.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{j as e,r as t,_ as r}from"./main-_1IghVZn.js";const n=t.lazy(()=>r(()=>import("./bots-screen-B8h4Y1VL.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])).then(s=>({default:s.BotsScreen})));function a(){return e.jsx(t.Suspense,{fallback:e.jsx("div",{className:"flex h-screen items-center justify-center text-sm text-primary-500",children:"Loading…"}),children:e.jsx(n,{})})}export{a as component};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{u as g,j as e,r as f,L as v}from"./main-CQKtcNr3.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-8ab4wOwy.js";import{S}from"./switch-CSnzINDW.js";import{u as j}from"./useQuery-Boaa6oF3.js";import{u as N}from"./useMutation-rx8UH99I.js";import{m as M,A as $}from"./proxy-CHQ-VCN1.js";import"./useControlled-CT2hRlcU.js";import"./useBaseUiId-DiwX_3so.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};
|
|
1
|
+
import{u as g,j as e,r as f,L as v}from"./main-_1IghVZn.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-BcUmP7JL.js";import{S}from"./switch-BwmDNR0d.js";import{u as j}from"./useQuery-BdjM5kzn.js";import{u as N}from"./useMutation-TzgejsE_.js";import{m as M,A as $}from"./proxy-CJ6-TEKD.js";import"./useControlled-DeDLOsPR.js";import"./useBaseUiId-DN9cOflS.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};
|