opencami 2.0.0 → 2.1.0
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-CrlIQW7-.js → CSPContext-CxrBvJ99.js} +1 -1
- package/dist/client/assets/{DirectionContext-X-0CRn1O.js → DirectionContext-BOL0P_1j.js} +1 -1
- package/dist/client/assets/_sessionKey-CTtu2ipR.js +25 -0
- package/dist/client/assets/agents-D7JS19Lo.js +2 -0
- package/dist/client/assets/{agents-screen-BhOVp_S6.js → agents-screen-CqdzZKaR.js} +1 -1
- package/dist/client/assets/bots-DAInzfLx.js +2 -0
- package/dist/client/assets/{bots-screen-DLFd0ydi.js → bots-screen-RYovD6cu.js} +1 -1
- package/dist/client/assets/{button-D0n2Qsd_.js → button-Bv-7bwZZ.js} +1 -1
- package/dist/client/assets/{composite-GtKwZKbV.js → composite-DwQIZFe9.js} +1 -1
- package/dist/client/assets/{connect-vQWL0_11.js → connect-DZSrhhNT.js} +1 -1
- package/dist/client/assets/{dashboard-Knwc61i1.js → dashboard-y8KVUVF-.js} +1 -1
- package/dist/client/assets/{event-CHpdjYFR.js → event-Cnr9OETn.js} +1 -1
- package/dist/client/assets/{file-explorer-screen-FoYNs9zK.js → file-explorer-screen-C_mYUJsr.js} +1 -1
- package/dist/client/assets/files-CG0jFYdO.js +2 -0
- package/dist/client/assets/follow-up-suggestions-C6RzpstA.js +2 -0
- package/dist/client/assets/{index-CNPHef4O.js → index-3-ASY4Cl.js} +1 -1
- package/dist/client/assets/index-BZxJSF4T.js +3 -0
- package/dist/client/assets/{keyboard-shortcuts-dialog-DP8ptQ7N.js → keyboard-shortcuts-dialog-jm4-DftO.js} +1 -1
- package/dist/client/assets/{main-xPlWrMhO.js → main-CbISK-pm.js} +2 -2
- package/dist/client/assets/{markdown-3Js_RbUp.js → markdown-UD7RzskQ.js} +1 -1
- package/dist/client/assets/memory-BYRJ1l_4.js +2 -0
- package/dist/client/assets/{memory-screen-nzRra2Qi.js → memory-screen-BRsm-Q8A.js} +1 -1
- package/dist/client/assets/{menu-BnSEqetd.js → menu-DRjoHFvG.js} +1 -1
- package/dist/client/assets/{opencami-logo-B_hLbomw.js → opencami-logo-D2mv84sX.js} +1 -1
- package/dist/client/assets/{proxy-BnlGpgC1.js → proxy-DtxqfBHY.js} +1 -1
- package/dist/client/assets/{react-BgjQyJHw.js → react-C_7UlEtd.js} +1 -1
- package/dist/client/assets/{search-dialog-Bib2QY9u.js → search-dialog-lsT8JUtT.js} +1 -1
- package/dist/client/assets/{search-sources-badge-COHcYFRB.js → search-sources-badge-BnqKxoia.js} +1 -1
- package/dist/client/assets/{session-export-dialog-ooPnfHh_.js → session-export-dialog-DHHpvwI8.js} +1 -1
- package/dist/client/assets/settings-dialog-vrd0eJGw.js +1 -0
- package/dist/client/assets/skills-Svd-7oxQ.js +2 -0
- package/dist/client/assets/{skills-panel-D2uMdCHp.js → skills-panel-Dkuo0yyD.js} +1 -1
- package/dist/client/assets/{switch-BUQ0qH6r.js → switch-BYFBYPmi.js} +1 -1
- package/dist/client/assets/{tabs-BEyU6TjN.js → tabs-1jrPkdUE.js} +1 -1
- package/dist/client/assets/{thinking-CA48yhOE.js → thinking-D9BBn5kK.js} +1 -1
- package/dist/client/assets/{tooltip-CcIdgcV0.js → tooltip-DzFgDY86.js} +1 -1
- package/dist/client/assets/{use-file-explorer-state-CN_IJGcd.js → use-file-explorer-state-Dwhw6Mpg.js} +1 -1
- package/dist/client/assets/{useBaseUiId-ClbEYEil.js → useBaseUiId-BdQC9KF3.js} +1 -1
- package/dist/client/assets/{useCompositeItem-B_OxfJee.js → useCompositeItem-BI09zNFD.js} +1 -1
- package/dist/client/assets/{useControlled-CyT-lqbs.js → useControlled-Bc2Emhlx.js} +1 -1
- package/dist/client/assets/{useMutation-eQUrsn-X.js → useMutation-CMp81lDO.js} +1 -1
- package/dist/client/assets/{useOnFirstRender-CR_o2MK_.js → useOnFirstRender-DpB3w0o4.js} +1 -1
- package/dist/client/assets/{useQuery-k6EMRoMD.js → useQuery-_BEWdUe1.js} +1 -1
- package/dist/server/assets/{_sessionKey-CaFqmyhU.js → _sessionKey-COz7RLKC.js} +121 -23
- package/dist/server/assets/_tanstack-start-manifest_v-D0f-0Utn.js +4 -0
- package/dist/server/assets/{connect-CTVBm0Vc.js → connect-sd_NDvQN.js} +1 -1
- package/dist/server/assets/follow-up-suggestions-DRQqO8_S.js +183 -0
- package/dist/server/assets/{index-B_F4DTUu.js → index-197lqzv2.js} +2 -0
- package/dist/server/assets/{index-C7lmufwX.js → index-sXe2QC5V.js} +1 -1
- package/dist/server/assets/{markdown-CFdYXCRQ.js → markdown-Dk1YdosA.js} +1 -1
- package/dist/server/assets/{memory-screen-vqXczcVo.js → memory-screen-DA_o-N1Z.js} +2 -2
- package/dist/server/assets/{memory-rBB015W-.js → memory-woPzJFfs.js} +1 -1
- package/dist/server/assets/{router-X2L0PDPI.js → router-CZhxPkYW.js} +305 -150
- package/dist/server/assets/{search-dialog-CXhofdoP.js → search-dialog-DlvWfq1e.js} +5 -5
- package/dist/server/assets/{settings-dialog-CPdftvjz.js → settings-dialog-BGtrS2RJ.js} +62 -1
- package/dist/server/assets/{thinking-YkRSlXtf.js → thinking-fzwT_aVT.js} +5 -5
- package/dist/server/server.js +2 -2
- package/package.json +1 -1
- package/dist/client/assets/_sessionKey-yNQ57svB.js +0 -23
- package/dist/client/assets/agents-WqWjsymD.js +0 -2
- package/dist/client/assets/bots-DNqiFT7w.js +0 -2
- package/dist/client/assets/files-BtR_gArr.js +0 -2
- package/dist/client/assets/follow-up-suggestions-DVXNLqga.js +0 -5
- package/dist/client/assets/index-CTT0Y1ya.js +0 -3
- package/dist/client/assets/memory-BRGPq5t6.js +0 -2
- package/dist/client/assets/settings-dialog-B8mz99u-.js +0 -1
- package/dist/client/assets/skills-DA9J_tsC.js +0 -2
- package/dist/server/assets/_tanstack-start-manifest_v-P3skSR3R.js +0 -4
- package/dist/server/assets/follow-up-suggestions-DHv2_XzB.js +0 -275
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as t}from"./main-
|
|
1
|
+
import{r as t}from"./main-CbISK-pm.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-CbISK-pm.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,25 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/settings-dialog-vrd0eJGw.js","assets/main-CbISK-pm.js","assets/react-C_7UlEtd.js","assets/button-Bv-7bwZZ.js","assets/use-file-explorer-state-Dwhw6Mpg.js","assets/useOnFirstRender-DpB3w0o4.js","assets/useBaseUiId-BdQC9KF3.js","assets/event-Cnr9OETn.js","assets/visuallyHidden-COI6QeQH.js","assets/composite-DwQIZFe9.js","assets/switch-BYFBYPmi.js","assets/useControlled-Bc2Emhlx.js","assets/tabs-1jrPkdUE.js","assets/useCompositeItem-BI09zNFD.js","assets/DirectionContext-BOL0P_1j.js","assets/CSPContext-CxrBvJ99.js","assets/index-BZxJSF4T.js","assets/session-export-dialog-DHHpvwI8.js","assets/thinking-D9BBn5kK.js","assets/useQuery-_BEWdUe1.js","assets/tooltip-DzFgDY86.js","assets/useMutation-CMp81lDO.js","assets/menu-DRjoHFvG.js","assets/opencami-logo-D2mv84sX.js","assets/proxy-DtxqfBHY.js","assets/markdown-UD7RzskQ.js","assets/index-T4TOjvD0.js","assets/search-sources-badge-BnqKxoia.js","assets/follow-up-suggestions-C6RzpstA.js","assets/keyboard-shortcuts-dialog-jm4-DftO.js","assets/search-dialog-lsT8JUtT.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as o,u as gt,j as n,L as Ye,_ as rt,d as Ut,w as ns,a as rs,z as ss}from"./main-CbISK-pm.js";import{u as Lt}from"./useQuery-_BEWdUe1.js";import{T as Oe,a as Le,b as _e,c as Pe,s as Ge,d as os,g as Tn}from"./tooltip-DzFgDY86.js";import{u as is,c as _,B as be,aa as dn,ae as Qe,t as as,H as re,J as or,V as Ft,ah as ls,ai as cs,aj as us,a as ir,ak as ds,C as fs,al as ms,l as ps,b as et,I as hs,am as gs,a1 as xs,an as en,ao as ys,G as ws,ap as bs,A as Ss,L as vs,N as js,X as ar,x as ks,h as Cs,aq as lr,ar as Es,p as Ns,T as cr,n as ur,as as Rn,at as Ts,au as Rs,av as Is}from"./button-Bv-7bwZZ.js";import{u as dr}from"./useMutation-CMp81lDO.js";import{j as As,k as Ms,l as Ds,m as Os,n as Ls,o as _s,p as Ps,q as $s,r as zs,s as fr,D as Us,a as Fs,b as Ks,c as Hs,d as Ws,u as Xs}from"./use-file-explorer-state-Dwhw6Mpg.js";import{e as mr,a as qe,g as pr,t as Bs,u as $e,f as Ys,n as Gs}from"./useBaseUiId-BdQC9KF3.js";import{u as Vs}from"./useControlled-Bc2Emhlx.js";import{a2 as qs,a3 as Js,a4 as In,t as hr,u as Qs,J as Ie,e as Zs,a as _t}from"./useOnFirstRender-DpB3w0o4.js";import{u as eo,e as to,p as no}from"./event-Cnr9OETn.js";import{u as ro}from"./CSPContext-CxrBvJ99.js";import{u as gr}from"./DirectionContext-BOL0P_1j.js";import{M as fn,a as mn,b as pn,c as nt}from"./menu-DRjoHFvG.js";import{O as so,a as oo}from"./opencami-logo-D2mv84sX.js";import{m as Se,A as De}from"./proxy-DtxqfBHY.js";import{u as hn,p as io}from"./index-BZxJSF4T.js";import{M as ao}from"./markdown-UD7RzskQ.js";import{c as lo}from"./react-C_7UlEtd.js";function tn(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 An=/^Conversation info \(untrusted metadata\):\s*```(?:json)?\s*[\s\S]*?```\s*/,Mn=/^Conversation info \(untrusted metadata\):\s*\{[\s\S]*?\}\s*/,Dn=/^Sender \(untrusted metadata\):\s*```(?:[a-zA-Z0-9_-]+)?\s*[\s\S]*?```\s*/gm,co=/^Sender \(untrusted metadata\):\s*\{[^\n]*\}\s*$/gm,On=/<supermemory-context\b[^>]*>[\s\S]*?<\/supermemory-context>/gi,Ln=/<supermemory-containers\b[^>]*>[\s\S]*?<\/supermemory-containers>/gi,uo=/<workspace-critical-rules\b[^>]*>[\s\S]*?<\/workspace-critical-rules>/gi,fo=/^\[(?:[A-Za-z]{3}\s+)?\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}\s+GMT[+-]?\d+\]\s*/gm,mo=/\n{3,}/g;function xr(e){let t=e;t=t.replace(On,"").replace(Ln,"").replace(uo,"").replace(Dn,"");const r=An.test(t),s=!r&&Mn.test(t);return r?t=t.replace(An,""):s&&(t=t.replace(Mn,"")),t=t.replace(On,"").replace(Ln,"").replace(Dn,"").replace(co,"").replace(fo,"").replace(mo,`
|
|
3
|
+
|
|
4
|
+
`),t.trim()}function po(e){return e.reduce((t,r)=>r?t?/\s$/.test(t)||/^\s/.test(r)?`${t}${r}`:/[([{"'`„“‚‘]$/.test(t)?`${t}${r}`:/^[,.;:!?%\])}"'`]/.test(r)?`${t}${r}`:`${t} ${r}`:r:t,"")}function ve(e){const t=Array.isArray(e.content)?e.content:[],r=po(t.map(s=>s.type==="text"?String(s.text??""):"")).trim();return xr(r)}function Ve(e){return(Array.isArray(e.content)?e.content:[]).filter(r=>r.type==="toolCall")}function ho(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 ht(e){const t=[e.createdAt,e.created_at,e.timestamp,e.time,e.ts];for(const r of t){const s=ho(r);if(s)return s}return Date.now()}const go=["agent:main:main","main"];function nn(e){return go.includes(e)}const xo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function yo(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 xo.test(t)?"webchat":"chat"}return"other"}function wo(e){return Array.isArray(e)?e.map(t=>{const r=typeof t.key=="string"&&t.key.trim().length>0?t.key.trim():tn(t.friendlyId??t.key),s=typeof t.friendlyId=="string"&&t.friendlyId.trim().length>0?t.friendlyId.trim():tn(r),a=yo(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:s,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 Fe(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 bo="Missing gateway auth. Set CLAWDBOT_GATEWAY_TOKEN (recommended) or CLAWDBOT_GATEWAY_PASSWORD in the server environment.";function _n(e){return e.includes(bo)}function Pn(e,t){const r=crypto.randomUUID(),s=`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:s,optimisticMessage:{role:"user",content:i,__optimisticId:s,clientId:r,status:"sending",timestamp:a}}}const xe={sessions:["chat","sessions"],history:function(t,r){return["chat","history",t,r]}};async function So(){const e=await fetch("/api/sessions");if(!e.ok)throw new Error(await Fe(e));const t=await e.json();return wo(t.sessions)}async function vo(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 Fe(r));return await r.json()}async function jo(){const e=new AbortController,t=window.setTimeout(()=>e.abort(),8e3);try{const r=await fetch("/api/ping",{signal:e.signal});if(!r.ok)throw new Error(await Fe(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 gn(e,t,r,s){const a=xe.history(t,r);e.setQueryData(a,function(l){const c=l,u=Array.isArray(c?.messages)?c.messages:[],d=s(u);return{sessionKey:c?.sessionKey??r,sessionId:c?.sessionId,messages:d}})}function lt(e){return typeof e=="string"?e.trim():""}function ko(e,t){const r=lt(e.id),s=lt(t.id);if(r&&s)return r===s;const a=lt(e.clientId),i=lt(t.clientId);if(a&&i)return a===i;const l=lt(e.__optimisticId),c=lt(t.__optimisticId);return l&&c?l===c:!1}function Wt(e,t,r,s){gn(e,t,r,function(i){return i.some(l=>ko(l,s))?i:[...i,s]})}function Co(e,t,r,s,a){const i=`opt-${s}`;gn(e,t,r,function(c){return c.map(u=>u.clientId===s||u.__optimisticId===s||u.__optimisticId===i?a(u):u)})}function Xt(e,t,r,s,a){gn(e,t,r,function(l){return l.filter(c=>!(c.clientId===s||c.__optimisticId===s||a&&c.__optimisticId===a))})}function rn(e,t,r){const s=xe.history(t,r);e.setQueryData(s,{sessionKey:r,messages:[]})}function Eo(e,t,r,s,a){const i=xe.history(t,r),l=xe.history(s,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 No(e,t,r,s){e.setQueryData(xe.sessions,function(i){return Array.isArray(i)?i.map(l=>l.key!==t&&l.friendlyId!==r?l:{...l,lastMessage:s}):i})}function To(e,t,r){e.setQueryData(xe.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 Ro(e,t,r,s){e.setQueryData(xe.sessions,function(i){return Array.isArray(i)?i.map(l=>l.key===t||l.friendlyId===r?{...l,label:s}:l):i});try{const a=await fetch("/api/sessions",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionKey:t,friendlyId:r,label:s})});if(!a.ok){const i=await Fe(a);console.error("[updateSessionLabel] Failed to persist:",i);return}await e.invalidateQueries({queryKey:xe.sessions})}catch(a){console.error("[updateSessionLabel] Network error:",a)}}function Io(){const[e,t]=o.useState(!1),[r,s]=o.useState(!1),[a,i]=o.useState(null),[l,c]=o.useState(null),u=o.useCallback(async()=>{if(t(!0),i(null),!(r||l)){s(!0);try{const m=await fetch("/api/paths");if(!m.ok)throw new Error(await Fe(m));const b=await m.json();c({agentId:String(b.agentId??"main"),stateDir:String(b.stateDir??""),sessionsDir:String(b.sessionsDir??""),storePath:String(b.storePath??"")})}catch(m){i(m instanceof Error?m.message:String(m))}finally{s(!1)}}},[l,r]),d=o.useCallback(()=>{u()},[u]),f=o.useCallback(()=>{t(!1)},[]),h=o.useCallback(()=>{if(l?.sessionsDir)try{navigator.clipboard.writeText(l.sessionsDir)}catch{}},[l]),p=o.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:h,copyStorePath:p}}let Te=null,xn=!1,Dt=null;function Ao(e){Te=e}function Bt(){return Te!==null}function St(e){xn=e}function Yt(){return xn}function Pt(){Te=null,xn=!1}function Mo(e,t){if(Te){if(e&&Te.sessionKey===e){Pt();return}t&&Te.friendlyId===t&&Pt()}}function Do(e){Dt={friendlyId:e,at:Date.now()}}function yr(e,t=15e3){return!(!Dt||Dt.friendlyId!==e||Date.now()-Dt.at>t)}function Oo(e,t){if(!Te)return null;if(e&&Te.sessionKey===e){const r=Te;return Te=null,r}if(t&&Te.friendlyId===t){const r=Te;return Te=null,r}return null}const Lo=8e3,tt=new Map;function _o(e){e&&tt.set(e,{id:e,expiresAt:Date.now()+Lo})}function Po(e){e&&tt.delete(e)}function $o(e){if(tt.size===0)return e;const t=Date.now();let r=!1;const s=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?s:e}function zo(){const e=gt(),[t,r]=o.useState(!1),[s,a]=o.useState(null),i=dr({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 Fe(f));return u},onMutate:async function(u){a(null),_o(u.sessionKey||u.friendlyId),Mo(u.sessionKey,u.friendlyId),await e.cancelQueries({queryKey:xe.sessions});const d=e.getQueryData(xe.sessions);return To(e,u.sessionKey,u.friendlyId),u.isActive&&(u.sessionKey||u.friendlyId)&&rn(e,u.friendlyId||u.sessionKey,u.sessionKey||u.friendlyId),{previousSessions:d,isActive:u.isActive}},onError:function(u,d,f){f?.previousSessions&&e.setQueryData(xe.sessions,f.previousSessions),Po(d.sessionKey||d.friendlyId),a(u instanceof Error?u.message:String(u))},onSuccess:function(u){u.isActive&&Pt(),e.invalidateQueries({queryKey:xe.sessions})},onSettled:function(){r(!1)}});return{deleteSession:o.useCallback(async(c,u,d)=>{!c&&!u||(r(!0),await i.mutateAsync({sessionKey:c,friendlyId:u,isActive:d}))},[i]),deleting:t,error:s}}function Uo(){const e=gt(),[t,r]=o.useState(!1),[s,a]=o.useState(null),i=dr({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 Fe(d));return u},onMutate:async function(u){a(null),await e.cancelQueries({queryKey:xe.sessions});const d=e.getQueryData(xe.sessions);return e.setQueryData(xe.sessions,function(h){return Array.isArray(h)?h.map(p=>p.key!==u.sessionKey?p:{...p,label:u.newTitle,title:u.newTitle}):h}),{previousSessions:d}},onError:function(u,d,f){f?.previousSessions&&e.setQueryData(xe.sessions,f.previousSessions),a(u instanceof Error?u.message:String(u))},onSuccess:function(){e.invalidateQueries({queryKey:xe.sessions})},onSettled:function(){r(!1)}});return{renameSession:o.useCallback(async(c,u)=>{!c||!u.trim()||(r(!0),await i.mutateAsync({sessionKey:c,newTitle:u.trim()}))},[i]),renaming:t,error:s}}function wr(e){return!e.content||!Array.isArray(e.content)?"":e.content.filter(t=>t.type==="text").map(t=>t.text||"").join(`
|
|
5
|
+
`)}function Fo(e,t,r){const s=[];s.push(`# Conversation: ${e}`),s.push(`Date: ${r.toLocaleString()}`),s.push("");for(const a of t){const i=a.role||"unknown",l=wr(a);if(l){const c=i==="user"?"User":"Assistant";s.push(`## ${c}`),s.push(""),s.push(l),s.push("")}}return s.join(`
|
|
6
|
+
`)}function Ko(e,t,r){const s={title:e,exportDate:r.toISOString(),messages:t.map(a=>({role:a.role,content:a.content,timestamp:a.timestamp}))};return JSON.stringify(s,null,2)}function Ho(e,t,r){const s=[];s.push(`Conversation: ${e}`),s.push(`Date: ${r.toLocaleString()}`),s.push("─".repeat(60)),s.push("");for(const a of t){const i=a.role||"unknown",l=wr(a);if(l){const c=i==="user"?"User":"Assistant";s.push(`${c}:`),s.push(l),s.push("")}}return s.join(`
|
|
7
|
+
`)}function Wo(e,t,r){const s=new Date;let a,i,l;switch(r){case"markdown":a=Fo(e,t,s),i=`${Gt(e)}.md`,l="text/markdown";break;case"json":a=Ko(e,t,s),i=`${Gt(e)}.json`,l="application/json";break;case"txt":a=Ho(e,t,s),i=`${Gt(e)}.txt`,l="text/plain";break;default:throw new Error(`Unsupported format: ${r}`)}Xo(a,i,l)}function Gt(e){return e.replace(/[^a-z0-9-_\s]/gi,"").replace(/\s+/g,"-").toLowerCase().slice(0,50)||"conversation"}function Xo(e,t,r){const s=new Blob([e],{type:r}),a=URL.createObjectURL(s),i=document.createElement("a");i.href=a,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(a)}function Bo(e){const{children:t,open:r,defaultOpen:s=!1,onOpenChange:a,onOpenChangeComplete:i,actionsRef:l,handle:c,triggerId:u,defaultTriggerId:d=null}=e,f=As(),h=!!f,p=is(()=>c?.store??new Ms({open:s,openProp:r,activeTriggerId:d,triggerIdProp:u,modal:!0,disablePointerDismissal:!0,nested:h,role:"alertdialog"})).current;p.useControlledProp("openProp",r),p.useControlledProp("triggerIdProp",u),p.useSyncedValue("nested",h),p.useContextCallback("onOpenChange",a),p.useContextCallback("onOpenChangeComplete",i);const m=p.useState("payload");Ds({store:p,actionsRef:l,parentContext:f?.store.context});const b=o.useMemo(()=>({store:p}),[p]);return n.jsx(Os.Provider,{value:b,children:typeof t=="function"?t({payload:m}):t})}function Yo({children:e,...t}){return n.jsx(Bo,{...t,children:e})}function Go({className:e,children:t}){return n.jsxs(Ls,{children:[n.jsx(_s,{className:"fixed inset-0 bg-primary-950/20 transition-all duration-150 data-[state=open]:opacity-100 data-[state=closed]:opacity-0"}),n.jsx(Ps,{className:_("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 Vo({className:e,...t}){return n.jsx($s,{className:_("text-lg font-medium text-primary-900",e),...t})}function qo({className:e,...t}){return n.jsx(zs,{className:_("text-sm text-primary-600",e),...t})}function Jo({className:e,...t}){return n.jsx(fr,{render:n.jsx(be,{variant:"outline",className:_(e)}),...t})}function Qo({className:e,...t}){return n.jsx(fr,{render:n.jsx(be,{variant:"destructive",className:_(e)}),...t})}function Zo({open:e,onOpenChange:t,sessionTitle:r,onConfirm:s,onCancel:a}){return n.jsx(Yo,{open:e,onOpenChange:t,children:n.jsx(Go,{children:n.jsxs("div",{className:"p-4",children:[n.jsx(Vo,{className:"mb-1",children:"Delete Session"}),n.jsxs(qo,{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(Jo,{onClick:a,children:"Cancel"}),n.jsx(Qo,{onClick:s,children:"Delete"})]})]})})})}function ei({open:e,onOpenChange:t,sessionTitle:r,onSave:s,onCancel:a}){return n.jsx(Us,{open:e,onOpenChange:t,children:n.jsx(Fs,{children:n.jsxs("div",{className:"p-4",children:[n.jsx(Ks,{className:"mb-1",children:"Rename"}),n.jsx(Hs,{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(),s(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(Ws,{onClick:a,children:"Cancel"}),n.jsx(be,{onClick:i=>{const l=i.currentTarget.parentElement?.previousElementSibling;s(l.value)},children:"Save"})]})]})})})}function ti(e){const{open:t,defaultOpen:r,onOpenChange:s,disabled:a}=e,i=t!==void 0,[l,c]=Vs({controlled:t,default:r,name:"Collapsible",state:"open"}),{mounted:u,setMounted:d,transitionStatus:f}=qs(l,!0,!0),[h,p]=o.useState(l),[{height:m,width:b},g]=o.useState({height:void 0,width:void 0}),v=mr(),[w,x]=o.useState(),z=w??v,[I,W]=o.useState(!1),[L,ee]=o.useState(!1),X=o.useRef(null),A=o.useRef(null),te=o.useRef(null),B=o.useRef(null),E=Js(B,!1),D=qe(N=>{const j=!l,k=pr(Bs,N.nativeEvent);if(s(j,k),k.isCanceled)return;const O=B.current;A.current==="css-animation"&&O!=null&&O.style.removeProperty("animation-name"),!I&&!L&&(A.current!=null&&A.current!=="css-animation"&&!u&&j&&d(!0),A.current==="css-animation"&&(!h&&j&&p(!0),!u&&j&&d(!0))),c(j),A.current==="none"&&u&&!j&&d(!1)});return $e(()=>{i&&A.current==="none"&&!L&&!l&&d(!1)},[i,L,l,t,d]),o.useMemo(()=>({abortControllerRef:X,animationTypeRef:A,disabled:a,handleTrigger:D,height:m,mounted:u,open:l,panelId:z,panelRef:B,runOnceAnimationsFinish:E,setDimensions:g,setHiddenUntilFound:W,setKeepMounted:ee,setMounted:d,setOpen:c,setPanelIdState:x,setVisible:p,transitionDimensionRef:te,transitionStatus:f,visible:h,width:b}),[X,A,a,D,m,u,l,z,B,E,g,W,ee,d,c,p,te,f,h,b])}const br=o.createContext(void 0);function Sr(){const e=o.useContext(br);if(e===void 0)throw new Error(dn(15));return e}let vt=(function(e){return e.open="data-open",e.closed="data-closed",e[e.startingStyle=In.startingStyle]="startingStyle",e[e.endingStyle=In.endingStyle]="endingStyle",e})({}),ni=(function(e){return e.panelOpen="data-panel-open",e})({});const ri={[vt.open]:""},si={[vt.closed]:""},oi={open(e){return e?{[ni.panelOpen]:""}:null}},ii={open(e){return e?ri:si}},vr={...ii,...hr},ai=o.forwardRef(function(t,r){const{render:s,className:a,defaultOpen:i=!1,disabled:l=!1,onOpenChange:c,open:u,...d}=t,f=qe(c),h=ti({open:u,defaultOpen:i,onOpenChange:f,disabled:l}),p=o.useMemo(()=>({open:h.open,disabled:h.disabled,transitionStatus:h.transitionStatus}),[h.open,h.disabled,h.transitionStatus]),m=o.useMemo(()=>({...h,onOpenChange:f,state:p}),[h,f,p]),b=Qe("div",t,{state:p,ref:r,props:d,stateAttributesMapping:vr});return n.jsx(br.Provider,{value:m,children:b})}),li={...oi,...hr},ci=o.forwardRef(function(t,r){const{panelId:s,open:a,handleTrigger:i,state:l,disabled:c}=Sr(),{className:u,disabled:d=c,id:f,render:h,nativeButton:p=!0,...m}=t,{getButtonProps:b,buttonRef:g}=Ys({disabled:d,focusableWhenDisabled:!0,native:p}),v=o.useMemo(()=>({"aria-controls":a?s:void 0,"aria-expanded":a,onClick:i}),[s,a,i]);return Qe("button",t,{state:l,ref:[r,g],props:[v,m,b],stateAttributesMapping:li})});let ui=(function(e){return e.disabled="data-disabled",e.orientation="data-orientation",e})({});function di(e){const{abortControllerRef:t,animationTypeRef:r,externalRef:s,height:a,hiddenUntilFound:i,keepMounted:l,id:c,mounted:u,onOpenChange:d,open:f,panelRef:h,runOnceAnimationsFinish:p,setDimensions:m,setMounted:b,setOpen:g,setVisible:v,transitionDimensionRef:w,visible:x,width:z}=e,I=o.useRef(!1),W=o.useRef(null),L=o.useRef(f),ee=o.useRef(f),X=Qs(),A=o.useMemo(()=>r.current==="css-animation"?!x:!f&&!u,[f,u,x,r]),te=qe(E=>{if(!E)return;if(r.current==null||w.current==null){const j=getComputedStyle(E),k=j.animationName!=="none"&&j.animationName!=="",O=j.transitionDuration!=="0s"&&j.transitionDuration!=="";k&&O||(j.animationName==="none"&&j.transitionDuration!=="0s"?r.current="css-transition":j.animationName!=="none"&&j.transitionDuration==="0s"?r.current="css-animation":r.current="none"),E.getAttribute(ui.orientation)==="horizontal"||j.transitionProperty.indexOf("width")>-1?w.current="width":w.current="height"}if(r.current!=="css-transition")return;(a===void 0||z===void 0)&&(m({height:E.scrollHeight,width:E.scrollWidth}),ee.current&&E.style.setProperty("transition-duration","0s"));let D=-1,N=-1;return D=Ie.request(()=>{ee.current=!1,N=Ie.request(()=>{setTimeout(()=>{E.style.removeProperty("transition-duration")})})}),()=>{Ie.cancel(D),Ie.cancel(N)}}),B=as(s,h,te);return $e(()=>{if(r.current!=="css-transition")return;const E=h.current;if(!E)return;let D=-1;if(t.current!=null&&(t.current.abort(),t.current=null),f){const N={"justify-content":E.style.justifyContent,"align-items":E.style.alignItems,"align-content":E.style.alignContent,"justify-items":E.style.justifyItems};Object.keys(N).forEach(j=>{E.style.setProperty(j,"initial","important")}),!ee.current&&!l&&E.setAttribute(vt.startingStyle,""),m({height:E.scrollHeight,width:E.scrollWidth}),D=Ie.request(()=>{Object.entries(N).forEach(([j,k])=>{k===""?E.style.removeProperty(j):E.style.setProperty(j,k)})})}else{if(E.scrollHeight===0&&E.scrollWidth===0)return;m({height:E.scrollHeight,width:E.scrollWidth});const N=new AbortController;t.current=N;const j=N.signal;let k=null;const O=vt.endingStyle;return k=new MutationObserver(Z=>{Z.some(M=>M.type==="attributes"&&M.attributeName===O)&&(k?.disconnect(),k=null,p(()=>{m({height:0,width:0}),E.style.removeProperty("content-visibility"),b(!1),t.current===N&&(t.current=null)},j))}),k.observe(E,{attributes:!0,attributeFilter:[O]}),()=>{k?.disconnect(),X.cancel(),t.current===N&&(N.abort(),t.current=null)}}return()=>{Ie.cancel(D)}},[t,r,X,i,l,u,f,h,p,m,b]),$e(()=>{if(r.current!=="css-animation")return;const E=h.current;E&&(W.current=E.style.animationName||W.current,E.style.setProperty("animation-name","none"),m({height:E.scrollHeight,width:E.scrollWidth}),!L.current&&!I.current&&E.style.removeProperty("animation-name"),f?(t.current!=null&&(t.current.abort(),t.current=null),b(!0),v(!0)):(t.current=new AbortController,p(()=>{b(!1),v(!1),t.current=null},t.current.signal)))},[t,r,f,h,p,m,b,v,x]),eo(()=>{const E=Ie.request(()=>{L.current=!1});return()=>Ie.cancel(E)}),$e(()=>{if(!i)return;const E=h.current;if(!E)return;let D=-1,N=-1;return f&&I.current&&(E.style.transitionDuration="0s",m({height:E.scrollHeight,width:E.scrollWidth}),D=Ie.request(()=>{I.current=!1,N=Ie.request(()=>{setTimeout(()=>{E.style.removeProperty("transition-duration")})})})),()=>{Ie.cancel(D),Ie.cancel(N)}},[i,f,h,m]),$e(()=>{const E=h.current;E&&i&&A&&(E.setAttribute("hidden","until-found"),r.current==="css-transition"&&E.setAttribute(vt.startingStyle,""))},[i,A,r,h]),o.useEffect(function(){const D=h.current;if(!D)return;function N(j){I.current=!0,g(!0),d(!0,pr(Gs,j))}return D.addEventListener("beforematch",N),()=>{D.removeEventListener("beforematch",N)}},[d,h,g]),o.useMemo(()=>({props:{hidden:A,id:c,ref:B}}),[A,c,B])}let $n=(function(e){return e.collapsiblePanelHeight="--collapsible-panel-height",e.collapsiblePanelWidth="--collapsible-panel-width",e})({});const fi=o.forwardRef(function(t,r){const{className:s,hiddenUntilFound:a,keepMounted:i,render:l,id:c,...u}=t,{abortControllerRef:d,animationTypeRef:f,height:h,mounted:p,onOpenChange:m,open:b,panelId:g,panelRef:v,runOnceAnimationsFinish:w,setDimensions:x,setHiddenUntilFound:z,setKeepMounted:I,setMounted:W,setPanelIdState:L,setOpen:ee,setVisible:X,state:A,transitionDimensionRef:te,visible:B,width:E,transitionStatus:D}=Sr(),N=a??!1,j=i??!1;$e(()=>{if(c)return L(c),()=>{L(void 0)}},[c,L]),$e(()=>{z(N)},[z,N]),$e(()=>{I(j)},[I,j]);const{props:k}=di({abortControllerRef:d,animationTypeRef:f,externalRef:r,height:h,hiddenUntilFound:N,id:g,keepMounted:j,mounted:p,onOpenChange:m,open:b,panelRef:v,runOnceAnimationsFinish:w,setDimensions:x,setMounted:W,setOpen:ee,setVisible:X,transitionDimensionRef:te,visible:B,width:E});Zs({open:b&&D==="idle",ref:v,onComplete(){b&&x({height:void 0,width:void 0})}});const O=o.useMemo(()=>({...A,transitionStatus:D}),[A,D]),Z=Qe("div",t,{state:O,ref:[r,v],props:[k,{style:{[$n.collapsiblePanelHeight]:h===void 0?"auto":`${h}px`,[$n.collapsiblePanelWidth]:E===void 0?"auto":`${E}px`}},u],stateAttributesMapping:vr});return j||N||!j&&p?Z:null});function sn(e){return n.jsx(ai,{...e})}function on({className:e,...t}){return n.jsx(ci,{className:_("group inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-left text-xs font-medium text-primary-500 transition-colors hover:bg-primary-100 hover:text-primary-700 data-panel-open:text-primary-700",e),...t})}function an({className:e,contentClassName:t,children:r,...s}){return n.jsx(fi,{className:_('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),...s,children:n.jsx("div",{className:_("pt-1",t),children:r})})}const jr=o.createContext(void 0);function Kt(){const e=o.useContext(jr);if(e===void 0)throw new Error(dn(53));return e}let $t=(function(e){return e.scrollAreaCornerHeight="--scroll-area-corner-height",e.scrollAreaCornerWidth="--scroll-area-corner-width",e})({});const Rt=500,zn=16;function Ae(e,t,r){if(!e)return 0;const s=getComputedStyle(e),a=r==="x"?"Inline":"Block";return r==="x"&&t==="margin"?parseFloat(s[`${t}InlineStart`])*2:parseFloat(s[`${t}${a}Start`])+parseFloat(s[`${t}${a}End`])}let mi=(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 It="base-ui-disable-scrollbar",kr={className:It,getElement(e){return n.jsx("style",{nonce:e,href:It,precedence:"base-ui:low",children:`.${It}{scrollbar-width:none}.${It}::-webkit-scrollbar{display:none}`})}};let ct=(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 yn={hasOverflowX:e=>e?{[ct.hasOverflowX]:""}:null,hasOverflowY:e=>e?{[ct.hasOverflowY]:""}:null,overflowXStart:e=>e?{[ct.overflowXStart]:""}:null,overflowXEnd:e=>e?{[ct.overflowXEnd]:""}:null,overflowYStart:e=>e?{[ct.overflowYStart]:""}:null,overflowYEnd:e=>e?{[ct.overflowYEnd]:""}:null,cornerHidden:()=>null},pi={x:0,y:0},Un={width:0,height:0},hi={xStart:!1,xEnd:!1,yStart:!1,yEnd:!1},gi={x:!1,y:!1,corner:!1},xi=o.forwardRef(function(t,r){const{render:s,className:a,overflowEdgeThreshold:i,...l}=t,c=yi(i),u=mr(),d=_t(),f=_t(),{nonce:h,disableStyleElements:p}=ro(),[m,b]=o.useState(!1),[g,v]=o.useState(!1),[w,x]=o.useState(!1),[z,I]=o.useState(!1),[W,L]=o.useState(Un),[ee,X]=o.useState(Un),[A,te]=o.useState(hi),[B,E]=o.useState(gi),D=o.useRef(null),N=o.useRef(null),j=o.useRef(null),k=o.useRef(null),O=o.useRef(null),Z=o.useRef(null),S=o.useRef(null),M=o.useRef(!1),U=o.useRef(0),Y=o.useRef(0),ie=o.useRef(0),we=o.useRef(0),T=o.useRef("vertical"),F=o.useRef(pi),K=qe($=>{const P=$.x-F.current.x,je=$.y-F.current.y;F.current=$,je!==0&&(x(!0),d.start(Rt,()=>{x(!1)})),P!==0&&(v(!0),f.start(Rt,()=>{v(!1)}))}),q=qe($=>{$.button===0&&(M.current=!0,U.current=$.clientY,Y.current=$.clientX,T.current=$.currentTarget.getAttribute(mi.orientation),N.current&&(ie.current=N.current.scrollTop,we.current=N.current.scrollLeft),O.current&&T.current==="vertical"&&O.current.setPointerCapture($.pointerId),Z.current&&T.current==="horizontal"&&Z.current.setPointerCapture($.pointerId))}),pe=qe($=>{if(!M.current)return;const P=$.clientY-U.current,je=$.clientX-Y.current;if(N.current){const ke=N.current.scrollHeight,He=N.current.clientHeight,R=N.current.scrollWidth,V=N.current.clientWidth;if(O.current&&j.current&&T.current==="vertical"){const H=Ae(j.current,"padding","y"),he=Ae(O.current,"margin","y"),oe=O.current.offsetHeight,ce=j.current.offsetHeight-oe-H-he,Re=P/ce;N.current.scrollTop=ie.current+Re*(ke-He),$.preventDefault(),x(!0),d.start(Rt,()=>{x(!1)})}if(Z.current&&k.current&&T.current==="horizontal"){const H=Ae(k.current,"padding","x"),he=Ae(Z.current,"margin","x"),oe=Z.current.offsetWidth,ce=k.current.offsetWidth-oe-H-he,Re=je/ce;N.current.scrollLeft=we.current+Re*(R-V),$.preventDefault(),v(!0),f.start(Rt,()=>{v(!1)})}}}),G=qe($=>{M.current=!1,O.current&&T.current==="vertical"&&O.current.releasePointerCapture($.pointerId),Z.current&&T.current==="horizontal"&&Z.current.releasePointerCapture($.pointerId)});function J($){I($.pointerType==="touch")}function ne($){if(J($),$.pointerType!=="touch"){const P=to(D.current,$.target);b(P)}}const ge=o.useMemo(()=>({scrolling:g||w,hasOverflowX:!B.x,hasOverflowY:!B.y,overflowXStart:A.xStart,overflowXEnd:A.xEnd,overflowYStart:A.yStart,overflowYEnd:A.yEnd,cornerHidden:B.corner}),[g,w,B.x,B.y,B.corner,A]),de={role:"presentation",onPointerEnter:ne,onPointerMove:ne,onPointerDown:J,onPointerLeave(){b(!1)},style:{position:"relative",[$t.scrollAreaCornerHeight]:`${W.height}px`,[$t.scrollAreaCornerWidth]:`${W.width}px`}},se=Qe("div",t,{state:ge,ref:[r,D],props:[de,l],stateAttributesMapping:yn}),le=o.useMemo(()=>({handlePointerDown:q,handlePointerMove:pe,handlePointerUp:G,handleScroll:K,cornerSize:W,setCornerSize:L,thumbSize:ee,setThumbSize:X,touchModality:z,cornerRef:S,scrollingX:g,setScrollingX:v,scrollingY:w,setScrollingY:x,hovering:m,setHovering:b,viewportRef:N,rootRef:D,scrollbarYRef:j,scrollbarXRef:k,thumbYRef:O,thumbXRef:Z,rootId:u,hiddenState:B,setHiddenState:E,overflowEdges:A,setOverflowEdges:te,viewportState:ge,overflowEdgeThreshold:c}),[q,pe,G,K,W,ee,z,g,v,w,x,m,b,u,B,A,ge,c]);return n.jsxs(jr.Provider,{value:le,children:[!p&&kr.getElement(h),se]})});function yi(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 wi=o.createContext(void 0);function dt(e,t=Number.MIN_SAFE_INTEGER,r=Number.MAX_SAFE_INTEGER){return Math.max(t,Math.min(e,r))}function bi(e,t){if(typeof IntersectionObserver>"u")return()=>{};const r=new IntersectionObserver(s=>{s.forEach(a=>{a.intersectionRatio>0&&(t(),r.disconnect())})});return r.observe(e),()=>{r.disconnect()}}let Je=(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 Fn=1;function Kn(e,t){if(t<=0)return 0;const r=dt(e,0,t),s=r,a=t-r,i=s<=Fn,l=a<=Fn;return i&&l?s<=a?0:t:i?0:l?t:r}let Hn=!1;function Si(){Hn||no||(typeof CSS<"u"&&"registerProperty"in CSS&&[Je.scrollAreaOverflowXStart,Je.scrollAreaOverflowXEnd,Je.scrollAreaOverflowYStart,Je.scrollAreaOverflowYEnd].forEach(e=>{try{CSS.registerProperty({name:e,syntax:"<length>",inherits:!1,initialValue:"0px"})}catch{}}),Hn=!0)}const vi=o.forwardRef(function(t,r){const{render:s,className:a,...i}=t,{viewportRef:l,scrollbarYRef:c,scrollbarXRef:u,thumbYRef:d,thumbXRef:f,cornerRef:h,cornerSize:p,setCornerSize:m,setThumbSize:b,rootId:g,setHiddenState:v,hiddenState:w,handleScroll:x,setHovering:z,setOverflowEdges:I,overflowEdges:W,overflowEdgeThreshold:L,scrollingX:ee,scrollingY:X}=Kt(),A=gr(),te=o.useRef(!0),B=_t(),E=_t(),D=qe(()=>{const S=l.current,M=c.current,U=u.current,Y=d.current,ie=f.current,we=h.current;if(!S)return;const T=S.scrollHeight,F=S.scrollWidth,K=S.clientHeight,q=S.clientWidth,pe=S.scrollTop,G=S.scrollLeft;if(T===0||F===0)return;const J=K>=T,ne=q>=F,ge=q/F,de=K/T,se=Math.max(0,F-q),le=Math.max(0,T-K);let $=0,P=0;if(!ne){let Q=0;A==="rtl"?Q=dt(-G,0,se):Q=dt(G,0,se),$=Kn(Q,se),P=se-$}const je=J?0:dt(pe,0,le),ke=J?0:Kn(je,le),He=J?0:le-ke,R=ne?0:q,V=J?0:K;let H=0,he=0;!ne&&!J&&(H=M?.offsetWidth||0,he=U?.offsetHeight||0);const oe=p.width===0&&p.height===0,ce=oe?H:0,Re=oe?he:0,st=Ae(U,"padding","x"),Me=Ae(M,"padding","y"),ze=Ae(ie,"margin","x"),Ke=Ae(Y,"margin","y"),kt=R-st-ze,xt=V-Me-Ke,Ct=U?Math.min(U.offsetWidth-ce,kt):kt,Et=M?Math.min(M.offsetHeight-Re,xt):xt,yt=Math.max(zn,Ct*ge),wt=Math.max(zn,Et*de);if(b(Q=>Q.height===wt&&Q.width===yt?Q:{width:yt,height:wt}),M&&Y){const Q=M.offsetHeight-wt-Me-Ke,Ce=T-K,Ze=Ce===0?0:pe/Ce,Xe=Math.min(Q,Math.max(0,Ze*Q));Y.style.transform=`translate3d(0,${Xe}px,0)`}if(U&&ie){const Q=U.offsetWidth-yt-st-ze,Ce=F-q,Ze=Ce===0?0:G/Ce,Xe=A==="rtl"?dt(Ze*Q,-Q,0):dt(Ze*Q,0,Q);ie.style.transform=`translate3d(${Xe}px,0,0)`}const Nt=[[Je.scrollAreaOverflowXStart,$],[Je.scrollAreaOverflowXEnd,P],[Je.scrollAreaOverflowYStart,ke],[Je.scrollAreaOverflowYEnd,He]];for(const[Q,Ce]of Nt)S.style.setProperty(Q,`${Ce}px`);we&&(ne||J?m({width:0,height:0}):!ne&&!J&&m({width:H,height:he})),v(Q=>{const Ce=J||ne;return Q.y===J&&Q.x===ne&&Q.corner===Ce?Q:{y:J,x:ne,corner:Ce}});const We={xStart:!ne&&$>L.xStart,xEnd:!ne&&P>L.xEnd,yStart:!J&&ke>L.yStart,yEnd:!J&&He>L.yEnd};I(Q=>Q.xStart===We.xStart&&Q.xEnd===We.xEnd&&Q.yStart===We.yStart&&Q.yEnd===We.yEnd?Q:We)});$e(()=>{if(!l.current)return;Si();let S=!1;return bi(l.current,()=>{if(!S){S=!0;return}D()})},[D,l]),$e(()=>{queueMicrotask(D)},[D,w,A]),$e(()=>{l.current?.matches(":hover")&&z(!0)},[l,z]),o.useEffect(()=>{const S=l.current;if(typeof ResizeObserver>"u"||!S)return;let M=!1;const U=new ResizeObserver(()=>{if(!M){M=!0;return}D()});return U.observe(S),E.start(0,()=>{const Y=S.getAnimations({subtree:!0});Y.length!==0&&Promise.allSettled(Y.map(ie=>ie.finished)).then(D).catch(()=>{})}),()=>{U.disconnect(),E.clear()}},[D,l,E]);function N(){te.current=!1}const j={role:"presentation",...g&&{"data-id":`${g}-viewport`},...(!w.x||!w.y)&&{tabIndex:0},className:kr.className,style:{overflow:"scroll"},onScroll(){l.current&&(D(),te.current||x({x:l.current.scrollLeft,y:l.current.scrollTop}),B.start(100,()=>{te.current=!0}))},onWheel:N,onTouchMove:N,onPointerMove:N,onPointerEnter:N,onKeyDown:N},k=o.useMemo(()=>({scrolling:ee||X,hasOverflowX:!w.x,hasOverflowY:!w.y,overflowXStart:W.xStart,overflowXEnd:W.xEnd,overflowYStart:W.yStart,overflowYEnd:W.yEnd,cornerHidden:w.corner}),[ee,X,w.x,w.y,w.corner,W]),O=Qe("div",t,{ref:[r,l],state:k,props:[j,i],stateAttributesMapping:yn}),Z=o.useMemo(()=>({computeThumbPosition:D}),[D]);return n.jsx(wi.Provider,{value:Z,children:O})}),Cr=o.createContext(void 0);function ji(){const e=o.useContext(Cr);if(e===void 0)throw new Error(dn(54));return e}let zt=(function(e){return e.scrollAreaThumbHeight="--scroll-area-thumb-height",e.scrollAreaThumbWidth="--scroll-area-thumb-width",e})({});const ki=o.forwardRef(function(t,r){const{render:s,className:a,orientation:i="vertical",keepMounted:l=!1,...c}=t,{hovering:u,scrollingX:d,scrollingY:f,hiddenState:h,overflowEdges:p,scrollbarYRef:m,scrollbarXRef:b,viewportRef:g,thumbYRef:v,thumbXRef:w,handlePointerDown:x,handlePointerUp:z,rootId:I,thumbSize:W}=Kt(),L={hovering:u,scrolling:{horizontal:d,vertical:f}[i],orientation:i,hasOverflowX:!h.x,hasOverflowY:!h.y,overflowXStart:p.xStart,overflowXEnd:p.xEnd,overflowYStart:p.yStart,overflowYEnd:p.yEnd,cornerHidden:h.corner},ee=gr();o.useEffect(()=>{const D=g.current,N=i==="vertical"?m.current:b.current;if(!N)return;function j(k){if(!(!D||!N||k.ctrlKey)){if(k.preventDefault(),i==="vertical"){if(D.scrollTop===0&&k.deltaY<0)return}else if(D.scrollLeft===0&&k.deltaX<0)return;if(i==="vertical"){if(D.scrollTop===D.scrollHeight-D.clientHeight&&k.deltaY>0)return}else if(D.scrollLeft===D.scrollWidth-D.clientWidth&&k.deltaX>0)return;i==="vertical"?D.scrollTop+=k.deltaY:D.scrollLeft+=k.deltaX}}return N.addEventListener("wheel",j,{passive:!1}),()=>{N.removeEventListener("wheel",j)}},[i,b,m,g]);const X={...I&&{"data-id":`${I}-scrollbar`},onPointerDown(D){if(D.button===0&&D.currentTarget===D.target&&g.current){if(v.current&&m.current&&i==="vertical"){const N=Ae(v.current,"margin","y"),j=Ae(m.current,"padding","y"),k=v.current.offsetHeight,O=m.current.getBoundingClientRect(),Z=D.clientY-O.top-k/2-j+N/2,S=g.current.scrollHeight,M=g.current.clientHeight,U=m.current.offsetHeight-k-j-N,ie=Z/U*(S-M);g.current.scrollTop=ie}if(w.current&&b.current&&i==="horizontal"){const N=Ae(w.current,"margin","x"),j=Ae(b.current,"padding","x"),k=w.current.offsetWidth,O=b.current.getBoundingClientRect(),Z=D.clientX-O.left-k/2-j+N/2,S=g.current.scrollWidth,M=g.current.clientWidth,U=b.current.offsetWidth-k-j-N,Y=Z/U;let ie;ee==="rtl"?(ie=(1-Y)*(S-M),g.current.scrollLeft<=0&&(ie=-ie)):ie=Y*(S-M),g.current.scrollLeft=ie}x(D)}},onPointerUp:z,style:{position:"absolute",touchAction:"none",WebkitUserSelect:"none",userSelect:"none",...i==="vertical"&&{top:0,bottom:`var(${$t.scrollAreaCornerHeight})`,insetInlineEnd:0,[zt.scrollAreaThumbHeight]:`${W.height}px`},...i==="horizontal"&&{insetInlineStart:0,insetInlineEnd:`var(${$t.scrollAreaCornerWidth})`,bottom:0,[zt.scrollAreaThumbWidth]:`${W.width}px`}}},A=Qe("div",t,{ref:[r,i==="vertical"?m:b],state:L,props:[X,c],stateAttributesMapping:yn}),te=o.useMemo(()=>({orientation:i}),[i]),B=i==="vertical"?h.y:h.x;return l||!B?n.jsx(Cr.Provider,{value:te,children:A}):null}),Ci=o.forwardRef(function(t,r){const{render:s,className:a,...i}=t,{thumbYRef:l,thumbXRef:c,handlePointerDown:u,handlePointerMove:d,handlePointerUp:f,setScrollingX:h,setScrollingY:p}=Kt(),{orientation:m}=ji();return Qe("div",t,{ref:[r,m==="vertical"?l:c],state:{orientation:m},props:[{onPointerDown:u,onPointerMove:d,onPointerUp(v){m==="vertical"&&p(!1),m==="horizontal"&&h(!1),f(v)},style:{...m==="vertical"&&{height:`var(${zt.scrollAreaThumbHeight})`},...m==="horizontal"&&{width:`var(${zt.scrollAreaThumbWidth})`}}},i]})}),Ei=o.forwardRef(function(t,r){const{render:s,className:a,...i}=t,{cornerRef:l,cornerSize:c,hiddenState:u}=Kt(),d=Qe("div",t,{ref:[r,l],props:[{style:{position:"absolute",bottom:0,insetInlineEnd:0,width:c.width,height:c.height}},i]});return u.corner?null:d});function Er({className:e,...t}){return n.jsx(xi,{className:_("group/scroll-area relative outline-none focus-visible:outline-none",e),...t})}function Nr({className:e,...t}){return n.jsx(vi,{className:_("h-full w-full outline-none focus-visible:outline-none",e),...t})}function Tr({className:e,...t}){return n.jsx(ki,{className:_("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 Rr({className:e,...t}){return n.jsx(Ci,{className:_("flex-1 rounded-full bg-primary-500 outline-none focus-visible:outline-none",e),...t})}function Ni({className:e,...t}){return n.jsx(Ei,{className:_("bg-primary-100 outline-none focus-visible:outline-none",e),...t})}function Ti(e){return e==="subagent"?ds:e==="cron"?fs:ms}function Ri(e){if(!e||!Array.isArray(e.content))return"";const t=e.content.map(s=>s.type==="text"?String(s.text??""):"").join(" ");return xr(t).replace(/\s+/g," ").trim()}function Ii(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 Ai(e){if(!e)return null;const t=[e.createdAt,e.created_at,e.timestamp,e.time,e.ts];for(const r of t){const s=Ii(r);if(s)return s}return null}function Mi(e){const t=e-Date.now(),r=Math.abs(t),s=[["minute",6e4],["hour",36e5],["day",864e5]];let a="minute",i=6e4;r>=s[2][1]?[a,i]=s[2]:r>=s[1][1]&&([a,i]=s[1]);const l=Math.round(t/i);return new Intl.RelativeTimeFormat("en",{numeric:"auto"}).format(l,a)}function Di(e){const t=String(e??"").toLowerCase().trim();return t?t==="error"||t==="failed"?"error":t==="completed"||t==="ended"||t==="done"?"success":null:null}function Oi({session:e,active:t,isGenerating:r=!1,isPinned:s,selectionMode:a=!1,selected:i=!1,onToggleSelect:l,onSelect:c,onTogglePin:u,onRename:d,onDelete:f,onExport:h}){const p=e.label||e.title||e.derivedTitle||e.friendlyId,m=Ti(e.kind),b=e.kind==="subagent"&&(e.lastMessage?.role==="assistant"||e.lastMessage?.role==="toolResult")?Ri(e.lastMessage):"",g=b.length>50?`${b.slice(0,50).trimEnd()}…`:b,v=e.kind==="subagent"?Di(e.status):null,w=e.kind==="cron"?Ai(e.lastMessage):null;return n.jsxs(Ye,{to:"/chat/$sessionKey",params:{sessionKey:e.friendlyId},onClick:x=>{if(a){x.preventDefault(),x.stopPropagation(),l?.(e);return}c?.()},className:_("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:_("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(re,{icon:m,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:[s?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"}):v==="success"?n.jsx(re,{icon:or,size:12,strokeWidth:1.8,className:"text-green-600/80 shrink-0"}):v==="error"?n.jsx(re,{icon:Ft,size:12,strokeWidth:1.8,className:"text-red-600/80 shrink-0"}):null:null]}),g?n.jsx("div",{className:"text-[11px] text-primary-600/80 line-clamp-1 mt-0.5 pl-[18px]",children:g}):null,e.kind==="cron"&&w?n.jsx("div",{className:"text-[10px] text-primary-500/75 line-clamp-1 mt-0.5 pl-[18px] font-mono",children:Mi(w)}):null]})]}),a?null:n.jsxs(fn,{children:[n.jsx(mn,{type:"button",onClick:x=>{x.preventDefault(),x.stopPropagation()},className:_("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(re,{icon:ls,size:20,strokeWidth:1.5})}),n.jsxs(pn,{side:"bottom",align:"end",children:[n.jsxs(nt,{onClick:x=>{x.preventDefault(),x.stopPropagation(),u(e)},className:"gap-2",children:[n.jsx("span",{className:"text-xs","aria-hidden":"true",children:"📌"})," ",s?"Unpin Session":"Pin Session"]}),n.jsxs(nt,{onClick:x=>{x.preventDefault(),x.stopPropagation(),d(e)},className:"gap-2",children:[n.jsx(re,{icon:cs,size:20,strokeWidth:1.5})," ","Rename"]}),n.jsxs(nt,{onClick:x=>{x.preventDefault(),x.stopPropagation(),h(e)},className:"gap-2",children:[n.jsx(re,{icon:us,size:20,strokeWidth:1.5})," ","Export"]}),nn(e.key)?null:n.jsxs(nt,{onClick:x=>{x.preventDefault(),x.stopPropagation(),f(e)},className:"text-red-700 gap-2 hover:bg-red-50/80 data-highlighted:bg-red-50/80",children:[n.jsx(re,{icon:ir,size:20,strokeWidth:1.5})," ","Delete"]})]})]})]})}function Li(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 Vt=o.memo(Oi,Li),Ir="opencami-pinned-sessions",Ar="opencami-sidebar-folders",Be={webchat:!1,subagent:!1,cron:!1,other:!1};async function _i(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 Fe(r))}async function Pi(e,t,r){const s=[];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){s.push(u)}}});return await Promise.all(i),s}function $i(){if(typeof window>"u")return[];try{const e=localStorage.getItem(Ir);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}catch{return[]}}function zi(e){if(!(typeof window>"u"))try{const t=Array.from(new Set(e));localStorage.setItem(Ir,JSON.stringify(t))}catch{}}function Ui(){if(typeof window>"u")return{...Be};try{const e=localStorage.getItem(Ar);if(!e)return{...Be};const t=JSON.parse(e);return!t||typeof t!="object"?{...Be}:{webchat:typeof t.webchat=="boolean"?t.webchat:Be.webchat,subagent:typeof t.subagent=="boolean"?t.subagent:Be.subagent,cron:typeof t.cron=="boolean"?t.cron:Be.cron,other:typeof t.other=="boolean"?t.other:Be.other}}catch{return{...Be}}}function Fi(e){if(!(typeof window>"u"))try{localStorage.setItem(Ar,JSON.stringify(e))}catch{}}function Ot(e,t,r){return r&&e.key?e.key===r:e.friendlyId===t}function Ki(e){if(!e)return!1;const t=e.toLowerCase();return t.includes("running")||t.includes("active")||t.includes("stream")||t.includes("generat")}function qt(e,t,r,s){return Ot(e,t,r)&&s?!0:Ki(e.status)}const Hi=o.memo(function({sessions:t,activeFriendlyId:r,activeSessionKey:s,isStreaming:a=!1,defaultOpen:i=!0,onSelect:l,onRename:c,onDelete:u,onExport:d}){const f=o.useDeferredValue(t),h=gt(),[p,m]=o.useState(()=>$i()),[b,g]=o.useState(()=>Ui()),[v,w]=o.useState(!1),[x,z]=o.useState(()=>new Set),I=o.useMemo(()=>new Set(p),[p]),W=f.filter(S=>I.has(S.key)),L=f.filter(S=>!I.has(S.key)),ee=W.length>0&&L.length>0,X=o.useMemo(()=>{const S={chat:[],webchat:[],subagent:[],cron:[],other:[]};for(const M of L){const U=M.kind??"other";S[U].push(M)}return S},[L]),A=o.useMemo(()=>f.filter(S=>x.has(S.key)),[x,f]),te=A.length,B=o.useCallback(()=>{w(S=>(S&&z(new Set),!S))},[]),E=o.useCallback(S=>{nn(S.key)||z(M=>{const U=new Set(M);return U.has(S.key)?U.delete(S.key):U.add(S.key),U})},[]),D=o.useCallback(()=>{z(new Set(f.filter(S=>!nn(S.key)).map(S=>S.key)))},[f]),N=o.useCallback(()=>{w(!1),z(new Set)},[]),j=o.useCallback(async()=>{if(A.length===0||!window.confirm(`Delete ${A.length} sessions? This will archive them.`))return;const M=[];await Pi(A,10,async U=>{try{await _i(U.key)}catch(Y){throw M.push(U.label||U.title||U.derivedTitle||U.friendlyId),Y}}),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
|
+
`)}`)),w(!1),z(new Set),h.invalidateQueries({queryKey:xe.sessions})},[h,A]),k=o.useCallback(S=>{m(M=>{const Y=M.includes(S.key)?M.filter(ie=>ie!==S.key):[...M,S.key];return zi(Y),Y})},[]),O=o.useCallback((S,M)=>{g(U=>{const Y={...U,[S]:M};return Fi(Y),Y})},[]);function Z(S,M,U){return U.length===0?null:n.jsxs(sn,{className:"flex flex-col",open:b[S],onOpenChange:Y=>O(S,Y),children:[n.jsxs(on,{className:_("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:_("rounded-full bg-primary-100 px-1.5 py-0.5 text-[10px] font-medium text-primary-700 tabular-nums"),children:U.length})]}),n.jsx(an,{contentClassName:"flex flex-col gap-px",children:U.map(Y=>n.jsx(Vt,{session:Y,active:Ot(Y,r,s),isGenerating:qt(Y,r,s,a),isPinned:!1,selectionMode:v,selected:x.has(Y.key),onToggleSelect:E,onSelect:l,onTogglePin:k,onRename:c,onDelete:u,onExport:d},Y.key))})]})}return n.jsxs(sn,{className:"flex h-full flex-col flex-1 min-h-0 w-full",defaultOpen:i,children:[n.jsxs("div",{className:"flex items-center justify-between pr-2 shrink-0",children:[n.jsxs(on,{className:"w-fit pl-1.5 text-balance",children:["Sessions",n.jsx("span",{className:"opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:n.jsx(re,{icon:ps,className:"size-3 transition-transform duration-150 group-data-panel-open:rotate-90"})})]}),n.jsx("button",{type:"button",onClick:B,className:_("text-[11px] font-medium px-1.5 py-0.5 rounded-md transition-colors",v?"text-primary-900 bg-primary-200":"text-primary-500 hover:text-primary-700 hover:bg-primary-100"),children:v?"Done":"Select"})]}),n.jsx(an,{className:"w-full flex-1 min-h-0 h-auto data-starting-style:h-0 data-ending-style:h-0",contentClassName:"flex flex-1 min-h-0 flex-col overflow-y-auto",children:n.jsxs(Er,{className:"flex-1 min-h-0",children:[n.jsx(Nr,{className:"min-h-0",children:n.jsxs("div",{className:"flex flex-col gap-2 pl-2 pr-2",children:[W.length>0?n.jsx("div",{className:"flex flex-col gap-px",children:W.map(S=>n.jsx(Vt,{session:S,active:Ot(S,r,s),isGenerating:qt(S,r,s,a),isPinned:!0,selectionMode:v,selected:x.has(S.key),onToggleSelect:E,onSelect:l,onTogglePin:k,onRename:c,onDelete:u,onExport:d},S.key))}):null,ee?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:_("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(S=>n.jsx(Vt,{session:S,active:Ot(S,r,s),isGenerating:qt(S,r,s,a),isPinned:!1,selectionMode:v,selected:x.has(S.key),onToggleSelect:E,onSelect:l,onTogglePin:k,onRename:c,onDelete:u,onExport:d},S.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(Tr,{orientation:"vertical",children:n.jsx(Rr,{})})]})}),v?n.jsxs("div",{className:"shrink-0 border-t border-primary-200 bg-surface px-2 py-2 flex flex-col gap-1.5",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("span",{className:"text-xs text-primary-600 font-medium",children:[te," selected"]}),n.jsx("button",{type:"button",onClick:D,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:j,disabled:te===0,className:_("flex-1 inline-flex items-center justify-center gap-1.5 rounded-md px-2 py-1.5 text-xs font-medium transition-colors",te>0?"bg-red-100 text-red-700 hover:bg-red-200":"bg-primary-100 text-primary-400 cursor-not-allowed"),children:[n.jsx(re,{icon:ir,size:14,strokeWidth:1.5}),"Delete"]}),n.jsx("button",{type:"button",onClick:N,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]})},Wi);function Wi(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 s=e.sessions[r],a=t.sessions[r];if(s.key!==a.key||s.friendlyId!==a.friendlyId||s.label!==a.label||s.title!==a.title||s.derivedTitle!==a.derivedTitle||s.updatedAt!==a.updatedAt||s.kind!==a.kind||s.status!==a.status||s.lastMessage!==a.lastMessage)return!1}return!0}const Xi=o.lazy(()=>rt(()=>import("./settings-dialog-vrd0eJGw.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])).then(e=>({default:e.SettingsDialog}))),Bi=o.lazy(()=>rt(()=>import("./session-export-dialog-DHHpvwI8.js"),__vite__mapDeps([17,1,4,3,5,6,7,8,9,2])).then(e=>({default:e.SessionExportDialog})));function Yi({sessions:e,activeFriendlyId:t,activeSessionKey:r,isStreaming:s=!1,creatingSession:a,onCreateSession:i,isCollapsed:l,onToggleCollapse:c,onSelectSession:u,onActiveSessionDelete:d,onOpenSearch:f}){const{settingsOpen:h,setSettingsOpen:p,pathsLoading:m,pathsError:b,paths:g,handleOpenSettings:v,closeSettings:w,copySessionsDir:x,copyStorePath:z}=Io(),{deleteSession:I}=zo(),{renameSession:W}=Uo(),L={duration:.15,ease:l?"easeIn":"easeOut"},[ee,X]=o.useState(!1),[A,te]=o.useState(null),[B,E]=o.useState(""),[D,N]=o.useState(!1),[j,k]=o.useState(null),[O,Z]=o.useState(null),[S,M]=o.useState(""),[U,Y]=o.useState(!1),[ie,we]=o.useState(null),[T,F]=o.useState(null),[K,q]=o.useState(""),[pe]=o.useState(()=>{try{return typeof window<"u"?localStorage.getItem("opencami-cron-manager")!=="false":!0}catch{return!0}}),G=gt();function J(P){te(P.key),E(P.label||P.title||P.derivedTitle||""),X(!0)}function ne(P){A&&W(A,P),X(!1),te(null)}function ge(P){k(P.key),Z(P.friendlyId),M(P.label||P.title||P.derivedTitle||P.friendlyId),N(!0)}function de(){if(j&&O){const P=O===t;P&&d&&d(),I(j,O,P)}N(!1),k(null),Z(null)}function se(P){we(P.key),F(P.friendlyId),q(P.label||P.title||P.derivedTitle||P.friendlyId),Y(!0)}function le(P){if(ie&&T){const je=xe.history(T,ie),ke=G.getQueryData(je);ke?.messages&&Wo(K,ke.messages,P)}Y(!1),we(null),F(null)}const $={className:"border-r border-primary-200 h-full overflow-hidden bg-primary-100 flex flex-col"};return n.jsxs(Se.aside,{initial:!1,animate:{width:l?48:"var(--opencami-sidebar-width)"},transition:L,className:$.className,children:[n.jsxs(Se.div,{layout:!0,transition:{layout:L},className:_("flex items-center h-12 px-2 justify-between"),children:[n.jsx(De,{initial:!1,children:l?null:n.jsx(Se.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:L,children:n.jsxs(Ye,{to:"/new",className:_(et({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),children:[n.jsx(so,{className:"size-5"}),n.jsx(oo,{})]})})}),n.jsx(Oe,{children:n.jsxs(Le,{children:[n.jsx(_e,{onClick:c,render:n.jsx(be,{size:"icon-sm",variant:"ghost",children:n.jsx(re,{icon:hs,size:20,strokeWidth:1.5})})}),n.jsx(Pe,{side:"right",children:l?"Open Sidebar":"Close Sidebar"})]})})]}),n.jsxs("div",{className:"px-2 mb-4 flex flex-col gap-1",children:[n.jsxs(Se.div,{layout:!0,transition:{layout:L},className:"w-full space-y-2",children:[n.jsxs(be,{disabled:a,variant:"ghost",size:"sm",onClick:i,onMouseUp:u,className:"w-full pl-1.5 justify-start",children:[n.jsx(re,{icon:gs,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(De,{initial:!1,mode:"wait",children:!l&&n.jsx(Se.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:L,className:"overflow-hidden whitespace-nowrap",children:"New Session"})})]}),(()=>{try{const P=localStorage.getItem("opencami-file-explorer");return P===null?!0:P==="true"}catch{return!0}})()&&n.jsx(Oe,{children:n.jsxs(Le,{children:[n.jsx(_e,{asChild:!0,children:n.jsxs(Ye,{to:"/files",className:_(et({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(re,{icon:xs,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(De,{initial:!1,mode:"wait",children:!l&&n.jsx(Se.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:L,className:"overflow-hidden whitespace-nowrap",children:"Files"})})]})}),l&&n.jsx(Pe,{side:"right",children:"Files"})]})}),(()=>{try{const P=localStorage.getItem("opencami-memory-viewer");return P===null?!0:P==="true"}catch{return!0}})()&&n.jsx(Oe,{children:n.jsxs(Le,{children:[n.jsx(_e,{asChild:!0,children:n.jsxs(Ye,{to:"/memory",className:_(et({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(re,{icon:en,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(De,{initial:!1,mode:"wait",children:!l&&n.jsx(Se.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:L,className:"overflow-hidden whitespace-nowrap",children:"Memory"})})]})}),l&&n.jsx(Pe,{side:"right",children:"Memory"})]})}),(()=>{try{return localStorage.getItem("opencami-skills-browser")==="true"}catch{return!1}})()&&n.jsx(Oe,{children:n.jsxs(Le,{children:[n.jsx(_e,{asChild:!0,children:n.jsxs(Ye,{to:"/skills",className:_(et({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(re,{icon:ys,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(De,{initial:!1,mode:"wait",children:!l&&n.jsx(Se.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:L,className:"overflow-hidden whitespace-nowrap",children:"Skills"})})]})}),l&&n.jsx(Pe,{side:"right",children:"Skills"})]})}),(()=>{try{return localStorage.getItem("opencami-agent-manager")==="true"}catch{return!1}})()&&n.jsx(Oe,{children:n.jsxs(Le,{children:[n.jsx(_e,{asChild:!0,children:n.jsxs(Ye,{to:"/agents",className:_(et({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(re,{icon:en,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(De,{initial:!1,mode:"wait",children:!l&&n.jsx(Se.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:L,className:"overflow-hidden whitespace-nowrap",children:"Agents"})})]})}),l&&n.jsx(Pe,{side:"right",children:"Agents"})]})}),pe&&n.jsx(Oe,{children:n.jsxs(Le,{children:[n.jsx(_e,{asChild:!0,children:n.jsxs(Ye,{to:"/bots",className:_(et({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(re,{icon:ws,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(De,{initial:!1,mode:"wait",children:!l&&n.jsx(Se.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:L,className:"overflow-hidden whitespace-nowrap",children:"Cron Jobs"})})]})}),l&&n.jsx(Pe,{side:"right",children:"Cron Jobs"})]})}),(()=>{try{return localStorage.getItem("opencami-feature_dashboard")==="true"}catch{return!1}})()&&n.jsx(Oe,{children:n.jsxs(Le,{children:[n.jsx(_e,{asChild:!0,children:n.jsxs(Ye,{to:"/dashboard",className:_(et({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(re,{icon:bs,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(De,{initial:!1,mode:"wait",children:!l&&n.jsx(Se.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:L,className:"overflow-hidden whitespace-nowrap",children:"Dashboard"})})]})}),l&&n.jsx(Pe,{side:"right",children:"Dashboard"})]})})]}),n.jsx(Se.div,{layout:!0,transition:{layout:L},className:"w-full",children:n.jsxs(be,{variant:"ghost",size:"sm",onClick:f,className:"w-full pl-1.5 justify-start",children:[n.jsx(re,{icon:Ss,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(De,{initial:!1,mode:"wait",children:!l&&n.jsx(Se.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:L,className:"overflow-hidden whitespace-nowrap",children:"Search"})})]})})]}),n.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:n.jsx(De,{initial:!1,children:!l&&n.jsx(Se.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:L,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(Hi,{sessions:e,activeFriendlyId:t,activeSessionKey:r,isStreaming:s,onSelect:u,onRename:J,onDelete:ge,onExport:se})})},"content")})}),n.jsx("div",{className:"px-2 py-3 border-t border-primary-200 bg-primary-100",children:n.jsx(Se.div,{layout:!0,transition:{layout:L},className:"w-full",children:n.jsxs(be,{variant:"ghost",size:"sm",onClick:v,title:l?"Settings":void 0,className:"w-full justify-start pl-1.5",children:[n.jsx(re,{icon:vs,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(De,{initial:!1,mode:"wait",children:!l&&n.jsx(Se.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:L,className:"overflow-hidden whitespace-nowrap",children:"Settings"})})]})})}),h&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Xi,{open:h,onOpenChange:p,pathsLoading:m,pathsError:b,paths:g,onClose:w,onCopySessionsDir:x,onCopyStorePath:z})}),n.jsx(ei,{open:ee,onOpenChange:X,sessionTitle:B,onSave:ne,onCancel:()=>X(!1)}),n.jsx(Zo,{open:D,onOpenChange:N,sessionTitle:S,onConfirm:de,onCancel:()=>N(!1)}),U&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Bi,{open:U,onOpenChange:Y,sessionTitle:K,onExport:le,onCancel:()=>Y(!1)})})]})}function Gi(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){const s=e[r],a=t[r];if(s.key!==a.key||s.friendlyId!==a.friendlyId||s.label!==a.label||s.title!==a.title||s.derivedTitle!==a.derivedTitle||s.updatedAt!==a.updatedAt||s.kind!==a.kind||s.status!==a.status||s.lastMessage!==a.lastMessage)return!1}return!0}function Vi(e,t){return!(e.activeFriendlyId!==t.activeFriendlyId||e.activeSessionKey!==t.activeSessionKey||e.isStreaming!==t.isStreaming||e.creatingSession!==t.creatingSession||e.isCollapsed!==t.isCollapsed||!Gi(e.sessions,t.sessions))}const qi=o.memo(Yi,Vi);function Wn(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 Xn(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 Ji({totalTokens:e,contextTokens:t,className:r}){const{percentage:s,usedStr:a,maxStr:i,colors:l,hasData:c,isNearlyFull:u}=o.useMemo(()=>{if(typeof t!="number"||t<=0)return{percentage:0,usedStr:"",maxStr:"",colors:Xn(0),hasData:!1,isNearlyFull:!1};const h=typeof e=="number"&&e>0?e:0,p=Math.min(100,Math.round(h/t*100));return{percentage:p,usedStr:Wn(h),maxStr:Wn(t),colors:Xn(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:_("group relative flex items-center gap-1.5",r),title:`Context: ${d} / ${f} tokens (${s}%)`,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:_("h-full rounded-full transition-all duration-500 ease-out",l.bar,u&&"animate-pulse"),style:{width:`${s}%`}})}),n.jsx("span",{className:_("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:_("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:_("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-500",children:"Context window"}),n.jsxs("span",{className:_("font-semibold",l.text),children:[s,"%"]})]}),n.jsxs("div",{className:"flex items-center gap-1.5 text-primary-700 dark:text-primary-700",children:[n.jsx("span",{className:"font-medium",children:a}),n.jsx("span",{className:"text-primary-400 dark:text-primary-500",children:"/"}),n.jsx("span",{children:i}),n.jsx("span",{className:"text-primary-400 dark:text-primary-500",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:_("h-full rounded-full transition-all duration-500 ease-out",l.bar),style:{width:`${s}%`}})}),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 Qi=o.memo(Ji);function Zi({activeTitle:e,wrapperRef:t,showSidebarButton:r=!1,onOpenSidebar:s,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(be,{size:"icon-sm",variant:"ghost",onClick:s,className:"mr-2 text-primary-800 hover:bg-primary-100",style:{WebkitAppRegion:"no-drag"},"aria-label":"Open sidebar",children:n.jsx(re,{icon:js,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(Qi,{totalTokens:a,contextTokens:i,className:"ml-3 hidden sm:flex"})]})}const ea=o.memo(Zi);function ta(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function na(e){const t=new Date(e);return ta(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 ra(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 sa({timestamp:e}){const t=na(e),r=ra(e);return n.jsx(Oe,{children:n.jsxs(Le,{children:[n.jsx(_e,{className:"inline-flex items-center text-xs text-primary-600",children:t}),n.jsx(Pe,{side:"top",children:r})]})})}function oa({text:e,align:t,timestamp:r,forceVisible:s=!1}){const[a,i]=o.useState(!1),[l,c]=o.useState("idle"),u=o.useRef(null),d=o.useRef(null),f=o.useRef(null),[h,p]=o.useState(()=>{if(typeof window>"u")return!0;try{const w=localStorage.getItem("opencami-tts-enabled");return w===null?!0:w==="true"}catch{return!0}});o.useEffect(()=>{function w(x){x.key==="opencami-tts-enabled"&&p(x.newValue===null?!0:x.newValue==="true")}return window.addEventListener("storage",w),()=>window.removeEventListener("storage",w)},[]),o.useEffect(()=>()=>{f.current?.abort(),u.current&&(u.current.pause(),u.current=null),d.current&&(URL.revokeObjectURL(d.current),d.current=null)},[]);const m=async()=>{try{await navigator.clipboard.writeText(e),i(!0),window.setTimeout(()=>i(!1),1400)}catch{i(!1)}},b=async()=>{if(l==="playing"){f.current?.abort(),u.current&&(u.current.pause(),u.current=null),d.current&&(URL.revokeObjectURL(d.current),d.current=null),c("idle");return}f.current?.abort();const w=new AbortController;f.current=w,c("loading");try{const x=await fetch("/api/tts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:e}),signal:w.signal});if(!x.ok)throw new Error("TTS failed");const z=await x.blob(),I=URL.createObjectURL(z);d.current=I;const W=new Audio(I);u.current=W,W.onended=()=>{c("idle"),d.current&&(URL.revokeObjectURL(d.current),d.current=null),u.current=null},W.onerror=()=>{c("idle"),d.current&&(URL.revokeObjectURL(d.current),d.current=null),u.current=null},await W.play(),c("playing")}catch(x){if(x instanceof Error&&x.name==="AbortError"){c("idle");return}c("idle"),d.current&&(URL.revokeObjectURL(d.current),d.current=null),u.current=null}},g=t==="end"?"justify-end":"justify-start",v=t==="start"&&h&&e.trim().length>0;return n.jsxs("div",{className:_("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",s?"opacity-100":"opacity-0",g),children:[n.jsx(Oe,{children:n.jsxs(Le,{children:[n.jsx(_e,{type:"button",onClick:()=>{m().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(re,{icon:a?ar:ks,size:16,strokeWidth:1.6})}),n.jsx(Pe,{side:"top",children:"Copy"})]})}),v&&n.jsx(Oe,{children:n.jsxs(Le,{children:[n.jsx(_e,{type:"button",onClick:()=>{b().catch(()=>{})},disabled:l==="loading",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",l==="loading"&&"opacity-60 cursor-wait"),children:n.jsx(re,{icon:l==="loading"?Cs:l==="playing"?lr:Es,size:16,strokeWidth:1.6,className:_(l==="loading"&&"animate-spin")})}),n.jsx(Pe,{side:"top",children:l==="loading"?"Generating speech…":l==="playing"?"Stop":"Listen"})]})}),n.jsx(sa,{timestamp:r})]})}function Mr({children:e,className:t,...r}){return n.jsx("div",{className:_("flex gap-3 w-full",t),...r,children:e})}function ia({children:e,markdown:t=!1,className:r,...s}){const a=_("rounded-[12px] break-words whitespace-normal min-w-0 max-w-full overflow-x-hidden",r);return t?n.jsx(ao,{className:a,...s,children:e}):n.jsx("div",{className:a,...s,children:e})}function aa({toolPart:e,defaultOpen:t=!1}){const{state:r,input:s,output:a,toolCallId:i}=e,l=(d,f=3200)=>{const h=d===void 0?"undefined":d;let p;if(typeof h=="string")try{p=JSON.stringify(JSON.parse(h),null,2)}catch{p=h}else p=JSON.stringify(h,null,2);return p.length<=f?p:`${p.slice(0,f).trimEnd()}
|
|
11
|
+
…[truncated]`},c=r==="output-error"?Ft:r==="output-available"?or:Ns,u=r==="output-error"?"text-red-600/80":r==="output-available"?"text-green-600/80":"text-primary-500/80";return n.jsx("div",{className:"inline-flex flex-col w-full",children:n.jsxs(sn,{defaultOpen:t,children:[n.jsxs(on,{render:n.jsx(be,{variant:"ghost",className:"h-auto w-full justify-start gap-1.5 rounded-md px-1.5 py-1"}),children:[n.jsx(re,{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(re,{icon:cr,size:14,strokeWidth:1.5,className:"ml-auto text-primary-700/80 transition-transform duration-150 group-data-panel-open:rotate-180"})]}),n.jsx(an,{className:"mt-1",children:n.jsxs("div",{className:"space-y-2 rounded-md border border-primary-200 bg-primary-100/70 p-2",children:[n.jsxs("div",{className:"rounded border border-primary-200 bg-primary-50 px-2 py-1.5",children:[n.jsx("div",{className:"text-[11px] font-medium text-primary-600",children:"Tool"}),n.jsx("div",{className:"font-mono text-xs text-primary-800 break-all",children:e.type})]}),s&&Object.keys(s).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(s)})]}),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 la=o.lazy(()=>rt(()=>import("./thinking-D9BBn5kK.js"),__vite__mapDeps([18,1,3,19,20,5,6,7,8,14,21,4,9,2,11,15,22,13,23,24,16,25,26])).then(e=>({default:e.Thinking}))),ca=o.lazy(()=>rt(()=>import("./search-sources-badge-BnqKxoia.js"),__vite__mapDeps([27,1,3])).then(e=>({default:e.SearchSourcesBadge})));function ua(e,t){const r=t!==void 0,s=t?.isError??!1;let a;r?s?a="output-error":a="output-available":a="input-available";let i;s&&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 Bn(e){return Ve(e).map(r=>{const s=r.id??"",a=r.name??"",i=r.partialJson??"",l=r.arguments?JSON.stringify(r.arguments):"";return`${s}|${a}|${i}|${l}`}).join("||")}function da(e){if(!e)return"missing";const r=(Array.isArray(e.content)?e.content:[]).map(a=>a.type==="text"?String(a.text??""):"").join("").trim(),s=e.details?JSON.stringify(e.details):"";return`${e.toolCallId??""}|${e.toolName??""}|${e.isError?"1":"0"}|${r}|${s}`}function Yn(e,t){if(!t)return"";const r=Ve(e);return r.length===0?"":r.map(s=>s.id?da(t.get(s.id)):"missing").join("||")}function fa(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 Gn(e){const t=[e.createdAt,e.created_at,e.timestamp,e.time,e.ts];for(const r of t){const s=fa(r);if(s)return s}return null}function ln(e){const r=(Array.isArray(e.content)?e.content:[]).find(s=>s.type==="thinking");return r&&"thinking"in r?String(r.thinking??""):null}function ma(e){const t=Array.isArray(e.content)?e.content:[],r=[];for(const s of t)s.type==="image"&&"source"in s&&typeof s.source?.data=="string"&&r.push(s);return r}const mt=/^📎 Uploaded file:\s*(\/uploads\/\S+)\s*$/;function pa(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,s=0;for(;r>=1024&&s<t.length-1;)r/=1024,s++;return`${r.toFixed(1)} ${t[s]}`}function ha(e){if(!e)return[];const t=e.trimStart();if(t.startsWith(">")||t.startsWith("```"))return[];const r=e.split(`
|
|
12
|
+
`),s=[];for(const i of r){if(mt.test(i)){s.push(i);continue}if(s.length>0&&i.trim()===""){s.push(i);continue}break}const a=r[0]??"";return mt.test(a)?s.filter(i=>mt.test(i)):[]}function ga(e){const t=[],r=new Set;for(const s of ha(e)){const i=s.match(mt)?.[1];!i||r.has(i)||(r.add(i),t.push({path:i,filename:i.split("/").pop()||i}))}return t}function xa(e){const t=e.split(`
|
|
13
|
+
`);if(!mt.test(t[0]??""))return e.trim();let r=0;for(;r<t.length&&mt.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 ya({message:e,toolResultsByCallId:t,forceActionsVisible:r=!1,isStreaming:s=!1,isLastAssistant:a=!1,aggregatedSearchSources:i,wrapperRef:l,wrapperClassName:c,wrapperScrollMarginTop:u,messageDomId:d,highlighted:f=!1,onRetry:h,onDismiss:p}){const{settings:m}=hn(),b=e.role||"assistant",g=ve(e),v=ln(e),w=ma(e),x=b==="user",z=x&&e.status==="error",I=o.useMemo(()=>w.map(k=>`data:${k.source.media_type};base64,${k.source.data}`),[w]),W=ht(e),L=Ut(),ee=Xs(k=>k.openInEditor),X=o.useMemo(()=>ga(g),[g]),[A,te]=o.useState({}),B=o.useMemo(()=>xa(g),[g]);o.useEffect(()=>{let k=!1;async function O(){const Z={};await Promise.all(X.map(async S=>{try{const M=await fetch(`/api/files/info?path=${encodeURIComponent(S.path)}`);if(!M.ok){Z[S.path]=null;return}const U=await M.json();Z[S.path]=typeof U.size=="number"?U.size:null}catch{Z[S.path]=null}})),k||te(Z)}return X.length>0?O():te({}),()=>{k=!0}},[X]);const E=async k=>{ee(k),await L({to:"/files"})},D=b==="assistant"?Ve(e):[],N=D.length>0,j=a&&!s&&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:_("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",x?"items-end":"items-start"),children:[v&&m.showReasoningBlocks&&n.jsx("div",{className:"w-full max-w-[var(--opencami-chat-width)]",children:n.jsx(o.Suspense,{fallback:null,children:n.jsx(la,{content:v})})}),w.length>0&&n.jsx("div",{className:_("flex flex-wrap gap-2 mb-2",x?"justify-end":"justify-start"),children:w.map((k,O)=>n.jsx("img",{src:I[O],alt:`Attachment ${O+1}`,loading:"lazy",decoding:"async",fetchPriority:"low",className:"max-w-[300px] max-h-[300px] rounded-lg object-cover"},O))}),X.length>0&&n.jsx("div",{className:_("mb-2 flex w-full flex-col gap-2",x?"items-end":"items-start"),children:X.map(k=>n.jsxs("button",{type:"button",onClick:()=>{E(k.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(re,{icon:ur,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:k.filename}),n.jsx("p",{className:"text-xs text-primary-600",children:pa(A[k.path]??null)})]})]},k.path))}),n.jsx(Mr,{className:_("min-w-0 max-w-full",x?"flex-row-reverse":""),children:n.jsx(ia,{markdown:!x,isStreaming:!x&&s,className:_("text-primary-900 opencami-text-size min-w-0 max-w-full",x?"opencami-message-user bg-primary-100 px-4 py-[var(--opencami-user-bubble-py)] max-w-[85%]":"opencami-message-assistant bg-transparent w-full",!x&&s&&"stream-fade-in",z&&"opacity-60"),children:B})}),z&&n.jsxs("div",{className:"flex items-center gap-2 text-xs text-red-500 dark:text-red-400",children:[n.jsx("span",{children:"Failed to send"}),h&&n.jsx("button",{type:"button",className:"underline hover:text-red-700 dark:hover:text-red-300",onClick:()=>h(e),children:"Retry"}),p&&n.jsx("button",{type:"button",className:"underline hover:text-red-700 dark:hover:text-red-300",onClick:()=>p(e),children:"Dismiss"})]}),N&&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:D.map(k=>{const O=k.id?t?.get(k.id):void 0,Z=ua(k,O);return n.jsx(aa,{toolPart:Z,defaultOpen:!1},k.id||k.name)})}),j.length>0&&n.jsx("div",{className:"w-full max-w-[var(--opencami-chat-width)]",children:n.jsx(o.Suspense,{fallback:null,children:n.jsx(ca,{sources:j})})}),!N&&n.jsx(oa,{text:g,timestamp:W,align:x?"end":"start",forceVisible:r})]})}function wa(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.onRetry!==t.onRetry||e.onDismiss!==t.onDismiss||e.message.status!==t.message.status||(e.message.role||"assistant")!==(t.message.role||"assistant")||ve(e.message)!==ve(t.message)||ln(e.message)!==ln(t.message)||Bn(e.message)!==Bn(t.message)||Yn(e.message,e.toolResultsByCallId)!==Yn(t.message,t.toolResultsByCallId)||Gn(e.message)!==Gn(t.message))}const Jt=o.memo(ya,wa);function ba({className:e,variant:t="outline",scrollRef:r,...s}){const[a,i]=o.useState(!0),[l,c]=o.useState(!1),u=o.useRef(0),d=o.useCallback(()=>{const f=r.current;if(!f)return;const h=Math.abs(f.scrollHeight-f.scrollTop-f.clientHeight)<100;i(h)},[r]);return o.useLayoutEffect(()=>{const f=r.current;if(!f)return;const h=()=>{u.current=f.scrollTop,d()},p=new MutationObserver(()=>{f&&(f.scrollTop!==u.current&&(u.current=f.scrollTop),d())});return d(),f.addEventListener("scroll",h),p.observe(f,{childList:!0,subtree:!0}),()=>{f.removeEventListener("scroll",h),p.disconnect()}},[d,r]),o.useLayoutEffect(()=>{if(a){c(!1);return}const f=window.setTimeout(()=>{c(!0)},200);return()=>window.clearTimeout(f)},[a]),n.jsx(be,{variant:"secondary",size:"icon-sm",className:_("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))},...s,children:n.jsx(re,{icon:cr,size:18,strokeWidth:1.8})})}function Sa({className:e,viewportRef:t,scrollRef:r,viewportProps:s}){return n.jsxs(Er,{className:_("relative flex flex-1 min-h-0 flex-col",e),children:[n.jsx(Nr,{className:"relative will-change-transform overflow-x-hidden",ref:t,...s}),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(ba,{scrollRef:r})})}),n.jsx(Tr,{orientation:"vertical",children:n.jsx(Rr,{})}),n.jsx(Ni,{})]})}function va(e,t){if(e===t)return!0;const r=Object.keys(e),s=Object.keys(t);if(r.length!==s.length)return!1;for(const a of r)if(e[a]!==t[a])return!1;return!0}function ja(e,t){return!(e.className!==t.className||e.viewportRef!==t.viewportRef||e.scrollRef!==t.scrollRef||!va(e.viewportProps,t.viewportProps))}const ka=o.memo(Sa,ja);function Ca({viewportNode:e,children:t}){return e?ns.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 Ea({children:e,className:t,onUserScroll:r,...s}){const a=o.useRef(null),[i,l]=o.useState(null),c=o.useCallback(function(d){a.current=d,l(d)},[]);return o.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(ka,{className:t,viewportRef:c,scrollRef:a,viewportProps:s}),n.jsx(Ca,{viewportNode:i,children:e})]})}const Na=o.memo(Ea);function Ta({children:e,className:t,...r}){return n.jsx("div",{className:_("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 Ra({...e}){return n.jsx("div",{className:"h-px w-full shrink-0 scroll-mt-4 pt-6","aria-hidden":"true",...e})}function Ia({as:e="span",className:t,duration:r=4,spread:s=20,children:a,...i}){const l=Math.min(Math.max(s,5),45),c=e;return n.jsx(c,{className:_("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 Aa({className:e}){return n.jsxs("div",{className:_("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(Ia,{className:"text-sm",duration:2,children:"Generating..."})]})}const Vn=o.lazy(()=>rt(()=>import("./follow-up-suggestions-C6RzpstA.js"),__vite__mapDeps([28,1,3,16,2])).then(e=>({default:e.FollowUpSuggestions})));function Ma({messages:e,loading:t,empty:r,emptyState:s,notice:a,noticePosition:i="start",waitingForResponse:l,isStreaming:c=!1,sessionKey:u,pinToTop:d,pinGroupMinHeight:f,headerHeight:h,contentStyle:p,onFollowUpClick:m,jumpToMessageId:b,onRetryMessage:g,onDismissMessage:v}){const w=o.useRef(null),x=o.useRef(null),z=o.useRef(!1),I=o.useRef(d),W=o.useRef(void 0),[L,ee]=o.useState(null),{settings:X}=hn(),A=o.useMemo(()=>e.filter(T=>T.role!=="toolResult"),[e]),te=o.useDeferredValue(A),B=o.useMemo(()=>{const T=new Map;for(const F of e){if(F.role!=="toolResult")continue;const K=F.toolCallId;typeof K=="string"&&K.trim().length>0&&T.set(K,F)}return T},[e]),E=o.useDeferredValue(B),D=o.useMemo(()=>{const T=[];for(const F of te){if(F.role!=="assistant")continue;const K=Ve(F);for(const q of K){if(!q.id)continue;const pe=q.name==="web_search",G=q.name==="web_fetch",J=q.name==="exec";if(!pe&&!G&&!J)continue;const ne=E.get(q.id),ge=ne?.content?.map(de=>de.type==="text"?String(de.text??""):"").join("").trim()??"";T.push([q.id,q.name??"",typeof q.arguments?.url=="string"?q.arguments.url:"",ne?.isError?"1":"0",ge].join("::"))}}return T.join("||")},[te,E]),N=o.useMemo(()=>{const T=pe=>pe?pe.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():"",F=(pe,G,J)=>{try{const ne=JSON.parse(pe),ge=Array.isArray(ne)?ne:ne?.results??ne?.web?.results??[];if(!Array.isArray(ge))return!1;let de=!1;for(const se of ge)se?.url&&se?.title&&!J.has(se.url)&&(J.add(se.url),G.push({title:T(se.title),url:se.url,snippet:T(se.description||se.snippet||se.content||"")}),de=!0);return de}catch{return!1}},K=[],q=new Set;for(const pe of te){if(pe.role!=="assistant")continue;const G=Ve(pe);for(const J of G){if(!J.id)continue;const ne=J.name==="web_search",ge=J.name==="web_fetch",de=J.name==="exec";if(!ne&&!ge&&!de)continue;const se=E.get(J.id);if(!se)continue;const le=se.content?.map($=>$.type==="text"?String($.text??""):"").join("").trim();if(le){if(ne||de){if(de&&(!le.includes('"results"')||!le.includes('"url"')))continue;let $=le;const P=le.indexOf("{");P>0&&($=le.slice(P));const je=$.lastIndexOf("}");je>0&&($=$.slice(0,je+1)),F($,K,q)}else if(ge){const $=J.arguments?.url;if($&&!q.has($)){q.add($);let P;try{P=new URL($).hostname}catch{P=$}K.push({title:P,url:$})}}}}}return K},[D,te,E]),j=A.map((T,F)=>({message:T,index:F})).filter(({message:T})=>T.role!=="user").map(({index:T})=>T).pop(),k=A.map((T,F)=>({message:T,index:F})).filter(({message:T})=>T.role==="assistant").map(({index:T})=>T).pop(),O=A.map((T,F)=>({message:T,index:F})).filter(({message:T})=>T.role==="user").map(({index:T})=>T).pop(),Z=l&&(typeof O!="number"||typeof j!="number"||j<O),S=typeof O=="number"?O:-1,M=d&&S>=0,U=typeof k=="number"?A[k]:void 0,Y=U?ve(U):"",ie=o.useMemo(()=>typeof k!="number"?"":A.slice(Math.max(0,k-5),k+1).map(F=>{const K=ve(F).trim();return K?`${F.role==="user"?"User":"Assistant"}: ${K}`:null}).filter(F=>!!F).join(`
|
|
18
|
+
|
|
19
|
+
`).slice(0,4e3),[A,k]),we=X.showFollowUps&&!l&&!c&&Y.length>0&&m!==void 0&&(typeof O!="number"||typeof k!="number"||k>O);return o.useLayoutEffect(()=>{if(!t){if(d){const T=!I.current||W.current!==O;I.current=!0,W.current=O,T&&x.current&&(z.current=!0,x.current.scrollIntoView({behavior:"auto",block:"start"}),window.setTimeout(()=>{z.current=!1},0));return}I.current=!1,W.current=O,w.current&&(z.current=!0,w.current.scrollIntoView({behavior:"auto",block:"end"}),window.setTimeout(()=>{z.current=!1},0))}},[t,A.length,u,d,O]),o.useEffect(()=>{if(!b||t)return;const T=document.getElementById(`message-${b}`);if(!T)return;T.scrollIntoView({behavior:"smooth",block:"center"}),ee(b);const F=window.setTimeout(()=>{ee(K=>K===b?null:K)},1800);return()=>window.clearTimeout(F)},[b,t,A]),n.jsx(Na,{className:"flex-1 min-h-0 -mb-4",children:n.jsxs(Ta,{className:"pt-6",style:p,children:[a&&i==="start"?a:null,r&&!a?s??n.jsx("div",{"aria-hidden":!0}):M?n.jsxs(n.Fragment,{children:[A.slice(0,S).map((T,F)=>{const K=typeof T.id=="string"?T.id:void 0,q=K||F,pe=typeof j=="number"&&F===j,G=typeof j=="number"&&F===j,J=T.role==="assistant"&&Ve(T).length>0;return n.jsx(Jt,{message:T,toolResultsByCallId:J?B:void 0,forceActionsVisible:pe,isStreaming:G&&c,isLastAssistant:G,aggregatedSearchSources:G?N:void 0,messageDomId:K?`message-${K}`:void 0,highlighted:L===K,onRetry:g,onDismiss:v},q)}),n.jsxs("div",{className:"flex flex-col gap-[var(--opencami-msg-gap)]",style:{minHeight:`${Math.max(0,f)}px`},children:[A.slice(S).map((T,F)=>{const K=S+F,q=typeof T.id=="string"?T.id:void 0,pe=q||K,G=typeof j=="number"&&K===j,J=typeof j=="number"&&K===j,ne=K===O?x:void 0,ge=K===O?"scroll-mt-0":void 0,de=K===O?h:void 0,se=T.role==="assistant"&&Ve(T).length>0;return n.jsx(Jt,{message:T,toolResultsByCallId:se?B:void 0,forceActionsVisible:G,isStreaming:J&&c,isLastAssistant:J,aggregatedSearchSources:J?N:void 0,wrapperRef:ne,wrapperClassName:ge,wrapperScrollMarginTop:de,messageDomId:q?`message-${q}`:void 0,highlighted:L===q,onRetry:g,onDismiss:v},pe)}),Z?n.jsx("div",{className:"py-2",children:n.jsx(Aa,{})}):null,we&&m?n.jsx(o.Suspense,{fallback:null,children:n.jsx(Vn,{responseText:Y,conversationContext:ie,onSuggestionClick:m,disabled:l})}):null]})]}):n.jsxs(n.Fragment,{children:[A.map((T,F)=>{const K=typeof T.id=="string"?T.id:void 0,q=K||F,pe=typeof j=="number"&&F===j,G=typeof j=="number"&&F===j,J=T.role==="assistant"&&Ve(T).length>0;return n.jsx(Jt,{message:T,toolResultsByCallId:J?B:void 0,forceActionsVisible:pe,isStreaming:G&&c,isLastAssistant:G,aggregatedSearchSources:G?N:void 0,messageDomId:K?`message-${K}`:void 0,highlighted:L===K,onRetry:g,onDismiss:v},q)}),we&&m?n.jsx(o.Suspense,{fallback:null,children:n.jsx(Vn,{responseText:Y,conversationContext:ie,onSuggestionClick:m,disabled:l})}):null]}),a&&i==="end"?a:null,n.jsx(Ra,{ref:w})]})})}function Da(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&&e.onRetryMessage===t.onRetryMessage&&e.onDismissMessage===t.onDismissMessage}const Oa=o.memo(Ma,Da),cn=lo()(io(e=>({level:"low",setLevel:t=>e({level:t})}),{name:"thinking-level"}));function La(){const e=cn(r=>r.level),t=cn(r=>r.setLevel);return{level:e,setLevel:t}}const Qt=[{value:"off",label:"Off",description:"No reasoning",shortLabel:"Off"},{value:"low",label:"Low",description:"Think",shortLabel:"Low"},{value:"medium",label:"Medium",description:"Think harder",shortLabel:"Medium"},{value:"high",label:"High",description:"Ultrathink",shortLabel:"High"}];function _a({className:e}){const{level:t,setLevel:r}=La(),s=Qt.find(a=>a.value===t)??Qt[1];return n.jsxs(fn,{children:[n.jsxs(mn,{className:_("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(re,{icon:en,size:20,strokeWidth:1.5,className:_(t==="off"?"text-primary-400":"text-primary-700")}),n.jsx("span",{className:"text-pretty",children:s.shortLabel})]}),n.jsx(pn,{side:"top",align:"start",className:"min-w-[190px]",children:Qt.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(re,{icon:ar,size:20,strokeWidth:1.5,className:"text-primary-600"})]},a.value))})]})}function Pa({commands:e,selectedIndex:t,onSelect:r,className:s}){return e.length===0?null:n.jsx("div",{className:_("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",s),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:_("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-700 dark:text-primary-700",children:a.command}),n.jsx("span",{className:"text-xs text-primary-600 dark:text-primary-600",children:a.description})]})},a.command)})})})}const $a=o.memo(Pa),Dr=o.createContext({isLoading:!1,value:"",setValue:()=>{},maxHeight:240,onSubmit:void 0,disabled:!1,textareaRef:rs.createRef()});let pt=null,qn=!1;function za(){qn||typeof window>"u"||(qn=!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 s=e.key.length===1,a=e.key==="Backspace";!s&&!a||!pt||pt.disabled||pt.focus()}))}function Or(){return o.useContext(Dr)}function Ua({className:e,isLoading:t=!1,maxHeight:r=240,value:s,onValueChange:a,onSubmit:i,children:l,disabled:c=!1,onClick:u,...d}){const[f,h]=o.useState(s||""),p=o.useRef(null);za();function m(g){h(g),a?.(g)}function b(g){c||p.current?.focus(),u?.(g)}return n.jsx(Oe,{children:n.jsx(Dr.Provider,{value:{isLoading:t,value:s??f,setValue:a??m,maxHeight:r,onSubmit:i,disabled:c,textareaRef:p},children:n.jsx("div",{onClick:b,className:_("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 Fa({className:e,onKeyDown:t,disableAutosize:r=!1,inputRef:s,...a}){const{value:i,setValue:l,maxHeight:c,onSubmit:u,disabled:d,textareaRef:f}=Or();function h(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 s=="function"?s(g):s&&"current"in s&&(s.current=g),g?pt=g:pt===g&&(pt=null),h(g)}o.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 m(g){h(g.target),l(g.target.value)}function b(g){g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),u?.()),t?.(g)}return n.jsx("textarea",{ref:p,value:i,onChange:m,onKeyDown:b,className:_("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 Ka({children:e,className:t,...r}){return n.jsx("div",{className:_("flex items-center gap-2",t),...r,children:e})}function Jn({tooltip:e,children:t,className:r,side:s="top",...a}){const{disabled:i}=Or();return n.jsxs(Le,{...a,children:[n.jsx(_e,{disabled:i,onClick:l=>l.stopPropagation(),children:t}),n.jsx(Pe,{side:s,className:r,children:e})]})}const Lr="opencami-personas-enabled",un="opencami-active-persona";function Ha(){if(typeof window>"u")return!0;try{const e=localStorage.getItem(Lr);return e===null?!0:e==="true"}catch{return!0}}function Wa(){if(typeof window>"u")return null;try{const e=localStorage.getItem(un);return e?JSON.parse(e):null}catch{return null}}function Qn(e){if(!(typeof window>"u"))try{e?localStorage.setItem(un,JSON.stringify(e)):localStorage.removeItem(un)}catch{}}const Xa={core:"Core",creative:"Creative",curator:"Curator",learning:"Learning",lifestyle:"Lifestyle",professional:"Professional"};function Ba({className:e,onSelect:t}){const[r,s]=o.useState({}),[a,i]=o.useState(null),[l,c]=o.useState(!0),[u,d]=o.useState(!1),[f,h]=o.useState(Ha),p=o.useRef(null);o.useEffect(()=>{const v=w=>{w.key===Lr&&h(w.newValue===null?!0:w.newValue==="true")};return window.addEventListener("storage",v),()=>window.removeEventListener("storage",v)},[]),o.useEffect(()=>{let v=!0;async function w(){p.current?.abort();const x=new AbortController;p.current=x;try{c(!0);const z=await fetch("/api/personas",{signal:x.signal});if(!z.ok){d(!1);return}const I=await z.json();if(!v)return;I.ok&&I.available?(s(I.personas),d(!0),i(Wa())):d(!1)}catch(z){if(z instanceof Error&&z.name==="AbortError"||!v)return;d(!1)}finally{v&&c(!1)}}return w(),()=>{v=!1,p.current?.abort()}},[]);const m=o.useCallback(v=>{i(v),Qn(v),t(`/persona ${v.id}`)},[t]),b=o.useCallback(()=>{i(null),Qn(null),t("/persona exit")},[t]);if(l||!u||!f)return null;const g=Object.entries(r);return g.length===0?null:n.jsxs(fn,{children:[n.jsxs(mn,{className:_("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(pn,{side:"top",align:"start",className:"w-[300px] max-h-[360px] overflow-y-auto",children:[a&&n.jsxs(n.Fragment,{children:[n.jsxs(nt,{onClick:b,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(([v,w])=>n.jsxs("div",{children:[n.jsx("div",{className:"px-2 pb-0.5 pt-2 text-[10px] font-semibold uppercase tracking-wider text-primary-400",children:Xa[v]??v}),w.map(x=>n.jsxs(nt,{onClick:()=>m(x),className:"justify-between",children:[n.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("span",{className:"text-sm flex-shrink-0",children:x.emoji}),n.jsx("span",{className:"truncate",children:x.name})]}),n.jsx("span",{className:"text-[11px] text-primary-400 truncate ml-2 max-w-[140px]",children:x.description})]},x.id))]},v))]})]})}const Ya=[{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 Ga({className:e,onCommandSelect:t}){const[r,s]=o.useState(!1);function a(i){t?.(i),s(!1)}return n.jsxs(n.Fragment,{children:[n.jsx(be,{variant:"ghost",size:"sm",onClick:()=>s(!0),className:_("h-7 w-7 p-0",e),title:"Show commands (Ctrl+/)",children:n.jsx(re,{icon:Rn,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(re,{icon:Rn,size:18,className:"text-primary-600 dark:text-primary-400"}),n.jsx("h2",{className:"font-semibold text-primary-900 dark:text-white",children:"Slash Commands"})]}),n.jsx(be,{variant:"ghost",size:"sm",onClick:()=>s(!1),className:"h-7 w-7 p-0",children:n.jsx(re,{icon:Ft,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"}),Ya.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-700 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 Va=10*1024*1024,ut=1280,qa=.75,Ja=300*1024,Qa=["image/png","image/jpeg","image/gif","image/webp"],_r=["pdf","txt","md","csv","json","xml","yaml","yml","log","py","js","ts","html","css"],Za=[".png",".jpg",".jpeg",".gif",".webp",..._r.map(e=>`.${e}`)].join(",");function el(){if(typeof document>"u")return!1;try{const e=document.createElement("canvas");return!!(e.getContext&&e.getContext("2d"))}catch{return!1}}async function tl(e){if(!el())throw new Error("Image compression not available in this browser");return new Promise((t,r)=>{const s=new Image,a=URL.createObjectURL(e),i=()=>{URL.revokeObjectURL(a)};s.onload=()=>{try{let l=s.width,c=s.height;(l>ut||c>ut)&&(l>c?(c=Math.round(c*ut/l),l=ut):(l=Math.round(l*ut/c),c=ut));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(s,0,0,l,c);const f=e.type==="image/png"?"image/png":"image/jpeg";let h=qa,p=u.toDataURL(f,h);if(f==="image/jpeg"){const b=Ja*1.37;for(;p.length>b&&h>.3;)h-=.1,p=u.toDataURL(f,h)}const m=p.split(",")[1];if(!m){i(),r(new Error("Failed to encode image"));return}i(),t(m)}catch(l){i(),r(l instanceof Error?l:new Error("Image compression failed"))}},s.onerror=()=>{i(),r(new Error("Failed to load image"))},s.src=a})}function Pr(e){return Qa.includes(e.type)}function nl(e){const t=e.name.includes(".")?e.name.split(".").pop()?.toLowerCase():"";return!!(t&&_r.includes(t))}async function rl(e){const t=crypto.randomUUID();if(!Pr(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>Va)return{id:t,file:e,preview:null,type:"image",base64:null,error:"Image is too large. Maximum size is 10MB."};try{const r=await tl(e),s=URL.createObjectURL(e);return{id:t,file:e,preview:s,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 sl({onFilesSelect:e,disabled:t=!1,className:r}){const s=o.useRef(null),a=o.useCallback(()=>{s.current?.click()},[]),i=o.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:s,type:"file",accept:Za,multiple:!0,onChange:i,className:"hidden","aria-hidden":"true"}),n.jsx(be,{variant:"ghost",size:"icon-sm",onClick:a,disabled:t,className:r,"aria-label":"Attach file",type:"button",children:n.jsx(re,{icon:Ts,size:18,strokeWidth:1.8})})]})}function Zn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function ol(e){const t=e.split(".");return t.length>1&&t.pop()?.toUpperCase()||""}function il({attachment:e,onRemove:t,className:r}){o.useEffect(()=>()=>{e.preview&&URL.revokeObjectURL(e.preview)},[e.preview]);const s=!!e.error;return e.type==="file"&&!s?n.jsxs("div",{className:_("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," (",Zn(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:_("relative flex items-center gap-3 rounded-xl border p-2 pr-3",s?"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(re,{icon:ur,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}),s?n.jsx("p",{className:"text-xs text-red-600",children:e.error}):n.jsxs("p",{className:"text-xs text-primary-500",children:[ol(e.file.name)," •"," ",Zn(e.file.size)]})]}),n.jsx(be,{variant:"ghost",size:"icon-sm",onClick:()=>t(e.id),className:"h-6 w-6 shrink-0 rounded-full hover:bg-primary-200","aria-label":"Remove attachment",type:"button",children:n.jsx(re,{icon:Ft,size:14})})]})}function al({attachments:e,onRemove:t,className:r}){return e.length===0?null:n.jsx("div",{className:_("flex flex-wrap gap-2 px-4",r),children:e.map(s=>n.jsx(il,{attachment:s,onRemove:t},s.id))})}const er=[{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 ll(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function cl(e,t){const r=ll(t),s=new RegExp(`(?:^|\\n\\n)📎 Uploaded file: ${r}\\n\\nPlease analyze this file\\.(?=\\n\\n|$)`);return e.replace(s,(a,i)=>i===0?"":`
|
|
20
|
+
|
|
21
|
+
`).trim()}function ul({onSubmit:e,isLoading:t,disabled:r,wrapperRef:s,inputRef:a}){const[i,l]=o.useState(""),[c,u]=o.useState(""),[d,f]=o.useState([]),[h,p]=o.useState(0),[m,b]=o.useState(!1),[g,v]=o.useState(!1),[w,x]=o.useState(!1),[z,I]=o.useState(0),[W,L]=o.useState(!1),[ee,X]=o.useState(null),A=o.useRef(null),te=o.useRef([]),B=o.useRef(null),E=o.useRef(null),D=o.useRef(null),N=o.useRef(null),j=o.useMemo(()=>/^\/\S*$/.test(i)&&!m,[i,m]),k=o.useMemo(()=>j?i.slice(1).toLowerCase():"",[j,i]),O=o.useMemo(()=>j?k?er.filter(R=>R.command.slice(1).toLowerCase().startsWith(k)):er:[],[j,k]),Z=o.useCallback(R=>{N.current=R,a&&(typeof a=="function"?a(R):a.current=R)},[a]),S=o.useCallback(()=>{typeof window>"u"||window.requestAnimationFrame(()=>{N.current?.focus()})},[]),M=o.useCallback(R=>{X(R)},[]),U=o.useCallback(()=>{l(""),f([]),p(0),b(!1),S()},[S]),Y=o.useCallback(R=>{l(V=>{const H=`📎 Uploaded file: ${R}
|
|
22
|
+
|
|
23
|
+
Please analyze this file.`;return V.trim()?`${V.trim()}
|
|
24
|
+
|
|
25
|
+
${H}`:H})},[]),ie=o.useCallback(async()=>{await fetch("/api/files/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:"/uploads"})})},[]),we=o.useCallback(async R=>{const V=crypto.randomUUID();if(!nl(R))return{id:V,file:R,preview:null,type:"file",base64:null,error:"Unsupported file type for upload."};try{await ie();const H=new FormData;H.append("path","/uploads"),H.append("file",R);const he=await fetch("/api/files/upload",{method:"POST",body:H});if(!he.ok){const Re=await he.text();throw new Error(Re||"File upload failed")}const ce=(await he.json()).files?.[0]?.path;if(!ce)throw new Error("Upload succeeded but no path was returned");return Y(ce),{id:V,file:R,preview:null,type:"file",base64:null,uploadedPath:ce}}catch(H){return{id:V,file:R,preview:null,type:"file",base64:null,error:H instanceof Error?H.message:"File upload failed"}}},[Y,ie]),T=o.useCallback(async R=>{if(R.length===0)return;const V=await Promise.all(R.map(H=>Pr(H)?rl(H):we(H)));f(H=>[...H,...V]),S()},[S,we]),F=o.useCallback(R=>{let V;f(H=>{const he=H.find(oe=>oe.id===R);return he?.uploadedPath&&(V=he.uploadedPath),H.filter(oe=>oe.id!==R)}),V&&l(H=>cl(H,V))},[]),K=o.useCallback(R=>{Array.from(R.dataTransfer.types).includes("Files")&&(R.preventDefault(),R.dataTransfer.dropEffect="copy",v(!0))},[]),q=o.useCallback(R=>{R.preventDefault();const V=R.relatedTarget;V&&R.currentTarget.contains(V)||v(!1)},[]),pe=o.useCallback(async R=>{R.preventDefault(),v(!1);const V=Array.from(R.dataTransfer.files);V.length!==0&&await T(V)},[T]),G=o.useCallback(R=>{l(R),p(0),b(!1),S()},[S]),J=o.useCallback(R=>{l(R),p(0),b(!1)},[]),ne=o.useCallback(R=>{l(`${R.command} `),p(0),b(!1),S()},[S]),ge=o.useCallback(()=>{if(r)return;if(j&&O.length>0){const H=Math.min(h,O.length-1);ne(O[H]);return}const R=i.trim(),V=d.filter(H=>!H.error&&H.base64);R.length===0&&V.length===0||(e(R,{reset:U,setValue:G,model:c||void 0,attachments:V}),S())},[r,j,O,h,ne,i,d,e,U,G,c,S]),de=o.useCallback(R=>{e(R,{reset:U,setValue:G,model:c||void 0,attachments:[]}),S()},[S,e,U,G,c]),se=o.useCallback(R=>{if(j){if(R.key==="Escape"){R.preventDefault(),b(!0),p(0);return}if(O.length!==0){if(R.key==="ArrowDown"){R.preventDefault(),p(V=>(V+1)%O.length);return}if(R.key==="ArrowUp"){R.preventDefault(),p(V=>(V-1+O.length)%O.length);return}if(R.key==="Tab"){R.preventDefault();const V=Math.min(h,O.length-1);ne(O[V])}}}},[j,O,h,ne]);o.useEffect(()=>()=>{E.current?.abort(),B.current&&clearInterval(B.current),A.current&&A.current.state!=="inactive"&&A.current.stop(),D.current&&D.current.abort()},[]);const le=o.useCallback(()=>{if(typeof window>"u")return"auto";try{return localStorage.getItem("opencami-stt-provider")||"auto"}catch{return"auto"}},[]),$=o.useCallback(()=>{A.current&&A.current.state!=="inactive"&&A.current.stop(),D.current&&D.current.stop(),B.current&&(clearInterval(B.current),B.current=null),x(!1),I(0)},[]),P=o.useCallback(async()=>{X(null);const R=le();if(R==="browser"){const V=window.SpeechRecognition||window.webkitSpeechRecognition;if(!V){M("Web Speech API is not supported in this browser.");return}const H=new V;H.continuous=!0,H.interimResults=!1,H.lang=navigator.language||"en-US",D.current=H,x(!0),I(0),B.current=setInterval(()=>{I(oe=>oe>=119?($(),0):oe+1)},1e3);let he="";H.onresult=oe=>{for(let ce=oe.resultIndex;ce<oe.results.length;ce++)oe.results[ce].isFinal&&(he+=oe.results[ce][0].transcript)},H.onend=()=>{x(!1),I(0),B.current&&clearInterval(B.current),he.trim()&&(X(null),l(oe=>oe+(oe?" ":"")+he.trim()),S())},H.onerror=()=>{x(!1),I(0),B.current&&clearInterval(B.current),M("Speech recognition failed. Try the Browser provider again or switch providers in Settings.")},H.start();return}try{const V=await navigator.mediaDevices.getUserMedia({audio:!0}),H=MediaRecorder.isTypeSupported("audio/webm")?"audio/webm":"audio/mp4",he=new MediaRecorder(V,{mimeType:H});A.current=he,te.current=[],he.ondataavailable=oe=>{oe.data.size>0&&te.current.push(oe.data)},he.onstop=async()=>{V.getTracks().forEach(ce=>ce.stop());const oe=new Blob(te.current,{type:H});if(oe.size!==0){L(!0);try{const ce=new FormData;ce.append("audio",oe,`recording.${H==="audio/webm"?"webm":"mp4"}`),R!=="auto"&&ce.append("provider",R),E.current?.abort();const Re=new AbortController;E.current=Re;const Me=await(await fetch("/api/stt",{method:"POST",body:ce,signal:Re.signal})).json();Me.ok&&Me.text?(X(null),l(ze=>ze+(ze?" ":"")+Me.text),S()):Me.ok||(console.warn("STT failed:",Me.error),M(Me.error||"Speech-to-text failed. Try the Browser provider in Settings."))}catch(ce){if(ce instanceof Error&&ce.name==="AbortError")return;console.warn("STT request failed:",ce),M("Could not reach speech-to-text service.")}finally{L(!1)}}},x(!0),I(0),B.current=setInterval(()=>{I(oe=>oe>=119?($(),0):oe+1)},1e3),he.start()}catch(V){const H=V instanceof Error?V.message:String(V);if(H.includes("NotAllowedError")||H.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: "+H)}},[le,$,S,M]),je=o.useCallback(()=>{w?$():P()},[w,$,P]),ke=d.filter(R=>!R.error&&R.base64),He=r||i.trim().length===0&&ke.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:s,onDragOver:K,onDragLeave:q,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(Ua,{value:i,onValueChange:J,onSubmit:ge,isLoading:t,disabled:r,children:[n.jsx(al,{attachments:d,onRemove:F}),ee&&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:ee}),j&&O.length>0&&n.jsx($a,{commands:O,selectedIndex:Math.min(h,O.length-1),onSelect:ne}),n.jsx(Fa,{placeholder:"Type a message…",inputRef:Z,onKeyDown:se}),n.jsxs(Ka,{className:"justify-between px-3",children:[n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(_a,{}),n.jsx(Ba,{onSelect:de}),n.jsx(Ga,{onCommandSelect:R=>J(R+" ")})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(sl,{onFilesSelect:T,disabled:r}),n.jsx(Jn,{tooltip:w?"Stop recording":"Voice input",children:n.jsx(be,{onClick:je,disabled:r||W,size:"icon-sm",variant:w?"destructive":"ghost",className:`rounded-full ${w?"animate-pulse":""}`,"aria-label":w?"Stop recording":"Voice input",children:W?n.jsx("span",{className:"size-4 animate-spin rounded-full border-2 border-current border-t-transparent"}):w?n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx("span",{className:"size-2 rounded-full bg-red-500"}),n.jsxs("span",{className:"text-xs tabular-nums",children:[Math.floor(z/60),":",String(z%60).padStart(2,"0")]}),n.jsx(re,{icon:lr,size:14,strokeWidth:2})]}):n.jsx(re,{icon:Rs,size:18,strokeWidth:2})})}),n.jsx(Jn,{tooltip:"Send message",children:n.jsx(be,{onClick:ge,disabled:He,size:"icon-sm",className:"rounded-full","aria-label":"Send message",children:n.jsx(re,{icon:Is,size:18,strokeWidth:2})})})]})]})]})]})}const dl=o.memo(ul);function fl({title:e,description:t,detail:r,actionLabel:s,onAction:a,className:i}){return n.jsx("div",{className:_("w-full max-w-[var(--opencami-chat-width)]",i),children:n.jsx(Mr,{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,s&&a?n.jsx("div",{className:"mt-3",children:n.jsx(be,{size:"sm",variant:"outline",onClick:a,children:s})}):null]})})})}function ml({state:e,error:t,onRetry:r,className:s}){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(fl,{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:s})}function pl(){const e=o.useRef(null),t=o.useRef(null),r=o.useRef(null),[s,a]=o.useState(0),[i,l]=o.useState(0);return o.useLayoutEffect(()=>{const c=e.current,u=t.current,d=r.current;if(!d)return;const f=()=>{const p=c?.offsetHeight??0,m=u?.offsetHeight??0,b=d.clientHeight;d.style.setProperty("--chat-header-height",`${Math.max(0,p)}px`),d.style.setProperty("--chat-composer-height",`${Math.max(0,m)}px`),l(p),a(Math.max(0,b-p-m))};f();const h=new ResizeObserver(()=>f());return c&&h.observe(c),u&&h.observe(u),()=>h.disconnect()},[]),{headerRef:e,composerRef:t,mainRef:r,pinGroupMinHeight:s,headerHeight:i}}function hl({activeFriendlyId:e,activeSessionKey:t,forcedSessionKey:r,isNewChat:s,isRedirecting:a,activeExists:i,sessionsReady:l,queryClient:c}){const u=r||t||e,d=xe.history(e,u),f=Lt({queryKey:d,queryFn:async function(){const x=c.getQueryData(d),z=Array.isArray(x?.messages)?x.messages.filter(A=>A.status==="sending"||A.__optimisticId?!0:!!A.clientId):[],I=Array.isArray(x?.messages)?x.messages:[],W=await vo({sessionKey:u,friendlyId:e}),L=yl(W.messages),ee=wl(L,I);if(!z.length)return{...W,messages:ee};const X=bl(ee,z);return{...W,messages:X}},enabled:!s&&!!e&&!a&&(!l||i),placeholderData:function(){return c.getQueryData(d)},gcTime:1e3*60*10}),h=o.useRef(""),p=o.useRef([]),m=o.useMemo(()=>{const w=Array.isArray(f.data?.messages)?f.data.messages:[],x=w[w.length-1],z=x&&typeof x.id=="string"?x.id:"",I=`${w.length}:${x?.role??""}:${z}:${ve(x??{content:[]}).slice(-32)}`;return I===h.current?p.current:(h.current=I,p.current=w,w)},[f.data?.messages]),b=f.error instanceof Error?f.error.message:null,g=o.useMemo(()=>{if(r)return r;const w=f.data?.sessionKey;return typeof w=="string"&&w.trim().length>0?w.trim():t},[t,r,f.data?.sessionKey]);return{historyQuery:f,historyMessages:m,displayMessages:m,historyError:b,resolvedSessionKey:g,activeCanonicalKey:s?"new":g||e,sessionKeyForHistory:u}}function gl(e,t){return e.findIndex(r=>{if(t.clientId&&r.clientId&&t.clientId===r.clientId||t.__optimisticId&&r.__optimisticId&&t.__optimisticId===r.__optimisticId)return!0;if(t.role&&r.role&&t.role!==r.role)return!1;const s=ve(t);if(!s||s!==ve(r))return!1;const a=ht(t),i=ht(r);return Math.abs(a-i)<=1e4})}function At(e){return typeof e=="string"?e.trim():""}function xl(e){const t=At(e.id);if(t)return`id:${t}`;const r=At(e.clientId);if(r)return`client:${r}`;const s=At(e.__optimisticId);if(s)return`optimistic:${s}`;const a=At(e.toolCallId);if(e.role==="toolResult"&&a)return`tool-result:${a}`;const i=Math.floor(ht(e)/1e3),l=ve(e);return l?`fallback:${e.role??"unknown"}:${i}:${l}`:`fallback:${e.role??"unknown"}:${i}:${JSON.stringify(e.content??[])}`}function yl(e){if(!Array.isArray(e)||e.length<=1)return e;const t=[],r=new Set;for(const s of e){const a=xl(s);r.has(a)||(r.add(a),t.push(s))}return t}function jt(e){return Array.isArray(e.content)?e.content.filter(t=>{if(typeof t!="object"||t===null)return!1;const r=t;if(r.type!=="image")return!1;const s=r.source;return typeof s?.data=="string"&&s.data.length>0}):[]}function wl(e,t){const r=t.filter(s=>jt(s).length>0);return r.length?e.map(s=>{if(jt(s).length>0)return s;const a=r.find(l=>{if(s.role!==l.role)return!1;if(s.id&&l.id&&s.id===l.id||s.clientId&&l.clientId&&s.clientId===l.clientId)return!0;const c=ve(s),u=ve(l);return!c||c!==u?!1:Math.abs(ht(s)-ht(l))<=3e4});if(!a)return s;const i=jt(a);return i.length?{...s,content:[...i,...Array.isArray(s.content)?s.content:[]]}:s}):e}function bl(e,t){if(!t.length)return e;const r=[...e];for(const s of t){const a=gl(r,s);if(a===-1){r.push(s);continue}const i=jt(s),l=r[a],c=jt(l),u=i.length>0&&c.length===0,d=!!(s.__optimisticId&&!l.__optimisticId),f=!!(s.clientId&&!l.clientId);!u&&!d&&!f||(r[a]={...l,...d?{__optimisticId:s.__optimisticId}:{},...f?{clientId:s.clientId}:{},...u?{content:[...i,...Array.isArray(l.content)?l.content:[]]}:{}})}return r}function Sl(e){const[t,r]=o.useState(!1);return o.useLayoutEffect(()=>{const s=window.matchMedia("(max-width: 768px)"),a=()=>r(s.matches);return a(),s.addEventListener("change",a),()=>s.removeEventListener("change",a)},[]),o.useLayoutEffect(()=>{t&&Ge(e,function(a){return{...a,isSidebarCollapsed:!0}})},[t,e]),{isMobile:t}}function vl({activeFriendlyId:e,isNewChat:t,forcedSessionKey:r}){const[s,a]=o.useState(()=>typeof document>"u"?!0:document.visibilityState==="visible");o.useEffect(()=>{if(typeof document>"u")return;const m=()=>{a(document.visibilityState==="visible")};return m(),document.addEventListener("visibilitychange",m),()=>{document.removeEventListener("visibilitychange",m)}},[]);const i=Lt({queryKey:xe.sessions,queryFn:So,refetchInterval:s?3e4:!1}),l=o.useMemo(()=>{const m=i.data??[];return $o(m)},[i.data]),c=o.useMemo(()=>l.find(m=>m.friendlyId===e),[l,e]),u=o.useMemo(()=>t||r||yr(e)?!0:l.some(m=>m.friendlyId===e),[e,r,t,l]),d=c?.key??"",f=o.useMemo(()=>c?c.label||c.title||c.derivedTitle||c.friendlyId:e,[e,c]),h=i.error instanceof Error?i.error.message:null,p=o.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:h}}function jl(){const{settings:e}=hn(),[t,r]=o.useState(!1),[s,a]=o.useState(null),[i,l]=o.useState(null),c=o.useRef(null);return{generateTitle:o.useCallback(async d=>{c.current&&c.current.abort();const f=new AbortController;c.current=f,r(!0);try{const h=await fetch("/api/llm-features",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"title",message:d,model:e.llmFeaturesModel?`openclaw/${e.llmFeaturesModel}`:void 0}),signal:f.signal});if(!h.ok)throw new Error(`API error: ${h.status}`);const p=await h.json();if(f.signal.aborted)throw new Error("Aborted");const m=p.title||d.slice(0,50),b=m.length>64?m.slice(0,61)+"...":m,g=p.source||"heuristic";return a(b),l(g),{title:b,source:g,error:p.error}}catch(h){if(h instanceof Error&&h.name==="AbortError")throw h;const p=kl(d);return a(p),l("heuristic"),{title:p,source:"heuristic",error:h instanceof Error?h.message:"Unknown error"}}finally{r(!1),c.current===f&&(c.current=null)}},[e.llmFeaturesModel]),isGenerating:t,lastTitle:s,lastSource:i}}function kl(e){let t=e.replace(/```[\s\S]*?```/g," ");t=t.replace(/`[^`]+`/g," "),t=t.replace(/https?:\/\/[^\s]+/g," "),t=t.replace(/[^\w\s.,!?'-]/g," "),t=t.replace(/\s+/g," ").trim();let a=t.split(/\s+/).filter(i=>{if(i.length<=2){const l=i.toUpperCase();return["AI","ML","UI","UX","API","CSS","JS"].includes(l)}return!0}).slice(0,6).join(" ");return a=a.replace(/[.,!?]+$/,""),a.length>60&&(a=a.slice(0,57)+"..."),a||e.slice(0,50)}function Cl(){return!0}function El(e,t,r){const s=ft(e),a=ye(s?.stream),i=ye(s?.runId),l=ye(s?.sessionKey)||t,c=ft(s?.data);if(i)if(r.anyRunSeen.current=!0,a==="lifecycle"){const m=ye(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=tr(c?.delta)||tr(c?.text);if(m.length===0)return;r.setState(b=>{const g=[...b.contentBlocks],v=g[g.length-1];return v?.kind==="text"?g[g.length-1]={...v,text:v.text+m}:g.push({kind:"text",text:m}),{...b,sessionKey:l,text:b.text+m,contentBlocks:g}}),r.onAssistantDelta?.({text:m,sessionKey:l});return}if(!a.includes("tool"))return;const u=ye(c?.toolCallId)||ye(c?.id)||ye(c?.callId)||`${i||"tool"}:${ye(c?.toolName)||ye(c?.name)||"unknown"}`,d=ye(c?.toolName)||ye(c?.name)||"Tool",f=Nl(a,c),h=ft(c?.arguments)||ft(c?.input)||ft(c?.params)||null,p=ye(c?.result)||ye(c?.output)||(a.includes("result")?ye(c?.text):"");r.setState(m=>{const b=[...m.tools],g=b.findIndex(W=>W.id===u),v={id:u,name:d,status:f};g>=0?b[g]=v:b.push(v);const w=[...m.contentBlocks],x=w.findIndex(W=>W.kind==="tool"&&W.id===u),z=x>=0?w[x]:null,I={kind:"tool",name:d,id:u,status:f,arguments:h??z?.arguments,output:p||z?.output||void 0};return x>=0?w[x]=I:w.push(I),{...m,sessionKey:l,tools:b,contentBlocks:w}})}function Nl(e,t){const r=ye(t?.phase)||ye(t?.status)||ye(t?.state);return r||(e.includes("result")||e.includes("output")?"done":(e.includes("call"),"running"))}function ft(e){return e&&typeof e=="object"?e:null}function ye(e){return typeof e=="string"?e.trim():""}function tr(e){return typeof e=="string"?e:""}const nr={active:!1,text:"",tools:[],contentBlocks:[],sessionKey:null};function Tl(e){const[t,r]=o.useState(nr),s=o.useRef(null),a=o.useRef(!1),i=o.useRef(!1),l=o.useRef(new Set),c=o.useRef(-1),u=o.useRef(""),d=o.useRef(!1),f=o.useRef(""),h=o.useRef(e.onDone),p=o.useRef(e.onError),m=o.useRef(e.onAssistantDelta);h.current=e.onDone,p.current=e.onError,m.current=e.onAssistantDelta;const b=o.useCallback(v=>{if(a.current=!0,i.current=!1,l.current.clear(),d.current=!1,c.current=-1,u.current="",s.current&&(s.current.close(),s.current=null),v?.preserveState){r(w=>({...w,active:!1}));return}r(nr)},[]),g=o.useCallback(function(w){if(f.current=w,s.current&&!a.current){r(z=>({...z,sessionKey:w,active:!0}));return}if(a.current=!1,i.current=!1,l.current.clear(),d.current=!1,c.current=-1,u.current="",r({active:!0,text:"",tools:[],contentBlocks:[],sessionKey:w}),s.current)return;const x=new EventSource(`/api/stream?sessionKey=${encodeURIComponent(w)}`);s.current=x,x.addEventListener("message",z=>{try{const I=JSON.parse(z.data);if(typeof I.seq=="number"){if(I.seq<=c.current)return;c.current=I.seq}const W=f.current;if(I.event==="agent"){const L=JSON.stringify(I.payload);if(L===u.current)return;u.current=L,El(I.payload,W,{setState:r,onAssistantDelta:m.current,activeRuns:l.current,anyRunSeen:d});return}if(I.event==="chat"){const L=ft(I.payload),ee=ye(L?.sessionKey)||W,X=ye(L?.state);X==="final"&&(i.current=!0),!a.current&&i.current&&(X==="final"||d.current&&l.current.size===0)&&(a.current=!0,r(A=>({...A,active:!1})),h.current(ee));return}if(I.event==="error"){const L=typeof I.payload=="string"?I.payload:"Stream connection lost";p.current?.(L)}}catch{}}),x.onerror=()=>{a.current||x.readyState===EventSource.CLOSED&&(s.current=null,r(z=>({...z,active:!1})),p.current?.("Stream connection lost"))}},[]);return{streaming:t,startStream:g,stopStream:b}}function Rl(e){const t=o.useCallback(r=>{const s=r.target,a=s.tagName==="INPUT"||s.tagName==="TEXTAREA"||s.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]);o.useEffect(()=>(window.addEventListener("keydown",t),()=>{window.removeEventListener("keydown",t)}),[t])}function rr(e){const{threshold:t=50,edgeWidth:r,onMove:s,onSwipe:a,onCancel:i,direction:l,enabled:c=!0}=e,u=o.useRef({startX:0,startY:0,tracking:!1,directionLocked:!1}),d=o.useCallback(p=>{if(!c)return;const m=p.touches[0];m&&(r!==void 0&&m.clientX>r||(u.current={startX:m.clientX,startY:m.clientY,tracking:!0,directionLocked:!1}))},[c,r]),f=o.useCallback(p=>{const m=u.current;if(!m.tracking)return;const b=p.touches[0];if(!b)return;const g=b.clientX-m.startX,v=b.clientY-m.startY,w=Math.abs(g),x=Math.abs(v);if(!m.directionLocked){if(w<5&&x<5)return;if(x>w){m.tracking=!1,i?.();return}m.directionLocked=!0}l==="left"&&g>0||l==="right"&&g<0||(p.preventDefault(),s?.(g))},[l,s,i]),h=o.useCallback(p=>{const m=u.current;if(!m.tracking)return;m.tracking=!1;const b=p.changedTouches[0];if(!b){i?.();return}const g=b.clientX-m.startX,v=Math.abs(g);if(!m.directionLocked||v<t){i?.();return}const w=g>0?"right":"left";if(l&&w!==l){i?.();return}a(w)},[l,i,a,t]);return{onTouchStart:d,onTouchMove:f,onTouchEnd:h}}const $r="opencami-browser-notifications-enabled",Il=5e3;function Zt(){return typeof window<"u"&&"Notification"in window}function sr(){if(typeof window>"u")return!1;try{return localStorage.getItem($r)==="true"}catch{return!1}}function Al(){const e=Ut(),t=o.useRef(0),[r,s]=o.useState(()=>sr()),a=o.useCallback(async()=>{if(!Zt())return"denied";try{return await Notification.requestPermission()}catch{return"denied"}},[]),i=o.useCallback(async c=>{s(c);try{localStorage.setItem($r,String(c))}catch{}c&&Zt()&&Notification.permission==="default"&&await a()},[a]),l=o.useCallback(c=>{if(!r||!Zt()||document.hidden!==!0||Notification.permission!=="granted")return;const u=Date.now();if(u-t.current<Il)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 o.useEffect(()=>{const c=()=>s(sr());return window.addEventListener("storage",c),()=>window.removeEventListener("storage",c)},[]),{notificationsEnabled:r,setNotificationsEnabled:i,requestNotificationPermission:a,maybeNotifyAssistantMessage:l}}const Ml=o.lazy(()=>rt(()=>import("./keyboard-shortcuts-dialog-jm4-DftO.js"),__vite__mapDeps([29,1,4,3,5,6,7,8,9,2])).then(e=>({default:e.KeyboardShortcutsDialog}))),Dl=o.lazy(()=>rt(()=>import("./search-dialog-lsT8JUtT.js"),__vite__mapDeps([30,1,3,4,5,6,7,8,9,2,19,20,14,21,11,15,22,13,23,24,16,25,26])).then(e=>({default:e.SearchDialog}))),Mt="opencami-search-jump-target";function Ol(e){const t=Array.isArray(e.content)?e.content:[],r=[],s=[];for(const[a,i]of t.entries()){if(i.type!=="image"||!("source"in i)||typeof i.source?.data!="string"||i.source.data.length===0)continue;const l=typeof i.source?.media_type=="string"&&i.source.media_type.length>0?i.source.media_type:"image/jpeg",c=i.source.data;r.push({id:crypto.randomUUID(),file:new File([],`retry-attachment-${a+1}`,{type:l}),preview:null,type:"image",base64:c}),s.push({mimeType:l,content:c})}return{attachments:r,payload:s}}function Ll({activeFriendlyId:e,isNewChat:t=!1,onSessionResolved:r,forcedSessionKey:s}){const a=Ut(),i=gt(),[l,c]=o.useState(!1),[u,d]=o.useState(!1),[f,h]=o.useState(null),[p,m]=o.useState(!1),{headerRef:b,composerRef:g,mainRef:v,pinGroupMinHeight:w,headerHeight:x}=pl(),[z,I]=o.useState(()=>Bt()||Yt()),[W,L]=o.useState(()=>Bt()||Yt()),[ee,X]=o.useState(!1),[A,te]=o.useState(!1),[B,E]=o.useState("global"),[D,N]=o.useState(null),[j,k]=o.useState(!1),O=cn(y=>y.level),{maybeNotifyAssistantMessage:Z}=Al(),S=o.useRef(null),M=o.useRef(null),U=o.useRef(null),Y=o.useRef(""),ie=o.useRef(()=>{}),we=o.useRef(!1),T=o.useRef(""),{isMobile:F}=Sl(i),{sessionsQuery:K,sessions:q,activeExists:pe,activeSessionKey:G,activeTitle:J,activeTokens:ne,sessionsError:ge}=vl({activeFriendlyId:e,isNewChat:t,forcedSessionKey:s}),{historyQuery:de,historyMessages:se,displayMessages:le,historyError:$,resolvedSessionKey:P,activeCanonicalKey:je,sessionKeyForHistory:ke}=hl({activeFriendlyId:e,activeSessionKey:G,forcedSessionKey:s,isNewChat:t,isRedirecting:p,activeExists:pe,sessionsReady:K.isSuccess,queryClient:i}),He=Lt({queryKey:os,queryFn:function(){return Tn(i)},initialData:function(){return Tn(i)},staleTime:1/0}),R=Lt({queryKey:["gateway","status"],queryFn:jo,retry:2,retryDelay:y=>Math.min(2e3*2**y,8e3),refetchOnWindowFocus:!1,refetchOnReconnect:!0,refetchOnMount:"always"}),V=o.useRef(Date.now()),H=R.error instanceof Error?R.error.message:R.data&&!R.data.ok?R.data.error||"Gateway unavailable":null,he=H??ge??$,oe=o.useCallback(()=>{R.refetch()},[R]),ce=He.data?.isSidebarCollapsed??!1;o.useEffect(()=>{K.isSuccess&&R.isError&&R.refetch()},[K.isSuccess,R.isError]);const Re=rr({enabled:F&&ce,edgeWidth:40,threshold:50,direction:"right",onSwipe:()=>{Ge(i,y=>({...y,isSidebarCollapsed:!1}))}}),st=rr({enabled:F&&!ce,threshold:50,direction:"left",onSwipe:()=>{Ge(i,y=>({...y,isSidebarCollapsed:!0}))}}),Me=o.useCallback(()=>{h(null),m(!0),a({to:"/new",replace:!0})},[a]),ze=o.useCallback(()=>{M.current&&(window.clearInterval(M.current),M.current=null),U.current&&(window.clearTimeout(U.current),U.current=null)},[]),Ke=o.useCallback(()=>{ze(),St(!1),I(!1),k(!1)},[ze]),kt=Cl(),{generateTitle:xt}=jl(),Ct=o.useRef(new Set),Et=2e3,yt=2e3,wt=o.useCallback(()=>{!e||t||(M.current&&window.clearInterval(M.current),k(!0),M.current=window.setInterval(()=>{ie.current()},Et))},[e,t]),Nt=o.useRef(()=>{}),We=o.useRef(()=>{}),{streaming:Q,startStream:Ce,stopStream:Ze}=Tl({onDone:y=>Nt.current(y),onError:y=>We.current(y),onAssistantDelta:({text:y})=>{T.current+=y,Z({text:T.current,sessionFriendlyId:e})}});Nt.current=o.useCallback(async y=>{await de.refetch(),Ke(),i.invalidateQueries({queryKey:xe.sessions})},[de,i,Ke]),We.current=o.useCallback(y=>{console.warn("[stream] SSE error, falling back to polling")},[]);const Xe=o.useMemo(()=>{if(Q.contentBlocks.length===0)return null;const y=[];for(const C of Q.contentBlocks)C.kind==="text"&&C.text?y.push({type:"text",text:C.text}):C.kind==="tool"&&y.push({type:"toolCall",name:C.name,id:C.id,arguments:C.arguments});return y.length===0?null:{role:"assistant",content:y,id:"__streaming__",__streaming:!0,timestamp:Date.now()}},[Q.contentBlocks]),Ht=o.useMemo(()=>{const y=[];for(const C of Q.contentBlocks)C.kind==="tool"&&C.status==="done"&&y.push({role:"toolResult",toolCallId:C.id,toolName:C.name,content:C.output?[{type:"text",text:C.output}]:[]});return y},[Q.contentBlocks]),zr=o.useMemo(()=>{if(!Xe)return le;const y=[...le].map((ue,Ee)=>({message:ue,index:Ee})).filter(({message:ue})=>ue.role!=="toolResult").map(({index:ue})=>ue).pop(),C=[...le].map((ue,Ee)=>({message:ue,index:Ee})).filter(({message:ue})=>ue.role==="assistant").map(({index:ue})=>ue).pop(),ae=[...le].map((ue,Ee)=>({message:ue,index:Ee})).filter(({message:ue})=>ue.role==="user").map(({index:ue})=>ue).pop(),fe=typeof C=="number"&&C===y&&(typeof ae!="number"||C>ae);if(!Q.active&&fe)return le;let me;if(fe&&typeof C=="number"){const ue=le[C];if(ve(ue).length>=Q.text.length&&Q.tools.length===0)return le;me=[...le],me[C]=Xe}else me=[...le,Xe];return Ht.length>0&&(me=[...me,...Ht]),me},[le,Xe,Ht,Q.active,Q.text,Q.tools]),Ur=o.useMemo(()=>({}),[]);ie.current=function(){de.refetch()},o.useEffect(()=>{if(p){f&&h(null);return}if(ot){f&&h(null);return}if(K.isSuccess&&!pe){f&&h(null);return}const y=ge??$??H;if(!y){f?.startsWith("Failed to load")&&h(null);return}_n(y)&&a({to:"/connect",replace:!0});const C=ge?`Failed to load sessions. ${ge}`:$?`Failed to load history. ${$}`:H?`Gateway unavailable. ${H}`:null;C&&h(C)},[f,H,$,p,a,ge]);const ot=!t&&!s&&!yr(e)&&K.isSuccess&&q.length>0&&!q.some(y=>y.friendlyId===e)&&!de.isFetching&&!de.isSuccess;o.useEffect(()=>{if(p){if(t){m(!1);return}!ot&&K.isSuccess&&m(!1)}},[t,p,K.isSuccess,ot]),o.useEffect(()=>{t||K.isSuccess&&q.length!==0&&ot&&(Pt(),rn(i,e,ke),a({to:"/new",replace:!0}))},[e,de.isFetching,de.isSuccess,t,a,i,ke,q,K.isSuccess,ot]);const wn=ot||p,bt=o.useRef("fast");o.useEffect(()=>{const y=[...se].reverse().find(ae=>ae.role==="assistant");if(!y)return;const C=`${se.length}:${ve(y).slice(-64)}`;C!==Y.current&&(Y.current=C,bt.current!=="fast"&&M.current&&(window.clearInterval(M.current),M.current=window.setInterval(()=>{ie.current()},Et),bt.current="fast"),U.current&&window.clearTimeout(U.current),U.current=window.setTimeout(()=>{M.current&&(window.clearInterval(M.current),M.current=window.setInterval(()=>{ie.current()},yt),bt.current="slow"),U.current=window.setTimeout(()=>{Ke(),bt.current="fast"},3e3)},1500))},[se,Ke]),o.useEffect(()=>{if(!j||Q.active)return;const y=[...se].map((fe,me)=>({message:fe,index:me})).filter(({message:fe})=>fe.role==="assistant").map(({index:fe})=>fe).pop(),C=[...se].map((fe,me)=>({message:fe,index:me})).filter(({message:fe})=>fe.role==="user").map(({index:fe})=>fe).pop();typeof y=="number"&&(typeof C!="number"||y>C)&&(Ke(),bt.current="fast")},[se,j,Ke,Q.active]),o.useEffect(()=>{if(t||p)return;const y=s||P||G;if(!y||Ct.current.has(y))return;const C=se.filter(me=>me.role==="user"),ae=se.filter(me=>me.role==="assistant");if(C.length===0||ae.length===0||C.length!==1)return;const fe=ve(C[0]);!fe||fe.length<5||(Ct.current.add(y),(async()=>{try{const me=await xt(fe);me.title&&await Ro(i,y,e,me.title)}catch(me){console.error("[smart-title] Error generating title:",me)}})())},[kt,t,p,s,P,G,e,se,xt,i]),o.useEffect(()=>{if(t||e){if(ze(),Ze(),Y.current="",k(!1),we.current){we.current=!1;return}if(Bt()||Yt()){I(!0),L(!0);return}I(!1),L(!1)}},[e,t,ze,Ze]),o.useEffect(()=>{if(!(typeof window>"u"))try{const y=sessionStorage.getItem(Mt);if(!y){N(null);return}const C=JSON.parse(y);if(typeof C.at=="number"&&Date.now()-C.at>300*1e3){sessionStorage.removeItem(Mt),N(null);return}if(C.friendlyId===e&&typeof C.messageId=="string"&&C.messageId.length>0){N(C.messageId),sessionStorage.removeItem(Mt);return}N(null)}catch{N(null)}},[e]),o.useLayoutEffect(()=>{if(t)return;const y=Oo(s||P||G,e);if(!y)return;we.current=!0;const C=xe.history(y.friendlyId,y.sessionKey),ae=i.getQueryData(C);(Array.isArray(ae?.messages)?ae.messages:[]).some(ue=>!!(y.optimisticMessage.clientId&&(ue.clientId===y.optimisticMessage.clientId||ue.__optimisticId===y.optimisticMessage.clientId)||y.optimisticMessage.__optimisticId&&ue.__optimisticId===y.optimisticMessage.__optimisticId))||Wt(i,y.friendlyId,y.sessionKey,y.optimisticMessage),I(!0),L(!0),Tt(y.sessionKey,y.friendlyId,y.message,!0,y.attachments)},[e,G,s,t,i,P]);function Tt(y,C,ae,fe=!1,me,ue,Ee){let Ue="";if(!fe){const{clientId:Ne,optimisticMessage:at}=Pn(ae,me);Ue=Ne,Wt(i,C,y,at),No(i,y,C,at)}St(!0),c(!0),h(null),I(!0),L(!0);const it=Ee??me?.flatMap(Ne=>Ne.base64?[{mimeType:Ne.file.type,content:Ne.base64}]:[]);T.current="",wt();const En=y||C;En&&Ce(En),fetch("/api/send",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({sessionKey:y,friendlyId:C,message:ae,thinking:O,idempotencyKey:crypto.randomUUID(),attachments:it,model:ue||void 0})}).then(async Ne=>{if(!Ne.ok)throw new Error(await Fe(Ne));const Nn=(await Ne.json()).sessionKey||y||C;Ce(Nn)}).catch(Ne=>{const at=Ne instanceof Error?Ne.message:String(Ne);if(_n(at)){a({to:"/connect",replace:!0});return}Ue&&Co(i,C,y,Ue,function(ts){return{...ts,status:"error"}}),h(`Failed to send message. ${at}`),St(!1),I(!1),L(!1)}).finally(()=>{c(!1)})}const bn=o.useCallback(async()=>{d(!0);try{const y=await fetch("/api/sessions",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({})});if(!y.ok)throw new Error(await Fe(y));const C=await y.json(),ae=typeof C.sessionKey=="string"?C.sessionKey:"",fe=typeof C.friendlyId=="string"&&C.friendlyId.trim().length>0?C.friendlyId.trim():tn(ae);if(!ae||!fe)throw new Error("Invalid session response");return i.invalidateQueries({queryKey:xe.sessions}),{sessionKey:ae,friendlyId:fe}}finally{d(!1)}},[i]),Fr=o.useCallback((y,C)=>{const ae=C.attachments;if(y.length===0&&(!ae||ae.length===0))return;if(C.reset(),t){const{clientId:me,optimisticId:ue,optimisticMessage:Ee}=Pn(y,ae);Wt(i,"new","new",Ee),St(!0),c(!0),I(!0),L(!0),bn().then(({sessionKey:Ue,friendlyId:it})=>{if(Do(it),Ao({sessionKey:Ue,friendlyId:it,message:y,optimisticMessage:Ee,attachments:ae}),r){r({sessionKey:Ue,friendlyId:it});return}a({to:"/chat/$sessionKey",params:{sessionKey:it},replace:!0})}).catch(Ue=>{Xt(i,"new","new",me,ue),C.setValue(y),h(`Failed to create session. ${Ue instanceof Error?Ue.message:String(Ue)}`),St(!1),I(!1),L(!1),c(!1)});return}Tt(s||P||G,e,y,!1,ae,C.model)},[e,G,bn,s,t,a,r,i,P]),Sn=o.useCallback(()=>{I(!1),L(!1),rn(i,"new","new"),a({to:"/new"}),F&&Ge(i,function(C){return{...C,isSidebarCollapsed:!0}})},[F,a,i]),Kr=o.useCallback(()=>{Ge(i,function(C){return{...C,isSidebarCollapsed:!C.isSidebarCollapsed}})},[i]),Hr=o.useCallback(()=>{F&&Ge(i,function(C){return{...C,isSidebarCollapsed:!0}})},[F,i]),Wr=o.useCallback(()=>{Ge(i,function(C){return{...C,isSidebarCollapsed:!1}})},[i]),Xr=o.useCallback(y=>{const C=ve(y),{attachments:ae,payload:fe}=Ol(y);if(!C&&ae.length===0)return;const me=s||P||G;if(!me)return;const ue=y.clientId,Ee=y.__optimisticId;ue&&Xt(i,e,me,ue,Ee),Tt(me,e,C,!1,ae,void 0,fe)},[e,G,s,i,P]),Br=o.useCallback(y=>{const C=s||P||G;if(!C)return;const ae=y.clientId,fe=y.__optimisticId;ae&&Xt(i,e,C,ae,fe),h(null)},[e,G,s,i,P]),Yr=o.useCallback(y=>{if(t||!y.trim())return;const C=s||P||G;C&&Tt(C,e,y.trim())},[e,G,s,t,P]),Gr=o.useCallback(()=>{S.current?.focus()},[]),Vr=o.useCallback(()=>{if(ee){X(!1);return}document.activeElement instanceof HTMLElement&&document.activeElement.blur()},[ee]),qr=o.useCallback(()=>{const y=[...le].reverse().find(ae=>ae.role==="assistant");if(!y)return;const C=ve(y);C&&navigator.clipboard.writeText(C).catch(()=>{})},[le]),Jr=o.useCallback(()=>{X(!0)},[]),Qr=o.useCallback(()=>{E(t?"global":"current"),te(!0)},[t]),vn=o.useCallback(()=>{E("global"),te(!0)},[]);Rl({onNewChat:Sn,onFocusInput:Gr,onEscape:Vr,onCopyLastResponse:qr,onShowHelp:Jr,onSearch:Qr,onSearchGlobal:vn});const jn=de.isLoading&&!de.data||p,kn=!!H&&!K.isSuccess&&R.errorUpdatedAt>V.current,Zr=!jn&&le.length===0,es=o.useMemo(()=>!kn||!he?null:n.jsx(ml,{state:"error",error:he,onRetry:oe}),[he,oe,kn]),Cn=n.jsx(qi,{sessions:q,activeFriendlyId:e,activeSessionKey:ke,creatingSession:u,onCreateSession:Sn,isCollapsed:F?!1:ce,onToggleCollapse:Kr,onSelectSession:Hr,onActiveSessionDelete:Me,onOpenSearch:vn});return n.jsxs("div",{className:"h-screen bg-surface text-primary-900",children:[n.jsxs("div",{className:_("h-full overflow-hidden",F?"relative":"grid grid-cols-[auto_minmax(0,1fr)]"),children:[wn?null:F?n.jsxs(n.Fragment,{children:[!ce&&n.jsx("div",{className:"fixed inset-0 z-40 bg-black/40 transition-opacity duration-200",onClick:()=>Ge(i,y=>({...y,isSidebarCollapsed:!0})),...st}),n.jsx("div",{className:_("fixed inset-y-0 left-0 z-50 w-[var(--opencami-sidebar-width)] transition-transform duration-150 safe-area-top",ce?"-translate-x-full":"translate-x-0"),...st,children:Cn})]}):Cn,n.jsxs("main",{className:"flex flex-col h-full min-h-0 min-w-0 overflow-x-hidden",ref:v,...Re,children:[n.jsx(ea,{activeTitle:J,wrapperRef:b,showSidebarButton:F,onOpenSidebar:Wr,totalTokens:ne.totalTokens,contextTokens:ne.contextTokens}),wn?null:n.jsxs(n.Fragment,{children:[n.jsx(Oa,{messages:zr,loading:jn,empty:Zr,notice:es,noticePosition:"end",waitingForResponse:z,isStreaming:j,sessionKey:je,pinToTop:W,pinGroupMinHeight:w,headerHeight:x,contentStyle:Ur,onFollowUpClick:Yr,jumpToMessageId:D,onRetryMessage:Xr,onDismissMessage:Br}),n.jsx(dl,{onSubmit:Fr,isLoading:l,disabled:l,wrapperRef:g,inputRef:S})]})]})]}),ee&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Ml,{open:ee,onOpenChange:X})}),A&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Dl,{open:A,onOpenChange:te,sessions:q,currentFriendlyId:e,currentSessionKey:G,mode:B,onJumpToMessage:y=>{if(te(!1),!!y.friendlyId){if(y.messageId&&y.friendlyId===e){N(y.messageId);return}if(y.messageId&&typeof window<"u")try{sessionStorage.setItem(Mt,JSON.stringify({friendlyId:y.friendlyId,messageId:y.messageId,at:Date.now()}))}catch{}a({to:"/chat/$sessionKey",params:{sessionKey:y.friendlyId}})}}})})]})}function _l(){const e=gt(),t=Ut(),[r,s]=o.useState(null),a=ss.useParams(),i=typeof a.sessionKey=="string"?a.sessionKey:"main",l=i==="new",c=r?.friendlyId===i?r.sessionKey:void 0,u=o.useCallback(function(f){Eo(e,"new","new",f.friendlyId,f.sessionKey),s({friendlyId:f.friendlyId,sessionKey:f.sessionKey}),t({to:"/chat/$sessionKey",params:{sessionKey:f.friendlyId},replace:!0})},[t,e]);return n.jsx(Ll,{activeFriendlyId:i,isNewChat:l,forcedSessionKey:c,onSessionResolved:l?u:void 0})}const nc=Object.freeze(Object.defineProperty({__proto__:null,component:_l},Symbol.toStringTag,{value:"Module"}));export{nc as $,sn as C,on as a,an as b,xe as c};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/agents-screen-CqdzZKaR.js","assets/main-CbISK-pm.js","assets/useQuery-_BEWdUe1.js","assets/button-Bv-7bwZZ.js","assets/switch-BYFBYPmi.js","assets/useControlled-Bc2Emhlx.js","assets/useBaseUiId-BdQC9KF3.js","assets/visuallyHidden-COI6QeQH.js","assets/tooltip-DzFgDY86.js","assets/useOnFirstRender-DpB3w0o4.js","assets/event-Cnr9OETn.js","assets/DirectionContext-BOL0P_1j.js","assets/opencami-logo-D2mv84sX.js","assets/proxy-DtxqfBHY.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{j as e,r as t,_ as r}from"./main-CbISK-pm.js";const n=t.lazy(()=>r(()=>import("./agents-screen-CqdzZKaR.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13])).then(s=>({default:s.AgentsScreen})));function o(){return e.jsx(t.Suspense,{fallback:e.jsx("div",{className:"flex h-screen items-center justify-center text-primary-500 text-sm",children:"Loading…"}),children:e.jsx(n,{})})}export{o as component};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{u as L,r as t,j as e,L as M}from"./main-xPlWrMhO.js";import{u as q}from"./useQuery-k6EMRoMD.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-D0n2Qsd_.js";import{S as _}from"./switch-BUQ0qH6r.js";import{s as X,T as Y,a as Z,b as $,c as ee,d as se,g as P}from"./tooltip-CcIdgcV0.js";import{O as re,a as ae}from"./opencami-logo-B_hLbomw.js";import{m as S,A as W}from"./proxy-BnlGpgC1.js";import"./useControlled-CyT-lqbs.js";import"./useBaseUiId-ClbEYEil.js";import"./visuallyHidden-COI6QeQH.js";import"./useOnFirstRender-CR_o2MK_.js";import"./event-CHpdjYFR.js";import"./DirectionContext-X-0CRn1O.js";async function te(){const s=await fetch("/api/agents");if(!s.ok)throw new Error("Failed to fetch agents");return(await s.json()).agents??[]}async function E(s){return await(await fetch("/api/agents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})).json()}function ie({agent:s,onEdit:d,onDelete:n}){const c=s.isDefault||s.id==="main",l=s.name||s.id.charAt(0).toUpperCase()+s.id.slice(1),m=s.model?s.model.split("/").pop():void 0;return e.jsx("div",{className:"group rounded-lg border border-primary-100 bg-surface p-4 transition-all duration-150 ease-out hover:border-primary-200 hover:shadow-sm",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("div",{className:"relative flex size-12 shrink-0 items-center justify-center rounded-lg bg-primary-50 text-xl",children:[s.emoji||"🤖",c&&e.jsx("span",{className:"absolute -top-1 -right-1 size-3 rounded-full bg-emerald-500 ring-2 ring-surface"})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("h4",{className:"text-[13px] font-semibold text-primary-900 leading-tight truncate",children:l}),l!==s.id&&e.jsx("span",{className:"text-[10px] font-mono text-primary-400 shrink-0",children:s.id})]}),c&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 text-[11px] font-medium rounded-full bg-emerald-50 text-emerald-600 border border-emerald-100 shrink-0",children:"Primary"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mb-3",children:[m&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 text-[10px] font-mono rounded-full bg-primary-50 text-primary-600 border border-primary-100 truncate max-w-[200px]",children:m}),s.sandbox!==void 0&&e.jsx("span",{className:B("inline-flex items-center px-2 py-0.5 text-[10px] font-medium rounded-full border",s.sandbox?"bg-amber-50 text-amber-600 border-amber-100":"bg-primary-50 text-primary-500 border-primary-100"),children:s.sandbox?"🔒 Sandbox":"🔓 Open"}),s.sessionScope&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 text-[10px] font-medium rounded-full bg-primary-50 text-primary-500 border border-primary-100",children:s.sessionScope==="per-sender"?"👤 Per-sender":"🌐 Global"})]}),s.tools&&s.tools.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1 mb-2",children:[s.tools.slice(0,6).map(i=>e.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 text-[10px] font-mono rounded bg-sky-50 text-sky-600 border border-sky-100",children:i},i)),s.tools.length>6&&e.jsxs("span",{className:"text-[10px] text-primary-400",children:["+",s.tools.length-6," more"]})]}),s.channelBindings&&s.channelBindings.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:s.channelBindings.map(i=>e.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 text-[10px] rounded bg-violet-50 text-violet-600 border border-violet-100",children:["#",i]},i))}),e.jsxs("div",{className:"flex items-center gap-3 pt-2 border-t border-primary-50",children:[s.workspace&&e.jsx("span",{className:"text-[11px] font-mono text-primary-400 truncate",title:s.workspace,children:s.workspace}),s.activeSessions!==void 0&&s.activeSessions>0&&e.jsxs("span",{className:"text-[11px] text-primary-400",children:[s.activeSessions," active session",s.activeSessions!==1?"s":""]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity duration-150",children:[e.jsx(f,{size:"icon-sm",variant:"ghost",onClick:d,"aria-label":"Edit agent",children:e.jsx(p,{icon:V,size:16,strokeWidth:1.5})}),!c&&e.jsx(f,{size:"icon-sm",variant:"ghost",onClick:n,"aria-label":"Delete agent",className:"text-red-500 hover:text-red-600",children:e.jsx(p,{icon:H,size:16,strokeWidth:1.5})})]})]})})}function D({label:s,placeholder:d,values:n,onChange:c}){const[l,m]=t.useState(""),i=o=>{(o.key==="Enter"||o.key===",")&&l.trim()&&(o.preventDefault(),n.includes(l.trim())||c([...n,l.trim()]),m("")),o.key==="Backspace"&&!l&&n.length>0&&c(n.slice(0,-1))};return e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:s}),e.jsxs("div",{className:"flex flex-wrap gap-1 p-2 rounded-md border border-primary-200 bg-surface min-h-[36px]",children:[n.map(o=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-primary-100 px-2 py-0.5 text-xs text-primary-700",children:[o,e.jsx("button",{onClick:()=>c(n.filter(x=>x!==o)),className:"text-primary-400 hover:text-primary-600",children:"×"})]},o)),e.jsx("input",{value:l,onChange:o=>m(o.target.value),onKeyDown:i,placeholder:n.length===0?d:"",className:"flex-1 min-w-[80px] bg-transparent text-sm outline-none"})]})]})}function F({agent:s,onSave:d,onCancel:n,saving:c}){const[l,m]=t.useState(s?.name??""),[i,o]=t.useState(s?.workspace??""),[x,g]=t.useState(s?.emoji??""),[u,v]=t.useState(s?.avatar??""),[b,N]=t.useState(s?.model??""),[w,U]=t.useState(s?.sandbox??!1),[h,z]=t.useState(s?.tools??[]),[j,y]=t.useState(s?.deniedTools??[]),[k,A]=t.useState(s?.channelBindings??[]),[C,T]=t.useState(s?.sessionScope??"per-sender"),r=!!s;return e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsx("h2",{className:"text-lg font-semibold text-primary-900",children:r?"Edit Agent":"Create Agent"}),e.jsx(f,{size:"icon-sm",variant:"ghost",onClick:n,children:e.jsx(p,{icon:G,size:18,strokeWidth:1.5})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"rounded-lg border border-primary-100 bg-surface p-4",children:[e.jsx("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3",children:"Basic Info"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"col-span-2 sm:col-span-1",children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Name"}),e.jsx("input",{value:l,onChange:a=>m(a.target.value),placeholder:"my-agent",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Emoji"}),e.jsx("input",{value:x,onChange:a=>g(a.target.value),placeholder:"🤖",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Avatar URL"}),e.jsx("input",{value:u,onChange:a=>v(a.target.value),placeholder:"https://...",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-500"})]})]})]}),e.jsxs("div",{className:"rounded-lg border border-primary-100 bg-surface p-4",children:[e.jsx("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3",children:"Model & Config"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Model"}),e.jsx("input",{value:b,onChange:a=>N(a.target.value),placeholder:"anthropic/claude-sonnet-4-20250514",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Workspace Path"}),e.jsx("input",{value:i,onChange:a=>o(a.target.value),placeholder:"/root/.openclaw/workspace-myagent",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-500"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-primary-800",children:"Sandbox Mode"}),e.jsx("div",{className:"text-xs text-primary-500",children:"Run agent in isolated sandbox"})]}),e.jsx(_,{checked:w,onCheckedChange:U})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Session Scope"}),e.jsxs("select",{value:C,onChange:a=>T(a.target.value),className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500",children:[e.jsx("option",{value:"per-sender",children:"Per-sender"}),e.jsx("option",{value:"global",children:"Global"})]})]})]})]}),e.jsxs("div",{className:"rounded-lg border border-primary-100 bg-surface p-4",children:[e.jsx("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3",children:"Tools"}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(D,{label:"Allowed Tools",placeholder:"Type tool name and press Enter",values:h,onChange:z}),e.jsx(D,{label:"Denied Tools",placeholder:"Type tool name and press Enter",values:j,onChange:y})]})]}),e.jsxs("div",{className:"rounded-lg border border-primary-100 bg-surface p-4",children:[e.jsx("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3",children:"Channel Bindings"}),e.jsx(D,{label:"Bound Channels",placeholder:"Type channel name and press Enter",values:k,onChange:A})]})]}),e.jsxs("div",{className:"mt-6 flex justify-end gap-2",children:[e.jsx(f,{size:"sm",variant:"outline",onClick:n,children:"Cancel"}),e.jsx(f,{size:"sm",onClick:()=>d({name:l,workspace:i,emoji:x,model:b,avatar:u,sandbox:w,tools:h,deniedTools:j,channelBindings:k,sessionScope:C}),disabled:!l.trim()||c,children:c?e.jsx(p,{icon:I,size:16,className:"animate-spin"}):r?"Save Changes":"Create Agent"})]})]})}function ne({agent:s,onConfirm:d,onCancel:n,deleting:c}){const[l,m]=t.useState(!1);return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onClick:n,children:e.jsxs("div",{className:"w-[min(380px,90vw)] rounded-xl border border-primary-200 bg-surface p-5 shadow-xl",onClick:i=>i.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(p,{icon:J,size:20,className:"text-red-500"}),e.jsx("h3",{className:"text-sm font-medium text-primary-900",children:"Delete Agent"})]}),e.jsxs("p",{className:"text-sm text-primary-600 mb-4",children:["Are you sure you want to delete ",e.jsx("strong",{children:s.name}),"? This cannot be undone."]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm text-primary-700 mb-4 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:l,onChange:i=>m(i.target.checked),className:"rounded border-primary-300"}),"Also delete workspace files"]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(f,{size:"sm",variant:"outline",onClick:n,children:"Cancel"}),e.jsx(f,{size:"sm",onClick:()=>d(l),disabled:c,className:"bg-red-600 text-white hover:bg-red-700",children:c?e.jsx(p,{icon:I,size:16,className:"animate-spin"}):"Delete"})]})]})})}function ge(){const s=L(),[d,n]=t.useState([]),[c,l]=t.useState(!0),[m,i]=t.useState(null),[o,x]=t.useState(!1),[g,u]=t.useState("list"),[v,b]=t.useState(null),[N,w]=t.useState(null),h=q({queryKey:se,queryFn:function(){return P(s)},initialData:function(){return P(s)},staleTime:1/0}).data?.isSidebarCollapsed??!1,z=t.useCallback(()=>{X(s,function(a){return{...a,isSidebarCollapsed:!a.isSidebarCollapsed}})},[s]),j=t.useMemo(()=>({duration:.15,ease:h?"easeIn":"easeOut"}),[h]),y=t.useCallback(async()=>{try{i(null);const r=await te();n(r)}catch(r){i(r instanceof Error?r.message:"Failed to load agents")}finally{l(!1)}},[]);t.useEffect(()=>{y()},[y]);const k=async r=>{x(!0);try{const a=await E({action:"create",name:r.name,workspace:r.workspace||void 0,emoji:r.emoji||void 0,avatar:r.avatar||void 0});if(a.error){i(a.error);return}u("list"),await y()}finally{x(!1)}},A=async r=>{if(v){x(!0);try{const a=await E({action:"update",agentId:v.id,name:r.name||void 0,workspace:r.workspace||void 0,model:r.model||void 0,avatar:r.avatar||void 0});if(a.error){i(a.error);return}b(null),u("list"),await y()}finally{x(!1)}}},C=async r=>{if(N){x(!0);try{const a=await E({action:"delete",agentId:N.id,deleteFiles:r});if(a.error){i(a.error);return}w(null),await y()}finally{x(!1)}}},T=e.jsxs(S.aside,{initial:!1,animate:{width:h?48:300},transition:j,className:"border-r border-primary-200 h-full overflow-hidden bg-primary-100 flex flex-col",children:[e.jsxs(S.div,{layout:!0,transition:{layout:j},className:"flex items-center h-12 px-2 justify-between",children:[e.jsx(W,{initial:!1,children:h?null:e.jsx(S.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:j,children:e.jsxs(M,{to:"/new",className:B(O({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),children:[e.jsx(re,{className:"size-5"}),e.jsx(ae,{})]})})}),e.jsx(Y,{children:e.jsxs(Z,{children:[e.jsx($,{onClick:z,render:e.jsx(f,{size:"icon-sm",variant:"ghost",children:e.jsx(p,{icon:Q,size:20,strokeWidth:1.5})})}),e.jsx(ee,{side:"right",children:h?"Open Sidebar":"Close Sidebar"})]})})]}),e.jsx("div",{className:"px-2 mb-4",children:e.jsxs(M,{to:"/",className:B(O({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),children:[e.jsx(p,{icon:K,size:20,strokeWidth:1.5,className:"min-w-5"}),e.jsx(W,{initial:!1,mode:"wait",children:!h&&e.jsx(S.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:j,className:"overflow-hidden whitespace-nowrap",children:"Back to Chat"})})]})})]});return e.jsx("div",{className:"h-screen bg-surface text-primary-900",children:e.jsxs("div",{className:"h-full overflow-hidden grid grid-cols-[auto_1fr]",children:[T,e.jsxs("main",{"aria-label":"Agent manager",className:"flex flex-col h-full min-h-0",children:[e.jsx("header",{className:"border-b border-primary-200 px-6 py-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg font-semibold text-primary-900",children:"Agents"}),e.jsxs("p",{className:"text-xs text-primary-500 mt-0.5",children:[d.length," agent",d.length!==1?"s":""," configured"]})]}),g==="list"&&e.jsxs(f,{size:"sm",onClick:()=>{b(null),u("create")},children:[e.jsx(p,{icon:R,size:16,strokeWidth:1.5}),e.jsx("span",{className:"ml-1",children:"Create Agent"})]})]})}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-6",children:[m&&e.jsx("div",{className:"mb-4 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 p-3 text-sm text-red-600 dark:text-red-400",children:m}),c?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(p,{icon:I,size:24,className:"animate-spin text-primary-400"})}):g==="list"?e.jsxs("div",{className:"max-w-3xl mx-auto space-y-3",children:[d.map(r=>e.jsx(ie,{agent:r,onEdit:()=>{b(r),u("edit")},onDelete:()=>w(r)},r.id)),d.length===0&&e.jsxs("div",{className:"py-12 text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-12 h-12 rounded-lg bg-primary-50 mb-3",children:e.jsx("span",{className:"text-2xl",children:"🤖"})}),e.jsx("p",{className:"text-sm text-primary-500",children:"No agents found"}),e.jsx("p",{className:"text-xs text-primary-400 mt-1",children:"Create one to get started"})]})]}):g==="create"?e.jsx(F,{onSave:k,onCancel:()=>u("list"),saving:o}):g==="edit"&&v?e.jsx(F,{agent:v,onSave:A,onCancel:()=>{b(null),u("list")},saving:o}):null]}),N&&e.jsx(ne,{agent:N,onConfirm:C,onCancel:()=>w(null),deleting:o})]})]})})}export{ge as AgentsScreen};
|
|
1
|
+
import{u as L,r as t,j as e,L as M}from"./main-CbISK-pm.js";import{u as q}from"./useQuery-_BEWdUe1.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-Bv-7bwZZ.js";import{S as _}from"./switch-BYFBYPmi.js";import{s as X,T as Y,a as Z,b as $,c as ee,d as se,g as P}from"./tooltip-DzFgDY86.js";import{O as re,a as ae}from"./opencami-logo-D2mv84sX.js";import{m as S,A as W}from"./proxy-DtxqfBHY.js";import"./useControlled-Bc2Emhlx.js";import"./useBaseUiId-BdQC9KF3.js";import"./visuallyHidden-COI6QeQH.js";import"./useOnFirstRender-DpB3w0o4.js";import"./event-Cnr9OETn.js";import"./DirectionContext-BOL0P_1j.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-RYovD6cu.js","assets/main-CbISK-pm.js","assets/button-Bv-7bwZZ.js","assets/switch-BYFBYPmi.js","assets/useControlled-Bc2Emhlx.js","assets/useBaseUiId-BdQC9KF3.js","assets/visuallyHidden-COI6QeQH.js","assets/useQuery-_BEWdUe1.js","assets/useMutation-CMp81lDO.js","assets/proxy-DtxqfBHY.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{j as e,r as t,_ as r}from"./main-CbISK-pm.js";const n=t.lazy(()=>r(()=>import("./bots-screen-RYovD6cu.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};
|