@augmentd-labs/canvas-web 2.26.17 → 2.26.18
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.
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/NextShell-Byg6OtC2.js","assets/rolldown-runtime-C0FnF6B9.js","assets/code-editor-BQnKd3jw.js","assets/workspace-BSXnX2Me.js","assets/react-BzqgEMSQ.js","assets/alert-dialog-BC58hyW-.js","assets/ui-BqHBdBU4.js","assets/utils-BxVxyehK.js","assets/utils-2pl1SbIp.js","assets/NextShell-BT6-_CFY.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{a as e,n as t,o as n,r,t as i}from"./rolldown-runtime-C0FnF6B9.js";import{a,i as o,l as s,n as c,r as l,t as u,u as d}from"./code-editor-BQnKd3jw.js";import{_t as f,gt as p,vt as m,yt as h}from"./react-BzqgEMSQ.js";import{t as g}from"./preload-helper-Czpn1I53.js";import{$ as _,$n as v,$t as y,A as b,An as x,At as S,B as C,Bn as w,Bt as T,C as E,Cn as D,Ct as O,D as k,Dn as A,Dt as j,E as M,En as N,Et as P,F as ee,Fn as F,Ft as I,G as te,Gn as L,Gt as R,H as ne,Hn as re,Ht as ie,I as ae,In as z,It as oe,J as se,Jn as B,Jt as ce,K as V,Kn as le,Kt as ue,L as de,Ln as fe,Lt as pe,M as me,Mn as he,Mt as ge,N as _e,Nn as ve,Nt as ye,O as be,On as xe,Ot as H,P as Se,Pn as Ce,Pt as U,Q as W,Qn as we,Qt as Te,R as Ee,Rn as De,Rt as Oe,S as ke,Sn as Ae,St as je,T as Me,Tn as Ne,Tt as Pe,U as Fe,Un as Ie,Ut as Le,V as Re,Vn as ze,Vt as Be,W as Ve,Wn as He,Wt as Ue,Xn as We,Xt as Ge,Y as Ke,Yn as G,Yt as qe,Z as Je,Zn as Ye,Zt as Xe,_ as Ze,_n as Qe,_t as $e,a as et,an as tt,ar as nt,at as rt,b as it,bn as at,bt as ot,c as st,cr as ct,ct as lt,d as ut,dn as dt,dr as ft,dt as pt,en as mt,er as ht,et as gt,f as _t,fn as vt,fr as yt,ft as bt,g as xt,gn as St,gt as Ct,h as wt,hn as Tt,ht as Et,i as Dt,in as Ot,ir as kt,it as At,j as jt,jn as Mt,jt as Nt,k as Pt,kn as Ft,kt as It,l as Lt,lr as Rt,lt as zt,m as Bt,mn as Vt,mt as Ht,n as Ut,nn as Wt,nr as Gt,nt as Kt,o as qt,on as Jt,or as Yt,ot as Xt,p as Zt,pn as Qt,pr as $t,pt as en,q as tn,qn as nn,qt as rn,r as an,rn as on,rr as sn,rt as cn,s as ln,sr as un,st as dn,t as fn,tn as pn,tr as mn,tt as hn,u as gn,un as _n,ur as vn,ut as yn,v as bn,vn as xn,vt as Sn,w as Cn,wn,wt as Tn,x as En,xn as Dn,xt as On,y as kn,yn as An,yt as jn,z as Mn,zn as Nn,zt as Pn}from"./document-list-BmUv3zzK.js";import{$ as Fn,$n as In,$r as Ln,$t as Rn,An as zn,Ar as Bn,At as Vn,B as Hn,Bn as Un,Br as Wn,Bt as Gn,C as Kn,Cn as qn,Cr as Jn,Ct as Yn,Dn as Xn,Dr as Zn,En as Qn,F as $n,Fr as er,Ft as tr,G as nr,Gn as rr,Gr as ir,H as ar,Hn as or,Hr as sr,Ht as cr,I as lr,It as ur,J as dr,Jn as fr,Jr as pr,Jt as mr,K as hr,Kn as gr,Kr as _r,L as vr,Lr as yr,Mt as br,Nn as xr,Nr as Sr,Nt as Cr,On as wr,Or as Tr,Ot as Er,P as Dr,Pn as Or,Pr as kr,Pt as Ar,Q as jr,Qn as Mr,Qr as Nr,R as Pr,Rn as Fr,Rr as Ir,Rt as Lr,S as Rr,Sn as zr,St as Br,Tt as Vr,U as Hr,Ur,Ut as Wr,V as Gr,Vn as Kr,Vr as qr,Vt as Jr,W as Yr,Wn as Xr,Wt as Zr,X as Qr,Xn as $r,Xt as ei,Y as ti,Yn as ni,Yr as ri,Yt as ii,Z as ai,Zn as oi,Zr as si,Zt as ci,_ as li,_i as ui,_n as di,_r as fi,_t as pi,an as mi,ar as hi,at as gi,b as _i,bn as vi,br as yi,bt as bi,ci as xi,cn as Si,ct as Ci,d as wi,dn as Ti,dr as Ei,dt as Di,ei as Oi,en as ki,er as Ai,et as ji,f as Mi,fi as Ni,fr as Pi,ft as Fi,g as Ii,gi as Li,gn as Ri,gr as zi,gt as Bi,h as Vi,hi as Hi,hn as Ui,ht as Wi,in as Gi,ir as Ki,it as qi,jn as Ji,jr as Yi,jt as Xi,kn as Zi,kr as Qi,kt as $i,ln as ea,lt as ta,m as na,mi as ra,mr as ia,mt as aa,ni as oa,nn as sa,oi as ca,on as la,or as ua,p as da,pi as fa,pn as pa,pr as ma,pt as ha,q as ga,qn as _a,qt as va,ri as ya,rn as ba,rr as xa,rt as Sa,si as Ca,sn as wa,st as Ta,tn as Ea,tt as Da,u as Oa,ui as ka,un as Aa,ur as ja,ut as Ma,v as Na,vn as Pa,vr as Fa,vt as Ia,w as La,wn as Ra,wr as za,wt as Ba,x as Va,xn as Ha,xt as Ua,y as Wa,yn as Ga,yr as Ka,yt as qa,z as Ja,zn as Ya,zr as Xa,zt as Za}from"./ui-BqHBdBU4.js";import{i as Qa,n as $a,r as eo}from"./utils-BxVxyehK.js";import{n as to,t as K}from"./utils-2pl1SbIp.js";import{_ as no,a as ro,b as q,c as io,d as ao,f as oo,g as so,h as co,i as lo,l as uo,m as fo,n as po,o as mo,p as ho,r as go,s as _o,t as vo,u as J,v as yo,x as Y,y as bo}from"./alert-dialog-BC58hyW-.js";import{t as xo}from"./socket-hM4c-ZSl.js";import{a as So,c as Co,l as wo,n as To,o as Eo,r as Do,s as Oo}from"./blobs-CtDkR2hC.js";import{$ as ko,$t as Ao,A as jo,At as Mo,B as No,C as Po,Cn as Fo,Ct as Io,D as Lo,Dn as Ro,Dt as zo,E as Bo,En as Vo,Fn as Ho,Ft as Uo,Gt as Wo,H as Go,Ht as Ko,I as qo,It as Jo,J as Yo,Jt as Xo,K as Zo,Kn as Qo,Kt as $o,L as es,Ln as ts,M as ns,Mn as rs,Nn as is,Nt as as,O as os,On as ss,Ot as cs,Pn as ls,Pt as us,Q as ds,Qt as fs,R as ps,Rn as ms,S as hs,Sn as gs,St as _s,T as vs,Tn as ys,Tt as bs,U as xs,Ut as Ss,V as Cs,Vt as ws,W as Ts,Wn as Es,Wt as Ds,Yt as Os,Zt as ks,_ as As,_n as js,_t as Ms,a as Ns,an as Ps,at as Fs,b as Is,bn as Ls,bt as Rs,cn as zs,ct as Bs,dn as Vs,dt as Hs,en as Us,et as Ws,f as Gs,fn as Ks,ft as qs,gn as Js,gt as Ys,ht as Xs,i as Zs,it as Qs,j as $s,jt as ec,k as tc,kn as nc,kt as rc,ln as ic,lt as ac,m as oc,mt as sc,n as cc,nn as lc,nt as uc,o as dc,on as fc,ot as pc,p as mc,pn as hc,pt as gc,q as _c,qt as vc,r as yc,rn as bc,rt as xc,s as Sc,sn as Cc,st as wc,t as Tc,tt as Ec,u as Dc,un as Oc,ut as kc,v as Ac,vn as jc,vt as Mc,w as Nc,wn as Pc,wt as Fc,x as Ic,xn as Lc,xt as Rc,y as zc,yt as Bc,z as Vc,zn as Hc,zt as Uc}from"./workspace-BSXnX2Me.js";import{_ as Wc,c as Gc,f as Kc,g as qc,h as Jc,l as Yc,m as Xc,o as Zc,p as Qc,s as $c,u as el,y as tl}from"./text-documents-BvR9-zf4.js";import{B as nl,D as rl,F as il,I as al,L as ol,N as sl,O as cl,P as ll,R as ul,T as dl,_ as fl,a as pl,b as ml,c as hl,d as gl,f as _l,g as vl,h as yl,i as bl,j as xl,m as Sl,n as Cl,o as wl,p as Tl,r as El,s as Dl,t as Ol,u as kl,w as Al,y as jl,z as Ml}from"./useAddTarget-CgZfKokT.js";import{n as Nl,t as Pl}from"./map-BxCwdK0d.js";import{t as Fl}from"./sha256-65KIjGvZ.js";import{n as Il,t as Ll}from"./use-theme-Bd8sb5Ox.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var X=n(d(),1),Rl=m(),Z=s(),zl=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`rounded-(--card-radius) border bg-card text-card-foreground shadow-elevation-1`,e),...t}));zl.displayName=`Card`;var Bl=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`flex flex-col space-y-1.5 p-6`,e),...t}));Bl.displayName=`CardHeader`;var Vl=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`h3`,{ref:n,className:K(`text-2xl font-semibold leading-none tracking-tight`,e),...t}));Vl.displayName=`CardTitle`;var Hl=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`p`,{ref:n,className:K(`text-sm text-muted-foreground`,e),...t}));Hl.displayName=`CardDescription`;var Ul=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`p-6 pt-0`,e),...t}));Ul.displayName=`CardContent`;var Wl=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`flex items-center p-6 pt-0`,e),...t}));Wl.displayName=`CardFooter`;var Gl=`2.26.17`,Kl=e=>{window.particlesJS.load(e,`/js/particles.config.json`,()=>{console.log(`particles.js config loaded for`,e)})};function ql(e){(0,X.useEffect)(()=>{if(window.particlesJS!==void 0)Kl(e);else{if(document.getElementById(`particles-js-script`))return;let t=document.createElement(`script`);t.id=`particles-js-script`,t.src=`/js/particles.min.js`,t.onload=()=>{console.log(`particles.js loaded`),Kl(e)},document.head.appendChild(t)}return()=>{window.pJS&&window.pJS[e]?.destroy&&window.pJS[e].destroy()}},[e])}var Jl=`session.open`,Yl=`session.set`,Xl=`session.ids`,Zl=`session.materialize`,Ql=`session.close`,$l=`session.delta`;function eu(){let[e,t]=(0,X.useState)(null),[n,r]=(0,X.useState)(!0),[i,a]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=!0;async function n(){try{r(!0),a(null);let n=await J.get(`/ping`,{skipAuth:!0});e&&(n?.version?t(n.version):a(`Invalid server response`))}catch(t){e&&(console.error(`Failed to fetch server version:`,t),a(`Unable to connect to server`))}finally{e&&r(!1)}}n();let i=setInterval(n,3e4);return()=>{e=!1,clearInterval(i)}},[]),{serverVersion:e,isLoading:n,error:i}}var tu=`https://github.com/canvas-ui/canvas-server`,nu=null;function ru(){return nu||=J.get(`/ping`,{skipAuth:!0}).then(e=>{let t=e??{};return{sourceUrl:t.sourceUrl||tu,version:t.version??null,commit:t.commit??null,license:t.license??null}}).catch(e=>(console.error(`Failed to fetch server source info:`,e),nu=null,{sourceUrl:tu,version:null,commit:null,license:null})),nu}function iu(){let[e,t]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=!0;return ru().then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function au({className:e=``}){let t=iu();if(!t)return null;let n=[t.version?`v${t.version}`:null,t.commit?.slice(0,7)].filter(Boolean).join(` `);return(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground ${e}`,children:[`Powered by`,` `,(0,Z.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Canvas`}),n?` ${n}`:``,t.license?`, ${t.license}`:``,`.`,` `,(0,Z.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})}function ou({children:e}){ql(`particle-js`);let{serverVersion:t,isLoading:n,error:r}=eu();return(0,Z.jsx)(`div`,{className:`flex min-h-viewport w-full items-center justify-center p-4 flex-col`,children:(0,Z.jsxs)(zl,{className:`flex w-[95vw] h-viewport-modal overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`hidden md:block w-1/2 relative bg-background`,"data-scheme":`dark`,id:`particle-js`,children:[(0,Z.jsxs)(we,{className:`absolute top-8 left-8 font-bold text-foreground flex items-center z-raised`,to:`/`,children:[(0,Z.jsx)(`img`,{src:`/images/logo-wr_128x128.png`,alt:`Canvas Logo`,className:`mr-2 h-6 w-6 touch-target`}),(0,Z.jsx)(`span`,{className:`text-2xl font-bold text-foreground`,children:`Canvas`})]}),(0,Z.jsxs)(`div`,{className:`absolute bottom-8 left-8 text-sm text-foreground max-w-[80%] z-raised`,children:[`Web UI: v`,Gl,`, Server: `,n?`Loading...`:r?`Unavailable`:t?`v${t}`:`Unknown`]})]}),(0,Z.jsx)(`div`,{className:`flex w-full md:w-1/2 flex-col justify-center px-4 py-12 sm:px-6 lg:px-8`,children:(0,Z.jsxs)(`div`,{className:`mx-auto w-full max-w-sm`,children:[e,(0,Z.jsxs)(`div`,{className:`mt-8 border-t pt-6`,children:[(0,Z.jsxs)(`a`,{href:`https://github.com/canvas-ui`,target:`_blank`,className:`text-muted-foreground hover:text-foreground justify-center flex items-center space-x-2`,rel:`noopener noreferrer`,children:[(0,Z.jsx)(`svg`,{viewBox:`0 0 24 24`,width:`24`,height:`24`,stroke:`currentColor`,fill:`none`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:`w-6 h-6`,children:(0,Z.jsx)(`path`,{d:`M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22`})}),(0,Z.jsx)(`span`,{children:`View on GitHub`})]}),(0,Z.jsx)(au,{className:`mt-4 text-center`})]})]})})]})})}async function su(e,t,n=`auto`){try{let r=await J.post(no.login,{email:e,password:t,strategy:n},{skipAuth:!0});console.log(`Login response:`,r);let i=r;if(`token`in i)return console.log(`Setting auth token (direct):`,i.token.substring(0,10)+`...`),J.setAuthToken(i.token),B.connect(i.token),r;if(i&&`payload`in i&&i.payload&&i.payload.token)return console.log(`Setting auth token (nested):`,i.payload.token.substring(0,10)+`...`),J.setAuthToken(i.payload.token),B.connect(i.payload.token),r;throw console.error(`Invalid login response structure:`,r),Error(`Invalid login response: missing token`)}catch(e){throw console.error(`Login error:`,e),J.clearAuthToken(),e}}async function cu(e,t,n){try{return await J.post(no.register,{name:e,email:t,password:n},{skipAuth:!0})}catch(e){throw console.error(`Registration failed:`,e),e}}function lu(e){return e instanceof Error&&/^Network error/i.test(e.message)}function uu(){let e=localStorage.getItem(`authToken`);if(!e)return!1;if(e.startsWith(`canvas-`))return!0;try{return eo(e).exp*1e3>Date.now()}catch{return!1}}function du(){let e=localStorage.getItem(`authToken`);if(!e||e.startsWith(`canvas-`))return null;try{let t=eo(e);return t.exp*1e3<Date.now()?(J.clearAuthToken(),null):{id:t.sub,email:t.email,userType:t.userType||`user`}}catch(e){return console.error(`Failed to decode token:`,e),J.clearAuthToken(),null}}async function fu(){try{if(!J.isAuthenticated())return console.log(`Not authenticated, skipping getCurrentUser request`),null;let e=await J.get(no.me);return console.log(`Current user response:`,e),e&&e?(B.isConnected()||B.reconnect(),e):(console.warn(`Invalid user profile response structure:`,e),null)}catch(e){if(console.error(`Failed to get current user:`,e),lu(e))throw e;return e instanceof Error&&(e.message.includes(`USER_NOT_FOUND_IN_DATABASE`)||e.message.includes(`Your session is invalid`)||e.message.includes(`Authentication required`)||e.message.includes(`user account no longer exists`))?(console.warn(`Authentication error detected, clearing token:`,e.message),J.clearAuthToken(),B.disconnect(),null):null}}function pu(){return J.isAuthenticated()}function mu(){let e=new URL(`${yo}/oauth/google/login`);e.searchParams.set(`origin`,window.location.origin),window.location.assign(e.toString())}async function hu(e){let t=await J.post(`${yo}/oauth/google/exchange`,{code:e},{skipAuth:!0});if(!t?.token)throw Error(`Invalid login response: missing token`);J.setAuthToken(t.token),B.connect(t.token)}async function gu(){try{let e=await J.get(no.authConfig,{skipAuth:!0});return e||e}catch(e){return console.error(`Failed to get auth config:`,e),{strategies:{local:{enabled:!0},imap:{enabled:!1,domains:[]}}}}}async function _u(e){try{await J.post(no.verifyEmailRequest,{email:e},{skipAuth:!0})}catch(e){throw console.error(`Failed to request email verification:`,e),e}}var vu=e=>e?.strategies?.local?.enabled!==!1,yu=e=>e?.allowUserRegistrations!==!1;function bu(){let e=ft(),[t,n]=X.useState(!1),[r,i]=X.useState(``),[a,o]=X.useState(``),[s,c]=X.useState(!1),[l,u]=X.useState({}),[d,p]=X.useState(null),[m,h]=X.useState({email:``,password:``,strategy:`auto`});X.useEffect(()=>{uu()&&e(`/workspaces`),fetch(`${yo}/runtime/capabilities`).then(e=>e.ok?e.json():null).then(e=>n(e?.payload?.local===!0)).catch(()=>{}),gu().then(e=>{p(e)}).catch(e=>{console.error(`Failed to load auth config:`,e)})},[e]);let g=()=>{let e={};return m.email?/\S+@\S+\.\S+/.test(m.email)||(e.email=`Email is invalid`):e.email=`Email is required`,m.password||(e.password=`Password is required`),u(e),Object.keys(e).length===0},_=e=>{let{name:t,value:n}=e.target;h(e=>({...e,[t]:n}))};async function v(t){if(t.preventDefault(),g()){c(!0);try{console.log(`Attempting login with:`,m.email,`strategy:`,m.strategy);let t=await su(m.email,m.password,m.strategy);console.log(`Login successful, received token:`,`token`in t?!!t.token:!!t.payload?.token),u({}),e(`/home`)}catch(e){console.error(`Login error:`,e);let t=`Login failed`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;n.message?t=n.message:n.error?t=n.error:n.payload?.message&&(t=n.payload.message)}u({password:t})}finally{c(!1)}}}return t?(0,Z.jsx)(ou,{children:(0,Z.jsxs)(`form`,{className:`grid gap-4`,onSubmit:async t=>{t.preventDefault(),c(!0),o(``);try{if(J.setAuthToken(r.trim()),!await fu())throw Error(`The local token was not accepted`);e(`/workspaces`)}catch(e){J.clearAuthToken(),o(e instanceof Error?e.message:`Authentication failed`)}finally{c(!1)}},children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold`,children:`Connect to your local runtime`}),(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Enter the token shown by `,(0,Z.jsx)(`code`,{children:`canvas runtime token`}),` in the runtime folder.`]}),(0,Z.jsx)(G,{htmlFor:`local-token`,children:`Local access token`}),(0,Z.jsx)(q,{id:`local-token`,type:`password`,autoComplete:`off`,value:r,onChange:e=>i(e.target.value),required:!0}),a&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}),(0,Z.jsx)(Y,{disabled:s,children:s?`Connecting…`:`Connect`})]})}):(0,Z.jsx)(ou,{children:(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Welcome back`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your credentials to access your account`})]}),(0,Z.jsx)(`form`,{onSubmit:v,children:(0,Z.jsxs)(`div`,{className:`grid gap-4`,children:[d?.strategies?.imap?.enabled&&d.strategies.imap.domains.length>0&&(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(G,{htmlFor:`strategy`,children:`Authentication Method`}),(0,Z.jsxs)(`select`,{id:`strategy`,name:`strategy`,value:m.strategy,onChange:_,disabled:s,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`,children:[(0,Z.jsx)(`option`,{value:`auto`,children:`Auto-detect`}),(0,Z.jsx)(`option`,{value:`local`,children:`Local Account`}),(0,Z.jsx)(`option`,{value:`imap`,children:`Email Server (IMAP)`})]})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(G,{htmlFor:`email`,children:`Email`}),(0,Z.jsx)(q,{id:`email`,name:`email`,placeholder:`name@example.com`,type:`email`,autoCapitalize:`none`,autoComplete:`email`,autoCorrect:`off`,disabled:s,value:m.email,onChange:_}),l.email&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:l.email})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(G,{htmlFor:`password`,children:`Password`}),(0,Z.jsx)(q,{id:`password`,name:`password`,type:`password`,disabled:s,value:m.password,onChange:_}),l.password&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:l.password})]}),(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,Z.jsx)(Y,{type:`submit`,disabled:s,children:s?`Signing in...`:`Sign In`}),d?.strategies?.google?.enabled&&(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,disabled:s,onClick:()=>mu(),children:[(0,Z.jsx)(f,{icon:`logos:google-icon`,width:16,height:16,className:`mr-2`}),`Sign in with Google`]}),vu(d)&&yu(d)&&(0,Z.jsx)(Y,{variant:`outline`,type:`button`,disabled:s,onClick:()=>e(`/register`),children:`Don't have an account? Sign up`})]})]})})]})})}function xu(){let e=ft(),{showToast:t}=wo(),[n,r]=X.useState(!1),[i,a]=X.useState({}),[o,s]=X.useState({name:``,email:``,password:``}),[c,l]=X.useState(!1),[u,d]=X.useState(!1),[f,p]=X.useState(null);X.useEffect(()=>{(async()=>{let t=await gu(),n=t?.strategies?.local;if(t?.allowUserRegistrations===!1||n?.enabled===!1){e(`/login`,{replace:!0});return}n?.passwordPolicy&&p(n.passwordPolicy),d(!!n?.requireEmailVerification)})()},[e]);let m=X.useMemo(()=>{if(!f)return null;let e=o.password||``;return{minLength:!f.minLength||e.length>=f.minLength,maxLength:!f.maxLength||e.length<=f.maxLength,uppercase:!f.requireUppercase||/[A-Z]/.test(e),lowercase:!f.requireLowercase||/[a-z]/.test(e),number:!f.requireNumbers||/[0-9]/.test(e),special:!f.requireSpecialChars||/[^A-Za-z0-9]/.test(e)}},[f,o.password]),h=()=>{let e={};if(!o.name)e.name=`Username is required`;else if(o.name.trim().length===0)e.name=`Username cannot be empty`;else{let t=o.name.toLowerCase().trim();t.length<3?e.name=`Username must be at least 3 characters long`:t.length>39?e.name=`Username cannot be longer than 39 characters`:/^[a-z0-9_-]+$/.test(t)?[`admin`,`administrator`,`root`,`system`,`support`,`help`,`api`,`www`,`mail`,`ftp`,`localhost`,`test`,`demo`,`canvas`,`universe`,`workspace`,`context`,`user`,`users`].includes(t)&&(e.name=`Username '${t}' is reserved and cannot be used`):e.name=`Username can only contain lowercase letters, numbers, underscores, and hyphens`}if(o.email?/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o.email)||(e.email=`Please enter a valid email address`):e.email=`Email is required`,!o.password)e.password=`Password is required`;else if(f){let t=o.password,n=[];f.minLength&&t.length<f.minLength&&n.push(`at least ${f.minLength} characters`),f.maxLength&&t.length>f.maxLength&&n.push(`no more than ${f.maxLength} characters`),f.requireUppercase&&!/[A-Z]/.test(t)&&n.push(`an uppercase letter`),f.requireLowercase&&!/[a-z]/.test(t)&&n.push(`a lowercase letter`),f.requireNumbers&&!/[0-9]/.test(t)&&n.push(`a number`),f.requireSpecialChars&&!/[^A-Za-z0-9]/.test(t)&&n.push(`a special character`),n.length&&(e.password=`Password must contain ${n.join(`, `).replace(/, ([^,]*)$/,` and $1`)}.`)}else o.password.length<8&&(e.password=`Password must be at least 8 characters long`);return a(e),Object.keys(e).length===0},g=e=>{let t={...o,[e.target.id]:e.target.value};s(t),(e.target.id===`name`||e.target.id===`email`||e.target.id===`password`)&&h()};return c?(0,Z.jsxs)(ou,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Registration Successful!`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:u?`Check your email for a verification link to activate your account.`:`Your account has been created.`})]}),(0,Z.jsx)(`div`,{className:`space-y-6 text-center pt-6`,children:!u&&(0,Z.jsx)(Y,{asChild:!0,className:`w-full`,children:(0,Z.jsx)(we,{to:`/login`,children:`Go to Login`})})})]}):(0,Z.jsxs)(ou,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Create an account`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your email below to create your account`})]}),(0,Z.jsxs)(`form`,{onSubmit:async e=>{if(e.preventDefault(),h()){r(!0);try{let e=await cu(o.name,o.email,o.password);console.log(`Registration successful:`,e),t({title:`Registration Successful`,description:u?`Check your email for a verification link before logging in.`:`You can now log in with your credentials.`,variant:`default`}),l(!0),s({name:``,email:``,password:``}),a({})}catch(e){console.error(`Registration failed:`,e);let n=e?.message||`Registration failed`;n.toLowerCase().includes(`password`)?a({...i,password:n}):a({...i,email:n}),t({title:`Registration Failed`,description:n,variant:`destructive`})}finally{r(!1)}}},className:`space-y-4 pt-6`,children:[(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(G,{htmlFor:`name`,children:`Username`}),(0,Z.jsx)(q,{id:`name`,type:`text`,placeholder:`Enter your username (e.g., john_doe)`,value:o.name,onChange:g,disabled:n,className:i.name?`border-destructive`:``}),i.name&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.name}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`3-39 characters, lowercase letters, numbers, underscores, and hyphens only`})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(G,{htmlFor:`email`,children:`Email`}),(0,Z.jsx)(q,{id:`email`,type:`email`,placeholder:`name@example.com`,value:o.email,onChange:g,disabled:n,className:i.email?`border-destructive`:``}),i.email&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.email})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(G,{htmlFor:`password`,children:`Password`}),(0,Z.jsx)(q,{id:`password`,type:`password`,placeholder:`Enter your password`,value:o.password,onChange:g,disabled:n,className:i.password?`border-destructive`:``}),i.password&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.password}),f&&m&&(0,Z.jsxs)(`ul`,{className:`text-xs list-disc pl-4 space-y-1`,children:[(0,Z.jsxs)(`li`,{className:m.minLength?`text-success`:`text-muted-foreground`,children:[`At least `,f.minLength,` characters`]}),f.requireUppercase&&(0,Z.jsx)(`li`,{className:m.uppercase?`text-success`:`text-muted-foreground`,children:`At least one uppercase letter`}),f.requireLowercase&&(0,Z.jsx)(`li`,{className:m.lowercase?`text-success`:`text-muted-foreground`,children:`At least one lowercase letter`}),f.requireNumbers&&(0,Z.jsx)(`li`,{className:m.number?`text-success`:`text-muted-foreground`,children:`At least one number`}),f.requireSpecialChars&&(0,Z.jsx)(`li`,{className:m.special?`text-success`:`text-muted-foreground`,children:`At least one special character`}),f.maxLength&&(0,Z.jsxs)(`li`,{className:m.maxLength?`text-success`:`text-muted-foreground`,children:[`No more than `,f.maxLength,` characters`]})]})]}),(0,Z.jsx)(Y,{type:`submit`,className:`w-full`,disabled:n,children:n?`Creating Account...`:`Create Account`})]}),(0,Z.jsxs)(`div`,{className:`mt-4 text-center text-sm`,children:[`Already have an account?`,` `,(0,Z.jsx)(we,{to:`/login`,className:`underline`,children:`Sign in`})]}),(0,Z.jsxs)(`div`,{className:`px-8 py-4 text-center text-sm text-muted-foreground border-t mt-6`,children:[`By clicking continue, you agree to our`,` `,(0,Z.jsx)(we,{to:`/terms`,className:`underline underline-offset-4 hover:text-primary`,children:`Terms of Service`}),` `,`and`,` `,(0,Z.jsx)(we,{to:`/privacy`,className:`underline underline-offset-4 hover:text-primary`,children:`Privacy Policy`}),`.`]})]})}function Su(){let e=ft(),[t]=$t(),[n,r]=X.useState(t.get(`error`)),i=X.useRef(!1);return X.useEffect(()=>{let n=t.get(`code`);!n||i.current||(i.current=!0,hu(n).then(()=>e(`/home`,{replace:!0})).catch(e=>r(e instanceof Error?e.message:`Google sign-in failed`)))},[t,e]),(0,Z.jsx)(ou,{children:(0,Z.jsx)(`div`,{className:`flex flex-col space-y-4 text-center`,children:n?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Google sign-in failed`}),(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:n}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,onClick:()=>e(`/login`,{replace:!0}),children:`Back to sign in`})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Signing you in…`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Completing Google sign-in.`})]})})})}function Cu({children:e}){let[t,n]=(0,X.useState)(`loading`);return(0,X.useEffect)(()=>{(async()=>{try{if(!pu()){console.log(`No authentication token found, redirecting to login`),n(`unauthenticated`);return}let e=await fu();e?(console.log(`User authenticated:`,e.email),n(`authenticated`)):(console.log(`User not authenticated or token expired`),n(`unauthenticated`))}catch(e){if(console.error(`Authentication check failed:`,e),lu(e)){if(uu()){n(`authenticated`);return}J.clearAuthToken(),n(`unauthenticated`);return}e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from ProtectedRoute`),J.clearAuthToken()),n(`unauthenticated`)}})()},[]),t===`loading`?(0,Z.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,Z.jsx)(nn,{className:`h-8 w-8`})}):t===`unauthenticated`?(0,Z.jsx)(ht,{to:`/login`,replace:!0}):(0,Z.jsx)(Z.Fragment,{children:e})}function wu({children:e}){let[t,n]=(0,X.useState)(null);return(0,X.useEffect)(()=>{(async()=>{try{await J.get(`/auth/me`),n(!0)}catch(e){e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from PublicRoute`),J.clearAuthToken()),n(!1)}})()},[]),t===null?null:t?(0,Z.jsx)(ht,{to:`/workspaces`,replace:!0}):(0,Z.jsx)(Z.Fragment,{children:e})}var Tu=i(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?r(e):typeof define==`function`&&define.amd?define([`exports`],r):(n=typeof globalThis<`u`?globalThis:n||self,r(n[`fast-equals`]={}))})(e,(function(e){function t(e){return function(t,n,r,i,a,o,s){return e(t,n,s)}}function n(e){return function(t,n,r,i){if(!t||!n||typeof t!=`object`||typeof n!=`object`)return e(t,n,r,i);var a=i.get(t),o=i.get(n);if(a&&o)return a===n&&o===t;i.set(t,n),i.set(n,t);var s=e(t,n,r,i);return i.delete(t),i.delete(n),s}}function r(e,t){var n={};for(var r in e)n[r]=e[r];for(var r in t)n[r]=t[r];return n}function i(e){return e.constructor===Object||e.constructor==null}function a(e){return typeof e.then==`function`}function o(e,t){return e===t||e!==e&&t!==t}var s=Object.prototype.toString;function c(e){var t=e.areArraysEqual,n=e.areDatesEqual,r=e.areMapsEqual,c=e.areObjectsEqual,l=e.areRegExpsEqual,u=e.areSetsEqual,d=e.createIsNestedEqual,f=d(p);function p(e,d,p){if(e===d)return!0;if(!e||!d||typeof e!=`object`||typeof d!=`object`)return e!==e&&d!==d;if(i(e)&&i(d))return c(e,d,f,p);var m=Array.isArray(e),h=Array.isArray(d);if(m||h)return m===h&&t(e,d,f,p);var g=s.call(e);return g===s.call(d)?g===`[object Date]`?n(e,d,f,p):g===`[object RegExp]`?l(e,d,f,p):g===`[object Map]`?r(e,d,f,p):g===`[object Set]`?u(e,d,f,p):g===`[object Object]`||g===`[object Arguments]`?a(e)||a(d)?!1:c(e,d,f,p):g===`[object Boolean]`||g===`[object Number]`||g===`[object String]`?o(e.valueOf(),d.valueOf()):!1:!1}return p}function l(e,t,n,r){var i=e.length;if(t.length!==i)return!1;for(;i-->0;)if(!n(e[i],t[i],i,i,e,t,r))return!1;return!0}var u=n(l);function d(e,t){return o(e.valueOf(),t.valueOf())}function f(e,t,n,r){var i=e.size===t.size;if(!i)return!1;if(!e.size)return!0;var a={},o=0;return e.forEach(function(s,c){if(i){var l=!1,u=0;t.forEach(function(i,d){!l&&!a[u]&&(l=n(c,d,o,u,e,t,r)&&n(s,i,c,d,e,t,r))&&(a[u]=!0),u++}),o++,i=l}}),i}var p=n(f),m=`_owner`,h=Object.prototype.hasOwnProperty;function g(e,t,n,r){var i=Object.keys(e),a=i.length;if(Object.keys(t).length!==a)return!1;for(var o;a-->0;){if(o=i[a],o===m){var s=!!e.$$typeof,c=!!t.$$typeof;if((s||c)&&s!==c)return!1}if(!h.call(t,o)||!n(e[o],t[o],o,o,e,t,r))return!1}return!0}var _=n(g);function v(e,t){return e.source===t.source&&e.flags===t.flags}function y(e,t,n,r){var i=e.size===t.size;if(!i)return!1;if(!e.size)return!0;var a={};return e.forEach(function(o,s){if(i){var c=!1,l=0;t.forEach(function(i,u){!c&&!a[l]&&(c=n(o,i,s,u,e,t,r))&&(a[l]=!0),l++}),i=c}}),i}var b=n(y),x=Object.freeze({areArraysEqual:l,areDatesEqual:d,areMapsEqual:f,areObjectsEqual:g,areRegExpsEqual:v,areSetsEqual:y,createIsNestedEqual:t}),S=Object.freeze({areArraysEqual:u,areDatesEqual:d,areMapsEqual:p,areObjectsEqual:_,areRegExpsEqual:v,areSetsEqual:b,createIsNestedEqual:t}),C=c(x);function w(e,t){return C(e,t,void 0)}var T=c(r(x,{createIsNestedEqual:function(){return o}}));function E(e,t){return T(e,t,void 0)}var D=c(S);function O(e,t){return D(e,t,new WeakMap)}var k=c(r(S,{createIsNestedEqual:function(){return o}}));function A(e,t){return k(e,t,new WeakMap)}function j(e){return c(r(x,e(x)))}function M(e){var t=c(r(S,e(S)));return(function(e,n,r){return r===void 0&&(r=new WeakMap),t(e,n,r)})}e.circularDeepEqual=O,e.circularShallowEqual=A,e.createCustomCircularEqual=M,e.createCustomEqual=j,e.deepEqual=w,e.sameValueZeroEqual=o,e.shallowEqual=E,Object.defineProperty(e,"__esModule",{value:!0})}))})),Eu=i(((e,t)=>{t.exports=function(e,t,n){return e===t||e.className===t.className&&n(e.style,t.style)&&e.width===t.width&&e.autoSize===t.autoSize&&e.cols===t.cols&&e.draggableCancel===t.draggableCancel&&e.draggableHandle===t.draggableHandle&&n(e.verticalCompact,t.verticalCompact)&&n(e.compactType,t.compactType)&&n(e.layout,t.layout)&&n(e.margin,t.margin)&&n(e.containerPadding,t.containerPadding)&&e.rowHeight===t.rowHeight&&e.maxRows===t.maxRows&&e.isBounded===t.isBounded&&e.isDraggable===t.isDraggable&&e.isResizable===t.isResizable&&e.allowOverlap===t.allowOverlap&&e.preventCollision===t.preventCollision&&e.useCSSTransforms===t.useCSSTransforms&&e.transformScale===t.transformScale&&e.isDroppable===t.isDroppable&&n(e.resizeHandles,t.resizeHandles)&&n(e.resizeHandle,t.resizeHandle)&&e.onLayoutChange===t.onLayoutChange&&e.onDragStart===t.onDragStart&&e.onDrag===t.onDrag&&e.onDragStop===t.onDragStop&&e.onResizeStart===t.onResizeStart&&e.onResize===t.onResize&&e.onResizeStop===t.onResizeStop&&e.onDrop===t.onDrop&&n(e.droppingItem,t.droppingItem)&&n(e.innerRef,t.innerRef)}})),Du=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.bottom=l,e.childrenEqual=h,e.cloneLayout=u,e.cloneLayoutItem=m,e.collides=_,e.compact=v,e.compactItem=x,e.compactType=se,e.correctBounds=S,e.fastPositionEqual=g,e.fastRGLPropsEqual=void 0,e.getAllCollisions=T,e.getFirstCollision=w,e.getLayoutItem=C,e.getStatics=E,e.modifyLayout=f,e.moveElement=D,e.moveElementAwayFromCollision=O,e.noop=void 0,e.perc=k,e.resizeItemInDirection=L,e.setTopLeft=ne,e.setTransform=R,e.sortLayoutItems=re,e.sortLayoutItemsByColRow=ae,e.sortLayoutItemsByRowCol=ie,e.synchronizeLayoutWithChildren=z,e.validateLayout=oe,e.withLayoutItem=p;var t=Tu(),n=r(d());function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?i(Object(n),!0).forEach(function(t){o(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function o(e,t,n){return(t=s(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e){var t=c(e,`string`);return typeof t==`symbol`?t:t+``}function c(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function l(e){let t=0,n;for(let r=0,i=e.length;r<i;r++)n=e[r].y+e[r].h,n>t&&(t=n);return t}function u(e){let t=Array(e.length);for(let n=0,r=e.length;n<r;n++)t[n]=m(e[n]);return t}function f(e,t){let n=Array(e.length);for(let r=0,i=e.length;r<i;r++)t.i===e[r].i?n[r]=t:n[r]=e[r];return n}function p(e,t,n){let r=C(e,t);return r?(r=n(m(r)),e=f(e,r),[e,r]):[e,null]}function m(e){return{w:e.w,h:e.h,x:e.x,y:e.y,i:e.i,minW:e.minW,maxW:e.maxW,minH:e.minH,maxH:e.maxH,moved:!!e.moved,static:!!e.static,isDraggable:e.isDraggable,isResizable:e.isResizable,resizeHandles:e.resizeHandles,isBounded:e.isBounded}}function h(e,r){return(0,t.deepEqual)(n.default.Children.map(e,e=>e?.key),n.default.Children.map(r,e=>e?.key))&&(0,t.deepEqual)(n.default.Children.map(e,e=>e?.props[`data-grid`]),n.default.Children.map(r,e=>e?.props[`data-grid`]))}e.fastRGLPropsEqual=Eu();function g(e,t){return e.left===t.left&&e.top===t.top&&e.width===t.width&&e.height===t.height}function _(e,t){return!(e.i===t.i||e.x+e.w<=t.x||e.x>=t.x+t.w||e.y+e.h<=t.y||e.y>=t.y+t.h)}function v(e,t,n,r){let i=E(e),a=l(i),o=re(e,t),s=Array(e.length);for(let c=0,l=o.length;c<l;c++){let l=m(o[c]);l.static||(l=x(i,l,t,n,o,r,a),a=Math.max(a,l.y+l.h),i.push(l)),s[e.indexOf(o[c])]=l,l.moved=!1}return s}var y={x:`w`,y:`h`};function b(e,t,n,r){let i=y[r];t[r]+=1;let a=e.map(e=>e.i).indexOf(t.i);for(let o=a+1;o<e.length;o++){let a=e[o];if(!a.static){if(a.y>t.y+t.h)break;_(t,a)&&b(e,a,n+t[i],r)}}t[r]=n}function x(e,t,n,r,i,a,o){let s=n===`vertical`,c=n===`horizontal`;if(s)for(t.y=Math.min(typeof o==`number`?o:l(e),t.y);t.y>0&&!w(e,t);)t.y--;else if(c)for(;t.x>0&&!w(e,t);)t.x--;let u;for(;(u=w(e,t))&&!(n===null&&a);)if(c?b(i,t,u.x+u.w,`x`):b(i,t,u.y+u.h,`y`),c&&t.x+t.w>r)for(t.x=r-t.w,t.y++;t.x>0&&!w(e,t);)t.x--;return t.y=Math.max(t.y,0),t.x=Math.max(t.x,0),t}function S(e,t){let n=E(e);for(let r=0,i=e.length;r<i;r++){let i=e[r];if(i.x+i.w>t.cols&&(i.x=t.cols-i.w),i.x<0&&(i.x=0,i.w=t.cols),!i.static)n.push(i);else for(;w(n,i);)i.y++}return e}function C(e,t){for(let n=0,r=e.length;n<r;n++)if(e[n].i===t)return e[n]}function w(e,t){for(let n=0,r=e.length;n<r;n++)if(_(e[n],t))return e[n]}function T(e,t){return e.filter(e=>_(e,t))}function E(e){return e.filter(e=>e.static)}function D(e,t,n,r,i,a,o,s,c){if(t.static&&t.isDraggable!==!0||t.y===r&&t.x===n)return e;`${t.i}${String(n)}${String(r)}${t.x}${t.y}`;let l=t.x,d=t.y;typeof n==`number`&&(t.x=n),typeof r==`number`&&(t.y=r),t.moved=!0;let f=re(e,o);(o===`vertical`&&typeof r==`number`?d>=r:o===`horizontal`&&typeof n==`number`&&l>=n)&&(f=f.reverse());let p=T(f,t),m=p.length>0;if(m&&c)return u(e);if(m&&a)return`${t.i}`,t.x=l,t.y=d,t.moved=!1,e;for(let n=0,r=p.length;n<r;n++){let r=p[n];`${t.i}${t.x}${t.y}${r.i}${r.x}${r.y}`,!r.moved&&(e=r.static?O(e,r,t,i,o,s):O(e,t,r,i,o,s))}return e}function O(e,t,n,r,i,a){let o=i===`horizontal`,s=i===`vertical`,c=t.static;if(r){r=!1;let l={x:o?Math.max(t.x-n.w,0):n.x,y:s?Math.max(t.y-n.h,0):n.y,w:n.w,h:n.h,i:`-1`},u=w(e,l),d=u&&u.y+u.h>t.y,f=u&&t.x+t.w>u.x;if(!u)return`${n.i}${l.x}${l.y}`,D(e,n,o?l.x:void 0,s?l.y:void 0,r,c,i,a);if(d&&s)return D(e,n,void 0,n.y+1,r,c,i,a);if(d&&i==null)return t.y=n.y,n.y+=n.h,e;if(f&&o)return D(e,t,n.x,void 0,r,c,i,a)}let l=o?n.x+1:void 0,u=s?n.y+1:void 0;return l==null&&u==null?e:D(e,n,o?n.x+1:void 0,s?n.y+1:void 0,r,c,i,a)}function k(e){return e*100+`%`}var A=(e,t,n,r)=>e+n>r?t:n,j=(e,t,n)=>e<0?t:n,M=e=>Math.max(0,e),N=e=>Math.max(0,e),P=(e,t,n)=>{let{left:r,height:i,width:a}=t,o=e.top-(i-e.height);return{left:r,width:a,height:j(o,e.height,i),top:N(o)}},ee=(e,t,n)=>{let{top:r,left:i,height:a,width:o}=t;return{top:r,height:a,width:A(e.left,e.width,o,n),left:M(i)}},F=(e,t,n)=>{let{top:r,height:i,width:a}=t,o=e.left-(a-e.width);return{height:i,width:o<0?e.width:A(e.left,e.width,a,n),top:N(r),left:M(o)}},I=(e,t,n)=>{let{top:r,left:i,height:a,width:o}=t;return{width:o,left:i,height:j(r,e.height,a),top:N(r)}},te={n:P,ne:function(){return P(arguments.length<=0?void 0:arguments[0],ee(...arguments),arguments.length<=2?void 0:arguments[2])},e:ee,se:function(){return I(arguments.length<=0?void 0:arguments[0],ee(...arguments),arguments.length<=2?void 0:arguments[2])},s:I,sw:function(){return I(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])},w:F,nw:function(){return P(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])}};function L(e,t,n,r){let i=te[e];return i?i(t,a(a({},t),n),r):n}function R(e){let{top:t,left:n,width:r,height:i}=e,a=`translate(${n}px,${t}px)`;return{transform:a,WebkitTransform:a,MozTransform:a,msTransform:a,OTransform:a,width:`${r}px`,height:`${i}px`,position:`absolute`}}function ne(e){let{top:t,left:n,width:r,height:i}=e;return{top:`${t}px`,left:`${n}px`,width:`${r}px`,height:`${i}px`,position:`absolute`}}function re(e,t){return t===`horizontal`?ae(e):t===`vertical`?ie(e):e}function ie(e){return e.slice(0).sort(function(e,t){return e.y>t.y||e.y===t.y&&e.x>t.x?1:e.y===t.y&&e.x===t.x?0:-1})}function ae(e){return e.slice(0).sort(function(e,t){return e.x>t.x||e.x===t.x&&e.y>t.y?1:-1})}function z(e,t,r,i,o){e||=[];let s=[];n.default.Children.forEach(t,t=>{if(t?.key==null)return;let n=C(e,String(t.key)),r=t.props[`data-grid`];n&&r==null?s.push(m(n)):r?s.push(m(a(a({},r),{},{i:t.key}))):s.push(m({w:1,h:1,x:0,y:l(s),i:String(t.key)}))});let c=S(s,{cols:r});return o?c:v(c,i,r)}function oe(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Layout`,n=[`x`,`y`,`w`,`h`];if(!Array.isArray(e))throw Error(t+` must be an array!`);for(let r=0,i=e.length;r<i;r++){let i=e[r];for(let e=0;e<n.length;e++){let a=n[e],o=i[a];if(typeof o!=`number`||Number.isNaN(o))throw Error(`ReactGridLayout: ${t}[${r}].${a} must be a number! Received: ${o} (${typeof o})`)}if(i.i!==void 0&&typeof i.i!=`string`)throw Error(`ReactGridLayout: ${t}[${r}].i must be a string! Received: ${i.i} (${typeof i.i})`)}}function se(e){let{verticalCompact:t,compactType:n}=e||{};return t===!1?null:n}e.noop=()=>{}})),Ou=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.calcGridColWidth=t,e.calcGridItemPosition=r,e.calcGridItemWHPx=n,e.calcWH=a,e.calcXY=i,e.clamp=o;function t(e){let{margin:t,containerPadding:n,containerWidth:r,cols:i}=e;return(r-t[0]*(i-1)-n[0]*2)/i}function n(e,t,n){return Number.isFinite(e)?Math.round(t*e+Math.max(0,e-1)*n):e}function r(e,r,i,a,o,s){let{margin:c,containerPadding:l,rowHeight:u}=e,d=t(e),f={};return s&&s.resizing?(f.width=Math.round(s.resizing.width),f.height=Math.round(s.resizing.height)):(f.width=n(a,d,c[0]),f.height=n(o,u,c[1])),s&&s.dragging?(f.top=Math.round(s.dragging.top),f.left=Math.round(s.dragging.left)):s&&s.resizing&&typeof s.resizing.top==`number`&&typeof s.resizing.left==`number`?(f.top=Math.round(s.resizing.top),f.left=Math.round(s.resizing.left)):(f.top=Math.round((u+c[1])*i+l[1]),f.left=Math.round((d+c[0])*r+l[0])),f}function i(e,n,r,i,a){let{margin:s,containerPadding:c,cols:l,rowHeight:u,maxRows:d}=e,f=t(e),p=Math.round((r-c[0])/(f+s[0])),m=Math.round((n-c[1])/(u+s[1]));return p=o(p,0,l-i),m=o(m,0,d-a),{x:p,y:m}}function a(e,n,r,i,a,s){let{margin:c,maxRows:l,cols:u,rowHeight:d}=e,f=t(e),p=Math.round((n+c[0])/(f+c[0])),m=Math.round((r+c[1])/(d+c[1])),h=o(p,0,u-i),g=o(m,0,l-a);return[`sw`,`w`,`nw`].indexOf(s)!==-1&&(h=o(p,0,u)),[`nw`,`n`,`ne`].indexOf(s)!==-1&&(g=o(m,0,l)),{w:h,h:g}}function o(e,t,n){return Math.max(Math.min(e,n),t)}})),ku=i(((e,t)=>{t.exports=`SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED`})),Au=i(((e,t)=>{var n=ku();function r(){}function i(){}i.resetWarningCache=r,t.exports=function(){function e(e,t,r,i,a,o){if(o!==n){var s=Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw s.name=`Invariant Violation`,s}}e.isRequired=e;function t(){return e}var a={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:i,resetWarningCache:r};return a.PropTypes=a,a}})),ju=i(((e,t)=>{t.exports=Au()()})),Mu=i(((e,t)=>{var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,c=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},l=(e,t,n,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!s.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(o=i(t,c))||o.enumerable});return e},u=(e,t,i)=>(i=e==null?{}:n(o(e)),l(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)),f=e=>l(r({},`__esModule`,{value:!0}),e),p={};c(p,{DraggableCore:()=>Se,default:()=>Ce}),t.exports=f(p);var m=u(d()),g=u(ju()),_=u(h()),v=$a();function y(e,t){for(let n=0,r=e.length;n<r;n++)if(t.apply(t,[e[n],n,e]))return e[n]}function b(e){return typeof e==`function`||Object.prototype.toString.call(e)===`[object Function]`}function x(e){return typeof e==`number`&&!isNaN(e)}function S(e){return parseInt(e,10)}function C(e,t,n){if(e[t])return Error(`Invalid prop ${t} passed to ${n} - do not set this, set it on the child.`)}var w=[`Moz`,`Webkit`,`O`,`ms`];function T(e=`transform`){if(typeof window>`u`)return``;let t=window.document?.documentElement?.style;if(!t||e in t)return``;for(let n=0;n<w.length;n++)if(E(e,w[n])in t)return w[n];return``}function E(e,t){return t?`${t}${D(e)}`:e}function D(e){let t=``,n=!0;for(let r=0;r<e.length;r++)n?(t+=e[r].toUpperCase(),n=!1):e[r]===`-`?n=!0:t+=e[r];return t}var O=T(),k=``;function A(e,t){k||=y([`matches`,`webkitMatchesSelector`,`mozMatchesSelector`,`msMatchesSelector`,`oMatchesSelector`],function(t){return b(e[t])})??``;let n=e[k];return b(n)?!!n.call(e,t):!1}function j(e,t,n){let r=e;do{if(A(r,t))return!0;if(r===n)return!1;r=r.parentNode}while(r);return!1}function M(e,t,n,r){if(!e)return;let i={capture:!0,...r},a=n;e.addEventListener?e.addEventListener(t,a,i):e.attachEvent?e.attachEvent(`on`+t,a):e[`on`+t]=a}function N(e,t,n,r){if(!e)return;let i={capture:!0,...r},a=n;e.removeEventListener?e.removeEventListener(t,a,i):e.detachEvent?e.detachEvent(`on`+t,a):e[`on`+t]=null}function P(e){let t=e.clientHeight,n=e.ownerDocument.defaultView.getComputedStyle(e);return t+=S(n.borderTopWidth),t+=S(n.borderBottomWidth),t}function ee(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t+=S(n.borderLeftWidth),t+=S(n.borderRightWidth),t}function F(e){let t=e.clientHeight,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingTop),t-=S(n.paddingBottom),t}function I(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingLeft),t-=S(n.paddingRight),t}function te(e,t,n){let r=t===t.ownerDocument.body?{left:0,top:0}:t.getBoundingClientRect();return{x:(e.clientX+t.scrollLeft-r.left)/n,y:(e.clientY+t.scrollTop-r.top)/n}}function L(e,t){let n=ne(e,t,`px`);return{[E(`transform`,O)]:n}}function R(e,t){return ne(e,t,``)}function ne({x:e,y:t},n,r){let i=`translate(${e}${r},${t}${r})`;return n&&(i=`translate(${`${typeof n.x==`string`?n.x:n.x+r}`}, ${`${typeof n.y==`string`?n.y:n.y+r}`})`+i),i}function re(e,t){return e.targetTouches&&y(e.targetTouches,e=>t===e.identifier)||e.changedTouches&&y(e.changedTouches,e=>t===e.identifier)}function ie(e){if(e.targetTouches&&e.targetTouches[0])return e.targetTouches[0].identifier;if(e.changedTouches&&e.changedTouches[0])return e.changedTouches[0].identifier}function ae(){return typeof __webpack_nonce__<`u`?__webpack_nonce__:void 0}function z(e,t){if(!e)return;let n=e.getElementById(`react-draggable-style-el`);if(!n){n=e.createElement(`style`),n.type=`text/css`,n.id=`react-draggable-style-el`;let r=t??ae();r&&n.setAttribute(`nonce`,r),n.innerHTML=`.react-draggable-transparent-selection *::-moz-selection {all: inherit;}
|
|
2
|
+
import{a as e,n as t,o as n,r,t as i}from"./rolldown-runtime-C0FnF6B9.js";import{a,i as o,l as s,n as c,r as l,t as u,u as d}from"./code-editor-BQnKd3jw.js";import{_t as f,gt as p,vt as m,yt as h}from"./react-BzqgEMSQ.js";import{t as g}from"./preload-helper-Czpn1I53.js";import{$ as _,$n as v,$t as y,A as b,An as x,At as S,B as C,Bn as w,Bt as T,C as E,Cn as D,Ct as O,D as k,Dn as A,Dt as j,E as M,En as N,Et as P,F as ee,Fn as F,Ft as I,G as te,Gn as L,Gt as R,H as ne,Hn as re,Ht as ie,I as ae,In as z,It as oe,J as se,Jn as B,Jt as ce,K as V,Kn as le,Kt as ue,L as de,Ln as fe,Lt as pe,M as me,Mn as he,Mt as ge,N as _e,Nn as ve,Nt as ye,O as be,On as xe,Ot as H,P as Se,Pn as Ce,Pt as U,Q as W,Qn as we,Qt as Te,R as Ee,Rn as De,Rt as Oe,S as ke,Sn as Ae,St as je,T as Me,Tn as Ne,Tt as Pe,U as Fe,Un as Ie,Ut as Le,V as Re,Vn as ze,Vt as Be,W as Ve,Wn as He,Wt as Ue,Xn as We,Xt as Ge,Y as Ke,Yn as G,Yt as qe,Z as Je,Zn as Ye,Zt as Xe,_ as Ze,_n as Qe,_t as $e,a as et,an as tt,ar as nt,at as rt,b as it,bn as at,bt as ot,c as st,cr as ct,ct as lt,d as ut,dn as dt,dr as ft,dt as pt,en as mt,er as ht,et as gt,f as _t,fn as vt,fr as yt,ft as bt,g as xt,gn as St,gt as Ct,h as wt,hn as Tt,ht as Et,i as Dt,in as Ot,ir as kt,it as At,j as jt,jn as Mt,jt as Nt,k as Pt,kn as Ft,kt as It,l as Lt,lr as Rt,lt as zt,m as Bt,mn as Vt,mt as Ht,n as Ut,nn as Wt,nr as Gt,nt as Kt,o as qt,on as Jt,or as Yt,ot as Xt,p as Zt,pn as Qt,pr as $t,pt as en,q as tn,qn as nn,qt as rn,r as an,rn as on,rr as sn,rt as cn,s as ln,sr as un,st as dn,t as fn,tn as pn,tr as mn,tt as hn,u as gn,un as _n,ur as vn,ut as yn,v as bn,vn as xn,vt as Sn,w as Cn,wn,wt as Tn,x as En,xn as Dn,xt as On,y as kn,yn as An,yt as jn,z as Mn,zn as Nn,zt as Pn}from"./document-list-BmUv3zzK.js";import{$ as Fn,$n as In,$r as Ln,$t as Rn,An as zn,Ar as Bn,At as Vn,B as Hn,Bn as Un,Br as Wn,Bt as Gn,C as Kn,Cn as qn,Cr as Jn,Ct as Yn,Dn as Xn,Dr as Zn,En as Qn,F as $n,Fr as er,Ft as tr,G as nr,Gn as rr,Gr as ir,H as ar,Hn as or,Hr as sr,Ht as cr,I as lr,It as ur,J as dr,Jn as fr,Jr as pr,Jt as mr,K as hr,Kn as gr,Kr as _r,L as vr,Lr as yr,Mt as br,Nn as xr,Nr as Sr,Nt as Cr,On as wr,Or as Tr,Ot as Er,P as Dr,Pn as Or,Pr as kr,Pt as Ar,Q as jr,Qn as Mr,Qr as Nr,R as Pr,Rn as Fr,Rr as Ir,Rt as Lr,S as Rr,Sn as zr,St as Br,Tt as Vr,U as Hr,Ur,Ut as Wr,V as Gr,Vn as Kr,Vr as qr,Vt as Jr,W as Yr,Wn as Xr,Wt as Zr,X as Qr,Xn as $r,Xt as ei,Y as ti,Yn as ni,Yr as ri,Yt as ii,Z as ai,Zn as oi,Zr as si,Zt as ci,_ as li,_i as ui,_n as di,_r as fi,_t as pi,an as mi,ar as hi,at as gi,b as _i,bn as vi,br as yi,bt as bi,ci as xi,cn as Si,ct as Ci,d as wi,dn as Ti,dr as Ei,dt as Di,ei as Oi,en as ki,er as Ai,et as ji,f as Mi,fi as Ni,fr as Pi,ft as Fi,g as Ii,gi as Li,gn as Ri,gr as zi,gt as Bi,h as Vi,hi as Hi,hn as Ui,ht as Wi,in as Gi,ir as Ki,it as qi,jn as Ji,jr as Yi,jt as Xi,kn as Zi,kr as Qi,kt as $i,ln as ea,lt as ta,m as na,mi as ra,mr as ia,mt as aa,ni as oa,nn as sa,oi as ca,on as la,or as ua,p as da,pi as fa,pn as pa,pr as ma,pt as ha,q as ga,qn as _a,qt as va,ri as ya,rn as ba,rr as xa,rt as Sa,si as Ca,sn as wa,st as Ta,tn as Ea,tt as Da,u as Oa,ui as ka,un as Aa,ur as ja,ut as Ma,v as Na,vn as Pa,vr as Fa,vt as Ia,w as La,wn as Ra,wr as za,wt as Ba,x as Va,xn as Ha,xt as Ua,y as Wa,yn as Ga,yr as Ka,yt as qa,z as Ja,zn as Ya,zr as Xa,zt as Za}from"./ui-BqHBdBU4.js";import{i as Qa,n as $a,r as eo}from"./utils-BxVxyehK.js";import{n as to,t as K}from"./utils-2pl1SbIp.js";import{_ as no,a as ro,b as q,c as io,d as ao,f as oo,g as so,h as co,i as lo,l as uo,m as fo,n as po,o as mo,p as ho,r as go,s as _o,t as vo,u as J,v as yo,x as Y,y as bo}from"./alert-dialog-BC58hyW-.js";import{t as xo}from"./socket-hM4c-ZSl.js";import{a as So,c as Co,l as wo,n as To,o as Eo,r as Do,s as Oo}from"./blobs-CtDkR2hC.js";import{$ as ko,$t as Ao,A as jo,At as Mo,B as No,C as Po,Cn as Fo,Ct as Io,D as Lo,Dn as Ro,Dt as zo,E as Bo,En as Vo,Fn as Ho,Ft as Uo,Gt as Wo,H as Go,Ht as Ko,I as qo,It as Jo,J as Yo,Jt as Xo,K as Zo,Kn as Qo,Kt as $o,L as es,Ln as ts,M as ns,Mn as rs,Nn as is,Nt as as,O as os,On as ss,Ot as cs,Pn as ls,Pt as us,Q as ds,Qt as fs,R as ps,Rn as ms,S as hs,Sn as gs,St as _s,T as vs,Tn as ys,Tt as bs,U as xs,Ut as Ss,V as Cs,Vt as ws,W as Ts,Wn as Es,Wt as Ds,Yt as Os,Zt as ks,_ as As,_n as js,_t as Ms,a as Ns,an as Ps,at as Fs,b as Is,bn as Ls,bt as Rs,cn as zs,ct as Bs,dn as Vs,dt as Hs,en as Us,et as Ws,f as Gs,fn as Ks,ft as qs,gn as Js,gt as Ys,ht as Xs,i as Zs,it as Qs,j as $s,jt as ec,k as tc,kn as nc,kt as rc,ln as ic,lt as ac,m as oc,mt as sc,n as cc,nn as lc,nt as uc,o as dc,on as fc,ot as pc,p as mc,pn as hc,pt as gc,q as _c,qt as vc,r as yc,rn as bc,rt as xc,s as Sc,sn as Cc,st as wc,t as Tc,tt as Ec,u as Dc,un as Oc,ut as kc,v as Ac,vn as jc,vt as Mc,w as Nc,wn as Pc,wt as Fc,x as Ic,xn as Lc,xt as Rc,y as zc,yt as Bc,z as Vc,zn as Hc,zt as Uc}from"./workspace-BSXnX2Me.js";import{_ as Wc,c as Gc,f as Kc,g as qc,h as Jc,l as Yc,m as Xc,o as Zc,p as Qc,s as $c,u as el,y as tl}from"./text-documents-BvR9-zf4.js";import{B as nl,D as rl,F as il,I as al,L as ol,N as sl,O as cl,P as ll,R as ul,T as dl,_ as fl,a as pl,b as ml,c as hl,d as gl,f as _l,g as vl,h as yl,i as bl,j as xl,m as Sl,n as Cl,o as wl,p as Tl,r as El,s as Dl,t as Ol,u as kl,w as Al,y as jl,z as Ml}from"./useAddTarget-CgZfKokT.js";import{n as Nl,t as Pl}from"./map-BxCwdK0d.js";import{t as Fl}from"./sha256-65KIjGvZ.js";import{n as Il,t as Ll}from"./use-theme-Bd8sb5Ox.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var X=n(d(),1),Rl=m(),Z=s(),zl=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`rounded-(--card-radius) border bg-card text-card-foreground shadow-elevation-1`,e),...t}));zl.displayName=`Card`;var Bl=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`flex flex-col space-y-1.5 p-6`,e),...t}));Bl.displayName=`CardHeader`;var Vl=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`h3`,{ref:n,className:K(`text-2xl font-semibold leading-none tracking-tight`,e),...t}));Vl.displayName=`CardTitle`;var Hl=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`p`,{ref:n,className:K(`text-sm text-muted-foreground`,e),...t}));Hl.displayName=`CardDescription`;var Ul=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`p-6 pt-0`,e),...t}));Ul.displayName=`CardContent`;var Wl=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`flex items-center p-6 pt-0`,e),...t}));Wl.displayName=`CardFooter`;var Gl=`2.26.18`,Kl=e=>{window.particlesJS.load(e,`/js/particles.config.json`,()=>{console.log(`particles.js config loaded for`,e)})};function ql(e){(0,X.useEffect)(()=>{if(window.particlesJS!==void 0)Kl(e);else{if(document.getElementById(`particles-js-script`))return;let t=document.createElement(`script`);t.id=`particles-js-script`,t.src=`/js/particles.min.js`,t.onload=()=>{console.log(`particles.js loaded`),Kl(e)},document.head.appendChild(t)}return()=>{window.pJS&&window.pJS[e]?.destroy&&window.pJS[e].destroy()}},[e])}var Jl=`session.open`,Yl=`session.set`,Xl=`session.ids`,Zl=`session.materialize`,Ql=`session.close`,$l=`session.delta`;function eu(){let[e,t]=(0,X.useState)(null),[n,r]=(0,X.useState)(!0),[i,a]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=!0;async function n(){try{r(!0),a(null);let n=await J.get(`/ping`,{skipAuth:!0});e&&(n?.version?t(n.version):a(`Invalid server response`))}catch(t){e&&(console.error(`Failed to fetch server version:`,t),a(`Unable to connect to server`))}finally{e&&r(!1)}}n();let i=setInterval(n,3e4);return()=>{e=!1,clearInterval(i)}},[]),{serverVersion:e,isLoading:n,error:i}}var tu=`https://github.com/canvas-ui/canvas-server`,nu=null;function ru(){return nu||=J.get(`/ping`,{skipAuth:!0}).then(e=>{let t=e??{};return{sourceUrl:t.sourceUrl||tu,version:t.version??null,commit:t.commit??null,license:t.license??null}}).catch(e=>(console.error(`Failed to fetch server source info:`,e),nu=null,{sourceUrl:tu,version:null,commit:null,license:null})),nu}function iu(){let[e,t]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=!0;return ru().then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function au({className:e=``}){let t=iu();if(!t)return null;let n=[t.version?`v${t.version}`:null,t.commit?.slice(0,7)].filter(Boolean).join(` `);return(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground ${e}`,children:[`Powered by`,` `,(0,Z.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Canvas`}),n?` ${n}`:``,t.license?`, ${t.license}`:``,`.`,` `,(0,Z.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})}function ou({children:e}){ql(`particle-js`);let{serverVersion:t,isLoading:n,error:r}=eu();return(0,Z.jsx)(`div`,{className:`flex min-h-viewport w-full items-center justify-center p-4 flex-col`,children:(0,Z.jsxs)(zl,{className:`flex w-[95vw] h-viewport-modal overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`hidden md:block w-1/2 relative bg-background`,"data-scheme":`dark`,id:`particle-js`,children:[(0,Z.jsxs)(we,{className:`absolute top-8 left-8 font-bold text-foreground flex items-center z-raised`,to:`/`,children:[(0,Z.jsx)(`img`,{src:`/images/logo-wr_128x128.png`,alt:`Canvas Logo`,className:`mr-2 h-6 w-6 touch-target`}),(0,Z.jsx)(`span`,{className:`text-2xl font-bold text-foreground`,children:`Canvas`})]}),(0,Z.jsxs)(`div`,{className:`absolute bottom-8 left-8 text-sm text-foreground max-w-[80%] z-raised`,children:[`Web UI: v`,Gl,`, Server: `,n?`Loading...`:r?`Unavailable`:t?`v${t}`:`Unknown`]})]}),(0,Z.jsx)(`div`,{className:`flex w-full md:w-1/2 flex-col justify-center px-4 py-12 sm:px-6 lg:px-8`,children:(0,Z.jsxs)(`div`,{className:`mx-auto w-full max-w-sm`,children:[e,(0,Z.jsxs)(`div`,{className:`mt-8 border-t pt-6`,children:[(0,Z.jsxs)(`a`,{href:`https://github.com/canvas-ui`,target:`_blank`,className:`text-muted-foreground hover:text-foreground justify-center flex items-center space-x-2`,rel:`noopener noreferrer`,children:[(0,Z.jsx)(`svg`,{viewBox:`0 0 24 24`,width:`24`,height:`24`,stroke:`currentColor`,fill:`none`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:`w-6 h-6`,children:(0,Z.jsx)(`path`,{d:`M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22`})}),(0,Z.jsx)(`span`,{children:`View on GitHub`})]}),(0,Z.jsx)(au,{className:`mt-4 text-center`})]})]})})]})})}async function su(e,t,n=`auto`){try{let r=await J.post(no.login,{email:e,password:t,strategy:n},{skipAuth:!0});console.log(`Login response:`,r);let i=r;if(`token`in i)return console.log(`Setting auth token (direct):`,i.token.substring(0,10)+`...`),J.setAuthToken(i.token),B.connect(i.token),r;if(i&&`payload`in i&&i.payload&&i.payload.token)return console.log(`Setting auth token (nested):`,i.payload.token.substring(0,10)+`...`),J.setAuthToken(i.payload.token),B.connect(i.payload.token),r;throw console.error(`Invalid login response structure:`,r),Error(`Invalid login response: missing token`)}catch(e){throw console.error(`Login error:`,e),J.clearAuthToken(),e}}async function cu(e,t,n){try{return await J.post(no.register,{name:e,email:t,password:n},{skipAuth:!0})}catch(e){throw console.error(`Registration failed:`,e),e}}function lu(e){return e instanceof Error&&/^Network error/i.test(e.message)}function uu(){let e=localStorage.getItem(`authToken`);if(!e)return!1;if(e.startsWith(`canvas-`))return!0;try{return eo(e).exp*1e3>Date.now()}catch{return!1}}function du(){let e=localStorage.getItem(`authToken`);if(!e||e.startsWith(`canvas-`))return null;try{let t=eo(e);return t.exp*1e3<Date.now()?(J.clearAuthToken(),null):{id:t.sub,email:t.email,userType:t.userType||`user`}}catch(e){return console.error(`Failed to decode token:`,e),J.clearAuthToken(),null}}async function fu(){try{if(!J.isAuthenticated())return console.log(`Not authenticated, skipping getCurrentUser request`),null;let e=await J.get(no.me);return console.log(`Current user response:`,e),e&&e?(B.isConnected()||B.reconnect(),e):(console.warn(`Invalid user profile response structure:`,e),null)}catch(e){if(console.error(`Failed to get current user:`,e),lu(e))throw e;return e instanceof Error&&(e.message.includes(`USER_NOT_FOUND_IN_DATABASE`)||e.message.includes(`Your session is invalid`)||e.message.includes(`Authentication required`)||e.message.includes(`user account no longer exists`))?(console.warn(`Authentication error detected, clearing token:`,e.message),J.clearAuthToken(),B.disconnect(),null):null}}function pu(){return J.isAuthenticated()}function mu(){let e=new URL(`${yo}/oauth/google/login`);e.searchParams.set(`origin`,window.location.origin),window.location.assign(e.toString())}async function hu(e){let t=await J.post(`${yo}/oauth/google/exchange`,{code:e},{skipAuth:!0});if(!t?.token)throw Error(`Invalid login response: missing token`);J.setAuthToken(t.token),B.connect(t.token)}async function gu(){try{let e=await J.get(no.authConfig,{skipAuth:!0});return e||e}catch(e){return console.error(`Failed to get auth config:`,e),{strategies:{local:{enabled:!0},imap:{enabled:!1,domains:[]}}}}}async function _u(e){try{await J.post(no.verifyEmailRequest,{email:e},{skipAuth:!0})}catch(e){throw console.error(`Failed to request email verification:`,e),e}}var vu=e=>e?.strategies?.local?.enabled!==!1,yu=e=>e?.allowUserRegistrations!==!1;function bu(){let e=ft(),[t,n]=X.useState(!1),[r,i]=X.useState(``),[a,o]=X.useState(``),[s,c]=X.useState(!1),[l,u]=X.useState({}),[d,p]=X.useState(null),[m,h]=X.useState({email:``,password:``,strategy:`auto`});X.useEffect(()=>{uu()&&e(`/workspaces`),fetch(`${yo}/runtime/capabilities`).then(e=>e.ok?e.json():null).then(e=>n(e?.payload?.local===!0)).catch(()=>{}),gu().then(e=>{p(e)}).catch(e=>{console.error(`Failed to load auth config:`,e)})},[e]);let g=()=>{let e={};return m.email?/\S+@\S+\.\S+/.test(m.email)||(e.email=`Email is invalid`):e.email=`Email is required`,m.password||(e.password=`Password is required`),u(e),Object.keys(e).length===0},_=e=>{let{name:t,value:n}=e.target;h(e=>({...e,[t]:n}))};async function v(t){if(t.preventDefault(),g()){c(!0);try{console.log(`Attempting login with:`,m.email,`strategy:`,m.strategy);let t=await su(m.email,m.password,m.strategy);console.log(`Login successful, received token:`,`token`in t?!!t.token:!!t.payload?.token),u({}),e(`/home`)}catch(e){console.error(`Login error:`,e);let t=`Login failed`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;n.message?t=n.message:n.error?t=n.error:n.payload?.message&&(t=n.payload.message)}u({password:t})}finally{c(!1)}}}return t?(0,Z.jsx)(ou,{children:(0,Z.jsxs)(`form`,{className:`grid gap-4`,onSubmit:async t=>{t.preventDefault(),c(!0),o(``);try{if(J.setAuthToken(r.trim()),!await fu())throw Error(`The local token was not accepted`);e(`/workspaces`)}catch(e){J.clearAuthToken(),o(e instanceof Error?e.message:`Authentication failed`)}finally{c(!1)}},children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold`,children:`Connect to your local runtime`}),(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Enter the token shown by `,(0,Z.jsx)(`code`,{children:`canvas runtime token`}),` in the runtime folder.`]}),(0,Z.jsx)(G,{htmlFor:`local-token`,children:`Local access token`}),(0,Z.jsx)(q,{id:`local-token`,type:`password`,autoComplete:`off`,value:r,onChange:e=>i(e.target.value),required:!0}),a&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}),(0,Z.jsx)(Y,{disabled:s,children:s?`Connecting…`:`Connect`})]})}):(0,Z.jsx)(ou,{children:(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Welcome back`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your credentials to access your account`})]}),(0,Z.jsx)(`form`,{onSubmit:v,children:(0,Z.jsxs)(`div`,{className:`grid gap-4`,children:[d?.strategies?.imap?.enabled&&d.strategies.imap.domains.length>0&&(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(G,{htmlFor:`strategy`,children:`Authentication Method`}),(0,Z.jsxs)(`select`,{id:`strategy`,name:`strategy`,value:m.strategy,onChange:_,disabled:s,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`,children:[(0,Z.jsx)(`option`,{value:`auto`,children:`Auto-detect`}),(0,Z.jsx)(`option`,{value:`local`,children:`Local Account`}),(0,Z.jsx)(`option`,{value:`imap`,children:`Email Server (IMAP)`})]})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(G,{htmlFor:`email`,children:`Email`}),(0,Z.jsx)(q,{id:`email`,name:`email`,placeholder:`name@example.com`,type:`email`,autoCapitalize:`none`,autoComplete:`email`,autoCorrect:`off`,disabled:s,value:m.email,onChange:_}),l.email&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:l.email})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(G,{htmlFor:`password`,children:`Password`}),(0,Z.jsx)(q,{id:`password`,name:`password`,type:`password`,disabled:s,value:m.password,onChange:_}),l.password&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:l.password})]}),(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,Z.jsx)(Y,{type:`submit`,disabled:s,children:s?`Signing in...`:`Sign In`}),d?.strategies?.google?.enabled&&(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,disabled:s,onClick:()=>mu(),children:[(0,Z.jsx)(f,{icon:`logos:google-icon`,width:16,height:16,className:`mr-2`}),`Sign in with Google`]}),vu(d)&&yu(d)&&(0,Z.jsx)(Y,{variant:`outline`,type:`button`,disabled:s,onClick:()=>e(`/register`),children:`Don't have an account? Sign up`})]})]})})]})})}function xu(){let e=ft(),{showToast:t}=wo(),[n,r]=X.useState(!1),[i,a]=X.useState({}),[o,s]=X.useState({name:``,email:``,password:``}),[c,l]=X.useState(!1),[u,d]=X.useState(!1),[f,p]=X.useState(null);X.useEffect(()=>{(async()=>{let t=await gu(),n=t?.strategies?.local;if(t?.allowUserRegistrations===!1||n?.enabled===!1){e(`/login`,{replace:!0});return}n?.passwordPolicy&&p(n.passwordPolicy),d(!!n?.requireEmailVerification)})()},[e]);let m=X.useMemo(()=>{if(!f)return null;let e=o.password||``;return{minLength:!f.minLength||e.length>=f.minLength,maxLength:!f.maxLength||e.length<=f.maxLength,uppercase:!f.requireUppercase||/[A-Z]/.test(e),lowercase:!f.requireLowercase||/[a-z]/.test(e),number:!f.requireNumbers||/[0-9]/.test(e),special:!f.requireSpecialChars||/[^A-Za-z0-9]/.test(e)}},[f,o.password]),h=()=>{let e={};if(!o.name)e.name=`Username is required`;else if(o.name.trim().length===0)e.name=`Username cannot be empty`;else{let t=o.name.toLowerCase().trim();t.length<3?e.name=`Username must be at least 3 characters long`:t.length>39?e.name=`Username cannot be longer than 39 characters`:/^[a-z0-9_-]+$/.test(t)?[`admin`,`administrator`,`root`,`system`,`support`,`help`,`api`,`www`,`mail`,`ftp`,`localhost`,`test`,`demo`,`canvas`,`universe`,`workspace`,`context`,`user`,`users`].includes(t)&&(e.name=`Username '${t}' is reserved and cannot be used`):e.name=`Username can only contain lowercase letters, numbers, underscores, and hyphens`}if(o.email?/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o.email)||(e.email=`Please enter a valid email address`):e.email=`Email is required`,!o.password)e.password=`Password is required`;else if(f){let t=o.password,n=[];f.minLength&&t.length<f.minLength&&n.push(`at least ${f.minLength} characters`),f.maxLength&&t.length>f.maxLength&&n.push(`no more than ${f.maxLength} characters`),f.requireUppercase&&!/[A-Z]/.test(t)&&n.push(`an uppercase letter`),f.requireLowercase&&!/[a-z]/.test(t)&&n.push(`a lowercase letter`),f.requireNumbers&&!/[0-9]/.test(t)&&n.push(`a number`),f.requireSpecialChars&&!/[^A-Za-z0-9]/.test(t)&&n.push(`a special character`),n.length&&(e.password=`Password must contain ${n.join(`, `).replace(/, ([^,]*)$/,` and $1`)}.`)}else o.password.length<8&&(e.password=`Password must be at least 8 characters long`);return a(e),Object.keys(e).length===0},g=e=>{let t={...o,[e.target.id]:e.target.value};s(t),(e.target.id===`name`||e.target.id===`email`||e.target.id===`password`)&&h()};return c?(0,Z.jsxs)(ou,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Registration Successful!`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:u?`Check your email for a verification link to activate your account.`:`Your account has been created.`})]}),(0,Z.jsx)(`div`,{className:`space-y-6 text-center pt-6`,children:!u&&(0,Z.jsx)(Y,{asChild:!0,className:`w-full`,children:(0,Z.jsx)(we,{to:`/login`,children:`Go to Login`})})})]}):(0,Z.jsxs)(ou,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Create an account`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your email below to create your account`})]}),(0,Z.jsxs)(`form`,{onSubmit:async e=>{if(e.preventDefault(),h()){r(!0);try{let e=await cu(o.name,o.email,o.password);console.log(`Registration successful:`,e),t({title:`Registration Successful`,description:u?`Check your email for a verification link before logging in.`:`You can now log in with your credentials.`,variant:`default`}),l(!0),s({name:``,email:``,password:``}),a({})}catch(e){console.error(`Registration failed:`,e);let n=e?.message||`Registration failed`;n.toLowerCase().includes(`password`)?a({...i,password:n}):a({...i,email:n}),t({title:`Registration Failed`,description:n,variant:`destructive`})}finally{r(!1)}}},className:`space-y-4 pt-6`,children:[(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(G,{htmlFor:`name`,children:`Username`}),(0,Z.jsx)(q,{id:`name`,type:`text`,placeholder:`Enter your username (e.g., john_doe)`,value:o.name,onChange:g,disabled:n,className:i.name?`border-destructive`:``}),i.name&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.name}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`3-39 characters, lowercase letters, numbers, underscores, and hyphens only`})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(G,{htmlFor:`email`,children:`Email`}),(0,Z.jsx)(q,{id:`email`,type:`email`,placeholder:`name@example.com`,value:o.email,onChange:g,disabled:n,className:i.email?`border-destructive`:``}),i.email&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.email})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(G,{htmlFor:`password`,children:`Password`}),(0,Z.jsx)(q,{id:`password`,type:`password`,placeholder:`Enter your password`,value:o.password,onChange:g,disabled:n,className:i.password?`border-destructive`:``}),i.password&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.password}),f&&m&&(0,Z.jsxs)(`ul`,{className:`text-xs list-disc pl-4 space-y-1`,children:[(0,Z.jsxs)(`li`,{className:m.minLength?`text-success`:`text-muted-foreground`,children:[`At least `,f.minLength,` characters`]}),f.requireUppercase&&(0,Z.jsx)(`li`,{className:m.uppercase?`text-success`:`text-muted-foreground`,children:`At least one uppercase letter`}),f.requireLowercase&&(0,Z.jsx)(`li`,{className:m.lowercase?`text-success`:`text-muted-foreground`,children:`At least one lowercase letter`}),f.requireNumbers&&(0,Z.jsx)(`li`,{className:m.number?`text-success`:`text-muted-foreground`,children:`At least one number`}),f.requireSpecialChars&&(0,Z.jsx)(`li`,{className:m.special?`text-success`:`text-muted-foreground`,children:`At least one special character`}),f.maxLength&&(0,Z.jsxs)(`li`,{className:m.maxLength?`text-success`:`text-muted-foreground`,children:[`No more than `,f.maxLength,` characters`]})]})]}),(0,Z.jsx)(Y,{type:`submit`,className:`w-full`,disabled:n,children:n?`Creating Account...`:`Create Account`})]}),(0,Z.jsxs)(`div`,{className:`mt-4 text-center text-sm`,children:[`Already have an account?`,` `,(0,Z.jsx)(we,{to:`/login`,className:`underline`,children:`Sign in`})]}),(0,Z.jsxs)(`div`,{className:`px-8 py-4 text-center text-sm text-muted-foreground border-t mt-6`,children:[`By clicking continue, you agree to our`,` `,(0,Z.jsx)(we,{to:`/terms`,className:`underline underline-offset-4 hover:text-primary`,children:`Terms of Service`}),` `,`and`,` `,(0,Z.jsx)(we,{to:`/privacy`,className:`underline underline-offset-4 hover:text-primary`,children:`Privacy Policy`}),`.`]})]})}function Su(){let e=ft(),[t]=$t(),[n,r]=X.useState(t.get(`error`)),i=X.useRef(!1);return X.useEffect(()=>{let n=t.get(`code`);!n||i.current||(i.current=!0,hu(n).then(()=>e(`/home`,{replace:!0})).catch(e=>r(e instanceof Error?e.message:`Google sign-in failed`)))},[t,e]),(0,Z.jsx)(ou,{children:(0,Z.jsx)(`div`,{className:`flex flex-col space-y-4 text-center`,children:n?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Google sign-in failed`}),(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:n}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,onClick:()=>e(`/login`,{replace:!0}),children:`Back to sign in`})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Signing you in…`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Completing Google sign-in.`})]})})})}function Cu({children:e}){let[t,n]=(0,X.useState)(`loading`);return(0,X.useEffect)(()=>{(async()=>{try{if(!pu()){console.log(`No authentication token found, redirecting to login`),n(`unauthenticated`);return}let e=await fu();e?(console.log(`User authenticated:`,e.email),n(`authenticated`)):(console.log(`User not authenticated or token expired`),n(`unauthenticated`))}catch(e){if(console.error(`Authentication check failed:`,e),lu(e)){if(uu()){n(`authenticated`);return}J.clearAuthToken(),n(`unauthenticated`);return}e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from ProtectedRoute`),J.clearAuthToken()),n(`unauthenticated`)}})()},[]),t===`loading`?(0,Z.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,Z.jsx)(nn,{className:`h-8 w-8`})}):t===`unauthenticated`?(0,Z.jsx)(ht,{to:`/login`,replace:!0}):(0,Z.jsx)(Z.Fragment,{children:e})}function wu({children:e}){let[t,n]=(0,X.useState)(null);return(0,X.useEffect)(()=>{(async()=>{try{await J.get(`/auth/me`),n(!0)}catch(e){e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from PublicRoute`),J.clearAuthToken()),n(!1)}})()},[]),t===null?null:t?(0,Z.jsx)(ht,{to:`/workspaces`,replace:!0}):(0,Z.jsx)(Z.Fragment,{children:e})}var Tu=i(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?r(e):typeof define==`function`&&define.amd?define([`exports`],r):(n=typeof globalThis<`u`?globalThis:n||self,r(n[`fast-equals`]={}))})(e,(function(e){function t(e){return function(t,n,r,i,a,o,s){return e(t,n,s)}}function n(e){return function(t,n,r,i){if(!t||!n||typeof t!=`object`||typeof n!=`object`)return e(t,n,r,i);var a=i.get(t),o=i.get(n);if(a&&o)return a===n&&o===t;i.set(t,n),i.set(n,t);var s=e(t,n,r,i);return i.delete(t),i.delete(n),s}}function r(e,t){var n={};for(var r in e)n[r]=e[r];for(var r in t)n[r]=t[r];return n}function i(e){return e.constructor===Object||e.constructor==null}function a(e){return typeof e.then==`function`}function o(e,t){return e===t||e!==e&&t!==t}var s=Object.prototype.toString;function c(e){var t=e.areArraysEqual,n=e.areDatesEqual,r=e.areMapsEqual,c=e.areObjectsEqual,l=e.areRegExpsEqual,u=e.areSetsEqual,d=e.createIsNestedEqual,f=d(p);function p(e,d,p){if(e===d)return!0;if(!e||!d||typeof e!=`object`||typeof d!=`object`)return e!==e&&d!==d;if(i(e)&&i(d))return c(e,d,f,p);var m=Array.isArray(e),h=Array.isArray(d);if(m||h)return m===h&&t(e,d,f,p);var g=s.call(e);return g===s.call(d)?g===`[object Date]`?n(e,d,f,p):g===`[object RegExp]`?l(e,d,f,p):g===`[object Map]`?r(e,d,f,p):g===`[object Set]`?u(e,d,f,p):g===`[object Object]`||g===`[object Arguments]`?a(e)||a(d)?!1:c(e,d,f,p):g===`[object Boolean]`||g===`[object Number]`||g===`[object String]`?o(e.valueOf(),d.valueOf()):!1:!1}return p}function l(e,t,n,r){var i=e.length;if(t.length!==i)return!1;for(;i-->0;)if(!n(e[i],t[i],i,i,e,t,r))return!1;return!0}var u=n(l);function d(e,t){return o(e.valueOf(),t.valueOf())}function f(e,t,n,r){var i=e.size===t.size;if(!i)return!1;if(!e.size)return!0;var a={},o=0;return e.forEach(function(s,c){if(i){var l=!1,u=0;t.forEach(function(i,d){!l&&!a[u]&&(l=n(c,d,o,u,e,t,r)&&n(s,i,c,d,e,t,r))&&(a[u]=!0),u++}),o++,i=l}}),i}var p=n(f),m=`_owner`,h=Object.prototype.hasOwnProperty;function g(e,t,n,r){var i=Object.keys(e),a=i.length;if(Object.keys(t).length!==a)return!1;for(var o;a-->0;){if(o=i[a],o===m){var s=!!e.$$typeof,c=!!t.$$typeof;if((s||c)&&s!==c)return!1}if(!h.call(t,o)||!n(e[o],t[o],o,o,e,t,r))return!1}return!0}var _=n(g);function v(e,t){return e.source===t.source&&e.flags===t.flags}function y(e,t,n,r){var i=e.size===t.size;if(!i)return!1;if(!e.size)return!0;var a={};return e.forEach(function(o,s){if(i){var c=!1,l=0;t.forEach(function(i,u){!c&&!a[l]&&(c=n(o,i,s,u,e,t,r))&&(a[l]=!0),l++}),i=c}}),i}var b=n(y),x=Object.freeze({areArraysEqual:l,areDatesEqual:d,areMapsEqual:f,areObjectsEqual:g,areRegExpsEqual:v,areSetsEqual:y,createIsNestedEqual:t}),S=Object.freeze({areArraysEqual:u,areDatesEqual:d,areMapsEqual:p,areObjectsEqual:_,areRegExpsEqual:v,areSetsEqual:b,createIsNestedEqual:t}),C=c(x);function w(e,t){return C(e,t,void 0)}var T=c(r(x,{createIsNestedEqual:function(){return o}}));function E(e,t){return T(e,t,void 0)}var D=c(S);function O(e,t){return D(e,t,new WeakMap)}var k=c(r(S,{createIsNestedEqual:function(){return o}}));function A(e,t){return k(e,t,new WeakMap)}function j(e){return c(r(x,e(x)))}function M(e){var t=c(r(S,e(S)));return(function(e,n,r){return r===void 0&&(r=new WeakMap),t(e,n,r)})}e.circularDeepEqual=O,e.circularShallowEqual=A,e.createCustomCircularEqual=M,e.createCustomEqual=j,e.deepEqual=w,e.sameValueZeroEqual=o,e.shallowEqual=E,Object.defineProperty(e,"__esModule",{value:!0})}))})),Eu=i(((e,t)=>{t.exports=function(e,t,n){return e===t||e.className===t.className&&n(e.style,t.style)&&e.width===t.width&&e.autoSize===t.autoSize&&e.cols===t.cols&&e.draggableCancel===t.draggableCancel&&e.draggableHandle===t.draggableHandle&&n(e.verticalCompact,t.verticalCompact)&&n(e.compactType,t.compactType)&&n(e.layout,t.layout)&&n(e.margin,t.margin)&&n(e.containerPadding,t.containerPadding)&&e.rowHeight===t.rowHeight&&e.maxRows===t.maxRows&&e.isBounded===t.isBounded&&e.isDraggable===t.isDraggable&&e.isResizable===t.isResizable&&e.allowOverlap===t.allowOverlap&&e.preventCollision===t.preventCollision&&e.useCSSTransforms===t.useCSSTransforms&&e.transformScale===t.transformScale&&e.isDroppable===t.isDroppable&&n(e.resizeHandles,t.resizeHandles)&&n(e.resizeHandle,t.resizeHandle)&&e.onLayoutChange===t.onLayoutChange&&e.onDragStart===t.onDragStart&&e.onDrag===t.onDrag&&e.onDragStop===t.onDragStop&&e.onResizeStart===t.onResizeStart&&e.onResize===t.onResize&&e.onResizeStop===t.onResizeStop&&e.onDrop===t.onDrop&&n(e.droppingItem,t.droppingItem)&&n(e.innerRef,t.innerRef)}})),Du=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.bottom=l,e.childrenEqual=h,e.cloneLayout=u,e.cloneLayoutItem=m,e.collides=_,e.compact=v,e.compactItem=x,e.compactType=se,e.correctBounds=S,e.fastPositionEqual=g,e.fastRGLPropsEqual=void 0,e.getAllCollisions=T,e.getFirstCollision=w,e.getLayoutItem=C,e.getStatics=E,e.modifyLayout=f,e.moveElement=D,e.moveElementAwayFromCollision=O,e.noop=void 0,e.perc=k,e.resizeItemInDirection=L,e.setTopLeft=ne,e.setTransform=R,e.sortLayoutItems=re,e.sortLayoutItemsByColRow=ae,e.sortLayoutItemsByRowCol=ie,e.synchronizeLayoutWithChildren=z,e.validateLayout=oe,e.withLayoutItem=p;var t=Tu(),n=r(d());function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?i(Object(n),!0).forEach(function(t){o(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function o(e,t,n){return(t=s(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e){var t=c(e,`string`);return typeof t==`symbol`?t:t+``}function c(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function l(e){let t=0,n;for(let r=0,i=e.length;r<i;r++)n=e[r].y+e[r].h,n>t&&(t=n);return t}function u(e){let t=Array(e.length);for(let n=0,r=e.length;n<r;n++)t[n]=m(e[n]);return t}function f(e,t){let n=Array(e.length);for(let r=0,i=e.length;r<i;r++)t.i===e[r].i?n[r]=t:n[r]=e[r];return n}function p(e,t,n){let r=C(e,t);return r?(r=n(m(r)),e=f(e,r),[e,r]):[e,null]}function m(e){return{w:e.w,h:e.h,x:e.x,y:e.y,i:e.i,minW:e.minW,maxW:e.maxW,minH:e.minH,maxH:e.maxH,moved:!!e.moved,static:!!e.static,isDraggable:e.isDraggable,isResizable:e.isResizable,resizeHandles:e.resizeHandles,isBounded:e.isBounded}}function h(e,r){return(0,t.deepEqual)(n.default.Children.map(e,e=>e?.key),n.default.Children.map(r,e=>e?.key))&&(0,t.deepEqual)(n.default.Children.map(e,e=>e?.props[`data-grid`]),n.default.Children.map(r,e=>e?.props[`data-grid`]))}e.fastRGLPropsEqual=Eu();function g(e,t){return e.left===t.left&&e.top===t.top&&e.width===t.width&&e.height===t.height}function _(e,t){return!(e.i===t.i||e.x+e.w<=t.x||e.x>=t.x+t.w||e.y+e.h<=t.y||e.y>=t.y+t.h)}function v(e,t,n,r){let i=E(e),a=l(i),o=re(e,t),s=Array(e.length);for(let c=0,l=o.length;c<l;c++){let l=m(o[c]);l.static||(l=x(i,l,t,n,o,r,a),a=Math.max(a,l.y+l.h),i.push(l)),s[e.indexOf(o[c])]=l,l.moved=!1}return s}var y={x:`w`,y:`h`};function b(e,t,n,r){let i=y[r];t[r]+=1;let a=e.map(e=>e.i).indexOf(t.i);for(let o=a+1;o<e.length;o++){let a=e[o];if(!a.static){if(a.y>t.y+t.h)break;_(t,a)&&b(e,a,n+t[i],r)}}t[r]=n}function x(e,t,n,r,i,a,o){let s=n===`vertical`,c=n===`horizontal`;if(s)for(t.y=Math.min(typeof o==`number`?o:l(e),t.y);t.y>0&&!w(e,t);)t.y--;else if(c)for(;t.x>0&&!w(e,t);)t.x--;let u;for(;(u=w(e,t))&&!(n===null&&a);)if(c?b(i,t,u.x+u.w,`x`):b(i,t,u.y+u.h,`y`),c&&t.x+t.w>r)for(t.x=r-t.w,t.y++;t.x>0&&!w(e,t);)t.x--;return t.y=Math.max(t.y,0),t.x=Math.max(t.x,0),t}function S(e,t){let n=E(e);for(let r=0,i=e.length;r<i;r++){let i=e[r];if(i.x+i.w>t.cols&&(i.x=t.cols-i.w),i.x<0&&(i.x=0,i.w=t.cols),!i.static)n.push(i);else for(;w(n,i);)i.y++}return e}function C(e,t){for(let n=0,r=e.length;n<r;n++)if(e[n].i===t)return e[n]}function w(e,t){for(let n=0,r=e.length;n<r;n++)if(_(e[n],t))return e[n]}function T(e,t){return e.filter(e=>_(e,t))}function E(e){return e.filter(e=>e.static)}function D(e,t,n,r,i,a,o,s,c){if(t.static&&t.isDraggable!==!0||t.y===r&&t.x===n)return e;`${t.i}${String(n)}${String(r)}${t.x}${t.y}`;let l=t.x,d=t.y;typeof n==`number`&&(t.x=n),typeof r==`number`&&(t.y=r),t.moved=!0;let f=re(e,o);(o===`vertical`&&typeof r==`number`?d>=r:o===`horizontal`&&typeof n==`number`&&l>=n)&&(f=f.reverse());let p=T(f,t),m=p.length>0;if(m&&c)return u(e);if(m&&a)return`${t.i}`,t.x=l,t.y=d,t.moved=!1,e;for(let n=0,r=p.length;n<r;n++){let r=p[n];`${t.i}${t.x}${t.y}${r.i}${r.x}${r.y}`,!r.moved&&(e=r.static?O(e,r,t,i,o,s):O(e,t,r,i,o,s))}return e}function O(e,t,n,r,i,a){let o=i===`horizontal`,s=i===`vertical`,c=t.static;if(r){r=!1;let l={x:o?Math.max(t.x-n.w,0):n.x,y:s?Math.max(t.y-n.h,0):n.y,w:n.w,h:n.h,i:`-1`},u=w(e,l),d=u&&u.y+u.h>t.y,f=u&&t.x+t.w>u.x;if(!u)return`${n.i}${l.x}${l.y}`,D(e,n,o?l.x:void 0,s?l.y:void 0,r,c,i,a);if(d&&s)return D(e,n,void 0,n.y+1,r,c,i,a);if(d&&i==null)return t.y=n.y,n.y+=n.h,e;if(f&&o)return D(e,t,n.x,void 0,r,c,i,a)}let l=o?n.x+1:void 0,u=s?n.y+1:void 0;return l==null&&u==null?e:D(e,n,o?n.x+1:void 0,s?n.y+1:void 0,r,c,i,a)}function k(e){return e*100+`%`}var A=(e,t,n,r)=>e+n>r?t:n,j=(e,t,n)=>e<0?t:n,M=e=>Math.max(0,e),N=e=>Math.max(0,e),P=(e,t,n)=>{let{left:r,height:i,width:a}=t,o=e.top-(i-e.height);return{left:r,width:a,height:j(o,e.height,i),top:N(o)}},ee=(e,t,n)=>{let{top:r,left:i,height:a,width:o}=t;return{top:r,height:a,width:A(e.left,e.width,o,n),left:M(i)}},F=(e,t,n)=>{let{top:r,height:i,width:a}=t,o=e.left-(a-e.width);return{height:i,width:o<0?e.width:A(e.left,e.width,a,n),top:N(r),left:M(o)}},I=(e,t,n)=>{let{top:r,left:i,height:a,width:o}=t;return{width:o,left:i,height:j(r,e.height,a),top:N(r)}},te={n:P,ne:function(){return P(arguments.length<=0?void 0:arguments[0],ee(...arguments),arguments.length<=2?void 0:arguments[2])},e:ee,se:function(){return I(arguments.length<=0?void 0:arguments[0],ee(...arguments),arguments.length<=2?void 0:arguments[2])},s:I,sw:function(){return I(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])},w:F,nw:function(){return P(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])}};function L(e,t,n,r){let i=te[e];return i?i(t,a(a({},t),n),r):n}function R(e){let{top:t,left:n,width:r,height:i}=e,a=`translate(${n}px,${t}px)`;return{transform:a,WebkitTransform:a,MozTransform:a,msTransform:a,OTransform:a,width:`${r}px`,height:`${i}px`,position:`absolute`}}function ne(e){let{top:t,left:n,width:r,height:i}=e;return{top:`${t}px`,left:`${n}px`,width:`${r}px`,height:`${i}px`,position:`absolute`}}function re(e,t){return t===`horizontal`?ae(e):t===`vertical`?ie(e):e}function ie(e){return e.slice(0).sort(function(e,t){return e.y>t.y||e.y===t.y&&e.x>t.x?1:e.y===t.y&&e.x===t.x?0:-1})}function ae(e){return e.slice(0).sort(function(e,t){return e.x>t.x||e.x===t.x&&e.y>t.y?1:-1})}function z(e,t,r,i,o){e||=[];let s=[];n.default.Children.forEach(t,t=>{if(t?.key==null)return;let n=C(e,String(t.key)),r=t.props[`data-grid`];n&&r==null?s.push(m(n)):r?s.push(m(a(a({},r),{},{i:t.key}))):s.push(m({w:1,h:1,x:0,y:l(s),i:String(t.key)}))});let c=S(s,{cols:r});return o?c:v(c,i,r)}function oe(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Layout`,n=[`x`,`y`,`w`,`h`];if(!Array.isArray(e))throw Error(t+` must be an array!`);for(let r=0,i=e.length;r<i;r++){let i=e[r];for(let e=0;e<n.length;e++){let a=n[e],o=i[a];if(typeof o!=`number`||Number.isNaN(o))throw Error(`ReactGridLayout: ${t}[${r}].${a} must be a number! Received: ${o} (${typeof o})`)}if(i.i!==void 0&&typeof i.i!=`string`)throw Error(`ReactGridLayout: ${t}[${r}].i must be a string! Received: ${i.i} (${typeof i.i})`)}}function se(e){let{verticalCompact:t,compactType:n}=e||{};return t===!1?null:n}e.noop=()=>{}})),Ou=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.calcGridColWidth=t,e.calcGridItemPosition=r,e.calcGridItemWHPx=n,e.calcWH=a,e.calcXY=i,e.clamp=o;function t(e){let{margin:t,containerPadding:n,containerWidth:r,cols:i}=e;return(r-t[0]*(i-1)-n[0]*2)/i}function n(e,t,n){return Number.isFinite(e)?Math.round(t*e+Math.max(0,e-1)*n):e}function r(e,r,i,a,o,s){let{margin:c,containerPadding:l,rowHeight:u}=e,d=t(e),f={};return s&&s.resizing?(f.width=Math.round(s.resizing.width),f.height=Math.round(s.resizing.height)):(f.width=n(a,d,c[0]),f.height=n(o,u,c[1])),s&&s.dragging?(f.top=Math.round(s.dragging.top),f.left=Math.round(s.dragging.left)):s&&s.resizing&&typeof s.resizing.top==`number`&&typeof s.resizing.left==`number`?(f.top=Math.round(s.resizing.top),f.left=Math.round(s.resizing.left)):(f.top=Math.round((u+c[1])*i+l[1]),f.left=Math.round((d+c[0])*r+l[0])),f}function i(e,n,r,i,a){let{margin:s,containerPadding:c,cols:l,rowHeight:u,maxRows:d}=e,f=t(e),p=Math.round((r-c[0])/(f+s[0])),m=Math.round((n-c[1])/(u+s[1]));return p=o(p,0,l-i),m=o(m,0,d-a),{x:p,y:m}}function a(e,n,r,i,a,s){let{margin:c,maxRows:l,cols:u,rowHeight:d}=e,f=t(e),p=Math.round((n+c[0])/(f+c[0])),m=Math.round((r+c[1])/(d+c[1])),h=o(p,0,u-i),g=o(m,0,l-a);return[`sw`,`w`,`nw`].indexOf(s)!==-1&&(h=o(p,0,u)),[`nw`,`n`,`ne`].indexOf(s)!==-1&&(g=o(m,0,l)),{w:h,h:g}}function o(e,t,n){return Math.max(Math.min(e,n),t)}})),ku=i(((e,t)=>{t.exports=`SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED`})),Au=i(((e,t)=>{var n=ku();function r(){}function i(){}i.resetWarningCache=r,t.exports=function(){function e(e,t,r,i,a,o){if(o!==n){var s=Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw s.name=`Invariant Violation`,s}}e.isRequired=e;function t(){return e}var a={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:i,resetWarningCache:r};return a.PropTypes=a,a}})),ju=i(((e,t)=>{t.exports=Au()()})),Mu=i(((e,t)=>{var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,c=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},l=(e,t,n,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!s.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(o=i(t,c))||o.enumerable});return e},u=(e,t,i)=>(i=e==null?{}:n(o(e)),l(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)),f=e=>l(r({},`__esModule`,{value:!0}),e),p={};c(p,{DraggableCore:()=>Se,default:()=>Ce}),t.exports=f(p);var m=u(d()),g=u(ju()),_=u(h()),v=$a();function y(e,t){for(let n=0,r=e.length;n<r;n++)if(t.apply(t,[e[n],n,e]))return e[n]}function b(e){return typeof e==`function`||Object.prototype.toString.call(e)===`[object Function]`}function x(e){return typeof e==`number`&&!isNaN(e)}function S(e){return parseInt(e,10)}function C(e,t,n){if(e[t])return Error(`Invalid prop ${t} passed to ${n} - do not set this, set it on the child.`)}var w=[`Moz`,`Webkit`,`O`,`ms`];function T(e=`transform`){if(typeof window>`u`)return``;let t=window.document?.documentElement?.style;if(!t||e in t)return``;for(let n=0;n<w.length;n++)if(E(e,w[n])in t)return w[n];return``}function E(e,t){return t?`${t}${D(e)}`:e}function D(e){let t=``,n=!0;for(let r=0;r<e.length;r++)n?(t+=e[r].toUpperCase(),n=!1):e[r]===`-`?n=!0:t+=e[r];return t}var O=T(),k=``;function A(e,t){k||=y([`matches`,`webkitMatchesSelector`,`mozMatchesSelector`,`msMatchesSelector`,`oMatchesSelector`],function(t){return b(e[t])})??``;let n=e[k];return b(n)?!!n.call(e,t):!1}function j(e,t,n){let r=e;do{if(A(r,t))return!0;if(r===n)return!1;r=r.parentNode}while(r);return!1}function M(e,t,n,r){if(!e)return;let i={capture:!0,...r},a=n;e.addEventListener?e.addEventListener(t,a,i):e.attachEvent?e.attachEvent(`on`+t,a):e[`on`+t]=a}function N(e,t,n,r){if(!e)return;let i={capture:!0,...r},a=n;e.removeEventListener?e.removeEventListener(t,a,i):e.detachEvent?e.detachEvent(`on`+t,a):e[`on`+t]=null}function P(e){let t=e.clientHeight,n=e.ownerDocument.defaultView.getComputedStyle(e);return t+=S(n.borderTopWidth),t+=S(n.borderBottomWidth),t}function ee(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t+=S(n.borderLeftWidth),t+=S(n.borderRightWidth),t}function F(e){let t=e.clientHeight,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingTop),t-=S(n.paddingBottom),t}function I(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingLeft),t-=S(n.paddingRight),t}function te(e,t,n){let r=t===t.ownerDocument.body?{left:0,top:0}:t.getBoundingClientRect();return{x:(e.clientX+t.scrollLeft-r.left)/n,y:(e.clientY+t.scrollTop-r.top)/n}}function L(e,t){let n=ne(e,t,`px`);return{[E(`transform`,O)]:n}}function R(e,t){return ne(e,t,``)}function ne({x:e,y:t},n,r){let i=`translate(${e}${r},${t}${r})`;return n&&(i=`translate(${`${typeof n.x==`string`?n.x:n.x+r}`}, ${`${typeof n.y==`string`?n.y:n.y+r}`})`+i),i}function re(e,t){return e.targetTouches&&y(e.targetTouches,e=>t===e.identifier)||e.changedTouches&&y(e.changedTouches,e=>t===e.identifier)}function ie(e){if(e.targetTouches&&e.targetTouches[0])return e.targetTouches[0].identifier;if(e.changedTouches&&e.changedTouches[0])return e.changedTouches[0].identifier}function ae(){return typeof __webpack_nonce__<`u`?__webpack_nonce__:void 0}function z(e,t){if(!e)return;let n=e.getElementById(`react-draggable-style-el`);if(!n){n=e.createElement(`style`),n.type=`text/css`,n.id=`react-draggable-style-el`;let r=t??ae();r&&n.setAttribute(`nonce`,r),n.innerHTML=`.react-draggable-transparent-selection *::-moz-selection {all: inherit;}
|
|
3
3
|
`,n.innerHTML+=`.react-draggable-transparent-selection *::selection {all: inherit;}
|
|
4
4
|
`,e.getElementsByTagName(`head`)[0].appendChild(n)}e.body&&B(e.body,`react-draggable-transparent-selection`)}function oe(e){window.requestAnimationFrame?window.requestAnimationFrame(()=>{se(e)}):se(e)}function se(e){if(e)try{e.body&&ce(e.body,`react-draggable-transparent-selection`);let t=e.selection;if(t)t.empty();else{let t=(e.defaultView||window).getSelection();t&&t.type!==`Caret`&&t.removeAllRanges()}}catch{}}function B(e,t){e.classList?e.classList.add(t):e.className.match(RegExp(`(?:^|\\s)${t}(?!\\S)`))||(e.className+=` ${t}`)}function ce(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(RegExp(`(?:^|\\s)${t}(?!\\S)`,`g`),``)}function V(e,t,n){if(!e.props.bounds)return[t,n];let{bounds:r}=e.props;r=typeof r==`string`?r:he(r);let i=ge(e);if(typeof r==`string`){let{ownerDocument:e}=i,t=e.defaultView;if(!t)throw Error(`Cannot resolve the owner window of the draggable node.`);let n;if(n=r===`parent`?i.parentNode:i.getRootNode().querySelector(r),!(n instanceof t.HTMLElement))throw Error(`Bounds selector "`+r+`" could not find an element.`);let a=n,o=t.getComputedStyle(i),s=t.getComputedStyle(a);r={left:-i.offsetLeft+S(s.paddingLeft)+S(o.marginLeft),top:-i.offsetTop+S(s.paddingTop)+S(o.marginTop),right:I(a)-ee(i)-i.offsetLeft+S(s.paddingRight)-S(o.marginRight),bottom:F(a)-P(i)-i.offsetTop+S(s.paddingBottom)-S(o.marginBottom)}}return x(r.right)&&(t=Math.min(t,r.right)),x(r.bottom)&&(n=Math.min(n,r.bottom)),x(r.left)&&(t=Math.max(t,r.left)),x(r.top)&&(n=Math.max(n,r.top)),[t,n]}function le(e,t,n){return[Math.round(t/e[0])*e[0],Math.round(n/e[1])*e[1]]}function ue(e){return e.props.axis===`both`||e.props.axis===`x`}function de(e){return e.props.axis===`both`||e.props.axis===`y`}function fe(e,t,n){let r=typeof t==`number`?re(e,t):null;if(typeof t==`number`&&!r)return null;let i=ge(n),a=n.props.offsetParent||i.offsetParent||i.ownerDocument.body;return te(r||e,a,n.props.scale)}function pe(e,t,n){let r=!x(e.lastX),i=ge(e);return r?{node:i,deltaX:0,deltaY:0,lastX:t,lastY:n,x:t,y:n}:{node:i,deltaX:t-e.lastX,deltaY:n-e.lastY,lastX:e.lastX,lastY:e.lastY,x:t,y:n}}function me(e,t){let n=e.props.scale;return{node:t.node,x:e.state.x+t.deltaX/n,y:e.state.y+t.deltaY/n,deltaX:t.deltaX/n,deltaY:t.deltaY/n,lastX:e.state.x,lastY:e.state.y}}function he(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom}}function ge(e){let t=e.findDOMNode();if(!t)throw Error(`<DraggableCore>: Unmounted during event!`);return t}var _e=u(d()),ve=u(ju()),ye=u(h()),be=typeof process<`u`&&{}.DRAGGABLE_DEBUG?console.log.bind(console):function(){},xe={touch:{start:`touchstart`,move:`touchmove`,stop:`touchend`},mouse:{start:`mousedown`,move:`mousemove`,stop:`mouseup`}},H=xe.mouse,Se=class extends _e.Component{constructor(){super(...arguments),this.dragging=!1,this.lastX=NaN,this.lastY=NaN,this.touchIdentifier=null,this.mounted=!1,this.handleDragStart=e=>{if(this.props.onMouseDown(e),!this.props.allowAnyClick&&(typeof e.button==`number`&&e.button!==0||e.ctrlKey))return!1;let t=this.findDOMNode();if(!t||!t.ownerDocument||!t.ownerDocument.body)throw Error(`<DraggableCore> not mounted on DragStart!`);let{ownerDocument:n}=t;if(this.props.disabled||!(e.target instanceof n.defaultView.Node)||this.props.handle&&!j(e.target,this.props.handle,t)||this.props.cancel&&j(e.target,this.props.cancel,t))return;e.type===`touchstart`&&!this.props.allowMobileScroll&&e.preventDefault();let r=ie(e);this.touchIdentifier=r;let i=fe(e,r,this);if(i==null)return;let{x:a,y:o}=i,s=pe(this,a,o);be(`DraggableCore: handleDragStart: %j`,s),be(`calling`,this.props.onStart),this.props.onStart(e,s)!==!1&&this.mounted!==!1&&(this.props.enableUserSelectHack&&z(n,this.props.nonce),this.dragging=!0,this.lastX=a,this.lastY=o,M(n,H.move,this.handleDrag),M(n,H.stop,this.handleDragStop))},this.handleDrag=e=>{let t=fe(e,this.touchIdentifier,this);if(t==null)return;let{x:n,y:r}=t;if(Array.isArray(this.props.grid)){let e=n-this.lastX,t=r-this.lastY;if([e,t]=le(this.props.grid,e,t),!e&&!t)return;n=this.lastX+e,r=this.lastY+t}let i=pe(this,n,r);if(be(`DraggableCore: handleDrag: %j`,i),this.props.onDrag(e,i)===!1||this.mounted===!1){try{this.handleDragStop(new MouseEvent(`mouseup`))}catch{let e=document.createEvent(`MouseEvents`);e.initMouseEvent(`mouseup`,!0,!0,window,0,0,0,0,0,!1,!1,!1,!1,0,null),this.handleDragStop(e)}return}this.lastX=n,this.lastY=r},this.handleDragStop=e=>{if(!this.dragging)return;let t=fe(e,this.touchIdentifier,this);if(t==null)return;let{x:n,y:r}=t;if(Array.isArray(this.props.grid)){let e=n-this.lastX||0,t=r-this.lastY||0;[e,t]=le(this.props.grid,e,t),n=this.lastX+e,r=this.lastY+t}let i=pe(this,n,r);if(this.props.onStop(e,i)===!1||this.mounted===!1)return!1;let a=this.findDOMNode();a&&this.props.enableUserSelectHack&&oe(a.ownerDocument),be(`DraggableCore: handleDragStop: %j`,i),this.dragging=!1,this.lastX=NaN,this.lastY=NaN,a&&(be(`DraggableCore: Removing handlers`),N(a.ownerDocument,H.move,this.handleDrag),N(a.ownerDocument,H.stop,this.handleDragStop))},this.onMouseDown=e=>(H=xe.mouse,this.handleDragStart(e)),this.onMouseUp=e=>(H=xe.mouse,this.handleDragStop(e)),this.onTouchStart=e=>(H=xe.touch,this.handleDragStart(e)),this.onTouchEnd=e=>(H=xe.touch,this.handleDragStop(e))}componentDidMount(){this.mounted=!0;let e=this.findDOMNode();e&&M(e,xe.touch.start,this.onTouchStart,{passive:!1})}componentWillUnmount(){this.mounted=!1;let e=this.findDOMNode();if(e){let{ownerDocument:t}=e;N(t,xe.mouse.move,this.handleDrag),N(t,xe.touch.move,this.handleDrag),N(t,xe.mouse.stop,this.handleDragStop),N(t,xe.touch.stop,this.handleDragStop),N(e,xe.touch.start,this.onTouchStart,{passive:!1}),this.props.enableUserSelectHack&&oe(t)}}findDOMNode(){if(this.props?.nodeRef)return this.props.nodeRef.current;let e=ye.default;return typeof e.findDOMNode==`function`?e.findDOMNode(this):(be(`react-draggable: ReactDOM.findDOMNode is not available in React 19+. You must provide a nodeRef prop. See: https://github.com/react-grid-layout/react-draggable#noderef`),null)}render(){return _e.cloneElement(_e.Children.only(this.props.children),{onMouseDown:this.onMouseDown,onMouseUp:this.onMouseUp,onTouchEnd:this.onTouchEnd})}};Se.displayName=`DraggableCore`,Se.propTypes={allowAnyClick:ve.default.bool,allowMobileScroll:ve.default.bool,children:ve.default.node.isRequired,disabled:ve.default.bool,enableUserSelectHack:ve.default.bool,offsetParent:function(e,t){if(e[t]&&e[t].nodeType!==1)throw Error(`Draggable's offsetParent must be a DOM Node.`)},grid:ve.default.arrayOf(ve.default.number),handle:ve.default.string,cancel:ve.default.string,nodeRef:ve.default.object,nonce:ve.default.string,onStart:ve.default.func,onDrag:ve.default.func,onStop:ve.default.func,onMouseDown:ve.default.func,scale:ve.default.number,className:C,style:C,transform:C},Se.defaultProps={allowAnyClick:!1,allowMobileScroll:!1,disabled:!1,enableUserSelectHack:!0,onStart:function(){},onDrag:function(){},onStop:function(){},onMouseDown:function(){},scale:1};var Ce=class extends m.Component{constructor(e){super(e),this.onDragStart=(e,t)=>{if(be(`Draggable: onDragStart: %j`,t),this.props.onStart(e,me(this,t))===!1)return!1;this.setState({dragging:!0,dragged:!0})},this.onDrag=(e,t)=>{if(!this.state.dragging)return!1;be(`Draggable: onDrag: %j`,t);let n=me(this,t),r={x:n.x,y:n.y,slackX:0,slackY:0};if(this.props.bounds){let{x:e,y:t}=r;r.x+=this.state.slackX,r.y+=this.state.slackY;let[i,a]=V(this,r.x,r.y);r.x=i,r.y=a,r.slackX=this.state.slackX+(e-r.x),r.slackY=this.state.slackY+(t-r.y),n.x=r.x,n.y=r.y,n.deltaX=r.x-this.state.x,n.deltaY=r.y-this.state.y}if(this.props.onDrag(e,n)===!1)return!1;this.setState(r)},this.onDragStop=(e,t)=>{if(!this.state.dragging||this.props.onStop(e,me(this,t))===!1)return!1;be(`Draggable: onDragStop: %j`,t);let n={dragging:!1,slackX:0,slackY:0};if(this.props.position){let{x:e,y:t}=this.props.position;n.x=e,n.y=t}this.setState(n)},this.state={dragging:!1,dragged:!1,x:e.position?e.position.x:e.defaultPosition.x,y:e.position?e.position.y:e.defaultPosition.y,prevPropsPosition:{...e.position},slackX:0,slackY:0,isElementSVG:!1},e.position&&!(e.onDrag||e.onStop)&&console.warn("A `position` was applied to this <Draggable>, without drag handlers. This will make this component effectively undraggable. Please attach `onDrag` or `onStop` handlers so you can adjust the `position` of this element.")}static getDerivedStateFromProps({position:e},{prevPropsPosition:t}){return e&&(!t||e.x!==t.x||e.y!==t.y)?(be(`Draggable: getDerivedStateFromProps %j`,{position:e,prevPropsPosition:t}),{x:e.x,y:e.y,prevPropsPosition:{...e}}):null}componentDidMount(){window.SVGElement!==void 0&&this.findDOMNode()instanceof window.SVGElement&&this.setState({isElementSVG:!0})}componentWillUnmount(){this.state.dragging&&this.setState({dragging:!1})}findDOMNode(){if(this.props?.nodeRef)return this.props.nodeRef.current;let e=_.default;return typeof e.findDOMNode==`function`?e.findDOMNode(this):null}render(){let{axis:e,bounds:t,children:n,defaultPosition:r,defaultClassName:i,defaultClassNameDragging:a,defaultClassNameDragged:o,position:s,positionOffset:c,scale:l,...u}=this.props,d={},f=null,p=!s||this.state.dragging,h=s||r,g={x:ue(this)&&p?this.state.x:h.x,y:de(this)&&p?this.state.y:h.y};this.state.isElementSVG?f=R(g,c):d=L(g,c);let _=m.Children.only(n),y=(0,v.clsx)(_.props.className||``,i,{[a]:this.state.dragging,[o]:this.state.dragged});return m.createElement(Se,{...u,onStart:this.onDragStart,onDrag:this.onDrag,onStop:this.onDragStop},m.cloneElement(_,{className:y,style:{..._.props.style,...d},transform:f}))}};Ce.displayName=`Draggable`,Ce.propTypes={...Se.propTypes,axis:g.default.oneOf([`both`,`x`,`y`,`none`]),bounds:g.default.oneOfType([g.default.shape({left:g.default.number,right:g.default.number,top:g.default.number,bottom:g.default.number}),g.default.string,g.default.oneOf([!1])]),defaultClassName:g.default.string,defaultClassNameDragging:g.default.string,defaultClassNameDragged:g.default.string,defaultPosition:g.default.shape({x:g.default.number,y:g.default.number}),positionOffset:g.default.shape({x:g.default.oneOfType([g.default.number,g.default.string]),y:g.default.oneOfType([g.default.number,g.default.string])}),position:g.default.shape({x:g.default.number,y:g.default.number}),className:C,style:C,transform:C},Ce.defaultProps={...Se.defaultProps,axis:`both`,bounds:!1,defaultClassName:`react-draggable`,defaultClassNameDragging:`react-draggable-dragging`,defaultClassNameDragged:`react-draggable-dragged`,defaultPosition:{x:0,y:0},scale:1},0&&(t.exports={DraggableCore:Se})})),Nu=i(((e,t)=>{var n=Mu(),r=n.DraggableCore,i=n.default||n;t.exports=i,t.exports.default=i,t.exports.DraggableCore=r})),Pu=i((e=>{e.__esModule=!0,e.cloneElement=c;var t=n(d());function n(e){return e&&e.__esModule?e:{default:e}}function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function i(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?r(Object(n),!0).forEach(function(t){a(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function a(e,t,n){return(t=o(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e){var t=s(e,`string`);return typeof t==`symbol`?t:t+``}function s(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function c(e,n){return n.style&&e.props.style&&(n.style=i(i({},e.props.style),n.style)),n.className&&e.props.className&&(n.className=e.props.className+` `+n.className),t.default.cloneElement(e,n)}})),Fu=i((e=>{e.__esModule=!0,e.resizableProps=void 0;var t=n(ju());Nu();function n(e){return e&&e.__esModule?e:{default:e}}e.resizableProps={axis:t.default.oneOf([`both`,`x`,`y`,`none`]),className:t.default.string,children:t.default.element.isRequired,draggableOpts:t.default.shape({allowAnyClick:t.default.bool,cancel:t.default.string,children:t.default.node,disabled:t.default.bool,enableUserSelectHack:t.default.bool,offsetParent:typeof Element<`u`?t.default.instanceOf(Element):t.default.any,grid:t.default.arrayOf(t.default.number),handle:t.default.string,nodeRef:t.default.object,onStart:t.default.func,onDrag:t.default.func,onStop:t.default.func,onMouseDown:t.default.func,scale:t.default.number}),height:function(){var e=[...arguments];let n=e[0];return n.axis===`both`||n.axis===`y`?t.default.number.isRequired(...e):t.default.number(...e)},handle:t.default.oneOfType([t.default.node,t.default.func]),handleSize:t.default.arrayOf(t.default.number),lockAspectRatio:t.default.bool,maxConstraints:t.default.arrayOf(t.default.number),minConstraints:t.default.arrayOf(t.default.number),onResizeStop:t.default.func,onResizeStart:t.default.func,onResize:t.default.func,resizeHandles:t.default.arrayOf(t.default.oneOf([`s`,`w`,`e`,`n`,`sw`,`nw`,`se`,`ne`])),transformScale:t.default.number,width:function(){var e=[...arguments];let n=e[0];return n.axis===`both`||n.axis===`x`?t.default.number.isRequired(...e):t.default.number(...e)}}})),Iu=i((e=>{e.__esModule=!0,e.default=void 0;var t=o(d()),n=Nu(),r=Pu(),i=Fu(),a=[`children`,`className`,`draggableOpts`,`width`,`height`,`handle`,`handleSize`,`lockAspectRatio`,`axis`,`minConstraints`,`maxConstraints`,`onResize`,`onResizeStop`,`onResizeStart`,`resizeHandles`,`transformScale`];function o(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(o=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!=="default"&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function s(){return s=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s.apply(null,arguments)}function c(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function l(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function u(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?l(Object(n),!0).forEach(function(t){f(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):l(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function f(e,t,n){return(t=p(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function p(e){var t=m(e,`string`);return typeof t==`symbol`?t:t+``}function m(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var h=class extends t.Component{constructor(){super(...arguments),this.handleRefs={},this.lastHandleRect=null,this.slack=null,this.lastSize=null}componentWillUnmount(){this.resetData()}resetData(){this.lastHandleRect=this.slack=this.lastSize=null}runConstraints(e,t){let n=this.props,r=n.minConstraints,i=n.maxConstraints,a=n.lockAspectRatio;if(!r&&!i&&!a)return[e,t];if(a){let n=this.props.width/this.props.height,r=e-this.props.width,i=t-this.props.height;Math.abs(r)>Math.abs(i*n)?t=e/n:e=t*n}let o=e,s=t,c=this.slack||[0,0],l=c[0],u=c[1];return e+=l,t+=u,r&&(e=Math.max(r[0],e),t=Math.max(r[1],t)),i&&(e=Math.min(i[0],e),t=Math.min(i[1],t)),this.slack=[l+(o-e),u+(s-t)],[e,t]}resizeHandler(e,t){return(n,r)=>{let i=r.node,a=r.deltaX,o=r.deltaY;e===`onResizeStart`&&this.resetData();let s=(this.props.axis===`both`||this.props.axis===`x`)&&t!==`n`&&t!==`s`,c=(this.props.axis===`both`||this.props.axis===`y`)&&t!==`e`&&t!==`w`;if(!s&&!c)return;let l=t[0],u=t[t.length-1],d=i.getBoundingClientRect();if(this.lastHandleRect!=null){if(u===`w`){let e=d.left-this.lastHandleRect.left;a+=e}if(l===`n`){let e=d.top-this.lastHandleRect.top;o+=e}}this.lastHandleRect=d,u===`w`&&(a=-a),l===`n`&&(o=-o);let f=this.lastSize?.width??this.props.width,p=this.lastSize?.height??this.props.height,m=f+(s?a/this.props.transformScale:0),h=p+(c?o/this.props.transformScale:0);var g=this.runConstraints(m,h);if(m=g[0],h=g[1],e===`onResizeStop`&&this.lastSize){var _=this.lastSize;m=_.width,h=_.height}let v=m!==f||h!==p;e!==`onResizeStop`&&(this.lastSize={width:m,height:h});let y=typeof this.props[e]==`function`?this.props[e]:null;y&&!(e===`onResize`&&!v)&&(n.persist==null||n.persist(),y(n,{node:i,size:{width:m,height:h},handle:t})),e===`onResizeStop`&&this.resetData()}}renderResizeHandle(e,n){let r=this.props.handle;if(!r)return t.createElement(`span`,{className:`react-resizable-handle react-resizable-handle-`+e,ref:n});if(typeof r==`function`)return r(e,n);let i=typeof r.type==`string`,a=u({ref:n},i?{}:{handleAxis:e});return t.cloneElement(r,a)}render(){let e=this.props,i=e.children,o=e.className,l=e.draggableOpts;e.width,e.height,e.handle,e.handleSize,e.lockAspectRatio,e.axis,e.minConstraints,e.maxConstraints,e.onResize,e.onResizeStop,e.onResizeStart;let d=e.resizeHandles;e.transformScale;let f=c(e,a);return(0,r.cloneElement)(i,u(u({},f),{},{className:(o?o+` `:``)+`react-resizable`,children:[...t.Children.toArray(i.props.children),...d.map(e=>{let r=this.handleRefs[e]??(this.handleRefs[e]=t.createRef());return t.createElement(n.DraggableCore,s({},l,{nodeRef:r,key:`resizableHandle-`+e,onStop:this.resizeHandler(`onResizeStop`,e),onStart:this.resizeHandler(`onResizeStart`,e),onDrag:this.resizeHandler(`onResize`,e)}),this.renderResizeHandle(e,r))})]}))}};e.default=h,h.propTypes=i.resizableProps,h.defaultProps={axis:`both`,handleSize:[20,20],lockAspectRatio:!1,minConstraints:[20,20],maxConstraints:[1/0,1/0],resizeHandles:[`se`],transformScale:1}})),Lu=i((e=>{e.__esModule=!0,e.default=void 0;var t=s(d()),n=o(ju()),r=o(Iu()),i=Fu(),a=[`handle`,`handleSize`,`onResize`,`onResizeStart`,`onResizeStop`,`draggableOpts`,`minConstraints`,`maxConstraints`,`lockAspectRatio`,`axis`,`width`,`height`,`resizeHandles`,`style`,`transformScale`];function o(e){return e&&e.__esModule?e:{default:e}}function s(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(s=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!=="default"&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function c(){return c=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},c.apply(null,arguments)}function l(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function u(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?l(Object(n),!0).forEach(function(t){f(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):l(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function f(e,t,n){return(t=p(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function p(e){var t=m(e,`string`);return typeof t==`symbol`?t:t+``}function m(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function h(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var g=class extends t.Component{constructor(){super(...arguments),this.state={width:this.props.width,height:this.props.height,propsWidth:this.props.width,propsHeight:this.props.height},this.onResize=(e,t)=>{let n=t.size;this.props.onResize?(e.persist==null||e.persist(),this.setState(n,()=>this.props.onResize&&this.props.onResize(e,t))):this.setState(n)}}static getDerivedStateFromProps(e,t){return t.propsWidth!==e.width||t.propsHeight!==e.height?{width:e.width,height:e.height,propsWidth:e.width,propsHeight:e.height}:null}render(){let e=this.props,n=e.handle,i=e.handleSize;e.onResize;let o=e.onResizeStart,s=e.onResizeStop,l=e.draggableOpts,d=e.minConstraints,f=e.maxConstraints,p=e.lockAspectRatio,m=e.axis;e.width,e.height;let g=e.resizeHandles,_=e.style,v=e.transformScale,y=h(e,a);return t.createElement(r.default,{axis:m,draggableOpts:l,handle:n,handleSize:i,height:this.state.height,lockAspectRatio:p,maxConstraints:f,minConstraints:d,onResizeStart:o,onResize:this.onResize,onResizeStop:s,resizeHandles:g,transformScale:v,width:this.state.width},t.createElement(`div`,c({},y,{style:u(u({},_),{},{width:this.state.width+`px`,height:this.state.height+`px`})})))}};e.default=g,g.propTypes=u(u({},i.resizableProps),{},{children:n.default.element})})),Ru=i(((e,t)=>{t.exports=function(){throw Error(`Don't instantiate Resizable directly! Use require('react-resizable').Resizable`)},t.exports.Resizable=Iu().default,t.exports.ResizableBox=Lu().default})),zu=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resizeHandleType=e.resizeHandleAxesType=e.default=void 0;var t=r(ju()),n=r(d());function r(e){return e&&e.__esModule?e:{default:e}}var i=e.resizeHandleAxesType=t.default.arrayOf(t.default.oneOf([`s`,`w`,`e`,`n`,`sw`,`nw`,`se`,`ne`])),a=e.resizeHandleType=t.default.oneOfType([t.default.node,t.default.func]);e.default={className:t.default.string,style:t.default.object,width:t.default.number,autoSize:t.default.bool,cols:t.default.number,draggableCancel:t.default.string,draggableHandle:t.default.string,verticalCompact:function(e){e.verticalCompact},compactType:t.default.oneOf([`vertical`,`horizontal`]),layout:function(e){var t=e.layout;t!==void 0&&Du().validateLayout(t,`layout`)},margin:t.default.arrayOf(t.default.number),containerPadding:t.default.arrayOf(t.default.number),rowHeight:t.default.number,maxRows:t.default.number,isBounded:t.default.bool,isDraggable:t.default.bool,isResizable:t.default.bool,allowOverlap:t.default.bool,preventCollision:t.default.bool,useCSSTransforms:t.default.bool,transformScale:t.default.number,isDroppable:t.default.bool,resizeHandles:i,resizeHandle:a,onLayoutChange:t.default.func,onDragStart:t.default.func,onDrag:t.default.func,onDragStop:t.default.func,onResizeStart:t.default.func,onResize:t.default.func,onResizeStop:t.default.func,onDrop:t.default.func,droppingItem:t.default.shape({i:t.default.string.isRequired,w:t.default.number.isRequired,h:t.default.number.isRequired}),children:function(e,t){let r=e[t],i={};n.default.Children.forEach(r,function(e){if(e?.key!=null){if(i[e.key])throw Error(`Duplicate child key "`+e.key+`" found! This will cause problems in ReactGridLayout.`);i[e.key]=!0}})},innerRef:t.default.any}})),Bu=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=u(d()),n=h(),r=u(ju()),i=Nu(),a=Ru(),o=Du(),s=Ou(),c=zu(),l=u($a());function u(e){return e&&e.__esModule?e:{default:e}}function f(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function p(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?f(Object(n),!0).forEach(function(t){m(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):f(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function m(e,t,n){return(t=g(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function g(e){var t=_(e,`string`);return typeof t==`symbol`?t:t+``}function _(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var v=class extends t.default.Component{constructor(){super(...arguments),m(this,`state`,{resizing:null,dragging:null,className:``}),m(this,`elementRef`,t.default.createRef()),m(this,`onDragStart`,(e,t)=>{let{node:n}=t,{onDragStart:r,transformScale:i}=this.props;if(!r)return;let a={top:0,left:0},{offsetParent:o}=n;if(!o)return;let c=o.getBoundingClientRect(),l=n.getBoundingClientRect(),u=l.left/i,d=c.left/i,f=l.top/i,p=c.top/i;a.left=u-d+o.scrollLeft,a.top=f-p+o.scrollTop,this.setState({dragging:a});let{x:m,y:h}=(0,s.calcXY)(this.getPositionParams(),a.top,a.left,this.props.w,this.props.h);return r.call(this,this.props.i,m,h,{e,node:n,newPosition:a})}),m(this,`onDrag`,(e,t,r)=>{let{node:i,deltaX:a,deltaY:o}=t,{onDrag:c}=this.props;if(!c)return;if(!this.state.dragging)throw Error(`onDrag called before onDragStart.`);let l=this.state.dragging.top+o,u=this.state.dragging.left+a,{isBounded:d,i:f,w:p,h:m,containerWidth:h}=this.props,g=this.getPositionParams();if(d){let{offsetParent:e}=i;if(e){let{margin:t,rowHeight:n}=this.props,r=e.clientHeight-(0,s.calcGridItemWHPx)(m,n,t[1]);l=(0,s.clamp)(l,0,r);let i=(0,s.calcGridColWidth)(g),a=h-(0,s.calcGridItemWHPx)(p,i,t[0]);u=(0,s.clamp)(u,0,a)}}let _={top:l,left:u};r?this.setState({dragging:_}):(0,n.flushSync)(()=>{this.setState({dragging:_})});let{x:v,y}=(0,s.calcXY)(g,l,u,p,m);return c.call(this,f,v,y,{e,node:i,newPosition:_})}),m(this,`onDragStop`,(e,t)=>{let{node:n}=t,{onDragStop:r}=this.props;if(!r)return;if(!this.state.dragging)throw Error(`onDragEnd called before onDragStart.`);let{w:i,h:a,i:o}=this.props,{left:c,top:l}=this.state.dragging,u={top:l,left:c};this.setState({dragging:null});let{x:d,y:f}=(0,s.calcXY)(this.getPositionParams(),l,c,i,a);return r.call(this,o,d,f,{e,node:n,newPosition:u})}),m(this,`onResizeStop`,(e,t,n)=>this.onResizeHandler(e,t,n,`onResizeStop`)),m(this,`onResizeStart`,(e,t,n)=>this.onResizeHandler(e,t,n,`onResizeStart`)),m(this,`onResize`,(e,t,n)=>this.onResizeHandler(e,t,n,`onResize`))}shouldComponentUpdate(e,t){if(this.props.children!==e.children||this.props.droppingPosition!==e.droppingPosition)return!0;let n=(0,s.calcGridItemPosition)(this.getPositionParams(this.props),this.props.x,this.props.y,this.props.w,this.props.h,this.state),r=(0,s.calcGridItemPosition)(this.getPositionParams(e),e.x,e.y,e.w,e.h,t);return!(0,o.fastPositionEqual)(n,r)||this.props.useCSSTransforms!==e.useCSSTransforms}componentDidMount(){this.moveDroppingItem({})}componentDidUpdate(e){this.moveDroppingItem(e)}moveDroppingItem(e){let{droppingPosition:t}=this.props;if(!t)return;let n=this.elementRef.current;if(!n)return;let r=e.droppingPosition||{left:0,top:0},{dragging:i}=this.state,a=i&&t.left!==r.left||t.top!==r.top;if(!i)this.onDragStart(t.e,{node:n,deltaX:t.left,deltaY:t.top});else if(a){let e=t.left-i.left,r=t.top-i.top;this.onDrag(t.e,{node:n,deltaX:e,deltaY:r},!0)}}getPositionParams(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.props;return{cols:e.cols,containerPadding:e.containerPadding,containerWidth:e.containerWidth,margin:e.margin,maxRows:e.maxRows,rowHeight:e.rowHeight}}createStyle(e){let{usePercentages:t,containerWidth:n,useCSSTransforms:r}=this.props,i;return r?i=(0,o.setTransform)(e):(i=(0,o.setTopLeft)(e),t&&(i.left=(0,o.perc)(e.left/n),i.width=(0,o.perc)(e.width/n))),i}mixinDraggable(e,n){return t.default.createElement(i.DraggableCore,{disabled:!n,onStart:this.onDragStart,onDrag:this.onDrag,onStop:this.onDragStop,handle:this.props.handle,cancel:`.react-resizable-handle`+(this.props.cancel?`,`+this.props.cancel:``),scale:this.props.transformScale,nodeRef:this.elementRef},e)}curryResizeHandler(e,t){return(n,r)=>t(n,r,e)}mixinResizable(e,n,r){let{cols:i,minW:o,minH:c,maxW:l,maxH:u,transformScale:d,resizeHandles:f,resizeHandle:p}=this.props,m=this.getPositionParams(),h=(0,s.calcGridItemPosition)(m,0,0,i,0).width,g=(0,s.calcGridItemPosition)(m,0,0,o,c),_=(0,s.calcGridItemPosition)(m,0,0,l,u),v=[g.width,g.height],y=[Math.min(_.width,h),Math.min(_.height,1/0)];return t.default.createElement(a.Resizable,{draggableOpts:{disabled:!r},className:r?void 0:`react-resizable-hide`,width:n.width,height:n.height,minConstraints:v,maxConstraints:y,onResizeStop:this.curryResizeHandler(n,this.onResizeStop),onResizeStart:this.curryResizeHandler(n,this.onResizeStart),onResize:this.curryResizeHandler(n,this.onResize),transformScale:d,resizeHandles:f,handle:p},e)}onResizeHandler(e,t,r,i){let{node:a,size:c,handle:l}=t,u=this.props[i];if(!u)return;let{x:d,y:f,i:p,maxH:m,minH:h,containerWidth:g}=this.props,{minW:_,maxW:v}=this.props,y=c;a&&(y=(0,o.resizeItemInDirection)(l,r,c,g),(0,n.flushSync)(()=>{this.setState({resizing:i===`onResizeStop`?null:y})}));let{w:b,h:x}=(0,s.calcWH)(this.getPositionParams(),y.width,y.height,d,f,l);b=(0,s.clamp)(b,Math.max(_,1),v),x=(0,s.clamp)(x,h,m),u.call(this,p,b,x,{e,node:a,size:y,handle:l})}render(){let{x:e,y:n,w:r,h:i,isDraggable:a,isResizable:o,droppingPosition:c,useCSSTransforms:u}=this.props,d=(0,s.calcGridItemPosition)(this.getPositionParams(),e,n,r,i,this.state),f=t.default.Children.only(this.props.children),m=t.default.cloneElement(f,{ref:this.elementRef,className:(0,l.default)(`react-grid-item`,f.props.className,this.props.className,{static:this.props.static,resizing:!!this.state.resizing,"react-draggable":a,"react-draggable-dragging":!!this.state.dragging,dropping:!!c,cssTransforms:u}),style:p(p(p({},this.props.style),f.props.style),this.createStyle(d))});return m=this.mixinResizable(m,d,o),m=this.mixinDraggable(m,a),m}};e.default=v,m(v,`propTypes`,{children:r.default.element,cols:r.default.number.isRequired,containerWidth:r.default.number.isRequired,rowHeight:r.default.number.isRequired,margin:r.default.array.isRequired,maxRows:r.default.number.isRequired,containerPadding:r.default.array.isRequired,x:r.default.number.isRequired,y:r.default.number.isRequired,w:r.default.number.isRequired,h:r.default.number.isRequired,minW:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`minWidth not Number`);if(n>e.w||n>e.maxW)return Error(`minWidth larger than item width/maxWidth`)},maxW:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`maxWidth not Number`);if(n<e.w||n<e.minW)return Error(`maxWidth smaller than item width/minWidth`)},minH:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`minHeight not Number`);if(n>e.h||n>e.maxH)return Error(`minHeight larger than item height/maxHeight`)},maxH:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`maxHeight not Number`);if(n<e.h||n<e.minH)return Error(`maxHeight smaller than item height/minHeight`)},i:r.default.string.isRequired,resizeHandles:c.resizeHandleAxesType,resizeHandle:c.resizeHandleType,onDragStop:r.default.func,onDragStart:r.default.func,onDrag:r.default.func,onResizeStop:r.default.func,onResizeStart:r.default.func,onResize:r.default.func,isDraggable:r.default.bool.isRequired,isResizable:r.default.bool.isRequired,isBounded:r.default.bool.isRequired,static:r.default.bool,useCSSTransforms:r.default.bool.isRequired,transformScale:r.default.number,className:r.default.string,handle:r.default.string,cancel:r.default.string,droppingPosition:r.default.shape({e:r.default.object.isRequired,left:r.default.number.isRequired,top:r.default.number.isRequired})}),m(v,`defaultProps`,{className:``,cancel:``,handle:``,minH:1,minW:1,maxH:1/0,maxW:1/0,transformScale:1})})),Vu=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=l(d()),n=Tu(),r=c($a()),i=Du(),a=Ou(),o=c(Bu()),s=c(zu());function c(e){return e&&e.__esModule?e:{default:e}}function l(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(l=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!=="default"&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function u(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function f(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?u(Object(n),!0).forEach(function(t){p(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):u(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function p(e,t,n){return(t=m(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function m(e){var t=h(e,`string`);return typeof t==`symbol`?t:t+``}function h(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var g=`react-grid-layout`,_=!1;try{_=/firefox/i.test(navigator.userAgent)}catch{}var v=class extends t.Component{constructor(){super(...arguments),p(this,`state`,{activeDrag:null,layout:(0,i.synchronizeLayoutWithChildren)(this.props.layout,this.props.children,this.props.cols,(0,i.compactType)(this.props),this.props.allowOverlap),mounted:!1,oldDragItem:null,oldLayout:null,oldResizeItem:null,resizing:!1,droppingDOMNode:null,children:[]}),p(this,`dragEnterCounter`,0),p(this,`onDragStart`,(e,t,n,r)=>{let{e:a,node:o}=r,{layout:s}=this.state,c=(0,i.getLayoutItem)(s,e);if(!c)return;let l={w:c.w,h:c.h,x:c.x,y:c.y,placeholder:!0,i:e};return this.setState({oldDragItem:(0,i.cloneLayoutItem)(c),oldLayout:s,activeDrag:l}),this.props.onDragStart(s,c,c,null,a,o)}),p(this,`onDrag`,(e,t,n,r)=>{let{e:a,node:o}=r,{oldDragItem:s}=this.state,{layout:c}=this.state,{cols:l,allowOverlap:u,preventCollision:d}=this.props,f=(0,i.getLayoutItem)(c,e);if(!f)return;let p={w:f.w,h:f.h,x:f.x,y:f.y,placeholder:!0,i:e};c=(0,i.moveElement)(c,f,t,n,!0,d,(0,i.compactType)(this.props),l,u),this.props.onDrag(c,s,f,p,a,o),this.setState({layout:u?c:(0,i.compact)(c,(0,i.compactType)(this.props),l),activeDrag:p})}),p(this,`onDragStop`,(e,t,n,r)=>{let{e:a,node:o}=r;if(!this.state.activeDrag)return;let{oldDragItem:s}=this.state,{layout:c}=this.state,{cols:l,preventCollision:u,allowOverlap:d}=this.props,f=(0,i.getLayoutItem)(c,e);if(!f)return;c=(0,i.moveElement)(c,f,t,n,!0,u,(0,i.compactType)(this.props),l,d);let p=d?c:(0,i.compact)(c,(0,i.compactType)(this.props),l);this.props.onDragStop(p,s,f,null,a,o);let{oldLayout:m}=this.state;this.setState({activeDrag:null,layout:p,oldDragItem:null,oldLayout:null}),this.onLayoutMaybeChanged(p,m)}),p(this,`onResizeStart`,(e,t,n,r)=>{let{e:a,node:o}=r,{layout:s}=this.state,c=(0,i.getLayoutItem)(s,e);c&&(this.setState({oldResizeItem:(0,i.cloneLayoutItem)(c),oldLayout:this.state.layout,resizing:!0}),this.props.onResizeStart(s,c,c,null,a,o))}),p(this,`onResize`,(e,t,n,r)=>{let{e:a,node:o,size:s,handle:c}=r,{oldResizeItem:l}=this.state,{layout:u}=this.state,{cols:d,preventCollision:p,allowOverlap:m}=this.props,h=!1,g,_,v,[y,b]=(0,i.withLayoutItem)(u,e,e=>{let r;return _=e.x,v=e.y,[`sw`,`w`,`nw`,`n`,`ne`].indexOf(c)!==-1&&([`sw`,`nw`,`w`].indexOf(c)!==-1&&(_=e.x+(e.w-t),t=e.x!==_&&_<0?e.w:t,_=_<0?0:_),[`ne`,`n`,`nw`].indexOf(c)!==-1&&(v=e.y+(e.h-n),n=e.y!==v&&v<0?e.h:n,v=v<0?0:v),h=!0),p&&!m&&(r=(0,i.getAllCollisions)(u,f(f({},e),{},{w:t,h:n,x:_,y:v})).filter(t=>t.i!==e.i).length>0,r&&(v=e.y,n=e.h,_=e.x,t=e.w,h=!1)),e.w=t,e.h=n,e});if(!b)return;g=y,h&&(g=(0,i.moveElement)(y,b,_,v,!0,this.props.preventCollision,(0,i.compactType)(this.props),d,m));let x={w:b.w,h:b.h,x:b.x,y:b.y,static:!0,i:e};this.props.onResize(g,l,b,x,a,o),this.setState({layout:m?g:(0,i.compact)(g,(0,i.compactType)(this.props),d),activeDrag:x})}),p(this,`onResizeStop`,(e,t,n,r)=>{let{e:a,node:o}=r,{layout:s,oldResizeItem:c}=this.state,{cols:l,allowOverlap:u}=this.props,d=(0,i.getLayoutItem)(s,e),f=u?s:(0,i.compact)(s,(0,i.compactType)(this.props),l);this.props.onResizeStop(f,c,d,null,a,o);let{oldLayout:p}=this.state;this.setState({activeDrag:null,layout:f,oldResizeItem:null,oldLayout:null,resizing:!1}),this.onLayoutMaybeChanged(f,p)}),p(this,`onDragOver`,e=>{var n;if(e.preventDefault(),e.stopPropagation(),_&&!((n=e.nativeEvent.target)!=null&&n.classList.contains(g)))return!1;let{droppingItem:r,onDropDragOver:i,margin:o,cols:s,rowHeight:c,maxRows:l,width:u,containerPadding:d,transformScale:p}=this.props,m=i?.(e);if(m===!1)return this.state.droppingDOMNode&&this.removeDroppingPlaceholder(),!1;let h=f(f({},r),m),{layout:v}=this.state,y=e.currentTarget.getBoundingClientRect(),b=e.clientX-y.left,x=e.clientY-y.top,S={left:b/p,top:x/p,e};if(!this.state.droppingDOMNode){let e={cols:s,margin:o,maxRows:l,rowHeight:c,containerWidth:u,containerPadding:d||o},n=(0,a.calcXY)(e,x,b,h.w,h.h);this.setState({droppingDOMNode:t.createElement(`div`,{key:h.i}),droppingPosition:S,layout:[...v,f(f({},h),{},{x:n.x,y:n.y,static:!1,isDraggable:!0})]})}else if(this.state.droppingPosition){let{left:e,top:t}=this.state.droppingPosition;(e!=b||t!=x)&&this.setState({droppingPosition:S})}}),p(this,`removeDroppingPlaceholder`,()=>{let{droppingItem:e,cols:t}=this.props,{layout:n}=this.state,r=(0,i.compact)(n.filter(t=>t.i!==e.i),(0,i.compactType)(this.props),t,this.props.allowOverlap);this.setState({layout:r,droppingDOMNode:null,activeDrag:null,droppingPosition:void 0})}),p(this,`onDragLeave`,e=>{e.preventDefault(),e.stopPropagation(),this.dragEnterCounter--,this.dragEnterCounter===0&&this.removeDroppingPlaceholder()}),p(this,`onDragEnter`,e=>{e.preventDefault(),e.stopPropagation(),this.dragEnterCounter++}),p(this,`onDrop`,e=>{e.preventDefault(),e.stopPropagation();let{droppingItem:t}=this.props,{layout:n}=this.state,r=n.find(e=>e.i===t.i);this.dragEnterCounter=0,this.removeDroppingPlaceholder(),this.props.onDrop(n,r,e)})}componentDidMount(){this.setState({mounted:!0}),this.onLayoutMaybeChanged(this.state.layout,this.props.layout)}static getDerivedStateFromProps(e,t){let r;return t.activeDrag?null:(!(0,n.deepEqual)(e.layout,t.propsLayout)||e.compactType!==t.compactType?r=e.layout:(0,i.childrenEqual)(e.children,t.children)||(r=t.layout),r?{layout:(0,i.synchronizeLayoutWithChildren)(r,e.children,e.cols,(0,i.compactType)(e),e.allowOverlap),compactType:e.compactType,children:e.children,propsLayout:e.layout}:null)}shouldComponentUpdate(e,t){return this.props.children!==e.children||!(0,i.fastRGLPropsEqual)(this.props,e,n.deepEqual)||this.state.activeDrag!==t.activeDrag||this.state.mounted!==t.mounted||this.state.droppingPosition!==t.droppingPosition}componentDidUpdate(e,t){if(!this.state.activeDrag){let e=this.state.layout,n=t.layout;this.onLayoutMaybeChanged(e,n)}}containerHeight(){if(!this.props.autoSize)return;let e=(0,i.bottom)(this.state.layout),t=this.props.containerPadding?this.props.containerPadding[1]:this.props.margin[1];return e*this.props.rowHeight+(e-1)*this.props.margin[1]+t*2+`px`}onLayoutMaybeChanged(e,t){t||=this.state.layout,(0,n.deepEqual)(t,e)||this.props.onLayoutChange(e)}placeholder(){let{activeDrag:e}=this.state;if(!e)return null;let{width:n,cols:r,margin:i,containerPadding:a,rowHeight:s,maxRows:c,useCSSTransforms:l,transformScale:u}=this.props;return t.createElement(o.default,{w:e.w,h:e.h,x:e.x,y:e.y,i:e.i,className:`react-grid-placeholder ${this.state.resizing?`placeholder-resizing`:``}`,containerWidth:n,cols:r,margin:i,containerPadding:a||i,maxRows:c,rowHeight:s,isDraggable:!1,isResizable:!1,isBounded:!1,useCSSTransforms:l,transformScale:u},t.createElement(`div`,null))}processGridItem(e,n){if(!e||!e.key)return;let r=(0,i.getLayoutItem)(this.state.layout,String(e.key));if(!r)return null;let{width:a,cols:s,margin:c,containerPadding:l,rowHeight:u,maxRows:d,isDraggable:f,isResizable:p,isBounded:m,useCSSTransforms:h,transformScale:g,draggableCancel:_,draggableHandle:v,resizeHandles:y,resizeHandle:b}=this.props,{mounted:x,droppingPosition:S}=this.state,C=typeof r.isDraggable==`boolean`?r.isDraggable:!r.static&&f,w=typeof r.isResizable==`boolean`?r.isResizable:!r.static&&p,T=r.resizeHandles||y,E=C&&m&&r.isBounded!==!1;return t.createElement(o.default,{containerWidth:a,cols:s,margin:c,containerPadding:l||c,maxRows:d,rowHeight:u,cancel:_,handle:v,onDragStop:this.onDragStop,onDragStart:this.onDragStart,onDrag:this.onDrag,onResizeStart:this.onResizeStart,onResize:this.onResize,onResizeStop:this.onResizeStop,isDraggable:C,isResizable:w,isBounded:E,useCSSTransforms:h&&x,usePercentages:!x,transformScale:g,w:r.w,h:r.h,x:r.x,y:r.y,i:r.i,minH:r.minH,minW:r.minW,maxH:r.maxH,maxW:r.maxW,static:r.static,droppingPosition:n?S:void 0,resizeHandles:T,resizeHandle:b},e)}render(){let{className:e,style:n,isDroppable:a,innerRef:o}=this.props,s=(0,r.default)(g,e),c=f({height:this.containerHeight()},n);return t.createElement(`div`,{ref:o,className:s,style:c,onDrop:a?this.onDrop:i.noop,onDragLeave:a?this.onDragLeave:i.noop,onDragEnter:a?this.onDragEnter:i.noop,onDragOver:a?this.onDragOver:i.noop},t.Children.map(this.props.children,e=>this.processGridItem(e)),a&&this.state.droppingDOMNode&&this.processGridItem(this.state.droppingDOMNode,!0),this.placeholder())}};e.default=v,p(v,`displayName`,`ReactGridLayout`),p(v,`propTypes`,s.default),p(v,`defaultProps`,{autoSize:!0,cols:12,className:``,style:{},draggableHandle:``,draggableCancel:``,containerPadding:null,rowHeight:150,maxRows:1/0,layout:[],margin:[10,10],isBounded:!1,isDraggable:!0,isResizable:!0,allowOverlap:!1,isDroppable:!1,useCSSTransforms:!0,transformScale:1,verticalCompact:!0,compactType:`vertical`,preventCollision:!1,droppingItem:{i:`__dropping-elem__`,h:1,w:1},resizeHandles:[`se`],onLayoutChange:i.noop,onDragStart:i.noop,onDrag:i.noop,onDragStop:i.noop,onResizeStart:i.noop,onResize:i.noop,onResizeStop:i.noop,onDrop:i.noop,onDropDragOver:i.noop})})),Hu=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.findOrGenerateResponsiveLayout=i,e.getBreakpointFromWidth=n,e.getColsFromBreakpoint=r,e.sortBreakpoints=a;var t=Du();function n(e,t){let n=a(e),r=n[0];for(let i=1,a=n.length;i<a;i++){let a=n[i];t>e[a]&&(r=a)}return r}function r(e,t){if(!t[e])throw Error("ResponsiveReactGridLayout: `cols` entry for breakpoint "+e+` is missing!`);return t[e]}function i(e,n,r,i,o,s){if(e[r])return(0,t.cloneLayout)(e[r]);let c=e[i],l=a(n),u=l.slice(l.indexOf(r));for(let t=0,n=u.length;t<n;t++){let n=u[t];if(e[n]){c=e[n];break}}return c=(0,t.cloneLayout)(c||[]),(0,t.compact)((0,t.correctBounds)(c,{cols:o}),s,o)}function a(e){return Object.keys(e).sort(function(t,n){return e[t]-e[n]})}})),Uu=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=l(d()),n=c(ju()),r=Tu(),i=Du(),a=Hu(),o=c(Vu()),s=[`breakpoint`,`breakpoints`,`cols`,`layouts`,`margin`,`containerPadding`,`onBreakpointChange`,`onLayoutChange`,`onWidthChange`];function c(e){return e&&e.__esModule?e:{default:e}}function l(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(l=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!=="default"&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function u(){return u=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u.apply(null,arguments)}function f(e,t){if(e==null)return{};var n,r,i=p(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function p(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function m(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function h(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?m(Object(n),!0).forEach(function(t){g(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):m(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function g(e,t,n){return(t=_(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function _(e){var t=v(e,`string`);return typeof t==`symbol`?t:t+``}function v(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var y=e=>Object.prototype.toString.call(e);function b(e,t){return e==null?null:Array.isArray(e)?e:e[t]}var x=class extends t.Component{constructor(){super(...arguments),g(this,`state`,this.generateInitialState()),g(this,`onLayoutChange`,e=>{this.props.onLayoutChange(e,h(h({},this.props.layouts),{},{[this.state.breakpoint]:e}))})}generateInitialState(){let{width:e,breakpoints:t,layouts:n,cols:r}=this.props,i=(0,a.getBreakpointFromWidth)(t,e),o=(0,a.getColsFromBreakpoint)(i,r),s=this.props.verticalCompact===!1?null:this.props.compactType;return{layout:(0,a.findOrGenerateResponsiveLayout)(n,t,i,i,o,s),breakpoint:i,cols:o}}static getDerivedStateFromProps(e,t){if(!(0,r.deepEqual)(e.layouts,t.layouts)){let{breakpoint:n,cols:r}=t;return{layout:(0,a.findOrGenerateResponsiveLayout)(e.layouts,e.breakpoints,n,n,r,e.compactType),layouts:e.layouts}}return null}componentDidUpdate(e){(this.props.width!=e.width||this.props.breakpoint!==e.breakpoint||!(0,r.deepEqual)(this.props.breakpoints,e.breakpoints)||!(0,r.deepEqual)(this.props.cols,e.cols))&&this.onWidthChange(e)}onWidthChange(e){let{breakpoints:t,cols:n,layouts:r,compactType:o}=this.props,s=this.props.breakpoint||(0,a.getBreakpointFromWidth)(this.props.breakpoints,this.props.width),c=this.state.breakpoint,l=(0,a.getColsFromBreakpoint)(s,n),u=h({},r);if(c!==s||e.breakpoints!==t||e.cols!==n){c in u||(u[c]=(0,i.cloneLayout)(this.state.layout));let e=(0,a.findOrGenerateResponsiveLayout)(u,t,s,c,l,o);e=(0,i.synchronizeLayoutWithChildren)(e,this.props.children,l,o,this.props.allowOverlap),u[s]=e,this.props.onBreakpointChange(s,l),this.props.onLayoutChange(e,u),this.setState({breakpoint:s,layout:e,cols:l})}let d=b(this.props.margin,s),f=b(this.props.containerPadding,s);this.props.onWidthChange(this.props.width,d,l,f)}render(){let e=this.props,{breakpoint:n,breakpoints:r,cols:i,layouts:a,margin:c,containerPadding:l,onBreakpointChange:d,onLayoutChange:p,onWidthChange:m}=e,h=f(e,s);return t.createElement(o.default,u({},h,{margin:b(c,this.state.breakpoint),containerPadding:b(l,this.state.breakpoint),onLayoutChange:this.onLayoutChange,layout:this.state.layout,cols:this.state.cols}))}};e.default=x,g(x,`propTypes`,{breakpoint:n.default.string,breakpoints:n.default.object,allowOverlap:n.default.bool,cols:n.default.object,margin:n.default.oneOfType([n.default.array,n.default.object]),containerPadding:n.default.oneOfType([n.default.array,n.default.object]),layouts(e,t){if(y(e[t])!==`[object Object]`)throw Error(`Layout property must be an object. Received: `+y(e[t]));Object.keys(e[t]).forEach(t=>{if(!(t in e.breakpoints))throw Error(`Each key in layouts must align with a key in breakpoints.`);(0,i.validateLayout)(e.layouts[t],`layouts.`+t)})},width:n.default.number.isRequired,onBreakpointChange:n.default.func,onLayoutChange:n.default.func,onWidthChange:n.default.func}),g(x,`defaultProps`,{breakpoints:{lg:1200,md:996,sm:768,xs:480,xxs:0},cols:{lg:12,md:10,sm:6,xs:4,xxs:2},containerPadding:{lg:null,md:null,sm:null,xs:null,xxs:null},layouts:{},margin:[10,10],allowOverlap:!1,onBreakpointChange:i.noop,onLayoutChange:i.noop,onWidthChange:i.noop})})),Wu=r({default:()=>yd});function Gu(e,t){var n=!1,r=!1,i=0;function a(){n&&(n=!1,e()),r&&s()}function o(){id(a)}function s(){var e=Date.now();if(n){if(e-i<ad)return;r=!0}else n=!0,r=!1,setTimeout(o,t);i=e}return s}function Ku(e){return parseFloat(e)||0}function qu(e){return[...arguments].slice(1).reduce(function(t,n){var r=e[`border-`+n+`-width`];return t+Ku(r)},0)}function Ju(e){for(var t=[`top`,`right`,`bottom`,`left`],n={},r=0,i=t;r<i.length;r++){var a=i[r],o=e[`padding-`+a];n[a]=Ku(o)}return n}function Yu(e){var t=e.getBBox();return ed(0,0,t.width,t.height)}function Xu(e){var t=e.clientWidth,n=e.clientHeight;if(!t&&!n)return fd;var r=dd(e).getComputedStyle(e),i=Ju(r),a=i.left+i.right,o=i.top+i.bottom,s=Ku(r.width),c=Ku(r.height);if(r.boxSizing===`border-box`&&(Math.round(s+a)!==t&&(s-=qu(r,`left`,`right`)+a),Math.round(c+o)!==n&&(c-=qu(r,`top`,`bottom`)+o)),!Zu(e)){var l=Math.round(s+a)-t,u=Math.round(c+o)-n;Math.abs(l)!==1&&(s-=l),Math.abs(u)!==1&&(c-=u)}return ed(i.left,i.top,s,c)}function Zu(e){return e===dd(e).document.documentElement}function Qu(e){return nd?pd(e)?Yu(e):Xu(e):fd}function $u(e){var t=e.x,n=e.y,r=e.width,i=e.height,a=Object.create((typeof DOMRectReadOnly<`u`?DOMRectReadOnly:Object).prototype);return ud(a,{x:t,y:n,width:r,height:i,top:n,right:t+r,bottom:i+n,left:t}),a}function ed(e,t,n,r){return{x:e,y:t,width:n,height:r}}var td,nd,rd,id,ad,od,sd,cd,ld,ud,dd,fd,pd,md,hd,gd,_d,vd,yd,bd=t((()=>{td=(function(){if(typeof Map<`u`)return Map;function e(e,t){var n=-1;return e.some(function(e,r){return e[0]===t&&(n=r,!0)}),n}return function(){function t(){this.__entries__=[]}return Object.defineProperty(t.prototype,"size",{get:function(){return this.__entries__.length},enumerable:!0,configurable:!0}),t.prototype.get=function(t){var n=e(this.__entries__,t),r=this.__entries__[n];return r&&r[1]},t.prototype.set=function(t,n){var r=e(this.__entries__,t);~r?this.__entries__[r][1]=n:this.__entries__.push([t,n])},t.prototype.delete=function(t){var n=this.__entries__,r=e(n,t);~r&&n.splice(r,1)},t.prototype.has=function(t){return!!~e(this.__entries__,t)},t.prototype.clear=function(){this.__entries__.splice(0)},t.prototype.forEach=function(e,t){t===void 0&&(t=null);for(var n=0,r=this.__entries__;n<r.length;n++){var i=r[n];e.call(t,i[1],i[0])}},t}()})(),nd=typeof window<`u`&&typeof document<`u`&&window.document===document,rd=(function(){return typeof global<`u`&&global.Math===Math?global:typeof self<`u`&&self.Math===Math?self:typeof window<`u`&&window.Math===Math?window:Function(`return this`)()})(),id=(function(){return typeof requestAnimationFrame==`function`?requestAnimationFrame.bind(rd):function(e){return setTimeout(function(){return e(Date.now())},1e3/60)}})(),ad=2,od=20,sd=[`top`,`right`,`bottom`,`left`,`width`,`height`,`size`,`weight`],cd=typeof MutationObserver<`u`,ld=function(){function e(){this.connected_=!1,this.mutationEventsAdded_=!1,this.mutationsObserver_=null,this.observers_=[],this.onTransitionEnd_=this.onTransitionEnd_.bind(this),this.refresh=Gu(this.refresh.bind(this),od)}return e.prototype.addObserver=function(e){~this.observers_.indexOf(e)||this.observers_.push(e),this.connected_||this.connect_()},e.prototype.removeObserver=function(e){var t=this.observers_,n=t.indexOf(e);~n&&t.splice(n,1),!t.length&&this.connected_&&this.disconnect_()},e.prototype.refresh=function(){this.updateObservers_()&&this.refresh()},e.prototype.updateObservers_=function(){var e=this.observers_.filter(function(e){return e.gatherActive(),e.hasActive()});return e.forEach(function(e){return e.broadcastActive()}),e.length>0},e.prototype.connect_=function(){!nd||this.connected_||(document.addEventListener(`transitionend`,this.onTransitionEnd_),window.addEventListener(`resize`,this.refresh),cd?(this.mutationsObserver_=new MutationObserver(this.refresh),this.mutationsObserver_.observe(document,{attributes:!0,childList:!0,characterData:!0,subtree:!0})):(document.addEventListener(`DOMSubtreeModified`,this.refresh),this.mutationEventsAdded_=!0),this.connected_=!0)},e.prototype.disconnect_=function(){!nd||!this.connected_||(document.removeEventListener(`transitionend`,this.onTransitionEnd_),window.removeEventListener(`resize`,this.refresh),this.mutationsObserver_&&this.mutationsObserver_.disconnect(),this.mutationEventsAdded_&&document.removeEventListener(`DOMSubtreeModified`,this.refresh),this.mutationsObserver_=null,this.mutationEventsAdded_=!1,this.connected_=!1)},e.prototype.onTransitionEnd_=function(e){var t=e.propertyName,n=t===void 0?``:t;sd.some(function(e){return!!~n.indexOf(e)})&&this.refresh()},e.getInstance=function(){return this.instance_||=new e,this.instance_},e.instance_=null,e}(),ud=(function(e,t){for(var n=0,r=Object.keys(t);n<r.length;n++){var i=r[n];Object.defineProperty(e,i,{value:t[i],enumerable:!1,writable:!1,configurable:!0})}return e}),dd=(function(e){return e&&e.ownerDocument&&e.ownerDocument.defaultView||rd}),fd=ed(0,0,0,0),pd=(function(){return typeof SVGGraphicsElement<`u`?function(e){return e instanceof dd(e).SVGGraphicsElement}:function(e){return e instanceof dd(e).SVGElement&&typeof e.getBBox==`function`}})(),md=function(){function e(e){this.broadcastWidth=0,this.broadcastHeight=0,this.contentRect_=ed(0,0,0,0),this.target=e}return e.prototype.isActive=function(){var e=Qu(this.target);return this.contentRect_=e,e.width!==this.broadcastWidth||e.height!==this.broadcastHeight},e.prototype.broadcastRect=function(){var e=this.contentRect_;return this.broadcastWidth=e.width,this.broadcastHeight=e.height,e},e}(),hd=function(){function e(e,t){var n=$u(t);ud(this,{target:e,contentRect:n})}return e}(),gd=function(){function e(e,t,n){if(this.activeObservations_=[],this.observations_=new td,typeof e!=`function`)throw TypeError(`The callback provided as parameter 1 is not a function.`);this.callback_=e,this.controller_=t,this.callbackCtx_=n}return e.prototype.observe=function(e){if(!arguments.length)throw TypeError(`1 argument required, but only 0 present.`);if(!(typeof Element>`u`||!(Element instanceof Object))){if(!(e instanceof dd(e).Element))throw TypeError(`parameter 1 is not of type "Element".`);var t=this.observations_;t.has(e)||(t.set(e,new md(e)),this.controller_.addObserver(this),this.controller_.refresh())}},e.prototype.unobserve=function(e){if(!arguments.length)throw TypeError(`1 argument required, but only 0 present.`);if(!(typeof Element>`u`||!(Element instanceof Object))){if(!(e instanceof dd(e).Element))throw TypeError(`parameter 1 is not of type "Element".`);var t=this.observations_;t.has(e)&&(t.delete(e),t.size||this.controller_.removeObserver(this))}},e.prototype.disconnect=function(){this.clearActive(),this.observations_.clear(),this.controller_.removeObserver(this)},e.prototype.gatherActive=function(){var e=this;this.clearActive(),this.observations_.forEach(function(t){t.isActive()&&e.activeObservations_.push(t)})},e.prototype.broadcastActive=function(){if(this.hasActive()){var e=this.callbackCtx_,t=this.activeObservations_.map(function(e){return new hd(e.target,e.broadcastRect())});this.callback_.call(e,t,e),this.clearActive()}},e.prototype.clearActive=function(){this.activeObservations_.splice(0)},e.prototype.hasActive=function(){return this.activeObservations_.length>0},e}(),_d=typeof WeakMap<`u`?new WeakMap:new td,vd=function(){function e(t){if(!(this instanceof e))throw TypeError(`Cannot call a class as a function.`);if(!arguments.length)throw TypeError(`1 argument required, but only 0 present.`);var n=new gd(t,ld.getInstance(),this);_d.set(this,n)}return e}(),[`observe`,`unobserve`,`disconnect`].forEach(function(e){vd.prototype[e]=function(){var t;return(t=_d.get(this))[e].apply(t,arguments)}}),yd=(function(){return rd.ResizeObserver===void 0?vd:rd.ResizeObserver})()})),xd=i((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=_;var n=c(d()),r=s(ju()),i=s((bd(),e(Wu))),a=s($a()),o=[`measureBeforeMount`];function s(e){return e&&e.__esModule?e:{default:e}}function c(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(c=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!=="default"&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function l(){return l=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l.apply(null,arguments)}function u(e,t){if(e==null)return{};var n,r,i=f(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function f(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function p(e,t,n){return(t=m(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function m(e){var t=h(e,`string`);return typeof t==`symbol`?t:t+``}function h(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var g=`react-grid-layout`;function _(e){var t;return t=class extends n.Component{constructor(){super(...arguments),p(this,`state`,{width:1280}),p(this,`elementRef`,n.createRef()),p(this,`mounted`,!1),p(this,`resizeObserver`,void 0)}componentDidMount(){this.mounted=!0,this.resizeObserver=new i.default(e=>{if(this.elementRef.current instanceof HTMLElement){let t=e[0].contentRect.width;this.setState({width:t})}});let e=this.elementRef.current;e instanceof HTMLElement&&this.resizeObserver.observe(e)}componentWillUnmount(){this.mounted=!1;let e=this.elementRef.current;e instanceof HTMLElement&&this.resizeObserver.unobserve(e),this.resizeObserver.disconnect()}render(){let t=this.props,{measureBeforeMount:r}=t,i=u(t,o);return r&&!this.mounted?n.createElement(`div`,{className:(0,a.default)(this.props.className,g),style:this.props.style,ref:this.elementRef}):n.createElement(e,l({innerRef:this.elementRef},i,this.state))}},p(t,`defaultProps`,{measureBeforeMount:!1}),p(t,`propTypes`,{measureBeforeMount:r.default.bool}),t}})),Sd=n(i(((e,t)=>{t.exports=Vu().default,t.exports.utils=Du(),t.exports.calculateUtils=Ou(),t.exports.Responsive=Uu().default,t.exports.Responsive.utils=Hu(),t.exports.WidthProvider=xd().default}))(),1),Cd=new Map;function wd(e){Cd.set(e.type,e)}function Td(e){return Cd.get(e)}function Ed(){return[...Cd.values()]}function Dd(e,t){let n=typeof e.setCanvasQueries==`function`,[r,i]=(0,X.useState)(e.canvasQueries??[]),a=(0,X.useMemo)(()=>n?e.canvasQueries??[]:r,[n,e.canvasQueries,r]),o=(0,X.useCallback)(r=>{n?e.setCanvasQueries(r):i(r),t?.()},[n,e,t]);return{queries:a,runSearch:(0,X.useCallback)(e=>{let t=e.trim();!t||a.includes(t)||o([...a,t])},[a,o]),removeQuery:(0,X.useCallback)(e=>{o(e<0?[]:a.filter((t,n)=>n!==e))},[a,o]),clearSearch:(0,X.useCallback)(()=>o([]),[o])}}function Od({config:e,canvas:t}){let n=typeof e.pageSize==`number`?e.pageSize:50,r=e.viewMode===`card`||e.viewMode===`tile`||e.viewMode===`table`?e.viewMode:`table`,[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(0),[c,l]=(0,X.useState)(1),[u,d]=(0,X.useState)(!0),f=t.canvasSort??xt,{queries:p,runSearch:m,removeQuery:h}=Dd(t,()=>l(1));(0,X.useEffect)(()=>{let e=!1;return(async()=>{d(!0);try{let r=await t.fetchDocuments({limit:n,page:c,sortBy:f.sortBy,order:f.order,queries:p.length?p:void 0});if(e)return;a(r.payload||[]),s(r.totalCount||r.count||0)}catch{e||(a([]),s(0))}finally{e||d(!1)}})(),()=>{e=!0}},[t,n,c,f.sortBy,f.order,p]);let g=(0,X.useCallback)(e=>{t.setCanvasSort?.(e),l(1)},[t]),_=t.readOnly===!0;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!_&&(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-2 border-b px-1 pb-2`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Sort`}),(0,Z.jsx)(wt,{workspaceId:t.workspaceId,value:f,onChange:g})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:(0,Z.jsx)(fn,{documents:i,isLoading:u,contextPath:t.path,treeName:t.treeName,workspaceId:t.workspaceId,totalCount:o,serverSort:f,viewMode:r,allowViewToggle:!0,currentPage:c,pageSize:n,onPageChange:l,backendSearchQueries:p,onBackendSearch:_?void 0:m,onRemoveBackendQuery:_?void 0:h})})]})}wd({type:`documents-table`,name:`Documents`,icon:Fn,defaultSize:{w:8,h:6,minW:4,minH:3},mobileHeight:.9,defaultConfig:{pageSize:50,viewMode:`table`},component:Od});function kd({config:e,setConfig:t,canvas:n}){let[r,i]=(0,X.useState)(()=>new Date),a=e.format!==`24`;return(0,X.useEffect)(()=>{let e=setInterval(()=>i(new Date),1e3);return()=>clearInterval(e)},[]),(0,Z.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-1`,children:[(0,Z.jsx)(`div`,{className:`text-3xl font-semibold tabular-nums`,children:r.toLocaleTimeString(void 0,{hour12:a,hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}),(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:r.toLocaleDateString(void 0,{weekday:`short`,month:`short`,day:`numeric`})}),!n.readOnly&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t({...e,format:a?`24`:`12`}),className:`mt-1 px-2 py-0.5 text-[10px] border rounded-md text-muted-foreground hover:bg-accent`,children:a?`12h`:`24h`})]})}wd({type:`clock`,name:`Clock`,icon:Zn,defaultSize:{w:3,h:2,minW:2,minH:2},defaultConfig:{format:`24`},component:kd});var Ad=450,jd=10;function Md(e,t){let{open:n}=I(),r=(0,X.useRef)(null),i=(0,X.useRef)(null),a=(0,X.useRef)(!1),o=()=>{e&&n(e,t)},s=()=>{r.current&&=(clearTimeout(r.current),null)};return{activationProps:{role:`button`,tabIndex:0,onClick:()=>{if(a.current){a.current=!1;return}o()},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())},onContextMenu:e=>{e.preventDefault(),o()},onPointerDown:e=>{e.pointerType===`touch`&&(i.current={x:e.clientX,y:e.clientY},a.current=!1,s(),r.current=setTimeout(()=>{a.current=!0,o()},Ad))},onPointerMove:e=>{i.current&&Math.hypot(e.clientX-i.current.x,e.clientY-i.current.y)>jd&&s()},onPointerUp:s,onPointerCancel:s,onPointerLeave:s},stopRowActivation:e=>e.stopPropagation()}}function Nd({doc:e,workspaceId:t}){let n=Ho(e),{activationProps:r}=Md(e,t);return(0,Z.jsxs)(`li`,{...r,title:`Open details`,className:`canvas-no-drag cursor-pointer py-1.5 min-w-0 rounded px-1 transition-colors hover:bg-accent/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,Z.jsx)(`div`,{className:`truncate font-medium`,children:n.title}),n.preview&&(0,Z.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:n.preview})]})}function Pd({config:e,canvas:t}){let n=typeof e.limit==`number`?e.limit:10,[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(!0),[s,c]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=!1;return(async()=>{o(!0);try{let r=await t.fetchDocuments({limit:n});if(e)return;i(r.payload||[]),c(null)}catch(t){if(e)return;c(t instanceof Error?t.message:`Failed to load documents`),i([])}finally{e||o(!1)}})(),()=>{e=!0}},[t,n]),a?(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground p-1`,children:`Loading…`}):s?(0,Z.jsx)(`div`,{className:`text-xs text-destructive p-1`,children:s}):r.length===0?(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground p-1`,children:`No documents on this canvas.`}):(0,Z.jsx)(`ul`,{className:`divide-y text-sm`,children:r.map(e=>(0,Z.jsx)(Nd,{doc:e,workspaceId:t.workspaceId},e.id))})}wd({type:`recent-documents`,name:`Recent documents`,icon:hi,defaultSize:{w:4,h:4,minW:3,minH:2},mobileHeight:.5,defaultConfig:{limit:10},component:Pd});function Fd({config:e,setConfig:t,canvas:n}){let r=typeof e.text==`string`?e.text:``;return(0,Z.jsx)(`textarea`,{value:r,readOnly:n.readOnly,onChange:n=>t({...e,text:n.target.value}),placeholder:n.readOnly?``:`Jot something down…`,className:`canvas-no-drag w-full h-full resize-none bg-transparent text-sm leading-6 outline-none`})}wd({type:`note`,name:`Note`,icon:Da,defaultSize:{w:3,h:3,minW:2,minH:2},defaultConfig:{text:``},component:Fd});var Id=`data/schema/file`,Ld=`data/schema/drawing`;function Rd(e){return(e.schema===Id||e.schema===Ld)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function zd(e){return e.schema===Id&&String(e.metadata?.contentType||``).startsWith(`video/`)}var Bd=`data/mime/image`;function Vd(e,t,n=!1){let[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(0),[s,c]=(0,X.useState)(1),[l,u]=(0,X.useState)(!0),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(``),{queries:h,runSearch:g,removeQuery:_,clearSearch:v}=Dd(e,()=>c(1)),y=e.canvasSort??xt;(0,X.useEffect)(()=>{let r=!1,a=async()=>{u(!0),f(null);try{let a=await e.fetchDocuments({limit:t,page:s,queries:h.length?h:void 0,sortBy:y.sortBy,order:y.order,...n?{anyOf:[Bd,`data/mime/video`]}:{allOf:[Bd]}});if(r)return;i((a.payload||[]).filter(e=>Rd(e)||n&&zd(e))),o(a.totalCount||a.count||0)}catch(e){if(r)return;i([]),o(0),f(e instanceof Error?e.message:`Failed to load images`)}finally{r||u(!1)}};return a(),window.addEventListener(`workspace:documents:refresh`,a),()=>{r=!0,window.removeEventListener(`workspace:documents:refresh`,a)}},[e,t,s,h,y.sortBy,y.order,n]);let b=(0,X.useCallback)(()=>{let e=p.trim();m(``),g(e)},[p,g]),x=(0,X.useCallback)(()=>{m(``),v()},[v]),S=(0,X.useCallback)(e=>{_(e)},[_]),C=(0,X.useCallback)(t=>{e.setCanvasSort?.(t),c(1)},[e]);return{images:r,isLoading:l,error:d,page:s,setPage:c,totalCount:a,totalPages:(0,X.useMemo)(()=>Math.max(1,Math.ceil(a/t)),[a,t]),input:p,setInput:m,submit:b,clearSearch:x,removeQuery:S,activeQueries:h,sort:y,setSort:C}}var Hd=n(h(),1);function Ud({workspaceId:e,doc:t,onClick:n,className:r=`aspect-square`,comments:i=`off`}){let{blobUrl:a,error:o,loading:s}=z(e,t.id,512,{blobFallback:!zd(t),version:t.checksumArray?.[0]??null}),c=ts(t)||`image-${t.id}`,l=ls(t),u=l!==``&&i!==`off`;return(0,Z.jsxs)(`button`,{type:`button`,onClick:n,title:l||c,className:`canvas-no-drag group relative block w-full overflow-hidden rounded-(--card-radius) border bg-muted/40 shadow-elevation-1 transition-shadow hover:shadow-elevation-2 hover:ring-2 hover:ring-primary/30 ${r}`,children:[s&&(0,Z.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),o&&!zd(t)&&(0,Z.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center p-1 text-[10px] text-destructive`,children:o}),a&&(0,Z.jsx)(`img`,{src:a,alt:c,loading:`lazy`,className:`h-full w-full object-cover transition-transform duration-normal group-hover:scale-105`}),zd(t)&&(0,Z.jsxs)(`span`,{className:`absolute inset-0 flex items-center justify-center`,children:[(0,Z.jsx)(Ar,{className:`h-10 w-10 rounded-full bg-black/60 p-2 text-white`}),(0,Z.jsx)(`span`,{className:`sr-only`,children:`Play video`})]}),u&&(0,Z.jsx)(`span`,{className:`pointer-events-none absolute inset-x-0 bottom-0 px-1.5 pb-1 pt-4 text-left text-[11px] leading-snug text-white bg-gradient-to-t from-black/75 via-black/45 to-transparent ${i===`reveal`?`caption-reveal`:``}`,children:(0,Z.jsx)(`span`,{className:`line-clamp-2`,children:l})}),l!==``&&i!==`caption`&&(0,Z.jsx)(`span`,{className:`pointer-events-none absolute right-1 top-1 rounded-full bg-black/55 p-1 text-white transition-opacity ${i===`reveal`?`hidden [@media(hover:hover)]:block [@media(hover:hover)]:group-hover:opacity-0`:``}`,title:`Has a comment`,children:(0,Z.jsx)(Rn,{className:`h-3 w-3`})})]})}function Wd({workspaceId:e,docs:t,index:n,onClose:r,onNavigate:i}){let a=t[n],{blobUrl:o,error:s,loading:c}=Xc(e,a.id,{version:a.checksumArray?.[0]??null,enabled:!zd(a)}),l=ts(a)||`image-${a.id}`,u=ls(a),[d,f]=(0,X.useState)(!1);return Ae(r),(0,X.useEffect)(()=>{let e=e=>{e.target?.closest(`video`)||(e.key===`ArrowLeft`&&n>0&&i(n-1),e.key===`ArrowRight`&&n<t.length-1&&i(n+1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n,t.length,i]),(0,Hd.createPortal)((0,Z.jsxs)(`div`,{"data-scheme":`dark`,className:`fixed inset-0 z-fullscreen flex flex-col bg-scrim p-0 sm:p-4`,onClick:r,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:r,className:`canvas-no-drag absolute right-2 top-2 z-10 rounded-full bg-foreground/10 p-2 text-foreground hover:bg-foreground/20 touch-target sm:right-4 sm:top-4`,title:`Close`,children:(0,Z.jsx)(vr,{className:`h-5 w-5`})}),n>0&&!d&&(0,Z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),i(n-1)},className:`canvas-no-drag absolute left-3 top-1/2 -translate-y-1/2 rounded-full bg-foreground/10 p-2 text-foreground hover:bg-foreground/20`,title:`Previous`,children:(0,Z.jsx)(Wn,{className:`h-6 w-6 touch-target`})}),n<t.length-1&&!d&&(0,Z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),i(n+1)},className:`canvas-no-drag absolute right-3 top-1/2 -translate-y-1/2 rounded-full bg-foreground/10 p-2 text-foreground hover:bg-foreground/20`,title:`Next`,children:(0,Z.jsx)(Xa,{className:`h-6 w-6 touch-target`})}),(0,Z.jsxs)(`figure`,{className:`flex min-h-0 flex-1 flex-col`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-1 items-center justify-center`,children:[c&&(0,Z.jsx)(`div`,{className:`text-sm text-foreground/70`,children:`Loading…`}),s&&(0,Z.jsx)(`div`,{className:`text-sm text-destructive`,children:s}),zd(a)&&(0,Z.jsx)(Kd,{workspaceId:e,doc:a},a.id),o&&(0,Z.jsx)(fe,{src:o,alt:l,onZoomChange:f,className:`max-h-full max-w-full rounded object-contain`})]}),(0,Z.jsxs)(`figcaption`,{className:`shrink-0 px-4 py-2 text-center text-xs text-foreground/70`,children:[u&&(0,Z.jsx)(`span`,{className:`mx-auto mb-1 block max-w-2xl whitespace-pre-wrap text-sm text-foreground`,children:u}),l,` · `,n+1,`/`,t.length,!d&&!zd(a)&&(0,Z.jsx)(`span`,{className:`ml-2 opacity-70`,children:`· double-tap to zoom`})]})]})]}),document.body)}function Gd({workspaceId:e,state:t,comments:n,onToggleComments:r}){let{input:i,setInput:a,submit:o,clearSearch:s,removeQuery:c,activeQueries:l,sort:u,setSort:d,page:f,setPage:p,totalPages:m,totalCount:h,isLoading:g}=t,_=l.length>0;return(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex flex-wrap items-center gap-x-2 gap-y-1.5 border-b px-1 pb-1.5`,children:[(0,Z.jsxs)(`div`,{className:`relative min-w-[9rem] flex-1 basis-full sm:basis-auto`,children:[(0,Z.jsx)(qa,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&o()},placeholder:_?`Refine: add another query (Enter)…`:`Search media (Enter)…`,className:`h-7 w-full rounded-md border bg-background pl-7 pr-7 text-xs`}),_&&(0,Z.jsx)(`button`,{type:`button`,onClick:s,title:`Clear search`,className:`absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-0.5 text-muted-foreground hover:text-foreground touch-target`,children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]}),_&&(0,Z.jsx)(`div`,{className:`flex w-full flex-wrap items-center gap-1 order-last`,children:l.map((e,t)=>(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[t>0&&(0,Z.jsx)(`span`,{className:`text-[10px] uppercase text-muted-foreground`,children:`then`}),(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-full border bg-accent/50 px-2 py-0.5 text-xs`,children:[(0,Z.jsx)(`span`,{className:`max-w-[10rem] truncate`,children:e}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>c(t),title:`Remove "${e}"`,className:`rounded p-0.5 text-muted-foreground hover:text-foreground touch-target`,children:(0,Z.jsx)(vr,{className:`h-3 w-3`})})]})]},`${e}-${t}`))}),(0,Z.jsxs)(`div`,{className:`flex flex-1 basis-full items-center justify-between gap-2 sm:basis-auto sm:justify-end`,children:[r&&(0,Z.jsx)(`button`,{type:`button`,onClick:r,"aria-pressed":n!==`off`,title:n===`off`?`Show comments on tiles`:`Hide comments on tiles`,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border touch-target ${n===`off`?`text-muted-foreground hover:bg-accent`:`border-primary/30 bg-primary/15 text-primary hover:bg-primary/25`}`,children:(0,Z.jsx)(Rn,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(wt,{workspaceId:e,value:u,onChange:d}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1`,children:[g&&(0,Z.jsx)(nn,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`shrink-0 whitespace-nowrap tabular-nums text-xs text-muted-foreground`,children:[h.toLocaleString(),(0,Z.jsxs)(`span`,{className:`hidden sm:inline`,children:[` item`,h===1?``:`s`]})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p(Math.max(1,f-1)),disabled:f<=1,title:`Previous page`,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent disabled:opacity-40 touch-target`,children:(0,Z.jsx)(Wn,{className:`h-3.5 w-3.5`})}),(0,Z.jsxs)(`span`,{className:`shrink-0 tabular-nums text-xs text-muted-foreground`,children:[f,`/`,m]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p(Math.min(m,f+1)),disabled:f>=m,title:`Next page`,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent disabled:opacity-40 touch-target`,children:(0,Z.jsx)(Xa,{className:`h-3.5 w-3.5`})})]})]})]})}function Kd({workspaceId:e,doc:t}){let{src:n,loading:r,error:i}=Jc(e,t.id);return(0,Z.jsxs)(Z.Fragment,{children:[r&&(0,Z.jsx)(`span`,{children:`Loading video…`}),i&&(0,Z.jsx)(`span`,{role:`alert`,children:i}),n&&(0,Z.jsx)(`video`,{src:n,controls:!0,playsInline:!0,preload:`metadata`,className:`max-h-full max-w-full`})]})}function qd({config:e,setConfig:t,canvas:n}){let r=Vd(n,typeof e.pageSize==`number`?e.pageSize:60,!0),i=tl()==null&&(n.interactive??!n.readOnly),[a,o]=(0,X.useState)(new Set),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(null),p=e=>o(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),[m,h]=(0,X.useState)(null),{images:g,isLoading:_,error:v,activeQueries:y}=r,b=e.showComments===!1?`off`:`caption`;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!n.readOnly&&(0,Z.jsx)(Gd,{workspaceId:n.workspaceId,state:r,comments:b,onToggleComments:()=>t({...e,showComments:b===`off`})}),i&&(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-2 py-1`,children:[(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,onClick:()=>{c(!s),o(new Set)},children:s?`Done selecting`:`Select`}),s&&(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,onClick:()=>o(new Set(g.map(e=>e.id))),children:`Select page`}),a.size>0&&(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,onClick:()=>u([...a]),children:[`Bulk Edit… (`,a.size,`)`]})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto p-1`,children:v?(0,Z.jsx)(`div`,{className:`p-4 text-sm text-destructive`,children:v}):g.length===0?(0,Z.jsx)(`div`,{className:`p-4 text-sm text-muted-foreground`,children:_?`Loading media…`:y.length?`No images or videos match your search.`:`No images or videos in this canvas' context.`}):(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(min(120px,100%),1fr))] gap-2 sm:grid-cols-[repeat(auto-fill,minmax(min(200px,100%),1fr))] sm:gap-3`,children:g.map((e,t)=>(0,Z.jsxs)(`div`,{className:`relative`,onContextMenu:t=>{i&&(t.preventDefault(),t.stopPropagation(),f({x:t.clientX,y:t.clientY,ids:a.has(e.id)?[...a]:[e.id]}))},children:[(0,Z.jsx)(Ud,{workspaceId:n.workspaceId,doc:e,onClick:()=>s?p(e.id):h(t),comments:b}),s&&(0,Z.jsx)(`input`,{type:`checkbox`,"aria-label":`Select document ${e.id}`,checked:a.has(e.id),onChange:()=>p(e.id),className:`canvas-no-drag absolute left-2 top-2 h-4 w-4 accent-primary`})]},e.id))})}),d&&(0,Z.jsx)(xn,{anchor:d,onClose:()=>f(null),label:`${d.ids.length} image${d.ids.length===1?``:`s`}`,items:[{id:`bulk-edit`,label:`Bulk edit… (${d.ids.length})`,icon:Lr,run:()=>u(d.ids)}]}),l&&(0,Z.jsx)(Ee,{workspaceId:n.workspaceId,documentIds:l,onClose:()=>u(null)}),m!=null&&g[m]&&(0,Z.jsx)(Wd,{workspaceId:n.workspaceId,docs:g,index:m,onClose:()=>h(null),onNavigate:h})]})}wd({type:`gallery`,name:`Gallery`,icon:Zi,defaultSize:{w:8,h:6,minW:3,minH:3},mobileHeight:.9,defaultConfig:{pageSize:60,showComments:!0},component:qd});var Jd=150;function Yd(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)&&t>0?t:0}function Xd(e){let t=e.metadata??{},n=e.data??{};return{w:Yd(t.width)||Yd(t.imageWidth)||Yd(n.width)||Yd(n.imageWidth),h:Yd(t.height)||Yd(t.imageHeight)||Yd(n.height)||Yd(n.imageHeight)}}function Zd(e,t){if(t%9==0)return{cols:2,rows:2};let{w:n,h:r}=Xd(e),i=n&&r?n/r:0;return i>=1.5?{cols:2,rows:1}:i>0&&i<=.66?{cols:1,rows:2}:!i&&t%7==3?{cols:2,rows:1}:{cols:1,rows:1}}function Qd({config:e,setConfig:t,canvas:n}){let r=Vd(n,typeof e.pageSize==`number`?e.pageSize:60),[i,a]=(0,X.useState)(null),{images:o,isLoading:s,error:c,activeQueries:l}=r,u=e.showComments===!1?`off`:`reveal`;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!n.readOnly&&(0,Z.jsx)(Gd,{workspaceId:n.workspaceId,state:r,comments:u,onToggleComments:()=>t({...e,showComments:u===`off`})}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto p-1`,children:c?(0,Z.jsx)(`div`,{className:`p-4 text-sm text-destructive`,children:c}):o.length===0?(0,Z.jsx)(`div`,{className:`p-4 text-sm text-muted-foreground`,children:s?`Loading images…`:l.length?`No images match your search.`:`No images in this canvas' context.`}):(0,Z.jsx)(`div`,{className:`grid gap-2`,style:{gridTemplateColumns:`repeat(auto-fill, minmax(${Jd}px, 1fr))`,gridAutoRows:`${Jd}px`,gridAutoFlow:`dense`},children:o.map((e,t)=>{let{cols:r,rows:i}=Zd(e,t);return(0,Z.jsx)(`div`,{style:{gridColumn:`span ${r}`,gridRow:`span ${i}`},children:(0,Z.jsx)(Ud,{workspaceId:n.workspaceId,doc:e,onClick:()=>a(t),className:`h-full`,comments:u})},e.id)})})}),i!=null&&o[i]&&(0,Z.jsx)(Wd,{workspaceId:n.workspaceId,docs:o,index:i,onClose:()=>a(null),onNavigate:a})]})}wd({type:`mosaic`,name:`Mosaic`,icon:Pa,defaultSize:{w:8,h:7,minW:4,minH:4},mobileHeight:.9,defaultConfig:{pageSize:60,showComments:!0},component:Qd});var $d=`data/schema/task`;function ef({doc:e,workspaceId:t,readOnly:n,onChanged:r}){let i=A(e),[a,o]=(0,X.useState)(!1),{replicating:s,label:c}=nc(e),l=i.status===`completed`,u=i.status??`pending`,d=Ne(i),{activationProps:f,stopRowActivation:p}=Md(e,t),m=async()=>{if(!(n||a)){o(!0);try{await N(t,e,l?`pending`:`completed`),r()}catch{}finally{o(!1)}}};return(0,Z.jsxs)(`div`,{...f,title:`Open details`,className:`canvas-no-drag flex cursor-pointer items-start gap-2.5 rounded-md border bg-card px-2.5 py-2 transition-colors hover:bg-accent/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring ${s?`opacity-60`:``}`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:e=>{p(e),m()},disabled:n||a||s,"aria-pressed":l,title:l?`Mark not done`:`Mark done`,className:`canvas-no-drag mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border transition-colors ${l?`border-success bg-success text-success-foreground`:`border-input hover:border-success`} ${n?`cursor-default opacity-70`:``}`,children:a?(0,Z.jsx)(Ti,{className:`h-2.5 w-2.5 animate-spin`}):l&&(0,Z.jsx)(sr,{className:`h-3 w-3`})}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm ${l?`text-muted-foreground line-through`:``}`,children:i.title||`Todo ${e.id}`}),(0,Z.jsxs)(`div`,{className:`mt-0.5 flex flex-wrap items-center gap-1.5 text-[11px]`,children:[(0,Z.jsx)(`span`,{className:`rounded-full px-1.5 py-0.5 ${D[u]}`,children:xe[u]}),i.dueDate&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 ${d?`font-medium text-destructive`:`text-muted-foreground`}`,children:[(0,Z.jsx)(_r,{className:`h-3 w-3`}),wn(i.dueDate)]}),typeof i.priority==`number`&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 text-muted-foreground`,children:[(0,Z.jsx)(Ai,{className:`h-3 w-3`}),`P`,i.priority]}),s&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-muted-foreground`,role:`status`,children:[(0,Z.jsx)(Ti,{className:`h-3 w-3 animate-spin`}),c]})]})]})]})}function tf({config:e,setConfig:t,canvas:n}){let r=typeof e.pageSize==`number`?e.pageSize:50,[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(!0),[c,l]=(0,X.useState)(0),u=n.interactive===!1,d=n.readOnly!==!0,[f,p]=(0,X.useState)(e.hideDone===!0),m=d?e.hideDone===!0:f,h=n=>{d?t({...e,hideDone:n}):p(n)};(0,X.useEffect)(()=>{let e=!1;return(async()=>{s(!0);try{let t=await n.fetchDocuments({limit:r,allOf:[$d],sortBy:`tasks`,order:`asc`});if(e)return;a((t.payload||[]).filter(e=>e.schema===Qo))}catch{e||a([])}finally{e||s(!1)}})(),()=>{e=!0}},[n,r,c]),(0,X.useEffect)(()=>{let e=()=>l(e=>e+1);return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[]);let g=(0,X.useCallback)(()=>l(e=>e+1),[]),_=m?i.filter(e=>A(e).status!==`completed`):i,v=i.filter(e=>{let t=A(e).status;return t!==`completed`&&t!==`cancelled`}).length;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center justify-between gap-2 border-b px-1 pb-2`,children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[v,` open`]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:m,onChange:e=>h(e.target.checked),className:`h-3 w-3`}),`Hide done`]})]}),(0,Z.jsx)(`div`,{className:`flex-1 space-y-1.5 overflow-y-auto p-1`,children:o&&i.length===0?(0,Z.jsx)(`div`,{className:`p-3 text-sm text-muted-foreground`,children:`Loading todos…`}):_.length===0?(0,Z.jsx)(`div`,{className:`p-3 text-sm text-muted-foreground`,children:`No todos in this canvas' context.`}):_.map(e=>(0,Z.jsx)(ef,{doc:e,workspaceId:n.workspaceId,readOnly:u,onChanged:g},e.id))})]})}wd({type:`todos`,name:`Todos`,icon:pa,defaultSize:{w:4,h:6,minW:3,minH:3},mobileHeight:.6,defaultConfig:{pageSize:50,hideDone:!1},component:tf});function nf(e){if(!e)return`/`;let t=e.replace(/\/+/g,`/`);return t.startsWith(`/`)?t:`/${t}`}var rf=`context`;function af(e){let t=e=>{try{return decodeURIComponent(e)}catch{return e}},n=e.split(`/`).filter(Boolean);if(n[0]!==`workspaces`)return{treeName:rf,path:`/`};if(n[2]===`trees`&&n[3]){let e=t(n[3]);if(n[4]!==`path`)return{treeName:e,path:`/`};let r=n.slice(5).map(t).join(`/`);return{treeName:e,path:r?`/${r}`:`/`}}if(n[2]===`path`){let e=n.slice(3).map(t).join(`/`);return{treeName:rf,path:e?`/${e}`:`/`}}return{treeName:rf,path:`/`}}function of(e,t,n){let r=n&&n!==rf?`/trees/${encodeURIComponent(n)}`:``,i=nf(t);return`/workspaces/${e}${r}${i===`/`?``:`/path/${i.split(`/`).filter(Boolean).map(encodeURIComponent).join(`/`)}`}`}function sf({canvas:e}){return tl()!=null||!pu()?(0,Z.jsx)(`p`,{className:`p-3 text-sm text-muted-foreground`,children:`Workspace pins are available in the signed-in workspace view.`}):(0,Z.jsx)(cf,{workspaceId:e.workspaceId},e.workspaceId)}function cf({workspaceId:e}){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(`Workspace`),[a,o]=(0,X.useState)(!0),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(0);return(0,X.useEffect)(()=>{let t=!1,r=0,a=async()=>{let a=++r;o(!0);try{let[o,s]=await Promise.all([Ws(e),rc(e)]);if(t||a!==r)return;i(o.label||o.name||`Workspace`),n(s),c(null)}catch{if(t||a!==r)return;n([]),c(`Workspace pins are unavailable. Check your workspace access or try again.`)}finally{!t&&a===r&&o(!1)}},s=()=>{document.visibilityState===`visible`&&a()};a(),window.addEventListener(`focus`,s),document.addEventListener(`visibilitychange`,s);let l=B.on(`pins.changed`,s),u=window.setInterval(s,6e4);return()=>{t=!0,window.removeEventListener(`focus`,s),document.removeEventListener(`visibilitychange`,s),l?.(),window.clearInterval(u)}},[e,l]),(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex h-full min-h-0 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-b px-2 pb-2`,children:[(0,Z.jsx)(`span`,{className:`truncate text-sm font-medium`,children:r}),(0,Z.jsx)(`button`,{type:`button`,title:`Refresh pins`,"aria-label":`Refresh pins`,disabled:a,onClick:()=>u(e=>e+1),className:`rounded p-1.5 text-muted-foreground hover:bg-accent disabled:opacity-40`,children:(0,Z.jsx)(Er,{className:`h-3.5 w-3.5 ${a?`animate-spin`:``}`})})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-1`,children:s?(0,Z.jsx)(`p`,{role:`alert`,className:`p-2 text-sm text-muted-foreground`,children:s}):t.length?(0,Z.jsx)(`ul`,{className:`space-y-2`,children:t.map(t=>{let n=t.resolvable===!1,r=Jt(t.color),i=(0,Z.jsxs)(Z.Fragment,{children:[n?(0,Z.jsx)(dr,{className:`h-5 w-5 shrink-0 text-warning`}):(0,Z.jsx)(f,{icon:t.icon||(t.type===`canvas`?`ph:squares-four-fill`:`ph:folder-fill`),width:22,height:22,color:r,className:`shrink-0`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`p`,{className:`truncate text-sm font-medium`,children:t.label||t.name||t.path}),(0,Z.jsxs)(`p`,{className:`truncate text-xs text-muted-foreground`,children:[t.tree,`:`,t.path]}),t.description&&(0,Z.jsx)(`p`,{className:`line-clamp-2 text-xs text-muted-foreground`,children:t.description}),n&&(0,Z.jsx)(`p`,{className:`text-xs text-warning`,children:`Folder no longer exists`})]})]}),a=`flex items-center gap-3 rounded-(--card-radius) border border-l-4 bg-card p-3`,o={borderLeftColor:r||`transparent`};return(0,Z.jsx)(`li`,{children:n?(0,Z.jsx)(`div`,{className:`${a} opacity-60`,style:o,children:i}):(0,Z.jsx)(we,{to:of(e,t.path,t.tree),title:`Open ${t.tree}:${t.path}`,className:`${a} transition-colors hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,style:o,children:i})},t.id)})}):(0,Z.jsx)(`p`,{className:`p-2 text-sm text-muted-foreground`,children:a?`Loading pins…`:`No workspace pins yet. Pin a folder from the workspace tree menu.`})})]})}wd({type:`workspace-pins`,name:`Workspace pins`,icon:tr,defaultSize:{w:4,h:6,minW:3,minH:2},mobileHeight:.6,defaultConfig:{},component:sf});function lf({title:e,icon:t,onRemove:n,fill:r,onToggleFill:i,readOnly:a=!1,stacked:o=!1,children:s}){let[c,l]=(0,X.useState)(!1),u=c?document.getElementById(`content-area`):null,d=(0,Z.jsxs)(`div`,{className:c?u?`absolute inset-0 z-40 flex flex-col bg-background`:`fixed inset-0 z-50 flex flex-col bg-background`:`flex flex-col h-full rounded-(--card-radius) border bg-background overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`canvas-drag-handle flex items-center gap-2 px-2 py-1 border-b bg-muted/30 select-none ${o?``:`cursor-move`}`,children:[t&&(0,Z.jsx)(t,{className:`w-3.5 h-3.5 text-muted-foreground shrink-0`}),(0,Z.jsx)(`span`,{className:`text-xs font-medium truncate flex-1`,children:e}),!a&&i&&!c&&!o&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(uf,{on:r?.w===!0,onClick:()=>i(`w`),label:`Fill width`,icon:ga}),(0,Z.jsx)(uf,{on:r?.h===!0,onClick:()=>i(`h`),label:`Fill height`,icon:hr})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>l(e=>!e),className:`canvas-no-drag shrink-0 p-0.5 rounded text-muted-foreground hover:text-foreground hover:bg-accent touch-target`,title:c?`Restore`:`Full screen`,children:c?(0,Z.jsx)(ei,{className:`w-3.5 h-3.5`}):(0,Z.jsx)(ba,{className:`w-3.5 h-3.5`})}),!a&&n&&(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`canvas-no-drag shrink-0 p-0.5 rounded text-muted-foreground hover:text-destructive hover:bg-destructive/10 touch-target`,title:`Remove widget`,children:(0,Z.jsx)(vr,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 min-h-0 overflow-auto p-2`,children:s})]});return c?(0,Hd.createPortal)(d,u??document.body):d}function uf({on:e,onClick:t,label:n,icon:r}){return(0,Z.jsx)(`button`,{type:`button`,onClick:t,"aria-pressed":e,title:e?`${n} (on)`:n,className:`canvas-no-drag shrink-0 p-0.5 rounded touch-target ${e?`bg-primary/15 text-primary hover:bg-primary/25`:`text-muted-foreground hover:text-foreground hover:bg-accent`}`,children:(0,Z.jsx)(r,{className:`w-3.5 h-3.5`})})}var df=(0,Sd.WidthProvider)(Sd.default),ff=12,pf=80,mf=40,hf=[12,12],gf=[8,8],_f={w:!1,h:!1};function vf(e){return Math.max(1,...e.map(e=>e.y+e.h).filter(Number.isFinite))}function yf(e){return Math.max(0,...e.map(e=>e.y+e.h).filter(Number.isFinite))}function bf(e){let t=(e,t)=>typeof e==`number`&&Number.isFinite(e)?e:t;return{...e,x:t(e.x,0),y:t(e.y,0),w:t(e.w,1),h:t(e.h,1)}}function xf(e,t,n=0){let r=n>0?n:vf(e);return e.map(e=>{let n=t[e.i]??_f;return!n.w&&!n.h?e:{...e,x:n.w?0:e.x,w:n.w?ff:e.w,y:n.h?0:e.y,h:n.h?Math.max(e.minH??1,r):e.h}})}var Sf=4;function Cf(e,t,n=hf[1]){return Math.max(1,Math.ceil((e-n-Sf)/(t+n)))}var wf=45,Tf=640;function Ef(e,t,n=0,r){let i=[...xf(e,t,n)].sort((e,t)=>e.y-t.y||e.x-t.x),a=0;return i.map(e=>{let t=r?.(e.i)??0,n=Math.max(e.h,e.minH??1,t),i={...e,x:0,w:ff,y:a,h:n};return a+=n,i})}var Df=e=>e&&e.trim()?[e]:[];function Of(e){let t=e?.ui??{},n=Array.isArray(t.layout)?t.layout.map(bf):[],r={};for(let e of n)r[e.i]={w:e.fillW??e.w>=ff,h:e.fillH===!0};return{layout:n,fills:r,widgets:t.widgets&&typeof t.widgets==`object`?t.widgets:{}}}function kf({workspaceId:e,treeName:t,path:n,layerId:r,querySpec:i,metadata:a,isLocked:o=!1,readOnly:s=!1,interactive:c=!0,fetchDocuments:l,onSaved:u}){let d=!s,f=(0,X.useMemo)(()=>Of(a),[a]),[p,m]=(0,X.useState)(f.layout),[h,g]=(0,X.useState)(f.widgets),[_,v]=(0,X.useState)(f.fills),y=(0,X.useRef)(f.fills),[b,x]=(0,X.useState)(!1),[S,C]=(0,X.useState)(!1),[w,T]=(0,X.useState)(!1),[E,D]=(0,X.useState)(null),[O,k]=(0,X.useState)(!1),[A,j]=(0,X.useState)(0),M=(0,X.useRef)(0),N=(0,X.useCallback)(e=>{y.current=e,v(e)},[]),[P,ee]=(0,X.useState)(()=>Cn(i?.sort)),F=(0,X.useRef)(!1),[I,te]=(0,X.useState)(()=>Df(i?.query)),L=(0,X.useRef)(!1),R=(0,X.useRef)(null),ne=(0,X.useRef)(f),re=(0,X.useCallback)(e=>{let t=Td(h[e]?.type??``)?.mobileHeight;if(!(!t||A<=0))return Math.max(1,Math.round(A*t))},[h,A]),ie=(0,X.useMemo)(()=>O?Ef(p,_,A,re):xf(p,_,A),[p,_,O,A,re]),ae=O?mf:pf,z=(0,X.useMemo)(()=>JSON.stringify(a?.ui??null),[a?.ui]);(0,X.useEffect)(()=>{let e=Of(a);m(e.layout),g(e.widgets),N(e.fills),ne.current=e,ee(Cn(i?.sort)),F.current=!1,te(Df(i?.query)),L.current=!1,C(!1)},[n,r]),(0,X.useEffect)(()=>{if(!s)return;let e=Of(a);m(e.layout),g(e.widgets),N(e.fills),ne.current=e},[s,z,a,N]),(0,X.useEffect)(()=>{let e=R.current;if(!e)return;let t=()=>{let t=e.clientHeight,n=e.clientWidth>0&&e.clientWidth<Tf;k(n),M.current=t,e.style.setProperty(`--canvas-host-h`,`${t}px`);let r=n?gf:hf;e.style.setProperty(`--canvas-grid-gutter`,`${r[1]}px`),t>0&&j(Cf(t,n?mf:pf,r[1]))};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[p]);let oe=(0,X.useCallback)(e=>{ee(e),F.current=!0,C(!0)},[]),se=(0,X.useCallback)(e=>{te(e),L.current=!0,C(!0)},[]),B=(0,X.useMemo)(()=>({workspaceId:e,treeName:t,path:n,layerId:r,querySpec:i,readOnly:!d,interactive:c,canvasSort:P,setCanvasSort:d?oe:void 0,canvasQueries:I,setCanvasQueries:d?se:void 0,fetchDocuments:l??(async r=>{let i;if(r?.anyOf?.length&&(i=((await Yo(e,n,t,{anyOf:r.anyOf,limit:0,applyCanvasSpec:!1})).payload||[]).map(e=>e.id),!i.length))return{payload:[],count:0,totalCount:0};let a=await Yo(e,n,t,{...r,anyOf:void 0,ids:i});return{payload:a.payload||[],count:a.count??void 0,totalCount:a.totalCount??void 0}})}),[e,t,n,r,i,d,c,l,P,oe,I,se]),ce=(0,X.useCallback)((e,t,n)=>{ne.current={layout:e,widgets:t,fills:n??y.current},C(!0)},[]),V=(0,X.useCallback)(async()=>{if(!(!d||w)){T(!0),D(null);try{let r={widgets:ne.current.widgets,layout:ne.current.layout.map(e=>({...e,fillW:y.current[e.i]?.w===!0,fillH:y.current[e.i]?.h===!0}))};ne.current={...r,fills:y.current};let o=F.current||L.current?{...i||{},...F.current?{sort:P.sortBy?P:null}:{},...L.current?{query:I.join(` `).trim()||null}:{}}:void 0;await zs(e,n,t,{...a||{},ui:r},o),F.current=!1,L.current=!1,C(!1),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:t}})),u?.()}catch(e){let t=e instanceof Error?e.message:`Save failed`;D(t),console.error(`Failed to save canvas layout:`,e)}finally{T(!1)}}},[d,w,e,n,t,a,u,i,P,I]),le=(0,X.useCallback)(e=>{!d||O||m(t=>{let n=e.map(e=>{let n=t.find(t=>t.i===e.i),r=y.current[e.i];return n?{...e,x:r?.w?n.x:e.x,w:r?.w?n.w:e.w,y:r?.h?n.y:e.y,h:r?.h?n.h:e.h}:e});return ce(n,h),n})},[d,O,ce,h]),ue=(0,X.useCallback)((e,t,n)=>{if(!d)return;let r=y.current[n.i]??_f,i=hf[1]+(n.y+n.h)*(pf+hf[1]),a={w:n.x+n.w>=ff,h:M.current>0&&i>=M.current-wf};if(a.w||=r.w&&n.w===t.w,a.h||=r.h&&n.h===t.h,a.w===r.w&&a.h===r.h)return;let o={...y.current,[n.i]:a};N(o),ce(ne.current.layout,h,o)},[d,N,ce,h]),de=(0,X.useCallback)((e,t)=>{if(!d)return;let n=y.current[e]??_f,r={...y.current,[e]:{...n,[t]:!n[t]}};N(r),ce(p,h,r)},[d,N,ce,p,h]),fe=(0,X.useCallback)(e=>{let t=Td(e);if(!t)return;let n=crypto.randomUUID(),{w:r,h:i,minW:a,minH:o,maxW:s,maxH:c}=t.defaultSize,l=[...p,{i:n,x:0,y:yf(ie),w:r,h:i,minW:a,minH:o,maxW:s,maxH:c}],u={...h,[n]:{type:e,config:{...t.defaultConfig||{}}}},d={...y.current,[n]:{w:r>=ff,h:!1}};m(l),g(u),N(d),x(!1),ce(l,u,d)},[p,ie,h,N,ce]),pe=(0,X.useCallback)(e=>{let t=p.filter(t=>t.i!==e),n={...h};delete n[e];let r={...y.current};delete r[e],m(t),g(n),N(r),ce(t,n,r)},[p,h,N,ce]),me=(0,X.useCallback)((e,t)=>{g(n=>{let r={...n,[e]:{...n[e],config:t}};return ce(p,r),r})},[p,ce]),he=Object.keys(h);return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full min-h-0`,children:[d&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-2 py-1.5 border-b shrink-0 sm:px-3`,children:[(0,Z.jsxs)(`div`,{className:`relative shrink-0`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>x(e=>!e),className:`flex items-center gap-1.5 whitespace-nowrap px-2.5 py-1 text-xs border rounded-md hover:bg-accent`,children:[(0,Z.jsx)(br,{className:`w-3.5 h-3.5`}),`Add`,(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:` widget`})]}),b&&(0,Z.jsx)(`div`,{className:`absolute left-0 top-full mt-1 z-20 w-48 rounded-md border bg-popover shadow-elevation-2 py-1`,children:Ed().map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>fe(e.type),className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs text-left hover:bg-accent`,children:[(0,Z.jsx)(e.icon,{className:`w-3.5 h-3.5 text-muted-foreground`}),e.name]},e.type))})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:V,disabled:!S||w,className:K(`flex shrink-0 items-center gap-1.5 whitespace-nowrap px-2.5 py-1 text-xs rounded-md transition-colors disabled:opacity-50`,S?`bg-primary text-primary-foreground hover:bg-primary`:`border hover:bg-accent`),children:[(0,Z.jsx)(Yn,{className:`w-3.5 h-3.5`}),w?`Saving…`:`Save`]}),(0,Z.jsxs)(`span`,{className:`min-w-0 truncate text-xs text-muted-foreground`,children:[he.length,` widget`,he.length===1?``:`s`,S?` · unsaved`:``,E?` · ${E}`:``]})]}),(0,Z.jsx)(`div`,{ref:R,className:`canvas-grid-host flex-1 min-h-0 bg-muted/10 overflow-y-auto overflow-x-hidden`,children:he.length===0?(0,Z.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(`p`,{children:`No widgets yet.`}),d&&(0,Z.jsx)(`p`,{className:`text-xs`,children:`Use “Add widget” to place one on the canvas.`})]}):(0,Z.jsx)(df,{className:`layout`,layout:ie,cols:ff,rowHeight:ae,margin:O?gf:hf,isDraggable:d&&!O,isResizable:d&&!O,resizeHandles:[`s`,`e`,`se`],draggableHandle:`.canvas-drag-handle`,draggableCancel:`.canvas-no-drag`,onLayoutChange:le,onResizeStop:ue,compactType:`vertical`,children:he.map(e=>{let t=h[e],n=Td(t.type),r=_[e]??_f,i=[r.w?`w`:``,r.h?`h`:``].filter(Boolean).join(` `);return(0,Z.jsx)(`div`,{"data-fill":i||void 0,children:n?(0,Z.jsx)(lf,{title:n.name,icon:n.icon,readOnly:!d,stacked:O,onRemove:()=>pe(e),fill:_[e]??_f,onToggleFill:d?t=>de(e,t):void 0,children:(0,Z.jsx)(n.component,{config:t.config??{...n.defaultConfig||{}},setConfig:t=>me(e,t),canvas:B})}):(0,Z.jsx)(lf,{title:`Unknown: ${t.type}`,readOnly:!d,stacked:O,onRemove:()=>pe(e),children:(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`This widget type is not available.`})})},e)})})})]})}var Af=`data/schema/file`;function jf(e){return String(e.locations?.[0]?.url||``).trim()}function Mf(e){let t=jf(e);if(!t)return``;let n=t.split(/[?#]/)[0].split(`/`).filter(Boolean).pop()||``;try{return decodeURIComponent(n)}catch{return n}}function Nf(e){return e.schema===Af&&String(e.metadata?.contentType||``).startsWith(`image/`)}function Pf(e){let t=Number(e);return!Number.isFinite(t)||t<0?``:t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}function Ff(e){if(e.schema!==Af)return Ho(e);let t=Mf(e),n=String(e.metadata?.contentType||``).trim(),r=Pf(e.metadata?.size);return{...Ho(e),title:t||`File ${e.id}`,preview:[n,r].filter(Boolean).join(` · `),subtitle:jf(e),schemaLabel:`file`}}function If(e){return/^https?:\/\/[^\s]+$/i.test(e)}function Lf(e,t){if(e.schema===`data/schema/tab`){let t=String(e.data?.url||``).trim();return If(t)?t:null}return t.isExternal&&If(t.subtitle)?t.subtitle:If(t.title)?t.title:null}function Rf(e,t,n=!1){return Wc(e,t,{download:n})}function zf(e){return e.split(/(https?:\/\/[^\s]+)/gi).map((e,t)=>If(e)?(0,Z.jsx)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,className:`underline decoration-muted-foreground underline-offset-2 hover:text-primary`,children:e},`${e}-${t}`):e)}function Bf(e){return e?new Date(e).toLocaleString():``}function Vf(){let{code:e=``}=yt(),[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!0),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(``),d=(0,X.useMemo)(()=>t?.documents?Array.isArray(t.documents)?t.documents:t.documents.data||[]:[],[t]),f=(0,X.useMemo)(()=>{let e=l.trim().toLowerCase();return e?d.filter(t=>{let n=Ff(t);return[t.schema,n.title,n.preview,n.subtitle,Mf(t),t.metadata?.contentType].join(` `).toLowerCase().includes(e)}):d},[d,l]),p=(0,X.useCallback)(async()=>{if(e){i(!0);try{let t=await J.get(`${yo}/pub/c/${encodeURIComponent(e)}`,{skipAuth:!0});n(t),o(null)}catch(e){n(null),o(e instanceof Error?e.message:`Failed to load public canvas`)}finally{i(!1)}}},[e]);(0,X.useEffect)(()=>{p()},[p]),(0,X.useEffect)(()=>{if(!e)return;let t=xo(`${bo}/pub`,{transports:[`websocket`],auth:{code:e},reconnection:!0,reconnectionAttempts:10,reconnectionDelay:1500});return t.on(`connect`,()=>c(!0)),t.on(`disconnect`,()=>c(!1)),t.on(`connect_error`,()=>c(!1)),t.on(`canvas:changed`,()=>p()),()=>{t?.disconnect(),t=null}},[e,p]);let m=(0,X.useCallback)(e=>{e?.preventDefault(),u(l.trim())},[l]),h=(0,X.useCallback)(()=>{u(``)},[]),g=(0,X.useCallback)(async e=>({payload:rs(e?.sortBy)?is(d,e.sortBy,e?.order):d,totalCount:t?.stats.documentCount??d.length}),[d,t]);if(r&&!t)return(0,Z.jsx)(`main`,{className:`min-h-screen bg-muted flex items-center justify-center p-6`,children:(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Loading canvas...`})});if(a||!t)return(0,Z.jsxs)(`main`,{className:`min-h-screen bg-muted flex flex-col items-center justify-center p-6`,children:[(0,Z.jsxs)(zl,{className:`max-w-md bg-card`,children:[(0,Z.jsx)(Bl,{children:(0,Z.jsx)(Vl,{children:`Canvas unavailable`})}),(0,Z.jsx)(Ul,{className:`text-sm text-muted-foreground`,children:a||`This public canvas does not exist.`})]}),(0,Z.jsx)(au,{className:`mt-6 text-center`})]});let _=t.canvas.metadata?.ui??{},v=!!_.widgets&&Object.keys(_.widgets).length>0;return(0,Z.jsx)(qc.Provider,{value:e,children:(0,Z.jsx)(`main`,{className:`min-h-screen bg-muted p-2 text-foreground sm:p-4 md:p-10`,children:(0,Z.jsxs)(`div`,{className:`mx-auto max-w-6xl`,children:[(0,Z.jsxs)(zl,{className:`bg-card shadow-elevation-3`,children:[(0,Z.jsx)(Bl,{className:`border-b p-3 sm:p-6`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 md:flex-row md:items-start md:justify-between md:gap-4`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 gap-3 sm:gap-4`,children:[(0,Z.jsx)(`div`,{className:`mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-accent text-primary sm:mt-1 sm:h-12 sm:w-12 sm:rounded-2xl`,style:t.canvas.color?{borderLeft:`4px solid ${t.canvas.color}`}:void 0,children:(0,Z.jsx)(Pa,{className:`h-5 w-5 sm:h-6 sm:w-6`})}),(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`truncate text-xs uppercase tracking-wide text-muted-foreground`,children:t.workspace.label||t.workspace.name}),(0,Z.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] text-muted-foreground md:hidden`,children:[s?(0,Z.jsx)(Ja,{className:`h-3 w-3 text-success`}):(0,Z.jsx)(Hn,{className:`h-3 w-3 text-muted-foreground`}),s?`Live`:`Offline`]})]}),(0,Z.jsx)(Vl,{className:`mt-0.5 truncate text-2xl sm:mt-1 sm:text-3xl md:text-5xl`,children:t.canvas.label||t.canvas.name||`Canvas`}),t.canvas.description&&(0,Z.jsx)(`p`,{className:`mt-1.5 max-w-3xl text-sm text-muted-foreground sm:mt-3 sm:text-base`,children:t.canvas.description})]})]}),(0,Z.jsxs)(`div`,{className:`hidden shrink-0 items-center gap-2 rounded-full border px-3 py-1 text-xs text-muted-foreground md:flex`,children:[s?(0,Z.jsx)(Ja,{className:`h-3.5 w-3.5 text-success`}):(0,Z.jsx)(Hn,{className:`h-3.5 w-3.5 text-muted-foreground`}),s?`Live`:`Offline`]})]})}),(0,Z.jsxs)(Ul,{className:`space-y-4 p-3 sm:space-y-6 sm:p-6 md:p-8`,children:[(0,Z.jsxs)(`section`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1 text-xs text-muted-foreground md:hidden`,children:[(0,Z.jsx)(`span`,{className:`w-full truncate font-mono text-foreground`,children:t.share.path}),(0,Z.jsxs)(`span`,{className:`tabular-nums`,children:[t.stats.documentCount,` docs`]}),f.length!==t.stats.documentCount&&(0,Z.jsxs)(`span`,{className:`tabular-nums`,children:[`· `,f.length,` shown`]}),(0,Z.jsxs)(`span`,{className:`truncate`,children:[`· `,Bf(t.stats.refreshedAt)]})]}),(0,Z.jsxs)(`section`,{className:`hidden gap-3 md:grid md:grid-cols-4`,children:[(0,Z.jsx)(Hf,{label:`Path`,value:t.share.path,mono:!0}),(0,Z.jsx)(Hf,{label:`Documents`,value:String(t.stats.documentCount)}),(0,Z.jsx)(Hf,{label:`Shown`,value:String(f.length)}),(0,Z.jsx)(Hf,{label:`Refreshed`,value:Bf(t.stats.refreshedAt)})]}),v&&(0,Z.jsx)(`section`,{id:`content-area`,className:`flex w-full flex-col overflow-hidden rounded-2xl border h-viewport-card min-h-[420px] md:h-viewport-pane`,children:(0,Z.jsx)(kf,{workspaceId:t.workspace.name,treeName:t.share.treeName,path:t.share.path,layerId:t.canvas.id,querySpec:t.canvas.querySpec,metadata:t.canvas.metadata,readOnly:!0,interactive:!1,fetchDocuments:g},JSON.stringify(_))}),!v&&(0,Z.jsxs)(`section`,{className:`rounded-2xl border`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 border-b px-4 py-3 md:flex-row md:items-center md:justify-between`,children:[(0,Z.jsx)(`h2`,{className:`font-semibold`,children:`Content`}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 md:flex-row md:items-center`,children:[(0,Z.jsxs)(`form`,{onSubmit:m,className:`flex min-w-0 items-center gap-2`,children:[(0,Z.jsxs)(`div`,{className:`relative min-w-0`,children:[(0,Z.jsx)(qa,{className:`pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{type:`search`,value:l,onChange:e=>u(e.target.value),placeholder:`Search loaded documents...`,className:`w-full rounded-md border py-1.5 pl-9 pr-8 text-sm md:w-72`}),l&&(0,Z.jsx)(`button`,{type:`button`,onClick:h,className:`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,"aria-label":`Clear search`,children:(0,Z.jsx)(vr,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`button`,{type:`submit`,className:`rounded-md border px-3 py-1.5 text-xs hover:bg-muted`,children:`Search`})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:p,className:`inline-flex items-center justify-center gap-2 rounded-md border px-3 py-1.5 text-xs hover:bg-muted`,children:[(0,Z.jsx)(Er,{className:`h-3.5 w-3.5 ${r?`animate-spin`:``}`}),`Refresh`]})]})]}),l.trim()&&(0,Z.jsxs)(`div`,{className:`border-b bg-muted px-4 py-2 text-xs text-muted-foreground`,children:[`Local search: `,(0,Z.jsxs)(`span`,{className:`font-mono`,children:[`"`,l.trim(),`"`]})]}),(0,Z.jsx)(`div`,{className:`divide-y`,children:f.length===0?(0,Z.jsx)(`div`,{className:`p-8 text-center text-sm text-muted-foreground`,children:l.trim()?`No loaded documents match your search.`:`No documents yet.`}):f.map(t=>{let n=Ff(t),r=Lf(t,n),i=t.schema===Af,a=i?Rf(e,t.id):null,o=a||r;return(0,Z.jsxs)(`article`,{className:`p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1 md:flex-row md:items-start md:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`h3`,{className:`truncate font-medium`,children:o?(0,Z.jsx)(`a`,{href:o,target:`_blank`,rel:`noreferrer`,className:`hover:text-primary hover:underline`,children:n.title}):n.title}),(0,Z.jsx)(`div`,{className:`mt-1 font-mono text-xs text-muted-foreground`,children:n.schemaLabel})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-3`,children:[i&&(0,Z.jsxs)(`a`,{href:Rf(e,t.id,!0),download:n.title,className:`inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs text-muted-foreground hover:bg-muted hover:text-foreground`,children:[(0,Z.jsx)(zi,{className:`h-3.5 w-3.5`}),`Download`]}),(0,Z.jsx)(`time`,{className:`text-xs text-muted-foreground`,children:Bf(t.updatedAt||t.createdAt)})]})]}),n.preview&&(0,Z.jsx)(`p`,{className:`mt-3 line-clamp-3 text-sm leading-6 text-foreground`,children:zf(n.preview)}),Nf(t)&&(0,Z.jsx)(`a`,{href:a||void 0,target:`_blank`,rel:`noreferrer`,className:`mt-3 block w-fit`,children:(0,Z.jsx)(`img`,{src:a||void 0,alt:n.title,loading:`lazy`,className:`max-h-64 max-w-full rounded border bg-muted object-contain transition-opacity hover:opacity-90`})})]},t.id)})})]})]})]}),(0,Z.jsx)(au,{className:`mt-6 text-center`})]})})})}function Hf({label:e,value:t,mono:n=!1}){return(0,Z.jsxs)(`div`,{className:`min-w-0 rounded-xl border bg-muted p-4`,children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:e}),(0,Z.jsx)(`div`,{className:`mt-2 truncate text-lg font-semibold ${n?`font-mono text-sm`:``}`,children:t||`-`})]})}var Uf=`false`,Wf=`false`,Gf=Uf===`true`,Kf=Wf===`true`;function qf(e={}){let{immediate:t=!1,onNeedReload:n,onNeedRefresh:r,onOfflineReady:i,onRegistered:a,onRegisteredSW:o,onRegisterError:s}=e,c,l,u,d=async(e=!0)=>{await l,Gf||u?.()};async function f(){if(`serviceWorker`in navigator){if(c=await g(async()=>{let{Workbox:e}=await import(`./workbox-window.prod.es5-Bd17z0YL.js`);return{Workbox:e}},[]).then(({Workbox:e})=>new e(`/sw.js`,{scope:`/`,type:`classic`})).catch(e=>{s?.(e)}),!c)return;if(u=()=>{c?.messageSkipWaiting()},!Kf){if(Gf)c.addEventListener(`activated`,e=>{(e.isUpdate||e.isExternal)&&(n?n():window.location.reload())}),c.addEventListener(`installed`,e=>{e.isUpdate||i?.()});else{let e=!1,t=()=>{e=!0,c?.addEventListener(`controlling`,e=>{e.isUpdate&&(n?n():window.location.reload())}),r?.()};c.addEventListener(`installed`,n=>{n.isUpdate===void 0?n.isExternal===void 0?!e&&i?.():n.isExternal?t():!e&&i?.():n.isUpdate||i?.()}),c.addEventListener(`waiting`,t)}}c.register({immediate:t}).then(e=>{o?o(`/sw.js`,e):a?.(e)}).catch(e=>{s?.(e)})}}return l=f(),d}var Jf=new Set,Yf=!1,Xf=qf({immediate:!0,onRegisteredSW(e,t){t&&setInterval(()=>{t.update()},36e5)},onNeedRefresh(){Yf=!0,Jf.forEach(e=>e())}});function Zf(e){return Jf.add(e),Yf&&e(),()=>{Jf.delete(e)}}function Qf(){Xf(!0)}function $f(){let[e,t]=(0,X.useState)(!1),[n,r]=(0,X.useState)(!1);return(0,X.useEffect)(()=>Zf(()=>t(!0)),[]),!e||n?null:(0,Z.jsx)(`div`,{className:`fixed bottom-4 left-1/2 z-50 -translate-x-1/2`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 rounded-full border border-border bg-card px-4 py-2 shadow-elevation-2`,children:[(0,Z.jsx)(`span`,{className:`text-sm`,children:`A new version of Canvas is ready`}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>Qf(),className:`flex items-center gap-1 rounded-full bg-foreground px-3 py-1 text-xs font-medium text-background hover:bg-foreground/90`,children:[(0,Z.jsx)(Er,{className:`h-3 w-3`}),` Reload`]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(!0),"aria-label":`Not now`,className:`rounded-full p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]})})}var ep=Object.defineProperty,tp=Object.getOwnPropertyDescriptor,np=(e,t)=>{for(var n in t)ep(e,n,{get:t[n],enumerable:!0})},rp=(e,t,n,r)=>{for(var i=r>1?void 0:r?tp(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(r?o(t,n,i):o(i))||i);return r&&i&&ep(t,n,i),i},ip=(e,t)=>(n,r)=>t(n,r,e),ap=`Terminal input`,op={get:()=>ap,set:e=>ap=e},sp=`Too much output to announce, navigate to rows manually to read`,cp={get:()=>sp,set:e=>sp=e};function lp(e){return e.replace(/\r?\n/g,`\r`)}function up(e,t){return t?`\x1B[200~`+e+`\x1B[201~`:e}function dp(e,t){e.clipboardData&&e.clipboardData.setData(`text/plain`,t.selectionText),e.preventDefault()}function fp(e,t,n,r){e.stopPropagation(),e.clipboardData&&pp(e.clipboardData.getData(`text/plain`),t,n,r)}function pp(e,t,n,r){e=lp(e),e=up(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=``}function mp(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,a=e.clientY-r.top-10;t.style.width=`20px`,t.style.height=`20px`,t.style.left=`${i}px`,t.style.top=`${a}px`,t.style.zIndex=`1000`,t.focus()}function hp(e,t,n,r,i){mp(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function gp(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function _p(e,t=0,n=e.length){let r=``;for(let i=t;i<n;++i){let t=e[i];t>65535?(t-=65536,r+=String.fromCharCode((t>>10)+55296)+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r}var vp=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=(this._interim-55296)*1024+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a<n;++a){let i=e.charCodeAt(a);if(55296<=i&&i<=56319){if(++a>=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=(i-55296)*1024+o-56320+65536:(t[r++]=i,t[r++]=o);continue}i!==65279&&(t[r++]=i)}return r}},yp=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i,a,o,s,c=0,l=0;if(this.interim[0]){let i=!1,a=this.interim[0];a&=(a&224)==192?31:(a&240)==224?15:7;let o=0,s;for(;(s=this.interim[++o]&63)&&o<4;)a<<=6,a|=s;let c=(this.interim[0]&224)==192?2:(this.interim[0]&240)==224?3:4,u=c-o;for(;l<u;){if(l>=n)return 0;if(s=e[l++],(s&192)!=128){l--,i=!0;break}this.interim[o++]=s,a<<=6,a|=s&63}i||(c===2?a<128?l--:t[r++]=a:c===3?a<2048||a>=55296&&a<=57343||a===65279||(t[r++]=a):a<65536||a>1114111||(t[r++]=a)),this.interim.fill(0)}let u=n-4,d=l;for(;d<n;){for(;d<u&&!((i=e[d])&128)&&!((a=e[d+1])&128)&&!((o=e[d+2])&128)&&!((s=e[d+3])&128);)t[r++]=i,t[r++]=a,t[r++]=o,t[r++]=s,d+=4;if(i=e[d++],i<128)t[r++]=i;else if((i&224)==192){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(c=(i&31)<<6|a&63,c<128){d--;continue}t[r++]=c}else if((i&240)==224){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(c=(i&15)<<12|(a&63)<<6|o&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((i&248)==240){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,this.interim[2]=o,r;if(s=e[d++],(s&192)!=128){d--;continue}if(c=(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},bp=``,xp=` `,Sp=class e{constructor(){this.fg=0,this.bg=0,this.extended=new Cp}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)==50331648}isBgRGB(){return(this.bg&50331648)==50331648}isFgPalette(){return(this.fg&50331648)==16777216||(this.fg&50331648)==33554432}isBgPalette(){return(this.bg&50331648)==16777216||(this.bg&50331648)==33554432}isFgDefault(){return!(this.fg&50331648)}isBgDefault(){return!(this.bg&50331648)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==16777216||(this.extended.underlineColor&50331648)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?!(this.extended.underlineColor&50331648):this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Cp=class e{constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},wp=class e extends Sp{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Cp,this.combinedData=``}static fromCharData(t){let n=new e;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?gp(this.content&2097151):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(e[1].length===2){let n=e[1].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(n-55296)*1024+r-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Tp=`di$target`,Ep=`di$dependencies`,Dp=new Map;function Op(e){return e[Ep]||[]}function kp(e){if(Dp.has(e))return Dp.get(e);let t=function(e,n,r){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);Ap(t,e,r)};return t._id=e,Dp.set(e,t),t}function Ap(e,t,n){t[Tp]===t?t[Ep].push({id:e,index:n}):(t[Ep]=[{id:e,index:n}],t[Tp]=t)}var jp=kp(`BufferService`),Mp=kp(`CoreMouseService`),Np=kp(`CoreService`),Pp=kp(`CharsetService`),Fp=kp(`InstantiationService`),Ip=kp(`LogService`),Lp=kp(`OptionsService`),Rp=kp(`OscLinkService`),zp=kp(`UnicodeService`),Bp=kp(`DecorationService`),Vp=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],i=this._optionsService.rawOptions.linkHandler,a=new wp,o=n.getTrimmedLength(),s=-1,c=-1,l=!1;for(let t=0;t<o;t++)if(!(c===-1&&!n.hasContent(t))){if(n.loadCell(t,a),a.hasExtendedAttrs()&&a.extended.urlId){if(c===-1){c=t,s=a.extended.urlId;continue}l=a.extended.urlId!==s}else c!==-1&&(l=!0);if(l||c!==-1&&t===o-1){let n=this._oscLinkService.getLinkData(s)?.uri;if(n){let a={start:{x:c+1,y:e},end:{x:t+ +(!l&&t===o-1),y:e}},s=!1;if(!i?.allowNonHttpProtocols)try{let e=new URL(n);[`http:`,`https:`].includes(e.protocol)||(s=!0)}catch{s=!0}s||r.push({text:n,range:a,activate:(e,t)=>i?i.activate(e,t,a):Hp(e,t),hover:(e,t)=>i?.hover?.(e,t,a),leave:(e,t)=>i?.leave?.(e,t,a)})}l=!1,a.hasExtendedAttrs()&&a.extended.urlId?(c=t,s=a.extended.urlId):(c=-1,s=-1)}}t(r)}};Vp=rp([ip(0,jp),ip(1,Lp),ip(2,Rp)],Vp);function Hp(e,t){if(confirm(`Do you want to navigate to ${t}?
|
|
5
5
|
|
|
@@ -25,18 +25,20 @@ WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){t
|
|
|
25
25
|
`)r=`image/png`;else if([`GIF87a`,`GIF89a`].includes(n(0,6)))r=`image/gif`;else if(n(0,4)===`RIFF`&&n(8,4)===`WEBP`)r=`image/webp`;else if(n(0,5)===`%PDF-`)r=`application/pdf`;else if(n(0,4)===`PK`)r=`application/zip`;else if(n(4,4)===`ftyp`){let e=[n(8,4)],i=new DataView(t.buffer).getUint32(0);for(let r=16;r+4<=Math.min(t.length,i);r+=4)e.push(n(r,4));e.some(e=>[`avif`,`avis`].includes(e))?r=`image/avif`:e.some(e=>[`heic`,`heix`,`hevc`,`hevx`].includes(e))?r=`image/heic`:e.some(e=>[`mif1`,`msf1`].includes(e))?r=`image/heif`:e.includes(`qt `)?r=`video/quicktime`:e.some(e=>[`isom`,`iso2`,`mp41`,`mp42`,`avc1`,`M4V `].includes(e))&&(r=`video/mp4`)}let i=e.type.toLowerCase().split(`;`)[0].trim(),a=!i||[`application/octet-stream`,`binary/octet-stream`,`*/*`].includes(i),o=e.name.split(`.`).pop()?.toLowerCase()??``,s=r||a&&zE[o]||i;return s===e.type?e:new File([e],e.name,{type:s,lastModified:e.lastModified})}));return{kind:t.length>0&&t.every(BE)?`photo`:`file`,files:t}}function HE({file:e}){let t=(0,X.useRef)(null),[n,r]=(0,X.useState)(!1);return(0,X.useEffect)(()=>{let n=t.current;if(!n)return;let r=URL.createObjectURL(e);return n.src=r,()=>{n.removeAttribute(`src`),URL.revokeObjectURL(r)}},[e]),(0,Z.jsx)(`div`,{className:`flex min-h-24 items-center justify-center overflow-hidden rounded-md border border-input bg-muted/30`,children:n?(0,Z.jsxs)(`p`,{className:`p-4 text-center text-sm text-muted-foreground`,children:[`Preview unavailable for `,e.name,`. You can still save the original.`]}):e.type.startsWith(`video/`)?(0,Z.jsx)(`video`,{ref:t,controls:!0,preload:`metadata`,"aria-label":e.name,onError:()=>r(!0),className:`max-h-64 max-w-full`}):(0,Z.jsx)(`img`,{ref:t,alt:e.name,onError:()=>r(!0),className:`max-h-64 max-w-full object-contain`})})}function UE({onClose:e,initialData:t}){let n=(0,X.useRef)(null),r=_T(t?.files),i=r.items.map(e=>e.file),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(!1),{state:l}=ol(),u=lT(l.activeWorkspaceName),d=e=>{e&&(s||r.addFiles(Array.from(e)))},f=e=>{e.preventDefault(),o(!1),d(e.dataTransfer.files)},p=i.length>0;return(0,Z.jsx)(Xe,{title:`Upload File`,icon:Yr,onClose:e,onSave:async e=>{c(!0);try{let t={mode:`workspace`,...e},n=await u.geotag.capture(),i=await r.start(t,(e,t)=>uT(e,t,{tags:u.tags,comment:u.comment,geo:n}));if(i.failed)throw Error(`${i.failed} file(s) failed or cancelled. Retry keeps completed uploads.`);return i.docIds}finally{c(!1)}},navigateAfterSave:!0,canSave:p,saving:s,saveProgress:(0,Z.jsx)(CT,{items:r.items,running:r.running,onCancel:r.cancel}),successMessage:`File(s) uploaded`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{onDragOver:e=>{e.preventDefault(),o(!0)},onDragLeave:()=>o(!1),onDrop:f,onClick:()=>n.current?.click(),className:K(`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-md border border-dashed px-4 py-8 text-center transition-colors`,a?`border-primary bg-primary/5`:`border-input hover:bg-muted/40`),children:[(0,Z.jsx)(Yr,{className:`h-6 w-6 text-muted-foreground touch-target`}),(0,Z.jsx)(`p`,{className:`text-sm`,children:`Drag & drop files here`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`or click to browse`}),(0,Z.jsx)(`input`,{ref:n,type:`file`,multiple:!0,disabled:s,className:`hidden`,onChange:e=>{d(e.target.files),e.target.value=``}})]}),r.items.filter(e=>BE(e.file)).map(e=>(0,Z.jsx)(HE,{file:e.file},e.id)),(0,Z.jsx)(ST,{items:r.items,running:s,onRemove:r.removeItem}),(0,Z.jsx)(mT,{fields:u,idPrefix:`qa-file`,multiple:i.length>1})]})})}function WE({onClose:e,initialData:t}){let n=_T(t?.files),r=(0,X.useRef)(null),i=n.items.length>0,[a,o]=(0,X.useState)(!1),{state:s}=ol(),c=lT(s.activeWorkspaceName),l=e=>{!a&&e&&n.addFiles([e])};return(0,Z.jsx)(Xe,{title:`Photo/Video`,icon:Ur,onClose:e,onSave:async e=>{if(!i)return[];o(!0);try{let t=await c.geotag.capture(),r={mode:`workspace`,...e},i=await n.start(r,(e,n)=>uT(e,n,{tags:c.tags,comment:c.comment,geo:t}));if(i.failed)throw Error(`Upload failed or cancelled. You can retry.`);return i.docIds}finally{o(!1)}},navigateAfterSave:!0,canSave:i,saving:a,saveProgress:(0,Z.jsx)(CT,{items:n.items,running:n.running,onCancel:n.cancel}),successMessage:`Upload saved`,children:(0,Z.jsxs)(`div`,{className:K(`flex h-full flex-col gap-4 p-4`,!i&&`items-center justify-center`),children:[i?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`flex min-h-0 w-full flex-1 flex-col gap-3 overflow-y-auto`,children:n.items.map(({id:e,file:t,status:r})=>(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(HE,{file:t}),(0,Z.jsxs)(`div`,{className:`flex w-full items-center gap-2 rounded border border-input px-3 py-2 text-sm`,children:[(0,Z.jsx)(xa,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`flex-1 truncate`,children:t.name}),(0,Z.jsxs)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:[(t.size/1024/1024).toFixed(1),` MB`]}),(0,Z.jsx)(`button`,{type:`button`,disabled:a||r===`done`,onClick:()=>n.removeItem(e),"aria-label":`Remove ${t.name}`,className:`text-muted-foreground hover:text-foreground disabled:opacity-40`,children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]})]},e))}),(0,Z.jsx)(`div`,{className:`w-full shrink-0 space-y-4`,children:(0,Z.jsx)(mT,{fields:c,idPrefix:`qa-photo`,multiple:n.items.length>1})})]}):(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>r.current?.click(),className:`flex flex-col items-center gap-2 rounded-md border border-dashed border-input px-6 py-10 text-center transition-colors hover:bg-muted/40`,children:[(0,Z.jsx)(Ur,{className:`h-8 w-8 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-sm`,children:`Open camera`})]}),(0,Z.jsx)(`input`,{ref:r,type:`file`,accept:`image/*,video/*`,capture:`environment`,className:`hidden`,disabled:a,onChange:e=>{l(e.target.files?.[0]??null),e.target.value=``}})]})})}var GE=`shrink-0 h-viewport-card w-[min(380px,90vw)] max-md:fixed max-md:inset-2 max-md:z-40 max-md:h-auto max-md:w-auto max-md:shadow-elevation-5`;function KE({onClose:e}){let{showSuccessToast:t,showErrorToast:n}=Oo(),[r,i]=(0,X.useState)(null),[a,o]=(0,X.useState)(!1);return r?(0,Z.jsx)(y,{sizeClassName:GE,documentCount:r.length,saving:a,onClose:e,onConfirm:async(i,a)=>{o(!0);try{await Promise.all(i.map(e=>Ko(a.workspaceName,e,r,a.treeName,a.treeType))),t(`${r.length} document${r.length===1?``:`s`} linked`),e()}catch(e){n(e instanceof Error?e.message:`Failed to link documents`)}finally{o(!1)}}}):(0,Z.jsx)(ae,{sizeClassName:GE,onConfirm:e=>{e.length&&i(e)},onClose:e})}function qE(){let e=el(`new:home-card:`);try{return Object.keys(localStorage).filter(t=>t.startsWith(e)&&t.endsWith(`:home`)).filter(e=>{let t=JSON.parse(localStorage.getItem(e)||`null`)?.value;return t&&(t.title||t.content||t.comment||t.tags?.length)}).map(t=>t.slice(e.length,-5))}catch{return[]}}var JE=0;function YE(){return JE+=1,`card-${JE}`}function XE({initialKind:e,initialData:t,onInitialCardClose:n,onCardsOpenChange:r}){let[i,a]=(0,X.useState)(!1),o=De(),s=ul(),c=!!(s?.state.t1Open||s?.state.addOpen),[l,u]=(0,X.useState)(()=>e?[{id:`initial`,kind:e,initialData:t,noteDraftId:crypto.randomUUID()}]:qE().map(e=>({id:e,kind:`note`,noteDraftId:e}))),d=l.length>0,f=(0,X.useRef)(r);(0,X.useEffect)(()=>{f.current=r},[r]),(0,X.useEffect)(()=>{f.current?.(d)},[d]),c&&i&&a(!1);let p=ft(),m=e=>{if(e===`sketch`){a(!1),p(DE.createUrl(null));return}let t=e===`note`?qE().find(e=>!l.some(t=>t.noteDraftId===e))||crypto.randomUUID():void 0;u(n=>[...n,{id:YE(),kind:e,noteDraftId:t}]),a(!1)},h=e=>{u(t=>t.filter(t=>t.id!==e)),e===`initial`&&n?.()},g=(0,Z.jsxs)(`div`,{className:K(`pointer-events-none fixed right-6 z-40 flex flex-col items-end gap-2`,`bottom-fab-inset md:bottom-[calc(var(--spacing-fab-inset)+5rem)]`,l.length>0&&`max-md:hidden`,c&&`hidden`),children:[(0,Z.jsx)(`div`,{className:K(`flex flex-col items-end gap-2 transition-all duration-fast`,i?`pointer-events-auto opacity-100`:`pointer-events-none translate-y-2 opacity-0`),children:(0,Z.jsx)(AE,{variant:`stack`,omit:[`plaintext`,`folder`,`message`],onSelect:m})}),(0,Z.jsx)(`div`,{className:`pointer-events-none flex w-16 justify-center`,children:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>a(e=>!e),"aria-label":i?`Close quick add`:`Quick add`,className:`pointer-events-auto flex h-11 w-11 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-elevation-3 transition-transform hover:scale-105`,children:i?(0,Z.jsx)(vr,{className:`h-5 w-5`}):(0,Z.jsx)(br,{className:`h-5 w-5`})})})]});return(0,Z.jsxs)(`div`,{className:`relative flex h-full w-full flex-col`,children:[l.length>0&&(0,Z.jsx)(`div`,{className:`pointer-events-auto flex flex-1 items-center gap-4 overflow-x-auto p-6 md:pr-28`,children:l.map(e=>{let t=()=>h(e.id);switch(e.kind){case`note`:return(0,Z.jsx)(jE,{draftId:e.noteDraftId,onClose:t,initialData:e.initialData},e.id);case`link`:return(0,Z.jsx)(IE,{onClose:t,initialData:e.initialData},e.id);case`todo`:return(0,Z.jsx)(LE,{onClose:t,initialData:e.initialData},e.id);case`identity`:return(0,Z.jsx)(RE,{onClose:t,initialData:e.initialData},e.id);case`file`:return(0,Z.jsx)(UE,{onClose:t,initialData:e.initialData},e.id);case`photo`:return(0,Z.jsx)(WE,{onClose:t,initialData:e.initialData},e.id);case`existing`:return(0,Z.jsx)(KE,{onClose:t},e.id);case`sketch`:return null;case`folder`:case`message`:return null}})}),o?(0,Hd.createPortal)(g,document.body):g]})}function ZE(e){let t=`${e.workspaceName}\0${e.treeName}\0${e.path}`,[n,r]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let n=!1;return ac(e.workspaceName,e.treeName).then(i=>{n||r({key:t,node:xs(i,e.path)})}).catch(()=>{n||r({key:t,node:null})}),()=>{n=!0}},[t,e.workspaceName,e.treeName,e.path]),!n||n.key!==t?{state:`loading`}:n.node?{state:`ready`,node:n.node}:{state:`missing`}}function QE(e){let t=`/workspaces/${encodeURIComponent(e.workspaceName)}`,n=e.path.replace(/^\//,``);return e.treeName===`context`?`${t}/path/${n}`:`${t}/trees/${encodeURIComponent(e.treeName)}/path/${n}`}var $E=`application/x-canvas-pin`;function eD({pin:e,onUnpin:t,onMinimize:n,onDropPin:r}){let i=ZE(e),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),l=!!r&&!a,u=e=>{let t=e.currentTarget.getBoundingClientRect();return e.clientX>t.left+t.width/2?`after`:`before`},d=l?{onDragOver:e=>{e.dataTransfer.types.includes(`application/x-canvas-pin`)&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`,c(u(e)))},onDragLeave:()=>c(null),onDrop:t=>{let n=t.dataTransfer.getData($E);c(null),!(!n||n===e.id)&&(t.preventDefault(),r?.(n,u(t)===`after`))}}:{},f=i.state===`ready`?i.node:null,p=f?.label||e.label||e.path.split(`/`).filter(Boolean).pop()||`Canvas`,m=f?.color;return(0,X.useEffect)(()=>{if(!a)return;let e=e=>{e.key===`Escape`&&o(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[a]),(0,Z.jsxs)(`section`,{...d,className:a?`fixed inset-0 z-picker flex flex-col bg-background`:`flex flex-col rounded-(--card-radius) border bg-background overflow-hidden min-h-0 min-w-0 ${s?`ring-2 ring-primary/60`:``}`,children:[(0,Z.jsxs)(`header`,{draggable:l,onDragStart:l?t=>{t.dataTransfer.setData($E,e.id),t.dataTransfer.effectAllowed=`move`}:void 0,className:`flex items-center gap-2 px-3 py-2 border-b bg-muted/20 shrink-0 min-w-0 ${l?`cursor-grab active:cursor-grabbing`:``}`,children:[l&&(0,Z.jsx)(Un,{className:`w-3.5 h-3.5 shrink-0 text-muted-foreground/60`,"aria-hidden":!0}),m&&(0,Z.jsx)(`div`,{className:`w-1 h-5 rounded-full shrink-0`,style:{backgroundColor:m}}),(0,Z.jsx)(Pa,{className:`w-4 h-4 shrink-0 text-primary`}),(0,Z.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-semibold leading-tight truncate`,children:p}),(0,Z.jsxs)(`span`,{className:`text-[11px] text-muted-foreground truncate leading-tight font-mono`,children:[e.workspaceName,`://`,e.path.replace(/^\//,``)]})]}),n&&(0,Z.jsx)(`button`,{type:`button`,onClick:n,title:`Minimize to tab bar`,"aria-label":`Minimize to tab bar`,className:`shrink-0 flex items-center justify-center w-7 h-7 rounded-md text-muted-foreground hover:bg-accent hover:text-foreground transition-colors`,children:(0,Z.jsx)(ii,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>o(e=>!e),"aria-pressed":a,title:a?`Restore tile (Esc)`:`Fill view area`,"aria-label":a?`Restore tile`:`Fill view area`,className:`shrink-0 flex items-center justify-center w-7 h-7 rounded-md text-muted-foreground hover:bg-accent hover:text-foreground transition-colors`,children:a?(0,Z.jsx)(ei,{className:`w-3.5 h-3.5`}):(0,Z.jsx)(ba,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(we,{to:QE(e),title:`Open in workspace`,"aria-label":`Open in workspace`,className:`shrink-0 flex items-center justify-center w-7 h-7 rounded-md text-muted-foreground hover:bg-accent hover:text-foreground transition-colors`,children:(0,Z.jsx)(Pi,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:t,title:`Unpin from home`,"aria-label":`Unpin from home`,className:`shrink-0 flex items-center justify-center w-7 h-7 rounded-md text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors`,children:(0,Z.jsx)(ur,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsxs)(`div`,{className:`flex-1 min-h-0`,children:[i.state===`loading`&&(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full text-xs text-muted-foreground`,children:`Loading…`}),i.state===`missing`&&(0,Z.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-2 px-4 text-center`,children:[(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`This canvas is no longer available.`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`It may have been renamed, moved or deleted.`}),(0,Z.jsx)(`button`,{type:`button`,onClick:t,className:`mt-1 px-2.5 py-1 text-xs border rounded-md hover:bg-accent`,children:`Remove pin`})]}),i.state===`ready`&&(0,Z.jsx)(kf,{workspaceId:e.workspaceName,treeName:e.treeName,path:e.path,layerId:i.node.id,querySpec:i.node.querySpec,metadata:i.node.metadata,readOnly:!0})]})]})}function tD(e,t,n){let r=Promise.resolve();return i=>{let a=r.then(async()=>{let r=await e(),a=i(r.home?.pinnedCanvases??[]);n(await t({...r,home:{...r.home,pinnedCanvases:a}}))});return r=a.catch(()=>{}),a}}function nD(e,t){return e.minimized===!0||t.has(e.id)}function rD(e){return e.label||e.path.split(`/`).filter(Boolean).pop()||`Canvas`}function iD({pins:e,onRestore:t}){let[n,r]=(0,X.useState)(!1),[i,a]=(0,X.useState)(e.length);return i!==e.length&&(a(e.length),e.length===0&&r(!1)),e.length===0?null:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`pointer-events-none absolute bottom-0 left-0 right-0 z-40 max-md:hidden`,children:(0,Z.jsx)(`div`,{className:`pointer-events-auto flex items-end gap-1 overflow-x-auto px-3 pr-28 pb-safe-bottom`,children:e.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>t(e.id),title:`Restore ${rD(e)}`,className:`flex max-w-[180px] shrink-0 items-center gap-1.5 rounded-t-lg border border-b-0 bg-background px-3 py-1.5 text-xs shadow-elevation-1 hover:bg-accent`,children:[(0,Z.jsx)(Pa,{className:`h-3.5 w-3.5 shrink-0 text-primary`}),(0,Z.jsx)(`span`,{className:`truncate`,children:rD(e)})]},e.id))})}),n&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-drawer md:hidden`,onClick:()=>r(!1),"aria-hidden":!0}),(0,Z.jsx)(`div`,{className:`fixed bottom-rail-stack left-2 z-rail w-60 max-w-[calc(100vw-1rem)] rounded-xl border bg-card p-1.5 shadow-elevation-5 animate-fade-in md:hidden touch-target`,children:e.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>t(e.id),className:`flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-sm hover:bg-accent`,children:[(0,Z.jsx)(Pa,{className:`h-4 w-4 shrink-0 text-primary`}),(0,Z.jsx)(`span`,{className:`truncate`,children:rD(e)})]},e.id))})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>r(e=>!e),"aria-label":n?`Close minimized canvases`:`Minimized canvases (${e.length})`,className:`fixed bottom-rail-inset left-16 z-nav flex h-12 w-12 items-center justify-center rounded-full bg-foreground text-background shadow-elevation-4 md:hidden`,children:[(0,Z.jsx)(Pa,{className:`h-5 w-5`}),(0,Z.jsx)(`span`,{className:`absolute -top-1 -right-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-semibold`,children:e.length})]})]})}function aD(){let{pins:e,unpin:t,movePin:n,setMinimized:r,isLoading:i}=ZT(),{showErrorToast:a}=Oo(),[o,s]=(0,X.useState)(new Set),c=(0,X.useRef)(e);(0,X.useEffect)(()=>{c.current=e},[e]);let l=e=>{r(e,!0).catch(()=>a(`Could not save minimized state`))},u=t=>{s(e=>{let n=new Set(e);return n.delete(t),n}),e.find(e=>e.id===t)?.minimized&&r(t,!1).catch(()=>a(`Could not save restored state`))},d=(0,X.useCallback)(e=>{s(e?new Set(c.current.filter(e=>!e.minimized).map(e=>e.id)):new Set)},[]),f=e.filter(e=>!nD(e,o)),p=e.filter(e=>nD(e,o)),m=(t,r,i)=>{let a=e.findIndex(e=>e.id===r.id);if(a===-1)return;let o=i?e[a+1]?.id??null:r.id;n(t,o)};return(0,Z.jsxs)(`div`,{className:`relative h-full`,children:[(0,Z.jsx)(`div`,{className:`h-full overflow-y-auto`,children:i?(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full text-xs text-muted-foreground`,children:`Loading…`}):(0,Z.jsx)(`div`,{className:`grid gap-4 p-4 h-full grid-cols-[repeat(auto-fit,minmax(min(640px,100%),1fr))] auto-rows-fr ${p.length>0?`md:pb-12`:``}`,children:f.map(e=>(0,Z.jsx)(eD,{pin:e,onUnpin:()=>{t(e.id)},onMinimize:()=>l(e.id),onDropPin:(t,n)=>m(t,e,n)},e.id))})}),(0,Z.jsx)(`div`,{className:`pointer-events-none absolute inset-0`,children:(0,Z.jsx)(XE,{onCardsOpenChange:d})}),(0,Z.jsx)(iD,{pins:p,onRestore:u})]})}function oD(){return(0,Z.jsx)(`div`,{className:`h-full w-full`,"aria-hidden":!0})}var sD=`share-target-inbox`,cD={"too-large":`Android shares are limited to 100 MiB in total for temporary device storage. Nothing was uploaded. Use Add File to upload larger files directly.`,"stash-failed":`Canvas couldn't hold on to the shared file — device storage may be full. Try again, or upload it from the app.`,"empty-share":`Canvas received no files or text from the sharing app. Try again, or use Add File to select the photo directly.`,"empty-file":`The sharing app delivered an empty file. Try again, or use Add File to select the original directly.`,expired:`Nothing shared, or the share expired.`};async function lD(e){let t=await caches.open(sD),n=null,r=Date.now()+3e5;for(;Date.now()<r;){let r=await t.match(`/share-target-inbox/${e}/meta`);if(!r)return null;if(n=await r.json(),n?.status===`error`)throw Error(n.error||`stash-failed`);if(n?.status!==`receiving`)break;await new Promise(e=>setTimeout(e,300))}if(!n||n.status===`receiving`)throw Error(`stash-failed`);let i=[];for(let r=0;r<n.fileNames.length;r++){let a=await t.match(`/share-target-inbox/${e}/file-${r}`);if(!a)throw Error(`stash-failed`);let o=await a.blob();i.push(new File([o],n.fileNames[r],{type:o.type}))}let a=i.length?await VE(i):null;if(await Promise.all(n.fileNames.map((n,r)=>t.delete(`/share-target-inbox/${e}/file-${r}`))),await t.delete(`/share-target-inbox/${e}/meta`),a)return{kind:a.kind,data:{files:a.files}};if(![n.title,n.text,n.url].some(e=>e.trim()))throw Error(`empty-share`);let o=n.text.trim(),s=n.url||(fD(o)?o:``);return s?{kind:`link`,data:{url:s,title:n.title}}:{kind:`note`,data:{title:n.title,content:n.text}}}var uD=new Map;function dD(e){let t=uD.get(e);return t||(t=lD(e),uD.set(e,t),t.finally(()=>setTimeout(()=>uD.delete(e),6e4)).catch(()=>{})),t}function fD(e){if(!e||/\s/.test(e))return!1;try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`}catch{return!1}}function pD(){let[e]=$t(),t=ft(),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(null);(0,X.useEffect)(()=>{let t=!1;async function n(){let n=e.get(`error`);if(n){a(n);return}let i=e.get(`token`),o=i?await dD(i):null;t||(o?r(o):a(`expired`))}return n().catch(e=>{t||a(e instanceof Error?e.message:`stash-failed`)}),()=>{t=!0}},[e]);let o=()=>t(`/home`,{replace:!0});return i?(0,Z.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 px-6 text-center`,children:[(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:cD[i]??cD.expired}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(`/apps/add/file`,{replace:!0}),className:`text-sm font-medium text-primary underline underline-offset-4`,children:`Add File`}),(0,Z.jsx)(`button`,{type:`button`,onClick:o,className:`text-sm font-medium text-primary underline underline-offset-4`,children:`Go to Canvas`})]}):n?(0,Z.jsx)(XE,{initialKind:n.kind,initialData:n.data,onInitialCardClose:o}):(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center text-sm text-muted-foreground`,children:`Receiving shared content on this device… No upload has started.`})}function mD(e,t=`An error occurred`){if(e instanceof Error)return e.message;if(typeof e==`object`&&e){let n=e;return n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||t}return t}function hD(e,t,n=`An error occurred`){return console.error(t,e),mD(e,n)}function gD(){let e=ft(),[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(!0),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(``),[p,m]=(0,X.useState)(`context`),[h,g]=(0,X.useState)(`/`),[_,v]=(0,X.useState)(``),[y,x]=(0,X.useState)(null),[S,w]=(0,X.useState)(`/`),[T,E]=(0,X.useState)(``),[D,O]=(0,X.useState)(!1),[k,A]=hw(),[j,M]=(0,X.useState)(null),[N,P]=(0,X.useState)(null),{showToast:F}=wo();(0,X.useEffect)(()=>{B.isConnected()||(console.log(`Socket not connected, attempting to connect...`),B.reconnect())},[]);let I=(0,X.useCallback)(async()=>{try{o(!0);let[e,t]=await Promise.all([ml(),Uo()]),r=e?.filter(e=>e&&typeof e==`object`&&e.id&&e.userId)||[];n(r);let a=t||[];if(i(a),a.length>0){let e=a.some(e=>e.id===T);(!T||!e)&&E(a[0].id)}else E(``);c(null)}catch(e){console.error(`Data fetch error:`,e),n([]),i([]);let t=`Failed to fetch data`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to fetch data`}c(t),F({title:`Error`,description:t,variant:`destructive`})}finally{o(!1)}},[T,F]);(0,X.useEffect)(()=>{I()},[I]),(0,X.useEffect)(()=>{let e=()=>B.emit(`subscribe`,{channel:`context`}),t=()=>B.emit(`unsubscribe`,{channel:`context`}),r=B.on(`connect`,e);console.log(`Subscribing to context events`),e();let i=e=>{let t=e;if(console.log(`Received context created:`,t),!t||!t.id||!t.userId){console.error(`Invalid context data received in context:created event:`,t);return}n(e=>e.some(e=>e&&e.id===t.id&&e.userId===t.userId)?(console.log(`Context ${t.id} already exists, skipping duplicate add`),e):[...e,t])},a=e=>{let t=e;if(console.log(`Received context update:`,t),!t||!t.id||!t.userId){console.error(`Invalid context data received in context:updated event:`,t);return}n(e=>e.map(e=>e&&e.id===t.id&&e.userId===t.userId?{...e,...t}:e))},o=e=>{let t=e;console.log(`Received context deletion:`,t);let r=t?.contextId??t?.id;if(!r){console.error(`Invalid context deletion data received:`,t);return}n(e=>e.filter(e=>e&&e.id!==r))},s=e=>{let t=e;if(console.log(`Received context URL change:`,t),!t||!t.id||!t.userId){console.error(`Invalid context data received in context:url:changed event:`,t);return}n(e=>e.map(e=>e&&e.id===t.id&&e.userId===t.userId?{...e,...t}:e))},c=[[`context:created`,i],[`context.created`,i],[`context:updated`,a],[`context.updated`,a],[`context:deleted`,o],[`context.deleted`,o],[`context:url:changed`,s],[`context.url.set`,s],[`context:url:set`,s]];return c.forEach(([e,t])=>B.on(e,t)),()=>{console.log(`Unsubscribing from context events`),t(),r?.(),c.forEach(([e,t])=>B.off(e,t))}},[]);let te=async t=>{if(t.preventDefault(),!h.trim()||!T||!l.trim()){F({title:`Missing Fields`,description:`Context ID, Context URL and Workspace are required.`,variant:`destructive`});return}O(!0);try{let t={id:l,name:d.trim()||void 0,url:h,description:_.trim()||void 0,metadata:{ui:{color:y}},workspaceId:T,baseUrl:S||void 0,treeType:p},n=await kl(t);u(``),f(``),g(`/`),v(``),x(null),w(`/`),await I(),F({title:`Success`,description:`Context created successfully`}),A(!1),window.dispatchEvent(new CustomEvent(`contexts:refresh`)),e(`/contexts/${n.id}`)}catch(e){let t=hD(e,`Context creation error:`,`Failed to create context`);F({title:`Error`,description:t,variant:`destructive`})}finally{O(!1)}},L=async e=>{let n=t.find(t=>t.id===e);if(n&&n.url&&(n.url.endsWith(`/default`)||n.url.includes(`://default`))){F({title:`Error`,description:`Cannot delete the default context`,variant:`destructive`});return}P(e)},R=async()=>{if(N)try{await gl(N),n(e=>e.filter(e=>!il(e,{id:N}))),F({title:`Success`,description:`Context deleted successfully`})}catch(e){console.error(`Context deletion error:`,e);let t=`Failed to delete context`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to delete context`}F({title:`Error`,description:t,variant:`destructive`})}finally{P(null)}},ne=t=>{let n=t.isShared||t.type===`shared`;e(n?`/contexts/${t.id}?ownerId=${encodeURIComponent(t.userId)}`:`/contexts/${t.id}`)},re=e=>{M(e)},ie=async e=>{if(e.preventDefault(),j)try{n(e=>e.map(e=>e.id===j.id&&e.userId===j.userId?j:e)),F({title:`Success`,description:`Context updated successfully (mock update)`}),M(null)}catch(e){let t=e instanceof Error?e.message:`Failed to update context`;F({title:`Error`,description:t,variant:`destructive`})}},ae=(0,X.useMemo)(()=>({type:e=>e.isShared||e.type===`shared`?`shared`:`owned`,id:e=>e.id??``,owner:e=>e.isShared||e.type===`shared`?e.ownerEmail||e.userId||``:`you`,url:e=>e.url??``,workspaceId:e=>e.workspaceId??``,baseUrl:e=>e.baseUrl??``,path:e=>e.path??``,locked:e=>+!!e.locked,created:e=>Date.parse(e.createdAt)||0,updated:e=>Date.parse(e.updatedAt)||0}),[]),{sorted:z,sort:oe,toggleSort:se}=be(t.filter(e=>e!=null),ae);return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{title:`Contexts`,description:`Create and manage contexts in your workspaces. View contexts shared with you.`,actions:!k&&(0,Z.jsxs)(Y,{onClick:()=>A(!0),className:`max-sm:h-9 max-sm:w-9 max-sm:p-0`,"aria-label":`Create context`,title:`Create context`,children:[(0,Z.jsx)(br,{className:`h-4 w-4 sm:mr-2`}),(0,Z.jsx)(`span`,{className:`max-sm:hidden`,children:`Create Context`})]})}),k&&(0,Z.jsx)(pw,{title:`Create New Context`,onClose:()=>A(!1),children:(0,Z.jsxs)(`form`,{onSubmit:te,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`workspace`,className:`block text-sm font-medium mb-1`,children:`Workspace`}),(0,Z.jsxs)(`select`,{id:`workspace`,className:`w-full px-3 py-2 border border-border rounded-md shadow-elevation-1 focus:outline-none focus:ring-primary focus:border-primary`,value:T,onChange:e=>E(e.target.value),disabled:D||r.length===0,children:[r.length===0&&(0,Z.jsx)(`option`,{value:``,children:`No workspaces available. Create one first.`}),r.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.label||e.name},`${e.owner}-${e.id}`))]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`newContextId`,className:`block text-sm font-medium mb-1`,children:`Context ID`}),(0,Z.jsx)(q,{id:`newContextId`,value:l,onChange:e=>u(e.target.value),placeholder:`e.g., my-new-context`,disabled:D})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`url`,className:`block text-sm font-medium mb-1`,children:`Context URL`}),(0,Z.jsx)(C,{id:`url`,value:h,onChange:g,placeholder:`e.g., /project/path/resource`,disabled:D,pickerTitle:`Context URL path…`,onPickTarget:(e,t)=>{g(e),m(t.treeType);let n=r.find(e=>e.name===t.workspaceName||e.id===t.workspaceName);n&&E(n.id)}})]}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`baseUrl`,className:`block text-sm font-medium mb-1`,children:`Base URL (Optional)`}),(0,Z.jsx)(C,{id:`baseUrl`,value:S,onChange:w,format:`path`,placeholder:`e.g., /base/path`,disabled:D,pickerTitle:`Base path…`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`description`,className:`block text-sm font-medium mb-1`,children:`Description (Optional)`}),(0,Z.jsx)(q,{id:`description`,value:_,onChange:e=>v(e.target.value),placeholder:`Description`,disabled:D})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`contextColor`,className:`block text-sm font-medium mb-1`,children:`Color (Optional)`}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(q,{id:`contextColor`,type:`color`,value:y||`#808080`,onChange:e=>x(e.target.value),className:`h-10 w-16 p-1`,disabled:D}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:D||y===null,onClick:()=>x(null),children:`Use inherited color`})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:y===null?`Uses the tree folder or workspace color.`:`Applies only to this context.`})]}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`contextName`,className:`block text-sm font-medium mb-1`,children:`Name (Optional)`}),(0,Z.jsx)(q,{id:`contextName`,value:d,onChange:e=>f(e.target.value),placeholder:`My Context`,disabled:D})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`treeType`,className:`block text-sm font-medium mb-1`,children:`Tree`}),(0,Z.jsxs)(`select`,{id:`treeType`,className:`w-full px-3 py-2 border border-border rounded-md shadow-elevation-1 focus:outline-none focus:ring-primary focus:border-primary`,value:p,onChange:e=>m(e.target.value),disabled:D,children:[(0,Z.jsx)(`option`,{value:`context`,children:`Context tree`}),(0,Z.jsx)(`option`,{value:`directory`,children:`Directory tree`})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Which workspace tree this context navigates.`})]})]}),(0,Z.jsxs)(Y,{type:`submit`,disabled:D||!h.trim()||!T||!l.trim(),children:[(0,Z.jsx)(br,{className:`mr-2 h-4 w-4`}),`Create Context`]})]})}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your Contexts & Shared Contexts`}),a&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading contexts...`}),s&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:s})}),!a&&!s&&t.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No contexts found. Create one above.`}),t.length>0&&(0,Z.jsx)(`div`,{className:`border rounded-lg overflow-hidden`,children:(0,Z.jsxs)(b,{children:[(0,Z.jsx)(Se,{children:(0,Z.jsxs)(ee,{children:[(0,Z.jsx)(Pt,{label:`Type`,sortKey:`type`,sort:oe,onSort:se}),(0,Z.jsx)(Pt,{label:`ID`,sortKey:`id`,sort:oe,onSort:se}),(0,Z.jsx)(Pt,{label:`Owner`,sortKey:`owner`,sort:oe,onSort:se}),(0,Z.jsx)(Pt,{label:`Context URL`,sortKey:`url`,sort:oe,onSort:se}),(0,Z.jsx)(Pt,{label:`Workspace ID`,sortKey:`workspaceId`,sort:oe,onSort:se}),(0,Z.jsx)(Pt,{label:`Base URL`,sortKey:`baseUrl`,sort:oe,onSort:se}),(0,Z.jsx)(Pt,{label:`Path`,sortKey:`path`,sort:oe,onSort:se}),(0,Z.jsx)(Pt,{label:`Locked`,sortKey:`locked`,sort:oe,onSort:se}),(0,Z.jsx)(Pt,{label:`Created`,sortKey:`created`,sort:oe,onSort:se}),(0,Z.jsx)(Pt,{label:`Updated`,sortKey:`updated`,sort:oe,onSort:se}),(0,Z.jsx)(_e,{className:`text-right`,children:`Actions`})]})}),(0,Z.jsx)(jt,{children:z.map(e=>{if(!e)return console.warn(`Found null/undefined context in contexts array, skipping`),null;let t=e.createdAt?new Date(e.createdAt).toLocaleDateString():`-`,n=e.updatedAt?new Date(e.updatedAt).toLocaleDateString():`-`,r=e.isShared||e.type===`shared`,i=r?e.ownerEmail||e.userId||`-`:`You`,a=r&&e.sharedVia?typeof e.sharedVia==`string`?e.sharedVia:e.sharedVia.accessLevel||`-`:`-`;return(0,Z.jsxs)(ee,{children:[(0,Z.jsx)(me,{children:r?(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 text-info`,title:`Shared with you (${a})`,children:[(0,Z.jsx)(aa,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{className:`text-xs`,children:`Shared`})]}):(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Owned`})}),(0,Z.jsx)(me,{className:`font-mono text-sm`,children:e.id||`-`}),(0,Z.jsx)(me,{className:`font-mono text-sm`,title:r?`Owned by: ${i}`:`You are the owner`,children:i}),(0,Z.jsx)(me,{className:`font-mono text-sm max-w-xs truncate`,title:e.url||`-`,children:e.url||`-`}),(0,Z.jsx)(me,{className:`font-mono text-sm`,children:e.workspaceId||`-`}),(0,Z.jsx)(me,{className:`font-mono text-sm`,children:e.baseUrl||`-`}),(0,Z.jsx)(me,{className:`font-mono text-sm`,children:e.path||`-`}),(0,Z.jsx)(me,{children:e.locked?`Yes`:`No`}),(0,Z.jsx)(me,{children:t}),(0,Z.jsx)(me,{children:n}),(0,Z.jsx)(me,{className:`text-right`,children:(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[!r&&(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>re(e),title:`Edit Context`,children:(0,Z.jsx)(gi,{className:`h-4 w-4`})}),(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>ne(e),title:r?`Open Shared Context`:`Open Context Details`,children:(0,Z.jsx)(fi,{className:`h-4 w-4`})}),!r&&(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>L(e.id),disabled:!!(e.url&&(e.url.endsWith(`/default`)||e.url.includes(`://default`))),className:`text-destructive hover:bg-destructive/10 hover:text-destructive disabled:opacity-50 disabled:cursor-not-allowed`,title:e.url&&(e.url.endsWith(`/default`)||e.url.includes(`://default`))?`Cannot delete default context`:`Delete Context`,children:(0,Z.jsx)(ti,{className:`h-4 w-4`})})]})})]},`${e.userId}-${e.id}`)})})]})})]}),j&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Edit Context`}),(0,Z.jsxs)(`form`,{onSubmit:ie,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-context-id`,className:`block text-sm font-medium mb-1`,children:`Context ID (read-only)`}),(0,Z.jsx)(q,{id:`edit-context-id`,value:j.id,disabled:!0,className:`bg-muted`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-context-url`,className:`block text-sm font-medium mb-1`,children:`Context URL`}),(0,Z.jsx)(C,{id:`edit-context-url`,value:j.url,onChange:e=>M(t=>t?{...t,url:e}:null),placeholder:`workspace://path or /path`,pickerTitle:`Context URL path…`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1`,children:`Use format: workspace://path or /path for current workspace`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-base-url`,className:`block text-sm font-medium mb-1`,children:`Base URL (optional)`}),(0,Z.jsx)(C,{id:`edit-base-url`,value:j.baseUrl||``,onChange:e=>M(t=>t?{...t,baseUrl:e||null}:null),format:`path`,placeholder:`/base/path`,pickerTitle:`Base path…`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1`,children:`Restricts context navigation to this base path`})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(Y,{type:`submit`,children:`Save Changes`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,onClick:()=>M(null),children:`Cancel`})]})]})]}),(0,Z.jsx)(vo,{open:N!==null,onOpenChange:e=>!e&&P(null),children:(0,Z.jsxs)(lo,{children:[(0,Z.jsxs)(_o,{children:[(0,Z.jsx)(io,{children:`Delete Context`}),(0,Z.jsx)(ro,{children:`Are you sure you want to delete this context? This action cannot be undone.`})]}),(0,Z.jsxs)(mo,{children:[(0,Z.jsx)(go,{children:`Cancel`}),(0,Z.jsx)(po,{onClick:R,className:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,children:`Delete`})]})]})})]})}function _D(e,t){if(!e||!t)return`/`;let n=`${t}://`;if(!e.startsWith(n))return`/`;let r=e.slice(n.length).replace(/^\/+/,``).replace(/\/+$/,``);return r?`/${r}`:`/`}function vD(){let{contextId:e}=yt(),t=vn(),n=ft(),r=new URLSearchParams(t.search).get(`ownerId`)||void 0,i=(0,X.useMemo)(()=>{let e=new URLSearchParams(t.search),n=e.getAll(`q`).map(e=>e.trim()).filter(Boolean),r=(e.get(`search`)||``).trim();return n.length?n:r?[r]:[]},[t.search]),{showToast:a,showProgress:o}=wo(),{state:s,saveFilters:c,setSort:l,setAccentColor:u,setMapDocuments:d}=ol(),{openM1Drawer:f,openM2Drawer:p,goBack:m}=qC(),h=s.filters.features.allOf,g=s.filters.features.anyOf,_=s.filters.features.noneOf,v=[...it(s.filters.timeline),...En(s.filters.geo),...ke(s.filters.lens,s.filters.geo.includeUnlocated)],y=JSON.stringify({a:h,b:g,c:_,d:v,ids:s.filters.lens.ids,sort:s.filters.sort,geoSelection:s.geoSelection,includeUnlocated:s.filters.geo.includeUnlocated}),b=(0,X.useMemo)(()=>JSON.parse(y),[y]),[x,S]=(0,X.useState)(null),[C,w]=(0,X.useState)(!0),[T,E]=(0,X.useState)(null),[D,O]=(0,X.useState)([]),[k,A]=(0,X.useState)(!1),[j,M]=(0,X.useState)(0),[N,P]=(0,X.useState)([]),[ee,F]=(0,X.useState)(1),[I,te]=(0,X.useState)(50),[L,R]=(0,X.useState)(i),[ne,re]=(0,X.useState)(!1),[ie,ae]=(0,X.useState)(null),[z,oe]=(0,X.useState)(!1),se=(0,X.useRef)(!1),ce=ie?.id===x?.id&&ie?.url===x?.url?ie?.path:null,V=new URLSearchParams(t.search).get(`layer`),le=!!r,ue=CE(le?void 0:x?.workspaceName||x?.workspaceId),de=x?_D(x.url,x.workspaceName):`/`,fe=V?`context-layer`:`context`,pe=!s.liveEnabled&&typeof x?.metadata?.toolboxSearchQuery==`string`?x.metadata.toolboxSearchQuery:``,me=le?null:x?.workspaceName??null,[he,ge]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!me)return;let e=!1;return _c(me,Tc).then(t=>{e||ge({key:me,tree:t})}).catch(()=>{e||ge({key:me,tree:null})}),()=>{e=!0}},[me]);let _e=me&&he?.key===me?he.tree:null,ve=!V&&!le&&_e?de===`/`?_e:xs(_e,de):null,ye=`${x?.workspaceName??``}\0${de}`,[be,xe]=(0,X.useState)(null),H=be?.key===ye?be.views:jT(ve?.metadata),Se=be?.key===ye?be.activeId:H[0]?.id??kT.id,Ce=H.find(e=>e.id===Se)??H[0]??kT,U=OT(Ce),W=e=>{F(1),xe({key:ye,views:H,activeId:e})},we=(e,t)=>{t&&t!==Se&&F(1),xe({key:ye,views:e,activeId:t??Se}),x?.workspaceName&&Ro(x.workspaceName,de,{metadata:{...ve?.metadata??{},views:e}},Tc).catch(()=>{a({title:`View not saved`,description:`Could not persist views to the layer`,variant:`destructive`})})},Te=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>Te.current?.abort(),[]);let Ee=(0,X.useCallback)(async()=>{if(!e)return;Te.current?.abort();let t=new AbortController;Te.current=t,A(!0);try{let n=await Sl(e,U?[...b.a,U]:b.a,b.d,{...b.sort,geoSelection:b.geoSelection,includeUnlocated:b.includeUnlocated,ids:b.ids,signal:t.signal,limit:I,page:ee,queries:L.length?L:void 0,anyOf:b.b,noneOf:b.c,applyContextSpec:!1},r);if(t.signal.aborted)return;O(n),M(n.totalCount||n.count||n.length)}catch(e){if(t.signal.aborted)return;a({title:`Error`,description:e instanceof Error?e.message:`Failed to fetch documents`,variant:`destructive`}),O([]),M(0)}finally{t.signal.aborted||A(!1)}},[e,ee,I,r,L,b,a,U]),De=(0,X.useCallback)(async()=>{if(e){w(!0);try{let t=le?await Tl(e,r):await Tl(e);if(!t)throw Error(`No context data received.`);let n=t.workspace,i=t.workspaceId||(typeof n==`string`?n:n?.id)||``,a=t.workspaceName||(typeof n==`string`?n:n?.name)||``;S({id:t.id,userId:t.userId,url:t.url,baseUrl:t.baseUrl||null,path:t.path||null,pathArray:t.pathArray||[],workspaceId:i,workspaceName:a,acl:t.acl||{},createdAt:t.createdAt,updatedAt:t.updatedAt,locked:t.locked||!1,serverContextArray:t.serverContextArray||[],clientContextArray:t.clientContextArray||[],contextBitmapArray:t.contextBitmapArray||[],featureBitmapArray:t.featureBitmapArray||[],filterArray:t.filterArray||[],pendingUrl:t.pendingUrl||null,description:t.description||null,metadata:t.metadata||{},name:t.name??null,color:t.color??null,icon:t.icon??null}),E(null)}catch(t){let n=t instanceof Error?t.message:`Failed to fetch context ${e}`;E(n),S(null),a({title:`Error`,description:n,variant:`destructive`})}w(!1)}},[e,r,le,a]);(0,X.useEffect)(()=>{De()},[De]);let Oe=Jt(x?.color)||null;(0,X.useEffect)(()=>(u(Oe),()=>u(null)),[Oe,u]);let Ae=s.geoSelection,je=x?.workspaceName||x?.workspaceId||null;(0,X.useEffect)(()=>{d(D,je)},[D,je,d]),(0,X.useEffect)(()=>()=>d([]),[d]);let Me=(0,X.useMemo)(()=>Ae?D.filter(e=>Pe(e,Ae,s.filters.geo.includeUnlocated)):D,[D,Ae,s.filters.geo.includeUnlocated]),Ne=x?.id,Fe=x?.url;(0,X.useEffect)(()=>{Ne&&Ee()},[Ne,Fe,Ee]),(0,X.useEffect)(()=>{let e=()=>Ee();return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[Ee]);let[Ie,Le]=(0,X.useState)(y);Ie!==y&&(Le(y),F(1));let[Re,ze]=(0,X.useState)(e);Re!==e&&(ze(e),F(1),re(!1));let[Be,Ve]=(0,X.useState)(i);Be!==i&&(Ve(i),R(i),F(1));let[He,Ue]=(0,X.useState)({urlSearchQueries:i,ignoreSavedSearch:ne,savedContextSearchQuery:pe});(He.urlSearchQueries!==i||He.ignoreSavedSearch!==ne||He.savedContextSearchQuery!==pe)&&(Ue({urlSearchQueries:i,ignoreSavedSearch:ne,savedContextSearchQuery:pe}),!new URLSearchParams(t.search).has(`q`)&&!i.length&&!ne&&(R(pe?[pe]:[]),F(1)));let We=(0,X.useCallback)(e=>{let r=new URLSearchParams(t.search);r.delete(`q`),r.delete(`search`);for(let t of e)r.append(`q`,t);let i=r.toString();n(`${t.pathname}${i?`?${i}`:``}${t.hash}`)},[t.pathname,t.search,t.hash,n]),Ge=(0,X.useCallback)(e=>{let t=e.trim();if(!t)return;re(!1);let n=L.includes(t)?L:[...L,t];R(n),We(n)},[L,We]),Ke=(0,X.useCallback)(e=>{let t=e<0?[]:L.filter((t,n)=>n!==e);t.length===0&&re(!0),R(t),We(t)},[L,We]),G=(L[0]||``).trim(),qe=!!s.activeContextType&&(s.isDirty||G!==(s.savedSearchQuery||pe||``));(0,X.useEffect)(()=>{if(!e)return;let t=`context:${r?`${r}/`:``}${e}`,n=()=>B.emit(`subscribe`,{channel:t}),i=()=>B.emit(`unsubscribe`,{channel:t}),a=B.on(`connect`,n);n();let o=new Map,s=(t,n)=>{let r=Date.now(),i=`${t}:${n?.id||n?.contextId||e}`;return(o.get(i)||0)+1e3>r?!1:(o.set(i,r),!0)},c=t=>{let n=t,r=n?.context||n;(r?.id===e||r?.contextId===e)&&s(`ctx:updated`,r)&&(S(e=>e?{...e,...r}:null),r.url&&Ee())},l=t=>{let n=t,r=n?.id||n?.contextId||n?.context?.id,i=n?.url||n?.context?.url;r===e&&typeof i==`string`&&s(`ctx:url`,n)&&(S(e=>e?{...e,url:i}:null),Ee())},u=t=>{let n=t;(n?.contextId||n?.id||n?.context?.id)===e&&s(`doc:changed`,n)&&Ee()},d=[[`context.updated`,c],[`context:updated`,c],[`context.url.set`,l],[`context:url:set`,l],[`document.inserted`,u],[`document.updated`,u],[`document.removed`,u],[`document.removed.batch`,u],[`document.linked`,u],[`document.unlinked`,u],[`document.linked.batch`,u],[`document.unlinked.batch`,u],[`document.deleted`,u],[`document.deleted.batch`,u]];return d.forEach(([e,t])=>B.on(e,t)),()=>{a(),i(),d.forEach(([e,t])=>B.off(e,t))}},[e,r,Ee]);let Je=async e=>{if(x)try{await rl(x.id,[e],r,de),O(t=>t.filter(t=>t.id!==e)),M(e=>Math.max(0,e-1)),a({title:`Success`,description:`Document removed from context.`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to remove document`,variant:`destructive`})}},Ye=async e=>{if(x)try{await _l(x.id,[e],r,de),O(t=>t.filter(t=>t.id!==e)),M(e=>Math.max(0,e-1)),a({title:`Success`,description:`Document deleted.`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to delete document`,variant:`destructive`})}},Xe=async e=>{if(x)try{await rl(x.id,e,r,de),O(t=>t.filter(t=>!e.includes(t.id))),M(t=>Math.max(0,t-e.length)),a({title:`Success`,description:`${e.length} document(s) removed.`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},Ze=async e=>{if(x)try{await _l(x.id,e,r,de),O(t=>t.filter(t=>!e.includes(t.id))),M(t=>Math.max(0,t-e.length)),a({title:`Success`,description:`${e.length} document(s) deleted.`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},Qe=e=>{P(e),a({title:`Copied`,description:`${e.length} document(s) copied to clipboard`})},$e=async(e,t,n={})=>{if(!x)return!1;let i=o({title:`Pasting…`,description:`${t.length} document(s) → "${e}"`});try{let a=n.targetTreeName&&!le?await Ko(x.workspaceName||x.workspaceId,e,t,n.targetTreeName,n.targetTreeType):await Al(x.id,e,t,r);return i.done(a?{title:`Success`,description:`${t.length} document(s) pasted to "${e}"`}:void 0),a&&(P([]),await Ee()),a}catch(e){return i.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},et=async(e,t)=>{if(!x)return!1;try{let n=await fl(x.workspaceId,t,e);return n&&(an(x.workspaceName||x.workspaceId,`context`,t),a({title:`Success`,description:`Imported ${e.length} document(s) to "${t}"`})),n}catch(e){return a({title:`Error`,description:e instanceof Error?e.message:`Failed to import documents`,variant:`destructive`}),!1}},tt=async()=>{if(!x||!ce||le||se.current)return;let e={id:x.id,url:x.url,path:ce};se.current=!0,oe(!0);try{let t=await sl(e.id,`${x.workspaceName}://${e.path.replace(/^\/+/,``)}`);S(n=>n?.id===e.id&&n.url===e.url?{...n,url:t.url,path:e.path}:n),ae(null),F(1),window.dispatchEvent(new CustomEvent(`contexts:refresh`,{detail:{contextId:e.id}})),a({title:`Saved`,description:`Context path updated`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Could not update context path`,variant:`destructive`})}finally{se.current=!1,oe(!1)}};if(C)return(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,Z.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,Z.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading context...`})]})});if(T&&!x)return(0,Z.jsxs)(`div`,{className:`flex items-center justify-center h-full text-destructive`,children:[`Error: `,T]});if(!x)return(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:`Context not found.`});let nt=Jt(x.color);return(0,Z.jsx)(`div`,{className:`flex flex-col h-full min-h-0`,children:(0,Z.jsx)(ET,{onBack:m,accentColor:nt,navigationTabs:ve?(0,Z.jsx)(NT,{views:H,activeId:Se,onSelect:W,onSave:we,accentColor:nt}):void 0,workspaceLabel:ue?.label||x.workspaceName||x.workspaceId,workspaceIcon:ue?.icon,treeName:Tc,urlType:fe,urlDisplay:x.url,contextPath:de,workspaceId:x.workspaceName||x.workspaceId,documentSchema:U,linkTree:_e,documents:Me,isLoading:k,totalCount:j,currentPage:ee,pageSize:I,onPageChange:F,onPageSizeChange:e=>{te(e),F(1)},onRemoveDocument:de===`/`?void 0:Je,onDeleteDocument:Ye,onRemoveDocuments:de===`/`?void 0:Xe,onDeleteDocuments:Ze,onCopyDocuments:Qe,onPasteDocuments:$e,onImportDocuments:le?void 0:et,pastedDocumentIds:N,backendSearchQueries:L,onBackendSearch:Ge,serverSort:s.filters.sort,onServerSortChange:l,onRemoveBackendQuery:Ke,canSaveChanges:qe,isSavingChanges:s.isSaving,onSaveChanges:c,onBrowseTree:!le&&e?()=>p(`contexts`,`detail`,e):void 0,onBrowseWorkspaces:()=>f(`workspaces`),onNavigatePath:le?void 0:e=>{se.current||ae({id:x.id,url:x.url,path:e})},contentBanner:ce?(0,Z.jsxs)(`div`,{className:`border-b bg-warning/10 px-4 py-2`,role:`status`,children:[(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Set this context to the selected path? Contents stay at the current path until you apply it.`}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,Z.jsx)(pn,{items:mt(ce,x.workspaceName),label:`Selected context path`}),(0,Z.jsx)(`button`,{type:`button`,disabled:z,onClick:()=>void tt(),className:`shrink-0 rounded border px-3 py-1 text-sm hover:bg-accent disabled:opacity-50`,children:z?`Setting…`:`Set`}),(0,Z.jsx)(`button`,{type:`button`,disabled:z,onClick:()=>ae(null),className:`shrink-0 rounded px-2 py-1 text-sm hover:bg-accent disabled:opacity-50`,children:`Cancel`})]})]}):void 0,children:Ce.kind===`columns`?(0,Z.jsx)(zT,{documents:Me,workspaceId:x.workspaceName||x.workspaceId,columns:Ce.columns??[],onColumnsChange:e=>we(H.map(t=>t.id===Ce.id?{...t,columns:e}:t))}):Ce.kind===`app`&&Ce.app&&Ce.app!==`notes`?(0,Z.jsx)(IT,{app:Ce.app,contextId:e,workspaceId:x.workspaceName||x.workspaceId,treeName:Tc,path:de}):null})})}function yD(){let{goBack:e}=qC();return e}function bD(){let[e,t]=(0,X.useState)([]),[n,r]=(0,X.useState)(!0),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(``),[f,p]=(0,X.useState)(!1),{showToast:m}=wo(),h=(0,X.useRef)(null),g=(0,X.useCallback)(async()=>{try{r(!0);let e=await J.get(no.tokens),n=Array.isArray(e)?e:e.tokens||[];t(n),a(null)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch tokens`;a(t),m({title:`Error`,description:t,variant:`destructive`})}finally{r(!1)}},[m]);(0,X.useEffect)(()=>{g()},[g]);let _=async()=>{if(!(!o.trim()||c)){l(!0);try{let e=await J.post(no.tokens,{name:o});s(``),await g(),e&&e.token&&(d(e.token),setTimeout(()=>{if(h.current){h.current.focus();let e=document.createRange();e.selectNodeContents(h.current);let t=window.getSelection();t&&(t.removeAllRanges(),t.addRange(e))}},100)),m({title:`Success`,description:`Token generated successfully`,variant:`default`})}catch(e){let t=e instanceof Error?e.message:`Failed to generate token`;a(t),m({title:`Error`,description:t,variant:`destructive`})}finally{l(!1)}}},v=async e=>{if(confirm(`Are you sure you want to revoke this API token? This action cannot be undone.`))try{await J.delete(`${no.tokens}/${e}`),await g(),m({title:`Success`,description:`API token revoked successfully`})}catch(e){let t=e instanceof Error?e.message:`Failed to revoke API token`;m({title:`Error`,description:t,variant:`destructive`})}},y=async e=>{try{await navigator.clipboard.writeText(e),p(!0),m({title:`Success`,description:`Token copied to clipboard`}),setTimeout(()=>p(!1),2e3)}catch{m({title:`Error`,description:`Failed to copy token to clipboard`,variant:`destructive`})}};return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{title:`API Tokens`,onBack:yD(),description:`Create and manage API tokens for programmatic access`}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Generate New API Token`}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`Token Name (e.g., 'CLI Access', 'Automation')`,disabled:c,className:`flex-1`}),(0,Z.jsxs)(Y,{type:`button`,disabled:c||!o.trim(),onClick:_,children:[(0,Z.jsx)(br,{className:`mr-2 h-4 w-4`}),c?`Generating...`:`Generate`]})]}),u&&(0,Z.jsxs)(`div`,{className:`p-4 border rounded-md bg-muted/50`,children:[(0,Z.jsxs)(`div`,{className:`flex justify-between items-center mb-2`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold`,children:`Your New API Token`}),(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>y(u),children:f?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(sr,{className:`mr-2 h-4 w-4`}),`Copied`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Jn,{className:`mr-2 h-4 w-4`}),`Copy`]})})]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mb-2`,children:`Make sure to copy your API token now. You won't be able to see it again!`}),(0,Z.jsx)(`div`,{ref:h,tabIndex:0,className:`p-2 bg-background border rounded font-mono text-sm break-all outline-none focus:ring-2 focus:ring-ring`,children:u})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your API Tokens`}),n&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading API tokens...`}),i&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:i})}),!n&&!i&&e.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No API tokens found`}),e.length>0&&(0,Z.jsx)(`div`,{className:`border rounded-md`,children:(0,Z.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Z.jsxs)(`table`,{className:`w-full`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{className:`bg-muted/50`,children:[(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Name`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Created`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Last Used`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Expires`}),(0,Z.jsx)(`th`,{className:`text-right p-3 font-medium`,children:`Actions`})]})}),(0,Z.jsx)(`tbody`,{children:e.map(e=>(0,Z.jsxs)(`tr`,{className:`border-t`,children:[(0,Z.jsx)(`td`,{className:`p-3 font-medium`,children:e.name}),(0,Z.jsx)(`td`,{className:`p-3`,children:new Date(e.createdAt).toLocaleDateString()}),(0,Z.jsx)(`td`,{className:`p-3`,children:e.lastUsedAt?new Date(e.lastUsedAt).toLocaleDateString():`Never`}),(0,Z.jsx)(`td`,{className:`p-3`,children:e.expiresAt?new Date(e.expiresAt).toLocaleDateString():`Never`}),(0,Z.jsx)(`td`,{className:`p-3 text-right`,children:(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>v(e.id),className:`text-destructive hover:bg-destructive/10 hover:text-destructive`,children:(0,Z.jsx)(ti,{className:`h-4 w-4`})})})]},e.id))})]})})})]})]})}async function xD(){return await J.get(no.devices)||[]}async function SD(e,t){return await J.patch(`${no.devices}/${encodeURIComponent(e)}`,t)}async function CD(e){await J.delete(`${no.devices}/${encodeURIComponent(e)}`)}async function wD(e){return await J.get(`${no.workspaces}/${e}/devices`)||[]}async function TD(e,t){let{deviceId:n,name:r,description:i,platform:a,arch:o,type:s}=t,c=await J.post(`${no.workspaces}/${e}/devices`,{devices:[{deviceId:n,name:r,description:i,platform:a,arch:o,type:s}]});return Array.isArray(c)?c:[c]}async function ED(e,t){await J.delete(`${no.workspaces}/${e}/devices/${encodeURIComponent(t)}`)}function DD({device:e,onUpdated:t,onRemoved:n}){let[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(e.name),[s,c]=(0,X.useState)(e.description??``),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),{showToast:h}=wo(),g=async()=>{m(!0);try{await CD(e.deviceId),n(e.deviceId),h({title:`Revoked`,description:`${e.name} can no longer sign in; a running mirror stops on its next request.`})}catch(e){h({title:`Error`,description:e instanceof Error?e.message:`Failed to revoke device`,variant:`destructive`}),f(!1)}finally{m(!1)}},_=async()=>{let n=a.trim();if(n){if(n===e.name&&s.trim()===(e.description??``)){i(!1);return}u(!0);try{let r=await SD(e.deviceId,{name:n,description:s.trim()||void 0});t({...e,...r}),i(!1),h({title:`Saved`,description:`Device updated`})}catch(e){h({title:`Error`,description:e instanceof Error?e.message:`Failed to update device`,variant:`destructive`})}finally{u(!1)}}},v=()=>{o(e.name),c(e.description??``),i(!1)},y=e=>e?new Date(e).toLocaleString(void 0,{dateStyle:`medium`,timeStyle:`short`}):`—`;return(0,Z.jsx)(`div`,{className:`rounded-lg border p-4`,children:(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start gap-3 min-w-0`,children:[(0,Z.jsx)(mr,{className:`h-4 w-4 text-muted-foreground mt-0.5 shrink-0`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[r?(0,Z.jsxs)(`div`,{className:`space-y-2 mb-2`,children:[(0,Z.jsx)(q,{value:a,onChange:e=>o(e.target.value),className:`h-7 text-sm`,placeholder:`Device name`,autoFocus:!0,disabled:l,onKeyDown:e=>{e.key===`Enter`&&_(),e.key===`Escape`&&v()}}),(0,Z.jsx)(q,{value:s,onChange:e=>c(e.target.value),className:`h-7 text-xs`,placeholder:`Description (optional)`,disabled:l,onKeyDown:e=>{e.key===`Enter`&&_(),e.key===`Escape`&&v()}})]}):(0,Z.jsxs)(`div`,{className:`mb-1`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:e.name}),e.description&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mt-0.5`,children:e.description})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] font-mono text-muted-foreground`,children:[(0,Z.jsx)(`span`,{title:`Device ID`,children:e.deviceId}),e.platform&&(0,Z.jsx)(`span`,{children:e.platform}),e.arch&&(0,Z.jsx)(`span`,{children:e.arch}),e.type&&(0,Z.jsx)(`span`,{className:`capitalize`,children:e.type})]}),(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-x-4 text-[11px] text-muted-foreground`,children:[e.createdAt&&(0,Z.jsxs)(`span`,{children:[`registered `,y(e.createdAt)]}),e.updatedAt&&e.updatedAt!==e.createdAt&&(0,Z.jsxs)(`span`,{children:[`updated `,y(e.updatedAt)]}),e.lastSeen&&(0,Z.jsxs)(`span`,{children:[`seen `,y(e.lastSeen)]})]})]})]}),(0,Z.jsx)(`div`,{className:`flex shrink-0 items-center gap-2`,children:d?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Y,{type:`button`,variant:`destructive`,size:`sm`,onClick:g,disabled:p,children:p?`Revoking…`:`Confirm revoke`}),(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>f(!1),disabled:p,children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]}):r?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:_,disabled:l||!a.trim(),children:(0,Z.jsx)(sr,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`sm`,onClick:v,disabled:l,children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>i(!0),title:`Edit name / description`,children:(0,Z.jsx)(Lr,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>f(!0),title:`Revoke this device: its tokens stop working and its mirrors stop syncing`,children:(0,Z.jsx)(Di,{className:`h-3.5 w-3.5`})})]})})]})})}function OD(){let[e,t]=(0,X.useState)([]),[n,r]=(0,X.useState)(!0),{showToast:i}=wo(),a=async()=>{r(!0);try{t(await xD())}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to load devices`,variant:`destructive`})}finally{r(!1)}};(0,X.useEffect)(()=>{(async()=>{try{t(await xD())}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to load devices`,variant:`destructive`})}finally{r(!1)}})()},[i]);let o=e=>t(t=>t.map(t=>t.deviceId===e.deviceId?e:t)),s=e=>t(t=>t.filter(t=>t.deviceId!==e));return(0,Z.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,Z.jsxs)(`div`,{className:`mx-auto max-w-3xl p-6 pb-12 space-y-6`,children:[(0,Z.jsx)(sw,{compact:!0,title:`Devices`,onBack:yD(),description:`All devices registered to your account. Link them to individual workspaces in Workspace › Settings › Devices.`,actions:(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:a,disabled:n,children:[(0,Z.jsx)(Er,{className:`mr-2 h-3.5 w-3.5 ${n?`animate-spin`:``}`}),`Refresh`]})}),n?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(Er,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):e.length===0?(0,Z.jsxs)(`div`,{className:`rounded-lg border p-6 text-center text-sm text-muted-foreground space-y-2`,children:[(0,Z.jsx)(mr,{className:`h-8 w-8 mx-auto text-muted-foreground/40`}),(0,Z.jsx)(`p`,{children:`No devices registered yet.`}),(0,Z.jsxs)(`p`,{className:`text-xs`,children:[`Devices register themselves automatically on first connection via`,` `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`POST /auth/devices/register`}),`.`]})]}):(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.map(e=>(0,Z.jsx)(DD,{device:e,onUpdated:o,onRemoved:s},e.deviceId))}),e.length>0&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 rounded-md border border-dashed p-3 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Ri,{className:`h-3.5 w-3.5 shrink-0`}),`To link a device to a workspace, go to Workspace › Settings › Devices.`]})]})})}var kD=[{id:`general`,label:`Workspace details`,description:`Rename, change appearance or remove this workspace`,icon:Bi},{id:`backups`,label:`Backups`,description:`Save or restore documents, relations and tree placements`,icon:ra},{id:`data`,label:`Files & storage`,description:`Connect folders and data sources, check disk usage or restore trash`,icon:Fr},{id:`db`,label:`Search & indexing`,description:`Rebuild indexes, tune search and choose embedding models`,icon:Fa},{id:`devices`,label:`Devices`,description:`Link devices to this workspace`,icon:mr},{id:`sync`,label:`Synchronization`,description:`Manage device copies and resolve sync conflicts`,icon:Er},{id:`services`,label:`Connected services`,description:`Configure Git, WebDAV, IMAP and other connectors`,icon:pi},{id:`shares`,label:`Sharing & permissions`,description:`Create public links and manage workspace access`,icon:Ri},{id:`policies`,label:`Storage policies`,description:`Mirror folders of the virtual tree to physical backends`,icon:gr},{id:`hooks`,label:`Automation`,description:`Run hooks in response to workspace events`,icon:Gr}],AD={embedding:`db`,trash:`data`};function jD(e){return e?AD[e]?AD[e]:kD.some(t=>t.id===e)?e:`general`:`general`}var MD=[{id:`general`,label:`Context details`,description:`Change the name, description or color, or remove this context`,icon:Bi},{id:`location`,label:`Tree & path`,description:`Choose the workspace, tree and path this context opens`,icon:Ri},{id:`shares`,label:`Sharing & permissions`,description:`Choose who can access this context`,icon:ar}];function ND(e){return e&&MD.some(t=>t.id===e)?e:`general`}var PD=[{id:`identity`,label:`Identity & instructions`,description:`Set the agent’s name, role and instructions`,icon:Bi},{id:`provider`,label:`AI connection`,description:`Connect a chat model provider and manage its credentials`,icon:Cr},{id:`models`,label:`Chat model`,description:`Choose the model and tune how it responds`,icon:yi},{id:`tools`,label:`Tools & skills`,description:`Choose the skills and MCP tools the agent can use`,icon:Pr},{id:`access`,label:`Access & permissions`,description:`Choose which Canvas content the agent can access`,icon:Ra},{id:`memory`,label:`Memory`,description:`Configure how the agent remembers information`,icon:ri},{id:`integrations`,label:`Integrations`,description:`Connect mail, chat, databases and external APIs`,icon:si}];function FD(e){return e&&PD.some(t=>t.id===e)?e:`identity`}var ID=class{static async handleStreamingResponse(e,t={}){let{onChunk:n,onError:r,onComplete:i,signal:a}=t;try{if(!e.body)throw Error(`Response body is null - streaming not supported`);if(typeof e.body.getReader!=`function`){console.warn(`ReadableStream.getReader not available, falling back to text response`);let t=await e.text();n&&n(t),i&&i();return}let t=e.body.getReader(),r=new TextDecoder;try{for(;;){if(a?.aborted)throw t.cancel(),Error(`Stream aborted`);let{done:e,value:o}=await t.read();if(e){i&&i();break}let s=r.decode(o,{stream:!0});s&&n&&n(s)}}finally{t.releaseLock()}}catch(e){console.error(`Streaming error:`,e),r&&r(e instanceof Error?e:Error(String(e)))}}static processSSEChunk(e){let t=[],n=e.split(`
|
|
26
26
|
`),r={};for(let e of n){let n=e.trim();if(n.startsWith(`data: `))try{let e=JSON.parse(n.slice(6));r={...r,...e}}catch{console.warn(`Failed to parse SSE data:`,n)}else n===``&&(r.agentId&&r.messageId&&t.push(r),r={})}return t}},LD=class{baseUrl;constructor(e,t=`/rest/v2/agents/anthropic`){this.baseUrl=t}async chatStream(e,t){let{agentId:n,messageId:r,onMessage:i,onError:a,onComplete:o,signal:s}=t;try{let t=await fetch(`${this.baseUrl}/chat/stream`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`text/plain, text/event-stream`,"Cache-Control":`no-cache`},body:JSON.stringify({message:e,agentId:n,messageId:r}),signal:s});if(!t.ok)throw Error(`HTTP ${t.status}: ${t.statusText}`);await ID.handleStreamingResponse(t,{onChunk:e=>{try{ID.processSSEChunk(e).forEach(e=>{i&&i(e)})}catch(e){console.warn(`Failed to process streaming chunk:`,e)}},onError:e=>{let t=Error(`Chat stream failed: AnthropicConnector chatStream failed: ${e.message}`);console.error(`Chat stream error:`,{agentId:n,messageId:r,error:t.message}),a&&a(t)},onComplete:o,signal:s})}catch(e){let t=Error(`Chat stream failed: AnthropicConnector chatStream failed: ${e instanceof Error?e.message:String(e)}`);console.error(`Chat stream error:`,{agentId:n,messageId:r,error:t.message}),a&&a(t)}}},RD=class{wsUrl;socket=null;messageHandlers=new Map;constructor(e){this.wsUrl=e}connect(){return new Promise((e,t)=>{try{this.socket=new WebSocket(this.wsUrl),this.socket.onopen=()=>{console.log(`WebSocket connected for streaming`),e()},this.socket.onerror=e=>{console.error(`WebSocket error:`,e),t(Error(`WebSocket connection failed`))},this.socket.onmessage=e=>{try{let t=JSON.parse(e.data),n=`${t.agentId}-${t.messageId}`,r=this.messageHandlers.get(n);r&&r(t)}catch(e){console.error(`Failed to parse WebSocket message:`,e)}},this.socket.onclose=()=>{console.log(`WebSocket disconnected`),this.socket=null}}catch(e){t(e)}})}startChatStream(e,t,n,r,i){if(!this.socket||this.socket.readyState!==WebSocket.OPEN){i&&i(Error(`WebSocket not connected`));return}let a=`${e}-${t}`;this.messageHandlers.set(a,r);try{this.socket.send(JSON.stringify({type:`chat_stream`,agentId:e,messageId:t,message:n}))}catch(e){i&&i(e instanceof Error?e:Error(String(e)))}}stopChatStream(e,t){let n=`${e}-${t}`;this.messageHandlers.delete(n)}disconnect(){this.socket&&=(this.socket.close(),null),this.messageHandlers.clear()}};function zD(e){if(!e)return``;if(typeof e.errorMessage==`string`&&e.errorMessage.trim())return e.errorMessage.trim();let t=e.content;return typeof t==`string`?t:Array.isArray(t)&&t.filter(e=>e?.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(`
|
|
27
27
|
`)||``}function BD(e){return e?typeof e?.metadata?.reasoning==`string`&&e.metadata.reasoning.trim()?e.metadata.reasoning.trim():Array.isArray(e.content)?e.content.filter(e=>e?.type===`thinking`||e?.type===`reasoning`).map(e=>typeof e?.thinking==`string`?e.thinking:typeof e?.reasoning==`string`?e.reasoning:typeof e?.text==`string`?e.text:``).filter(Boolean).join(`
|
|
28
|
-
`).trim():``:``}function VD(e){if(!e)return;let t=BD(e),n={...e.api?{api:e.api}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.stopReason?{stopReason:e.stopReason}:{},...e.timestamp===void 0?{}:{timestamp:e.timestamp},...e.responseId?{responseId:e.responseId}:{},...e.usage?{usage:e.usage}:{},...e.metadata?.toolCalls?{toolCalls:e.metadata.toolCalls}:{},...t?{reasoning:t}:{}};return Object.keys(n).length>0?n:void 0}function HD(e){if(typeof e==`number`)return new Date(e).toISOString();if(typeof e==`string`){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t.toISOString()}return new Date().toISOString()}function UD(e=[]){return e.filter(e=>e?.role===`user`||e?.role===`assistant`).map(e=>({role:e.role,content:zD(e),timestamp:HD(e.timestamp),...e.role===`assistant`?{metadata:VD(e)}:{}})).filter(e=>e.content||e.metadata?.reasoning)}function WD(e){return{mode:e?.mode,sessionId:e?.sessionId,sessionFile:e?.sessionFile,thinkingLevel:e?.thinkingLevel,model:e?.model,messages:UD(e?.messages||[])}}function GD(e){return{current:WD(e?.current),sessions:e?.sessions}}new class{connectors=new Map;wsService=null;messageCallbacks=new Map;constructor(){this.initializeWebSocketFallback()}async initializeWebSocketFallback(){try{let e=`${window.location.protocol===`https:`?`wss:`:`ws:`}//${window.location.host}/ws`;this.wsService=new RD(e)}catch(e){console.warn(`WebSocket fallback not available:`,e)}}registerAgent(e){if(e.type===`anthropic`){let t=new LD(e.apiKey||``,e.endpoint||`${yo}/agents/${e.id}`);this.connectors.set(e.id,t)}}async sendMessage(e,t,n={}){let{onMessage:r,onError:i,onComplete:a,useWebSocketFallback:o=!1}=n,s=`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;r&&this.messageCallbacks.set(s,r);try{if(o&&this.wsService){await this.sendMessageViaWebSocket(e,s,t,r,i),a&&a();return}let n=this.connectors.get(e);n?await n.chatStream(t,{agentId:e,messageId:s,onMessage:e=>{let t={id:e.messageId,agentId:e.agentId,content:e.content||``,timestamp:new Date,type:`agent`,streaming:!e.done,error:e.error};r&&r(t)},onError:n=>{if(console.error(`Agent connector error:`,n),n.message.includes(`getReader is not a function`)&&this.wsService){console.log(`Falling back to WebSocket streaming...`),this.sendMessageViaWebSocket(e,s,t,r,i);return}i&&i(n)},onComplete:a}):await this.sendMessageViaAPI(e,s,t,r,i,a)}catch(e){console.error(`Agent communication error:`,e),i&&i(e instanceof Error?e:Error(String(e)))}finally{this.messageCallbacks.delete(s)}}async sendMessageViaAPI(e,t,n,r,i,a){try{await J.stream(`${yo}/agents/${e}/chat/stream`,{message:n,messageId:t},{onChunk:n=>{try{let i=JSON.parse(n),a={id:t,agentId:e,content:i.content||n,timestamp:new Date,type:`agent`,streaming:!i.done,error:i.error};r&&r(a)}catch{r&&r({id:t,agentId:e,content:n,timestamp:new Date,type:`agent`,streaming:!0})}},onError:e=>{console.error(`API streaming error:`,e),i&&i(e)},onComplete:a})}catch(e){i&&i(e instanceof Error?e:Error(String(e)))}}async sendMessageViaWebSocket(e,t,n,r,i){if(!this.wsService){i&&i(Error(`WebSocket service not available`));return}try{this.wsService.socket?.readyState!==WebSocket.OPEN&&await this.wsService.connect(),this.wsService.startChatStream(e,t,n,e=>{let t={id:e.messageId,agentId:e.agentId,content:e.content||``,timestamp:new Date,type:`agent`,streaming:!e.done,error:e.error};r&&r(t)},i)}catch(e){i&&i(e instanceof Error?e:Error(String(e)))}}async getAvailableAgents(){try{return(await J.get(`${yo}/agents`)).agents||[]}catch(e){return console.error(`Failed to fetch available agents:`,e),[]}}async createAgent(e){let t=await J.post(`${yo}/agents`,e);return this.registerAgent(t),t}dispose(){this.connectors.clear(),this.messageCallbacks.clear(),this.wsService&&this.wsService.disconnect()}};async function KD(e){return await J.get(`${yo}/agents/${e}/access`)||null}async function qD(e,t){return await J.put(`${yo}/agents/${e}/access`,t)}async function JD(e){return await J.post(`${yo}/agents/${e}/access/token`)}async function YD(e){await J.delete(`${yo}/agents/${e}/access`)}async function XD(e){return await J.get(`${yo}/agents/${e}/tools`)||{tools:[],config:{}}}async function ZD(){try{return await J.get(`${yo}/agents`)||[]}catch(e){return console.error(`Failed to list agents:`,e),[]}}async function QD(e){return await J.get(`${yo}/agents/${e}`)}async function $D(e){return WD(await J.get(`${yo}/agents/${e}/session`))}async function eO(e){return await J.get(`${yo}/agents/${e}/sessions`)}async function tO(e,t){return GD(await J.post(`${yo}/agents/${e}/sessions`,t))}async function nO(e,t){return GD(await J.put(`${yo}/agents/${e}/session`,t))}async function rO(e,t,n){return GD(await J.patch(`${yo}/agents/${e}/sessions/${t}`,n))}async function iO(e,t){return GD(await J.delete(`${yo}/agents/${e}/sessions/${t}`))}async function aO(e){return await J.get(`${yo}/agents/${e}/skills`)||[]}async function oO(e,t){return await J.post(`${yo}/agents/${e}/skills`,t)||[]}async function sO(e,t){return await J.delete(`${yo}/agents/${e}/skills/${encodeURIComponent(t)}`)||[]}async function cO(e){return await J.post(`${yo}/agents`,e)}async function lO(e,t){return await J.put(`${yo}/agents/${e}`,t)}async function uO(e){await J.delete(`${yo}/agents/${e}`)}async function dO(e){return await J.post(`${yo}/agents/${e}/start`)}async function fO(e){return await J.post(`${yo}/agents/${e}/stop`)}async function pO(e){return await J.get(`${yo}/agents/${e}/status`)}async function mO(e,t,n={}){let{onStart:r,onMessage:i,onError:a,onComplete:o,context:s,mcpContext:c,maxTokens:l,temperature:u,images:d}=n,f
|
|
28
|
+
`).trim():``:``}function VD(e){if(!e)return;let t=BD(e),n={...e.api?{api:e.api}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.stopReason?{stopReason:e.stopReason}:{},...e.timestamp===void 0?{}:{timestamp:e.timestamp},...e.responseId?{responseId:e.responseId}:{},...e.usage?{usage:e.usage}:{},...e.metadata?.toolCalls?{toolCalls:e.metadata.toolCalls}:{},...t?{reasoning:t}:{}};return Object.keys(n).length>0?n:void 0}function HD(e){if(typeof e==`number`)return new Date(e).toISOString();if(typeof e==`string`){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t.toISOString()}return new Date().toISOString()}function UD(e=[]){return e.filter(e=>e?.role===`user`||e?.role===`assistant`).map(e=>({role:e.role,content:zD(e),timestamp:HD(e.timestamp),...e.role===`assistant`?{metadata:VD(e)}:{}})).filter(e=>e.content||e.metadata?.reasoning)}function WD(e){return{mode:e?.mode,sessionId:e?.sessionId,sessionFile:e?.sessionFile,thinkingLevel:e?.thinkingLevel,model:e?.model,messages:UD(e?.messages||[])}}function GD(e){return{current:WD(e?.current),sessions:e?.sessions}}new class{connectors=new Map;wsService=null;messageCallbacks=new Map;constructor(){this.initializeWebSocketFallback()}async initializeWebSocketFallback(){try{let e=`${window.location.protocol===`https:`?`wss:`:`ws:`}//${window.location.host}/ws`;this.wsService=new RD(e)}catch(e){console.warn(`WebSocket fallback not available:`,e)}}registerAgent(e){if(e.type===`anthropic`){let t=new LD(e.apiKey||``,e.endpoint||`${yo}/agents/${e.id}`);this.connectors.set(e.id,t)}}async sendMessage(e,t,n={}){let{onMessage:r,onError:i,onComplete:a,useWebSocketFallback:o=!1}=n,s=`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;r&&this.messageCallbacks.set(s,r);try{if(o&&this.wsService){await this.sendMessageViaWebSocket(e,s,t,r,i),a&&a();return}let n=this.connectors.get(e);n?await n.chatStream(t,{agentId:e,messageId:s,onMessage:e=>{let t={id:e.messageId,agentId:e.agentId,content:e.content||``,timestamp:new Date,type:`agent`,streaming:!e.done,error:e.error};r&&r(t)},onError:n=>{if(console.error(`Agent connector error:`,n),n.message.includes(`getReader is not a function`)&&this.wsService){console.log(`Falling back to WebSocket streaming...`),this.sendMessageViaWebSocket(e,s,t,r,i);return}i&&i(n)},onComplete:a}):await this.sendMessageViaAPI(e,s,t,r,i,a)}catch(e){console.error(`Agent communication error:`,e),i&&i(e instanceof Error?e:Error(String(e)))}finally{this.messageCallbacks.delete(s)}}async sendMessageViaAPI(e,t,n,r,i,a){try{await J.stream(`${yo}/agents/${e}/chat/stream`,{message:n,messageId:t},{onChunk:n=>{try{let i=JSON.parse(n),a={id:t,agentId:e,content:i.content||n,timestamp:new Date,type:`agent`,streaming:!i.done,error:i.error};r&&r(a)}catch{r&&r({id:t,agentId:e,content:n,timestamp:new Date,type:`agent`,streaming:!0})}},onError:e=>{console.error(`API streaming error:`,e),i&&i(e)},onComplete:a})}catch(e){i&&i(e instanceof Error?e:Error(String(e)))}}async sendMessageViaWebSocket(e,t,n,r,i){if(!this.wsService){i&&i(Error(`WebSocket service not available`));return}try{this.wsService.socket?.readyState!==WebSocket.OPEN&&await this.wsService.connect(),this.wsService.startChatStream(e,t,n,e=>{let t={id:e.messageId,agentId:e.agentId,content:e.content||``,timestamp:new Date,type:`agent`,streaming:!e.done,error:e.error};r&&r(t)},i)}catch(e){i&&i(e instanceof Error?e:Error(String(e)))}}async getAvailableAgents(){try{return(await J.get(`${yo}/agents`)).agents||[]}catch(e){return console.error(`Failed to fetch available agents:`,e),[]}}async createAgent(e){let t=await J.post(`${yo}/agents`,e);return this.registerAgent(t),t}dispose(){this.connectors.clear(),this.messageCallbacks.clear(),this.wsService&&this.wsService.disconnect()}};async function KD(e){return await J.get(`${yo}/agents/${e}/access`)||null}async function qD(e,t){return await J.put(`${yo}/agents/${e}/access`,t)}async function JD(e){return await J.post(`${yo}/agents/${e}/access/token`)}async function YD(e){await J.delete(`${yo}/agents/${e}/access`)}async function XD(e){return await J.get(`${yo}/agents/${e}/tools`)||{tools:[],config:{}}}async function ZD(){try{return await J.get(`${yo}/agents`)||[]}catch(e){return console.error(`Failed to list agents:`,e),[]}}async function QD(e){return await J.get(`${yo}/agents/${e}`)}async function $D(e){return WD(await J.get(`${yo}/agents/${e}/session`))}async function eO(e){return await J.get(`${yo}/agents/${e}/sessions`)}async function tO(e,t){return GD(await J.post(`${yo}/agents/${e}/sessions`,t))}async function nO(e,t){return GD(await J.put(`${yo}/agents/${e}/session`,t))}async function rO(e,t,n){return GD(await J.patch(`${yo}/agents/${e}/sessions/${t}`,n))}async function iO(e,t){return GD(await J.delete(`${yo}/agents/${e}/sessions/${t}`))}async function aO(e){return await J.get(`${yo}/agents/${e}/skills`)||[]}async function oO(e,t){return await J.post(`${yo}/agents/${e}/skills`,t)||[]}async function sO(e,t){return await J.delete(`${yo}/agents/${e}/skills/${encodeURIComponent(t)}`)||[]}async function cO(e){return await J.post(`${yo}/agents`,e)}async function lO(e,t){return await J.put(`${yo}/agents/${e}`,t)}async function uO(e){await J.delete(`${yo}/agents/${e}`)}async function dO(e){return await J.post(`${yo}/agents/${e}/start`)}async function fO(e){return await J.post(`${yo}/agents/${e}/stop`)}async function pO(e){return await J.get(`${yo}/agents/${e}/status`)}async function mO(e,t,n={}){let{onStart:r,onMessage:i,onError:a,onComplete:o,context:s,mcpContext:c,maxTokens:l,temperature:u,images:d}=n,f=``,p=``,m=``,h=e=>{e!==m&&(m=e,a?.(Error(e)))};await J.stream(`${yo}/agents/${e}/prompt/stream`,{message:t,images:d,context:s,mcpContext:c,maxTokens:l,temperature:u},{onOpen:()=>{r?.()},onChunk:e=>{f+=e;let t=f.split(`
|
|
29
29
|
|
|
30
30
|
`);f=t.pop()||``;for(let e of t){let t=e.split(`
|
|
31
|
-
`).map(e=>e.trim()).filter(Boolean);for(let e of t){if(!e.startsWith(`data: `))continue;let t=e.slice(6).trim();if(t!==`[DONE]`)try{let e=JSON.parse(t);if(!i)continue;if(e.type===`chunk`)i(e.delta||``,!1,e.metadata||{});else if(e.type===`thinking`)i(``,!1,{...e.metadata||{},reasoningDelta:e.delta||``});else if(e.type===`complete`){let t=Array.isArray(e.messages)?[...e.messages].reverse().find(e=>e?.role===`assistant`):null;i(``,!0,{...e.metadata||{},...VD(t)||{}})}else e.type===`error`&&a&&a(Error(e.error||`Prompt stream failed`))}catch{}}}},onError:a,onComplete:o})}async function hO(e,t){let{message:n,onMessage:r,onError:i,onComplete:a,context:o,mcpContext:s,maxTokens:c,temperature:l,images:u}=t;try{let t=await J.post(`${yo}/agents/${e}/prompt`,{message:n,images:u,context:o,mcpContext:s,maxTokens:c,temperature:l}),i=Array.isArray(t.messages)?[...t.messages].reverse().find(e=>e?.role===`assistant`):null,d={content:zD(i),metadata:VD(i)};return r&&r(d.content,!0,d.metadata),a&&a(),d}catch(e){throw i&&i(e),e}}function gO(e){return e.map(e=>({...e,timestamp:typeof e.timestamp==`string`?e.timestamp:new Date().toISOString()}))}async function _O(){return await J.get(`${yo}/voice/status`)}async function vO(e,t,n={}){let r=new FormData,i=(t.type.split(`/`)[1]||`webm`).split(`;`)[0];r.append(`file`,t,`voice.${i}`);let a=new URLSearchParams;n.tts===!1&&a.set(`tts`,`false`),n.voice&&a.set(`voice`,n.voice);let o=a.toString()?`?${a.toString()}`:``;return await J.post(`${yo}/agents/${e}/voice${o}`,r)}function yO(e,t){return J.post(`${yo}/agents/models`,e,{signal:t})}var bO=[{id:`workspace`,label:`Workspace`,path:`workspaces`,description:`Files, search, devices and sharing for one workspace. These settings override account defaults.`,sections:kD,load:async()=>(await Uo()).map(e=>({id:e.name,label:e.label||e.name}))},{id:`context`,label:`Context`,path:`contexts`,description:`Choose the tree and path a context opens, and who can access that view. File storage belongs to its workspace.`,sections:MD,load:async()=>(await ml()).map(e=>({id:e.id,label:e.name||e.id}))},{id:`agent`,label:`Agent`,path:`agents`,description:`Configure one assistant: its instructions, chat model, tools and access to Canvas.`,sections:PD,load:async()=>(await ZD()).map(e=>({id:e.id,label:e.label||e.name}))}];function xO({to:e,label:t,description:n,icon:r}){return(0,Z.jsxs)(we,{to:e,className:`group flex items-start gap-3 rounded-lg border bg-card p-4 transition-colors hover:border-primary/50 hover:bg-accent/30 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary`,children:[(0,Z.jsx)(r,{className:`mt-0.5 h-5 w-5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-semibold`,children:t}),(0,Z.jsx)(`span`,{className:`mt-1 block text-sm leading-relaxed text-muted-foreground`,children:n})]}),(0,Z.jsx)(xi,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground group-hover:text-primary`})]})}function SO({group:e,query:t}){let[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(`loading`),[c,l]=(0,X.useState)(0);(0,X.useEffect)(()=>{let t=!1;return e.load().then(e=>{t||(r(e),s(`ready`))}).catch(()=>{t||s(`error`)}),()=>{t=!0}},[e,c]);let u=e.sections.filter(n=>wC(t,e.label,n.label,n.description));return u.length?(0,Z.jsxs)(`section`,{id:e.id,className:`scroll-mt-6 space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsxs)(`label`,{className:`block max-w-md text-sm font-medium`,children:[`Choose a `,e.label.toLowerCase(),(0,Z.jsxs)(`select`,{className:`mt-2 h-10 w-full rounded-md border bg-background px-3 text-sm`,value:i,disabled:o!==`ready`||!n.length,onChange:e=>a(e.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:o===`loading`?`Loading…`:o===`error`?`Unable to load list`:n.length?`Select ${e.label.toLowerCase()}…`:`No ${e.path} available`}),n.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),o===`error`&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`The list could not be loaded. `,(0,Z.jsx)(`button`,{type:`button`,className:`underline`,onClick:()=>{s(`loading`),l(e=>e+1)},children:`Retry`})]}),(0,Z.jsxs)(`details`,{open:!!(i||t.trim()),children:[(0,Z.jsx)(`summary`,{className:`cursor-pointer py-2 text-sm text-muted-foreground`,children:i?`Settings for ${n.find(e=>e.id===i)?.label||i}`:`What you can configure (${u.length})`}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:u.map(t=>i?(0,Z.jsx)(xO,{to:`/${e.path}/${encodeURIComponent(i)}/settings/${t.id}`,...t},t.id):(0,Z.jsxs)(`div`,{className:`rounded-lg border border-dashed p-4`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:t.label}),(0,Z.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:t.description})]},t.id))})]})]}):null}function CO(){let{state:e}=qC(),[t,n]=(0,X.useState)(``),r=SC.filter(t=>t.id!==`server`||e.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(n=>wC(t,e.label,n.label,n.description))})).filter(e=>e.items.length),i=bO.some(e=>e.sections.some(n=>wC(t,e.label,n.label,n.description)));return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-6xl space-y-8 pb-8 max-md:pb-rail-stack`,children:[(0,Z.jsx)(sw,{title:`Settings`,description:`Start with what you want to change. Each section explains where your changes apply.`}),(0,Z.jsx)(q,{type:`search`,className:`max-w-xl`,"aria-label":`Search all settings`,placeholder:`Find a setting: offline, folders, models, sharing…`,value:t,onChange:e=>n(e.target.value)}),r.filter(e=>e.id===`device`||e.id===`account`).map(e=>(0,Z.jsxs)(`section`,{className:`space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,Z.jsx)(xO,{to:e.path,...e},e.path))})]},e.id)),bO.map(e=>(0,Z.jsx)(SO,{group:e,query:t},e.id)),r.filter(e=>e.id===`server`||e.id===`information`).map(e=>(0,Z.jsxs)(`section`,{className:`space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,Z.jsx)(xO,{to:e.path,...e},e.path))})]},e.id)),!r.length&&!i&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`No settings match “`,t,`”. Try a shorter phrase or clear the search.`]})]})}var wO=[{id:`canvas_1`,title:`Canvas Deep`,scheme:`dark`,background:`#032940`,accent:`#f2f2f2`,sources:[{type:`image/svg+xml`,src:`files/canvas_1.svg`},{type:`image/avif`,src:`files/canvas_1.avif`},{type:`image/webp`,src:`files/canvas_1.webp`}],thumb:`thumbs/canvas_1.webp`,author:`Canvas`,license:`LicenseRef-Canvas-Brand`},{id:`canvas_3`,title:`Canvas Mono Dark`,scheme:`dark`,background:`#000000`,accent:`#ffffff`,sources:[{type:`image/svg+xml`,src:`files/canvas_3.svg`},{type:`image/avif`,src:`files/canvas_3.avif`},{type:`image/webp`,src:`files/canvas_3.webp`}],thumb:`thumbs/canvas_3.webp`,author:`Canvas`,license:`LicenseRef-Canvas-Brand`},{id:`w1`,title:`Frost`,scheme:`dark`,background:`#164a6f`,accent:`#9ad9f0`,sources:[{type:`image/avif`,src:`files/w1.avif`},{type:`image/webp`,src:`files/w1.webp`},{type:`image/jpeg`,src:`files/w1.jpg`}],thumb:`thumbs/w1.webp`,author:`Peter Cui Bide`,source:`https://petercui.deviantart.com`,license:`LicenseRef-Attribution-Only`}],TO=`/wallpapers`;function EO(e){return wO.find(t=>t.id===e)}function DO(e,t={}){let n=typeof e==`string`?EO(e):e;if(!n)return null;let{base:r=TO,types:i}=t,a=(i?n.sources.find(e=>i.includes(e.type)):n.sources[0])??n.sources[n.sources.length-1];return`${r.replace(/\/$/,``)}/${a.src}`}function OO(e,t=TO){let n=typeof e==`string`?EO(e):e;return n?`${t.replace(/\/$/,``)}/${n.thumb}`:null}var kO=[{id:`cover`,label:`Scale and Crop`,description:`Fills the screen, cropping edges as needed`},{id:`fill`,label:`Fill`,description:`Stretches to the exact screen size`},{id:`center`,label:`Centered`,description:`Original size, centered on the desk`}],AO=`canvas:wallpaper`,jO=`canvas-wallpaper`,MO=`settings`,NO=`builtin:`,PO=wO;function FO(e){return OO(e)??``}function IO(e){return`${NO}${e}`}function LO(e){return e?.startsWith(NO)?e.slice(8):null}function RO(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.image!=`string`&&t.image!==null?null:{image:t.image,fit:t.fit===`fill`||t.fit===`center`?t.fit:`cover`}}function zO(){try{let e=localStorage.getItem(AO);if(e){let t=RO(JSON.parse(e));if(t)return t}}catch{}return{image:null,fit:`cover`}}var BO=zO(),VO=null;function HO(){return BO}async function UO(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(jO,1),r=!1;n.onupgradeneeded=()=>n.result.createObjectStore(MO),n.onsuccess=()=>{if(r){n.result.close();return}n.result.onversionchange=()=>n.result.close(),e(n.result)},n.onerror=()=>t(n.error),n.onblocked=()=>{r=!0,t(Error(`Close other Canvas tabs and try again.`))}});try{return await new Promise((n,r)=>{let i=t.transaction(MO,e?`readwrite`:`readonly`),a=i.objectStore(MO),o=e?a.put(e,AO):a.get(AO);i.oncomplete=()=>n(o.result),i.onerror=()=>r(i.error),i.onabort=()=>r(i.error)})}finally{t.close()}}function WO(){try{localStorage.removeItem(AO)}catch{}}function GO(){return VO||=(async()=>{try{let e=RO(await UO());e?BO=e:await UO(BO),WO()}catch{}return $O(BO),BO})(),VO.then(()=>BO)}async function KO(e){await GO(),await UO(e),BO=e,WO(),$O(e)}function qO(e){if(e.size>10485760)return Promise.reject(Error(`Image too large. Choose one up to 10 MB.`));let t=e.type||(/\.gif$/i.test(e.name)?`image/gif`:``);return t.startsWith(`image/`)?new Promise((n,r)=>{let i=new FileReader;i.onload=()=>n(String(i.result)),i.onerror=()=>r(Error(`Could not read the image. Try selecting it again.`)),i.onabort=()=>r(Error(`Reading the image was cancelled.`)),i.readAsDataURL(e.type?e:e.slice(0,e.size,t))}):Promise.reject(Error(`Pick an image file (animated GIFs are supported).`))}var JO=typeof CSS<`u`&&CSS.supports(`background-image`,`image-set(url("a.avif") type("image/avif"))`);function YO(e){if(!e)return null;let t=LO(e);if(t===null)return`url("${e}")`;let n=EO(t);if(!n)return null;let r=`url("${DO(n,{types:[n.sources[n.sources.length-1].type]})}")`;return!JO||n.sources.length===1?r:`image-set(${n.sources.map(e=>`url("${DO(n,{types:[e.type]})}") type("${e.type}")`).join(`, `)})`}function XO(e){return e===`fill`?`100% 100%`:e===`center`?`auto`:`cover`}var ZO=null;function QO(e){let t=e.indexOf(`,`);if(t<0)throw Error(`Invalid wallpaper data URL`);let n=e.slice(5,t),r=e.slice(t+1),i;if(n.endsWith(`;base64`)){let e=atob(r);i=new Uint8Array(e.length);for(let t=0;t<e.length;t++)i[t]=e.charCodeAt(t)}else i=new TextEncoder().encode(decodeURIComponent(r));return new Blob([i],{type:n.split(`;`)[0]})}function $O(e=HO()){let t=document.documentElement.style,n=ZO,r=e.image;if(r?.startsWith(`data:`))try{ZO?.dataUrl!==r&&(ZO={dataUrl:r,objectUrl:URL.createObjectURL(QO(r))}),r=ZO.objectUrl}catch{ZO=null,r=null}else ZO=null;let i=YO(r);i?(t.setProperty(`--wallpaper-image`,i),t.setProperty(`--wallpaper-size`,XO(e.fit))):(t.removeProperty(`--wallpaper-image`),t.removeProperty(`--wallpaper-size`)),n&&n!==ZO&&URL.revokeObjectURL(n.objectUrl)}var ek=[{id:`cards`,name:`Cards`,description:`Nested cards with connector lines. Each level indents.`},{id:`accordion-mobile`,name:`Accordion on phones (beta)`,description:`Experimental. Full-width accordion rows on a phone, cards on wider screens.`},{id:`accordion`,name:`Accordion (beta)`,description:`Experimental. Full-width rows at every depth; a depth rail, tint and colour swatch replace the indent, and open parents stick to the top while you scroll.`}],tk=`canvas:treeStyle`;function nk(){try{let e=localStorage.getItem(tk);return e===`accordion`||e===`accordion-mobile`?e:`cards`}catch{return`cards`}}var rk=nk(),ik=new Set;function ak(){return rk}function ok(e){try{e===`cards`?localStorage.removeItem(tk):localStorage.setItem(tk,e)}catch{}rk=e;for(let e of ik)e()}function sk(e){ik.add(e);let t=t=>{(t.key===tk||t.key===null)&&(rk=nk(),e())};return window.addEventListener(`storage`,t),()=>{ik.delete(e),window.removeEventListener(`storage`,t)}}function ck(){return(0,X.useSyncExternalStore)(sk,ak,()=>`cards`)}function lk(){let e=ck(),t=De();return e===`accordion`||e===`accordion-mobile`&&t}var uk=[{id:`canvas`,name:`Canvas`,description:`Black and white with a teal accent. Sheets of paper on a grey desk.`,swatches:[`oklch(1 0 0)`,`oklch(0 0 0)`,`oklch(0.704 0.135 183)`]},{id:`nord`,name:`Nord`,description:`Cool arctic blues, lower contrast, softer corners.`,swatches:[`oklch(0.976 0.006 251)`,`oklch(0.588 0.056 244)`,`oklch(0.686 0.062 213)`]},{id:`contrast`,name:`High Contrast`,description:`WCAG AAA text contrast, square corners, hard borders, no shadows.`,swatches:[`oklch(1 0 0)`,`oklch(0 0 0)`,`oklch(0.32 0.16 258)`]},{id:`frost`,name:`Frosted Glass`,description:`Translucent, blurred surfaces over a soft backdrop. Best with a wallpaper.`,swatches:[`oklch(0.92 0.008 250)`,`oklch(0.31 0.025 255)`,`oklch(0.55 0.05 250)`]},{id:`terminal`,name:`Terminal`,description:`Monospaced and dense. Tighter rows and chrome for large displays.`,swatches:[`oklch(0.17 0.006 152)`,`oklch(0.8 0.19 148)`,`oklch(0.75 0.12 220)`]},{id:`halflife`,name:`Half-Life`,description:`Lambda orange on black steel. Square corners; the left rail is orange.`,swatches:[`oklch(0.724 0.181 52)`,`oklch(0 0 0)`,`oklch(1 0 0)`]}],dk=uk.map(e=>e.id),fk=[{id:`system`,name:`System`},{id:`light`,name:`Light`},{id:`dark`,name:`Dark`}],pk=[{id:`auto`,name:`Auto`,description:`Match the pointer: touch on phones, mouse on desktop`},{id:`compact`,name:`Compact`,description:`Maximum rows per screen`},{id:`comfortable`,name:`Comfortable`,description:`Balanced for mouse use`},{id:`touch`,name:`Touch`,description:`Large targets for finger input`}],mk={theme:`canvas`,scheme:`light`,density:`auto`},hk=`canvas.ui.theme`;function gk(e){return typeof e==`string`&&dk.includes(e)}function _k(e){return e===`light`||e===`dark`||e===`system`}function vk(e){return e===`auto`||e===`compact`||e===`comfortable`||e===`touch`}function yk(e){let t=typeof e==`object`&&e?e:{};return{theme:gk(t.theme)?t.theme:mk.theme,scheme:_k(t.scheme)?t.scheme:mk.scheme,density:vk(t.density)?t.density:mk.density}}var bk=`(prefers-color-scheme: dark)`;function xk(){return typeof document<`u`}function Sk(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(bk).matches}function Ck(e){return e===`system`?Sk()?`dark`:`light`:e}function wk(e){if(typeof window>`u`||typeof window.matchMedia!=`function`)return()=>{};let t=window.matchMedia(bk),n=t=>e(t.matches?`dark`:`light`);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)}function Tk(e){return wk(e)}function Ek(){return Sk()?`dark`:`light`}function Dk(){return`light`}function Ok(e){let t=getComputedStyle(e).getPropertyValue(`--background`).trim();if(!t)return;let n=document.querySelector(`meta[name="theme-color"]`);n||(n=document.createElement(`meta`),n.name=`theme-color`,document.head.appendChild(n)),n.content=t}function kk(e,t=xk()?document.documentElement:void 0){let n=Ck(e.scheme);return t?(t.dataset.theme=e.theme,t.dataset.scheme=n,t.dataset.density=e.density,Ok(t),n):n}function Ak(e,t=xk()?document.documentElement:void 0){if(!t||typeof window>`u`)return kk(e,t);let n=document.createElement(`style`);n.appendChild(document.createTextNode(`*,*::before,*::after{transition:none!important;animation:none!important}`)),document.head.appendChild(n);let r=kk(e,t);return window.getComputedStyle(n).opacity,document.head.removeChild(n),r}function jk(e){let t=e??Pk();if(!t)return mk;try{let e=t.getItem(hk);return e?yk(JSON.parse(e)):mk}catch{return mk}}function Mk(e,t){let n=t??Pk();if(n)try{n.setItem(hk,JSON.stringify(e))}catch{}}function Nk(e){let t=e??Pk();if(t)try{t.removeItem(hk)}catch{}}function Pk(){try{return typeof localStorage<`u`?localStorage:void 0}catch{return}}function Fk({children:e,initial:t,storage:n,persist:r=!0}){let[i,a]=(0,X.useState)(()=>({...jk(n),...t})),o=(0,X.useSyncExternalStore)(Tk,Ek,Dk),s=i.scheme===`system`?o:i.scheme;(0,X.useEffect)(()=>{Ak({...i,scheme:s})},[i,s]),(0,X.useEffect)(()=>{r&&Mk(i,n)},[i,r,n]);let c=(0,X.useCallback)(e=>{a(t=>t.theme===e?t:{...t,theme:e})},[]),l=(0,X.useCallback)(e=>{a(t=>t.scheme===e?t:{...t,scheme:e})},[]),u=(0,X.useCallback)(e=>{a(t=>t.density===e?t:{...t,density:e})},[]),d=(0,X.useCallback)(()=>{a(e=>({...e,scheme:(e.scheme===`system`?Ek():e.scheme)===`dark`?`light`:`dark`}))},[]),f=(0,X.useCallback)(()=>{Nk(n),a(mk)},[n]),p=(0,X.useMemo)(()=>({...i,resolvedScheme:s,setTheme:c,setScheme:l,setDensity:u,toggleScheme:d,reset:f}),[i,s,c,l,u,d,f]);return(0,Z.jsx)(Il.Provider,{value:p,children:e})}var Ik={system:mr,light:ji,dark:va};function Lk(){let{theme:e,scheme:t,density:n,resolvedScheme:r,setTheme:i,setScheme:a,setDensity:o,reset:s}=Ll(),c=re(),l=k(),u=PC(),d=L(),f=ck(),p=UC();return(0,Z.jsxs)(`div`,{className:`space-y-8`,children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Vk,{title:`Theme`,description:`Palette, shape and typography. Each theme defines its own light and dark variants.`}),(0,Z.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3`,children:uk.map(t=>{let n=t.id===e;return(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>i(t.id),"aria-pressed":n,className:K(`focus-ring group flex flex-col gap-3 rounded-lg border p-4 text-left transition-colors`,n?`border-primary bg-accent`:`border-border hover:border-muted-foreground/40 hover:bg-accent/50`),children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:t.name}),n&&(0,Z.jsx)(sr,{className:`size-4 shrink-0 text-primary`})]}),(0,Z.jsx)(`div`,{className:`flex gap-1.5`,"aria-hidden":!0,children:t.swatches.map(e=>(0,Z.jsx)(`span`,{className:`size-6 rounded-full border border-border`,style:{backgroundColor:e}},e))}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:t.description})]},t.id)})})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Vk,{title:`Colour scheme`,description:t===`system`?`Following your system setting, currently ${r}.`:`Overrides your system setting.`}),(0,Z.jsx)(Hk,{options:fk.map(e=>{let t=Ik[e.id];return{id:e.id,label:e.name,icon:(0,Z.jsx)(t,{className:`size-4 shrink-0`})}}),value:t,onChange:a})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Vk,{title:`Density`,description:`Controls row height, hit-target size and shell spacing across the whole app.`}),(0,Z.jsx)(Hk,{options:pk.map(e=>({id:e.id,label:e.name,title:e.description})),value:n,onChange:o}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:pk.find(e=>e.id===n)?.description})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Vk,{title:`Layout`,description:`How menus and content share the screen. Device-local, like the wallpaper.`}),(0,Z.jsx)(Hk,{options:TC.map(e=>({id:e.id,label:e.name,title:e.description})),value:u,onChange:MC}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:TC.find(e=>e.id===u)?.description}),u===`strip`&&(0,Z.jsxs)(`div`,{className:`mt-4`,children:[(0,Z.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Navigation keys`}),(0,Z.jsx)(Hk,{options:FC.map(e=>({id:e.id,label:e.name,title:e.description})),value:p,onChange:VC}),(0,Z.jsxs)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:[FC.find(e=>e.id===p)?.description,` `,`Left and right walk the columns, up and down switch pin rows.`]})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Vk,{title:`Tree style`,description:`How workspace and context trees are drawn in the menu. Device-local.`}),(0,Z.jsx)(Hk,{options:ek.map(e=>({id:e.id,label:e.name,title:e.description})),value:f,onChange:ok}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:ek.find(e=>e.id===f)?.description})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Vk,{title:`Open documents`,description:`Choose how documents open from lists, tiles and boards. Saved on this device.`}),(0,Z.jsx)(Hk,{options:[{id:`modal`,label:`Modal`},{id:`side`,label:`Side reading pane`}],value:l,onChange:M}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`The reading pane opens beside the content and updates as you select another document. On small screens it opens as a drawer.`})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Vk,{title:`Always-on content area`,description:`Keep a reading pane beside document lists on tablets and desktops. Remember the selected item in each folder, or show the first available item.`}),(0,Z.jsx)(Hk,{options:[{id:`on`,label:`On`},{id:`off`,label:`Off`}],value:c?`on`:`off`,onChange:e=>ze(e===`on`)}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`On by default. The reader uses roughly half the screen; drag its divider to resize. Phones keep tap-to-open navigation. When enabled, list selections use this pane regardless of the Open documents setting.`})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Vk,{title:`Document tiles`,description:`Choose the photo and media layout for tile view. Saved on this device.`}),(0,Z.jsx)(Hk,{options:Ie,value:d,onChange:He})]}),(0,Z.jsx)(Rk,{}),(0,Z.jsx)(`section`,{children:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{s(),M(`modal`)},className:`focus-ring rounded-md text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline`,children:`Reset to defaults`})})]})}function Rk(){let[e,t]=(0,X.useState)(HO),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(!0),[o,s]=(0,X.useState)(!1),c=(0,X.useRef)(!1);(0,X.useEffect)(()=>{let e=!1;return GO().then(()=>{e||(t(HO()),a(!1))}),()=>{e=!0}},[]);let l=async(e,n)=>{if(!c.current){c.current=!0,s(!0);try{let i=n?{...e,image:await qO(n)}:e;await KO(i),t(i),r(null)}catch(e){r(e instanceof Error&&e.name!==`QuotaExceededError`?e.message:`Could not store the wallpaper. Free some browser storage or try a smaller image.`)}finally{c.current=!1,s(!1)}}},u=t=>{t&&l(e,t)},d=e.image!==null&&LO(e.image)===null,f=YO(e.image);return(0,Z.jsx)(`section`,{children:(0,Z.jsxs)(`fieldset`,{disabled:i||o,className:`min-w-0`,children:[(0,Z.jsx)(Vk,{title:`Wallpaper`,description:`Background image for the desk behind all panels. Without one, the theme's desk color shows (the default).`}),(0,Z.jsxs)(`div`,{role:`radiogroup`,"aria-label":`Wallpaper`,className:`grid grid-cols-3 gap-3 sm:grid-cols-4 lg:grid-cols-6`,children:[(0,Z.jsx)(Bk,{label:`None`,isActive:e.image===null,onSelect:()=>l({...e,image:null}),children:(0,Z.jsx)(`span`,{className:`flex size-full items-center justify-center surface-desk text-xs text-muted-foreground`,style:{backgroundImage:`none`},children:`None`})}),PO.map(t=>(0,Z.jsx)(Bk,{label:t.title,title:`${t.title} — suits the ${t.scheme} scheme`,isActive:LO(e.image)===t.id,onSelect:()=>l({...e,image:IO(t.id)}),children:(0,Z.jsx)(`img`,{src:FO(t),alt:``,loading:`lazy`,className:`size-full object-cover`,style:{backgroundColor:t.background}})},t.id)),d&&(0,Z.jsx)(Bk,{label:`Your image`,isActive:!0,onSelect:()=>{},children:(0,Z.jsx)(`img`,{src:e.image??void 0,alt:``,className:`size-full object-cover`})})]}),(0,Z.jsx)(zk,{}),(0,Z.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center gap-3`,children:[(0,Z.jsx)(`div`,{className:`h-20 w-32 shrink-0 rounded-md border surface-desk`,style:f?{backgroundImage:f,backgroundSize:XO(e.fit),backgroundPosition:`center`,backgroundRepeat:`no-repeat`}:void 0,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsxs)(`label`,{className:`focus-ring inline-flex cursor-pointer items-center rounded-md border px-3 py-1.5 text-sm hover:bg-accent/50`,children:[d?`Change image…`:`Use your own image…`,(0,Z.jsx)(`input`,{type:`file`,accept:`image/*,.gif`,className:`hidden`,onChange:e=>{u(e.target.files?.[0]),e.target.value=``}})]}),e.image&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>l({...e,image:null}),className:`focus-ring rounded-md border px-3 py-1.5 text-sm text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:`Remove`})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Images and animated GIFs up to 10 MB. Stored on this device.`}),(0,Z.jsx)(Hk,{options:kO.map(e=>({id:e.id,label:e.label,title:e.description})),value:e.fit,onChange:t=>l({...e,fit:t})}),n&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:n}),o&&(0,Z.jsx)(`p`,{role:`status`,className:`text-xs text-muted-foreground`,children:`Saving wallpaper…`})]})]})]})})}function zk(){let e=PO.filter(e=>e.author!==`Canvas`);return e.length===0?null:(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:e.map((e,t)=>(0,Z.jsxs)(`span`,{children:[t>0&&` · `,e.title,` © `,e.author,e.source&&(0,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.jsx)(`a`,{href:e.source,target:`_blank`,rel:`noreferrer noopener`,className:`focus-ring underline underline-offset-2 hover:text-foreground`,children:new URL(e.source).hostname})]})]},e.id))})}function Bk({label:e,title:t,isActive:n,onSelect:r,children:i}){return(0,Z.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":n,"aria-label":e,title:t??e,onClick:r,className:K(`focus-ring group relative aspect-video overflow-hidden rounded-md border transition-colors`,n?`border-primary ring-1 ring-primary`:`border-border hover:border-muted-foreground/40`),children:[i,n&&(0,Z.jsx)(`span`,{className:`absolute right-1 top-1 rounded-full bg-primary p-0.5 text-primary-foreground`,children:(0,Z.jsx)(sr,{className:`size-3`})})]})}function Vk({title:e,description:t}){return(0,Z.jsxs)(`div`,{className:`mb-3`,children:[(0,Z.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function Hk({options:e,value:t,onChange:n}){return(0,Z.jsx)(`div`,{role:`radiogroup`,className:`inline-flex flex-wrap gap-1 rounded-lg bg-muted p-1`,children:e.map(e=>{let r=e.id===t;return(0,Z.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":r,title:e.title,onClick:()=>n(e.id),className:K(`focus-ring flex h-control items-center gap-2 rounded-md px-3 text-sm transition-colors`,r?`bg-card text-foreground shadow-elevation-1`:`text-muted-foreground hover:text-foreground`),children:[e.icon,e.label]},e.id)})})}function Uk(){return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(sw,{className:`mb-6`,title:`Appearance`,onBack:yD(),description:`Theme, colour scheme and density. Changes apply immediately and are remembered on this device.`}),(0,Z.jsx)(Lk,{})]})}var Wk={previousTree:`Alt+Q`,nextTree:`Alt+W`},Gk=`canvas:key-bindings`,Kk=/^(Alt|Alt\+Shift|Ctrl\+Shift|Meta\+Shift)\+[A-Z]$/;function qk(){try{let e=JSON.parse(localStorage.getItem(Gk)||`{}`),t={...Wk};for(let n of Object.keys(t))(e[n]===``||Kk.test(e[n]))&&(t[n]=e[n]);return t.previousTree&&t.previousTree===t.nextTree?{...Wk}:t}catch{return{...Wk}}}function Jk(e){localStorage.setItem(Gk,JSON.stringify(e))}function Yk(e){return/^Key[A-Z]$/.test(e.code)?[e.ctrlKey&&`Ctrl`,e.altKey&&`Alt`,e.metaKey&&`Meta`,e.shiftKey&&`Shift`,e.code.slice(3)].filter(Boolean).join(`+`):``}function Xk(e,t,n){return e[(Math.max(0,e.indexOf(t))+n+e.length)%e.length]}function Zk(e,t){return Math.abs(e)>=48&&Math.abs(e)>Math.abs(t)*1.5?e<0?1:-1:0}function Qk(){let[e,t]=(0,X.useState)(qk),[n,r]=(0,X.useState)(``),i=e=>{if(e.previousTree&&e.previousTree===e.nextTree){r(`Choose a different shortcut: that combination is already assigned.`);return}try{Jk(e),t(e),r(`Saved on this device.`)}catch{r(`Could not save shortcuts in this browser.`)}};return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(sw,{className:`mb-6`,title:`Key bindings`,onBack:yD(),description:`Web UI shortcuts, saved on this device and available offline.`}),(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`font-medium`,children:`Tree navigation`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Cycle the open workspace menu’s tabs in their displayed order, including Pins and Layers. Swipe left for next or right for previous over the tab bar. Shortcuts pause while typing or using a dialog.`}),[`previousTree`,`nextTree`].map(t=>(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Z.jsx)(`label`,{htmlFor:t,className:`min-w-32 text-sm`,children:t===`previousTree`?`Previous tree`:`Next tree`}),(0,Z.jsxs)(`select`,{id:t,className:`rounded-md border bg-background p-2 text-sm`,value:e[t].split(`+`).slice(0,-1).join(`+`),onChange:n=>i({...e,[t]:n.target.value?`${n.target.value}+${e[t].slice(-1)||Wk[t].slice(-1)}`:``}),children:[(0,Z.jsx)(`option`,{value:``,children:`Disabled`}),[`Alt`,`Alt+Shift`,`Ctrl+Shift`,`Meta+Shift`].map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))]}),(0,Z.jsx)(`select`,{"aria-label":`${t===`previousTree`?`Previous`:`Next`} tree key`,disabled:!e[t],className:`rounded-md border bg-background p-2 text-sm disabled:opacity-50`,value:e[t].slice(-1)||Wk[t].slice(-1),onChange:n=>i({...e,[t]:`${e[t].split(`+`).slice(0,-1).join(`+`)}+${n.target.value}`}),children:`ABCDEFGHIJKLMNOPQRSTUVWXYZ`.split(``).map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))})]},t)),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Browsers and operating systems may reserve combinations. Choose another if a shortcut does not reach Canvas. Letters refer to physical keyboard positions (Q/W on a US keyboard); Meta is Command on Mac.`}),(0,Z.jsx)(`button`,{type:`button`,className:`rounded-md border px-3 py-2 text-sm hover:bg-accent`,onClick:()=>i({...Wk}),children:`Restore defaults`}),(0,Z.jsx)(`p`,{role:`status`,className:`text-sm`,children:n})]})]})}var $k=`offline-content-v1`,eA=`offline-api-v1`,tA=1073741824,nA={enabled:!1,budgetBytes:4*tA,excludedWorkspaces:[]},rA=1e3;function iA(e){return(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``)||`/`}function aA(e,t,n){return`${e}:${t}:${iA(n)}`}var oA=`canvas-offline`,sA=2,cA=null;function lA(){return cA||(cA=new Promise((e,t)=>{let n=indexedDB.open(oA,sA);n.onupgradeneeded=e=>{let t=n.result;if(t.objectStoreNames.contains(`config`)||t.createObjectStore(`config`),t.objectStoreNames.contains(`entries`)||t.createObjectStore(`entries`,{keyPath:`url`}),e.oldVersion>=1&&t.objectStoreNames.contains(`pins`)){t.deleteObjectStore(`pins`);let e=n.transaction.objectStore(`entries`).openCursor();e.onsuccess=()=>{let t=e.result;if(!t)return;let n=t.value;n.pinned&&t.update({...n,pinned:!1}),t.continue()}}t.objectStoreNames.contains(`scopes`)||t.createObjectStore(`scopes`,{keyPath:`id`})},n.onsuccess=()=>{n.result.onversionchange=()=>{n.result.close(),cA=null},e(n.result)},n.onerror=()=>{cA=null,t(n.error)}}),cA)}function uA(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function dA(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}async function fA(e,t){return dA((await lA()).transaction(e).objectStore(e).get(t))}async function pA(e){return dA((await lA()).transaction(e).objectStore(e).getAll())}async function mA(e,t,n){let r=(await lA()).transaction(e,`readwrite`);return r.objectStore(e).put(t,n),uA(r)}async function hA(e,t){let n=(await lA()).transaction(e,`readwrite`);return n.objectStore(e).delete(t),uA(n)}async function gA(e){let t=(await lA()).transaction(e,`readwrite`);return t.objectStore(e).clear(),uA(t)}async function _A(){try{let e=await fA(`config`,`settings`);return e?{...nA,...e}:nA}catch{return nA}}async function vA(e){await mA(`config`,e,`settings`)}async function yA(e,t){let n=(await lA()).transaction(`entries`,`readwrite`),r=n.objectStore(`entries`);for(let n of e){let e=r.get(n);e.onsuccess=()=>{let i=e.result;i?r.put({...i,pinned:t}):t&&r.put({url:n,kind:`content`,size:0,lastAccess:Date.now(),pinned:t})}}return uA(n)}async function bA(e){let t=await pA(`entries`),n=t.filter(e=>e.kind===`api`).sort((e,t)=>e.lastAccess-t.lastAccess),r=n.slice(0,Math.max(0,n.length-rA)),i=t.filter(e=>e.kind===`content`),a=i.reduce((e,t)=>e+t.size,0),o=i.filter(e=>!e.pinned).sort((e,t)=>e.lastAccess-t.lastAccess),s=[];for(let t of o){if(a<=e)break;s.push(t),a-=t.size}if(!r.length&&!s.length)return;let[c,l]=await Promise.all([caches.open(eA),caches.open($k)]);await Promise.all([...r.map(async e=>{await c.delete(e.url),await hA(`entries`,e.url)}),...s.map(async e=>{await l.delete(e.url),await hA(`entries`,e.url)})])}async function xA(){let e=await pA(`entries`),t=e.filter(e=>e.kind===`content`);return{contentBytes:t.reduce((e,t)=>e+t.size,0),contentCount:t.length,pinnedBytes:t.filter(e=>e.pinned).reduce((e,t)=>e+t.size,0),apiCount:e.length-t.length}}async function SA(){await Promise.all([caches.delete($k),caches.delete(eA)]),await gA(`entries`),await gA(`scopes`)}async function CA(){return pA(`scopes`)}async function wA(e){return fA(`scopes`,e)}async function TA(e){await mA(`scopes`,e)}async function EA(e){let t=await fA(`scopes`,e);await hA(`scopes`,e),t?.urls.length&&await DA(t.urls)}async function DA(e){let t=await pA(`scopes`),n=new Set(t.flatMap(e=>e.urls)),r=e.filter(e=>!n.has(e));r.length&&await yA(r,!1)}var OA=3,kA=`data/schema/file`,AA=128;async function jA({workspaceRef:e,path:t,treeName:n,treeType:r},i){let a=await _A();if(!a.enabled)throw Error(`Enable the offline cache first`);if(a.excludedWorkspaces.includes(e))throw Error(`Workspace "${e}" is excluded from offline caching`);let o=aA(e,n,t),s=iA(t),c=await wA(o),l=((await Fs(e,s,[],{limit:1e4,treeName:n,treeType:r})).payload??[]).filter(e=>e.schema===kA),u=[],d=0,f=0,p=!1,m=l.length;i?.({done:f,total:m,bytes:d});let h=0;await Promise.all(Array.from({length:Math.min(OA,l.length)},async()=>{for(;h<l.length;){let t=l[h++];if(d>=a.budgetBytes*.9){p=!0;return}try{let{blob:n}=await No(e,t.id);d+=n.size,u.push(`${no.workspaces}/${e}/documents/${t.id}/content`);try{await Cs(e,t.id,AA),u.push(`${no.workspaces}/${e}/documents/${t.id}/thumbnail?size=${AA}`)}catch{}}catch{}f+=1,i?.({done:f,total:m,bytes:d})}})),await yA(u,!0);let g={id:o,workspaceRef:e,treeName:n,treeType:r,path:s,urls:u,bytes:d,warmedAt:Date.now(),...p?{truncated:!0}:{}};if(await TA(g),c){let e=new Set(u),t=c.urls.filter(t=>!e.has(t));t.length&&await DA(t)}return g}var MA=[{label:`1 GB`,bytes:1*tA},{label:`2 GB`,bytes:2*tA},{label:`4 GB`,bytes:4*tA},{label:`8 GB`,bytes:8*tA}];function NA(e){return e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${(e/tA).toFixed(2)} GB`}function PA(){navigator.serviceWorker?.controller?.postMessage({type:`OFFLINE_SETTINGS_CHANGED`})}function FA(){let{showSuccessToast:e,showErrorToast:t}=Oo(),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)([]),[u,d]=(0,X.useState)([]),[f,p]=(0,X.useState)({}),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(!1),v=(0,X.useCallback)(()=>{_A().then(r).catch(()=>{}),xA().then(a).catch(()=>{}),CA().then(e=>d(e.sort((e,t)=>e.id.localeCompare(t.id)))).catch(()=>{}),navigator.storage?.persisted?.().then(s).catch(()=>{})},[]);(0,X.useEffect)(()=>{v(),Uo().then(e=>l(e.map(e=>e.name).filter(Boolean).sort())).catch(()=>{})},[v]);let b=async e=>{r(e),await vA(e),PA(),e.enabled&&navigator.storage?.persist?.().then(s).catch(()=>{}),bA(e.budgetBytes).then(v).catch(()=>{})},x=e=>{if(!n)return;let t=n.excludedWorkspaces.includes(e)?n.excludedWorkspaces.filter(t=>t!==e):[...n.excludedWorkspaces,e];b({...n,excludedWorkspaces:t})},S=async()=>{h(!0);try{await SA(),e(`Offline cache cleared`),v()}catch(e){t(e instanceof Error?e.message:`Failed to clear cache`)}finally{h(!1)}},C=async n=>{let r=aA(n.workspaceRef,n.treeName,n.path);p(e=>({...e,[r]:{done:0,total:0,bytes:0}}));try{let t=await jA(n,e=>p(t=>({...t,[r]:e})));e(t.truncated?`Pinned ${NA(t.bytes)} — stopped at the size budget`:`Pinned ${t.workspaceRef}:/${t.path} (${NA(t.bytes)})`)}catch(e){t(e instanceof Error?e.message:`Failed to pin`)}finally{p(e=>{let{[r]:t,...n}=e;return n}),v()}},w=(e,t)=>{_(!1);for(let n of e)C({workspaceRef:t.workspaceName,path:n,treeName:t.treeName,treeType:t.treeType})},T=e=>({workspaceRef:e.workspaceRef,path:e.path,treeName:e.treeName||`context`,treeType:e.treeType||`context`}),E=async e=>{await EA(e),v()};return n?(0,Z.jsxs)(`div`,{className:`space-y-8`,children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(IA,{title:`Offline cache`,description:`Keep documents you open (and scopes you pin) readable without a connection. Cached on this device only; least-recently-used files are evicted when the size budget fills. Video streaming is not cached.`}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>b({...n,enabled:!n.enabled}),"aria-pressed":n.enabled,className:K(`focus-ring flex items-center gap-3 rounded-lg border p-4 text-left transition-colors`,n.enabled?`border-primary bg-accent`:`border-input hover:bg-muted/40`),children:[(0,Z.jsx)(Ya,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`flex-1`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium`,children:n.enabled?`Enabled`:`Disabled`}),(0,Z.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:n.enabled?o===!1?`Storage is not persistent — the browser may still evict the cache under disk pressure`:`Documents are cached as you browse`:`Nothing is cached for offline use`})]}),n.enabled&&(0,Z.jsx)(sr,{className:`h-4 w-4 shrink-0 text-primary`})]}),n.enabled&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Size budget`}),(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:MA.map(e=>(0,Z.jsx)(Y,{variant:n.budgetBytes===e.bytes?`default`:`outline`,size:`sm`,onClick:()=>b({...n,budgetBytes:e.bytes}),children:e.label},e.bytes))})]}),i&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between text-sm`,children:[(0,Z.jsxs)(`span`,{children:[NA(i.contentBytes),` of `,NA(n.budgetBytes),` used`]}),(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[i.contentCount,` file(s)`,i.pinnedBytes>0?`, ${NA(i.pinnedBytes)} pinned`:``]})]}),(0,Z.jsx)(`div`,{className:`h-2 w-full overflow-hidden rounded-full bg-muted`,children:(0,Z.jsx)(`div`,{className:`h-full rounded-full bg-primary`,style:{width:`${Math.min(100,i.contentBytes/n.budgetBytes*100)}%`}})})]}),(0,Z.jsx)(`div`,{children:(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:S,disabled:m,children:[m?(0,Z.jsx)(Ti,{className:`mr-1.5 h-3.5 w-3.5 animate-spin`}):(0,Z.jsx)(Qr,{className:`mr-1.5 h-3.5 w-3.5`}),`Clear offline cache`]})})]})]})]}),n.enabled&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(IA,{title:`Pinned scopes`,description:`A pinned scope — a workspace, or one of its tree paths — is downloaded up front and never evicted. Scopes resolve fresh on every re-warm, so moved contexts and reorganized trees are picked up; documents that left a scope return to normal eviction.`}),(0,Z.jsx)(`div`,{className:`mb-3`,children:(0,Z.jsxs)(Y,{size:`sm`,onClick:()=>_(!0),disabled:!!Object.keys(f).length,children:[(0,Z.jsx)(tr,{className:`mr-1.5 h-3.5 w-3.5`}),`Pin a path…`]})}),(0,Z.jsxs)(`ul`,{className:`space-y-1`,children:[u.map(e=>{let t=f[e.id];return(0,Z.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,Z.jsxs)(`span`,{className:`flex-1 truncate font-mono text-xs sm:text-sm`,children:[e.workspaceRef,`://`,e.path.replace(/^\//,``),e.treeName&&e.treeName!==`context`&&(0,Z.jsx)(`span`,{className:`ml-1.5 rounded bg-muted px-1 py-0.5 font-sans text-[10px] text-muted-foreground`,children:e.treeName})]}),t?(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Ti,{className:`h-3.5 w-3.5 animate-spin`}),t.total>0?`${t.done}/${t.total} · ${NA(t.bytes)}`:`listing…`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[NA(e.bytes),e.truncated?` (partial)`:``]}),(0,Z.jsx)(Y,{variant:`ghost`,size:`sm`,onClick:()=>C(T(e)),"aria-label":`Re-warm ${e.id}`,title:`Re-warm: re-resolve the scope and download anything new`,children:(0,Z.jsx)(Er,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(Y,{variant:`ghost`,size:`sm`,onClick:()=>E(e.id),"aria-label":`Unpin ${e.id}`,children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]})]},e.id)}),u.length===0&&(0,Z.jsx)(`li`,{className:`rounded-md border border-dashed border-input px-3 py-4 text-center text-sm text-muted-foreground`,children:`Nothing pinned — everything relies on browse-caching and LRU`})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(IA,{title:`Workspace caching`,description:`Excluded workspaces are never cached — not even as you browse — and are not served from cache.`}),(0,Z.jsx)(`ul`,{className:`space-y-1`,children:c.map(e=>{let t=n.excludedWorkspaces.includes(e);return(0,Z.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,Z.jsx)(`span`,{className:K(`flex-1 truncate`,t&&`text-muted-foreground line-through`),children:e}),t&&(0,Z.jsx)(ya,{className:`h-3.5 w-3.5 text-muted-foreground`}),(0,Z.jsx)(Y,{variant:t?`outline`:`ghost`,size:`sm`,onClick:()=>x(e),children:t?`Include`:`Exclude`})]},e)})})]})]}),g&&(0,Z.jsx)(Le,{onClose:()=>_(!1),children:(0,Z.jsx)(y,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,multiple:!1,tabs:[`context`,`directory`],title:`Pin for offline…`,confirmLabel:`Pin path`,onConfirm:w,onClose:()=>_(!1)})})]}):null}function IA({title:e,description:t}){return(0,Z.jsxs)(`div`,{className:`mb-4`,children:[(0,Z.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function LA(){return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(sw,{className:`mb-6`,title:`Offline`,onBack:yD(),description:`Per-device offline cache: browse notes, files, photos and saved websites without a connection.`}),(0,Z.jsx)(FA,{})]})}function RA(e){let t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60);return t>0?`${t}d ${n}h ${r}m`:n>0?`${n}h ${r}m`:`${r}m`}function zA({name:e,version:t,detail:n}){return(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 px-4 py-2.5`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium truncate`,children:e}),n&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate`,children:n})]}),(0,Z.jsx)(`code`,{className:`text-xs text-muted-foreground shrink-0`,children:t})]})}function BA(){let[e,t]=(0,X.useState)(null),[n,r]=(0,X.useState)(null);(0,X.useEffect)(()=>{let e=!0;return J.get(`/ping`,{skipAuth:!0}).then(n=>{e&&t(n??{})}).catch(t=>{e&&r(t instanceof Error?t.message:`Failed to reach the server`)}),()=>{e=!1}},[]);let i=[e?.commit?`commit ${e.commit.slice(0,7)}`:null,typeof e?.uptime==`number`?`up ${RA(e.uptime)}`:null].filter(Boolean).join(` · `),a=Object.entries(e?.components??{}).sort(([e],[t])=>e.localeCompare(t));return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(sw,{className:`mb-6`,title:`About`,onBack:yD(),description:`Versions of every Canvas component this installation is running.`}),(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsxs)(`section`,{className:`rounded-md border border-border divide-y divide-border`,children:[(0,Z.jsx)(zA,{name:`Canvas Web`,detail:`this interface`,version:`v2.26.17`}),e?.version&&(0,Z.jsx)(zA,{name:e.productName||e.appName||`Canvas Server`,detail:i||void 0,version:`v${e.version}`})]}),a.length>0&&(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(`h2`,{className:`mb-2 px-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:`Server components`}),(0,Z.jsx)(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:a.map(([e,t])=>(0,Z.jsx)(zA,{name:e,version:`v${t}`},e))})]}),n&&(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Server details unavailable: `,n]}),e?.sourceUrl&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[e.license?`Licensed ${e.license}. `:``,(0,Z.jsx)(`a`,{href:e.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})]})]})}var VA=[`onnx`,`clip`,`blip`,`openai`],HA=[`onnx`,`clip`,`blip`,`ollama`,`vllm`],UA=[{id:`openai`,baseUrl:`https://api.openai.com/v1`,label:`OpenAI`},{id:`vllm`,baseUrl:`http://127.0.0.1:8000/v1`,label:`vLLM`},{id:`ollama`,baseUrl:`http://127.0.0.1:11434/v1`,label:`Ollama`}],WA=e=>`${no.workspaces}/${encodeURIComponent(e)}/inferd`;function GA(e,t){let n={};for(let[r,i]of Object.entries(e.providers||{})){let e={...i};delete e.apiKeySet,delete e.headerNames,t.has(r)&&i.apiKey?e.apiKey=i.apiKey:delete e.apiKey,n[r]=e}return{...e,providers:n}}async function KA(e){return await J.get(`${WA(e)}/status`)}async function qA(e,t={}){let n={};return t.force!==void 0&&(n.force=t.force),await J.post(`${WA(e)}/summarize/images`,n)}async function JA(e){return await J.post(`${WA(e)}/summarize/images/stop`,{})}async function YA(e){return await J.get(`${WA(e)}/config`)}async function XA(e,t){return await J.put(`${WA(e)}/config`,t)}async function ZA(e,t={}){let n={};return t.space&&(n.space=t.space),t.reindex!==void 0&&(n.reindex=t.reindex),t.scope&&(n.scope=t.scope),await J.post(`${WA(e)}/reindex`,n)}async function QA(e){return await J.get(`${WA(e)}/vector-tables`)}async function $A(e,t){return await J.delete(`${WA(e)}/vector-tables/${encodeURIComponent(t)}`)}async function ej(){return await J.get(`${no.inferd}/config`)}async function tj(e){return await J.put(`${no.inferd}/config`,e)}async function nj(){return await J.get(`${no.inferd}/defaults`)}async function rj(e){return await J.put(`${no.inferd}/defaults`,e)}async function ij(e,t){let n={...e};return delete n.apiKeySet,delete n.headerNames,(await J.post(`${no.inferd}/test`,{provider:n,...t?{model:t}:{},probe:!0})).cached??null}async function aj(e,t,n=`text`){let r={...e};return delete r.apiKeySet,delete r.headerNames,await J.post(`${no.inferd}/test`,{provider:r,...t?{model:t}:{},modality:n})}var oj=`h-8 w-full rounded-md border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring`,sj=`font-semibold uppercase tracking-[0.08em]`,cj={openai:{url:{key:`baseUrl`,label:`Base URL`,placeholder:`http://gpu.local:8000/v1`,hint:`OpenAI-compatible embeddings endpoint — Ollama, vLLM, TEI, infinity, LM Studio and OpenAI itself all speak this. A trailing /v1 is optional; both http://host:8000 and http://host:8000/v1 work.`},apiKey:"Sent as `Authorization: Bearer …`. Leave empty for servers that do not check it.",imageInput:!0,timeoutMs:!0,headers:!0,where:e=>e.baseUrl||`no endpoint set`},ollama:{url:{key:`host`,label:`Host (legacy)`,placeholder:`http://127.0.0.1:11434`,hint:`Written by an older version. Switch the type to openai — the host becomes the base URL and the /v1 suffix is added for you.`},apiKey:"Sent as `Authorization: Bearer …`.",where:e=>e.host||`http://127.0.0.1:11434`},onnx:{cacheDir:`Where downloaded weights are cached on the server. Empty uses the server default.`,note:`Runs in-process on the server. No endpoint and no credentials.`,where:()=>`in-process`},clip:{cacheDir:`Where downloaded weights are cached on the server. Empty uses the server default.`,note:`Runs in-process on the server. No endpoint and no credentials.`,where:()=>`in-process`}},lj=[`baseUrl`,`host`,`apiKey`,`cacheDir`,`imageInput`,`timeoutMs`],uj=[{value:`data-uri`,label:`data-uri (default)`,hint:"Images ride in the ordinary `input` array as data URIs (infinity, TEI-style servers)."},{value:`messages`,label:`messages`,hint:`vLLM's multimodal shape: one request per image, wrapped in a chat message.`}],dj=12e4;function fj(e){if(typeof e!=`string`||e.trim()===``)return null;let t;try{t=new URL(e.trim())}catch{return`Must be an absolute URL including the scheme, e.g. http://127.0.0.1:11434`}return t.protocol!==`http:`&&t.protocol!==`https:`?`Unsupported scheme '${t.protocol.replace(`:`,``)}'. Use http or https.`:null}function pj({title:e,hint:t}){return(0,Z.jsxs)(`div`,{className:`mb-2`,children:[(0,Z.jsx)(`h3`,{className:K(`text-[11px] text-muted-foreground`,sj),children:e}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:t})]})}function mj({overridden:e,source:t}){return e?(0,Z.jsx)(`span`,{className:`rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary`,title:`Set on this layer; it wins over anything inherited`,children:`overridden`}):(0,Z.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground`,title:t?`Inherited: ${t}`:`Inherited from a lower config layer`,children:`inherited`})}function hj({label:e,value:t,inheritedValue:n,onChange:r,type:i=`text`,placeholder:a,disabled:o,hint:s,error:c,mono:l}){let u=t!==void 0&&t!==``;return(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:e}),(0,Z.jsx)(mj,{overridden:u,source:n===void 0?void 0:String(n)}),u&&!o&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(``),className:`text-[10px] text-muted-foreground underline hover:text-foreground`,title:`Clear the override and fall back to the inherited value`,children:`reset`})]}),(0,Z.jsx)(q,{type:i,value:t??``,disabled:o,onChange:e=>r(e.target.value),placeholder:a??(n===void 0?`—`:String(n)),className:K(`h-8 text-sm`,l&&`font-mono`,c&&`border-destructive focus-visible:ring-destructive`)}),c&&(0,Z.jsx)(`p`,{className:`text-[11px] font-medium text-destructive`,children:c}),s&&(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:s})]})}function gj({label:e,checked:t,overridden:n,disabled:r,onChange:i}){return(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,disabled:r,checked:t,onChange:e=>i(e.target.checked)}),e,(0,Z.jsx)(mj,{overridden:n})]})}function _j({storedNames:e,value:t,disabled:n,onChange:r}){let i=t!==void 0,[a,o]=(0,X.useState)([]),s=e=>{o(e),r(Object.fromEntries(e.filter(([e])=>e.trim()!==``)))};return(0,Z.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Custom headers`}),i?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will replace stored`}),!n&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{o([]),r(void 0)},className:`text-[10px] text-muted-foreground underline hover:text-foreground`,children:`cancel`})]}):(0,Z.jsx)(mj,{overridden:!1,source:e?.join(`, `)})]}),!i&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e?.length?(0,Z.jsxs)(Z.Fragment,{children:[`Stored: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:e.join(`, `)}),` (values are never sent back)`]}):`None set.`}),!n&&(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>{o([[``,``]]),r({})},children:e?.length?`Replace headers`:`Add headers`})]}),i&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Saving replaces every stored header, so re-enter the ones you want to keep.`}),a.map(([e,t],r)=>(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:e,disabled:n,placeholder:`X-Tenant`,className:`h-8 font-mono text-sm`,onChange:e=>s(a.map((t,n)=>n===r?[e.target.value,t[1]]:t))}),(0,Z.jsx)(q,{value:t,disabled:n,placeholder:`value`,className:`h-8 font-mono text-sm`,onChange:e=>s(a.map((t,n)=>n===r?[t[0],e.target.value]:t))}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,disabled:n,"aria-label":`Remove header ${e||r+1}`,onClick:()=>s(a.filter((e,t)=>t!==r)),children:(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`})})]},r)),!n&&(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>s([...a,[``,``]]),children:[(0,Z.jsx)(br,{className:`mr-1.5 h-3.5 w-3.5`}),`Add header`]})]})]})}function vj({open:e,onClick:t,label:n}){return(0,Z.jsx)(`button`,{type:`button`,onClick:t,"aria-expanded":e,title:n,"aria-label":n,className:`flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:(0,Z.jsx)(qr,{className:K(`h-4 w-4 transition-transform motion-reduce:transition-none`,e&&`rotate-180`)})})}var yj={configured:`bg-success`,"needs-fill":`bg-warning`,unresolved:`bg-destructive`,unset:`bg-muted-foreground/30`};function bj({value:e,effective:t,inherited:n,resolvedSpaces:r,invalid:i,attention:a,onFill:o,saving:s=!1,disabled:c=!1,saveLabel:l=`Save`,onSave:u}){let{showToast:d}=wo(),[f,p]=(0,X.useState)(()=>structuredClone(e)),[m,h]=(0,X.useState)(new Set),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(``),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)(null),E=(0,X.useMemo)(()=>[...new Set([...Object.keys(t.spaces||{}),...Object.keys(f.spaces||{})])].sort(),[t.spaces,f.spaces]),D=(0,X.useMemo)(()=>[...new Set([...Object.keys(t.providers||{}),...Object.keys(f.providers||{})])].sort(),[t.providers,f.providers]),O=(e,t,n)=>{p(r=>{let i={...r.spaces||{}},a={...i[e]||{}};if(n===``)delete a[t];else if(t===`dim`||t===`maxLength`||t===`dimensions`){let e=Number(n);if(Number.isNaN(e))return r;a[t]=e}else a[t]=n;return Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,spaces:i}})},k=(e,t,n)=>{p(r=>{let i={...r.spaces||{}},a={...i[e]||{}};return n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,spaces:i}})},A=(e,t,n)=>{t===`apiKey`&&h(t=>{let r=new Set(t);return n===``?r.delete(e):r.add(e),r}),p(r=>{let i={...r.providers||{}},a={...i[e]||{}};if(n===``)delete a[t];else if(t===`timeoutMs`){let e=Number(n);if(Number.isNaN(e))return r;a[t]=e}else a[t]=n;return Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,providers:i}})},j=(e,t,n)=>{p(r=>{let i={...r.providers||{}},a={...i[e]||{}};return n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,providers:i}})},M=e=>{p(t=>{let n={...t.providers||{}};return delete n[e],{...t,providers:n}}),h(t=>{let n=new Set(t);return n.delete(e),n})},N=()=>{let e=S.trim();if(e){if(E.includes(e)){d({title:`Space exists`,description:`'${e}' already has a row below.`,variant:`destructive`});return}p(t=>({...t,spaces:{...t.spaces||{},[e]:{}}})),C(``),T(`space:${e}`)}},P=(e,t)=>{if(e){if(D.includes(e)){d({title:`Backend exists`,description:`'${e}' is already declared. Open it below to edit.`,variant:`destructive`});return}p(n=>({...n,providers:{...n.providers||{},[e]:{type:`openai`,...t?{baseUrl:t}:{}}}})),x(``),T(`provider:${e}`)}},ee=e=>({...t.providers?.[e]||{},...f.providers?.[e]||{}}),F=async e=>{let n=f.spaces?.[e]?.provider??t.spaces?.[e]?.provider,r=f.spaces?.[e]?.model??t.spaces?.[e]?.model;if(!n){d({title:`No backend`,description:`Space '${e}' has no backend to test.`,variant:`destructive`});return}let i=ee(n),a=i.type?cj[i.type]?.url?.key:void 0,o=a?fj(i[a]):null;if(o){d({title:`Backend '${n}'`,description:o,variant:`destructive`});return}_(e);try{try{await ij(i,r)===!1&&(y(!0),d({title:`Downloading model`,description:`'${r??`the configured model`}' is not in the server's cache yet; downloading now. A first test can take a few minutes; the model is then cached for good.`}))}catch{}let n=await aj(i,r,e),a=f.spaces?.[e]?.dim??t.spaces?.[e]?.dim,o=n.dim>0&&a!==void 0&&n.dim!==a;(o||n.dim>0&&a===void 0)&&O(e,`dim`,String(n.dim)),d({title:o?`Backend answered; dimensions corrected`:`Backend answered`,description:o?`Returned ${n.dim}-d but '${e}' was set to ${a}-d. Dimensions updated to ${n.dim}; save to apply. (${n.latencyMs} ms)`:`${n.dim}-d in ${n.latencyMs} ms`})}catch(e){d({title:`Test failed`,description:e instanceof Error?e.message:`Backend unreachable`,variant:`destructive`})}finally{_(null),y(!1)}},I=(0,X.useMemo)(()=>{let e=[];for(let[n,r]of Object.entries(f.providers||{})){let i=r.type??t.providers?.[n]?.type,a=i?cj[i]?.url?.key:void 0;if(!a)continue;let o=fj(r[a]);o&&e.push(`${n}: ${o}`)}return e},[f.providers,t.providers]),te=(0,X.useMemo)(()=>JSON.stringify(f)!==JSON.stringify(e)||m.size>0,[f,e,m]),L=async()=>{if(I.length>0){d({title:`Fix the endpoint first`,description:I.join(` · `),variant:`destructive`});return}await u(GA(f,m)),h(new Set)},R=e=>T(t=>t===e?null:e);return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[i&&(0,Z.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive-subtle p-3 text-xs`,children:[(0,Z.jsx)(dr,{className:`mt-0.5 h-4 w-4 shrink-0 text-destructive`}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Stored config does not resolve; defaults are standing in`}),(0,Z.jsx)(`p`,{className:`mt-0.5 font-mono text-[11px] text-muted-foreground`,children:i})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(pj,{title:`Search models`,hint:`Choose a provider and model for each kind of content. After switching models, fill the new index to make existing documents searchable. Previous model indexes are preserved.`}),E.length===0?(0,Z.jsxs)(`div`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:`No spaces on this layer`}),(0,Z.jsx)(`p`,{className:`mx-auto mt-1 max-w-sm text-xs text-muted-foreground`,children:`A space needs a backend, a model and a dimension count. Add one below to start embedding.`})]}):(0,Z.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:E.map(e=>{let s=f.spaces?.[e]||{},l=t.spaces?.[e]||{},u=n.spaces?.[e]||{},d=r?.[e],p=`space:${e}`,m=w===p,h=s.model??l.model,_=s.provider??l.provider,y=s.dim??l.dim,b=s.chunk??l.chunk??!1,x=a?.includes(e)??!1;return(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(`span`,{className:K(`absolute inset-y-0 left-0 w-[3px]`,yj[i?`unresolved`:x?`needs-fill`:h?`configured`:`unset`]),"aria-hidden":!0}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 py-3 pl-4 pr-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,Z.jsx)(`span`,{className:K(`text-[11px]`,sj),children:e}),(0,Z.jsx)(`span`,{className:`truncate font-mono text-sm`,children:h||`no model set`}),_&&(0,Z.jsxs)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground`,children:[`via `,_]}),y!==void 0&&(0,Z.jsxs)(`span`,{className:`text-xs tabular-nums text-muted-foreground`,children:[y,`-d`]}),b&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`chunked`})]}),r&&h&&(0,Z.jsxs)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,title:`Vector table backing this space`,children:[`└─ `,d?.table??(0,Z.jsx)(`span`,{className:`not-italic`,children:`not created yet`})]}),x&&(0,Z.jsx)(`p`,{className:`mt-1 text-[11px] text-warning`,children:`New table, nothing embedded in it yet; dense search stays thin for this space until it is filled. Reverting the model is still instant.`})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[x&&o&&(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>o(e),children:`Fill`}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,disabled:c||g!==null,onClick:()=>F(e),title:`Round-trip a real embedding call against this backend and report the dimensions it returns`,children:[(0,Z.jsx)(lr,{className:`mr-1.5 h-3.5 w-3.5`}),g===e?v?`Downloading…`:`Testing…`:`Test`]}),(0,Z.jsx)(vj,{open:m,onClick:()=>R(p),label:`Edit ${e}`})]})]}),m&&(0,Z.jsxs)(`div`,{className:`border-t bg-muted/40 py-4 pl-4 pr-3`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Backend`}),(0,Z.jsx)(mj,{overridden:s.provider!==void 0,source:u.provider})]}),(0,Z.jsxs)(`select`,{className:oj,disabled:c,value:s.provider??``,onChange:t=>O(e,`provider`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:l.provider?`inherited: ${l.provider}`:`inherited`}),D.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Z.jsx)(hj,{label:`Model`,mono:!0,value:s.model,inheritedValue:l.model,onChange:t=>O(e,`model`,t),disabled:c}),(0,Z.jsx)(hj,{label:`Dimensions`,type:`number`,value:s.dim,inheritedValue:l.dim,onChange:t=>O(e,`dim`,t),disabled:c,hint:`Sizes the vector table. Test asks the backend and fills in what it really returns.`}),(0,Z.jsx)(hj,{label:`Max length`,type:`number`,value:s.maxLength,inheritedValue:l.maxLength,onChange:t=>O(e,`maxLength`,t),disabled:c})]}),(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-4`,children:[(0,Z.jsx)(gj,{label:`Chunk long inputs`,checked:b,overridden:s.chunk!==void 0,disabled:c,onChange:t=>k(e,`chunk`,t)}),(0,Z.jsx)(gj,{label:`Build ANN index`,checked:s.annIndex??l.annIndex??!0,overridden:s.annIndex!==void 0,disabled:c,onChange:t=>k(e,`annIndex`,t)})]})]})]},e)})}),!c&&(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{value:S,onChange:e=>C(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),N())},placeholder:`new space name (e.g. audio)`,className:`h-8 w-full max-w-xs text-sm sm:w-auto`}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:N,children:[(0,Z.jsx)(br,{className:`mr-1.5 h-3.5 w-3.5`}),`Add space`]})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(pj,{title:`Model providers`,hint:`Connect a service here, then select it under Search models above. Built-in providers work without an extra connection. Provider changes take effect when you save.`}),(0,Z.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:D.map(e=>{let n=f.providers?.[e]||{},r=t.providers?.[e]||{},i=HA.includes(e),a=f.providers?.[e]!==void 0,o=`provider:${e}`,s=w===o,l=n.type??r.type,u=l?cj[l]:void 0,d=u?.url?fj(n[u.url.key]):null,p={...r,...n},h=lj.filter(e=>!(n[e]===void 0||e===u?.url?.key||e===`apiKey`&&u?.apiKey||e===`cacheDir`&&u?.cacheDir)),g=E.filter(n=>(f.spaces?.[n]?.provider??t.spaces?.[n]?.provider)===e);return(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 px-4 py-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,Z.jsx)(`span`,{className:`font-mono text-sm font-semibold`,children:e}),(0,Z.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:l??`no type`}),i&&(0,Z.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:`built-in`}),p.apiKeySet&&!m.has(e)&&(0,Z.jsx)(`span`,{className:`text-[10px] font-medium text-success`,children:`key set`}),d&&(0,Z.jsx)(`span`,{className:`text-[10px] font-medium text-destructive`,children:`check endpoint`})]}),(0,Z.jsx)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,children:u?u.where(p):`—`}),g.length>0&&(0,Z.jsxs)(`p`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`used by `,g.join(`, `)]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[a&&!i&&!c&&(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>M(e),title:`Remove this override`,children:(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(vj,{open:s,onClick:()=>R(o),label:`Edit ${e}`})]})]}),s&&(0,Z.jsxs)(`div`,{className:`border-t bg-muted/40 px-4 py-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Type`}),(0,Z.jsx)(mj,{overridden:n.type!==void 0,source:r.type})]}),(0,Z.jsxs)(`select`,{className:oj,disabled:c,value:n.type??``,onChange:t=>A(e,`type`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:r.type?`inherited: ${r.type}`:`inherited`}),VA.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e)),l&&!VA.includes(l)&&(0,Z.jsxs)(`option`,{value:l,children:[l,` (legacy)`]})]}),u?.note&&(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:u.note})]}),u?.url&&(0,Z.jsx)(hj,{label:u.url.label,mono:!0,value:n[u.url.key],inheritedValue:r[u.url.key],onChange:t=>A(e,u.url.key,t),disabled:c,placeholder:r[u.url.key]??u.url.placeholder,hint:u.url.hint,error:d??void 0}),u?.cacheDir&&(0,Z.jsx)(hj,{label:`Cache directory`,mono:!0,value:n.cacheDir,inheritedValue:r.cacheDir,onChange:t=>A(e,`cacheDir`,t),disabled:c,placeholder:r.cacheDir??`server default`,hint:u.cacheDir}),u?.imageInput&&(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Image input shape`}),(0,Z.jsx)(mj,{overridden:n.imageInput!==void 0,source:r.imageInput})]}),(0,Z.jsxs)(`select`,{className:oj,disabled:c,value:n.imageInput??``,onChange:t=>A(e,`imageInput`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:r.imageInput?`inherited: ${r.imageInput}`:`inherited: data-uri`}),uj.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:uj.find(e=>e.value===(n.imageInput??r.imageInput??`data-uri`))?.hint})]}),u?.timeoutMs&&(0,Z.jsx)(hj,{label:`Request timeout (ms)`,type:`number`,value:n.timeoutMs,inheritedValue:r.timeoutMs??dj,onChange:t=>A(e,`timeoutMs`,t),disabled:c,hint:`How long to wait for a batch before giving up. Raise it for a slow or cold GPU host.`}),u?.apiKey&&(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`API key`}),m.has(e)&&(0,Z.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will be written`})]}),(0,Z.jsx)(q,{type:`password`,autoComplete:`new-password`,disabled:c,value:n.apiKey??``,onChange:t=>A(e,`apiKey`,t.target.value),placeholder:r.apiKeySet?`•••••••• (stored; leave empty to keep)`:`unset`,className:`h-8 text-sm`}),(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[u.apiKey,` Write-only: the stored key is never sent back, and leaving this empty keeps whatever is stored.`]})]})]}),u?.headers&&(0,Z.jsx)(_j,{disabled:c,storedNames:r.headerNames,value:n.headers,onChange:t=>j(e,`headers`,t)}),h.length>0&&!c&&(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2 rounded-md border border-dashed p-2 text-[11px] text-muted-foreground`,children:[(0,Z.jsxs)(`span`,{children:[`Not used by type `,(0,Z.jsx)(`span`,{className:`font-mono`,children:l}),`:`,` `,(0,Z.jsx)(`span`,{className:`font-mono`,children:h.join(`, `)})]}),(0,Z.jsx)(`button`,{type:`button`,className:`underline hover:text-foreground`,onClick:()=>h.forEach(t=>A(e,t,``)),children:`clear`})]}),r.headerNames&&r.headerNames.length>0&&(0,Z.jsxs)(`p`,{className:`mt-3 text-[11px] text-muted-foreground`,children:[`Stored custom headers: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:r.headerNames.join(`, `)}),` (values not shown)`]})]})]},e)})}),!c&&(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{value:b,onChange:e=>x(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),P(b.trim()))},placeholder:`new backend name (e.g. gpu)`,className:`h-8 w-full max-w-xs text-sm sm:w-auto`}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>P(b.trim()),children:[(0,Z.jsx)(br,{className:`mr-1.5 h-3.5 w-3.5`}),`Add backend`]}),UA.filter(e=>!D.includes(e.id)).map(e=>(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>P(e.id,e.baseUrl),title:`Add an openai-type backend '${e.id}' pointed at ${e.baseUrl}`,children:e.label},e.id))]})]}),!c&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t pt-4`,children:[(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:te?`default`:`outline`,onClick:L,disabled:s||!te||I.length>0,children:s?`Saving…`:l}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,disabled:s||!te,onClick:()=>{p(structuredClone(e)),h(new Set)},children:`Discard changes`}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:I.length>0?(0,Z.jsxs)(`span`,{className:`font-medium text-destructive`,children:[I.length,` endpoint `,I.length===1?`needs`:`need`,` fixing`]}):te?`Unsaved changes`:`Everything saved`})]})]})}function xj(){let{showToast:e}=wo(),[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!0),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),l=(0,X.useCallback)(()=>ej().then(e=>{n(e),c(null)}).catch(e=>c(e instanceof Error?e.message:`Failed to load embedding defaults`)).finally(()=>i(!1)),[]);(0,X.useEffect)(()=>{l()},[l]);let u=()=>{i(!0),l()};return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl p-6`,children:[(0,Z.jsx)(sw,{compact:!0,className:`mb-6`,title:`Search & AI defaults`,onBack:yD(),description:`Your account · Choose the embedding models used for text and image search. Workspace settings override these defaults. Running workspaces adopt new defaults when restarted.`,actions:(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:u,disabled:r,children:[(0,Z.jsx)(Er,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})}),r?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(Er,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):s||!t?(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`rounded-md border border-destructive/40 bg-destructive/5 p-4 text-sm`,children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Embedding defaults unavailable`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s||`No config returned.`})]}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:u,children:`Retry`})]}):(0,Z.jsx)(bj,{value:t.user||{},effective:t.effective||{},inherited:t.serverDefaults||{},invalid:t.invalid,saving:a,saveLabel:`Save defaults`,onSave:async t=>{o(!0);try{let n=await tj(t);e({title:`Defaults saved`,description:n.restartRequired?`${n.workspaces.length} running workspace(s) keep their current tables until restarted. Set the config on a workspace directly to change it live.`:`New workspaces will inherit this.`}),await l()}catch(t){e({title:`Save failed`,description:t instanceof Error?t.message:`Failed to save`,variant:`destructive`})}finally{o(!1)}}},JSON.stringify(t.user))]})}function Sj(){let e=vn(),{showToast:t}=wo(),n=new URLSearchParams(e.search),r=e=>{try{let t=new URL(e);return t.pathname.includes(`/rest/v2/workspaces/`)&&!t.pathname.includes(`/rest/v2/pub/`)?t.pathname=t.pathname.replace(`/rest/v2/workspaces/`,`/rest/v2/pub/workspaces/`):t.pathname.includes(`/rest/v2/contexts/`)&&!t.pathname.includes(`/rest/v2/pub/`)&&(t.pathname=t.pathname.replace(`/rest/v2/contexts/`,`/rest/v2/pub/contexts/`)),t.toString()}catch{return e}},i=r(n.get(`url`)||``),a=sessionStorage.getItem(`sharedToken:last`)||``,[o,s]=(0,X.useState)(i),[c,l]=(0,X.useState)(a),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)([]),[m,h]=(0,X.useState)(!1),g=(0,X.useMemo)(()=>{try{let e=new URL(o);return e.pathname.includes(`/pub/workspaces/`)?`workspace`:e.pathname.includes(`/pub/contexts/`)?`context`:`unknown`}catch{return`unknown`}},[o]),_=()=>({Authorization:`Bearer ${c.trim()}`}),v=async()=>{if(!(!o||!c)){h(!0);try{let e=r(o),t=await J.get(e,{skipAuth:!0,headers:_()});d(t);let n=await J.get(`${e}/documents`,{skipAuth:!0,headers:_()}),i=Array.isArray(n)?n:Array.isArray(n?.data)?n.data:[];p(Array.isArray(i)?i:[])}catch(e){let n=o.includes(`/rest/v2/workspaces/`)?`Ensure the URL uses /rest/v2/pub/workspaces/<workspace-id> and the token matches that workspace.`:o.includes(`/rest/v2/contexts/`)?`Ensure the URL uses /rest/v2/pub/contexts/<context-id>.`:void 0;t({title:`Error`,description:`${e instanceof Error?e.message:`Failed to load shared resource`}${n?`: ${n}`:``}`,variant:`destructive`}),d(null),p([])}finally{h(!1)}}},y=(0,X.useRef)(v);return(0,X.useEffect)(()=>{y.current()},[]),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(sw,{onBack:yD(),title:`Shared Resource Viewer`,description:`Open a resource someone shared with you.`}),(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`Full pub URL`}),(0,Z.jsx)(q,{value:c,onChange:e=>l(e.target.value),placeholder:`Access token (canvas-...)`}),(0,Z.jsx)(Y,{onClick:v,disabled:m||!o||!c,children:`Load`})]}),(0,Z.jsxs)(`div`,{className:`text-sm text-muted-foreground`,children:[`Type: `,g]}),m?(0,Z.jsx)(`div`,{className:`text-center py-8 text-muted-foreground`,children:`Loading...`}):(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,Z.jsx)(`h2`,{className:`font-semibold mb-2`,children:`Metadata`}),(0,Z.jsx)(`pre`,{className:`text-xs overflow-auto max-h-80`,children:JSON.stringify(u,null,2)})]}),(0,Z.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,Z.jsxs)(`h2`,{className:`font-semibold mb-2`,children:[`Documents (`,f.length,`)`]}),f.length===0?(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`No documents`}):(0,Z.jsx)(`ul`,{className:`space-y-2 text-sm`,children:f.slice(0,100).map((e,t)=>(0,Z.jsxs)(`li`,{className:`border rounded p-2`,children:[(0,Z.jsx)(`div`,{className:`font-mono text-xs`,children:e.id}),(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:e.schema})]},t))})]})]}),(0,Z.jsx)(au,{className:`mt-8`})]})}function Cj(e={}){let t=new URLSearchParams;e.tail&&t.set(`tail`,String(e.tail)),e.level&&t.set(`level`,e.level),e.module&&t.set(`module`,e.module);let n=t.toString();return n?`?${n}`:``}function wj(){let e=localStorage.getItem(`authToken`);if(!e)throw Error(`Authentication required`);let t=localStorage.getItem(`appName`)||window.location.hostname;return{Authorization:`Bearer ${e}`,"X-App-Name":t,Accept:`text/event-stream`}}var Tj={users:{async listUsers(e){let t=new URLSearchParams;e?.status&&t.append(`status`,e.status),e?.userType&&t.append(`userType`,e.userType);let n=t.toString(),r=n?`${no.admin.users}?${n}`:no.admin.users;return await J.get(r)},async getUser(e){return await J.get(`${no.admin.users}/${e}`)},async createUser(e){return await J.post(no.admin.users,e)},async updateUser(e,t){return await J.put(`${no.admin.users}/${e}`,t)},async deleteUser(e){await J.delete(`${no.admin.users}/${e}`)}},workspaces:{async listAllWorkspaces(){return await J.get(no.admin.workspaces)},async createWorkspace(e){return await J.post(no.admin.workspaces,e)},async deleteWorkspace(e){await J.delete(`${no.admin.workspaces}/${e}`)}},logs:{async getLogs(e={}){return(await J.get(`${no.admin.logs}${Cj(e)}`)).logs||[]},async streamLogs(e={},t={}){let{signal:n,onEntry:r,onError:i}=t;try{let t=await fetch(`${no.admin.logsStream}${Cj(e)}`,{method:`GET`,headers:wj(),credentials:`include`,signal:n});if(!t.ok)throw Error(`Failed to open log stream (${t.status})`);if(!t.body)throw Error(`Streaming is not supported by this browser`);let i=t.body.getReader(),a=new TextDecoder,o=``,s=e=>{let t=e.split(`
|
|
31
|
+
`).map(e=>e.trim()).filter(Boolean);for(let e of t){if(!e.startsWith(`data: `))continue;let t=e.slice(6).trim();if(t===`[DONE]`)continue;let n;try{n=JSON.parse(t)}catch{continue}if(n.type===`chunk`)p+=n.delta||``,i?.(n.delta||``,!1,n.metadata||{});else if(n.type===`thinking`)i?.(``,!1,{...n.metadata||{},reasoningDelta:n.delta||``});else if(n.type===`complete`){let e=Array.isArray(n.messages)?[...n.messages].reverse().find(e=>e?.role===`assistant`):null,t=e?.stopReason===`error`,r=zD(e);t&&h(r||`Prompt stream failed`);let a=t?`${p?`
|
|
32
|
+
|
|
33
|
+
`:``}${r||`Prompt stream failed`}`:p?``:r;i?.(a,!0,{...n.metadata||{},...VD(e)||{}})}else n.type===`error`&&h(n.error||`Prompt stream failed`)}}},onError:a,onComplete:o})}async function hO(e,t){let{message:n,onMessage:r,onError:i,onComplete:a,context:o,mcpContext:s,maxTokens:c,temperature:l,images:u}=t;try{let t=await J.post(`${yo}/agents/${e}/prompt`,{message:n,images:u,context:o,mcpContext:s,maxTokens:c,temperature:l}),i=Array.isArray(t.messages)?[...t.messages].reverse().find(e=>e?.role===`assistant`):null,d={content:zD(i),metadata:VD(i)};return r&&r(d.content,!0,d.metadata),a&&a(),d}catch(e){throw i&&i(e),e}}function gO(e){return e.map(e=>({...e,timestamp:typeof e.timestamp==`string`?e.timestamp:new Date().toISOString()}))}async function _O(){return await J.get(`${yo}/voice/status`)}async function vO(e,t,n={}){let r=new FormData,i=(t.type.split(`/`)[1]||`webm`).split(`;`)[0];r.append(`file`,t,`voice.${i}`);let a=new URLSearchParams;n.tts===!1&&a.set(`tts`,`false`),n.voice&&a.set(`voice`,n.voice);let o=a.toString()?`?${a.toString()}`:``;return await J.post(`${yo}/agents/${e}/voice${o}`,r)}function yO(e,t){return J.post(`${yo}/agents/models`,e,{signal:t})}var bO=[{id:`workspace`,label:`Workspace`,path:`workspaces`,description:`Files, search, devices and sharing for one workspace. These settings override account defaults.`,sections:kD,load:async()=>(await Uo()).map(e=>({id:e.name,label:e.label||e.name}))},{id:`context`,label:`Context`,path:`contexts`,description:`Choose the tree and path a context opens, and who can access that view. File storage belongs to its workspace.`,sections:MD,load:async()=>(await ml()).map(e=>({id:e.id,label:e.name||e.id}))},{id:`agent`,label:`Agent`,path:`agents`,description:`Configure one assistant: its instructions, chat model, tools and access to Canvas.`,sections:PD,load:async()=>(await ZD()).map(e=>({id:e.id,label:e.label||e.name}))}];function xO({to:e,label:t,description:n,icon:r}){return(0,Z.jsxs)(we,{to:e,className:`group flex items-start gap-3 rounded-lg border bg-card p-4 transition-colors hover:border-primary/50 hover:bg-accent/30 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary`,children:[(0,Z.jsx)(r,{className:`mt-0.5 h-5 w-5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-semibold`,children:t}),(0,Z.jsx)(`span`,{className:`mt-1 block text-sm leading-relaxed text-muted-foreground`,children:n})]}),(0,Z.jsx)(xi,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground group-hover:text-primary`})]})}function SO({group:e,query:t}){let[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(`loading`),[c,l]=(0,X.useState)(0);(0,X.useEffect)(()=>{let t=!1;return e.load().then(e=>{t||(r(e),s(`ready`))}).catch(()=>{t||s(`error`)}),()=>{t=!0}},[e,c]);let u=e.sections.filter(n=>wC(t,e.label,n.label,n.description));return u.length?(0,Z.jsxs)(`section`,{id:e.id,className:`scroll-mt-6 space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsxs)(`label`,{className:`block max-w-md text-sm font-medium`,children:[`Choose a `,e.label.toLowerCase(),(0,Z.jsxs)(`select`,{className:`mt-2 h-10 w-full rounded-md border bg-background px-3 text-sm`,value:i,disabled:o!==`ready`||!n.length,onChange:e=>a(e.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:o===`loading`?`Loading…`:o===`error`?`Unable to load list`:n.length?`Select ${e.label.toLowerCase()}…`:`No ${e.path} available`}),n.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),o===`error`&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`The list could not be loaded. `,(0,Z.jsx)(`button`,{type:`button`,className:`underline`,onClick:()=>{s(`loading`),l(e=>e+1)},children:`Retry`})]}),(0,Z.jsxs)(`details`,{open:!!(i||t.trim()),children:[(0,Z.jsx)(`summary`,{className:`cursor-pointer py-2 text-sm text-muted-foreground`,children:i?`Settings for ${n.find(e=>e.id===i)?.label||i}`:`What you can configure (${u.length})`}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:u.map(t=>i?(0,Z.jsx)(xO,{to:`/${e.path}/${encodeURIComponent(i)}/settings/${t.id}`,...t},t.id):(0,Z.jsxs)(`div`,{className:`rounded-lg border border-dashed p-4`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:t.label}),(0,Z.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:t.description})]},t.id))})]})]}):null}function CO(){let{state:e}=qC(),[t,n]=(0,X.useState)(``),r=SC.filter(t=>t.id!==`server`||e.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(n=>wC(t,e.label,n.label,n.description))})).filter(e=>e.items.length),i=bO.some(e=>e.sections.some(n=>wC(t,e.label,n.label,n.description)));return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-6xl space-y-8 pb-8 max-md:pb-rail-stack`,children:[(0,Z.jsx)(sw,{title:`Settings`,description:`Start with what you want to change. Each section explains where your changes apply.`}),(0,Z.jsx)(q,{type:`search`,className:`max-w-xl`,"aria-label":`Search all settings`,placeholder:`Find a setting: offline, folders, models, sharing…`,value:t,onChange:e=>n(e.target.value)}),r.filter(e=>e.id===`device`||e.id===`account`).map(e=>(0,Z.jsxs)(`section`,{className:`space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,Z.jsx)(xO,{to:e.path,...e},e.path))})]},e.id)),bO.map(e=>(0,Z.jsx)(SO,{group:e,query:t},e.id)),r.filter(e=>e.id===`server`||e.id===`information`).map(e=>(0,Z.jsxs)(`section`,{className:`space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,Z.jsx)(xO,{to:e.path,...e},e.path))})]},e.id)),!r.length&&!i&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`No settings match “`,t,`”. Try a shorter phrase or clear the search.`]})]})}var wO=[{id:`canvas_1`,title:`Canvas Deep`,scheme:`dark`,background:`#032940`,accent:`#f2f2f2`,sources:[{type:`image/svg+xml`,src:`files/canvas_1.svg`},{type:`image/avif`,src:`files/canvas_1.avif`},{type:`image/webp`,src:`files/canvas_1.webp`}],thumb:`thumbs/canvas_1.webp`,author:`Canvas`,license:`LicenseRef-Canvas-Brand`},{id:`canvas_3`,title:`Canvas Mono Dark`,scheme:`dark`,background:`#000000`,accent:`#ffffff`,sources:[{type:`image/svg+xml`,src:`files/canvas_3.svg`},{type:`image/avif`,src:`files/canvas_3.avif`},{type:`image/webp`,src:`files/canvas_3.webp`}],thumb:`thumbs/canvas_3.webp`,author:`Canvas`,license:`LicenseRef-Canvas-Brand`},{id:`w1`,title:`Frost`,scheme:`dark`,background:`#164a6f`,accent:`#9ad9f0`,sources:[{type:`image/avif`,src:`files/w1.avif`},{type:`image/webp`,src:`files/w1.webp`},{type:`image/jpeg`,src:`files/w1.jpg`}],thumb:`thumbs/w1.webp`,author:`Peter Cui Bide`,source:`https://petercui.deviantart.com`,license:`LicenseRef-Attribution-Only`}],TO=`/wallpapers`;function EO(e){return wO.find(t=>t.id===e)}function DO(e,t={}){let n=typeof e==`string`?EO(e):e;if(!n)return null;let{base:r=TO,types:i}=t,a=(i?n.sources.find(e=>i.includes(e.type)):n.sources[0])??n.sources[n.sources.length-1];return`${r.replace(/\/$/,``)}/${a.src}`}function OO(e,t=TO){let n=typeof e==`string`?EO(e):e;return n?`${t.replace(/\/$/,``)}/${n.thumb}`:null}var kO=[{id:`cover`,label:`Scale and Crop`,description:`Fills the screen, cropping edges as needed`},{id:`fill`,label:`Fill`,description:`Stretches to the exact screen size`},{id:`center`,label:`Centered`,description:`Original size, centered on the desk`}],AO=`canvas:wallpaper`,jO=`canvas-wallpaper`,MO=`settings`,NO=`builtin:`,PO=wO;function FO(e){return OO(e)??``}function IO(e){return`${NO}${e}`}function LO(e){return e?.startsWith(NO)?e.slice(8):null}function RO(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.image!=`string`&&t.image!==null?null:{image:t.image,fit:t.fit===`fill`||t.fit===`center`?t.fit:`cover`}}function zO(){try{let e=localStorage.getItem(AO);if(e){let t=RO(JSON.parse(e));if(t)return t}}catch{}return{image:null,fit:`cover`}}var BO=zO(),VO=null;function HO(){return BO}async function UO(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(jO,1),r=!1;n.onupgradeneeded=()=>n.result.createObjectStore(MO),n.onsuccess=()=>{if(r){n.result.close();return}n.result.onversionchange=()=>n.result.close(),e(n.result)},n.onerror=()=>t(n.error),n.onblocked=()=>{r=!0,t(Error(`Close other Canvas tabs and try again.`))}});try{return await new Promise((n,r)=>{let i=t.transaction(MO,e?`readwrite`:`readonly`),a=i.objectStore(MO),o=e?a.put(e,AO):a.get(AO);i.oncomplete=()=>n(o.result),i.onerror=()=>r(i.error),i.onabort=()=>r(i.error)})}finally{t.close()}}function WO(){try{localStorage.removeItem(AO)}catch{}}function GO(){return VO||=(async()=>{try{let e=RO(await UO());e?BO=e:await UO(BO),WO()}catch{}return $O(BO),BO})(),VO.then(()=>BO)}async function KO(e){await GO(),await UO(e),BO=e,WO(),$O(e)}function qO(e){if(e.size>10485760)return Promise.reject(Error(`Image too large. Choose one up to 10 MB.`));let t=e.type||(/\.gif$/i.test(e.name)?`image/gif`:``);return t.startsWith(`image/`)?new Promise((n,r)=>{let i=new FileReader;i.onload=()=>n(String(i.result)),i.onerror=()=>r(Error(`Could not read the image. Try selecting it again.`)),i.onabort=()=>r(Error(`Reading the image was cancelled.`)),i.readAsDataURL(e.type?e:e.slice(0,e.size,t))}):Promise.reject(Error(`Pick an image file (animated GIFs are supported).`))}var JO=typeof CSS<`u`&&CSS.supports(`background-image`,`image-set(url("a.avif") type("image/avif"))`);function YO(e){if(!e)return null;let t=LO(e);if(t===null)return`url("${e}")`;let n=EO(t);if(!n)return null;let r=`url("${DO(n,{types:[n.sources[n.sources.length-1].type]})}")`;return!JO||n.sources.length===1?r:`image-set(${n.sources.map(e=>`url("${DO(n,{types:[e.type]})}") type("${e.type}")`).join(`, `)})`}function XO(e){return e===`fill`?`100% 100%`:e===`center`?`auto`:`cover`}var ZO=null;function QO(e){let t=e.indexOf(`,`);if(t<0)throw Error(`Invalid wallpaper data URL`);let n=e.slice(5,t),r=e.slice(t+1),i;if(n.endsWith(`;base64`)){let e=atob(r);i=new Uint8Array(e.length);for(let t=0;t<e.length;t++)i[t]=e.charCodeAt(t)}else i=new TextEncoder().encode(decodeURIComponent(r));return new Blob([i],{type:n.split(`;`)[0]})}function $O(e=HO()){let t=document.documentElement.style,n=ZO,r=e.image;if(r?.startsWith(`data:`))try{ZO?.dataUrl!==r&&(ZO={dataUrl:r,objectUrl:URL.createObjectURL(QO(r))}),r=ZO.objectUrl}catch{ZO=null,r=null}else ZO=null;let i=YO(r);i?(t.setProperty(`--wallpaper-image`,i),t.setProperty(`--wallpaper-size`,XO(e.fit))):(t.removeProperty(`--wallpaper-image`),t.removeProperty(`--wallpaper-size`)),n&&n!==ZO&&URL.revokeObjectURL(n.objectUrl)}var ek=[{id:`cards`,name:`Cards`,description:`Nested cards with connector lines. Each level indents.`},{id:`accordion-mobile`,name:`Accordion on phones (beta)`,description:`Experimental. Full-width accordion rows on a phone, cards on wider screens.`},{id:`accordion`,name:`Accordion (beta)`,description:`Experimental. Full-width rows at every depth; a depth rail, tint and colour swatch replace the indent, and open parents stick to the top while you scroll.`}],tk=`canvas:treeStyle`;function nk(){try{let e=localStorage.getItem(tk);return e===`accordion`||e===`accordion-mobile`?e:`cards`}catch{return`cards`}}var rk=nk(),ik=new Set;function ak(){return rk}function ok(e){try{e===`cards`?localStorage.removeItem(tk):localStorage.setItem(tk,e)}catch{}rk=e;for(let e of ik)e()}function sk(e){ik.add(e);let t=t=>{(t.key===tk||t.key===null)&&(rk=nk(),e())};return window.addEventListener(`storage`,t),()=>{ik.delete(e),window.removeEventListener(`storage`,t)}}function ck(){return(0,X.useSyncExternalStore)(sk,ak,()=>`cards`)}function lk(){let e=ck(),t=De();return e===`accordion`||e===`accordion-mobile`&&t}var uk=[{id:`canvas`,name:`Canvas`,description:`Black and white with a teal accent. Sheets of paper on a grey desk.`,swatches:[`oklch(1 0 0)`,`oklch(0 0 0)`,`oklch(0.704 0.135 183)`]},{id:`nord`,name:`Nord`,description:`Cool arctic blues, lower contrast, softer corners.`,swatches:[`oklch(0.976 0.006 251)`,`oklch(0.588 0.056 244)`,`oklch(0.686 0.062 213)`]},{id:`contrast`,name:`High Contrast`,description:`WCAG AAA text contrast, square corners, hard borders, no shadows.`,swatches:[`oklch(1 0 0)`,`oklch(0 0 0)`,`oklch(0.32 0.16 258)`]},{id:`frost`,name:`Frosted Glass`,description:`Translucent, blurred surfaces over a soft backdrop. Best with a wallpaper.`,swatches:[`oklch(0.92 0.008 250)`,`oklch(0.31 0.025 255)`,`oklch(0.55 0.05 250)`]},{id:`terminal`,name:`Terminal`,description:`Monospaced and dense. Tighter rows and chrome for large displays.`,swatches:[`oklch(0.17 0.006 152)`,`oklch(0.8 0.19 148)`,`oklch(0.75 0.12 220)`]},{id:`halflife`,name:`Half-Life`,description:`Lambda orange on black steel. Square corners; the left rail is orange.`,swatches:[`oklch(0.724 0.181 52)`,`oklch(0 0 0)`,`oklch(1 0 0)`]}],dk=uk.map(e=>e.id),fk=[{id:`system`,name:`System`},{id:`light`,name:`Light`},{id:`dark`,name:`Dark`}],pk=[{id:`auto`,name:`Auto`,description:`Match the pointer: touch on phones, mouse on desktop`},{id:`compact`,name:`Compact`,description:`Maximum rows per screen`},{id:`comfortable`,name:`Comfortable`,description:`Balanced for mouse use`},{id:`touch`,name:`Touch`,description:`Large targets for finger input`}],mk={theme:`canvas`,scheme:`light`,density:`auto`},hk=`canvas.ui.theme`;function gk(e){return typeof e==`string`&&dk.includes(e)}function _k(e){return e===`light`||e===`dark`||e===`system`}function vk(e){return e===`auto`||e===`compact`||e===`comfortable`||e===`touch`}function yk(e){let t=typeof e==`object`&&e?e:{};return{theme:gk(t.theme)?t.theme:mk.theme,scheme:_k(t.scheme)?t.scheme:mk.scheme,density:vk(t.density)?t.density:mk.density}}var bk=`(prefers-color-scheme: dark)`;function xk(){return typeof document<`u`}function Sk(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(bk).matches}function Ck(e){return e===`system`?Sk()?`dark`:`light`:e}function wk(e){if(typeof window>`u`||typeof window.matchMedia!=`function`)return()=>{};let t=window.matchMedia(bk),n=t=>e(t.matches?`dark`:`light`);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)}function Tk(e){return wk(e)}function Ek(){return Sk()?`dark`:`light`}function Dk(){return`light`}function Ok(e){let t=getComputedStyle(e).getPropertyValue(`--background`).trim();if(!t)return;let n=document.querySelector(`meta[name="theme-color"]`);n||(n=document.createElement(`meta`),n.name=`theme-color`,document.head.appendChild(n)),n.content=t}function kk(e,t=xk()?document.documentElement:void 0){let n=Ck(e.scheme);return t?(t.dataset.theme=e.theme,t.dataset.scheme=n,t.dataset.density=e.density,Ok(t),n):n}function Ak(e,t=xk()?document.documentElement:void 0){if(!t||typeof window>`u`)return kk(e,t);let n=document.createElement(`style`);n.appendChild(document.createTextNode(`*,*::before,*::after{transition:none!important;animation:none!important}`)),document.head.appendChild(n);let r=kk(e,t);return window.getComputedStyle(n).opacity,document.head.removeChild(n),r}function jk(e){let t=e??Pk();if(!t)return mk;try{let e=t.getItem(hk);return e?yk(JSON.parse(e)):mk}catch{return mk}}function Mk(e,t){let n=t??Pk();if(n)try{n.setItem(hk,JSON.stringify(e))}catch{}}function Nk(e){let t=e??Pk();if(t)try{t.removeItem(hk)}catch{}}function Pk(){try{return typeof localStorage<`u`?localStorage:void 0}catch{return}}function Fk({children:e,initial:t,storage:n,persist:r=!0}){let[i,a]=(0,X.useState)(()=>({...jk(n),...t})),o=(0,X.useSyncExternalStore)(Tk,Ek,Dk),s=i.scheme===`system`?o:i.scheme;(0,X.useEffect)(()=>{Ak({...i,scheme:s})},[i,s]),(0,X.useEffect)(()=>{r&&Mk(i,n)},[i,r,n]);let c=(0,X.useCallback)(e=>{a(t=>t.theme===e?t:{...t,theme:e})},[]),l=(0,X.useCallback)(e=>{a(t=>t.scheme===e?t:{...t,scheme:e})},[]),u=(0,X.useCallback)(e=>{a(t=>t.density===e?t:{...t,density:e})},[]),d=(0,X.useCallback)(()=>{a(e=>({...e,scheme:(e.scheme===`system`?Ek():e.scheme)===`dark`?`light`:`dark`}))},[]),f=(0,X.useCallback)(()=>{Nk(n),a(mk)},[n]),p=(0,X.useMemo)(()=>({...i,resolvedScheme:s,setTheme:c,setScheme:l,setDensity:u,toggleScheme:d,reset:f}),[i,s,c,l,u,d,f]);return(0,Z.jsx)(Il.Provider,{value:p,children:e})}var Ik={system:mr,light:ji,dark:va};function Lk(){let{theme:e,scheme:t,density:n,resolvedScheme:r,setTheme:i,setScheme:a,setDensity:o,reset:s}=Ll(),c=re(),l=k(),u=PC(),d=L(),f=ck(),p=UC();return(0,Z.jsxs)(`div`,{className:`space-y-8`,children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Vk,{title:`Theme`,description:`Palette, shape and typography. Each theme defines its own light and dark variants.`}),(0,Z.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3`,children:uk.map(t=>{let n=t.id===e;return(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>i(t.id),"aria-pressed":n,className:K(`focus-ring group flex flex-col gap-3 rounded-lg border p-4 text-left transition-colors`,n?`border-primary bg-accent`:`border-border hover:border-muted-foreground/40 hover:bg-accent/50`),children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:t.name}),n&&(0,Z.jsx)(sr,{className:`size-4 shrink-0 text-primary`})]}),(0,Z.jsx)(`div`,{className:`flex gap-1.5`,"aria-hidden":!0,children:t.swatches.map(e=>(0,Z.jsx)(`span`,{className:`size-6 rounded-full border border-border`,style:{backgroundColor:e}},e))}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:t.description})]},t.id)})})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Vk,{title:`Colour scheme`,description:t===`system`?`Following your system setting, currently ${r}.`:`Overrides your system setting.`}),(0,Z.jsx)(Hk,{options:fk.map(e=>{let t=Ik[e.id];return{id:e.id,label:e.name,icon:(0,Z.jsx)(t,{className:`size-4 shrink-0`})}}),value:t,onChange:a})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Vk,{title:`Density`,description:`Controls row height, hit-target size and shell spacing across the whole app.`}),(0,Z.jsx)(Hk,{options:pk.map(e=>({id:e.id,label:e.name,title:e.description})),value:n,onChange:o}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:pk.find(e=>e.id===n)?.description})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Vk,{title:`Layout`,description:`How menus and content share the screen. Device-local, like the wallpaper.`}),(0,Z.jsx)(Hk,{options:TC.map(e=>({id:e.id,label:e.name,title:e.description})),value:u,onChange:MC}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:TC.find(e=>e.id===u)?.description}),u===`strip`&&(0,Z.jsxs)(`div`,{className:`mt-4`,children:[(0,Z.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Navigation keys`}),(0,Z.jsx)(Hk,{options:FC.map(e=>({id:e.id,label:e.name,title:e.description})),value:p,onChange:VC}),(0,Z.jsxs)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:[FC.find(e=>e.id===p)?.description,` `,`Left and right walk the columns, up and down switch pin rows.`]})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Vk,{title:`Tree style`,description:`How workspace and context trees are drawn in the menu. Device-local.`}),(0,Z.jsx)(Hk,{options:ek.map(e=>({id:e.id,label:e.name,title:e.description})),value:f,onChange:ok}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:ek.find(e=>e.id===f)?.description})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Vk,{title:`Open documents`,description:`Choose how documents open from lists, tiles and boards. Saved on this device.`}),(0,Z.jsx)(Hk,{options:[{id:`modal`,label:`Modal`},{id:`side`,label:`Side reading pane`}],value:l,onChange:M}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`The reading pane opens beside the content and updates as you select another document. On small screens it opens as a drawer.`})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Vk,{title:`Always-on content area`,description:`Keep a reading pane beside document lists on tablets and desktops. Remember the selected item in each folder, or show the first available item.`}),(0,Z.jsx)(Hk,{options:[{id:`on`,label:`On`},{id:`off`,label:`Off`}],value:c?`on`:`off`,onChange:e=>ze(e===`on`)}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`On by default. The reader uses roughly half the screen; drag its divider to resize. Phones keep tap-to-open navigation. When enabled, list selections use this pane regardless of the Open documents setting.`})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(Vk,{title:`Document tiles`,description:`Choose the photo and media layout for tile view. Saved on this device.`}),(0,Z.jsx)(Hk,{options:Ie,value:d,onChange:He})]}),(0,Z.jsx)(Rk,{}),(0,Z.jsx)(`section`,{children:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{s(),M(`modal`)},className:`focus-ring rounded-md text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline`,children:`Reset to defaults`})})]})}function Rk(){let[e,t]=(0,X.useState)(HO),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(!0),[o,s]=(0,X.useState)(!1),c=(0,X.useRef)(!1);(0,X.useEffect)(()=>{let e=!1;return GO().then(()=>{e||(t(HO()),a(!1))}),()=>{e=!0}},[]);let l=async(e,n)=>{if(!c.current){c.current=!0,s(!0);try{let i=n?{...e,image:await qO(n)}:e;await KO(i),t(i),r(null)}catch(e){r(e instanceof Error&&e.name!==`QuotaExceededError`?e.message:`Could not store the wallpaper. Free some browser storage or try a smaller image.`)}finally{c.current=!1,s(!1)}}},u=t=>{t&&l(e,t)},d=e.image!==null&&LO(e.image)===null,f=YO(e.image);return(0,Z.jsx)(`section`,{children:(0,Z.jsxs)(`fieldset`,{disabled:i||o,className:`min-w-0`,children:[(0,Z.jsx)(Vk,{title:`Wallpaper`,description:`Background image for the desk behind all panels. Without one, the theme's desk color shows (the default).`}),(0,Z.jsxs)(`div`,{role:`radiogroup`,"aria-label":`Wallpaper`,className:`grid grid-cols-3 gap-3 sm:grid-cols-4 lg:grid-cols-6`,children:[(0,Z.jsx)(Bk,{label:`None`,isActive:e.image===null,onSelect:()=>l({...e,image:null}),children:(0,Z.jsx)(`span`,{className:`flex size-full items-center justify-center surface-desk text-xs text-muted-foreground`,style:{backgroundImage:`none`},children:`None`})}),PO.map(t=>(0,Z.jsx)(Bk,{label:t.title,title:`${t.title} — suits the ${t.scheme} scheme`,isActive:LO(e.image)===t.id,onSelect:()=>l({...e,image:IO(t.id)}),children:(0,Z.jsx)(`img`,{src:FO(t),alt:``,loading:`lazy`,className:`size-full object-cover`,style:{backgroundColor:t.background}})},t.id)),d&&(0,Z.jsx)(Bk,{label:`Your image`,isActive:!0,onSelect:()=>{},children:(0,Z.jsx)(`img`,{src:e.image??void 0,alt:``,className:`size-full object-cover`})})]}),(0,Z.jsx)(zk,{}),(0,Z.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center gap-3`,children:[(0,Z.jsx)(`div`,{className:`h-20 w-32 shrink-0 rounded-md border surface-desk`,style:f?{backgroundImage:f,backgroundSize:XO(e.fit),backgroundPosition:`center`,backgroundRepeat:`no-repeat`}:void 0,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsxs)(`label`,{className:`focus-ring inline-flex cursor-pointer items-center rounded-md border px-3 py-1.5 text-sm hover:bg-accent/50`,children:[d?`Change image…`:`Use your own image…`,(0,Z.jsx)(`input`,{type:`file`,accept:`image/*,.gif`,className:`hidden`,onChange:e=>{u(e.target.files?.[0]),e.target.value=``}})]}),e.image&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>l({...e,image:null}),className:`focus-ring rounded-md border px-3 py-1.5 text-sm text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:`Remove`})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Images and animated GIFs up to 10 MB. Stored on this device.`}),(0,Z.jsx)(Hk,{options:kO.map(e=>({id:e.id,label:e.label,title:e.description})),value:e.fit,onChange:t=>l({...e,fit:t})}),n&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:n}),o&&(0,Z.jsx)(`p`,{role:`status`,className:`text-xs text-muted-foreground`,children:`Saving wallpaper…`})]})]})]})})}function zk(){let e=PO.filter(e=>e.author!==`Canvas`);return e.length===0?null:(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:e.map((e,t)=>(0,Z.jsxs)(`span`,{children:[t>0&&` · `,e.title,` © `,e.author,e.source&&(0,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.jsx)(`a`,{href:e.source,target:`_blank`,rel:`noreferrer noopener`,className:`focus-ring underline underline-offset-2 hover:text-foreground`,children:new URL(e.source).hostname})]})]},e.id))})}function Bk({label:e,title:t,isActive:n,onSelect:r,children:i}){return(0,Z.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":n,"aria-label":e,title:t??e,onClick:r,className:K(`focus-ring group relative aspect-video overflow-hidden rounded-md border transition-colors`,n?`border-primary ring-1 ring-primary`:`border-border hover:border-muted-foreground/40`),children:[i,n&&(0,Z.jsx)(`span`,{className:`absolute right-1 top-1 rounded-full bg-primary p-0.5 text-primary-foreground`,children:(0,Z.jsx)(sr,{className:`size-3`})})]})}function Vk({title:e,description:t}){return(0,Z.jsxs)(`div`,{className:`mb-3`,children:[(0,Z.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function Hk({options:e,value:t,onChange:n}){return(0,Z.jsx)(`div`,{role:`radiogroup`,className:`inline-flex flex-wrap gap-1 rounded-lg bg-muted p-1`,children:e.map(e=>{let r=e.id===t;return(0,Z.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":r,title:e.title,onClick:()=>n(e.id),className:K(`focus-ring flex h-control items-center gap-2 rounded-md px-3 text-sm transition-colors`,r?`bg-card text-foreground shadow-elevation-1`:`text-muted-foreground hover:text-foreground`),children:[e.icon,e.label]},e.id)})})}function Uk(){return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(sw,{className:`mb-6`,title:`Appearance`,onBack:yD(),description:`Theme, colour scheme and density. Changes apply immediately and are remembered on this device.`}),(0,Z.jsx)(Lk,{})]})}var Wk={previousTree:`Alt+Q`,nextTree:`Alt+W`},Gk=`canvas:key-bindings`,Kk=/^(Alt|Alt\+Shift|Ctrl\+Shift|Meta\+Shift)\+[A-Z]$/;function qk(){try{let e=JSON.parse(localStorage.getItem(Gk)||`{}`),t={...Wk};for(let n of Object.keys(t))(e[n]===``||Kk.test(e[n]))&&(t[n]=e[n]);return t.previousTree&&t.previousTree===t.nextTree?{...Wk}:t}catch{return{...Wk}}}function Jk(e){localStorage.setItem(Gk,JSON.stringify(e))}function Yk(e){return/^Key[A-Z]$/.test(e.code)?[e.ctrlKey&&`Ctrl`,e.altKey&&`Alt`,e.metaKey&&`Meta`,e.shiftKey&&`Shift`,e.code.slice(3)].filter(Boolean).join(`+`):``}function Xk(e,t,n){return e[(Math.max(0,e.indexOf(t))+n+e.length)%e.length]}function Zk(e,t){return Math.abs(e)>=48&&Math.abs(e)>Math.abs(t)*1.5?e<0?1:-1:0}function Qk(){let[e,t]=(0,X.useState)(qk),[n,r]=(0,X.useState)(``),i=e=>{if(e.previousTree&&e.previousTree===e.nextTree){r(`Choose a different shortcut: that combination is already assigned.`);return}try{Jk(e),t(e),r(`Saved on this device.`)}catch{r(`Could not save shortcuts in this browser.`)}};return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(sw,{className:`mb-6`,title:`Key bindings`,onBack:yD(),description:`Web UI shortcuts, saved on this device and available offline.`}),(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`font-medium`,children:`Tree navigation`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Cycle the open workspace menu’s tabs in their displayed order, including Pins and Layers. Swipe left for next or right for previous over the tab bar. Shortcuts pause while typing or using a dialog.`}),[`previousTree`,`nextTree`].map(t=>(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Z.jsx)(`label`,{htmlFor:t,className:`min-w-32 text-sm`,children:t===`previousTree`?`Previous tree`:`Next tree`}),(0,Z.jsxs)(`select`,{id:t,className:`rounded-md border bg-background p-2 text-sm`,value:e[t].split(`+`).slice(0,-1).join(`+`),onChange:n=>i({...e,[t]:n.target.value?`${n.target.value}+${e[t].slice(-1)||Wk[t].slice(-1)}`:``}),children:[(0,Z.jsx)(`option`,{value:``,children:`Disabled`}),[`Alt`,`Alt+Shift`,`Ctrl+Shift`,`Meta+Shift`].map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))]}),(0,Z.jsx)(`select`,{"aria-label":`${t===`previousTree`?`Previous`:`Next`} tree key`,disabled:!e[t],className:`rounded-md border bg-background p-2 text-sm disabled:opacity-50`,value:e[t].slice(-1)||Wk[t].slice(-1),onChange:n=>i({...e,[t]:`${e[t].split(`+`).slice(0,-1).join(`+`)}+${n.target.value}`}),children:`ABCDEFGHIJKLMNOPQRSTUVWXYZ`.split(``).map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))})]},t)),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Browsers and operating systems may reserve combinations. Choose another if a shortcut does not reach Canvas. Letters refer to physical keyboard positions (Q/W on a US keyboard); Meta is Command on Mac.`}),(0,Z.jsx)(`button`,{type:`button`,className:`rounded-md border px-3 py-2 text-sm hover:bg-accent`,onClick:()=>i({...Wk}),children:`Restore defaults`}),(0,Z.jsx)(`p`,{role:`status`,className:`text-sm`,children:n})]})]})}var $k=`offline-content-v1`,eA=`offline-api-v1`,tA=1073741824,nA={enabled:!1,budgetBytes:4*tA,excludedWorkspaces:[]},rA=1e3;function iA(e){return(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``)||`/`}function aA(e,t,n){return`${e}:${t}:${iA(n)}`}var oA=`canvas-offline`,sA=2,cA=null;function lA(){return cA||(cA=new Promise((e,t)=>{let n=indexedDB.open(oA,sA);n.onupgradeneeded=e=>{let t=n.result;if(t.objectStoreNames.contains(`config`)||t.createObjectStore(`config`),t.objectStoreNames.contains(`entries`)||t.createObjectStore(`entries`,{keyPath:`url`}),e.oldVersion>=1&&t.objectStoreNames.contains(`pins`)){t.deleteObjectStore(`pins`);let e=n.transaction.objectStore(`entries`).openCursor();e.onsuccess=()=>{let t=e.result;if(!t)return;let n=t.value;n.pinned&&t.update({...n,pinned:!1}),t.continue()}}t.objectStoreNames.contains(`scopes`)||t.createObjectStore(`scopes`,{keyPath:`id`})},n.onsuccess=()=>{n.result.onversionchange=()=>{n.result.close(),cA=null},e(n.result)},n.onerror=()=>{cA=null,t(n.error)}}),cA)}function uA(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function dA(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}async function fA(e,t){return dA((await lA()).transaction(e).objectStore(e).get(t))}async function pA(e){return dA((await lA()).transaction(e).objectStore(e).getAll())}async function mA(e,t,n){let r=(await lA()).transaction(e,`readwrite`);return r.objectStore(e).put(t,n),uA(r)}async function hA(e,t){let n=(await lA()).transaction(e,`readwrite`);return n.objectStore(e).delete(t),uA(n)}async function gA(e){let t=(await lA()).transaction(e,`readwrite`);return t.objectStore(e).clear(),uA(t)}async function _A(){try{let e=await fA(`config`,`settings`);return e?{...nA,...e}:nA}catch{return nA}}async function vA(e){await mA(`config`,e,`settings`)}async function yA(e,t){let n=(await lA()).transaction(`entries`,`readwrite`),r=n.objectStore(`entries`);for(let n of e){let e=r.get(n);e.onsuccess=()=>{let i=e.result;i?r.put({...i,pinned:t}):t&&r.put({url:n,kind:`content`,size:0,lastAccess:Date.now(),pinned:t})}}return uA(n)}async function bA(e){let t=await pA(`entries`),n=t.filter(e=>e.kind===`api`).sort((e,t)=>e.lastAccess-t.lastAccess),r=n.slice(0,Math.max(0,n.length-rA)),i=t.filter(e=>e.kind===`content`),a=i.reduce((e,t)=>e+t.size,0),o=i.filter(e=>!e.pinned).sort((e,t)=>e.lastAccess-t.lastAccess),s=[];for(let t of o){if(a<=e)break;s.push(t),a-=t.size}if(!r.length&&!s.length)return;let[c,l]=await Promise.all([caches.open(eA),caches.open($k)]);await Promise.all([...r.map(async e=>{await c.delete(e.url),await hA(`entries`,e.url)}),...s.map(async e=>{await l.delete(e.url),await hA(`entries`,e.url)})])}async function xA(){let e=await pA(`entries`),t=e.filter(e=>e.kind===`content`);return{contentBytes:t.reduce((e,t)=>e+t.size,0),contentCount:t.length,pinnedBytes:t.filter(e=>e.pinned).reduce((e,t)=>e+t.size,0),apiCount:e.length-t.length}}async function SA(){await Promise.all([caches.delete($k),caches.delete(eA)]),await gA(`entries`),await gA(`scopes`)}async function CA(){return pA(`scopes`)}async function wA(e){return fA(`scopes`,e)}async function TA(e){await mA(`scopes`,e)}async function EA(e){let t=await fA(`scopes`,e);await hA(`scopes`,e),t?.urls.length&&await DA(t.urls)}async function DA(e){let t=await pA(`scopes`),n=new Set(t.flatMap(e=>e.urls)),r=e.filter(e=>!n.has(e));r.length&&await yA(r,!1)}var OA=3,kA=`data/schema/file`,AA=128;async function jA({workspaceRef:e,path:t,treeName:n,treeType:r},i){let a=await _A();if(!a.enabled)throw Error(`Enable the offline cache first`);if(a.excludedWorkspaces.includes(e))throw Error(`Workspace "${e}" is excluded from offline caching`);let o=aA(e,n,t),s=iA(t),c=await wA(o),l=((await Fs(e,s,[],{limit:1e4,treeName:n,treeType:r})).payload??[]).filter(e=>e.schema===kA),u=[],d=0,f=0,p=!1,m=l.length;i?.({done:f,total:m,bytes:d});let h=0;await Promise.all(Array.from({length:Math.min(OA,l.length)},async()=>{for(;h<l.length;){let t=l[h++];if(d>=a.budgetBytes*.9){p=!0;return}try{let{blob:n}=await No(e,t.id);d+=n.size,u.push(`${no.workspaces}/${e}/documents/${t.id}/content`);try{await Cs(e,t.id,AA),u.push(`${no.workspaces}/${e}/documents/${t.id}/thumbnail?size=${AA}`)}catch{}}catch{}f+=1,i?.({done:f,total:m,bytes:d})}})),await yA(u,!0);let g={id:o,workspaceRef:e,treeName:n,treeType:r,path:s,urls:u,bytes:d,warmedAt:Date.now(),...p?{truncated:!0}:{}};if(await TA(g),c){let e=new Set(u),t=c.urls.filter(t=>!e.has(t));t.length&&await DA(t)}return g}var MA=[{label:`1 GB`,bytes:1*tA},{label:`2 GB`,bytes:2*tA},{label:`4 GB`,bytes:4*tA},{label:`8 GB`,bytes:8*tA}];function NA(e){return e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${(e/tA).toFixed(2)} GB`}function PA(){navigator.serviceWorker?.controller?.postMessage({type:`OFFLINE_SETTINGS_CHANGED`})}function FA(){let{showSuccessToast:e,showErrorToast:t}=Oo(),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)([]),[u,d]=(0,X.useState)([]),[f,p]=(0,X.useState)({}),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(!1),v=(0,X.useCallback)(()=>{_A().then(r).catch(()=>{}),xA().then(a).catch(()=>{}),CA().then(e=>d(e.sort((e,t)=>e.id.localeCompare(t.id)))).catch(()=>{}),navigator.storage?.persisted?.().then(s).catch(()=>{})},[]);(0,X.useEffect)(()=>{v(),Uo().then(e=>l(e.map(e=>e.name).filter(Boolean).sort())).catch(()=>{})},[v]);let b=async e=>{r(e),await vA(e),PA(),e.enabled&&navigator.storage?.persist?.().then(s).catch(()=>{}),bA(e.budgetBytes).then(v).catch(()=>{})},x=e=>{if(!n)return;let t=n.excludedWorkspaces.includes(e)?n.excludedWorkspaces.filter(t=>t!==e):[...n.excludedWorkspaces,e];b({...n,excludedWorkspaces:t})},S=async()=>{h(!0);try{await SA(),e(`Offline cache cleared`),v()}catch(e){t(e instanceof Error?e.message:`Failed to clear cache`)}finally{h(!1)}},C=async n=>{let r=aA(n.workspaceRef,n.treeName,n.path);p(e=>({...e,[r]:{done:0,total:0,bytes:0}}));try{let t=await jA(n,e=>p(t=>({...t,[r]:e})));e(t.truncated?`Pinned ${NA(t.bytes)} — stopped at the size budget`:`Pinned ${t.workspaceRef}:/${t.path} (${NA(t.bytes)})`)}catch(e){t(e instanceof Error?e.message:`Failed to pin`)}finally{p(e=>{let{[r]:t,...n}=e;return n}),v()}},w=(e,t)=>{_(!1);for(let n of e)C({workspaceRef:t.workspaceName,path:n,treeName:t.treeName,treeType:t.treeType})},T=e=>({workspaceRef:e.workspaceRef,path:e.path,treeName:e.treeName||`context`,treeType:e.treeType||`context`}),E=async e=>{await EA(e),v()};return n?(0,Z.jsxs)(`div`,{className:`space-y-8`,children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(IA,{title:`Offline cache`,description:`Keep documents you open (and scopes you pin) readable without a connection. Cached on this device only; least-recently-used files are evicted when the size budget fills. Video streaming is not cached.`}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>b({...n,enabled:!n.enabled}),"aria-pressed":n.enabled,className:K(`focus-ring flex items-center gap-3 rounded-lg border p-4 text-left transition-colors`,n.enabled?`border-primary bg-accent`:`border-input hover:bg-muted/40`),children:[(0,Z.jsx)(Ya,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`flex-1`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium`,children:n.enabled?`Enabled`:`Disabled`}),(0,Z.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:n.enabled?o===!1?`Storage is not persistent — the browser may still evict the cache under disk pressure`:`Documents are cached as you browse`:`Nothing is cached for offline use`})]}),n.enabled&&(0,Z.jsx)(sr,{className:`h-4 w-4 shrink-0 text-primary`})]}),n.enabled&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Size budget`}),(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:MA.map(e=>(0,Z.jsx)(Y,{variant:n.budgetBytes===e.bytes?`default`:`outline`,size:`sm`,onClick:()=>b({...n,budgetBytes:e.bytes}),children:e.label},e.bytes))})]}),i&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between text-sm`,children:[(0,Z.jsxs)(`span`,{children:[NA(i.contentBytes),` of `,NA(n.budgetBytes),` used`]}),(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[i.contentCount,` file(s)`,i.pinnedBytes>0?`, ${NA(i.pinnedBytes)} pinned`:``]})]}),(0,Z.jsx)(`div`,{className:`h-2 w-full overflow-hidden rounded-full bg-muted`,children:(0,Z.jsx)(`div`,{className:`h-full rounded-full bg-primary`,style:{width:`${Math.min(100,i.contentBytes/n.budgetBytes*100)}%`}})})]}),(0,Z.jsx)(`div`,{children:(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:S,disabled:m,children:[m?(0,Z.jsx)(Ti,{className:`mr-1.5 h-3.5 w-3.5 animate-spin`}):(0,Z.jsx)(Qr,{className:`mr-1.5 h-3.5 w-3.5`}),`Clear offline cache`]})})]})]})]}),n.enabled&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(IA,{title:`Pinned scopes`,description:`A pinned scope — a workspace, or one of its tree paths — is downloaded up front and never evicted. Scopes resolve fresh on every re-warm, so moved contexts and reorganized trees are picked up; documents that left a scope return to normal eviction.`}),(0,Z.jsx)(`div`,{className:`mb-3`,children:(0,Z.jsxs)(Y,{size:`sm`,onClick:()=>_(!0),disabled:!!Object.keys(f).length,children:[(0,Z.jsx)(tr,{className:`mr-1.5 h-3.5 w-3.5`}),`Pin a path…`]})}),(0,Z.jsxs)(`ul`,{className:`space-y-1`,children:[u.map(e=>{let t=f[e.id];return(0,Z.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,Z.jsxs)(`span`,{className:`flex-1 truncate font-mono text-xs sm:text-sm`,children:[e.workspaceRef,`://`,e.path.replace(/^\//,``),e.treeName&&e.treeName!==`context`&&(0,Z.jsx)(`span`,{className:`ml-1.5 rounded bg-muted px-1 py-0.5 font-sans text-[10px] text-muted-foreground`,children:e.treeName})]}),t?(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Ti,{className:`h-3.5 w-3.5 animate-spin`}),t.total>0?`${t.done}/${t.total} · ${NA(t.bytes)}`:`listing…`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[NA(e.bytes),e.truncated?` (partial)`:``]}),(0,Z.jsx)(Y,{variant:`ghost`,size:`sm`,onClick:()=>C(T(e)),"aria-label":`Re-warm ${e.id}`,title:`Re-warm: re-resolve the scope and download anything new`,children:(0,Z.jsx)(Er,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(Y,{variant:`ghost`,size:`sm`,onClick:()=>E(e.id),"aria-label":`Unpin ${e.id}`,children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]})]},e.id)}),u.length===0&&(0,Z.jsx)(`li`,{className:`rounded-md border border-dashed border-input px-3 py-4 text-center text-sm text-muted-foreground`,children:`Nothing pinned — everything relies on browse-caching and LRU`})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(IA,{title:`Workspace caching`,description:`Excluded workspaces are never cached — not even as you browse — and are not served from cache.`}),(0,Z.jsx)(`ul`,{className:`space-y-1`,children:c.map(e=>{let t=n.excludedWorkspaces.includes(e);return(0,Z.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,Z.jsx)(`span`,{className:K(`flex-1 truncate`,t&&`text-muted-foreground line-through`),children:e}),t&&(0,Z.jsx)(ya,{className:`h-3.5 w-3.5 text-muted-foreground`}),(0,Z.jsx)(Y,{variant:t?`outline`:`ghost`,size:`sm`,onClick:()=>x(e),children:t?`Include`:`Exclude`})]},e)})})]})]}),g&&(0,Z.jsx)(Le,{onClose:()=>_(!1),children:(0,Z.jsx)(y,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,multiple:!1,tabs:[`context`,`directory`],title:`Pin for offline…`,confirmLabel:`Pin path`,onConfirm:w,onClose:()=>_(!1)})})]}):null}function IA({title:e,description:t}){return(0,Z.jsxs)(`div`,{className:`mb-4`,children:[(0,Z.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function LA(){return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(sw,{className:`mb-6`,title:`Offline`,onBack:yD(),description:`Per-device offline cache: browse notes, files, photos and saved websites without a connection.`}),(0,Z.jsx)(FA,{})]})}function RA(e){let t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60);return t>0?`${t}d ${n}h ${r}m`:n>0?`${n}h ${r}m`:`${r}m`}function zA({name:e,version:t,detail:n}){return(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 px-4 py-2.5`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium truncate`,children:e}),n&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate`,children:n})]}),(0,Z.jsx)(`code`,{className:`text-xs text-muted-foreground shrink-0`,children:t})]})}function BA(){let[e,t]=(0,X.useState)(null),[n,r]=(0,X.useState)(null);(0,X.useEffect)(()=>{let e=!0;return J.get(`/ping`,{skipAuth:!0}).then(n=>{e&&t(n??{})}).catch(t=>{e&&r(t instanceof Error?t.message:`Failed to reach the server`)}),()=>{e=!1}},[]);let i=[e?.commit?`commit ${e.commit.slice(0,7)}`:null,typeof e?.uptime==`number`?`up ${RA(e.uptime)}`:null].filter(Boolean).join(` · `),a=Object.entries(e?.components??{}).sort(([e],[t])=>e.localeCompare(t));return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(sw,{className:`mb-6`,title:`About`,onBack:yD(),description:`Versions of every Canvas component this installation is running.`}),(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsxs)(`section`,{className:`rounded-md border border-border divide-y divide-border`,children:[(0,Z.jsx)(zA,{name:`Canvas Web`,detail:`this interface`,version:`v2.26.18`}),e?.version&&(0,Z.jsx)(zA,{name:e.productName||e.appName||`Canvas Server`,detail:i||void 0,version:`v${e.version}`})]}),a.length>0&&(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(`h2`,{className:`mb-2 px-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:`Server components`}),(0,Z.jsx)(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:a.map(([e,t])=>(0,Z.jsx)(zA,{name:e,version:`v${t}`},e))})]}),n&&(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Server details unavailable: `,n]}),e?.sourceUrl&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[e.license?`Licensed ${e.license}. `:``,(0,Z.jsx)(`a`,{href:e.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})]})]})}var VA=[`onnx`,`clip`,`blip`,`openai`],HA=[`onnx`,`clip`,`blip`,`ollama`,`vllm`],UA=[{id:`openai`,baseUrl:`https://api.openai.com/v1`,label:`OpenAI`},{id:`vllm`,baseUrl:`http://127.0.0.1:8000/v1`,label:`vLLM`},{id:`ollama`,baseUrl:`http://127.0.0.1:11434/v1`,label:`Ollama`}],WA=e=>`${no.workspaces}/${encodeURIComponent(e)}/inferd`;function GA(e,t){let n={};for(let[r,i]of Object.entries(e.providers||{})){let e={...i};delete e.apiKeySet,delete e.headerNames,t.has(r)&&i.apiKey?e.apiKey=i.apiKey:delete e.apiKey,n[r]=e}return{...e,providers:n}}async function KA(e){return await J.get(`${WA(e)}/status`)}async function qA(e,t={}){let n={};return t.force!==void 0&&(n.force=t.force),await J.post(`${WA(e)}/summarize/images`,n)}async function JA(e){return await J.post(`${WA(e)}/summarize/images/stop`,{})}async function YA(e){return await J.get(`${WA(e)}/config`)}async function XA(e,t){return await J.put(`${WA(e)}/config`,t)}async function ZA(e,t={}){let n={};return t.space&&(n.space=t.space),t.reindex!==void 0&&(n.reindex=t.reindex),t.scope&&(n.scope=t.scope),await J.post(`${WA(e)}/reindex`,n)}async function QA(e){return await J.get(`${WA(e)}/vector-tables`)}async function $A(e,t){return await J.delete(`${WA(e)}/vector-tables/${encodeURIComponent(t)}`)}async function ej(){return await J.get(`${no.inferd}/config`)}async function tj(e){return await J.put(`${no.inferd}/config`,e)}async function nj(){return await J.get(`${no.inferd}/defaults`)}async function rj(e){return await J.put(`${no.inferd}/defaults`,e)}async function ij(e,t){let n={...e};return delete n.apiKeySet,delete n.headerNames,(await J.post(`${no.inferd}/test`,{provider:n,...t?{model:t}:{},probe:!0})).cached??null}async function aj(e,t,n=`text`){let r={...e};return delete r.apiKeySet,delete r.headerNames,await J.post(`${no.inferd}/test`,{provider:r,...t?{model:t}:{},modality:n})}var oj=`h-8 w-full rounded-md border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring`,sj=`font-semibold uppercase tracking-[0.08em]`,cj={openai:{url:{key:`baseUrl`,label:`Base URL`,placeholder:`http://gpu.local:8000/v1`,hint:`OpenAI-compatible embeddings endpoint — Ollama, vLLM, TEI, infinity, LM Studio and OpenAI itself all speak this. A trailing /v1 is optional; both http://host:8000 and http://host:8000/v1 work.`},apiKey:"Sent as `Authorization: Bearer …`. Leave empty for servers that do not check it.",imageInput:!0,timeoutMs:!0,headers:!0,where:e=>e.baseUrl||`no endpoint set`},ollama:{url:{key:`host`,label:`Host (legacy)`,placeholder:`http://127.0.0.1:11434`,hint:`Written by an older version. Switch the type to openai — the host becomes the base URL and the /v1 suffix is added for you.`},apiKey:"Sent as `Authorization: Bearer …`.",where:e=>e.host||`http://127.0.0.1:11434`},onnx:{cacheDir:`Where downloaded weights are cached on the server. Empty uses the server default.`,note:`Runs in-process on the server. No endpoint and no credentials.`,where:()=>`in-process`},clip:{cacheDir:`Where downloaded weights are cached on the server. Empty uses the server default.`,note:`Runs in-process on the server. No endpoint and no credentials.`,where:()=>`in-process`}},lj=[`baseUrl`,`host`,`apiKey`,`cacheDir`,`imageInput`,`timeoutMs`],uj=[{value:`data-uri`,label:`data-uri (default)`,hint:"Images ride in the ordinary `input` array as data URIs (infinity, TEI-style servers)."},{value:`messages`,label:`messages`,hint:`vLLM's multimodal shape: one request per image, wrapped in a chat message.`}],dj=12e4;function fj(e){if(typeof e!=`string`||e.trim()===``)return null;let t;try{t=new URL(e.trim())}catch{return`Must be an absolute URL including the scheme, e.g. http://127.0.0.1:11434`}return t.protocol!==`http:`&&t.protocol!==`https:`?`Unsupported scheme '${t.protocol.replace(`:`,``)}'. Use http or https.`:null}function pj({title:e,hint:t}){return(0,Z.jsxs)(`div`,{className:`mb-2`,children:[(0,Z.jsx)(`h3`,{className:K(`text-[11px] text-muted-foreground`,sj),children:e}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:t})]})}function mj({overridden:e,source:t}){return e?(0,Z.jsx)(`span`,{className:`rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary`,title:`Set on this layer; it wins over anything inherited`,children:`overridden`}):(0,Z.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground`,title:t?`Inherited: ${t}`:`Inherited from a lower config layer`,children:`inherited`})}function hj({label:e,value:t,inheritedValue:n,onChange:r,type:i=`text`,placeholder:a,disabled:o,hint:s,error:c,mono:l}){let u=t!==void 0&&t!==``;return(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:e}),(0,Z.jsx)(mj,{overridden:u,source:n===void 0?void 0:String(n)}),u&&!o&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(``),className:`text-[10px] text-muted-foreground underline hover:text-foreground`,title:`Clear the override and fall back to the inherited value`,children:`reset`})]}),(0,Z.jsx)(q,{type:i,value:t??``,disabled:o,onChange:e=>r(e.target.value),placeholder:a??(n===void 0?`—`:String(n)),className:K(`h-8 text-sm`,l&&`font-mono`,c&&`border-destructive focus-visible:ring-destructive`)}),c&&(0,Z.jsx)(`p`,{className:`text-[11px] font-medium text-destructive`,children:c}),s&&(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:s})]})}function gj({label:e,checked:t,overridden:n,disabled:r,onChange:i}){return(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,disabled:r,checked:t,onChange:e=>i(e.target.checked)}),e,(0,Z.jsx)(mj,{overridden:n})]})}function _j({storedNames:e,value:t,disabled:n,onChange:r}){let i=t!==void 0,[a,o]=(0,X.useState)([]),s=e=>{o(e),r(Object.fromEntries(e.filter(([e])=>e.trim()!==``)))};return(0,Z.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Custom headers`}),i?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will replace stored`}),!n&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{o([]),r(void 0)},className:`text-[10px] text-muted-foreground underline hover:text-foreground`,children:`cancel`})]}):(0,Z.jsx)(mj,{overridden:!1,source:e?.join(`, `)})]}),!i&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e?.length?(0,Z.jsxs)(Z.Fragment,{children:[`Stored: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:e.join(`, `)}),` (values are never sent back)`]}):`None set.`}),!n&&(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>{o([[``,``]]),r({})},children:e?.length?`Replace headers`:`Add headers`})]}),i&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Saving replaces every stored header, so re-enter the ones you want to keep.`}),a.map(([e,t],r)=>(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:e,disabled:n,placeholder:`X-Tenant`,className:`h-8 font-mono text-sm`,onChange:e=>s(a.map((t,n)=>n===r?[e.target.value,t[1]]:t))}),(0,Z.jsx)(q,{value:t,disabled:n,placeholder:`value`,className:`h-8 font-mono text-sm`,onChange:e=>s(a.map((t,n)=>n===r?[t[0],e.target.value]:t))}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,disabled:n,"aria-label":`Remove header ${e||r+1}`,onClick:()=>s(a.filter((e,t)=>t!==r)),children:(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`})})]},r)),!n&&(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>s([...a,[``,``]]),children:[(0,Z.jsx)(br,{className:`mr-1.5 h-3.5 w-3.5`}),`Add header`]})]})]})}function vj({open:e,onClick:t,label:n}){return(0,Z.jsx)(`button`,{type:`button`,onClick:t,"aria-expanded":e,title:n,"aria-label":n,className:`flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:(0,Z.jsx)(qr,{className:K(`h-4 w-4 transition-transform motion-reduce:transition-none`,e&&`rotate-180`)})})}var yj={configured:`bg-success`,"needs-fill":`bg-warning`,unresolved:`bg-destructive`,unset:`bg-muted-foreground/30`};function bj({value:e,effective:t,inherited:n,resolvedSpaces:r,invalid:i,attention:a,onFill:o,saving:s=!1,disabled:c=!1,saveLabel:l=`Save`,onSave:u}){let{showToast:d}=wo(),[f,p]=(0,X.useState)(()=>structuredClone(e)),[m,h]=(0,X.useState)(new Set),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(``),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)(null),E=(0,X.useMemo)(()=>[...new Set([...Object.keys(t.spaces||{}),...Object.keys(f.spaces||{})])].sort(),[t.spaces,f.spaces]),D=(0,X.useMemo)(()=>[...new Set([...Object.keys(t.providers||{}),...Object.keys(f.providers||{})])].sort(),[t.providers,f.providers]),O=(e,t,n)=>{p(r=>{let i={...r.spaces||{}},a={...i[e]||{}};if(n===``)delete a[t];else if(t===`dim`||t===`maxLength`||t===`dimensions`){let e=Number(n);if(Number.isNaN(e))return r;a[t]=e}else a[t]=n;return Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,spaces:i}})},k=(e,t,n)=>{p(r=>{let i={...r.spaces||{}},a={...i[e]||{}};return n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,spaces:i}})},A=(e,t,n)=>{t===`apiKey`&&h(t=>{let r=new Set(t);return n===``?r.delete(e):r.add(e),r}),p(r=>{let i={...r.providers||{}},a={...i[e]||{}};if(n===``)delete a[t];else if(t===`timeoutMs`){let e=Number(n);if(Number.isNaN(e))return r;a[t]=e}else a[t]=n;return Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,providers:i}})},j=(e,t,n)=>{p(r=>{let i={...r.providers||{}},a={...i[e]||{}};return n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,providers:i}})},M=e=>{p(t=>{let n={...t.providers||{}};return delete n[e],{...t,providers:n}}),h(t=>{let n=new Set(t);return n.delete(e),n})},N=()=>{let e=S.trim();if(e){if(E.includes(e)){d({title:`Space exists`,description:`'${e}' already has a row below.`,variant:`destructive`});return}p(t=>({...t,spaces:{...t.spaces||{},[e]:{}}})),C(``),T(`space:${e}`)}},P=(e,t)=>{if(e){if(D.includes(e)){d({title:`Backend exists`,description:`'${e}' is already declared. Open it below to edit.`,variant:`destructive`});return}p(n=>({...n,providers:{...n.providers||{},[e]:{type:`openai`,...t?{baseUrl:t}:{}}}})),x(``),T(`provider:${e}`)}},ee=e=>({...t.providers?.[e]||{},...f.providers?.[e]||{}}),F=async e=>{let n=f.spaces?.[e]?.provider??t.spaces?.[e]?.provider,r=f.spaces?.[e]?.model??t.spaces?.[e]?.model;if(!n){d({title:`No backend`,description:`Space '${e}' has no backend to test.`,variant:`destructive`});return}let i=ee(n),a=i.type?cj[i.type]?.url?.key:void 0,o=a?fj(i[a]):null;if(o){d({title:`Backend '${n}'`,description:o,variant:`destructive`});return}_(e);try{try{await ij(i,r)===!1&&(y(!0),d({title:`Downloading model`,description:`'${r??`the configured model`}' is not in the server's cache yet; downloading now. A first test can take a few minutes; the model is then cached for good.`}))}catch{}let n=await aj(i,r,e),a=f.spaces?.[e]?.dim??t.spaces?.[e]?.dim,o=n.dim>0&&a!==void 0&&n.dim!==a;(o||n.dim>0&&a===void 0)&&O(e,`dim`,String(n.dim)),d({title:o?`Backend answered; dimensions corrected`:`Backend answered`,description:o?`Returned ${n.dim}-d but '${e}' was set to ${a}-d. Dimensions updated to ${n.dim}; save to apply. (${n.latencyMs} ms)`:`${n.dim}-d in ${n.latencyMs} ms`})}catch(e){d({title:`Test failed`,description:e instanceof Error?e.message:`Backend unreachable`,variant:`destructive`})}finally{_(null),y(!1)}},I=(0,X.useMemo)(()=>{let e=[];for(let[n,r]of Object.entries(f.providers||{})){let i=r.type??t.providers?.[n]?.type,a=i?cj[i]?.url?.key:void 0;if(!a)continue;let o=fj(r[a]);o&&e.push(`${n}: ${o}`)}return e},[f.providers,t.providers]),te=(0,X.useMemo)(()=>JSON.stringify(f)!==JSON.stringify(e)||m.size>0,[f,e,m]),L=async()=>{if(I.length>0){d({title:`Fix the endpoint first`,description:I.join(` · `),variant:`destructive`});return}await u(GA(f,m)),h(new Set)},R=e=>T(t=>t===e?null:e);return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[i&&(0,Z.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive-subtle p-3 text-xs`,children:[(0,Z.jsx)(dr,{className:`mt-0.5 h-4 w-4 shrink-0 text-destructive`}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Stored config does not resolve; defaults are standing in`}),(0,Z.jsx)(`p`,{className:`mt-0.5 font-mono text-[11px] text-muted-foreground`,children:i})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(pj,{title:`Search models`,hint:`Choose a provider and model for each kind of content. After switching models, fill the new index to make existing documents searchable. Previous model indexes are preserved.`}),E.length===0?(0,Z.jsxs)(`div`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:`No spaces on this layer`}),(0,Z.jsx)(`p`,{className:`mx-auto mt-1 max-w-sm text-xs text-muted-foreground`,children:`A space needs a backend, a model and a dimension count. Add one below to start embedding.`})]}):(0,Z.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:E.map(e=>{let s=f.spaces?.[e]||{},l=t.spaces?.[e]||{},u=n.spaces?.[e]||{},d=r?.[e],p=`space:${e}`,m=w===p,h=s.model??l.model,_=s.provider??l.provider,y=s.dim??l.dim,b=s.chunk??l.chunk??!1,x=a?.includes(e)??!1;return(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(`span`,{className:K(`absolute inset-y-0 left-0 w-[3px]`,yj[i?`unresolved`:x?`needs-fill`:h?`configured`:`unset`]),"aria-hidden":!0}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 py-3 pl-4 pr-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,Z.jsx)(`span`,{className:K(`text-[11px]`,sj),children:e}),(0,Z.jsx)(`span`,{className:`truncate font-mono text-sm`,children:h||`no model set`}),_&&(0,Z.jsxs)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground`,children:[`via `,_]}),y!==void 0&&(0,Z.jsxs)(`span`,{className:`text-xs tabular-nums text-muted-foreground`,children:[y,`-d`]}),b&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`chunked`})]}),r&&h&&(0,Z.jsxs)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,title:`Vector table backing this space`,children:[`└─ `,d?.table??(0,Z.jsx)(`span`,{className:`not-italic`,children:`not created yet`})]}),x&&(0,Z.jsx)(`p`,{className:`mt-1 text-[11px] text-warning`,children:`New table, nothing embedded in it yet; dense search stays thin for this space until it is filled. Reverting the model is still instant.`})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[x&&o&&(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>o(e),children:`Fill`}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,disabled:c||g!==null,onClick:()=>F(e),title:`Round-trip a real embedding call against this backend and report the dimensions it returns`,children:[(0,Z.jsx)(lr,{className:`mr-1.5 h-3.5 w-3.5`}),g===e?v?`Downloading…`:`Testing…`:`Test`]}),(0,Z.jsx)(vj,{open:m,onClick:()=>R(p),label:`Edit ${e}`})]})]}),m&&(0,Z.jsxs)(`div`,{className:`border-t bg-muted/40 py-4 pl-4 pr-3`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Backend`}),(0,Z.jsx)(mj,{overridden:s.provider!==void 0,source:u.provider})]}),(0,Z.jsxs)(`select`,{className:oj,disabled:c,value:s.provider??``,onChange:t=>O(e,`provider`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:l.provider?`inherited: ${l.provider}`:`inherited`}),D.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Z.jsx)(hj,{label:`Model`,mono:!0,value:s.model,inheritedValue:l.model,onChange:t=>O(e,`model`,t),disabled:c}),(0,Z.jsx)(hj,{label:`Dimensions`,type:`number`,value:s.dim,inheritedValue:l.dim,onChange:t=>O(e,`dim`,t),disabled:c,hint:`Sizes the vector table. Test asks the backend and fills in what it really returns.`}),(0,Z.jsx)(hj,{label:`Max length`,type:`number`,value:s.maxLength,inheritedValue:l.maxLength,onChange:t=>O(e,`maxLength`,t),disabled:c})]}),(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-4`,children:[(0,Z.jsx)(gj,{label:`Chunk long inputs`,checked:b,overridden:s.chunk!==void 0,disabled:c,onChange:t=>k(e,`chunk`,t)}),(0,Z.jsx)(gj,{label:`Build ANN index`,checked:s.annIndex??l.annIndex??!0,overridden:s.annIndex!==void 0,disabled:c,onChange:t=>k(e,`annIndex`,t)})]})]})]},e)})}),!c&&(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{value:S,onChange:e=>C(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),N())},placeholder:`new space name (e.g. audio)`,className:`h-8 w-full max-w-xs text-sm sm:w-auto`}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:N,children:[(0,Z.jsx)(br,{className:`mr-1.5 h-3.5 w-3.5`}),`Add space`]})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(pj,{title:`Model providers`,hint:`Connect a service here, then select it under Search models above. Built-in providers work without an extra connection. Provider changes take effect when you save.`}),(0,Z.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:D.map(e=>{let n=f.providers?.[e]||{},r=t.providers?.[e]||{},i=HA.includes(e),a=f.providers?.[e]!==void 0,o=`provider:${e}`,s=w===o,l=n.type??r.type,u=l?cj[l]:void 0,d=u?.url?fj(n[u.url.key]):null,p={...r,...n},h=lj.filter(e=>!(n[e]===void 0||e===u?.url?.key||e===`apiKey`&&u?.apiKey||e===`cacheDir`&&u?.cacheDir)),g=E.filter(n=>(f.spaces?.[n]?.provider??t.spaces?.[n]?.provider)===e);return(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 px-4 py-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,Z.jsx)(`span`,{className:`font-mono text-sm font-semibold`,children:e}),(0,Z.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:l??`no type`}),i&&(0,Z.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:`built-in`}),p.apiKeySet&&!m.has(e)&&(0,Z.jsx)(`span`,{className:`text-[10px] font-medium text-success`,children:`key set`}),d&&(0,Z.jsx)(`span`,{className:`text-[10px] font-medium text-destructive`,children:`check endpoint`})]}),(0,Z.jsx)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,children:u?u.where(p):`—`}),g.length>0&&(0,Z.jsxs)(`p`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`used by `,g.join(`, `)]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[a&&!i&&!c&&(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>M(e),title:`Remove this override`,children:(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(vj,{open:s,onClick:()=>R(o),label:`Edit ${e}`})]})]}),s&&(0,Z.jsxs)(`div`,{className:`border-t bg-muted/40 px-4 py-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Type`}),(0,Z.jsx)(mj,{overridden:n.type!==void 0,source:r.type})]}),(0,Z.jsxs)(`select`,{className:oj,disabled:c,value:n.type??``,onChange:t=>A(e,`type`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:r.type?`inherited: ${r.type}`:`inherited`}),VA.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e)),l&&!VA.includes(l)&&(0,Z.jsxs)(`option`,{value:l,children:[l,` (legacy)`]})]}),u?.note&&(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:u.note})]}),u?.url&&(0,Z.jsx)(hj,{label:u.url.label,mono:!0,value:n[u.url.key],inheritedValue:r[u.url.key],onChange:t=>A(e,u.url.key,t),disabled:c,placeholder:r[u.url.key]??u.url.placeholder,hint:u.url.hint,error:d??void 0}),u?.cacheDir&&(0,Z.jsx)(hj,{label:`Cache directory`,mono:!0,value:n.cacheDir,inheritedValue:r.cacheDir,onChange:t=>A(e,`cacheDir`,t),disabled:c,placeholder:r.cacheDir??`server default`,hint:u.cacheDir}),u?.imageInput&&(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Image input shape`}),(0,Z.jsx)(mj,{overridden:n.imageInput!==void 0,source:r.imageInput})]}),(0,Z.jsxs)(`select`,{className:oj,disabled:c,value:n.imageInput??``,onChange:t=>A(e,`imageInput`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:r.imageInput?`inherited: ${r.imageInput}`:`inherited: data-uri`}),uj.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:uj.find(e=>e.value===(n.imageInput??r.imageInput??`data-uri`))?.hint})]}),u?.timeoutMs&&(0,Z.jsx)(hj,{label:`Request timeout (ms)`,type:`number`,value:n.timeoutMs,inheritedValue:r.timeoutMs??dj,onChange:t=>A(e,`timeoutMs`,t),disabled:c,hint:`How long to wait for a batch before giving up. Raise it for a slow or cold GPU host.`}),u?.apiKey&&(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`API key`}),m.has(e)&&(0,Z.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will be written`})]}),(0,Z.jsx)(q,{type:`password`,autoComplete:`new-password`,disabled:c,value:n.apiKey??``,onChange:t=>A(e,`apiKey`,t.target.value),placeholder:r.apiKeySet?`•••••••• (stored; leave empty to keep)`:`unset`,className:`h-8 text-sm`}),(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[u.apiKey,` Write-only: the stored key is never sent back, and leaving this empty keeps whatever is stored.`]})]})]}),u?.headers&&(0,Z.jsx)(_j,{disabled:c,storedNames:r.headerNames,value:n.headers,onChange:t=>j(e,`headers`,t)}),h.length>0&&!c&&(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2 rounded-md border border-dashed p-2 text-[11px] text-muted-foreground`,children:[(0,Z.jsxs)(`span`,{children:[`Not used by type `,(0,Z.jsx)(`span`,{className:`font-mono`,children:l}),`:`,` `,(0,Z.jsx)(`span`,{className:`font-mono`,children:h.join(`, `)})]}),(0,Z.jsx)(`button`,{type:`button`,className:`underline hover:text-foreground`,onClick:()=>h.forEach(t=>A(e,t,``)),children:`clear`})]}),r.headerNames&&r.headerNames.length>0&&(0,Z.jsxs)(`p`,{className:`mt-3 text-[11px] text-muted-foreground`,children:[`Stored custom headers: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:r.headerNames.join(`, `)}),` (values not shown)`]})]})]},e)})}),!c&&(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{value:b,onChange:e=>x(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),P(b.trim()))},placeholder:`new backend name (e.g. gpu)`,className:`h-8 w-full max-w-xs text-sm sm:w-auto`}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>P(b.trim()),children:[(0,Z.jsx)(br,{className:`mr-1.5 h-3.5 w-3.5`}),`Add backend`]}),UA.filter(e=>!D.includes(e.id)).map(e=>(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>P(e.id,e.baseUrl),title:`Add an openai-type backend '${e.id}' pointed at ${e.baseUrl}`,children:e.label},e.id))]})]}),!c&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t pt-4`,children:[(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:te?`default`:`outline`,onClick:L,disabled:s||!te||I.length>0,children:s?`Saving…`:l}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,disabled:s||!te,onClick:()=>{p(structuredClone(e)),h(new Set)},children:`Discard changes`}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:I.length>0?(0,Z.jsxs)(`span`,{className:`font-medium text-destructive`,children:[I.length,` endpoint `,I.length===1?`needs`:`need`,` fixing`]}):te?`Unsaved changes`:`Everything saved`})]})]})}function xj(){let{showToast:e}=wo(),[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!0),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),l=(0,X.useCallback)(()=>ej().then(e=>{n(e),c(null)}).catch(e=>c(e instanceof Error?e.message:`Failed to load embedding defaults`)).finally(()=>i(!1)),[]);(0,X.useEffect)(()=>{l()},[l]);let u=()=>{i(!0),l()};return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl p-6`,children:[(0,Z.jsx)(sw,{compact:!0,className:`mb-6`,title:`Search & AI defaults`,onBack:yD(),description:`Your account · Choose the embedding models used for text and image search. Workspace settings override these defaults. Running workspaces adopt new defaults when restarted.`,actions:(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:u,disabled:r,children:[(0,Z.jsx)(Er,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})}),r?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(Er,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):s||!t?(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`rounded-md border border-destructive/40 bg-destructive/5 p-4 text-sm`,children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Embedding defaults unavailable`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s||`No config returned.`})]}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:u,children:`Retry`})]}):(0,Z.jsx)(bj,{value:t.user||{},effective:t.effective||{},inherited:t.serverDefaults||{},invalid:t.invalid,saving:a,saveLabel:`Save defaults`,onSave:async t=>{o(!0);try{let n=await tj(t);e({title:`Defaults saved`,description:n.restartRequired?`${n.workspaces.length} running workspace(s) keep their current tables until restarted. Set the config on a workspace directly to change it live.`:`New workspaces will inherit this.`}),await l()}catch(t){e({title:`Save failed`,description:t instanceof Error?t.message:`Failed to save`,variant:`destructive`})}finally{o(!1)}}},JSON.stringify(t.user))]})}function Sj(){let e=vn(),{showToast:t}=wo(),n=new URLSearchParams(e.search),r=e=>{try{let t=new URL(e);return t.pathname.includes(`/rest/v2/workspaces/`)&&!t.pathname.includes(`/rest/v2/pub/`)?t.pathname=t.pathname.replace(`/rest/v2/workspaces/`,`/rest/v2/pub/workspaces/`):t.pathname.includes(`/rest/v2/contexts/`)&&!t.pathname.includes(`/rest/v2/pub/`)&&(t.pathname=t.pathname.replace(`/rest/v2/contexts/`,`/rest/v2/pub/contexts/`)),t.toString()}catch{return e}},i=r(n.get(`url`)||``),a=sessionStorage.getItem(`sharedToken:last`)||``,[o,s]=(0,X.useState)(i),[c,l]=(0,X.useState)(a),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)([]),[m,h]=(0,X.useState)(!1),g=(0,X.useMemo)(()=>{try{let e=new URL(o);return e.pathname.includes(`/pub/workspaces/`)?`workspace`:e.pathname.includes(`/pub/contexts/`)?`context`:`unknown`}catch{return`unknown`}},[o]),_=()=>({Authorization:`Bearer ${c.trim()}`}),v=async()=>{if(!(!o||!c)){h(!0);try{let e=r(o),t=await J.get(e,{skipAuth:!0,headers:_()});d(t);let n=await J.get(`${e}/documents`,{skipAuth:!0,headers:_()}),i=Array.isArray(n)?n:Array.isArray(n?.data)?n.data:[];p(Array.isArray(i)?i:[])}catch(e){let n=o.includes(`/rest/v2/workspaces/`)?`Ensure the URL uses /rest/v2/pub/workspaces/<workspace-id> and the token matches that workspace.`:o.includes(`/rest/v2/contexts/`)?`Ensure the URL uses /rest/v2/pub/contexts/<context-id>.`:void 0;t({title:`Error`,description:`${e instanceof Error?e.message:`Failed to load shared resource`}${n?`: ${n}`:``}`,variant:`destructive`}),d(null),p([])}finally{h(!1)}}},y=(0,X.useRef)(v);return(0,X.useEffect)(()=>{y.current()},[]),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(sw,{onBack:yD(),title:`Shared Resource Viewer`,description:`Open a resource someone shared with you.`}),(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`Full pub URL`}),(0,Z.jsx)(q,{value:c,onChange:e=>l(e.target.value),placeholder:`Access token (canvas-...)`}),(0,Z.jsx)(Y,{onClick:v,disabled:m||!o||!c,children:`Load`})]}),(0,Z.jsxs)(`div`,{className:`text-sm text-muted-foreground`,children:[`Type: `,g]}),m?(0,Z.jsx)(`div`,{className:`text-center py-8 text-muted-foreground`,children:`Loading...`}):(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,Z.jsx)(`h2`,{className:`font-semibold mb-2`,children:`Metadata`}),(0,Z.jsx)(`pre`,{className:`text-xs overflow-auto max-h-80`,children:JSON.stringify(u,null,2)})]}),(0,Z.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,Z.jsxs)(`h2`,{className:`font-semibold mb-2`,children:[`Documents (`,f.length,`)`]}),f.length===0?(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`No documents`}):(0,Z.jsx)(`ul`,{className:`space-y-2 text-sm`,children:f.slice(0,100).map((e,t)=>(0,Z.jsxs)(`li`,{className:`border rounded p-2`,children:[(0,Z.jsx)(`div`,{className:`font-mono text-xs`,children:e.id}),(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:e.schema})]},t))})]})]}),(0,Z.jsx)(au,{className:`mt-8`})]})}function Cj(e={}){let t=new URLSearchParams;e.tail&&t.set(`tail`,String(e.tail)),e.level&&t.set(`level`,e.level),e.module&&t.set(`module`,e.module);let n=t.toString();return n?`?${n}`:``}function wj(){let e=localStorage.getItem(`authToken`);if(!e)throw Error(`Authentication required`);let t=localStorage.getItem(`appName`)||window.location.hostname;return{Authorization:`Bearer ${e}`,"X-App-Name":t,Accept:`text/event-stream`}}var Tj={users:{async listUsers(e){let t=new URLSearchParams;e?.status&&t.append(`status`,e.status),e?.userType&&t.append(`userType`,e.userType);let n=t.toString(),r=n?`${no.admin.users}?${n}`:no.admin.users;return await J.get(r)},async getUser(e){return await J.get(`${no.admin.users}/${e}`)},async createUser(e){return await J.post(no.admin.users,e)},async updateUser(e,t){return await J.put(`${no.admin.users}/${e}`,t)},async deleteUser(e){await J.delete(`${no.admin.users}/${e}`)}},workspaces:{async listAllWorkspaces(){return await J.get(no.admin.workspaces)},async createWorkspace(e){return await J.post(no.admin.workspaces,e)},async deleteWorkspace(e){await J.delete(`${no.admin.workspaces}/${e}`)}},logs:{async getLogs(e={}){return(await J.get(`${no.admin.logs}${Cj(e)}`)).logs||[]},async streamLogs(e={},t={}){let{signal:n,onEntry:r,onError:i}=t;try{let t=await fetch(`${no.admin.logsStream}${Cj(e)}`,{method:`GET`,headers:wj(),credentials:`include`,signal:n});if(!t.ok)throw Error(`Failed to open log stream (${t.status})`);if(!t.body)throw Error(`Streaming is not supported by this browser`);let i=t.body.getReader(),a=new TextDecoder,o=``,s=e=>{let t=e.split(`
|
|
32
34
|
`),n=`message`,i=[];for(let e of t)if(!(!e||e.startsWith(`:`))){if(e.startsWith(`event:`)){n=e.slice(6).trim();continue}e.startsWith(`data:`)&&i.push(e.slice(5).trim())}if(n!==`log`||i.length===0)return;let a=JSON.parse(i.join(`
|
|
33
35
|
`));r?.(a)};try{for(;;){let{done:e,value:t}=await i.read();if(e)break;o+=a.decode(t,{stream:!0});let n=o.split(`
|
|
34
36
|
|
|
35
37
|
`);o=n.pop()||``;for(let e of n)s(e)}o.trim()&&s(o)}finally{i.releaseLock()}}catch(e){if(n?.aborted)return;let t=e instanceof Error?e:Error(String(e));throw i?.(t),t}}}},Ej=()=>{let e=[`#FF6B6B`,`#4ECDC4`,`#45B7D1`,`#96CEB4`,`#FECA57`,`#FF9FF3`,`#54A0FF`,`#5F27CD`,`#00D2D3`,`#FF9F43`,`#10AC84`,`#EE5A24`,`#EA2027`,`#009432`,`#0652DD`];return e[Math.floor(Math.random()*e.length)]};function Dj(){let e=du()?.userType===`admin`,[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(e),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(e?null:`Access denied. Admin privileges required.`),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)({search:``,owner:``,type:``,status:``}),[_,v]=(0,X.useState)({userId:``,name:``,label:``,description:``,color:Ej(),type:`workspace`}),{showToast:y}=wo(),b=(0,X.useCallback)(async()=>{try{o(!0);let e=await Tj.workspaces.listAllWorkspaces();n(e),u(null)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch workspaces`;u(t),y({title:`Error`,description:t,variant:`destructive`})}finally{o(!1)}},[y]);(0,X.useEffect)(()=>{e&&b()},[e,b]);let x=(0,X.useCallback)(async()=>{try{c(!0);let e=await Tj.users.listUsers({status:`active`});i(e)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch users`;y({title:`Error`,description:t,variant:`destructive`})}finally{c(!1)}},[y]),S=async e=>{if(e.preventDefault(),!_.userId||!_.name.trim()){y({title:`Validation Error`,description:`User and workspace name are required`,variant:`destructive`});return}f(!0);try{let e={userId:_.userId,name:_.name.trim(),label:_.label.trim()||_.name.trim(),description:_.description.trim(),color:_.color,type:_.type};await Tj.workspaces.createWorkspace(e),v({userId:``,name:``,label:``,description:``,color:Ej(),type:`workspace`}),m(!1),await b(),y({title:`Success`,description:`Workspace created successfully`})}catch(e){let t=e instanceof Error?e.message:`Failed to create workspace`;y({title:`Error`,description:t,variant:`destructive`})}finally{f(!1)}},C=async(e,t)=>{if(confirm(`Are you sure you want to delete workspace "${t}"? This action cannot be undone and will delete all data in the workspace.`))try{await Tj.workspaces.deleteWorkspace(e),await b(),y({title:`Success`,description:`Workspace deleted successfully`})}catch(e){let t=e instanceof Error?e.message:`Failed to delete workspace`;y({title:`Error`,description:t,variant:`destructive`})}},w=async()=>{v({userId:``,name:``,label:``,description:``,color:Ej(),type:`workspace`}),m(!0),await x()},T=()=>{m(!1)};Ae(T,p);let E=t.filter(e=>{let t=h.search===``||e.name.toLowerCase().includes(h.search.toLowerCase())||e.label.toLowerCase().includes(h.search.toLowerCase())||e.ownerName&&e.ownerName.toLowerCase().includes(h.search.toLowerCase())||e.ownerEmail&&e.ownerEmail.toLowerCase().includes(h.search.toLowerCase()),n=h.owner===``||e.owner===h.owner,r=h.type===``||e.type===h.type,i=h.status===``||e.status===h.status;return t&&n&&r&&i}),D=Array.from(new Set(t.map(e=>e.owner))).map(e=>{let n=t.find(t=>t.owner===e);return{id:e,name:n?.ownerName||n?.ownerEmail||e}});return e?(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{title:`Workspace Administration`,description:`Manage workspaces across all users`}),t.some(e=>e.status!==`active`&&e.protection?.mode&&e.protection.mode!==`none`)&&(0,Z.jsxs)(`p`,{className:`text-sm rounded border p-3`,children:[t.filter(e=>e.status!==`active`&&e.protection?.mode&&e.protection.mode!==`none`).length,` protected workspaces waiting for their owners to start them.`]}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 md:flex-row md:items-center md:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 md:flex-row md:items-center`,children:[(0,Z.jsx)(q,{placeholder:`Search workspaces...`,value:h.search,onChange:e=>g(t=>({...t,search:e.target.value})),className:`md:w-64`}),(0,Z.jsxs)(`select`,{value:h.owner,onChange:e=>g(t=>({...t,owner:e.target.value})),className:`px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:``,children:`All Owners`}),D.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),(0,Z.jsxs)(`select`,{value:h.type,onChange:e=>g(t=>({...t,type:e.target.value})),className:`px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:``,children:`All Types`}),(0,Z.jsx)(`option`,{value:`workspace`,children:`Workspace`}),(0,Z.jsx)(`option`,{value:`universe`,children:`Universe`})]}),(0,Z.jsxs)(`select`,{value:h.status,onChange:e=>g(t=>({...t,status:e.target.value})),className:`px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:``,children:`All Statuses`}),(0,Z.jsx)(`option`,{value:`active`,children:`Active`}),(0,Z.jsx)(`option`,{value:`inactive`,children:`Inactive`}),(0,Z.jsx)(`option`,{value:`error`,children:`Error`})]})]}),(0,Z.jsxs)(Y,{onClick:w,children:[(0,Z.jsx)(br,{className:`mr-2 h-4 w-4`}),`Create Workspace`]})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[a&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading workspaces...`}),l&&!t.length&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:l})}),!a&&!l&&E.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No workspaces found`}),E.length>0&&(0,Z.jsx)(`div`,{className:`border rounded-md`,children:(0,Z.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Z.jsxs)(`table`,{className:`w-full`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{className:`bg-muted/50`,children:[(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Name`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Label`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Owner`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Type`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Status`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Color`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Created`}),(0,Z.jsx)(`th`,{className:`text-right p-3 font-medium`,children:`Actions`})]})}),(0,Z.jsx)(`tbody`,{children:E.map(e=>(0,Z.jsxs)(`tr`,{className:`border-t`,children:[(0,Z.jsx)(`td`,{className:`p-3 font-medium font-mono text-sm`,children:e.name}),(0,Z.jsx)(`td`,{className:`p-3`,children:e.label}),(0,Z.jsx)(`td`,{className:`p-3`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(ar,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`font-medium`,children:e.ownerName||`Unknown`}),(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:e.ownerEmail})]})]})}),(0,Z.jsx)(`td`,{className:`p-3`,children:(0,Z.jsx)(`span`,{className:`px-2 py-1 rounded-full text-xs ${e.type===`universe`?`bg-accent text-primary`:`bg-info-subtle text-info`}`,children:e.type})}),(0,Z.jsx)(`td`,{className:`p-3`,children:(0,Z.jsx)(`span`,{className:`px-2 py-1 rounded-full text-xs ${e.status===`active`?`bg-success-subtle text-success`:e.status===`inactive`?`bg-warning-subtle text-warning`:`bg-destructive-subtle text-destructive`}`,children:e.status})}),(0,Z.jsx)(`td`,{className:`p-3`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`div`,{className:`w-4 h-4 rounded border`,style:{backgroundColor:e.color}}),(0,Z.jsx)(`span`,{className:`font-mono text-xs`,children:e.color})]})}),(0,Z.jsx)(`td`,{className:`p-3`,children:new Date(e.createdAt).toLocaleDateString()}),(0,Z.jsxs)(`td`,{className:`p-3 text-right space-x-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>window.open(`/workspaces/${e.name}`,`_blank`),title:`View workspace`,children:(0,Z.jsx)(ja,{className:`h-4 w-4`})}),(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>C(e.id,e.name),className:`text-destructive hover:bg-destructive/10 hover:text-destructive`,title:`Delete workspace`,disabled:e.type===`universe`,children:(0,Z.jsx)(ti,{className:`h-4 w-4`})})]})]},e.id))})]})})})]}),(0,Z.jsxs)(`div`,{className:`grid grid-cols-1 md:grid-cols-4 gap-4 mt-8`,children:[(0,Z.jsxs)(`div`,{className:`bg-card p-4 rounded-lg border`,children:[(0,Z.jsx)(`div`,{className:`text-2xl font-bold`,children:t.length}),(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Total Workspaces`})]}),(0,Z.jsxs)(`div`,{className:`bg-card p-4 rounded-lg border`,children:[(0,Z.jsx)(`div`,{className:`text-2xl font-bold`,children:t.filter(e=>e.status===`active`).length}),(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Active Workspaces`})]}),(0,Z.jsxs)(`div`,{className:`bg-card p-4 rounded-lg border`,children:[(0,Z.jsx)(`div`,{className:`text-2xl font-bold`,children:t.filter(e=>e.type===`universe`).length}),(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Universe Workspaces`})]}),(0,Z.jsxs)(`div`,{className:`bg-card p-4 rounded-lg border`,children:[(0,Z.jsx)(`div`,{className:`text-2xl font-bold`,children:D.length}),(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Unique Owners`})]})]}),p&&(0,Z.jsx)(`div`,{className:`fixed inset-0 bg-scrim flex items-center justify-center z-50`,children:(0,Z.jsxs)(`div`,{className:`bg-card rounded-lg p-6 w-full max-w-md mx-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-4`,children:[(0,Z.jsx)(`h3`,{className:`text-lg font-semibold`,children:`Create New Workspace`}),(0,Z.jsx)(Y,{variant:`ghost`,size:`sm`,onClick:T,children:(0,Z.jsx)(vr,{className:`h-4 w-4`})})]}),(0,Z.jsxs)(`form`,{onSubmit:S,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`userId`,children:`User`}),(0,Z.jsxs)(`select`,{id:`userId`,value:_.userId,onChange:e=>v(t=>({...t,userId:e.target.value})),disabled:d||s,className:`w-full px-3 py-2 border border-border rounded-md`,required:!0,children:[(0,Z.jsx)(`option`,{value:``,children:`Select a user...`}),r.map(e=>(0,Z.jsxs)(`option`,{value:e.id,children:[e.name,` (`,e.email,`)`]},e.id))]}),s&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:`Loading users...`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`name`,children:`Workspace Name`}),(0,Z.jsx)(q,{id:`name`,type:`text`,value:_.name,onChange:e=>v(t=>({...t,name:e.target.value})),placeholder:`my-workspace`,disabled:d,required:!0}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:`Lowercase letters, numbers, and hyphens only`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`label`,children:`Display Label`}),(0,Z.jsx)(q,{id:`label`,type:`text`,value:_.label,onChange:e=>v(t=>({...t,label:e.target.value})),placeholder:`My Workspace`,disabled:d})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`description`,children:`Description`}),(0,Z.jsx)(q,{id:`description`,type:`text`,value:_.description,onChange:e=>v(t=>({...t,description:e.target.value})),placeholder:`Workspace description (optional)`,disabled:d})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`type`,children:`Type`}),(0,Z.jsxs)(`select`,{id:`type`,value:_.type,onChange:e=>v(t=>({...t,type:e.target.value})),disabled:d,className:`w-full px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:`workspace`,children:`Workspace`}),(0,Z.jsx)(`option`,{value:`universe`,children:`Universe`})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`color`,children:`Color`}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(q,{id:`color`,type:`color`,value:_.color,onChange:e=>v(t=>({...t,color:e.target.value})),className:`h-10 w-16 p-1`,disabled:d}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>v(e=>({...e,color:Ej()})),disabled:d,children:`Random`})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2 pt-4`,children:[(0,Z.jsx)(Y,{type:`submit`,disabled:d||s,className:`flex-1`,children:d?`Creating...`:`Create Workspace`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,onClick:T,disabled:d,children:`Cancel`})]})]})]})})]}):(0,Z.jsx)(`div`,{className:`text-center space-y-4`,children:(0,Z.jsx)(`div`,{className:`text-destructive`,children:`Access denied. Admin privileges required.`})})}function Oj(){let e=du()?.userType===`admin`;return(0,X.useEffect)(()=>{},[e]),e?(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{title:`All Contexts`,description:`Manage all contexts across all users`}),(0,Z.jsx)(`div`,{className:`flex flex-col items-center justify-center py-12 space-y-4`,children:(0,Z.jsxs)(`div`,{className:`text-center`,children:[(0,Z.jsx)(`h2`,{className:`text-2xl font-semibold mb-2`,children:`Coming Soon`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground max-w-md`,children:`Global context management is currently under development. Check back later for updates.`})]})})]}):(0,Z.jsx)(`div`,{className:`text-center space-y-4`,children:(0,Z.jsx)(`div`,{className:`text-destructive`,children:`Access denied. Admin privileges required.`})})}function kj(){let e=du()?.userType===`admin`;return(0,X.useEffect)(()=>{},[e]),e?(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{title:`All Agents`,description:`Manage all AI agents across all users`}),(0,Z.jsx)(`div`,{className:`flex flex-col items-center justify-center py-12 space-y-4`,children:(0,Z.jsxs)(`div`,{className:`text-center`,children:[(0,Z.jsx)(`h2`,{className:`text-2xl font-semibold mb-2`,children:`Coming Soon`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground max-w-md`,children:`Global agent management is currently under development. Check back later for updates.`})]})})]}):(0,Z.jsx)(`div`,{className:`text-center space-y-4`,children:(0,Z.jsx)(`div`,{className:`text-destructive`,children:`Access denied. Admin privileges required.`})})}var Aj={tail:200,level:``,module:``};function jj(e){return e.slice(-1e3)}function Mj(e){switch(e.levelLabel){case`fatal`:return`text-destructive`;case`error`:return`text-destructive`;case`warn`:return`text-warning`;case`info`:return`text-info`;case`debug`:return`text-muted-foreground`;case`trace`:return`text-muted-foreground`;default:return`text-success`}}function Nj(){let e=yD(),t=du()?.userType===`admin`,{showToast:n}=wo(),r=(0,X.useRef)(null),[i,a]=(0,X.useState)(Aj),[o,s]=(0,X.useState)(Aj),[c,l]=(0,X.useState)([]),[u,d]=(0,X.useState)(t),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(t?null:`Access denied. Admin privileges required.`),v=(0,X.useCallback)(async e=>{try{d(!0);let t=await Tj.logs.getLogs(e);l(jj(t)),_(null)}catch(e){let t=e instanceof Error?e.message:`Failed to load server logs`;_(t),n({title:`Error`,description:t,variant:`destructive`})}finally{d(!1)}},[n]);(0,X.useEffect)(()=>{t&&v(i)},[i,t,v]),(0,X.useEffect)(()=>{if(!t||m)return;let e=new AbortController;return p(!0),Tj.logs.streamLogs(i,{signal:e.signal,onEntry:e=>{l(t=>jj([...t,e]))},onError:e=>{_(e.message)}}).catch(e=>{let t=e instanceof Error?e.message:`Log stream stopped`;_(t),n({title:`Stream error`,description:t,variant:`destructive`})}).finally(()=>{p(!1)}),()=>{e.abort()}},[i,t,m,n]),(0,X.useEffect)(()=>{!r.current||m||(r.current.scrollTop=r.current.scrollHeight)},[c,m]);let y=()=>{a({tail:Math.min(Math.max(Number(o.tail)||Aj.tail,1),500),level:o.level||``,module:o.module.trim()})},b=(0,X.useMemo)(()=>[{value:``,label:`All levels`},{value:`trace`,label:`Trace`},{value:`debug`,label:`Debug`},{value:`info`,label:`Info`},{value:`warn`,label:`Warn`},{value:`error`,label:`Error`},{value:`fatal`,label:`Fatal`}],[]);return t?(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{onBack:e,title:`Server Logs`,description:`Live tail for the unified canvas-server logger`,actions:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm`,children:[(0,Z.jsx)(ui,{className:`w-4 h-4 ${f?`text-success`:`text-muted-foreground`}`}),(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:m?`Paused`:f?`Streaming`:`Disconnected`})]})}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-[140px_180px_1fr_auto]`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`tail`,children:`Tail`}),(0,Z.jsx)(q,{id:`tail`,type:`number`,min:1,max:500,value:o.tail,onChange:e=>s(t=>({...t,tail:Number(e.target.value)}))})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`level`,children:`Level`}),(0,Z.jsx)(`select`,{id:`level`,className:`w-full px-3 py-2 border rounded-md bg-background`,value:o.level,onChange:e=>s(t=>({...t,level:e.target.value})),children:b.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value||`all`))})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`module`,children:`Module filter`}),(0,Z.jsx)(q,{id:`module`,placeholder:`auth, http, workspace...`,value:o.module,onChange:e=>s(t=>({...t,module:e.target.value}))})]}),(0,Z.jsx)(`div`,{className:`flex items-end`,children:(0,Z.jsx)(Y,{onClick:y,className:`w-full`,children:`Apply`})})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsxs)(Y,{variant:`outline`,onClick:()=>h(e=>!e),children:[m?(0,Z.jsx)(Ar,{className:`w-4 h-4 mr-2`}):(0,Z.jsx)(Jr,{className:`w-4 h-4 mr-2`}),m?`Resume`:`Pause`]}),(0,Z.jsxs)(Y,{variant:`outline`,onClick:()=>v(i),children:[(0,Z.jsx)(Ba,{className:`w-4 h-4 mr-2`}),`Refresh`]}),(0,Z.jsxs)(Y,{variant:`outline`,onClick:()=>l([]),children:[(0,Z.jsx)(Qr,{className:`w-4 h-4 mr-2`}),`Clear buffer`]}),(0,Z.jsxs)(`span`,{className:`text-sm text-muted-foreground ml-auto`,children:[`Showing `,c.length,` lines`]})]}),g&&(0,Z.jsx)(`div`,{className:`rounded-md border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm text-destructive`,children:g}),(0,Z.jsx)(`div`,{className:`border rounded-lg overflow-hidden`,children:(0,Z.jsx)(`div`,{ref:r,"data-scheme":`dark`,className:`bg-background text-success font-mono text-xs h-viewport-pane overflow-auto p-4 rounded-md`,children:u?(0,Z.jsx)(`div`,{className:`text-muted-foreground`,children:`Loading logs...`}):c.length===0?(0,Z.jsx)(`div`,{className:`text-muted-foreground`,children:`No logs available`}):(0,Z.jsx)(`div`,{className:`whitespace-pre-wrap break-words`,children:c.map((e,t)=>(0,Z.jsx)(`div`,{className:Mj(e),children:e.line},`${e.time||`log`}-${t}`))})})})]}):(0,Z.jsx)(`div`,{className:`text-center space-y-4`,children:(0,Z.jsx)(`div`,{className:`text-destructive`,children:`Access denied. Admin privileges required.`})})}var Pj={async listRoles(e){let t=new URLSearchParams;e?.type&&t.append(`type`,e.type),e?.userId&&t.append(`userId`,e.userId),e?.workspaceId&&t.append(`workspaceId`,e.workspaceId),e?.status&&t.append(`status`,e.status);let n=t.toString(),r=n?`${no.roles}?${n}`:no.roles;return(await J.get(r)).roles||[]},async getRole(e){return(await J.get(`${no.roles}/${e}`)).role},async createRole(e){return(await J.post(no.roles,e)).role},async deleteRole(e,t=!1){let n=t?`?force=true`:``;await J.delete(`${no.roles}/${e}${n}`)},async startRole(e){return(await J.post(`${no.roles}/${e}/start`,{})).role},async stopRole(e){await J.post(`${no.roles}/${e}/stop`,{})},async restartRole(e){return(await J.post(`${no.roles}/${e}/restart`,{})).role},async getRoleLogs(e,t=100){return(await J.get(`${no.roles}/${e}/logs?tail=${t}`)).logs||[]},async getRoleStats(e){return(await J.get(`${no.roles}/${e}/stats`)).stats},async getRoleHealth(e){return(await J.get(`${no.roles}/${e}/health`)).health},async listTemplates(){return(await J.get(`${no.roleTemplates}`)).templates||[]},async getTemplate(e){return(await J.get(`${no.roleTemplates}/${e}`)).template}};function Fj({status:e}){let t={running:{icon:kr,color:`text-success`,bg:`bg-success-subtle`,label:`Running`},stopped:{icon:Bn,color:`text-muted-foreground`,bg:`bg-muted`,label:`Stopped`},starting:{icon:Zn,color:`text-info`,bg:`bg-info-subtle`,label:`Starting`},stopping:{icon:Zn,color:`text-warning`,bg:`bg-warning-subtle`,label:`Stopping`},error:{icon:er,color:`text-destructive`,bg:`bg-destructive-subtle`,label:`Error`},created:{icon:ui,color:`text-muted-foreground`,bg:`bg-muted`,label:`Created`},configured:{icon:ui,color:`text-info`,bg:`bg-info-subtle`,label:`Configured`},removed:{icon:Bn,color:`text-destructive`,bg:`bg-destructive-subtle`,label:`Removed`}},n=t[e]||t.created,r=n.icon;return(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium ${n.bg} ${n.color}`,children:[(0,Z.jsx)(r,{className:`w-3 h-3`}),n.label]})}function Ij({type:e}){return(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium ${e===`global`?`bg-accent text-primary`:`bg-info-subtle text-info`}`,children:[(0,Z.jsx)(pi,{className:`w-3 h-3`}),e===`global`?`Global`:`Workspace`]})}function Lj(){let e=yD(),t=du()?.userType===`admin`,[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(t),[c,l]=(0,X.useState)(t?null:`Access denied. Admin privileges required.`),[u,d]=(0,X.useState)(!1);Ae(()=>d(!1),u);let[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(!1);Ae(()=>h(!1),m);let[g,_]=(0,X.useState)([]),[v,y]=(0,X.useState)({type:``,status:``,search:``}),[b,x]=(0,X.useState)({template:``,name:``,type:`global`}),{showToast:S}=wo(),C=(0,X.useRef)(v);(0,X.useEffect)(()=>{C.current=v},[v]);let w=(0,X.useCallback)(async()=>{try{s(!0);let{type:e,status:t}=C.current,n=await Pj.listRoles({type:e||void 0,status:t||void 0});r(n),l(null)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch roles`;l(t)}finally{s(!1)}},[]),T=(0,X.useCallback)(async()=>{try{let e=await Pj.listTemplates();a(e)}catch(e){console.error(`Failed to fetch templates:`,e)}},[]);(0,X.useEffect)(()=>{t&&(w(),T())},[t,w,T]);let E=async()=>{if(!b.template||!b.name){S({title:`Validation Error`,description:`Template and name are required`,variant:`destructive`});return}try{await Pj.createRole(b),S({title:`Success`,description:`Role "${b.name}" created successfully`}),d(!1),M(),w()}catch(e){let t=e instanceof Error?e.message:`Failed to create role`;S({title:`Error`,description:t,variant:`destructive`})}},D=async e=>{try{await Pj.startRole(e.id),S({title:`Success`,description:`Role "${e.name}" started successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to start role`;S({title:`Error`,description:t,variant:`destructive`})}},O=async e=>{try{await Pj.stopRole(e.id),S({title:`Success`,description:`Role "${e.name}" stopped successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to stop role`;S({title:`Error`,description:t,variant:`destructive`})}},k=async e=>{try{await Pj.restartRole(e.id),S({title:`Success`,description:`Role "${e.name}" restarted successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to restart role`;S({title:`Error`,description:t,variant:`destructive`})}},A=async e=>{if(confirm(`Are you sure you want to delete role "${e.name}"?`))try{await Pj.deleteRole(e.id,e.status===`running`),S({title:`Success`,description:`Role "${e.name}" deleted successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to delete role`;S({title:`Error`,description:t,variant:`destructive`})}},j=async e=>{try{let t=await Pj.getRoleLogs(e.id,100);_(t),p(e),h(!0)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch logs`;S({title:`Error`,description:t,variant:`destructive`})}},M=()=>{x({template:``,name:``,type:`global`})},N=()=>{M(),d(!0)},P=()=>{d(!1),M()},ee=n.filter(e=>!v.search||e.name.toLowerCase().includes(v.search.toLowerCase())||e.template.toLowerCase().includes(v.search.toLowerCase()));return t?c&&!t?(0,Z.jsx)(`div`,{className:`text-center space-y-4`,children:(0,Z.jsx)(`div`,{className:`text-destructive`,children:c})}):(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{onBack:e,title:`Role Management`,description:`Manage global and workspace roles for Canvas services`,actions:(0,Z.jsxs)(Y,{onClick:N,className:`gap-2`,children:[(0,Z.jsx)(br,{className:`w-4 h-4`}),`Create Role`]})}),(0,Z.jsxs)(`div`,{className:`flex gap-4 items-end`,children:[(0,Z.jsxs)(`div`,{className:`flex-1`,children:[(0,Z.jsx)(G,{htmlFor:`search`,children:`Search`}),(0,Z.jsx)(q,{id:`search`,placeholder:`Search by name or template...`,value:v.search,onChange:e=>y({...v,search:e.target.value})})]}),(0,Z.jsxs)(`div`,{className:`w-48`,children:[(0,Z.jsx)(G,{htmlFor:`type`,children:`Type`}),(0,Z.jsxs)(`select`,{id:`type`,className:`w-full px-3 py-2 border rounded-md bg-background`,value:v.type,onChange:e=>y({...v,type:e.target.value}),children:[(0,Z.jsx)(`option`,{value:``,children:`All Types`}),(0,Z.jsx)(`option`,{value:`global`,children:`Global`}),(0,Z.jsx)(`option`,{value:`workspace`,children:`Workspace`})]})]}),(0,Z.jsxs)(`div`,{className:`w-48`,children:[(0,Z.jsx)(G,{htmlFor:`status`,children:`Status`}),(0,Z.jsxs)(`select`,{id:`status`,className:`w-full px-3 py-2 border rounded-md bg-background`,value:v.status,onChange:e=>y({...v,status:e.target.value}),children:[(0,Z.jsx)(`option`,{value:``,children:`All Statuses`}),(0,Z.jsx)(`option`,{value:`running`,children:`Running`}),(0,Z.jsx)(`option`,{value:`stopped`,children:`Stopped`}),(0,Z.jsx)(`option`,{value:`starting`,children:`Starting`}),(0,Z.jsx)(`option`,{value:`error`,children:`Error`})]})]}),(0,Z.jsxs)(Y,{onClick:w,variant:`outline`,children:[(0,Z.jsx)(Ba,{className:`w-4 h-4 mr-2`}),`Refresh`]})]}),o?(0,Z.jsx)(`div`,{className:`text-center py-8`,children:`Loading roles...`}):ee.length===0?(0,Z.jsxs)(`div`,{className:`text-center py-8 border rounded-lg`,children:[(0,Z.jsx)(pi,{className:`w-12 h-12 mx-auto text-muted-foreground mb-4`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:v.search||v.type||v.status?`No roles match your filters`:`No roles created yet`}),!v.search&&!v.type&&!v.status&&(0,Z.jsxs)(Y,{onClick:N,variant:`outline`,className:`mt-4`,children:[(0,Z.jsx)(br,{className:`w-4 h-4 mr-2`}),`Create Your First Role`]})]}):(0,Z.jsx)(`div`,{className:`border rounded-lg`,children:(0,Z.jsxs)(`table`,{className:`w-full`,children:[(0,Z.jsx)(`thead`,{className:`bg-muted/50`,children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{className:`text-left p-4 font-medium`,children:`Name`}),(0,Z.jsx)(`th`,{className:`text-left p-4 font-medium`,children:`Template`}),(0,Z.jsx)(`th`,{className:`text-left p-4 font-medium`,children:`Type`}),(0,Z.jsx)(`th`,{className:`text-left p-4 font-medium`,children:`Status`}),(0,Z.jsx)(`th`,{className:`text-left p-4 font-medium`,children:`Container`}),(0,Z.jsx)(`th`,{className:`text-left p-4 font-medium`,children:`Created`}),(0,Z.jsx)(`th`,{className:`text-right p-4 font-medium`,children:`Actions`})]})}),(0,Z.jsx)(`tbody`,{className:`divide-y`,children:ee.map(e=>(0,Z.jsxs)(`tr`,{className:`hover:bg-muted/50`,children:[(0,Z.jsx)(`td`,{className:`p-4 font-medium`,children:e.name}),(0,Z.jsx)(`td`,{className:`p-4 text-sm text-muted-foreground`,children:e.template}),(0,Z.jsx)(`td`,{className:`p-4`,children:(0,Z.jsx)(Ij,{type:e.type})}),(0,Z.jsx)(`td`,{className:`p-4`,children:(0,Z.jsx)(Fj,{status:e.status})}),(0,Z.jsx)(`td`,{className:`p-4 text-sm text-muted-foreground`,children:e.container?.name||`-`}),(0,Z.jsx)(`td`,{className:`p-4 text-sm text-muted-foreground`,children:new Date(e.createdAt).toLocaleDateString()}),(0,Z.jsx)(`td`,{className:`p-4`,children:(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[e.status===`stopped`||e.status===`created`?(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>D(e),title:`Start`,children:(0,Z.jsx)(Ar,{className:`w-4 h-4`})}):e.status===`running`?(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>O(e),title:`Stop`,children:(0,Z.jsx)(Sa,{className:`w-4 h-4`})}):null,e.status===`running`&&(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>k(e),title:`Restart`,children:(0,Z.jsx)(Ba,{className:`w-4 h-4`})}),(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>j(e),title:`View Logs`,children:(0,Z.jsx)(Ki,{className:`w-4 h-4`})}),(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>A(e),title:`Delete`,className:`text-destructive hover:text-destructive`,children:(0,Z.jsx)(ti,{className:`w-4 h-4`})})]})})]},e.id))})]})}),u&&(0,Z.jsx)(`div`,{className:`fixed inset-0 bg-scrim flex items-center justify-center z-50`,children:(0,Z.jsx)(`div`,{className:`bg-background rounded-lg shadow-elevation-3 max-w-lg w-full mx-4 max-h-viewport-modal overflow-y-auto`,children:(0,Z.jsxs)(`div`,{className:`p-6 space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-bold`,children:`Create New Role`}),(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,onClick:P,children:(0,Z.jsx)(vr,{className:`w-4 h-4`})})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`template`,children:`Template *`}),(0,Z.jsxs)(`select`,{id:`template`,className:`w-full px-3 py-2 border rounded-md bg-background mt-1`,value:b.template,onChange:e=>x({...b,template:e.target.value}),children:[(0,Z.jsx)(`option`,{value:``,children:`Select a template...`}),i.map(e=>(0,Z.jsxs)(`option`,{value:e.id,children:[e.name,` - `,e.description]},e.id))]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`name`,children:`Role Name *`}),(0,Z.jsx)(q,{id:`name`,placeholder:`e.g., canvas-sshd`,value:b.name,onChange:e=>x({...b,name:e.target.value})})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`roleType`,children:`Type *`}),(0,Z.jsxs)(`select`,{id:`roleType`,className:`w-full px-3 py-2 border rounded-md bg-background mt-1`,value:b.type,onChange:e=>x({...b,type:e.target.value}),children:[(0,Z.jsx)(`option`,{value:`global`,children:`Global (Server-wide)`}),(0,Z.jsx)(`option`,{value:`workspace`,children:`Workspace (User-scoped)`})]})]}),b.template&&(0,Z.jsxs)(`div`,{className:`p-4 bg-muted rounded-lg`,children:[(0,Z.jsx)(`h3`,{className:`font-medium mb-2`,children:`Template Info`}),i.find(e=>e.id===b.template)&&(0,Z.jsxs)(`div`,{className:`text-sm space-y-1 text-muted-foreground`,children:[(0,Z.jsxs)(`p`,{children:[(0,Z.jsx)(`strong`,{children:`Image:`}),` `,i.find(e=>e.id===b.template)?.container.image]}),(0,Z.jsxs)(`p`,{children:[(0,Z.jsx)(`strong`,{children:`Category:`}),` `,i.find(e=>e.id===b.template)?.category]}),i.find(e=>e.id===b.template)?.documentation?.readme&&(0,Z.jsx)(`p`,{className:`mt-2`,children:i.find(e=>e.id===b.template)?.documentation?.readme})]})]})]}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2 pt-4 border-t`,children:[(0,Z.jsx)(Y,{variant:`outline`,onClick:P,children:`Cancel`}),(0,Z.jsx)(Y,{onClick:E,children:`Create Role`})]})]})})}),m&&f&&(0,Z.jsx)(`div`,{className:`fixed inset-0 bg-scrim flex items-center justify-center z-50`,children:(0,Z.jsxs)(`div`,{className:`bg-background rounded-lg shadow-elevation-3 max-w-4xl w-full mx-4 max-h-viewport-modal flex flex-col`,children:[(0,Z.jsxs)(`div`,{className:`p-6 border-b flex items-center justify-between`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-xl font-bold`,children:`Role Logs`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:f.name})]}),(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,onClick:()=>h(!1),children:(0,Z.jsx)(vr,{className:`w-4 h-4`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto p-6`,children:(0,Z.jsx)(`div`,{"data-scheme":`dark`,className:`bg-background text-success p-4 rounded font-mono text-xs overflow-x-auto`,children:g.length===0?(0,Z.jsx)(`div`,{className:`text-muted-foreground`,children:`No logs available`}):(0,Z.jsx)(`pre`,{children:g.join(`
|
|
36
38
|
`)})})}),(0,Z.jsx)(`div`,{className:`p-4 border-t flex justify-end`,children:(0,Z.jsx)(Y,{onClick:()=>h(!1),children:`Close`})})]})})]}):(0,Z.jsx)(`div`,{className:`text-center space-y-4`,children:(0,Z.jsx)(`div`,{className:`text-destructive`,children:`Access denied. Admin privileges required.`})})}function Rj(){let e=yD(),t=du(),n=t?.userType===`admin`,[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(n),[s,c]=(0,X.useState)(n?null:`Access denied. Admin privileges required.`),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(null),[y,b]=(0,X.useState)({status:``,userType:``,search:``}),[x,S]=(0,X.useState)({name:``,email:``,password:``,userType:`user`,status:`active`}),{showToast:C}=wo();(0,X.useEffect)(()=>{n&&(async()=>{try{let e=await gu(),t=!!e?.strategies?.local?.requireEmailVerification;g(t),v(e?.strategies?.local?.passwordPolicy||null)}catch{g(!1),v(null)}})()},[n]);let w=e=>{let t=e.trim().toLowerCase();return t.length<3||t.length>39?`Username must be 3-39 characters long`:/^[a-z0-9_-]+$/.test(t)?null:`Username can only contain lowercase letters, numbers, underscores, and hyphens`},T=e=>{let t=e||``,n=_||{},r=n.minLength??12,i=n.maxLength??128,a=[];return t.length<r&&a.push(`at least ${r} characters`),t.length>i&&a.push(`no more than ${i} characters`),(n.requireUppercase??!0)&&!/[A-Z]/.test(t)&&a.push(`an uppercase letter`),(n.requireLowercase??!0)&&!/[a-z]/.test(t)&&a.push(`a lowercase letter`),(n.requireNumbers??!0)&&!/[0-9]/.test(t)&&a.push(`a number`),(n.requireSpecialChars??!0)&&!/[^A-Za-z0-9]/.test(t)&&a.push(`a special character`),a.length?`Password must contain ${a.join(`, `).replace(/, ([^,]*)$/,` and $1`)}.`:null},E=()=>{let e=_||{},t=[],n=e.minLength??12;return t.push(`${n}+ chars`),(e.requireUppercase??!0)&&t.push(`uppercase`),(e.requireLowercase??!0)&&t.push(`lowercase`),(e.requireNumbers??!0)&&t.push(`number`),(e.requireSpecialChars??!0)&&t.push(`special`),t.join(`, `)},D=e=>{if(!e)return`-`;let t=new Date(e);return isNaN(t.getTime())?`-`:t.toLocaleString()},O=async e=>{try{await _u(e),C({title:`Verification email`,description:`If the account exists, a verification email was sent.`})}catch(e){let t=e instanceof Error?e.message:`Failed to send verification email`;C({title:`Error`,description:t,variant:`destructive`})}},k=(0,X.useCallback)(async()=>{try{o(!0);let{status:e,userType:t}=y,n=await Tj.users.listUsers({status:e||void 0,userType:t||void 0});i(n),c(null)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch users`;c(t),C({title:`Error`,description:t,variant:`destructive`})}finally{o(!1)}},[y,C]);(0,X.useEffect)(()=>{n&&k()},[k,n]);let A=async e=>{if(e.preventDefault(),!x.name.trim()||!x.email.trim()){C({title:`Validation Error`,description:`Name and email are required`,variant:`destructive`});return}let t=w(x.name);if(t){C({title:`Validation Error`,description:t,variant:`destructive`});return}if(!x.password.trim()){C({title:`Validation Error`,description:`Password is required`,variant:`destructive`});return}let n=T(x.password);if(n){C({title:`Validation Error`,description:n,variant:`destructive`});return}u(!0);try{let e={name:x.name.trim().toLowerCase(),email:x.email.trim(),userType:x.userType,status:x.status};if(x.password.trim()&&(e.password=x.password),await Tj.users.createUser(e),h&&x.status===`pending`)try{await _u(x.email.trim())}catch{}S({name:``,email:``,password:``,userType:`user`,status:h?`pending`:`active`}),m(!1),await k(),C({title:`Success`,description:`User created successfully`})}catch(e){let t=e instanceof Error?e.message:`Failed to create user`;C({title:`Error`,description:t,variant:`destructive`})}finally{u(!1)}},j=async e=>{if(e.preventDefault(),!d)return;let t=w(x.name);if(t){C({title:`Validation Error`,description:t,variant:`destructive`});return}if(x.password.trim()){let e=T(x.password);if(e){C({title:`Validation Error`,description:e,variant:`destructive`});return}}u(!0);try{let e={name:x.name.trim().toLowerCase(),email:x.email.trim(),userType:x.userType,status:x.status};x.password.trim()&&(e.password=x.password),await Tj.users.updateUser(d.id,e),f(null),m(!1),await k(),C({title:`Success`,description:`User updated successfully`})}catch(e){let t=e instanceof Error?e.message:`Failed to update user`;C({title:`Error`,description:t,variant:`destructive`})}finally{u(!1)}},M=async(e,t)=>{if(confirm(`Are you sure you want to delete user "${t}"? This action cannot be undone.`))try{await Tj.users.deleteUser(e),await k(),C({title:`Success`,description:`User deleted successfully`})}catch(e){let t=e instanceof Error?e.message:`Failed to delete user`;C({title:`Error`,description:t,variant:`destructive`})}},N=()=>{f(null),S({name:``,email:``,password:``,userType:`user`,status:h?`pending`:`active`}),m(!0)},P=e=>{f(e),S({name:e.name,email:e.email,password:``,userType:e.userType,status:e.status}),m(!0)},ee=()=>{m(!1),f(null)};Ae(ee,p);let F=r.filter(e=>y.search===``||e.name.toLowerCase().includes(y.search.toLowerCase())||e.email.toLowerCase().includes(y.search.toLowerCase()));return n?(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{onBack:e,title:`User Management`,description:`Manage user accounts and permissions`}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 md:flex-row md:items-center md:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 md:flex-row md:items-center`,children:[(0,Z.jsx)(q,{placeholder:`Search users...`,value:y.search,onChange:e=>b(t=>({...t,search:e.target.value})),className:`md:w-64`}),(0,Z.jsxs)(`select`,{value:y.status,onChange:e=>b(t=>({...t,status:e.target.value})),className:`px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:``,children:`All Statuses`}),(0,Z.jsx)(`option`,{value:`active`,children:`Active`}),(0,Z.jsx)(`option`,{value:`inactive`,children:`Inactive`}),(0,Z.jsx)(`option`,{value:`pending`,children:`Pending`}),(0,Z.jsx)(`option`,{value:`deleted`,children:`Deleted`})]}),(0,Z.jsxs)(`select`,{value:y.userType,onChange:e=>b(t=>({...t,userType:e.target.value})),className:`px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:``,children:`All Types`}),(0,Z.jsx)(`option`,{value:`user`,children:`User`}),(0,Z.jsx)(`option`,{value:`admin`,children:`Admin`})]})]}),(0,Z.jsxs)(Y,{onClick:N,children:[(0,Z.jsx)(br,{className:`mr-2 h-4 w-4`}),`Create User`]})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[a&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading users...`}),s&&!r.length&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:s})}),!a&&!s&&F.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No users found`}),F.length>0&&(0,Z.jsx)(`div`,{className:`border rounded-md`,children:(0,Z.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Z.jsxs)(`table`,{className:`w-full`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{className:`bg-muted/50`,children:[(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Name`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Email`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Type`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Status`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Created`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Updated`}),(0,Z.jsx)(`th`,{className:`text-right p-3 font-medium`,children:`Actions`})]})}),(0,Z.jsx)(`tbody`,{children:F.map(e=>(0,Z.jsxs)(`tr`,{className:`border-t`,children:[(0,Z.jsx)(`td`,{className:`p-3 font-medium`,children:e.name}),(0,Z.jsx)(`td`,{className:`p-3`,children:e.email}),(0,Z.jsx)(`td`,{className:`p-3`,children:(0,Z.jsx)(`span`,{className:`px-2 py-1 rounded-full text-xs ${e.userType===`admin`?`bg-destructive-subtle text-destructive`:`bg-info-subtle text-info`}`,children:e.userType})}),(0,Z.jsx)(`td`,{className:`p-3`,children:(0,Z.jsx)(`span`,{className:`px-2 py-1 rounded-full text-xs ${e.status===`active`?`bg-success-subtle text-success`:e.status===`inactive`?`bg-warning-subtle text-warning`:e.status===`pending`?`bg-info-subtle text-info`:`bg-destructive-subtle text-destructive`}`,children:e.status})}),(0,Z.jsx)(`td`,{className:`p-3`,children:D(e.createdAt)}),(0,Z.jsx)(`td`,{className:`p-3`,children:D(e.updatedAt)}),(0,Z.jsxs)(`td`,{className:`p-3 text-right space-x-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>P(e),children:(0,Z.jsx)(Za,{className:`h-4 w-4`})}),h&&e.status===`pending`&&(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>O(e.email),title:`Resend activation email`,children:`Resend activation`}),(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>M(e.id,e.name),className:`text-destructive hover:bg-destructive/10 hover:text-destructive`,disabled:e.id===t?.id,title:e.id===t?.id?`Cannot delete your own account`:`Delete user`,children:(0,Z.jsx)(ti,{className:`h-4 w-4`})})]})]},e.id))})]})})})]}),p&&(0,Z.jsx)(`div`,{className:`fixed inset-0 bg-scrim flex items-center justify-center z-50`,children:(0,Z.jsxs)(`div`,{className:`bg-card rounded-lg p-6 w-full max-w-md mx-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-4`,children:[(0,Z.jsx)(`h3`,{className:`text-lg font-semibold`,children:d?`Edit User`:`Create New User`}),(0,Z.jsx)(Y,{variant:`ghost`,size:`sm`,onClick:ee,children:(0,Z.jsx)(vr,{className:`h-4 w-4`})})]}),(0,Z.jsxs)(`form`,{onSubmit:d?j:A,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`name`,children:`Username`}),(0,Z.jsx)(q,{id:`name`,type:`text`,value:x.name,onChange:e=>S(t=>({...t,name:e.target.value.toLowerCase().replace(/\s+/g,``)})),placeholder:`Enter username`,disabled:l,required:!0}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:`3-39 characters, lowercase letters, numbers, underscores, and hyphens only`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`email`,children:`Email`}),(0,Z.jsx)(q,{id:`email`,type:`email`,value:x.email,onChange:e=>S(t=>({...t,email:e.target.value})),placeholder:`Enter email address`,disabled:l,required:!0})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(G,{htmlFor:`password`,children:[`Password `,d&&`(leave blank to keep current)`]}),(0,Z.jsx)(q,{id:`password`,type:`password`,value:x.password,onChange:e=>S(t=>({...t,password:e.target.value})),placeholder:d?`Leave blank to keep current`:`Enter password`,disabled:l,required:!d}),!d&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:[`Must satisfy: `,E()]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`userType`,children:`User Type`}),(0,Z.jsxs)(`select`,{id:`userType`,value:x.userType,onChange:e=>S(t=>({...t,userType:e.target.value})),disabled:l,className:`w-full px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:`user`,children:`User`}),(0,Z.jsx)(`option`,{value:`admin`,children:`Admin`})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(G,{htmlFor:`status`,children:`Status`}),(0,Z.jsxs)(`select`,{id:`status`,value:x.status,onChange:e=>S(t=>({...t,status:e.target.value})),disabled:l,className:`w-full px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:`active`,children:`Active`}),(0,Z.jsx)(`option`,{value:`inactive`,children:`Inactive`}),(0,Z.jsx)(`option`,{value:`pending`,children:`Pending`}),(0,Z.jsx)(`option`,{value:`deleted`,children:`Deleted`})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2 pt-4`,children:[(0,Z.jsx)(Y,{type:`submit`,disabled:l,className:`flex-1`,children:l?`Processing...`:d?`Update User`:`Create User`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,onClick:ee,disabled:l,children:`Cancel`})]})]})]})})]}):(0,Z.jsx)(`div`,{className:`text-center space-y-4`,children:(0,Z.jsx)(`div`,{className:`text-destructive`,children:`Access denied. Admin privileges required.`})})}function zj(){let e=yD(),{showToast:t}=wo(),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(!0),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(``),f=du()?.userType===`admin`,p=(0,X.useCallback)(()=>nj().then(e=>{r(e),d((e.allowHosts||[]).join(`, `)),l(null)}).catch(e=>l(e instanceof Error?e.message:`Failed to load server defaults`)).finally(()=>a(!1)),[]);(0,X.useEffect)(()=>{p()},[p]);let m=()=>{a(!0),p()};return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl p-6`,children:[(0,Z.jsx)(sw,{onBack:e,compact:!0,className:`mb-6`,title:`Server search & AI defaults`,description:`Entire server · Set the embedding defaults accounts inherit. Account and workspace overrides take priority. Running workspaces adopt new defaults when restarted.`,actions:(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:m,disabled:i,children:[(0,Z.jsx)(Er,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})}),!f&&(0,Z.jsxs)(`div`,{className:`mb-4 flex items-start gap-2 rounded-md border p-3 text-xs`,children:[(0,Z.jsx)(ha,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:`Read-only. Changing server defaults requires an admin account. This is what your workspaces inherit.`})]}),i?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(Er,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):c||!n?(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`rounded-md border border-destructive/40 bg-destructive/5 p-4 text-sm`,children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Server defaults unavailable`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:c||`No config returned.`})]}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:m,children:`Retry`})]}):(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Config file: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:n.configPath})]}),(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsx)(`h3`,{className:`text-sm font-semibold`,children:`Endpoint allowlist`}),(0,Z.jsx)(`p`,{className:`mb-2 mt-1 text-[11px] text-muted-foreground`,children:`Provider URLs are fetched by the server, so they are an SSRF surface. Link-local and cloud-metadata targets are always refused; list additional hosts here to permit them. Comma-separated, empty = only the always-blocked ranges apply.`}),(0,Z.jsx)(q,{value:u,disabled:!f,onChange:e=>d(e.target.value),placeholder:`gpu.internal, embeddings.example.com`,className:`h-8 text-sm`})]}),(0,Z.jsx)(bj,{value:n.serverDefaults||{},effective:n.serverDefaults||{},inherited:{},saving:o,disabled:!f,saveLabel:`Save server defaults`,onSave:async e=>{s(!0);try{let n=u.split(`,`).map(e=>e.trim()).filter(Boolean),r=await rj({...e,...n.length?{allowHosts:n}:{}});t({title:`Server defaults saved`,description:`Written to ${r.configPath}. Every user inherits these, so running workspaces keep their current tables until restarted.`}),await p()}catch(e){t({title:`Save failed`,description:e instanceof Error?e.message:`Failed to save`,variant:`destructive`})}finally{s(!1)}}},JSON.stringify(n.serverDefaults))]})]})}function Bj(){return J.get(no.admin.authConfig)}function Vj(e){return J.put(no.admin.authConfig,e)}function Hj(e,t,n){return J.post(`${no.admin.authConfig}/test`,{strategy:`ldap`,name:e,server:t,email:n})}function Uj(e,t,n){return J.post(`${no.admin.authConfig}/test`,{strategy:`imap`,domain:e,email:t,password:n})}var Wj=0,Gj=()=>`row-${++Wj}`;function Kj(e){let{servers:t,...n}=e.strategies.ldap,{domains:r,...i}=e.strategies.imap;return{allowUserRegistrations:e.allowUserRegistrations,local:e.strategies.local,ldap:{...n,servers:Object.entries(t).map(([e,t])=>({...t,id:Gj(),name:e,originalName:e}))},imap:{...i,domains:Object.entries(r).map(([e,t])=>({...t,id:Gj(),domain:e}))},google:e.strategies.google??{enabled:!1,defaultUserType:`user`,defaultStatus:`active`,clientId:``,clientSecretSet:!1,allowedDomains:[],autoCreateUsers:!0,webOrigins:[]}}}function qj(e){let{id:t,name:n,originalName:r,...i}=e;return{...i,...r&&r!==e.name?{previousName:r}:{}}}function Jj(e){return{allowUserRegistrations:e.allowUserRegistrations,strategies:{local:e.local,ldap:{enabled:e.ldap.enabled,defaultUserType:e.ldap.defaultUserType,defaultStatus:e.ldap.defaultStatus,servers:Object.fromEntries(e.ldap.servers.map(e=>[e.name.trim(),qj(e)]))},imap:{enabled:e.imap.enabled,defaultUserType:e.imap.defaultUserType,defaultStatus:e.imap.defaultStatus,domains:Object.fromEntries(e.imap.domains.map(({id:e,domain:t,...n})=>[t.trim().toLowerCase(),n]))},google:e.google}}}function Yj({value:e,onChange:t,placeholder:n,disabled:r}){let i=e.join(`, `),[a,o]=(0,X.useState)(i),[s,c]=(0,X.useState)(i);return i!==s&&(c(i),a.split(/[\s,]+/).filter(Boolean).join(`, `)!==i&&o(i)),(0,Z.jsx)(q,{className:`h-8 text-sm`,value:a,placeholder:n,disabled:r,onChange:e=>{o(e.target.value),t(e.target.value.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean))}})}var Xj={originalName:null,url:`ldap://`,bindDN:``,bindPasswordSet:!1,bindPassword:void 0,searchBase:``,searchFilter:`(mail={{email}})`,attributes:[`mail`,`cn`,`displayName`,`memberOf`],groupAttribute:`memberOf`,tls:!1},Zj={domain:``,name:``,host:``,port:993,secure:!0,startTLS:!1,requireAppPassword:!1},Qj=`h-8 rounded-md border border-input bg-transparent px-2 text-sm outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-50`;function $j({label:e,hint:t,children:n,className:r}){return(0,Z.jsxs)(`label`,{className:K(`flex min-w-0 flex-col gap-1`,r),children:[(0,Z.jsx)(`span`,{className:`text-xs font-medium`,children:e}),n,t&&(0,Z.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:t})]})}function eM({checked:e,onChange:t,disabled:n,label:r,hint:i}){return(0,Z.jsxs)(`label`,{className:`flex items-start gap-2 text-sm`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:e,disabled:n,onChange:e=>t(e.target.checked)}),(0,Z.jsxs)(`span`,{children:[r,i&&(0,Z.jsx)(`span`,{className:`block text-[11px] text-muted-foreground`,children:i})]})]})}function tM({title:e,description:t,enabled:n,onToggle:r,disabled:i,children:a}){return(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`h3`,{className:`text-sm font-semibold`,children:e}),(0,Z.jsx)(`p`,{className:`mt-1 text-[11px] text-muted-foreground`,children:t})]}),r&&(0,Z.jsxs)(`label`,{className:`flex shrink-0 items-center gap-2 text-xs font-medium`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:!!n,disabled:i,onChange:e=>r(e.target.checked)}),n?`Enabled`:`Disabled`]})]}),(0,Z.jsx)(`div`,{className:K(`mt-4 space-y-4`,r&&!n&&`opacity-60`),children:a})]})}function nM({result:e}){return e?(0,Z.jsxs)(`div`,{className:K(`flex items-start gap-2 rounded-md border p-2 text-xs`,e.ok?`border-emerald-500/40 bg-emerald-500/5`:`border-destructive/40 bg-destructive/5`),children:[e.ok?(0,Z.jsx)(Sr,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-600`}):(0,Z.jsx)(Bn,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-destructive`}),(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`p`,{children:e.message}),e.user&&e.user.groups.length>0&&(0,Z.jsxs)(`p`,{className:`mt-1 break-all text-muted-foreground`,children:[`Groups: `,e.user.groups.join(` · `)]})]})]}):null}function rM({value:e,onChange:t,disabled:n}){return(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-4`,children:[(0,Z.jsx)($j,{label:`New accounts are`,children:(0,Z.jsxs)(`select`,{className:Qj,value:e.defaultUserType,disabled:n,onChange:e=>t({defaultUserType:e.target.value}),children:[(0,Z.jsx)(`option`,{value:`user`,children:`Users`}),(0,Z.jsx)(`option`,{value:`admin`,children:`Admins`})]})}),(0,Z.jsx)($j,{label:`Initial status`,children:(0,Z.jsxs)(`select`,{className:Qj,value:e.defaultStatus,disabled:n,onChange:e=>t({defaultStatus:e.target.value}),children:[(0,Z.jsx)(`option`,{value:`active`,children:`Active — can sign in right away`}),(0,Z.jsx)(`option`,{value:`pending`,children:`Pending — an admin activates them`}),(0,Z.jsx)(`option`,{value:`inactive`,children:`Inactive`})]})})]}),e.defaultUserType===`admin`&&(0,Z.jsxs)(`p`,{className:`flex items-start gap-1.5 text-[11px] text-destructive`,children:[(0,Z.jsx)(ha,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),`Everyone who can sign in through this backend becomes a server admin on first login.`]})]})}function iM({row:e,index:t,onChange:n,onRemove:r,disabled:i}){let[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(null),d=async()=>{c(!0),u(null);try{u(await Hj(e.originalName??e.name,qj(e),a.trim()||void 0))}catch(e){u({ok:!1,message:e instanceof Error?e.message:`Test failed`})}finally{c(!1)}},f=e.bindPassword===null?`cleared on save`:typeof e.bindPassword==`string`?`replaced on save`:e.bindPasswordSet?`stored — leave empty to keep it`:`none set`;return(0,Z.jsxs)(`div`,{className:`space-y-3 rounded-md border p-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsxs)(`span`,{className:`shrink-0 text-[11px] text-muted-foreground`,children:[`#`,t+1]}),(0,Z.jsx)(q,{className:`h-8 max-w-[14rem] font-mono text-sm`,value:e.name,disabled:i,onChange:e=>n({name:e.target.value}),placeholder:`primary`,"aria-label":`Server name`}),(0,Z.jsx)(`div`,{className:`flex-1`}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:r,disabled:i,"aria-label":`Remove server`,children:(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsx)($j,{label:`Server URL`,hint:`ldap:// or ldaps://host:port`,children:(0,Z.jsx)(q,{className:`h-8 font-mono text-sm`,value:e.url,disabled:i,onChange:e=>n({url:e.target.value}),placeholder:`ldaps://dc1.example.com:636`})}),(0,Z.jsx)($j,{label:`Search base`,children:(0,Z.jsx)(q,{className:`h-8 font-mono text-sm`,value:e.searchBase,disabled:i,onChange:e=>n({searchBase:e.target.value}),placeholder:`ou=users,dc=example,dc=com`})}),(0,Z.jsx)($j,{label:`Bind DN`,hint:`Service account used to look users up. Empty = anonymous search.`,children:(0,Z.jsx)(q,{className:`h-8 font-mono text-sm`,value:e.bindDN,disabled:i,onChange:e=>n({bindDN:e.target.value}),placeholder:`cn=canvas,ou=services,dc=example,dc=com`})}),(0,Z.jsx)($j,{label:`Bind password`,hint:(0,Z.jsxs)(Z.Fragment,{children:[`Currently: `,f,e.bindPasswordSet&&e.bindPassword!==null&&(0,Z.jsxs)(Z.Fragment,{children:[` · `,(0,Z.jsx)(`button`,{type:`button`,className:`underline hover:text-foreground`,disabled:i,onClick:()=>n({bindPassword:null}),children:`clear`})]})]}),children:(0,Z.jsx)(q,{className:`h-8 text-sm`,type:`password`,autoComplete:`new-password`,value:typeof e.bindPassword==`string`?e.bindPassword:``,disabled:i,onChange:e=>n({bindPassword:e.target.value===``?void 0:e.target.value}),placeholder:e.bindPasswordSet&&e.bindPassword!==null?`••••••••`:``})}),(0,Z.jsx)($j,{label:`User search filter`,hint:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`font-mono`,children:`{{email}}`}),` is replaced by the address typed at sign-in.`]}),children:(0,Z.jsx)(q,{className:`h-8 font-mono text-sm`,value:e.searchFilter,disabled:i,onChange:e=>n({searchFilter:e.target.value})})}),(0,Z.jsx)($j,{label:`Group attribute`,hint:`Group memberships drive team workspace sharing.`,children:(0,Z.jsx)(q,{className:`h-8 font-mono text-sm`,value:e.groupAttribute,disabled:i,onChange:e=>n({groupAttribute:e.target.value}),placeholder:`memberOf`})}),(0,Z.jsx)($j,{label:`Attributes to read`,hint:`Comma-separated.`,className:`sm:col-span-2`,children:(0,Z.jsx)(q,{className:`h-8 font-mono text-sm`,value:e.attributes.join(`, `),disabled:i,onChange:e=>n({attributes:e.target.value.split(`,`).map(e=>e.trim()).filter(Boolean)})})})]}),(0,Z.jsx)(eM,{checked:e.tls,disabled:i,onChange:e=>n({tls:e}),label:`Accept self-signed certificates`,hint:`Skips certificate verification for ldaps://. Only for directories with a private CA.`}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-end gap-2 border-t pt-3`,children:[(0,Z.jsx)($j,{label:`Test`,hint:`Binds with the settings above (unsaved edits included). Add an e-mail to also look that user up.`,className:`min-w-[14rem] flex-1`,children:(0,Z.jsx)(q,{className:`h-8 text-sm`,type:`email`,value:a,onChange:e=>o(e.target.value),placeholder:`someone@example.com (optional)`})}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:d,disabled:s||i,className:`mb-5`,children:[s&&(0,Z.jsx)(Ti,{className:`mr-2 h-3.5 w-3.5 animate-spin`}),`Test connection`]})]}),(0,Z.jsx)(nM,{result:l})]})}function aM({row:e,onChange:t,onRemove:n,disabled:r}){let[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(null);return(0,Z.jsxs)(`div`,{className:`space-y-3 rounded-md border p-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:`@`}),(0,Z.jsx)(q,{className:`h-8 max-w-[16rem] font-mono text-sm`,value:e.domain,disabled:r,onChange:e=>t({domain:e.target.value}),placeholder:`example.com`,"aria-label":`E-mail domain`}),(0,Z.jsx)(`div`,{className:`flex-1`}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:n,disabled:r,"aria-label":`Remove domain`,children:(0,Z.jsx)(Qr,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-[1fr_6rem_1fr]`,children:[(0,Z.jsx)($j,{label:`IMAP host`,children:(0,Z.jsx)(q,{className:`h-8 font-mono text-sm`,value:e.host,disabled:r,onChange:e=>t({host:e.target.value}),placeholder:`imap.example.com`})}),(0,Z.jsx)($j,{label:`Port`,children:(0,Z.jsx)(q,{className:`h-8 text-sm`,type:`number`,min:1,max:65535,value:e.port,disabled:r,onChange:e=>t({port:Number(e.target.value)})})}),(0,Z.jsx)($j,{label:`Label on the sign-in form`,hint:`Optional.`,children:(0,Z.jsx)(q,{className:`h-8 text-sm`,value:e.name,disabled:r,onChange:e=>t({name:e.target.value}),placeholder:`Example Mail`})})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-x-6 gap-y-2`,children:[(0,Z.jsx)(eM,{checked:e.secure,disabled:r,onChange:e=>t({secure:e,...e?{startTLS:!1}:{}}),label:`TLS from the start`,hint:`Usually port 993.`}),(0,Z.jsx)(eM,{checked:e.startTLS,disabled:r||e.secure,onChange:e=>t({startTLS:e}),label:`Require STARTTLS`,hint:`Plain port 143 upgraded to TLS.`}),(0,Z.jsx)(eM,{checked:e.requireAppPassword,disabled:r,onChange:e=>t({requireAppPassword:e}),label:`Needs an app password`,hint:`Shown as a hint on the sign-in form.`})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-end gap-2 border-t pt-3`,children:[(0,Z.jsx)($j,{label:`Test sign-in`,hint:`A real IMAP login with these credentials, logged straight out. Nothing is stored.`,className:`min-w-[12rem] flex-1`,children:(0,Z.jsx)(q,{className:`h-8 text-sm`,type:`email`,value:i,onChange:e=>a(e.target.value),placeholder:`someone@${e.domain||`example.com`}`})}),(0,Z.jsx)($j,{label:`Password`,className:`mb-5 min-w-[10rem] flex-1`,children:(0,Z.jsx)(q,{className:`h-8 text-sm`,type:`password`,autoComplete:`off`,value:o,onChange:e=>s(e.target.value)})}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:async()=>{l(!0),d(null);try{let{id:t,domain:n,...r}=e;d(await Uj(r,i.trim(),o))}catch(e){d({ok:!1,message:e instanceof Error?e.message:`Test failed`})}finally{l(!1),s(``)}},disabled:c||r||!i||!o,className:`mb-5`,children:[c&&(0,Z.jsx)(Ti,{className:`mr-2 h-3.5 w-3.5 animate-spin`}),`Test`]})]}),(0,Z.jsx)(nM,{result:u})]})}function oM(){let e=yD(),{showToast:t}=wo(),n=du()?.userType===`admin`,[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(!0),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(null),_=(0,X.useCallback)(()=>Bj().then(e=>{let t=Kj(e.config);i(e.configPath),o(t),c(t),m(null)}).catch(e=>m(e instanceof Error?e.message:`Failed to load auth configuration`)).finally(()=>u(!1)),[]);(0,X.useEffect)(()=>{n&&_()},[n,_]);let v=(0,X.useMemo)(()=>!!s&&!!a&&JSON.stringify(Jj(s))!==JSON.stringify(Jj(a)),[s,a]),y=e=>c(t=>t&&e(t)),b=(e,t)=>y(n=>({...n,ldap:{...n.ldap,servers:n.ldap.servers.map(n=>n.id===e?{...n,...t}:n)}})),x=(e,t)=>y(n=>({...n,imap:{...n.imap,domains:n.imap.domains.map(n=>n.id===e?{...n,...t}:n)}})),S=async()=>{if(!s)return;let e=s.ldap.servers.map(e=>e.name.trim()),n=s.imap.domains.map(e=>e.domain.trim().toLowerCase());if(e.some(e=>!e)||new Set(e).size!==e.length){g(`Every LDAP server needs a unique name.`);return}if(n.some(e=>!e)||new Set(n).size!==n.length){g(`Every IMAP domain must be filled in and listed once.`);return}f(!0),g(null);try{let e=Kj((await Vj(Jj(s))).config);o(e),c(e),t({title:`Authentication settings saved`,description:`Applied immediately — the next sign-in uses them.`})}catch(e){g(e instanceof Error?e.message.replace(/^HTTP \d+:\s*/,``):`Failed to save`)}finally{f(!1)}},C=(0,Z.jsx)(sw,{onBack:e,compact:!0,className:`mb-6`,title:`Authentication`,description:`Entire server · Choose how people sign in: local passwords, your LDAP directory, or their mail server over IMAP.`,actions:n&&(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>{u(!0),_()},disabled:l||d,children:[(0,Z.jsx)(Er,{className:`mr-2 h-3.5 w-3.5`}),`Reload`]})});return n?(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl p-6 pb-24`,children:[C,l&&!s?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(Er,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):p||!s?(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`rounded-md border border-destructive/40 bg-destructive/5 p-4 text-sm`,children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Authentication settings unavailable`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:p||`No config returned.`})]}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>{u(!0),_()},children:`Retry`})]}):(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Config file: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:r}),` · Sign-in picks the backend from the account: existing users keep the method they were created with; a new address tries LDAP first (when enabled), then IMAP for a listed domain, then local.`]}),(0,Z.jsxs)(tM,{title:`Sign-up & local passwords`,description:`Accounts whose password is stored on this server.`,children:[(0,Z.jsx)(eM,{checked:s.allowUserRegistrations,onChange:e=>y(t=>({...t,allowUserRegistrations:e})),label:`Allow self-registration`,hint:`Off = only admins create accounts (and LDAP/IMAP users on first sign-in).`}),(0,Z.jsx)(eM,{checked:s.local.enabled,onChange:e=>y(t=>({...t,local:{...t.local,enabled:e}})),label:`Local password accounts`,hint:`Off refuses new local registrations. Existing local accounts — admins included — can still sign in, so this cannot lock you out.`}),(0,Z.jsx)(eM,{checked:s.local.requireEmailVerification,onChange:e=>y(t=>({...t,local:{...t.local,requireEmailVerification:e}})),label:`Require e-mail verification`,hint:`Needs working SMTP (config/smtp.json).`}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`mb-2 text-xs font-medium`,children:`Password policy`}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-start gap-4`,children:[(0,Z.jsx)($j,{label:`Min length`,children:(0,Z.jsx)(q,{className:`h-8 w-24 text-sm`,type:`number`,min:1,max:1024,value:s.local.passwordPolicy.minLength,onChange:e=>y(t=>({...t,local:{...t.local,passwordPolicy:{...t.local.passwordPolicy,minLength:Number(e.target.value)}}}))})}),(0,Z.jsx)($j,{label:`Max length`,children:(0,Z.jsx)(q,{className:`h-8 w-24 text-sm`,type:`number`,min:1,max:1024,value:s.local.passwordPolicy.maxLength,onChange:e=>y(t=>({...t,local:{...t.local,passwordPolicy:{...t.local.passwordPolicy,maxLength:Number(e.target.value)}}}))})}),(0,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-x-6 gap-y-1 pt-1`,children:[[`requireUppercase`,`Uppercase letter`],[`requireLowercase`,`Lowercase letter`],[`requireNumbers`,`Number`],[`requireSpecialChars`,`Special character`]].map(([e,t])=>(0,Z.jsx)(eM,{checked:s.local.passwordPolicy[e],label:t,onChange:t=>y(n=>({...n,local:{...n.local,passwordPolicy:{...n.local.passwordPolicy,[e]:t}}}))},e))})]})]})]}),(0,Z.jsxs)(tM,{title:`LDAP / Active Directory`,description:`Users sign in with their directory password. Servers are tried in order, so later ones act as fallbacks.`,enabled:s.ldap.enabled,onToggle:e=>y(t=>({...t,ldap:{...t.ldap,enabled:e}})),children:[(0,Z.jsx)(rM,{value:s.ldap,onChange:e=>y(t=>({...t,ldap:{...t.ldap,...e}}))}),s.ldap.servers.map((e,t)=>(0,Z.jsx)(iM,{row:e,index:t,onChange:t=>b(e.id,t),onRemove:()=>y(t=>({...t,ldap:{...t.ldap,servers:t.ldap.servers.filter(t=>t.id!==e.id)}}))},e.id)),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>y(e=>({...e,ldap:{...e.ldap,servers:[...e.ldap.servers,{...Xj,id:Gj(),name:e.ldap.servers.length?`server${e.ldap.servers.length+1}`:`primary`}]}})),children:[(0,Z.jsx)(br,{className:`mr-2 h-3.5 w-3.5`}),` Add LDAP server`]})]}),(0,Z.jsxs)(tM,{title:`IMAP (mail server sign-in)`,description:`Users of a listed e-mail domain sign in with their mailbox password — the server checks it by logging in to IMAP.`,enabled:s.imap.enabled,onToggle:e=>y(t=>({...t,imap:{...t.imap,enabled:e}})),children:[(0,Z.jsx)(rM,{value:s.imap,onChange:e=>y(t=>({...t,imap:{...t.imap,...e}}))}),s.imap.domains.map(e=>(0,Z.jsx)(aM,{row:e,onChange:t=>x(e.id,t),onRemove:()=>y(t=>({...t,imap:{...t.imap,domains:t.imap.domains.filter(t=>t.id!==e.id)}}))},e.id)),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>y(e=>({...e,imap:{...e.imap,domains:[...e.imap.domains,{...Zj,id:Gj()}]}})),children:[(0,Z.jsx)(br,{className:`mr-2 h-3.5 w-3.5`}),` Add mail domain`]})]}),(0,Z.jsxs)(tM,{title:`Google sign-in`,description:(0,Z.jsxs)(Z.Fragment,{children:[`One-click sign-in with a Google account via OAuth. Needs a Google Cloud OAuth client of type `,(0,Z.jsx)(`em`,{children:`Web application`}),` whose authorized redirect URI is `,(0,Z.jsx)(`code`,{className:`select-all`,children:`${yo}/oauth/google/callback`}),`.`]}),enabled:s.google.enabled,onToggle:e=>y(t=>({...t,google:{...t.google,enabled:e}})),children:[(0,Z.jsx)(rM,{value:s.google,onChange:e=>y(t=>({...t,google:{...t.google,...e}}))}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsx)($j,{label:`OAuth client id`,children:(0,Z.jsx)(q,{className:`h-8 font-mono text-sm`,value:s.google.clientId,autoComplete:`off`,onChange:e=>y(t=>({...t,google:{...t.google,clientId:e.target.value}}))})}),(0,Z.jsx)($j,{label:`OAuth client secret`,hint:s.google.clientSecretSet&&s.google.clientSecret===void 0?`A secret is stored; leave blank to keep it.`:void 0,children:(0,Z.jsx)(q,{className:`h-8 font-mono text-sm`,type:`password`,autoComplete:`off`,value:s.google.clientSecret??``,placeholder:s.google.clientSecretSet?`••••••••`:``,onChange:e=>y(t=>({...t,google:{...t.google,clientSecret:e.target.value===``?void 0:e.target.value}}))})}),(0,Z.jsx)($j,{label:`Allowed e-mail domains`,hint:`Comma separated. Empty = any Google account may sign in.`,children:(0,Z.jsx)(Yj,{value:s.google.allowedDomains,placeholder:`example.com, example.org`,onChange:e=>y(t=>({...t,google:{...t.google,allowedDomains:e}}))})}),(0,Z.jsx)($j,{label:`Extra web origins`,hint:`Only when the web UI is served from another origin than the API (e.g. a Vite dev server).`,children:(0,Z.jsx)(Yj,{value:s.google.webOrigins,placeholder:`http://localhost:5173`,onChange:e=>y(t=>({...t,google:{...t.google,webOrigins:e}}))})})]}),(0,Z.jsx)(eM,{checked:s.google.autoCreateUsers,label:`Create an account on first sign-in`,hint:`Off: only users that already exist (by e-mail) can sign in with Google.`,onChange:e=>y(t=>({...t,google:{...t.google,autoCreateUsers:e}}))})]}),(v||h)&&(0,Z.jsxs)(`div`,{className:`sticky bottom-4 z-10 rounded-lg border bg-card p-3 shadow-elevation-4`,children:[h&&(0,Z.jsx)(`ul`,{className:`mb-2 space-y-0.5 text-xs text-destructive`,children:h.split(`; `).map(e=>(0,Z.jsx)(`li`,{children:e},e))}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-end gap-2`,children:[(0,Z.jsx)(`span`,{className:`mr-auto text-xs text-muted-foreground`,children:v?`Unsaved changes`:``}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,disabled:d,onClick:()=>{c(a),g(null)},children:`Discard`}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,disabled:d||!v,onClick:()=>void S(),children:[d&&(0,Z.jsx)(Ti,{className:`mr-2 h-3.5 w-3.5 animate-spin`}),`Save`]})]})]})]})]}):(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl p-6`,children:[C,(0,Z.jsxs)(`div`,{className:`flex items-start gap-2 rounded-md border p-3 text-xs`,children:[(0,Z.jsx)(ha,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:`Authentication settings are only available to server admins.`})]})]})}function sM(e,t,n){return[e.trim()?`## Role\n${e.trim()}`:``,t.trim()?`## Identity\n${t.trim()}`:``,n.trim()?`## Instructions\n${n.trim()}`:``].filter(Boolean).join(`
|
|
37
39
|
|
|
38
|
-
`)}function cM({value:e,onChange:t,models:n,loading:r,error:i,refresh:a,disabled:o,id:s}){let c=(0,X.useId)(),l=n.find(t=>t.id===e);return(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{id:s,"aria-label":`Model`,list:c,value:e,onChange:e=>t(e.target.value,n.find(t=>t.id===e.target.value)),placeholder:`Choose or enter a model ID`,disabled:o}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,disabled:o||r,onClick:a,children:`Refresh models`})]}),(0,Z.jsx)(`datalist`,{id:c,children:n.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.name},e.id))}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,role:`status`,children:r?`Loading models…`:i||(n.length?`${n.length} models available`:`Enter provider credentials to load available models. You can also enter a model ID.`)}),l&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Context: `,l.contextWindow?.toLocaleString()??`not reported`,` · Max output: `,l.maxTokens?.toLocaleString()??`not reported`,` tokens`,l.limitsSource===`runtime`?` (runtime catalogue)`:l.limitsSource===`provider`?` (provider)`:``]})]})}function lM(e,t,n,r){let[i,a]=(0,X.useState)(0),o=JSON.stringify([e,t,n,r,i]),[s,c]=(0,X.useState)({key:``,models:[],loading:!1,error:``}),l=!!t.trim()||!!r||[`ollama`,`lm-studio`,`vllm`,`custom`].includes(e);return(0,X.useEffect)(()=>{if(!l)return;let i=new AbortController,a=setTimeout(()=>{c({key:o,models:[],loading:!0,error:``}),yO({provider:e,apiKey:t.trim()||void 0,baseUrl:n.trim()||void 0,agentIdentifier:r},i.signal).then(e=>{i.signal.aborted||c({key:o,models:e,loading:!1,error:``})}).catch(e=>{i.signal.aborted||c({key:o,models:[],loading:!1,error:e instanceof Error?e.message:`Unable to load models`})})},700);return()=>{clearTimeout(a),i.abort()}},[o,l,e,t,n,r]),{...s.key===o?s:{models:[],loading:l,error:``},refresh:()=>a(e=>e+1)}}function uM({agent:e,onStart:t,onStop:n,onEnter:r}){let[i,a]=(0,X.useState)(!1),o=async()=>{a(!0);try{await t(e.name)}finally{a(!1)}},s=async()=>{a(!0);try{await n(e.name)}finally{a(!1)}},c=()=>{switch(e.status){case`active`:return(0,Z.jsx)(yi,{className:`h-4 w-4 text-success`});case`inactive`:return(0,Z.jsx)(yi,{className:`h-4 w-4 text-warning`});case`error`:return(0,Z.jsx)(yi,{className:`h-4 w-4 text-destructive`});default:return(0,Z.jsx)(yi,{className:`h-4 w-4 text-muted-foreground`})}},l=()=>{switch(e.llmProvider){case`anthropic`:return(0,Z.jsx)(ri,{className:`h-4 w-4 text-warning`});case`openai`:return(0,Z.jsx)(ri,{className:`h-4 w-4 text-success`});case`ollama`:return(0,Z.jsx)(lr,{className:`h-4 w-4 text-info`});default:return(0,Z.jsx)(ri,{className:`h-4 w-4 text-muted-foreground`})}},u=()=>{switch(e.status){case`active`:return`text-success bg-success-subtle border-success`;case`inactive`:return`text-warning bg-warning-subtle border-warning`;case`error`:return`text-destructive bg-destructive-subtle border-destructive`;case`available`:return`text-info bg-info-subtle border-info`;default:return`text-foreground bg-muted border-border`}},d=e.status===`available`||e.status===`inactive`,f=e.status===`active`;return(0,Z.jsxs)(`div`,{className:`border rounded-lg p-4 space-y-4 hover:shadow-elevation-2 transition-shadow bg-card`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between`,children:[(0,Z.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 mb-1`,children:[l(),(0,Z.jsx)(`h3`,{className:`text-lg font-semibold truncate`,children:e.label||e.name}),e.color&&(0,Z.jsx)(`div`,{className:`w-4 h-4 rounded border flex-shrink-0`,style:{backgroundColor:e.color},title:`Color: ${e.color}`})]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground font-mono`,children:e.name}),e.description&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1 line-clamp-2`,children:e.description})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 flex-shrink-0`,children:[c(),(0,Z.jsx)(`span`,{className:`px-2 py-1 rounded-full text-xs font-medium border ${u()}`,children:e.status})]})]}),(0,Z.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 text-sm`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Provider:`}),(0,Z.jsx)(`div`,{className:`font-medium capitalize`,children:e.llmProvider})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Model:`}),(0,Z.jsx)(`div`,{className:`font-mono text-xs`,children:e.model})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Created:`}),(0,Z.jsx)(`div`,{children:new Date(e.createdAt).toLocaleDateString()})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Last Access:`}),(0,Z.jsx)(`div`,{children:e.lastAccessed?new Date(e.lastAccessed).toLocaleDateString():`Never`})]})]}),e.config.mcp?.servers&&e.config.mcp.servers.length>0&&(0,Z.jsxs)(`div`,{className:`text-sm`,children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`MCP Servers:`}),(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-1 mt-1`,children:e.config.mcp.servers.map((e,t)=>(0,Z.jsx)(`span`,{className:`px-2 py-1 bg-secondary text-secondary-foreground rounded text-xs`,children:e.name},t))})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2 pt-2 border-t`,children:[d&&(0,Z.jsxs)(Y,{onClick:o,disabled:i,size:`sm`,variant:`outline`,className:`flex-1`,children:[(0,Z.jsx)(Ar,{className:`mr-2 h-4 w-4`}),`Start`]}),f&&(0,Z.jsxs)(Y,{onClick:s,disabled:i,size:`sm`,variant:`outline`,className:`flex-1`,children:[(0,Z.jsx)(Sa,{className:`mr-2 h-4 w-4`}),`Stop`]}),(0,Z.jsxs)(Y,{onClick:()=>r(e.name),size:`sm`,className:`flex-1`,children:[(0,Z.jsx)(Ea,{className:`mr-2 h-4 w-4`}),`Chat`]})]})]})}function dM(){let e={anthropic:`https://api.anthropic.com`,openai:`https://api.openai.com/v1`,ollama:`http://localhost:11434/v1`},t={anthropic:`claude-3-5-sonnet-20241022`,openai:`gpt-4o`,ollama:`qwen2.5-coder:latest`},[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(!0),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(``),[f,p]=(0,X.useState)(on()),[m,h]=(0,X.useState)(``),[g,_]=(0,X.useState)(`anthropic`),[v,y]=(0,X.useState)(t.anthropic),[b,x]=(0,X.useState)({apiKey:``,baseUrl:e.anthropic,maxTokens:4096,temperature:.7,topP:1,frequencyPenalty:0,presencePenalty:0,numCtx:4096}),S=lM(g,b.apiKey,b.baseUrl),C=S.models.find(e=>e.id===v),[w,T]=(0,X.useState)(``),[E,D]=(0,X.useState)(``),[O,k]=(0,X.useState)(``),[A,j]=(0,X.useState)(``),[M,N]=(0,X.useState)(!1),P=aw(),[ee,F]=hw(),{showToast:I}=wo(),te=ft(),L=Cw();fw(L,`agent`,{"agent:status:changed":e=>{r(t=>t.map(t=>t.id===e.agentId?{...t,status:e.status,isActive:e.isActive}:t))},"agent:created":e=>{r(t=>[...t,e.agent])},"agent:deleted":e=>{r(t=>t.filter(t=>t.id!==e.agentId))}});let R=n=>{_(n),y(t[n]),x({apiKey:``,baseUrl:e[n],maxTokens:4096,temperature:.7,topP:1,frequencyPenalty:0,presencePenalty:0,numCtx:4096})};(0,X.useEffect)(()=>((async()=>{try{a(!0);let e=await ZD();r(e),s(null)}catch(e){console.error(`Agent fetch error:`,e);let t=`Failed to fetch agents`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to fetch agents`}s(t),I({title:`Error`,description:t,variant:`destructive`})}finally{a(!1)}})(),()=>{}),[L,I]);let ne=async t=>{if(t.preventDefault(),c.trim()){N(!0);try{let t=A.trim()||sM(w,E,O),n=await cO({name:c,label:m||c,description:u||void 0,color:f,llmProvider:g,model:v,apiKey:b.apiKey.trim()||void 0,baseUrl:b.baseUrl.trim()||void 0,config:{type:g,model:v,identity:{role:w.trim()||void 0,identity:E.trim()||void 0,instructions:O.trim()||void 0},prompts:t?{system:t}:void 0,connectors:{[g]:{maxTokens:b.maxTokens,temperature:b.temperature,topP:b.topP,frequencyPenalty:b.frequencyPenalty,presencePenalty:b.presencePenalty,...g===`ollama`?{numCtx:b.numCtx}:{}}}},mcp:{enabled:!0,servers:[{name:`weather`,command:`node`,args:[`src/managers/agent/mcp-servers/weather.js`]}]}});r(e=>[...e,n]),l(``),d(``),p(on()),h(``),j(``),T(``),D(``),k(``),x({apiKey:``,baseUrl:e[g],maxTokens:4096,temperature:.7,topP:1,frequencyPenalty:0,presencePenalty:0,numCtx:4096}),I({title:`Success`,description:`Agent '${n.label||n.name}' created.`}),F(!1)}catch(e){console.error(`Agent creation error:`,e);let t=`Failed to create agent`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to create agent`}I({title:`Error`,description:t,variant:`destructive`})}finally{N(!1)}}},re=async e=>{try{let t=await dO(e);r(e=>e.map(e=>e.name===t.name?t:e)),I({title:`Success`,description:`Agent '${t.label||t.name}' started.`})}catch(e){console.error(`Agent start error:`,e);let t=`Failed to start agent`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to start agent`}I({title:`Error`,description:t,variant:`destructive`})}},ie=async e=>{try{await fO(e),r(t=>t.map(t=>t.name===e?{...t,status:`inactive`,isActive:!1}:t)),I({title:`Success`,description:`Agent '${e}' stopped.`})}catch(e){console.error(`Agent stop error:`,e);let t=`Failed to stop agent`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to stop agent`}I({title:`Error`,description:t,variant:`destructive`})}},ae=e=>{te(`/agents/${e}`)};return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{title:`AI Agents`,description:`Create and manage your AI agents with multiple LLM providers`,actions:!P.local&&!ee&&(0,Z.jsxs)(Y,{onClick:()=>F(!0),className:`max-sm:h-9 max-sm:w-9 max-sm:p-0`,"aria-label":`Create agent`,title:`Create agent`,children:[(0,Z.jsx)(br,{className:`h-4 w-4 sm:mr-2`}),(0,Z.jsx)(`span`,{className:`max-sm:hidden`,children:`Create Agent`})]})}),!P.local&&ee&&(0,Z.jsx)(pw,{title:`Create New Agent`,onClose:()=>F(!1),children:(0,Z.jsxs)(`form`,{onSubmit:ne,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsx)(q,{value:c,onChange:e=>l(e.target.value),placeholder:`Agent Name (e.g., 'my-assistant')`,disabled:M}),(0,Z.jsx)(q,{value:m,onChange:e=>h(e.target.value),placeholder:`Agent Label (display name, optional)`,disabled:M})]}),(0,Z.jsx)(q,{value:u,onChange:e=>d(e.target.value),placeholder:`Description (optional)`,disabled:M}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`agent-provider`,className:`text-sm font-medium`,children:`LLM Provider`}),(0,Z.jsxs)(`select`,{id:`agent-provider`,value:g,onChange:e=>R(e.target.value),className:`w-full mt-1 px-3 py-2 border border-input bg-background rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-ring`,disabled:M,children:[(0,Z.jsx)(`option`,{value:`anthropic`,children:`Anthropic Claude`}),(0,Z.jsx)(`option`,{value:`openai`,children:`OpenAI GPT`}),(0,Z.jsx)(`option`,{value:`ollama`,children:`Ollama (Local)`})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`agent-model`,className:`text-sm font-medium`,children:`Model`}),(0,Z.jsx)(cM,{id:`agent-model`,value:v,onChange:(e,t)=>{y(e),t?.maxTokens&&x(e=>({...e,maxTokens:t.maxTokens}))},...S,disabled:M})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h3`,{className:`text-lg font-medium`,children:`Persona`}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`agent-role`,className:`text-sm font-medium`,children:`Role`}),(0,Z.jsx)(q,{id:`agent-role`,value:w,onChange:e=>T(e.target.value),placeholder:`e.g. Software Engineer`,disabled:M})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`agent-identity`,className:`text-sm font-medium`,children:`Identity`}),(0,Z.jsx)(`textarea`,{id:`agent-identity`,value:E,onChange:e=>D(e.target.value),placeholder:`Who this agent is…`,disabled:M,className:`w-full mt-1 px-3 py-2 border border-input bg-background rounded-md text-sm min-h-[80px] resize-y`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`agent-instructions`,className:`text-sm font-medium`,children:`Instructions`}),(0,Z.jsx)(`textarea`,{id:`agent-instructions`,value:O,onChange:e=>k(e.target.value),placeholder:`Behavioral instructions…`,disabled:M,className:`w-full mt-1 px-3 py-2 border border-input bg-background rounded-md text-sm min-h-[80px] resize-y`})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`system-prompt`,className:`text-sm font-medium`,children:`System Prompt (Optional Override)`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Built from Role, Identity and Instructions unless you enter an override.`}),(0,Z.jsx)(`textarea`,{id:`system-prompt`,value:A,onChange:e=>j(e.target.value),placeholder:sM(w,E,O)||`System prompt sent to the LLM…`,className:`w-full mt-1 px-3 py-2 border border-input bg-background rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-ring min-h-[80px] resize-y`,disabled:M})]}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`api-key`,className:`text-sm font-medium`,children:`API Key (Optional)`}),(0,Z.jsx)(q,{id:`api-key`,type:`password`,value:b.apiKey,onChange:e=>x(t=>({...t,apiKey:e.target.value})),placeholder:`Enter your API key`,disabled:M})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`baseUrl`,className:`text-sm font-medium`,children:`Base URL (Optional)`}),(0,Z.jsx)(q,{id:`baseUrl`,value:b.baseUrl,onChange:e=>x(t=>({...t,baseUrl:e.target.value})),placeholder:e[g],disabled:M})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h3`,{className:`text-lg font-medium`,children:`LLM Parameters`}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2 lg:grid-cols-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`max-tokens`,className:`text-sm font-medium`,children:`Max Output Tokens`}),(0,Z.jsx)(q,{id:`max-tokens`,type:`number`,min:`1`,max:C?.maxTokens,value:b.maxTokens,onChange:e=>x(t=>({...t,maxTokens:parseInt(e.target.value)||4096})),disabled:M})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`temperature`,className:`text-sm font-medium`,children:`Temperature`}),(0,Z.jsx)(q,{id:`temperature`,type:`number`,min:`0`,max:`2`,step:`0.1`,value:b.temperature,onChange:e=>x(t=>({...t,temperature:Number.isNaN(e.target.valueAsNumber)?.7:e.target.valueAsNumber})),disabled:M})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`top-p`,className:`text-sm font-medium`,children:`Top P`}),(0,Z.jsx)(q,{id:`top-p`,type:`number`,min:`0`,max:`1`,step:`0.1`,value:b.topP,onChange:e=>x(t=>({...t,topP:Number.isNaN(e.target.valueAsNumber)?1:e.target.valueAsNumber})),disabled:M})]}),g===`ollama`&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`num-ctx`,className:`text-sm font-medium`,children:`Context Length`}),(0,Z.jsx)(q,{id:`num-ctx`,type:`number`,min:`1024`,max:C?.contextWindow,value:b.numCtx,onChange:e=>x(t=>({...t,numCtx:parseInt(e.target.value)||4096})),disabled:M})]})]}),g!==`ollama`&&(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`frequency-penalty`,className:`text-sm font-medium`,children:`Frequency Penalty`}),(0,Z.jsx)(q,{id:`frequency-penalty`,type:`number`,min:`-2`,max:`2`,step:`0.1`,value:b.frequencyPenalty,onChange:e=>x(t=>({...t,frequencyPenalty:parseFloat(e.target.value)||0})),disabled:M})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`presence-penalty`,className:`text-sm font-medium`,children:`Presence Penalty`}),(0,Z.jsx)(q,{id:`presence-penalty`,type:`number`,min:`-2`,max:`2`,step:`0.1`,value:b.presencePenalty,onChange:e=>x(t=>({...t,presencePenalty:parseFloat(e.target.value)||0})),disabled:M})]})]})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{htmlFor:`agent-color`,className:`text-sm font-medium`,children:`Agent Color`}),(0,Z.jsx)(q,{id:`agent-color`,type:`color`,value:f,onChange:e=>p(e.target.value),className:`h-10 w-16 p-1`,disabled:M}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>p(on()),disabled:M,children:`Randomize`})]}),(0,Z.jsxs)(Y,{type:`submit`,disabled:M||!c.trim(),children:[(0,Z.jsx)(br,{className:`mr-2 h-4 w-4`}),`Create Agent`]})]})}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your Agents`}),i&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading agents...`}),o&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:o})}),!i&&!o&&n.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No agents found`}),n.length>0&&(0,Z.jsx)(`div`,{className:`grid gap-4`,children:n.map(e=>(0,Z.jsx)(uM,{agent:e,onStart:re,onStop:ie,onEnter:ae},e.id))})]})]})}function fM(e){let t=e?.usage;if(!t)return null;let n=t.totalTokens,r=t.input,i=t.output;return typeof n==`number`&&typeof r==`number`&&typeof i==`number`?`${n} tok (${r} in / ${i} out)`:typeof n==`number`?`${n} tok`:null}function pM(e){let t=e?.usage?.cost?.total;return typeof t==`number`?`$${t.toFixed(t<.01?6:4)}`:null}function mM({reasoning:e,metadata:t,isStreaming:n=!1,compact:r=!1}){let i=t?.model,a=[t?.provider,i,fM(t),pM(t)].filter(Boolean);return!e&&a.length===0?null:(0,Z.jsxs)(Z.Fragment,{children:[e&&(0,Z.jsxs)(`details`,{open:n,className:`mb-2 rounded border border-border bg-background ${r?`px-2 py-1.5`:`px-3 py-2`}`,children:[(0,Z.jsx)(`summary`,{className:`cursor-pointer font-medium text-foreground ${r?`text-[11px]`:`text-xs`}`,children:`Reasoning`}),(0,Z.jsx)(F,{content:e,className:`mt-1 text-foreground ${r?`text-[11px]`:`text-xs`}`})]}),a.length>0&&(0,Z.jsx)(`div`,{className:`mt-2 text-muted-foreground ${r?`text-[11px]`:`text-xs`}`,children:a.join(` • `)})]})}function hM({message:e,isStreaming:t=!1,connectionStatus:n=`disconnected`}){let[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(!0);(0,X.useEffect)(()=>{if(!t||e.isComplete)return;let n=e.content,r=0,a=setInterval(()=>{r<n.length?(i(n.substring(0,r+1)),r++):clearInterval(a)},20);return()=>clearInterval(a)},[e.content,t,e.isComplete]);let s=t&&!e.isComplete?r:e.content;return(0,X.useEffect)(()=>{if(!t||e.isComplete)return;let n=setInterval(()=>{o(e=>!e)},500);return()=>{clearInterval(n),o(!0)}},[t,e.isComplete]),(0,Z.jsx)(`div`,{className:`flex ${e.role===`user`?`justify-end`:`justify-start`}`,children:(0,Z.jsxs)(`div`,{className:`max-w-[70%] p-3 rounded-lg ${e.role===`user`?`bg-primary text-primary-foreground`:`bg-muted`} ${t&&!e.isComplete?`border-2 border-info`:``}`,children:[(0,Z.jsx)(mM,{reasoning:e.role===`assistant`?e.metadata?.reasoning?.trim():void 0,metadata:e.role===`assistant`?e.metadata:void 0,isStreaming:t&&!e.isComplete}),(0,Z.jsxs)(`div`,{className:`text-sm`,children:[e.role===`assistant`?(0,Z.jsx)(F,{content:s}):(0,Z.jsx)(`span`,{className:`whitespace-pre-wrap break-words`,children:s}),t&&!e.isComplete&&(0,Z.jsx)(`span`,{className:`inline-block w-2 ${a?`bg-current`:`bg-transparent`}`,children:`|`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-between text-xs mt-2 opacity-70`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{children:new Date(e.timestamp).toLocaleTimeString()}),t&&!e.isComplete&&(0,Z.jsx)(`span`,{className:`text-info`,children:`• streaming...`})]}),e.role===`assistant`&&(()=>{switch(n){case`websocket`:return(0,Z.jsx)(`span`,{title:`WebSocket`,children:(0,Z.jsx)(Ja,{className:`h-3 w-3 text-success`})});case`sse`:return(0,Z.jsx)(`span`,{title:`Server-Sent Events`,children:(0,Z.jsx)($i,{className:`h-3 w-3 text-info`})});case`rest`:return(0,Z.jsx)(`span`,{title:`REST API`,children:(0,Z.jsx)(yi,{className:`h-3 w-3 text-warning`})});default:return(0,Z.jsx)(`span`,{title:`Disconnected`,children:(0,Z.jsx)(Hn,{className:`h-3 w-3 text-destructive`})})}})()]})]})})}var gM=(0,X.createContext)(null);function _M(e){let t=(0,X.useContext)(gM);if(!t)throw Error(`useAgentSessions must be used within an AgentSessionProvider`);let{getState:n,refresh:r,create:i,select:a,rename:o,remove:s}=t,c=n(e),l=(0,X.useCallback)(()=>r(e),[r,e]),u=(0,X.useCallback)(t=>i(e,t),[i,e]),d=(0,X.useCallback)(t=>a(e,t),[a,e]),f=(0,X.useCallback)((t,n)=>o(e,t,n),[o,e]),p=(0,X.useCallback)(t=>s(e,t),[s,e]);return(0,X.useMemo)(()=>({...c,refresh:l,create:u,select:d,rename:f,remove:p}),[c,l,u,d,f,p])}function vM(e={}){let[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(!1),s=(0,X.useRef)(e),c=(0,X.useRef)(null),l=(0,X.useRef)(!1);(0,X.useEffect)(()=>{s.current=e},[e]);let u=(0,X.useCallback)(()=>{if(!s.current.agentId||c.current||l.current)return;let e=localStorage.getItem(`authToken`);if(!e){console.warn(`No auth token available for WebSocket connection`);return}console.log(`[WebSocket] Using token type: ${e.startsWith(`canvas-`)?`API`:`JWT`}, length: ${e.length}`),l.current=!0,o(!0);let t=xo(no.ws,{auth:{token:e},transports:[`websocket`],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3,timeout:1e4,forceNew:!0});t.on(`connect`,()=>{console.log(`Agent WebSocket connected successfully`),i(!0),l.current=!1,o(!1)}),t.on(`connect_error`,e=>{console.error(`Agent WebSocket connection error:`,e),i(!1),l.current=!1,o(!1),(e.message?.includes(`Auth error`)||e.message?.includes(`token`))&&console.warn(`WebSocket auth failed, will fallback to SSE for streaming`)}),t.on(`disconnect`,e=>{console.log(`Agent WebSocket disconnected:`,e),i(!1),l.current=!1,o(!1)}),t.on(`agent:chat:chunk`,e=>{console.log(`Received chat chunk:`,e),s.current.onMessage&&s.current.onMessage(e)}),t.on(`agent:chat:complete`,e=>{console.log(`Chat stream complete:`,e),s.current.onComplete&&s.current.onComplete(e.agentId,e.messageId,e.messages)}),t.on(`agent:chat:error`,e=>{console.error(`Chat stream error:`,e),s.current.onError&&s.current.onError(e)}),t.on(`agent:chat:start`,e=>{console.log(`Chat stream started:`,e)}),c.current=t,n(t)},[]),d=(0,X.useCallback)(()=>{let e=c.current;e&&(e.removeAllListeners(),e.close()),c.current=null,l.current=!1,n(null),i(!1),o(!1)},[]),f=(0,X.useCallback)(e=>{t&&r&&(console.log(`Subscribing to agent channel: ${e}`),t.emit(`agent:subscribe`,{agentId:e}))},[t,r]),p=(0,X.useCallback)(e=>{t&&r&&(console.log(`Unsubscribing from agent channel: ${e}`),t.emit(`agent:unsubscribe`,{agentId:e}))},[t,r]),m=(0,X.useCallback)((e,n)=>{if(!t||!r)throw Error(`WebSocket not connected`);let i=`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return console.log(`Starting streaming chat for agent ${e}, message ${i}`),t.emit(`agent:chat:stream`,{agentId:e,messageId:i,...n}),i},[t,r]);return(0,X.useEffect)(()=>{if(e.agentId)return u(),()=>{d()}},[e.agentId,u,d]),(0,X.useEffect)(()=>{if(r&&e.agentId)return f(e.agentId),()=>{e.agentId&&p(e.agentId)}},[r,e.agentId,f,p]),{socket:t,isConnected:r,isConnecting:a,connect:u,disconnect:d,joinAgentChannel:f,leaveAgentChannel:p,startStreamingChat:m}}function yM(e){if(!e)return``;if(typeof e.errorMessage==`string`&&e.errorMessage.trim())return e.errorMessage.trim();let t=e.content;return typeof t==`string`?t:Array.isArray(t)&&t.filter(e=>e?.type===`text`&&typeof e.text==`string`).map(e=>e.text??``).join(`
|
|
39
|
-
`)||``}function bM(e,t){return`${e||``}${t||``}`.trim()||void 0}function xM(e,t){if(!e&&!t)return;let{reasoningDelta:n,...r}=e||{};return{...r,...t?{reasoning:t}:{}}}function SM(e){let{agentId:t,initialMessages:n=[],historyKey:r,loadHistory:i=!0,onError:a,enableWebSocket:o=!0,enableSSE:s=!0,enableFallback:c=!0,llmProvider:l}=e,[u,d]=(0,X.useState)(gO(n)),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(`disconnected`),[v,y]=(0,X.useState)(null),b=(0,X.useRef)(n);(0,X.useEffect)(()=>{b.current=n});let x=`${t}${String(i)}${r??``}`,[S,C]=(0,X.useState)(x);S!==x&&(C(x),(!t||!i)&&d(gO(n))),(0,X.useEffect)(()=>{let e=!1;if(!(!t||!i))return $D(t).then(t=>{e||d(gO(t.messages))}).catch(()=>{e||d(gO(b.current))}),()=>{e=!0}},[t,i,r]);let w=(0,X.useRef)(null),T=(0,X.useRef)(null),{isConnected:E,startStreamingChat:D}=vM({agentId:o?t:void 0,onMessage:j,onComplete:M,onError:N}),O=o&&E,[k,A]=(0,X.useState)(!1);k!==O&&(A(O),_(O?`websocket`:e=>e===`websocket`?`disconnected`:e));function j(e){e.messageId===T.current&&(console.log(`Processing WebSocket chunk:`,{type:e.type,content:e.content,delta:e.delta}),e.type===`content`||e.type===`chunk`?h(t=>t?{...t,content:t.content+(e.delta||e.content||``),isComplete:!1,metadata:t.metadata}:{role:`assistant`,content:e.delta||e.content||``,timestamp:new Date().toISOString(),isComplete:!1}):e.type===`thinking`?h(t=>{let n=bM(t?.metadata?.reasoning,e.delta);return t?{...t,metadata:{...t.metadata||{},...n?{reasoning:n}:{}}}:{role:`assistant`,content:``,timestamp:new Date().toISOString(),isComplete:!1,metadata:n?{reasoning:n}:void 0}}):(e.type===`complete`||e.type===`done`)&&h(e=>{if(e){let t={...e,isComplete:!0};return d(e=>[...e,t]),p(!1),T.current=null,null}return null}))}function M(e,t,n){if(t===T.current){let e=Array.isArray(n)?[...n].reverse().find(e=>e?.role===`assistant`):null,t=yM(e),r=VD(e);h(e=>{if(e){let n={...e,content:t||e.content,isComplete:!0,metadata:{...e.metadata||{},...r||{}}};d(e=>[...e,n])}else t&&d(e=>[...e,{role:`assistant`,content:t,timestamp:new Date().toISOString(),isComplete:!0,metadata:r}]);return null}),p(!1),T.current=null}}function N(e){e.messageId===T.current&&(console.error(`WebSocket streaming error:`,e),y(e.error),p(!1),T.current=null,a&&a(Error(e.error)))}let P=(0,X.useCallback)(async(e,n={})=>{if(f)throw Error(`Cannot send message while streaming`);y(null);let r={role:`user`,content:e||(n.images?.length?`[${n.images.length} image${n.images.length===1?``:`s`} attached]`:``),timestamp:new Date().toISOString(),isComplete:!0};d(e=>[...e,r]),p(!0);let i={message:e,images:n.images,context:u.slice(-10),mcpContext:n.mcpContext??!0,maxTokens:n.maxTokens,temperature:n.temperature},m=Array.isArray(n.images)&&n.images.length>0,g=o&&E&&l!==`ollama`&&!m,v=s;if(l===`ollama`&&console.log(`🦙 Ollama detected: Using SSE streaming (WebSocket not supported by Ollama)`),g)try{console.log(`🔌 Attempting WebSocket streaming for ${l||`unknown`} provider...`);let e=D(t,i);T.current=e,_(`websocket`);return}catch(e){console.warn(`WebSocket streaming failed for ${l||`unknown`}, falling back to SSE:`,e)}if(v){let e=!1;try{console.log(`📡 ${l===`ollama`?`Using`:`Attempting`} SSE streaming for ${l||`unknown`} provider...`),_(`sse`),w.current=new AbortController;let r=``;await mO(t,i.message,{onStart:()=>{e=!0},onMessage:(e,t,n)=>{r+=e;let i=typeof n?.reasoningDelta==`string`?n.reasoningDelta:``;if(h(e=>{let a=n?.reasoning||bM(e?.metadata?.reasoning,i);return{role:`assistant`,content:r,timestamp:e?.timestamp||new Date().toISOString(),isComplete:t,metadata:xM({...e?.metadata||{},...n},a)}}),t){let e=n?.reasoning;d(t=>[...t,{role:`assistant`,content:r,timestamp:new Date().toISOString(),isComplete:!0,metadata:xM(n,e)}]),h(null),p(!1)}},onError:e=>{console.error(`SSE streaming error:`,e),y(e.message),p(!1),a&&a(e)},context:u.slice(-10).map(e=>({role:e.role,content:e.content,timestamp:e.timestamp,metadata:e.metadata})),images:n.images,mcpContext:n.mcpContext??!0,maxTokens:n.maxTokens,temperature:n.temperature});return}catch(t){if(e){console.warn(`SSE stream failed after server accepted prompt for ${l||`unknown`}; refusing REST fallback to avoid duplicate prompt.`);return}console.warn(`SSE streaming failed for ${l||`unknown`}, falling back to REST:`,t)}}if(c)try{console.log(`⚙️ Using REST API fallback for ${l||`unknown`} provider...`),_(`rest`);let r=await hO(t,{message:e,images:n.images,context:u.slice(-10).map(e=>({role:e.role,content:e.content,timestamp:e.timestamp,metadata:e.metadata})),mcpContext:n.mcpContext??!0,maxTokens:n.maxTokens,temperature:n.temperature}),i={role:`assistant`,content:r.content,timestamp:new Date().toISOString(),isComplete:!0,metadata:r.metadata};d(e=>[...e,i]),p(!1)}catch(e){console.error(`All chat methods failed:`,e);let t=e instanceof Error?e.message:`Failed to send message`;y(t),p(!1),a&&a(e instanceof Error?e:Error(t))}else y(`All streaming methods failed and fallback is disabled`),p(!1)},[t,u,f,E,D,o,s,c,l,a]),ee=(0,X.useCallback)(()=>{d([]),h(null),y(null)},[]),F=(0,X.useCallback)(()=>{w.current&&=(w.current.abort(),null),T.current=null,p(!1),h(null)},[]);return(0,X.useEffect)(()=>()=>{w.current&&w.current.abort()},[]),{messages:u,isStreaming:f,currentStreamingMessage:m,connectionStatus:g,error:v,sendMessage:P,clearMessages:ee,stopStreaming:F,allMessages:m?[...u,m]:u,isWebSocketConnected:g===`websocket`,isUsingSSE:g===`sse`,isUsingREST:g===`rest`}}function CM(e){let{sessions:t,create:n}=_M(e),r=(t?.sessions.length??0)>0;return{hasSession:r,ensureSession:async()=>r?null:n({mode:`persistent`})}}async function wM(e){let t=await new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let[,e=``]=(typeof r.result==`string`?r.result:``).split(`,`,2);t(e)},r.onerror=()=>n(r.error||Error(`Failed to read image`)),r.readAsDataURL(e)});return{id:`${e.name}-${e.size}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:`image`,data:t,mimeType:e.type||`image/png`,name:e.name}}function TM(e){return String(e||``).trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)}function EM({agentId:e,routeAgentId:t,initialMessages:n,llmProvider:r,sessionKey:i}){let{showToast:a}=wo(),{hasSession:o,ensureSession:s}=CM(e),c=ft(),l=(0,X.useRef)(null),u=(0,X.useRef)(null),[d,f]=(0,X.useState)(``),[p,m]=(0,X.useState)([]),{allMessages:h,isStreaming:g,currentStreamingMessage:_,connectionStatus:v,error:y,sendMessage:b,clearMessages:x,stopStreaming:S}=SM({agentId:e,initialMessages:n,historyKey:i,loadHistory:!1,llmProvider:r,enableWebSocket:!1,onError:e=>{a({title:`Chat Error`,description:e.message,variant:`destructive`})}});return(0,X.useEffect)(()=>{l.current?.scrollIntoView({behavior:`smooth`})},[h,_]),(0,X.useEffect)(()=>{g||u.current?.focus()},[g,i]),(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col rounded-lg border`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between border-b px-4 py-3`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Chat`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Current session conversation`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`span`,{children:v}),h.length>0&&(0,Z.jsx)(`button`,{type:`button`,onClick:x,disabled:g,className:`text-destructive hover:underline disabled:opacity-50`,children:`Clear visible chat`})]})]}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4 space-y-4`,children:[h.length===0?(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center text-center text-muted-foreground`,children:(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(Ea,{className:`mx-auto mb-4 h-10 w-10 opacity-40`}),(0,Z.jsx)(`p`,{className:`text-sm`,children:o?`No messages yet.`:`No session yet.`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs`,children:o?`Send a message to start the conversation.`:`Type a message to auto-create a session, or pick one in the Sessions panel.`})]})}):h.map((e,t)=>(0,Z.jsx)(hM,{message:e,isStreaming:g&&e===_,connectionStatus:v},`${e.timestamp}-${t}`)),y&&(0,Z.jsx)(`div`,{className:`rounded-lg bg-destructive/10 p-3 text-sm text-destructive`,children:y}),(0,Z.jsx)(`div`,{ref:l})]}),(0,Z.jsxs)(`div`,{className:`border-t p-4`,children:[p.length>0&&(0,Z.jsx)(`div`,{className:`mb-3 flex flex-wrap gap-2`,children:p.map(e=>(0,Z.jsxs)(`div`,{className:`group relative overflow-hidden rounded-md border bg-muted/20`,children:[(0,Z.jsx)(`img`,{src:`data:${e.mimeType};base64,${e.data}`,alt:e.name||`Pasted image`,className:`h-16 w-16 object-cover`}),(0,Z.jsx)(`div`,{className:`max-w-16 truncate px-2 py-1 text-[10px] text-muted-foreground`,children:e.name||e.mimeType}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>m(t=>t.filter(t=>t.id!==e.id)),className:`absolute right-1 top-1 flex h-5 w-5 items-center justify-center rounded-full bg-background/90 text-muted-foreground hover:text-foreground`,title:`Remove image`,children:(0,Z.jsx)(vr,{className:`h-3 w-3`})})]},e.id))}),(0,Z.jsxs)(`form`,{onSubmit:async e=>{e.preventDefault();let n=d.trim();if(!(!n&&p.length===0)){f(``);try{let e=await s();e?.current.sessionId&&c(`/agents/${encodeURIComponent(t)}/${encodeURIComponent(e.current.sessionId)}`,{replace:!0}),await b(n,{images:p.map(({id:e,...t})=>t)}),m([])}catch(e){a({title:`Chat Error`,description:e instanceof Error?e.message:`Failed to send message`,variant:`destructive`})}}},className:`flex gap-2`,children:[(0,Z.jsx)(`textarea`,{ref:u,value:d,onChange:e=>f(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),e.currentTarget.form?.requestSubmit())},onPaste:async e=>{let t=Array.from(e.clipboardData.items).filter(e=>e.kind===`file`&&e.type.startsWith(`image/`)).map(e=>e.getAsFile()).filter(e=>!!e);if(t.length!==0)try{let e=await Promise.all(t.map(wM));m(t=>[...t,...e])}catch(e){a({title:`Paste Error`,description:e instanceof Error?e.message:`Failed to read pasted image`,variant:`destructive`})}},placeholder:g?`Streaming in progress...`:o?`Type a message...`:`Type to start a new session…`,disabled:g,rows:2,className:`flex min-h-10 flex-1 resize-y rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50`}),g?(0,Z.jsx)(Y,{type:`button`,variant:`outline`,onClick:S,children:`Stop`}):(0,Z.jsx)(Y,{type:`submit`,disabled:!d.trim()&&p.length===0,children:`Send`})]}),(0,Z.jsxs)(`div`,{className:`mt-2 flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(zn,{className:`h-3.5 w-3.5`}),`Paste image files from clipboard directly into the input.`]})]})]})}function DM(){let{agentId:e,sessionId:t}=yt(),n=vn(),r=ft(),{showToast:i}=wo(),{selectEntity:a,goBack:o}=qC(),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(!0),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(!1),y=(0,X.useRef)(null),{current:b,sessions:x,refresh:S,select:C}=_M(e||``),w=(0,X.useMemo)(()=>x?.sessions?x.currentSessionId?x.sessions.find(e=>e.id===x.currentSessionId)||null:x.currentSessionPath?x.sessions.find(e=>e.path===x.currentSessionPath)||null:x.sessions.find(e=>e.isCurrent)||null:null,[x]),T=[b?.mode||`persistent`,b?.sessionId||b?.sessionFile||`initial`].join(`:`);return(0,X.useEffect)(()=>{e&&(async()=>{u(!0);try{let i=await QD(e);a(i.id),c(i);let o=i.name||i.id;if(o&&decodeURIComponent(e)!==o){let e=n.pathname.endsWith(`/settings`)?`/agents/${encodeURIComponent(o)}/settings`:t?`/agents/${encodeURIComponent(o)}/${encodeURIComponent(t)}`:`/agents/${encodeURIComponent(o)}`;r(e,{replace:!0})}await S(),g(null)}catch(e){let t=e instanceof Error?e.message:`Failed to load agent`;g(t),i({title:`Error`,description:t,variant:`destructive`})}finally{u(!1)}})()},[e,t,n.pathname,r,S,a,i]),(0,X.useEffect)(()=>{if(!e||!t||!x)return;let n=decodeURIComponent(t),r=TM(n),a=x.sessions.find(e=>e.id===n||e.slug===n||TM(e.name)===r),o=!!(a&&(x.currentSessionId===a.id||x.currentSessionPath===a.path||b?.sessionId===a.id||b?.sessionFile===a.path)),s=b?.sessionId===n||x.currentSessionId===n;if(b?.mode===`persistent`&&o){y.current=null;return}if(!a){b?.mode===`persistent`&&s&&(y.current=null);return}y.current!==a.id&&(y.current=a.id,C({mode:`persistent`,sessionId:a.id}).catch(e=>{i({title:`Session Error`,description:e instanceof Error?e.message:`Failed to select session`,variant:`destructive`})}).finally(()=>{y.current===a.id&&(y.current=null)}))},[e,t,x,b?.mode,b?.sessionId,b?.sessionFile,C,i]),(0,X.useEffect)(()=>{if(!e)return;let t=async()=>{try{let t=await pO(e);c(e=>e?{...e,isActive:t.isActive,status:t.status,lastAccessed:t.lastAccessed}:null)}catch{}};t();let n=setInterval(t,5e3);return()=>clearInterval(n)},[e]),l?(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,Z.jsxs)(`div`,{className:`text-center text-muted-foreground`,children:[(0,Z.jsx)(Nr,{className:`mx-auto mb-3 h-8 w-8 animate-pulse`}),(0,Z.jsx)(`p`,{children:`Loading agent...`})]})}):!s||h?(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,Z.jsxs)(`div`,{className:`text-center text-destructive`,children:[(0,Z.jsx)(Nr,{className:`mx-auto mb-3 h-8 w-8`}),(0,Z.jsx)(`p`,{children:h||`Agent not found`})]})}):(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Z.jsx)(lw,{title:`Back to previous view`,onBack:o}),(0,Z.jsx)(`span`,{className:`h-3 w-3 shrink-0 rounded-full`,style:{backgroundColor:s.color||`#9ca3af`}}),(0,Z.jsx)(`h1`,{className:`truncate text-xl font-semibold`,children:s.label||s.name}),(0,Z.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,children:s.status})]}),(0,Z.jsx)(`p`,{className:`mt-1 truncate text-sm text-muted-foreground`,children:s.description||`${s.llmProvider} / ${s.model}`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[s.isActive?(0,Z.jsxs)(Y,{variant:`outline`,onClick:async()=>{if(e){m(!0);try{let t=await fO(e);c(t),i({title:`Stopped`,description:`${t.label||t.name} is inactive`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to stop agent`,variant:`destructive`})}finally{m(!1)}}},disabled:p,children:[(0,Z.jsx)(Sa,{className:`mr-2 h-4 w-4`}),p?`Stopping...`:`Stop`]}):(0,Z.jsxs)(Y,{onClick:async()=>{if(e){f(!0);try{let t=await dO(e);c(t),i({title:`Started`,description:`${t.label||t.name} is active`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to start agent`,variant:`destructive`})}finally{f(!1)}}},disabled:d,children:[(0,Z.jsx)(Ar,{className:`mr-2 h-4 w-4`}),d?`Starting...`:`Start`]}),(0,Z.jsxs)(Y,{variant:`outline`,onClick:()=>{a(s.id),r(`/agents/${encodeURIComponent(s.name||s.id)}/settings/identity`)},children:[(0,Z.jsx)(Wi,{className:`mr-2 h-4 w-4`}),`Settings`]}),(0,Z.jsx)(cw,{className:`h-9 w-9`})]})]}),(0,Z.jsxs)(`div`,{className:`grid min-h-0 flex-1 grid-cols-1 gap-4 grid-rows-[minmax(0,1fr)_auto] xl:grid-rows-none xl:grid-cols-[minmax(0,1.2fr)_minmax(320px,0.8fr)]`,children:[(0,Z.jsx)(EM,{agentId:s.id,routeAgentId:s.name||s.id,initialMessages:b?.messages||[],llmProvider:s.llmProvider,sessionKey:T},T),(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-col rounded-lg border`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>v(e=>!e),"aria-expanded":_,className:K(`flex w-full items-center justify-between gap-2 px-4 py-3 text-left xl:pointer-events-none`,_?`border-b`:`xl:border-b`),children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Contextual Information`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Current session and runtime state.`})]}),(0,Z.jsx)(qr,{className:K(`h-4 w-4 shrink-0 text-muted-foreground transition-transform xl:hidden`,_&&`rotate-180`)})]}),(0,Z.jsxs)(`div`,{className:K(`space-y-4 overflow-y-auto p-4 text-sm max-xl:max-h-viewport-half`,!_&&`max-xl:hidden`),children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Mode`}),(0,Z.jsx)(`div`,{className:`mt-1`,children:b?.mode||x?.mode||`persistent`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Selected Session`}),(0,Z.jsx)(`div`,{className:`mt-1 break-all`,children:w?.name||(w?.isExperimental?`Experimental`:null)||b?.sessionId||`Default session`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Known Sessions`}),(0,Z.jsx)(`div`,{className:`mt-1`,children:x?.sessions.length||0})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Thinking Level`}),(0,Z.jsx)(`div`,{className:`mt-1`,children:b?.thinkingLevel||`high`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Model`}),(0,Z.jsx)(`div`,{className:`mt-1`,children:b?.model?.modelId||s.model||`Not set`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Session File`}),(0,Z.jsx)(`div`,{className:`mt-1 break-all text-xs text-muted-foreground`,children:b?.sessionFile||`In-memory / not persisted yet`})]}),(0,Z.jsxs)(`div`,{className:`rounded-lg border bg-muted/20 p-4 text-sm text-muted-foreground`,children:[(0,Z.jsxs)(`div`,{className:`mb-2 flex items-center gap-2 font-medium text-foreground`,children:[(0,Z.jsx)(yi,{className:`h-4 w-4`}),`Shape`]}),(0,Z.jsx)(`p`,{children:`Session selection lives in M2. Main content stays focused on the active conversation and its context.`})]})]})]})]})]})}var OM={anthropic:`claude-3-5-sonnet-20241022`,openai:`gpt-4o`,ollama:`qwen2.5-coder:latest`,"lm-studio":``,vllm:``,custom:``},kM={anthropic:`https://api.anthropic.com`,openai:`https://api.openai.com/v1`,ollama:`http://localhost:11434/v1`,"lm-studio":`http://localhost:1234/v1`,vllm:`http://localhost:8000/v1`,custom:``};function AM(e){return kM[e]||``}function jM({label:e,hint:t,children:n}){return(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`text-sm font-medium`,children:e}),t&&(0,Z.jsx)(`p`,{className:`mb-1 mt-0.5 text-xs text-muted-foreground`,children:t}),(0,Z.jsx)(`div`,{className:t?void 0:`mt-1`,children:n})]})}var MM=`w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring resize-y`,NM=`w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring`;function PM(){let{agentId:e,tab:t}=yt(),n=ft(),{showToast:r}=wo(),{selectEntity:i,goBack:a}=qC(),o=De(),s=FD(t);(0,X.useEffect)(()=>{t!==s&&e&&n(`/agents/${encodeURIComponent(e)}/settings/${s}`,{replace:!0})},[t,s,e,n]);let[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(!0),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(``),[b,x]=(0,X.useState)(``),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)(on()),[E,D]=(0,X.useState)(``),[O,k]=(0,X.useState)(``),[A,j]=(0,X.useState)(``),[M,N]=(0,X.useState)(``),[P,ee]=(0,X.useState)(`anthropic`),[F,I]=(0,X.useState)(``),[te,L]=(0,X.useState)(``),[R,ne]=(0,X.useState)(``),[re,ie]=(0,X.useState)(.7),[ae,z]=(0,X.useState)(4096),[oe,se]=(0,X.useState)(1),B=lM(P,F,te,c?.id),ce=B.models.find(e=>e.id===R),[V,le]=(0,X.useState)([]),[ue,de]=(0,X.useState)(``),[fe,pe]=(0,X.useState)(``),[me,he]=(0,X.useState)(``),[ge,_e]=(0,X.useState)(``),[ve,ye]=(0,X.useState)(!1),[be,xe]=(0,X.useState)(null),[H,Se]=(0,X.useState)(null),[Ce,U]=(0,X.useState)(null),[W,we]=(0,X.useState)(!1),[Te,Ee]=(0,X.useState)(null),[Oe,ke]=(0,X.useState)(`context`),[Ae,je]=(0,X.useState)(``),[Me,Ne]=(0,X.useState)(`/`),[Pe,Fe]=(0,X.useState)(``),[Ie,Le]=(0,X.useState)(!0),[Re,ze]=(0,X.useState)(!1),[Be,Ve]=(0,X.useState)([]),[He,Ue]=(0,X.useState)([]),[We,Ge]=(0,X.useState)(null),[Ke,G]=(0,X.useState)(`{}`),[qe,Je]=(0,X.useState)(null),[Ye,Xe]=(0,X.useState)(e);Ye!==e&&(Xe(e),d(!0),l(null)),(0,X.useEffect)(()=>{if(!e)return;let t=!1;return QD(e).then(async e=>{if(t)return;let n=e.config?.identity||{};l(e),i(e.id),y(e.name||``),x(e.label||``),C(e.description||``),T(e.color||on()),D(n.role||``),k(n.identity||``),j(n.instructions||``),N(e.config?.prompts?.system||``),ee(e.llmProvider||`anthropic`),I(e.config?.apiKey||``),L(e.config?.baseUrl||AM(e.llmProvider)),ne(e.model||OM[e.llmProvider]||``);let r=e.config?.connectors?.[e.llmProvider];r&&(ie(r.temperature??.7),z(r.maxTokens??4096),se(r.topP??1)),G(JSON.stringify(e.config?.tools??{},null,2)),Je(null),p(null);try{le(await aO(e.id))}catch{le([])}}).catch(e=>{t||p(e instanceof Error?e.message:`Failed to load agent`)}).finally(()=>{t||d(!1)}),()=>{t=!0}},[e,i]),(0,X.useEffect)(()=>{if(s!==`access`&&s!==`tools`||!c?.id)return;let e=c.id,t=!1;return Promise.all([KD(c.id).catch(()=>null),Uo().catch(()=>[]),ml().catch(()=>[]),XD(c.id).catch(()=>null)]).then(([n,r,i,a])=>{t||(Se(n),Ve(r),Ue(i),Ge(a?a.tools:[]),n&&(ke(n.binding.type),je(n.binding.workspace||``),Ne(n.binding.path||`/`),Fe(n.binding.context||``),Le(n.permissions.includes(`read`)),ze(n.permissions.includes(`write`))),U(e))}),()=>{t=!0}},[s,c?.id]);let Ze=()=>{let e=sM(E,O,A),t;try{let e=JSON.parse(Ke);e&&typeof e==`object`&&!Array.isArray(e)&&(t=e)}catch{}return{...t===void 0?{}:{tools:t},name:v.trim(),label:b.trim(),description:S.trim()||void 0,color:w,llmProvider:P,model:R,apiKey:F.trim()||(P===c?.llmProvider?void 0:``),baseUrl:te||void 0,config:{type:P,model:R,identity:{role:E.trim()||void 0,identity:O.trim()||void 0,instructions:A.trim()||void 0},prompts:M.trim()||e?{system:M.trim()||e}:void 0,connectors:{[P]:{temperature:re,maxTokens:ae,topP:oe}}}}},Qe=async e=>{if(e.preventDefault(),c){h(!0);try{let e=await lO(c.id,Ze());l(e),window.dispatchEvent(new CustomEvent(`agents:refresh`)),r({title:`Saved`,description:`Agent updated`}),e.name&&e.name!==c.name&&n(`/agents/${encodeURIComponent(e.name)}/settings/${s}`,{replace:!0})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{h(!1)}}},$e=async()=>{if(c&&window.confirm(`Delete agent "${c.label||c.name}"? This cannot be undone.`)){_(!0);try{await uO(c.id),window.dispatchEvent(new CustomEvent(`agents:refresh`)),r({title:`Deleted`,description:`Agent removed`}),n(`/agents`)}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Delete failed`,variant:`destructive`})}finally{_(!1)}}},et=()=>{de(``),pe(``),he(``),_e(``)},tt=async()=>{if(!(!c||!ge.trim()&&!me.trim())){ye(!0);try{let e=await oO(c.id,ge.trim()?{source:ge.trim()}:{name:ue,description:fe,content:me});le(e),et(),window.dispatchEvent(new CustomEvent(`agents:refresh`)),r({title:`Installed`,description:`Skill saved`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Skill install failed`,variant:`destructive`})}finally{ye(!1)}}},nt=async e=>{if(c){xe(e);try{let t=await sO(c.id,e);le(t),(ue===e||ge===e)&&et(),window.dispatchEvent(new CustomEvent(`agents:refresh`)),r({title:`Removed`,description:`Skill "${e}" removed`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Skill remove failed`,variant:`destructive`})}finally{xe(null)}}},rt=()=>Oe===`global`?{type:`global`}:Oe===`context`?Pe?{type:`context`,context:Pe}:null:Ae?Oe===`path`?{type:`path`,workspace:Ae,path:Me.trim()||`/`}:{type:`workspace`,workspace:Ae}:null,it=async()=>{if(!c||W)return;let e=rt(),t=[];if(Ie&&t.push(`read`),Re&&t.push(`write`),!e||t.length===0){r({title:`Invalid binding`,description:`Pick a scope target and at least one permission`,variant:`destructive`});return}if(!(e.type===`global`&&!window.confirm(`Global scope lets this agent ${Re?`read and write`:`read`} ALL your workspaces. Continue?`))){we(!0);try{let n=await qD(c.id,{binding:e,permissions:t});Se(n.access),Ee(n.token),r({title:`Bound`,description:`Access bound — copy the token now, it is not shown again`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Bind failed`,variant:`destructive`})}finally{we(!1)}}},at=async()=>{if(!(!c||W)){we(!0);try{let e=await JD(c.id);Se(e.access),Ee(e.token),r({title:`Rotated`,description:`New token minted — the previous one no longer works`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Rotate failed`,variant:`destructive`})}finally{we(!1)}}},ot=async()=>{if(!(!c||W)&&window.confirm(`Revoke this agent's canvas access? Its token stops working immediately.`)){we(!0);try{await YD(c.id),Se(null),Ee(null),r({title:`Revoked`,description:`Agent access removed`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Revoke failed`,variant:`destructive`})}finally{we(!1)}}},st=e=>{if(e.type===`global`)return`Global — all workspaces`;if(e.type===`context`){let t=He.find(t=>t.id===e.context);return`Context ${t?`${t.id} (${t.url})`:e.context} — follows the context live`}let t=e.workspaceName||e.workspace;return e.type===`path`?`Workspace ${t}, path ${e.path||`/`}`:`Workspace ${t} (whole tree)`};if(u)return(0,Z.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Loading...`});if(!c||f)return(0,Z.jsx)(`div`,{className:`p-6 text-sm text-destructive`,children:f||`Agent not found`});let ct=PD.find(e=>e.id===s),lt=encodeURIComponent(c.name||c.id),ut=s===`identity`||s===`provider`||s===`models`||s===`tools`;return(0,Z.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,Z.jsxs)(`div`,{className:`mx-auto max-w-5xl p-6 pb-12 max-md:px-4 max-md:pb-rail-stack`,children:[(0,Z.jsx)(sw,{compact:!0,className:`mb-6 border-b pb-4`,title:`${ct.label} - ${c.label||c.name}`,description:ct.description,backTo:`/agents/${lt}`,onBack:o?a:void 0}),(0,Z.jsxs)(`form`,{onSubmit:Qe,className:`space-y-6`,children:[s===`identity`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsx)(jM,{label:`Name`,hint:`ID: ${c.id}`,children:(0,Z.jsx)(q,{value:v,onChange:e=>y(e.target.value),placeholder:`lucy`})}),(0,Z.jsx)(jM,{label:`Label`,children:(0,Z.jsx)(q,{value:b,onChange:e=>x(e.target.value),placeholder:`Display name`})})]}),(0,Z.jsx)(jM,{label:`Description`,children:(0,Z.jsx)(q,{value:S,onChange:e=>C(e.target.value),placeholder:`Short description`})}),(0,Z.jsx)(jM,{label:`Color`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(q,{type:`color`,value:w,onChange:e=>T(e.target.value),className:`h-10 w-16 p-1`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>T(on()),children:`Randomize`})]})})]}),(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Persona`}),(0,Z.jsx)(jM,{label:`Role`,children:(0,Z.jsx)(q,{value:E,onChange:e=>D(e.target.value),placeholder:`e.g. Software Engineer`})}),(0,Z.jsx)(jM,{label:`Identity`,children:(0,Z.jsx)(`textarea`,{value:O,onChange:e=>k(e.target.value),placeholder:`Who this agent is…`,className:`${MM} min-h-[80px]`})}),(0,Z.jsx)(jM,{label:`Instructions`,children:(0,Z.jsx)(`textarea`,{value:A,onChange:e=>j(e.target.value),placeholder:`Behavioral instructions…`,className:`${MM} min-h-[80px]`})}),(0,Z.jsx)(jM,{label:`System Prompt`,hint:`Compiled from Role + Identity + Instructions. Override manually.`,children:(0,Z.jsx)(`textarea`,{value:M,onChange:e=>N(e.target.value),placeholder:`System prompt sent to the LLM…`,className:`${MM} min-h-[140px] font-mono text-xs`})})]}),(0,Z.jsxs)(`section`,{className:`rounded-lg border border-destructive/30 p-4`,children:[(0,Z.jsx)(`h2`,{className:`mb-3 text-sm font-semibold text-destructive`,children:`Danger Zone`}),(0,Z.jsxs)(Y,{type:`button`,variant:`destructive`,disabled:g,onClick:$e,children:[(0,Z.jsx)(Qr,{className:`mr-2 h-4 w-4`}),g?`Deleting...`:`Delete Agent`]})]})]}),s===`provider`&&(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(jM,{label:`Provider`,children:(0,Z.jsxs)(`select`,{value:P,onChange:e=>{let t=e.target.value;ee(t),I(``),ne(OM[t]||``),L(AM(t))},className:`w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring`,children:[(0,Z.jsx)(`option`,{value:`anthropic`,children:`Anthropic Claude`}),(0,Z.jsx)(`option`,{value:`openai`,children:`OpenAI GPT`}),(0,Z.jsx)(`option`,{value:`ollama`,children:`Ollama (Local)`}),(0,Z.jsx)(`option`,{value:`lm-studio`,children:`LM Studio (Local)`}),(0,Z.jsx)(`option`,{value:`vllm`,children:`vLLM (Local)`}),(0,Z.jsx)(`option`,{value:`custom`,children:`Custom`})]})}),(0,Z.jsx)(jM,{label:`API Key`,hint:[`ollama`,`lm-studio`,`vllm`].includes(P)?`Any value works for local providers.`:void 0,children:(0,Z.jsx)(q,{type:`password`,value:F,onChange:e=>I(e.target.value),placeholder:P===`ollama`?`ollama`:P===`lm-studio`?`lm-studio`:`sk-…`})}),(0,Z.jsx)(jM,{label:`Host / Base URL`,children:(0,Z.jsx)(q,{value:te,onChange:e=>L(e.target.value),placeholder:AM(P)||`https://api.example.com`})})]}),s===`models`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Main Model`}),(0,Z.jsx)(jM,{label:`Model`,children:(0,Z.jsx)(cM,{value:R,onChange:(e,t)=>{ne(e),t?.maxTokens&&z(t.maxTokens)},...B})}),(0,Z.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-3`,children:[(0,Z.jsx)(jM,{label:`Temperature`,children:(0,Z.jsx)(q,{type:`number`,min:0,max:2,step:.1,value:re,onChange:e=>ie(Number.isNaN(e.target.valueAsNumber)?.7:e.target.valueAsNumber)})}),(0,Z.jsx)(jM,{label:`Max Output Tokens`,children:(0,Z.jsx)(q,{type:`number`,min:1,max:ce?.maxTokens,value:ae,onChange:e=>z(parseInt(e.target.value)||4096)})}),(0,Z.jsx)(jM,{label:`Top P`,children:(0,Z.jsx)(q,{type:`number`,min:0,max:1,step:.1,value:oe,onChange:e=>se(Number.isNaN(e.target.valueAsNumber)?1:e.target.valueAsNumber)})})]})]}),[`Governance`,`Memory Management`,`Subagent / Tool Use`].map(e=>(0,Z.jsxs)(`section`,{className:`rounded-lg border border-dashed p-4`,children:[(0,Z.jsxs)(`h2`,{className:`text-sm font-semibold text-muted-foreground`,children:[e,` Model`]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Coming soon`})]},e))]}),s===`tools`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Runtime Tools`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Injected at start (pi defineTool): coding tools plus canvas tools scoped by the token binding (Access / ACL). Definitions live in the runtime — read-only here until the agent-runtime workspace lands.`})]}),We===null?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Loading…`}):We.length===0?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`No tools resolved.`}):(0,Z.jsx)(`div`,{className:`space-y-1.5`,children:We.map(e=>(0,Z.jsxs)(`details`,{className:`rounded-md border px-3 py-2`,children:[(0,Z.jsxs)(`summary`,{className:`cursor-pointer text-sm`,children:[(0,Z.jsx)(`code`,{className:`font-mono text-xs font-medium`,children:e.name}),(0,Z.jsx)(`span`,{className:`ml-2 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,children:e.source})]}),e.description&&(0,Z.jsx)(`p`,{className:`mt-2 whitespace-pre-wrap text-xs text-muted-foreground`,children:e.description}),e.parameters!=null&&(0,Z.jsx)(`pre`,{className:`mt-2 overflow-x-auto rounded bg-muted p-2 font-mono text-[11px]`,children:JSON.stringify(e.parameters,null,2)})]},e.name))}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:H?st(H.binding):`Unbound — no canvas tools are injected. Bind under Access / ACL.`})]}),(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Tools Config`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`config.tools JSON, merged server-side — e.g. {"canvas": {"enabled": false}} gates the canvas tools. Saved with Save Changes.`})]}),(0,Z.jsx)(`textarea`,{value:Ke,onChange:e=>{G(e.target.value);try{JSON.parse(e.target.value),Je(null)}catch(e){Je(e instanceof Error?e.message:`Invalid JSON`)}},className:`${MM} min-h-[120px] font-mono text-xs`}),qe&&(0,Z.jsxs)(`p`,{className:`text-xs text-destructive`,children:[`Invalid JSON (not saved): `,qe]})]}),(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Skills`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Installed skills are saved immediately, independent of Save Changes.`})]}),V.length===0?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`No skills installed.`}):V.map(e=>(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3 rounded-md border p-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-medium`,children:e.name}),(0,Z.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:e.package?e.source:e.description||`No description`})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{de(e.name),pe(e.description||``),he(e.content||``),_e(e.source||``)},children:`Edit`}),(0,Z.jsx)(Y,{type:`button`,variant:`destructive`,size:`sm`,disabled:be===(e.source||e.name),onClick:()=>nt(e.source||e.name),children:be===(e.source||e.name)?`Removing…`:`Remove`})]})]},e.name)),(0,Z.jsxs)(`div`,{className:`space-y-4 rounded-md border p-4`,children:[(0,Z.jsx)(jM,{label:`Package Source`,hint:`Use this for whole pi packages. Leave empty to save inline SKILL.md content.`,children:(0,Z.jsx)(q,{value:ge,onChange:e=>_e(e.target.value),placeholder:`npm:@foo/pi-tools or git:github.com/badlogic/pi-doom`})}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsx)(jM,{label:`Name`,children:(0,Z.jsx)(q,{value:ue,onChange:e=>de(e.target.value),placeholder:`skill-name, or read from frontmatter`,disabled:!!ge.trim()})}),(0,Z.jsx)(jM,{label:`Description`,children:(0,Z.jsx)(q,{value:fe,onChange:e=>pe(e.target.value),placeholder:`What this skill helps with`,disabled:!!ge.trim()})})]}),(0,Z.jsx)(jM,{label:`SKILL.md Content`,children:(0,Z.jsx)(`textarea`,{value:me,onChange:e=>he(e.target.value),placeholder:`# Skill instructions…`,disabled:!!ge.trim(),className:`${MM} min-h-[160px] font-mono text-xs`})}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(Y,{type:`button`,disabled:ve||!ge.trim()&&!me.trim(),onClick:tt,children:ve?`Saving…`:`Install / Update Skill`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,onClick:et,children:`Clear`})]})]})]}),(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`MCP Servers`}),(c.config?.mcp?.servers||[]).length===0?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`No MCP servers configured.`}):(c.config?.mcp?.servers||[]).map((e,t)=>(0,Z.jsxs)(`div`,{className:`rounded-md border p-3`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium`,children:e.name}),(0,Z.jsxs)(`div`,{className:`font-mono text-xs text-muted-foreground`,children:[e.command,` `,(e.args||[]).join(` `)]})]},t))]})]}),s===`access`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Canvas Access`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The agent talks to canvas through its own scoped token; the server clamps every request to the binding. Bind, rotate and revoke apply immediately.`})]}),Ce===c.id?H?(0,Z.jsxs)(`div`,{className:`space-y-2 rounded-md border p-3`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium`,children:st(H.binding)}),(0,Z.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[`Permissions: `,H.permissions.join(`, `)||`none`,H.boundAt?` · bound ${new Date(H.boundAt).toLocaleString()}`:``,H.rotatedAt?` · token rotated ${new Date(H.rotatedAt).toLocaleString()}`:``]}),(0,Z.jsxs)(`div`,{className:`flex gap-2 pt-1`,children:[(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:W,onClick:at,children:`Rotate Token`}),(0,Z.jsx)(Y,{type:`button`,variant:`destructive`,size:`sm`,disabled:W,onClick:ot,children:`Revoke Access`})]})]}):(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Unbound — this agent has no canvas access.`}):(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Loading…`}),Te&&(0,Z.jsxs)(`div`,{className:`space-y-2 rounded-md border border-warning/50 bg-warning/10 p-3`,children:[(0,Z.jsx)(`div`,{className:`text-xs font-medium`,children:`Agent token — shown once, store it now`}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`code`,{className:`flex-1 truncate rounded bg-background px-2 py-1 font-mono text-xs`,children:Te}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>navigator.clipboard?.writeText(Te),children:`Copy`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>Ee(null),children:`Dismiss`})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`In-process agents receive it automatically (canvas.env); external runtimes (agentd) take it as CANVAS_TOKEN.`})]})]}),(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:H?`Rebind`:`Bind`}),(0,Z.jsx)(jM,{label:`Scope`,hint:`Context bindings follow the context live; global spans all workspaces.`,children:(0,Z.jsxs)(`select`,{value:Oe,onChange:e=>ke(e.target.value),className:NM,children:[(0,Z.jsx)(`option`,{value:`context`,children:`Context (follows live)`}),(0,Z.jsx)(`option`,{value:`workspace`,children:`Workspace`}),(0,Z.jsx)(`option`,{value:`path`,children:`Workspace path`}),(0,Z.jsx)(`option`,{value:`global`,children:`Global (all workspaces)`})]})}),Oe===`context`&&(0,Z.jsx)(jM,{label:`Context`,children:(0,Z.jsxs)(`select`,{value:Pe,onChange:e=>Fe(e.target.value),className:NM,children:[(0,Z.jsx)(`option`,{value:``,children:`Select a context…`}),He.map(e=>(0,Z.jsxs)(`option`,{value:e.id,children:[e.id,` — `,e.url]},e.id))]})}),(Oe===`workspace`||Oe===`path`)&&(0,Z.jsx)(jM,{label:`Workspace`,children:(0,Z.jsxs)(`select`,{value:Ae,onChange:e=>je(e.target.value),className:NM,children:[(0,Z.jsx)(`option`,{value:``,children:`Select a workspace…`}),Be.map(e=>(0,Z.jsx)(`option`,{value:e.name||e.id,children:e.label||e.name},e.id))]})}),Oe===`path`&&(0,Z.jsx)(jM,{label:`Base path`,hint:`The agent is clamped to this subtree.`,children:(0,Z.jsx)(q,{value:Me,onChange:e=>Ne(e.target.value),placeholder:`/work/projects/foo`})}),(0,Z.jsx)(jM,{label:`Permissions`,children:(0,Z.jsxs)(`div`,{className:`flex gap-4 text-sm`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:Ie,onChange:e=>Le(e.target.checked)}),` read`]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:Re,onChange:e=>ze(e.target.checked)}),` write`]})]})}),(0,Z.jsx)(Y,{type:`button`,disabled:W,onClick:it,children:W?`Working…`:H?`Rebind & Mint Token`:`Bind & Mint Token`})]})]}),s===`memory`&&(0,Z.jsxs)(`section`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold text-muted-foreground`,children:`Memory Engine`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Loop-based memory management. Settings coming soon.`})]}),s===`integrations`&&(0,Z.jsxs)(`section`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold text-muted-foreground`,children:`Integrations`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`IMAP, chat, SQL and REST API accounts. Coming soon.`})]}),ut&&(0,Z.jsx)(Y,{type:`submit`,disabled:m,children:m?`Saving…`:`Save Changes`})]})]})})}var FM=`workspace:backups`,IM=e=>`${no.workspaces}/${encodeURIComponent(e)}/db/backups`,LM=e=>J.get(IM(e)),RM=e=>J.post(IM(e),{action:`backup`}),zM=(e,t)=>J.post(IM(e),{action:`restore`,backupId:t,confirm:!0}),BM=new Map;function VM(e,t,n){let r=JSON.stringify([t,n.id]),i=BM.get(r);if(i)return i;let a=(async()=>{let r=n.action===`restore`,i=e({title:r?`Restoring workspace database`:`Backing up workspace database`,description:r?`Stopping the workspace and preserving its current database…`:`Copying and verifying all datasets…`});try{let e=n;for(;e.status===`running`;){let n=await LM(t),r=n.jobs.find(t=>t.id===e.id);if(!r)throw Error(`The server restarted. Refresh the backup list to check the result.`);e=r,window.dispatchEvent(new CustomEvent(FM,{detail:{workspace:t,status:n}})),e.status===`running`&&await new Promise(e=>setTimeout(e,1500))}if(e.status===`failed`)throw Error(e.error||`Database operation failed`);i.done({title:r?`Workspace database restored`:`Workspace backup verified`,description:r?`The workspace is stopped. Start it when you are ready; search indexes will rebuild.`:`Documents, relations and virtual tree placements are saved.`})}catch(e){throw i.fail({title:`Workspace backup needs attention`,description:e instanceof Error?e.message:String(e),variant:`destructive`}),e}})();return BM.set(r,a),a.finally(()=>BM.delete(r)).catch(()=>{}),a}var HM={startup:`Startup`,hourly:`Hourly`,manual:`Manual`,"pre-restore":`Before restore`};function UM({workspaceId:e,onRestored:t}){let{showToast:n,showProgress:r}=wo(),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(!1),f=(0,X.useRef)(!1),p=(0,X.useRef)(!1),m=(0,X.useRef)(0),h=(0,X.useCallback)(()=>{let t=++m.current;return LM(e).then(n=>{if(!(!f.current||t!==m.current)){a(n),s(null);for(let t of n.jobs.filter(e=>e.status===`running`))VM(r,e,t).catch(()=>{})}}).catch(e=>{f.current&&t===m.current&&s(e instanceof Error?e.message:String(e))})},[e,r]);(0,X.useEffect)(()=>{f.current=!0,h();let t=t=>{let n=t.detail;n.workspace===e&&a(n.status)};return window.addEventListener(FM,t),()=>{f.current=!1,window.removeEventListener(FM,t)}},[e,h]);let g=async i=>{if(!p.current){p.current=!0,d(!0);try{let n=i?await zM(e,i.id):await RM(e);f.current&&a(e=>e&&{...e,jobs:[n,...e.jobs]}),await VM(r,e,n),i&&t()}catch(e){n({title:`Database operation did not complete`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{p.current=!1,f.current&&(d(!1),h())}}},_=u||!!i?.jobs.some(e=>e.status===`running`),v=i?.jobs[0];return(0,Z.jsxs)(`div`,{className:`min-w-0 space-y-5`,children:[(0,Z.jsxs)(`section`,{className:`space-y-4 rounded border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Z.jsx)(ra,{className:`h-5 w-5 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`font-semibold`,children:`Workspace checkpoints`}),(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,className:`ml-auto`,disabled:_||!i||!!o,onClick:()=>void g(),children:[_?(0,Z.jsx)(Ti,{className:`mr-2 h-4 w-4 animate-spin`}):(0,Z.jsx)(ra,{className:`mr-2 h-4 w-4`}),`Back up now`]})]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Save a checkpoint before a bulk action. Each backup includes every document, relation and virtual tree placement in this workspace’s database.`}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-x-5 gap-y-2 text-sm`,children:[(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`strong`,{children:i?.retention.hourly??24}),` hourly backups`]}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`strong`,{children:i?.retention.startup??14}),` startup backups`]}),(0,Z.jsx)(`span`,{children:`Manual checkpoints kept`})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Hourly backups run while the workspace is active. These checkpoints cover the database only; files in storage backends and workspace settings need their own backups.`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsxs)(`h2`,{className:`text-sm font-semibold`,children:[`Verified checkpoints`,i?` · ${i.backups.length}`:``]}),(0,Z.jsx)(Y,{variant:`ghost`,size:`icon`,className:`h-8 w-8`,onClick:()=>void h(),"aria-label":`Refresh backups`,children:(0,Z.jsx)(Er,{className:`h-4 w-4`})})]}),o&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:o}),v&&(0,Z.jsx)(`p`,{role:`status`,className:`text-sm ${v.status===`failed`?`text-destructive`:`text-muted-foreground`}`,children:v.status===`running`?`Database operation in progress…`:v.status===`failed`?v.error:v.action===`restore`?`Database restored. The workspace is stopped and ready to start.`:`Backup complete and verified.`}),!i&&!o&&(0,Z.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:`Loading backups…`}),i?.backups.length===0&&(0,Z.jsx)(`p`,{className:`rounded border border-dashed p-6 text-sm text-muted-foreground`,children:`No verified checkpoints yet. Create one before your next bulk action.`}),(0,Z.jsx)(`div`,{className:`space-y-2`,children:i?.backups.map(e=>(0,Z.jsxs)(`article`,{className:`flex min-w-0 flex-wrap items-center gap-3 rounded border p-3`,children:[(0,Z.jsx)(sr,{className:`h-4 w-4 shrink-0 text-muted-foreground`,"aria-label":`Verified`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 basis-40`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:new Date(e.createdAt).toLocaleString()}),(0,Z.jsxs)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:[HM[e.kind],` · `,Ts(e.bytes),` · `,(e.datasets.documents?.count??0).toLocaleString(),` documents`]})]}),(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,disabled:_,onClick:()=>l(e),children:[(0,Z.jsx)(Vr,{className:`mr-2 h-3.5 w-3.5`}),`Restore`]})]},e.id))}),(0,Z.jsx)(vo,{open:!!c,onOpenChange:e=>{e||l(null)},children:(0,Z.jsxs)(lo,{className:`max-w-[calc(100vw-2rem)] sm:max-w-lg`,children:[(0,Z.jsxs)(_o,{children:[(0,Z.jsx)(io,{children:`Restore this workspace checkpoint?`}),(0,Z.jsxs)(ro,{children:[`The workspace will stop and its current database will be backed up first. Documents, relations and virtual tree placements will return to `,c?new Date(c.createdAt).toLocaleString():`the selected checkpoint`,`. Files in storage backends and workspace settings will stay as they are. The workspace stays stopped after restoration.`]})]}),(0,Z.jsxs)(mo,{children:[(0,Z.jsx)(go,{children:`Cancel`}),(0,Z.jsx)(po,{disabled:_,onClick:()=>{c&&g(c)},children:`Back up current & restore`})]})]})})]})}var WM={collect:`Collect unused blobs`,verify:`Verify integrity`,compact:`Compact index`},GM=e=>e.status===`queued`||e.status===`running`,KM=e=>`${no.workspaces}/${encodeURIComponent(e)}/cache/maintenance`,qM=e=>J.get(KM(e)),JM=(e,t,n)=>J.post(KM(e),{store:t,action:n,...n===`verify`?{confirm:!0}:{}});function YM(e){if(e.status===`failed`)return e.error||`Maintenance failed`;if(e.status===`queued`)return`Waiting for active storage operations…`;if(e.status===`running`)return e.action===`verify`?`Reading and checking stored content…`:`Processing the cache index…`;let t=e.result||{};return e.action===`compact`?`${(t.compactedCount||0).toLocaleString()} keys compacted`:e.action===`verify`?`${(t.verifiedContent||0).toLocaleString()} blobs verified · ${(t.badContentCount||0).toLocaleString()} corrupted blobs removed · ${Ts(t.reclaimedSize||0)} reclaimed`:`${(t.reclaimedCount||0).toLocaleString()} unused blobs removed · ${Ts(t.reclaimedSize||0)} reclaimed`}var XM=new Map,ZM=`workspace:cache-maintenance`;function QM(e,t,n){let r=JSON.stringify([t,n.id]),i=XM.get(r);if(i)return i;let a=(async()=>{let r=e({title:WM[n.action],description:`${n.store} · ${YM(n)}`});try{let e=n;for(;GM(e);){let i=await qM(t),a=i.jobs.find(e=>e.id===n.id);if(!a)throw Error(`Maintenance receipt is no longer available. The server may have restarted; refresh the cache settings.`);if(e=a,window.dispatchEvent(new CustomEvent(ZM,{detail:{workspace:t,status:i}})),!GM(e))break;r.update({title:WM[e.action],description:`${e.store} · ${YM(e)}`}),await new Promise(e=>setTimeout(e,2e3))}if(e.status===`failed`)throw Error(YM(e));r.done({title:`${WM[e.action]} complete`,description:`${e.store} · ${YM(e)}`})}catch(e){throw r.fail({title:`Cache maintenance needs attention`,description:`${n.store} · ${e instanceof Error?e.message:String(e)}`,variant:`destructive`}),e}})();return XM.set(r,a),a.finally(()=>{XM.get(r)===a&&XM.delete(r)}).catch(()=>{}),a}function $M({workspaceId:e,children:t}){let{showToast:n,showProgress:r}=wo(),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(`workspace:cache`),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(null),m=(0,X.useRef)(!1),h=(0,X.useRef)(!1),g=(0,X.useCallback)(()=>qM(e).then(t=>{if(h.current){a(t),p(null);for(let n of t.jobs.filter(GM))QM(r,e,n).catch(()=>{})}}).catch(e=>{h.current&&p(e instanceof Error?e.message:`Cannot load maintenance status`)}),[e,r]);(0,X.useEffect)(()=>{h.current=!0,g();let t=t=>{let{workspace:n,status:r}=t.detail;n===e&&(a(r),p(null))};return window.addEventListener(ZM,t),()=>{h.current=!1,window.removeEventListener(ZM,t)}},[e,g]);let _=async t=>{if(!(m.current||i?.jobs.some(GM))){m.current=!0,l(!0);try{let n=await JM(e,o,t);h.current&&a(e=>e&&{...e,jobs:[n,...e.jobs.filter(e=>e.id!==n.id)]}),QM(r,e,n).catch(()=>{})}catch(e){n({title:`Could not start maintenance`,description:e instanceof Error?e.message:String(e),variant:`destructive`}),g()}finally{m.current=!1,h.current&&l(!1)}}},v=c||!!i?.jobs.some(GM),y=i?.stores.find(e=>e.id===o),b=i?.jobs[0];return(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-(--panel-radius) border p-4`,"aria-label":`Workspace cache maintenance`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`h2`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[(0,Z.jsx)(Fa,{className:`h-4 w-4 shrink-0`}),`Workspace cache`]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Thumbnails, cached resources and pending transfers. Maintenance runs only when requested.`})]}),t&&(0,Z.jsx)(`fieldset`,{disabled:v,children:t})]}),(0,Z.jsxs)(`div`,{className:`space-y-3 border-t pt-3`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`label`,{htmlFor:`cache-maintenance-store`,className:`text-xs font-medium`,children:`Store`}),(0,Z.jsxs)(`select`,{id:`cache-maintenance-store`,value:o,onChange:e=>s(e.target.value),disabled:v,className:`min-w-0 max-w-full rounded-md border bg-background px-2 py-1.5 text-xs`,children:[(0,Z.jsx)(`option`,{value:`workspace:cache`,children:`workspace:cache`}),(0,Z.jsx)(`option`,{value:`workspace:data`,children:`workspace:data`})]}),(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`icon`,onClick:()=>void g(),"aria-label":`Refresh cache maintenance status`,className:`ml-auto h-8 w-8`,children:(0,Z.jsx)(Er,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:o===`workspace:data`?`Managed document blobs. Referenced content is kept during collection.`:`Working cache, including content awaiting transfer. Referenced content is kept during collection.`}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:v||!y?.canCollect||!!f,onClick:()=>void _(`collect`),children:[(0,Z.jsx)(Qr,{className:`mr-2 h-3.5 w-3.5`}),`Collect unused blobs`]}),(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:v||!y?.canCompact||!!f,onClick:()=>void _(`compact`),children:[(0,Z.jsx)(ra,{className:`mr-2 h-3.5 w-3.5`}),`Compact index`]}),(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:v||!y?.canVerify||!!f,onClick:()=>d(!0),children:[(0,Z.jsx)(Fi,{className:`mr-2 h-3.5 w-3.5`}),`Verify integrity`]})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Collection removes unreferenced blobs. Compaction trims index history. Verification reads every blob and may remove corrupted content. Storage writes may wait during maintenance.`}),!i&&!f&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,role:`status`,children:`Loading maintenance status…`}),y&&!y.canCollect&&!y.canVerify&&!y.canCompact&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Update canvas-stored to enable maintenance for this store.`}),f&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,role:`alert`,children:f}),b&&(0,Z.jsxs)(`div`,{className:`rounded-md bg-muted/50 p-3 text-xs`,role:`status`,"aria-live":`polite`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 font-medium`,children:[GM(b)&&(0,Z.jsx)(Ti,{className:`h-3.5 w-3.5 animate-spin`}),WM[b.action],` · `,b.store]}),(0,Z.jsx)(`p`,{className:`mt-1 ${b.status===`failed`?`text-destructive`:`text-muted-foreground`}`,children:YM(b)}),(0,Z.jsx)(`p`,{className:`mt-1 text-muted-foreground`,children:b.finishedAt?`Finished ${new Date(b.finishedAt).toLocaleString()}`:`Requested ${new Date(b.createdAt).toLocaleString()}`})]})]}),(0,Z.jsx)(vo,{open:u,onOpenChange:d,children:(0,Z.jsxs)(lo,{className:`max-w-[calc(100vw-2rem)] sm:max-w-lg`,children:[(0,Z.jsxs)(_o,{children:[(0,Z.jsxs)(io,{children:[`Verify `,o,`?`]}),(0,Z.jsx)(ro,{children:`This reads all stored content and can take a long time. Corrupted blobs and their index entries may be removed. Keep a recovery backup before running it. Storage writes may wait until it finishes.`})]}),(0,Z.jsxs)(mo,{children:[(0,Z.jsx)(go,{children:`Cancel`}),(0,Z.jsx)(po,{disabled:v,onClick:()=>void _(`verify`),children:`Verify and repair`})]})]})})]})}function eN({workspaceId:e,backend:t,onSaved:n}){let r=t?.config||{},i=()=>({name:String(r.label||``),bucket:String(r.bucket||``),prefix:String(r.prefix||``),endpoint:String(r.endpoint||``),region:String(r.region||`us-east-1`),accessKeyId:``,secretAccessKey:``,sessionToken:``}),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(i),[l,u]=(0,X.useState)(r.forcePathStyle!==!1),[d,f]=(0,X.useState)(r.readOnly===!0),[p,m]=(0,X.useState)(r.watch===!0),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(!1),{showToast:y}=wo(),b=e=>({value:s[e],onChange:t=>c(n=>({...n,[e]:t.target.value}))});return a?(0,Z.jsxs)(`form`,{onSubmit:async r=>{r.preventDefault(),v(!0);try{let r={label:s.name.trim(),bucket:s.bucket.trim(),prefix:s.prefix.trim(),endpoint:s.endpoint.trim(),region:s.region.trim()||`us-east-1`,forcePathStyle:l,readOnly:d,watch:p,...Object.fromEntries([`accessKeyId`,`secretAccessKey`,`sessionToken`].flatMap(e=>{let t=s[e].trim();return t?[[e,t]]:[]})),...h?{sessionToken:``}:{}};t?await Fo(e,`s3`,t.address,r):await Zs(e,`s3`,r),o(!1),c(i()),y({title:t?`S3 backend updated`:`S3 backend added`,description:`Use Re-sync to check indexing progress, and filing policies to automate copies.`}),await n()}catch(e){y({title:`Could not connect S3`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{v(!1)}},className:`w-full space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`h2`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[(0,Z.jsx)(Fa,{className:`h-4 w-4`}),t?`Edit S3 connection`:`Add S3-compatible bucket`]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Amazon S3, MinIO, Garage, RustFS or Ceph RGW. Connect an existing bucket, optionally scoped to a prefix. Supports browsing, reads and filing copies; mirror policies and overwrites are unavailable.`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs`,children:[`Name`,(0,Z.jsx)(q,{...b(`name`),required:!0,placeholder:`Accounting archive`})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs`,children:[`Bucket`,(0,Z.jsx)(q,{...b(`bucket`),disabled:!!t,required:!0,placeholder:`accounting`})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs`,children:[`Endpoint (blank for Amazon S3)`,(0,Z.jsx)(q,{...b(`endpoint`),disabled:!!t,type:`url`,placeholder:`https://s3.example.com`})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs`,children:[`Region`,(0,Z.jsx)(q,{...b(`region`),required:!0,placeholder:`us-east-1`})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs sm:col-span-2`,children:[`Prefix (optional)`,(0,Z.jsx)(q,{...b(`prefix`),disabled:!!t,placeholder:`Augmentd/Accounting`})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs`,children:[`Access key ID`,(0,Z.jsx)(q,{...b(`accessKeyId`),required:!t,autoComplete:`off`,placeholder:t?`Leave blank to keep stored value`:``})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs`,children:[`Secret access key`,(0,Z.jsx)(q,{...b(`secretAccessKey`),type:`password`,required:!t,autoComplete:`off`,placeholder:t?`Leave blank to keep stored value`:``})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs sm:col-span-2`,children:[`Session token (optional)`,(0,Z.jsx)(q,{...b(`sessionToken`),disabled:h,type:`password`,autoComplete:`off`,placeholder:t?`Leave blank to keep stored value`:``})]}),t&&(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:h,onChange:e=>g(e.target.checked)}),`Clear stored session token`]})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-4 text-xs`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:l,onChange:e=>u(e.target.checked)}),`Path-style addressing`]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:d,onChange:e=>f(e.target.checked)}),`Read-only`]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:p,onChange:e=>m(e.target.checked)}),`Poll for changes`]})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Writable connections test conflict protection using a temporary object, then delete it. The key needs list/read/write access and delete access under .canvas-probe/. Initial indexing reads file bytes; polling can incur request and download charges. Upload limit: 5 GiB per file.`}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,disabled:_,onClick:()=>{o(!1),c(i())},children:`Cancel`}),(0,Z.jsx)(Y,{disabled:_,children:_?`Checking connection…`:`Save connection`})]})]}):(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:()=>{c(i()),u(r.forcePathStyle!==!1),f(r.readOnly===!0),m(r.watch===!0),g(!1),o(!0)},children:[t?(0,Z.jsx)(Lr,{className:`mr-2 h-3.5 w-3.5`}):(0,Z.jsx)(br,{className:`mr-2 h-3.5 w-3.5`}),t?`Edit S3 connection`:`Add S3 bucket`]})}function tN({workspaceId:e,isActive:t,currentMode:n,onChanged:r}){let[i,a]=(0,X.useState)(n===`workspace`?`workspace`:`secrets`),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(``),[f,p]=(0,X.useState)(``),[m,h]=(0,X.useState)(``),[g,_]=(0,X.useState)(!1);return(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`font-semibold text-sm`,children:`Workspace protection`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Protect service credentials with a PIN or password. Optionally require it to start the whole workspace. Files and document contents are not encrypted.`}),t&&(0,Z.jsx)(`p`,{className:`text-sm`,children:`Stop the workspace before changing protection.`}),(0,Z.jsxs)(`form`,{className:`space-y-3`,onSubmit:async t=>{if(t.preventDefault(),h(``),o!==c){h(`PIN/password confirmation does not match`);return}_(!0);try{let t=await J.put(`${no.workspaces}/${e}/protection`,{mode:i,passphrase:o,currentPassphrase:u||void 0});p(t.recoveryKey),s(``),l(``),d(``)}catch(e){h(e instanceof Error?e.message:`Could not save protection`)}finally{_(!1)}},children:[(0,Z.jsxs)(`label`,{className:`block text-sm space-y-1`,children:[`Protection mode`,(0,Z.jsxs)(`select`,{className:`block rounded border bg-background p-2 w-full`,value:i,onChange:e=>a(e.target.value),disabled:t||g,children:[(0,Z.jsx)(`option`,{value:`secrets`,children:`Secrets only — allow start without integrations`}),(0,Z.jsx)(`option`,{value:`workspace`,children:`Whole workspace — require PIN/password to start`})]})]}),(0,Z.jsxs)(`label`,{className:`block text-sm space-y-1`,children:[`Current PIN/password or recovery key (if already protected)`,(0,Z.jsx)(q,{type:`password`,autoComplete:`current-password`,value:u,onChange:e=>d(e.target.value),disabled:t||g})]}),(0,Z.jsxs)(`label`,{className:`block text-sm space-y-1`,children:[`New PIN/password`,(0,Z.jsx)(q,{type:`password`,autoComplete:`new-password`,minLength:4,maxLength:1024,required:!0,value:o,onChange:e=>s(e.target.value),disabled:t||g})]}),(0,Z.jsxs)(`label`,{className:`block text-sm space-y-1`,children:[`Confirm new PIN/password`,(0,Z.jsx)(q,{type:`password`,autoComplete:`new-password`,required:!0,value:c,onChange:e=>l(e.target.value),disabled:t||g})]}),(0,Z.jsx)(Y,{disabled:t||g||!!f,children:g?`Saving…`:`Save protection`})]}),m&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:m}),f&&(0,Z.jsxs)(`div`,{className:`space-y-2 rounded border p-3`,children:[(0,Z.jsx)(`p`,{className:`text-sm`,children:`Save this recovery key now. It is shown only once and replaces any previous recovery key.`}),(0,Z.jsx)(`code`,{className:`block break-all select-all`,children:f}),(0,Z.jsx)(Y,{variant:`outline`,onClick:()=>{p(``),r()},children:`I saved the recovery key`})]})]})}var nN=`h-8 rounded-md border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring`;function rN({title:e,hint:t,children:n}){let[r,i]=(0,X.useState)(!1);return(0,Z.jsxs)(`section`,{className:`overflow-hidden rounded-lg border`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>i(e=>!e),"aria-expanded":r,className:`flex w-full items-center justify-between gap-4 px-4 py-3 text-left transition-colors hover:bg-muted/40`,children:[(0,Z.jsxs)(`span`,{className:`min-w-0`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium`,children:e}),(0,Z.jsx)(`span`,{className:`mt-0.5 block text-xs text-muted-foreground`,children:t})]}),(0,Z.jsx)(qr,{className:K(`h-4 w-4 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none`,r&&`rotate-180`)})]}),r&&(0,Z.jsx)(`div`,{className:`border-t p-4`,children:n})]})}function iN({workspaceId:e,workspaceName:t,refreshKey:n,onRefresh:r}){let{showToast:i}=wo(),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),l=(0,X.useCallback)(()=>KA(e).then(e=>o(e.queue??null)).catch(()=>{}),[e]);(0,X.useEffect)(()=>{l();let e=window.setInterval(()=>{o(e=>(e&&(e.pending>0||e.draining)&&l(),e))},3e3);return()=>window.clearInterval(e)},[l,n]);let u=async()=>{if(a){c(!0);try{let e=await Oc(!a.paused,t);i({title:e.paused?`Embedding paused`:`Embedding resumed`,description:e.paused?`${e.pending.toLocaleString()} job(s) held for this workspace. Resume any time; a restart also resumes.`:`${e.pending.toLocaleString()} job(s) draining.`}),await l()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to toggle the embedding queue (admin only)`,variant:`destructive`})}finally{c(!1)}}},d=!!a?.draining,f=a?a.paused?`bg-warning`:d?`bg-success`:`bg-muted-foreground/40`:`bg-muted-foreground/40`;return(0,Z.jsxs)(`section`,{className:`flex flex-wrap items-center justify-between gap-x-4 gap-y-2 rounded-lg border bg-muted/30 px-4 py-2.5`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 text-sm`,children:[(0,Z.jsxs)(`span`,{className:`relative flex h-2 w-2 shrink-0`,"aria-hidden":!0,children:[d&&(0,Z.jsx)(`span`,{className:`absolute inline-flex h-full w-full animate-ping rounded-full bg-success opacity-60 motion-reduce:hidden`}),(0,Z.jsx)(`span`,{className:K(`relative inline-flex h-2 w-2 rounded-full`,f)})]}),(0,Z.jsx)(`span`,{className:`font-medium`,children:a?a.pending>0?(0,Z.jsxs)(Z.Fragment,{children:[a.pending.toLocaleString(),` `,(0,Z.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`pending`})]}):a.paused?`Paused`:`Idle`:`Queue unavailable`}),a?.paused&&a.pending>0&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`held`}),a?.ingestDisabled&&(0,Z.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,title:`CANVAS_INFERD_INGEST_DISABLED=true: nothing new is enqueued; existing vectors still serve search`,children:`ingest disabled`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1`,children:[a&&(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,disabled:s,onClick:u,title:a.paused?`Resume embedding; the held backlog drains`:`Pause after the current batch. Stops the CPU-heavy model inference; documents keep indexing and stay searchable by text.`,children:s?`…`:a.paused?`Resume`:`Pause`}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:r,title:`Reload config, queue and tables`,children:(0,Z.jsx)(Er,{className:`h-3.5 w-3.5`})})]})]})}function aN({workspaceId:e,tables:t,error:n,onChanged:r}){let{showToast:i}=wo(),[a,o]=(0,X.useState)(null),s=t.filter(e=>!e.active),c=async t=>{if(window.confirm(`Reclaim "${t.name}"?\n\nThis permanently deletes the vectors for ${t.model||`that model`} and its "already embedded" ledger. Switching back to it afterwards would cost a full re-embed rather than being instant.\n\nThis is the only irreversible step in the whole flow.`)){o(t.name);try{let n=await $A(e,t.name);if(!n.dropped)throw Error(n.error||`Failed to drop the vector table`);i({title:`Reclaimed`,description:`Dropped '${n.name||t.name}'.`}),r()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to reclaim`,variant:`destructive`})}finally{o(null)}}};return n?(0,Z.jsxs)(`section`,{className:`rounded-lg border border-destructive/40 bg-destructive-subtle p-4`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium text-destructive`,children:`Vector tables unavailable`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:n})]}):s.length===0?null:(0,Z.jsx)(rN,{title:`Previous models (${s.length})`,hint:`Kept on disk so switching back is instant. Reclaiming deletes their vectors for good (the only irreversible step here).`,children:(0,Z.jsx)(`div`,{className:`divide-y`,children:s.map(e=>(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-4 py-2 first:pt-0 last:pb-0`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`p`,{className:`truncate font-mono text-xs`,children:[e.model||`unknown model`,e.dim?` · ${e.dim}-d`:``]}),(0,Z.jsxs)(`p`,{className:`truncate font-mono text-[11px] text-muted-foreground`,children:[`└─ `,e.name]})]}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,className:`text-destructive hover:text-destructive`,disabled:a===e.name,onClick:()=>c(e),title:`Permanently delete this model's vectors and ledger`,children:[(0,Z.jsx)(Qr,{className:`mr-1.5 h-3.5 w-3.5`}),a===e.name?`Reclaiming…`:`Reclaim`]})]},e.name))})})}function oN({workspaceId:e,workspaceName:t,spaces:n,onDone:r}){let{showToast:i}=wo(),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(``),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1);return(0,Z.jsxs)(rN,{title:`Fill a space`,hint:`Embed documents that are missing from a space. Narrow it to one subtree to try a model on a single project first.`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Space`}),(0,Z.jsxs)(`select`,{className:`${nN} w-full`,value:a,onChange:e=>o(e.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:`all spaces`}),n.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`label`,{className:`text-xs font-medium`,children:[`Limit to a path `,(0,Z.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(optional)`})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:s,onChange:e=>c(e.target.value),placeholder:`ctx://work/project or dir://photos`,className:`h-8 font-mono text-sm`}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>m(!0),title:`Pick a context or directory path from the tree`,children:(0,Z.jsx)(fr,{className:`h-3.5 w-3.5`})})]})]})]}),(0,Z.jsxs)(`label`,{className:`mt-3 flex items-start gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:l,onChange:e=>u(e.target.checked)}),(0,Z.jsxs)(`span`,{children:[`Re-embed documents that are already embedded`,l&&s.trim()&&(0,Z.jsx)(`span`,{className:`mt-1 block text-[11px] text-warning`,children:`Combined with a path limit this clears the WHOLE space, not just that subtree. A partial clear is not expressible in the ledger. Leave this off unless you mean to redo everything.`})]})]}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,className:`mt-3`,onClick:async()=>{f(!0);try{let t=await ZA(e,{space:a||void 0,reindex:l,scope:s.trim()||void 0});t.ingestDisabled?i({title:`Ingest disabled`,description:`CANVAS_INFERD_INGEST_DISABLED=true: nothing was enqueued. Existing vectors still serve search.`,variant:`destructive`}):i({title:`Fill enqueued`,description:`${t.enqueued.toLocaleString()} document(s) queued${t.scope?` under ${t.scope}`:``}. The status line reports progress.`}),r()}catch(e){i({title:`Fill failed`,description:e instanceof Error?e.message:`Failed to enqueue`,variant:`destructive`})}finally{f(!1)}},disabled:d,children:d?`Queueing…`:`Start fill`}),p&&(0,Z.jsx)(Le,{onClose:()=>m(!1),children:(0,Z.jsx)(y,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,fixedWorkspaceName:t,multiple:!1,onClose:()=>m(!1),onConfirm:(e,t)=>{let n=e[0];if(n){let e=t.treeType===`directory`?`dir`:`ctx`;c(`${e}://${n.replace(/^\/+/,``)}`)}m(!1)}})})]})}var sN=[{provider:`blip`,model:`HuggingFaceTB/SmolVLM-500M-Instruct`,task:`instruct`,label:`SmolVLM 500M: prompted description (recommended)`,note:`~500 MB. Follows the prompt below, so architecture/materials/setting can be asked for.`},{provider:`blip`,model:`HuggingFaceTB/SmolVLM-256M-Instruct`,task:`instruct`,label:`SmolVLM 256M: prompted, smaller`,note:`~250 MB. Same prompting, weaker; for memory-tight boxes.`},{provider:`blip`,model:`onnx-community/Florence-2-base-ft`,task:`florence2`,label:`Florence-2 base: detailed caption`,note:`Detailed multi-sentence captions, but not steerable: no prompt, fixed task token.`},{provider:`blip`,model:`Xenova/vit-gpt2-image-captioning`,task:`caption`,label:`vit-gpt2: one short sentence (weakest)`,note:`The old default. Terse and repetition-prone; kept for continuity and low memory.`}],cN=`custom`,lN=[{value:`instruct`,label:`Instruct VLM (image + prompt)`},{value:`florence2`,label:`Florence-2 (task token)`},{value:`caption`,label:`Plain captioner (image only)`}],uN=`Describe this photograph in two or three sentences. If it shows a building or interior, name the architectural style, the main materials and the setting. Describe only what is visible.`;function dN({workspaceId:e,config:t,saving:n,onSave:r}){let{showToast:i}=wo(),a=t.workspace||{},o=t.effective||{},s=sN[0],c=a.summarize?.image||o.summarize?.image||{},[l,u]=(0,X.useState)(()=>o.summarize?.image?.enabled===!0||a.summarize?.image?.enabled===!0),[d,f]=(0,X.useState)(()=>{let e=sN.find(e=>e.provider===(c.provider||s.provider)&&e.model===c.model);return e?`${e.provider}::${e.model}`:c.model?cN:`${s.provider}::${s.model}`}),[p,m]=(0,X.useState)(()=>sN.some(e=>e.model===c.model)?``:c.model||``),[h,g]=(0,X.useState)(()=>c.task||`instruct`),[_,v]=(0,X.useState)(()=>c.prompt||``),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(null),[C,w]=(0,X.useState)(!1),[T,E]=(0,X.useState)(!1),[D,O]=(0,X.useState)(!1),k=sN.find(e=>`${e.provider}::${e.model}`===d),A=d===cN,j=A?{provider:s.provider,model:p.trim(),task:h,label:`Custom`,note:``}:k||s,M=j.task===`instruct`,N=(0,X.useCallback)(()=>KA(e).then(e=>S(e.summarize||null)).catch(()=>{}),[e]);(0,X.useEffect)(()=>{N();let e=window.setInterval(()=>{S(e=>(e?.running&&N(),e))},2e3);return()=>window.clearInterval(e)},[N]);let P=async()=>{await r({...a,summarize:{...a.summarize||{},image:{enabled:l,provider:j.provider,model:j.model,task:j.task,...M&&_.trim()?{prompt:_.trim()}:{}}}}),b(!1)},ee=async()=>{E(!0);try{S(await JA(e)),i({title:`Stopping image summaries`,description:`The image being captioned finishes first; the rest are left for a later run.`})}catch(e){i({title:`Could not stop`,description:e instanceof Error?e.message:`Failed to stop`,variant:`destructive`})}finally{E(!1)}},F=async(t=!1)=>{w(!0);try{let n=await qA(e,{force:t});S(n),i({title:t?`Rebuilding image summaries`:`Backfilling image summaries`,description:`${n.total.toLocaleString()} candidate image(s). First run downloads model weights.`})}catch(e){i({title:`Summaries failed to start`,description:e instanceof Error?e.message:`Failed to start`,variant:`destructive`})}finally{w(!1)}},I=o.summarize?.image?.enabled===!0,te=x?.running===!0,L=x?.errors?.[0]?.error;return(0,Z.jsx)(rN,{title:`Summaries`,hint:`Generate descriptions for indexed images (metadata.summary); searchable via full-text and dense search`,children:(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-sm`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:l,disabled:n,onChange:e=>{u(e.target.checked),b(!0)}}),`Images`]}),(0,Z.jsxs)(`select`,{className:nN,value:d,disabled:n||!l,onChange:e=>{f(e.target.value),b(!0)},children:[sN.map(e=>(0,Z.jsx)(`option`,{value:`${e.provider}::${e.model}`,children:e.label},`${e.provider}::${e.model}`)),(0,Z.jsx)(`option`,{value:cN,children:`Custom model…`})]}),!A&&(0,Z.jsx)(`span`,{className:`font-mono text-xs text-muted-foreground`,children:j.model})]}),A&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{className:`h-8 w-72 font-mono text-xs`,placeholder:`org/model-id (Transformers.js / ONNX)`,value:p,disabled:n||!l,onChange:e=>{m(e.target.value),b(!0)}}),(0,Z.jsx)(`select`,{className:nN,value:h,disabled:n||!l,onChange:e=>{g(e.target.value),b(!0)},children:lN.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))})]}),l&&j.note&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:j.note}),l&&M&&(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`textarea`,{className:`w-full rounded-md border border-input bg-transparent p-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,rows:3,placeholder:uN,value:_,disabled:n,onChange:e=>{v(e.target.value),b(!0)}}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`What to ask of every image. Empty uses the default shown above. Captions are indexed, so ask for the words you would search by.`})]}),x&&(x.running||x.total>0||x.finishedAt)&&(0,Z.jsxs)(`p`,{className:K(`text-xs`,x.aborted?`text-destructive`:`text-muted-foreground`),children:[te?`Running`:x.aborted?`Stopped`:x.cancelled?`Cancelled`:`Last run`,`: `,x.described,`/`,x.total,` described`,x.skipped?`, ${x.skipped} skipped`:``,x.failed?`, ${x.failed} failed`:``,x.aborted?`. ${x.abortedReason||`model worker died`}. Remaining images were not attempted; generate again to retry.`:x.cancelled?`. Stopped by you. The remaining images were left untouched; generate again to continue.`:L?`. ${L}`:``]}),(0,Z.jsxs)(`label`,{className:`flex items-start gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:D,disabled:n||te,onChange:e=>O(e.target.checked)}),(0,Z.jsxs)(`span`,{children:[`Re-caption images that already have a summary`,D&&(0,Z.jsxs)(`span`,{className:`mt-1 block text-[11px] text-warning`,children:[`Replaces every existing `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`metadata.summary`}),`, including ones written by a different model. Leave this off to fill in only what is missing.`]})]})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Enable + save, then run. Only the local caption provider is wired today. Candidates come from `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`data/mime/image`}),`.`]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>void P(),disabled:n||!y,children:`Save summaries`}),(0,Z.jsx)(Y,{size:`sm`,onClick:()=>void F(D),disabled:n||y||C||te||!I,title:I?y?`Save config first`:D?`Re-caption every image, replacing existing summaries`:`Caption images that have no summary yet`:`Enable image summaries and save first`,children:te||C?`Running…`:D?`Rebuild`:`Backfill`}),te&&(0,Z.jsx)(Y,{size:`sm`,variant:`destructive`,onClick:()=>void ee(),disabled:T,title:`Finish the current image, then stop. The rest are left for later.`,children:T?`Stopping…`:`Stop`})]})]})]})})}function fN({workspaceId:e,workspaceName:t}){let{showToast:n}=wo(),[r,i]=(0,X.useState)(null),[a,o]=(0,X.useState)([]),[s,c]=(0,X.useState)(),[l,u]=(0,X.useState)(!0),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)([]),[_,v]=(0,X.useState)(0),y=(0,X.useCallback)(()=>YA(e).then(e=>{i(e),m(null)}).catch(e=>m(e instanceof Error?e.message:`Failed to load the embedding config`)).finally(()=>u(!1)),[e]),b=(0,X.useCallback)(()=>QA(e).then(e=>{o(e.tables||[]),c(e.error)}).catch(e=>c(e instanceof Error?e.message:`Failed to list vector tables`)),[e]);(0,X.useEffect)(()=>{y(),b()},[y,b]);let x=()=>{u(!0),y(),b(),v(e=>e+1)},S=async t=>{f(!0);try{let r=await XA(e,t);g(r.movedSpaces||[]),r.movedSpaces?.length?n({title:`Saved; fill to finish`,description:`${r.movedSpaces.join(`, `)} now targets a new model. The switch is live, but the new table is empty until you fill it.`}):r.applied===!1?n({title:`Saved; applies on next start`,description:`The workspace is not running, so the new spaces take effect when it starts.`}):n({title:`Saved`,description:`Embedding config updated.`}),await y(),await b()}catch(e){n({title:`Save failed`,description:e instanceof Error?e.message:`Failed to save`,variant:`destructive`})}finally{f(!1)}},C=async t=>{try{let r=await ZA(e,{space:t});if(r.ingestDisabled){n({title:`Ingest disabled`,description:`CANVAS_INFERD_INGEST_DISABLED=true: nothing was enqueued. Existing vectors still serve search.`,variant:`destructive`});return}n({title:`Filling ${t}`,description:`${r.enqueued.toLocaleString()} document(s) queued. The status line reports progress.`}),g(e=>e.filter(e=>e!==t)),v(e=>e+1),b()}catch(e){n({title:`Fill failed`,description:e instanceof Error?e.message:`Failed to enqueue`,variant:`destructive`})}};if(l)return(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(Er,{className:`h-4 w-4 animate-spin`}),`Loading the embedding config…`]});if(p||!r)return(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`rounded-lg border border-destructive/40 bg-destructive-subtle p-4 text-sm`,children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Embedding config unavailable`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:p||`No config returned.`})]}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:x,children:`Try again`})]});let w=Object.keys(r.effective.spaces||{}).sort();return(0,Z.jsxs)(`div`,{className:`space-y-5`,children:[(0,Z.jsx)(iN,{workspaceId:e,workspaceName:t,refreshKey:_,onRefresh:x}),(0,Z.jsx)(bj,{value:r.workspace||{},effective:r.effective||{},inherited:r.inherited||{},resolvedSpaces:r.spaces,invalid:r.invalid,attention:h,onFill:C,saving:d,saveLabel:`Save embedding config`,onSave:S},JSON.stringify(r.workspace)),(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsx)(dN,{workspaceId:e,config:r,saving:d,onSave:S},`summarize:${JSON.stringify(r.workspace?.summarize||{})}`),(0,Z.jsx)(oN,{workspaceId:e,workspaceName:t,spaces:w,onDone:()=>{b(),v(e=>e+1)}}),(0,Z.jsx)(aN,{workspaceId:e,tables:a,error:s,onChanged:()=>{b()}})]}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Stored in this workspace's own `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`workspace.json`}),`, so it travels with the workspace. Settings resolve in layers: built-in, then server, then your defaults, then this workspace, which wins. Changes apply live, with no restart.`]})]})}function pN(e){let t=(e||``).split(`.`).pop()?.toLowerCase();switch(t){case`js`:case`mjs`:case`ts`:return[l({typescript:t===`ts`})];case`json`:return[c()];case`sh`:case`bash`:return[a.define(u)];default:return[]}}function mN({value:e,onChange:t,path:n,className:r=``}){let i=(0,X.useMemo)(()=>pN(n),[n]),{resolvedScheme:a}=Ll();return(0,Z.jsx)(o,{value:e,onChange:t,extensions:i,theme:a===`dark`?`dark`:`light`,className:r,basicSetup:{lineNumbers:!0,foldGutter:!0,highlightActiveLine:!0,bracketMatching:!0,autocompletion:!1}})}var hN=[`pending`,`approved`,`declined`,`failed`,`expired`,`all`],gN={pending:`text-warning dark:text-warning`,approved:`text-success dark:text-success`,declined:`text-muted-foreground`,failed:`text-destructive`,expired:`text-muted-foreground line-through`};function _N(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return`now`;if(n<60)return`${n}m`;let r=Math.floor(n/60);return r<24?`${r}h`:`${Math.floor(r/24)}d`}function vN(e,t){return t.split(`.`).reduce((e,t)=>typeof e==`object`&&e?e[t]:void 0,e)}function yN(e){let t=e.split(`.`);return t.slice(Math.max(t.length-2,2)).join(`.`)}var bN=/(body|content|message|text|prompt)$/i;function xN({workspaceId:e,id:t,children:n}){let{open:r}=I(),{showToast:i}=wo(),[a,o]=(0,X.useState)(!1),s=async n=>{n.stopPropagation(),o(!0);try{r(await xc(e,t),e)}catch(e){i({title:`Document ${t} not available`,description:e instanceof Error?e.message:void 0,variant:`destructive`})}finally{o(!1)}};return(0,Z.jsx)(`button`,{type:`button`,disabled:a,onClick:e=>void s(e),className:`text-primary underline-offset-2 hover:underline disabled:opacity-60`,title:`Open document ${t}`,children:n??`doc ${t}`})}function SN({workspaceId:e,text:t}){let n=t.split(/(\bdoc \d+\b)/);return(0,Z.jsx)(Z.Fragment,{children:n.map((t,n)=>{let r=/^doc (\d+)$/.exec(t);return r?(0,Z.jsx)(xN,{workspaceId:e,id:Number(r[1])},n):(0,Z.jsx)(X.Fragment,{children:t},n)})})}function CN({action:e,amend:t,onAmend:n}){return e.editable?.length?(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.editable.map(r=>{let i=vN(e,r),a=typeof i==`string`,o=r in t?t[r]:i,s=a?String(o??``):JSON.stringify(o,null,2),c=a&&(bN.test(r)||s.length>80);return(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[(0,Z.jsxs)(`span`,{className:`font-medium text-muted-foreground`,children:[yN(r),(0,Z.jsx)(`span`,{className:`ml-1.5 font-mono text-[10px] opacity-60`,children:r}),r in t&&(0,Z.jsx)(`span`,{className:`ml-1.5 text-warning dark:text-warning`,children:`edited`})]}),c?(0,Z.jsx)(`textarea`,{className:`mt-1 w-full rounded-md border bg-background px-2 py-1.5 font-mono text-xs outline-none focus:ring-2 focus:ring-ring min-h-[100px]`,value:s,onChange:e=>n(r,e.target.value)}):(0,Z.jsx)(`input`,{className:`mt-1 w-full h-8 rounded-md border bg-background px-2 font-mono text-xs outline-none focus:ring-2 focus:ring-ring`,value:s,onChange:e=>{if(a){n(r,e.target.value);return}try{n(r,JSON.parse(e.target.value))}catch{n(r,e.target.value)}}})]},r)})}):null}function wN({workspaceId:e,onPendingCount:t}){let{showToast:n}=wo(),r=Cw(),[i,a]=(0,X.useState)(`pending`),[o,s]=(0,X.useState)([]),[c,l]=(0,X.useState)(!0),[u,d]=(0,X.useState)(new Set),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)({}),[g,_]=(0,X.useState)(!1),v=(0,X.useCallback)(()=>en(e,{status:i===`all`?void 0:i,limit:200}).then(e=>{s(e),d(t=>new Set(e.filter(e=>e.status===`pending`&&t.has(e.actionId)).map(e=>e.actionId))),t?.(i===`pending`?e.length:e.filter(e=>e.status===`pending`).length)}).catch(()=>{n({title:`Error`,description:`Failed to load pending actions`,variant:`destructive`})}).finally(()=>l(!1)),[e,i]),y=(0,X.useCallback)(async()=>{l(!0),await v()},[v]),[b,x]=(0,X.useState)(`${e}|${i}`),S=`${e}|${i}`;S!==b&&(x(S),l(!0)),(0,X.useEffect)(()=>{v()},[v]),fw(r,`workspace:${e}`,(0,X.useMemo)(()=>{let e=()=>{y()};return{"action.proposed":e,"action.approved":e,"action.declined":e,"action.failed":e}},[y]));let C=o.filter(e=>e.status===`pending`),w=C.length>0&&C.every(e=>u.has(e.actionId)),T=()=>{d(w?new Set:new Set(C.map(e=>e.actionId)))},E=e=>{d(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},D=(e,t,n)=>{h(r=>({...r,[e]:{...r[e],[t]:n}}))},O=async(t,r)=>{if(!(!t.length&&!r.length)){_(!0);try{let i=await gt(e,{approve:t.map(e=>{let t=m[e];return t&&Object.keys(t).length?{actionId:e,amend:t}:e}),decline:r}),a=i.results.filter(e=>e.status===`error`||e.status===`failed`);a.length?n({title:`${a.length} of ${i.decided} failed`,description:a.map(e=>`${e.actionId}: ${e.error??`execution failed`}`).join(`; `),variant:`destructive`}):n({title:t.length&&r.length?`Decisions applied`:t.length?`Approved ${t.length}`:`Declined ${r.length}`,description:t.length?`Approved actions executed with their original provenance.`:void 0}),h(e=>{let n={...e};for(let e of[...t,...r])delete n[e];return n}),d(new Set),f&&[...t,...r].includes(f)&&p(null),await y()}catch(e){n({title:`Decision failed`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{_(!1)}}};return(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 flex-wrap`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`select`,{className:`h-8 rounded-md border bg-background px-2 text-xs outline-none focus:ring-2 focus:ring-ring`,value:i,onChange:e=>a(e.target.value),children:hN.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))}),(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,onClick:()=>void y(),title:`Reload`,children:(0,Z.jsx)(Er,{className:`h-4 w-4`})})]}),u.size>0&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[u.size,` selected`]}),(0,Z.jsxs)(Y,{size:`sm`,disabled:g,onClick:()=>void O([...u],[]),children:[(0,Z.jsx)(sr,{className:`mr-1 h-3.5 w-3.5`}),` Approve`]}),(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,disabled:g,onClick:()=>void O([],[...u]),children:[(0,Z.jsx)(vr,{className:`mr-1 h-3.5 w-3.5`}),` Decline`]})]})]}),(0,Z.jsx)(`div`,{className:`border rounded-lg overflow-auto max-h-[560px]`,children:c?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground p-3`,children:`Loading...`}):o.length===0?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground p-3`,children:i===`pending`?`Nothing waiting for review. Rules or hooks with approval enabled queue their actions here.`:`No ${i===`all`?``:i+` `}actions recorded.`}):(0,Z.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,Z.jsx)(`thead`,{className:`text-xs text-muted-foreground border-b sticky top-0 bg-background`,children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{className:`px-3 py-2 w-8`,children:C.length>0&&(0,Z.jsx)(`input`,{type:`checkbox`,checked:w,onChange:T,title:`Select all pending`})}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Proposed action`}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Handler`}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Age`}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Status`}),(0,Z.jsx)(`th`,{className:`px-2 py-2 w-40`})]})}),(0,Z.jsx)(`tbody`,{children:o.map(t=>{let n=t.status===`pending`||t.status===`failed`,r=f===t.actionId,i=t.envelope?.payload?.document;return(0,Z.jsxs)(X.Fragment,{children:[(0,Z.jsxs)(`tr`,{className:`border-b last:border-0 align-top hover:bg-muted/40 cursor-pointer`,onClick:()=>p(r?null:t.actionId),children:[(0,Z.jsx)(`td`,{className:`px-3 py-2`,onClick:e=>e.stopPropagation(),children:t.status===`pending`&&(0,Z.jsx)(`input`,{type:`checkbox`,checked:u.has(t.actionId),onChange:()=>E(t.actionId)})}),(0,Z.jsxs)(`td`,{className:`px-3 py-2`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-1 font-medium`,children:[r?(0,Z.jsx)(qr,{className:`h-3 w-3 shrink-0`}):(0,Z.jsx)(Xa,{className:`h-3 w-3 shrink-0`}),t.title,t.editable?.length>0&&(0,Z.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide rounded bg-muted-foreground/15 px-1 py-0.5 text-muted-foreground shrink-0`,children:`editable`})]}),t.summary&&(0,Z.jsx)(`span`,{className:`block text-xs text-muted-foreground pl-4`,children:(0,Z.jsx)(SN,{workspaceId:e,text:t.summary})})]}),(0,Z.jsxs)(`td`,{className:`px-3 py-2 font-mono text-xs whitespace-nowrap`,children:[(0,Z.jsxs)(`span`,{className:`text-muted-foreground`,children:[t.handlerType,`:`]}),t.handler,t.event&&(0,Z.jsxs)(`span`,{className:`block text-muted-foreground`,children:[t.event,i?.id!=null&&(0,Z.jsxs)(Z.Fragment,{children:[` · `,(0,Z.jsx)(xN,{workspaceId:e,id:i.id})]})]})]}),(0,Z.jsx)(`td`,{className:`px-3 py-2 text-xs whitespace-nowrap`,title:t.ts,children:_N(t.ts)}),(0,Z.jsxs)(`td`,{className:`px-3 py-2 text-xs`,children:[(0,Z.jsx)(`span`,{className:gN[t.status],children:t.status}),t.amended&&(0,Z.jsx)(`span`,{className:`block text-muted-foreground`,children:`amended`}),t.decidedBy&&(0,Z.jsx)(`span`,{className:`block text-muted-foreground truncate max-w-[120px]`,title:t.decidedBy,children:t.decidedBy})]}),(0,Z.jsx)(`td`,{className:`px-2 py-2 whitespace-nowrap text-right`,onClick:e=>e.stopPropagation(),children:n&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Y,{size:`sm`,className:`h-7 px-2`,disabled:g,title:t.status===`failed`?`Retry (re-approve)`:`Approve and execute`,onClick:()=>void O([t.actionId],[]),children:(0,Z.jsx)(sr,{className:`h-3.5 w-3.5`})}),t.status===`pending`&&(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,className:`h-7 px-2 text-muted-foreground`,disabled:g,title:`Decline`,onClick:()=>void O([],[t.actionId]),children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]})})]}),r&&(0,Z.jsxs)(`tr`,{className:`border-b last:border-0 bg-muted/20`,children:[(0,Z.jsx)(`td`,{className:`px-3 py-3`}),(0,Z.jsxs)(`td`,{className:`px-3 py-3 space-y-3`,colSpan:5,children:[n&&t.editable?.length>0&&(0,Z.jsx)(CN,{action:t,amend:m[t.actionId]??{},onAmend:(e,n)=>D(t.actionId,e,n)}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Actions on approve`}),(0,Z.jsx)(`pre`,{className:`mt-1 rounded border bg-background p-2 font-mono text-xs overflow-auto max-h-56`,children:JSON.stringify(t.actions,null,2)})]}),t.result&&t.result.length>0&&(0,Z.jsx)(`div`,{className:`text-xs font-mono`,children:t.result.map((e,t)=>(0,Z.jsxs)(`span`,{className:`mr-2 ${e.status===`error`?`text-destructive`:`text-muted-foreground`}`,children:[e.action,`:`,e.status,e.error?` (${e.error})`:``]},t))}),(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground font-mono`,children:[t.actionId,` · origin `,t.provenance?.origin,t.provenance?.causedBy?` · causedBy ${t.provenance.causedBy}`:``,t.expiresAt?` · expires ${new Date(t.expiresAt).toLocaleString()}`:``]})]})]})]},t.actionId)})})]})})]})}var TN=`#!/usr/bin/env bash
|
|
40
|
+
`)}function cM({value:e,onChange:t,models:n,loading:r,error:i,refresh:a,disabled:o,id:s}){let c=(0,X.useId)(),l=n.find(t=>t.id===e);return(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{id:s,"aria-label":`Model`,list:c,value:e,onChange:e=>t(e.target.value,n.find(t=>t.id===e.target.value)),placeholder:`Choose or enter a model ID`,disabled:o}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,disabled:o||r,onClick:a,children:`Refresh models`})]}),(0,Z.jsx)(`datalist`,{id:c,children:n.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.name},e.id))}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,role:`status`,children:r?`Loading models…`:i||(n.length?`${n.length} models available`:`Enter provider credentials to load available models. You can also enter a model ID.`)}),l&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Context: `,l.contextWindow?.toLocaleString()??`not reported`,` · Max output: `,l.maxTokens?.toLocaleString()??`not reported`,` tokens`,l.limitsSource===`runtime`?` (runtime catalogue)`:l.limitsSource===`provider`?` (provider)`:``]})]})}function lM(e,t,n,r){let[i,a]=(0,X.useState)(0),o=JSON.stringify([e,t,n,r,i]),[s,c]=(0,X.useState)({key:``,models:[],loading:!1,error:``}),l=!!t.trim()||!!r||[`ollama`,`lm-studio`,`vllm`,`custom`].includes(e);return(0,X.useEffect)(()=>{if(!l)return;let i=new AbortController,a=setTimeout(()=>{c({key:o,models:[],loading:!0,error:``}),yO({provider:e,apiKey:t.trim()||void 0,baseUrl:n.trim()||void 0,agentIdentifier:r},i.signal).then(e=>{i.signal.aborted||c({key:o,models:e,loading:!1,error:``})}).catch(e=>{i.signal.aborted||c({key:o,models:[],loading:!1,error:e instanceof Error?e.message:`Unable to load models`})})},700);return()=>{clearTimeout(a),i.abort()}},[o,l,e,t,n,r]),{...s.key===o?s:{models:[],loading:l,error:``},refresh:()=>a(e=>e+1)}}function uM({agent:e,onStart:t,onStop:n,onEnter:r}){let[i,a]=(0,X.useState)(!1),o=async()=>{a(!0);try{await t(e.name)}finally{a(!1)}},s=async()=>{a(!0);try{await n(e.name)}finally{a(!1)}},c=()=>{switch(e.status){case`active`:return(0,Z.jsx)(yi,{className:`h-4 w-4 text-success`});case`inactive`:return(0,Z.jsx)(yi,{className:`h-4 w-4 text-warning`});case`error`:return(0,Z.jsx)(yi,{className:`h-4 w-4 text-destructive`});default:return(0,Z.jsx)(yi,{className:`h-4 w-4 text-muted-foreground`})}},l=()=>{switch(e.llmProvider){case`anthropic`:return(0,Z.jsx)(ri,{className:`h-4 w-4 text-warning`});case`openai`:return(0,Z.jsx)(ri,{className:`h-4 w-4 text-success`});case`ollama`:return(0,Z.jsx)(lr,{className:`h-4 w-4 text-info`});default:return(0,Z.jsx)(ri,{className:`h-4 w-4 text-muted-foreground`})}},u=()=>{switch(e.status){case`active`:return`text-success bg-success-subtle border-success`;case`inactive`:return`text-warning bg-warning-subtle border-warning`;case`error`:return`text-destructive bg-destructive-subtle border-destructive`;case`available`:return`text-info bg-info-subtle border-info`;default:return`text-foreground bg-muted border-border`}},d=e.status===`available`||e.status===`inactive`,f=e.status===`active`;return(0,Z.jsxs)(`div`,{className:`border rounded-lg p-4 space-y-4 hover:shadow-elevation-2 transition-shadow bg-card`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between`,children:[(0,Z.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 mb-1`,children:[l(),(0,Z.jsx)(`h3`,{className:`text-lg font-semibold truncate`,children:e.label||e.name}),e.color&&(0,Z.jsx)(`div`,{className:`w-4 h-4 rounded border flex-shrink-0`,style:{backgroundColor:e.color},title:`Color: ${e.color}`})]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground font-mono`,children:e.name}),e.description&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1 line-clamp-2`,children:e.description})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 flex-shrink-0`,children:[c(),(0,Z.jsx)(`span`,{className:`px-2 py-1 rounded-full text-xs font-medium border ${u()}`,children:e.status})]})]}),(0,Z.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 text-sm`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Provider:`}),(0,Z.jsx)(`div`,{className:`font-medium capitalize`,children:e.llmProvider})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Model:`}),(0,Z.jsx)(`div`,{className:`font-mono text-xs`,children:e.model})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Created:`}),(0,Z.jsx)(`div`,{children:new Date(e.createdAt).toLocaleDateString()})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Last Access:`}),(0,Z.jsx)(`div`,{children:e.lastAccessed?new Date(e.lastAccessed).toLocaleDateString():`Never`})]})]}),e.config.mcp?.servers&&e.config.mcp.servers.length>0&&(0,Z.jsxs)(`div`,{className:`text-sm`,children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`MCP Servers:`}),(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-1 mt-1`,children:e.config.mcp.servers.map((e,t)=>(0,Z.jsx)(`span`,{className:`px-2 py-1 bg-secondary text-secondary-foreground rounded text-xs`,children:e.name},t))})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2 pt-2 border-t`,children:[d&&(0,Z.jsxs)(Y,{onClick:o,disabled:i,size:`sm`,variant:`outline`,className:`flex-1`,children:[(0,Z.jsx)(Ar,{className:`mr-2 h-4 w-4`}),`Start`]}),f&&(0,Z.jsxs)(Y,{onClick:s,disabled:i,size:`sm`,variant:`outline`,className:`flex-1`,children:[(0,Z.jsx)(Sa,{className:`mr-2 h-4 w-4`}),`Stop`]}),(0,Z.jsxs)(Y,{onClick:()=>r(e.name),size:`sm`,className:`flex-1`,children:[(0,Z.jsx)(Ea,{className:`mr-2 h-4 w-4`}),`Chat`]})]})]})}function dM(){let e={anthropic:`https://api.anthropic.com`,openai:`https://api.openai.com/v1`,ollama:`http://localhost:11434/v1`},t={anthropic:`claude-3-5-sonnet-20241022`,openai:`gpt-4o`,ollama:`qwen2.5-coder:latest`},[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(!0),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(``),[f,p]=(0,X.useState)(on()),[m,h]=(0,X.useState)(``),[g,_]=(0,X.useState)(`anthropic`),[v,y]=(0,X.useState)(t.anthropic),[b,x]=(0,X.useState)({apiKey:``,baseUrl:e.anthropic,maxTokens:4096,temperature:.7,topP:1,frequencyPenalty:0,presencePenalty:0,numCtx:4096}),S=lM(g,b.apiKey,b.baseUrl),C=S.models.find(e=>e.id===v),[w,T]=(0,X.useState)(``),[E,D]=(0,X.useState)(``),[O,k]=(0,X.useState)(``),[A,j]=(0,X.useState)(``),[M,N]=(0,X.useState)(!1),P=aw(),[ee,F]=hw(),{showToast:I}=wo(),te=ft(),L=Cw();fw(L,`agent`,{"agent:status:changed":e=>{r(t=>t.map(t=>t.id===e.agentId?{...t,status:e.status,isActive:e.isActive}:t))},"agent:created":e=>{r(t=>[...t,e.agent])},"agent:deleted":e=>{r(t=>t.filter(t=>t.id!==e.agentId))}});let R=n=>{_(n),y(t[n]),x({apiKey:``,baseUrl:e[n],maxTokens:4096,temperature:.7,topP:1,frequencyPenalty:0,presencePenalty:0,numCtx:4096})};(0,X.useEffect)(()=>((async()=>{try{a(!0);let e=await ZD();r(e),s(null)}catch(e){console.error(`Agent fetch error:`,e);let t=`Failed to fetch agents`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to fetch agents`}s(t),I({title:`Error`,description:t,variant:`destructive`})}finally{a(!1)}})(),()=>{}),[L,I]);let ne=async t=>{if(t.preventDefault(),c.trim()){N(!0);try{let t=A.trim()||sM(w,E,O),n=await cO({name:c,label:m||c,description:u||void 0,color:f,llmProvider:g,model:v,apiKey:b.apiKey.trim()||void 0,baseUrl:b.baseUrl.trim()||void 0,config:{type:g,model:v,identity:{role:w.trim()||void 0,identity:E.trim()||void 0,instructions:O.trim()||void 0},prompts:t?{system:t}:void 0,connectors:{[g]:{maxTokens:b.maxTokens,...g===`anthropic`?{}:{temperature:b.temperature},topP:b.topP,frequencyPenalty:b.frequencyPenalty,presencePenalty:b.presencePenalty,...g===`ollama`?{numCtx:b.numCtx}:{}}}},mcp:{enabled:!0,servers:[{name:`weather`,command:`node`,args:[`src/managers/agent/mcp-servers/weather.js`]}]}});r(e=>[...e,n]),l(``),d(``),p(on()),h(``),j(``),T(``),D(``),k(``),x({apiKey:``,baseUrl:e[g],maxTokens:4096,temperature:.7,topP:1,frequencyPenalty:0,presencePenalty:0,numCtx:4096}),I({title:`Success`,description:`Agent '${n.label||n.name}' created.`}),F(!1)}catch(e){console.error(`Agent creation error:`,e);let t=`Failed to create agent`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to create agent`}I({title:`Error`,description:t,variant:`destructive`})}finally{N(!1)}}},re=async e=>{try{let t=await dO(e);r(e=>e.map(e=>e.name===t.name?t:e)),I({title:`Success`,description:`Agent '${t.label||t.name}' started.`})}catch(e){console.error(`Agent start error:`,e);let t=`Failed to start agent`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to start agent`}I({title:`Error`,description:t,variant:`destructive`})}},ie=async e=>{try{await fO(e),r(t=>t.map(t=>t.name===e?{...t,status:`inactive`,isActive:!1}:t)),I({title:`Success`,description:`Agent '${e}' stopped.`})}catch(e){console.error(`Agent stop error:`,e);let t=`Failed to stop agent`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to stop agent`}I({title:`Error`,description:t,variant:`destructive`})}},ae=e=>{te(`/agents/${e}`)};return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(sw,{title:`AI Agents`,description:`Create and manage your AI agents with multiple LLM providers`,actions:!P.local&&!ee&&(0,Z.jsxs)(Y,{onClick:()=>F(!0),className:`max-sm:h-9 max-sm:w-9 max-sm:p-0`,"aria-label":`Create agent`,title:`Create agent`,children:[(0,Z.jsx)(br,{className:`h-4 w-4 sm:mr-2`}),(0,Z.jsx)(`span`,{className:`max-sm:hidden`,children:`Create Agent`})]})}),!P.local&&ee&&(0,Z.jsx)(pw,{title:`Create New Agent`,onClose:()=>F(!1),children:(0,Z.jsxs)(`form`,{onSubmit:ne,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsx)(q,{value:c,onChange:e=>l(e.target.value),placeholder:`Agent Name (e.g., 'my-assistant')`,disabled:M}),(0,Z.jsx)(q,{value:m,onChange:e=>h(e.target.value),placeholder:`Agent Label (display name, optional)`,disabled:M})]}),(0,Z.jsx)(q,{value:u,onChange:e=>d(e.target.value),placeholder:`Description (optional)`,disabled:M}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`agent-provider`,className:`text-sm font-medium`,children:`LLM Provider`}),(0,Z.jsxs)(`select`,{id:`agent-provider`,value:g,onChange:e=>R(e.target.value),className:`w-full mt-1 px-3 py-2 border border-input bg-background rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-ring`,disabled:M,children:[(0,Z.jsx)(`option`,{value:`anthropic`,children:`Anthropic Claude`}),(0,Z.jsx)(`option`,{value:`openai`,children:`OpenAI GPT`}),(0,Z.jsx)(`option`,{value:`ollama`,children:`Ollama (Local)`})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`agent-model`,className:`text-sm font-medium`,children:`Model`}),(0,Z.jsx)(cM,{id:`agent-model`,value:v,onChange:(e,t)=>{y(e),t?.maxTokens&&x(e=>({...e,maxTokens:t.maxTokens}))},...S,disabled:M})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h3`,{className:`text-lg font-medium`,children:`Persona`}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`agent-role`,className:`text-sm font-medium`,children:`Role`}),(0,Z.jsx)(q,{id:`agent-role`,value:w,onChange:e=>T(e.target.value),placeholder:`e.g. Software Engineer`,disabled:M})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`agent-identity`,className:`text-sm font-medium`,children:`Identity`}),(0,Z.jsx)(`textarea`,{id:`agent-identity`,value:E,onChange:e=>D(e.target.value),placeholder:`Who this agent is…`,disabled:M,className:`w-full mt-1 px-3 py-2 border border-input bg-background rounded-md text-sm min-h-[80px] resize-y`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`agent-instructions`,className:`text-sm font-medium`,children:`Instructions`}),(0,Z.jsx)(`textarea`,{id:`agent-instructions`,value:O,onChange:e=>k(e.target.value),placeholder:`Behavioral instructions…`,disabled:M,className:`w-full mt-1 px-3 py-2 border border-input bg-background rounded-md text-sm min-h-[80px] resize-y`})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`system-prompt`,className:`text-sm font-medium`,children:`System Prompt (Optional Override)`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Built from Role, Identity and Instructions unless you enter an override.`}),(0,Z.jsx)(`textarea`,{id:`system-prompt`,value:A,onChange:e=>j(e.target.value),placeholder:sM(w,E,O)||`System prompt sent to the LLM…`,className:`w-full mt-1 px-3 py-2 border border-input bg-background rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-ring min-h-[80px] resize-y`,disabled:M})]}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`api-key`,className:`text-sm font-medium`,children:`API Key (Optional)`}),(0,Z.jsx)(q,{id:`api-key`,type:`password`,value:b.apiKey,onChange:e=>x(t=>({...t,apiKey:e.target.value})),placeholder:`Enter your API key`,disabled:M})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`baseUrl`,className:`text-sm font-medium`,children:`Base URL (Optional)`}),(0,Z.jsx)(q,{id:`baseUrl`,value:b.baseUrl,onChange:e=>x(t=>({...t,baseUrl:e.target.value})),placeholder:e[g],disabled:M})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h3`,{className:`text-lg font-medium`,children:`LLM Parameters`}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2 lg:grid-cols-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`max-tokens`,className:`text-sm font-medium`,children:`Max Output Tokens`}),(0,Z.jsx)(q,{id:`max-tokens`,type:`number`,min:`1`,max:C?.maxTokens,value:b.maxTokens,onChange:e=>x(t=>({...t,maxTokens:parseInt(e.target.value)||4096})),disabled:M})]}),g!==`anthropic`&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`temperature`,className:`text-sm font-medium`,children:`Temperature`}),(0,Z.jsx)(q,{id:`temperature`,type:`number`,min:`0`,max:`2`,step:`0.1`,value:b.temperature,onChange:e=>x(t=>({...t,temperature:Number.isNaN(e.target.valueAsNumber)?.7:e.target.valueAsNumber})),disabled:M})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`top-p`,className:`text-sm font-medium`,children:`Top P`}),(0,Z.jsx)(q,{id:`top-p`,type:`number`,min:`0`,max:`1`,step:`0.1`,value:b.topP,onChange:e=>x(t=>({...t,topP:Number.isNaN(e.target.valueAsNumber)?1:e.target.valueAsNumber})),disabled:M})]}),g===`ollama`&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`num-ctx`,className:`text-sm font-medium`,children:`Context Length`}),(0,Z.jsx)(q,{id:`num-ctx`,type:`number`,min:`1024`,max:C?.contextWindow,value:b.numCtx,onChange:e=>x(t=>({...t,numCtx:parseInt(e.target.value)||4096})),disabled:M})]})]}),g!==`ollama`&&(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`frequency-penalty`,className:`text-sm font-medium`,children:`Frequency Penalty`}),(0,Z.jsx)(q,{id:`frequency-penalty`,type:`number`,min:`-2`,max:`2`,step:`0.1`,value:b.frequencyPenalty,onChange:e=>x(t=>({...t,frequencyPenalty:parseFloat(e.target.value)||0})),disabled:M})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`presence-penalty`,className:`text-sm font-medium`,children:`Presence Penalty`}),(0,Z.jsx)(q,{id:`presence-penalty`,type:`number`,min:`-2`,max:`2`,step:`0.1`,value:b.presencePenalty,onChange:e=>x(t=>({...t,presencePenalty:parseFloat(e.target.value)||0})),disabled:M})]})]})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{htmlFor:`agent-color`,className:`text-sm font-medium`,children:`Agent Color`}),(0,Z.jsx)(q,{id:`agent-color`,type:`color`,value:f,onChange:e=>p(e.target.value),className:`h-10 w-16 p-1`,disabled:M}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>p(on()),disabled:M,children:`Randomize`})]}),(0,Z.jsxs)(Y,{type:`submit`,disabled:M||!c.trim(),children:[(0,Z.jsx)(br,{className:`mr-2 h-4 w-4`}),`Create Agent`]})]})}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your Agents`}),i&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading agents...`}),o&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:o})}),!i&&!o&&n.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No agents found`}),n.length>0&&(0,Z.jsx)(`div`,{className:`grid gap-4`,children:n.map(e=>(0,Z.jsx)(uM,{agent:e,onStart:re,onStop:ie,onEnter:ae},e.id))})]})]})}function fM(e){let t=e?.usage;if(!t)return null;let n=t.totalTokens,r=t.input,i=t.output;return typeof n==`number`&&typeof r==`number`&&typeof i==`number`?`${n} tok (${r} in / ${i} out)`:typeof n==`number`?`${n} tok`:null}function pM(e){let t=e?.usage?.cost?.total;return typeof t==`number`?`$${t.toFixed(t<.01?6:4)}`:null}function mM({reasoning:e,metadata:t,isStreaming:n=!1,compact:r=!1}){let i=t?.model,a=[t?.provider,i,fM(t),pM(t)].filter(Boolean);return!e&&a.length===0?null:(0,Z.jsxs)(Z.Fragment,{children:[e&&(0,Z.jsxs)(`details`,{open:n,className:`mb-2 rounded border border-border bg-background ${r?`px-2 py-1.5`:`px-3 py-2`}`,children:[(0,Z.jsx)(`summary`,{className:`cursor-pointer font-medium text-foreground ${r?`text-[11px]`:`text-xs`}`,children:`Reasoning`}),(0,Z.jsx)(F,{content:e,className:`mt-1 text-foreground ${r?`text-[11px]`:`text-xs`}`})]}),a.length>0&&(0,Z.jsx)(`div`,{className:`mt-2 text-muted-foreground ${r?`text-[11px]`:`text-xs`}`,children:a.join(` • `)})]})}function hM({message:e,isStreaming:t=!1,connectionStatus:n=`disconnected`}){let[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(!0);(0,X.useEffect)(()=>{if(!t||e.isComplete)return;let n=e.content,r=0,a=setInterval(()=>{r<n.length?(i(n.substring(0,r+1)),r++):clearInterval(a)},20);return()=>clearInterval(a)},[e.content,t,e.isComplete]);let s=t&&!e.isComplete?r:e.content;return(0,X.useEffect)(()=>{if(!t||e.isComplete)return;let n=setInterval(()=>{o(e=>!e)},500);return()=>{clearInterval(n),o(!0)}},[t,e.isComplete]),(0,Z.jsx)(`div`,{className:`flex ${e.role===`user`?`justify-end`:`justify-start`}`,children:(0,Z.jsxs)(`div`,{className:`max-w-[70%] p-3 rounded-lg ${e.role===`user`?`bg-primary text-primary-foreground`:`bg-muted`} ${t&&!e.isComplete?`border-2 border-info`:``}`,children:[(0,Z.jsx)(mM,{reasoning:e.role===`assistant`?e.metadata?.reasoning?.trim():void 0,metadata:e.role===`assistant`?e.metadata:void 0,isStreaming:t&&!e.isComplete}),(0,Z.jsxs)(`div`,{className:`text-sm`,children:[e.role===`assistant`?(0,Z.jsx)(F,{content:s}):(0,Z.jsx)(`span`,{className:`whitespace-pre-wrap break-words`,children:s}),t&&!e.isComplete&&(0,Z.jsx)(`span`,{className:`inline-block w-2 ${a?`bg-current`:`bg-transparent`}`,children:`|`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-between text-xs mt-2 opacity-70`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{children:new Date(e.timestamp).toLocaleTimeString()}),t&&!e.isComplete&&(0,Z.jsx)(`span`,{className:`text-info`,children:`• streaming...`})]}),e.role===`assistant`&&(()=>{switch(n){case`websocket`:return(0,Z.jsx)(`span`,{title:`WebSocket`,children:(0,Z.jsx)(Ja,{className:`h-3 w-3 text-success`})});case`sse`:return(0,Z.jsx)(`span`,{title:`Server-Sent Events`,children:(0,Z.jsx)($i,{className:`h-3 w-3 text-info`})});case`rest`:return(0,Z.jsx)(`span`,{title:`REST API`,children:(0,Z.jsx)(yi,{className:`h-3 w-3 text-warning`})});default:return(0,Z.jsx)(`span`,{title:`Disconnected`,children:(0,Z.jsx)(Hn,{className:`h-3 w-3 text-destructive`})})}})()]})]})})}var gM=(0,X.createContext)(null);function _M(e){let t=(0,X.useContext)(gM);if(!t)throw Error(`useAgentSessions must be used within an AgentSessionProvider`);let{getState:n,refresh:r,create:i,select:a,rename:o,remove:s}=t,c=n(e),l=(0,X.useCallback)(()=>r(e),[r,e]),u=(0,X.useCallback)(t=>i(e,t),[i,e]),d=(0,X.useCallback)(t=>a(e,t),[a,e]),f=(0,X.useCallback)((t,n)=>o(e,t,n),[o,e]),p=(0,X.useCallback)(t=>s(e,t),[s,e]);return(0,X.useMemo)(()=>({...c,refresh:l,create:u,select:d,rename:f,remove:p}),[c,l,u,d,f,p])}function vM(e={}){let[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(!1),s=(0,X.useRef)(e),c=(0,X.useRef)(null),l=(0,X.useRef)(!1);(0,X.useEffect)(()=>{s.current=e},[e]);let u=(0,X.useCallback)(()=>{if(!s.current.agentId||c.current||l.current)return;let e=localStorage.getItem(`authToken`);if(!e){console.warn(`No auth token available for WebSocket connection`);return}console.log(`[WebSocket] Using token type: ${e.startsWith(`canvas-`)?`API`:`JWT`}, length: ${e.length}`),l.current=!0,o(!0);let t=xo(no.ws,{auth:{token:e},transports:[`websocket`],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3,timeout:1e4,forceNew:!0});t.on(`connect`,()=>{console.log(`Agent WebSocket connected successfully`),i(!0),l.current=!1,o(!1)}),t.on(`connect_error`,e=>{console.error(`Agent WebSocket connection error:`,e),i(!1),l.current=!1,o(!1),(e.message?.includes(`Auth error`)||e.message?.includes(`token`))&&console.warn(`WebSocket auth failed, will fallback to SSE for streaming`)}),t.on(`disconnect`,e=>{console.log(`Agent WebSocket disconnected:`,e),i(!1),l.current=!1,o(!1)}),t.on(`agent:chat:chunk`,e=>{console.log(`Received chat chunk:`,e),s.current.onMessage&&s.current.onMessage(e)}),t.on(`agent:chat:complete`,e=>{console.log(`Chat stream complete:`,e),s.current.onComplete&&s.current.onComplete(e.agentId,e.messageId,e.messages)}),t.on(`agent:chat:error`,e=>{console.error(`Chat stream error:`,e),s.current.onError&&s.current.onError(e)}),t.on(`agent:chat:start`,e=>{console.log(`Chat stream started:`,e)}),c.current=t,n(t)},[]),d=(0,X.useCallback)(()=>{let e=c.current;e&&(e.removeAllListeners(),e.close()),c.current=null,l.current=!1,n(null),i(!1),o(!1)},[]),f=(0,X.useCallback)(e=>{t&&r&&(console.log(`Subscribing to agent channel: ${e}`),t.emit(`agent:subscribe`,{agentId:e}))},[t,r]),p=(0,X.useCallback)(e=>{t&&r&&(console.log(`Unsubscribing from agent channel: ${e}`),t.emit(`agent:unsubscribe`,{agentId:e}))},[t,r]),m=(0,X.useCallback)((e,n)=>{if(!t||!r)throw Error(`WebSocket not connected`);let i=`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return console.log(`Starting streaming chat for agent ${e}, message ${i}`),t.emit(`agent:chat:stream`,{agentId:e,messageId:i,...n}),i},[t,r]);return(0,X.useEffect)(()=>{if(e.agentId)return u(),()=>{d()}},[e.agentId,u,d]),(0,X.useEffect)(()=>{if(r&&e.agentId)return f(e.agentId),()=>{e.agentId&&p(e.agentId)}},[r,e.agentId,f,p]),{socket:t,isConnected:r,isConnecting:a,connect:u,disconnect:d,joinAgentChannel:f,leaveAgentChannel:p,startStreamingChat:m}}function yM(e){if(!e)return``;if(typeof e.errorMessage==`string`&&e.errorMessage.trim())return e.errorMessage.trim();let t=e.content;return typeof t==`string`?t:Array.isArray(t)&&t.filter(e=>e?.type===`text`&&typeof e.text==`string`).map(e=>e.text??``).join(`
|
|
41
|
+
`)||``}function bM(e,t){return`${e||``}${t||``}`.trim()||void 0}function xM(e,t){if(!e&&!t)return;let{reasoningDelta:n,...r}=e||{};return{...r,...t?{reasoning:t}:{}}}function SM(e){let{agentId:t,initialMessages:n=[],historyKey:r,loadHistory:i=!0,onError:a,enableWebSocket:o=!0,enableSSE:s=!0,enableFallback:c=!0,llmProvider:l}=e,[u,d]=(0,X.useState)(gO(n)),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(`disconnected`),[v,y]=(0,X.useState)(null),b=(0,X.useRef)(n);(0,X.useEffect)(()=>{b.current=n});let x=`${t}${String(i)}${r??``}`,[S,C]=(0,X.useState)(x);S!==x&&(C(x),(!t||!i)&&d(gO(n))),(0,X.useEffect)(()=>{let e=!1;if(!(!t||!i))return $D(t).then(t=>{e||d(gO(t.messages))}).catch(()=>{e||d(gO(b.current))}),()=>{e=!0}},[t,i,r]);let w=(0,X.useRef)(null),T=(0,X.useRef)(null),{isConnected:E,startStreamingChat:D}=vM({agentId:o?t:void 0,onMessage:j,onComplete:M,onError:N}),O=o&&E,[k,A]=(0,X.useState)(!1);k!==O&&(A(O),_(O?`websocket`:e=>e===`websocket`?`disconnected`:e));function j(e){e.messageId===T.current&&(console.log(`Processing WebSocket chunk:`,{type:e.type,content:e.content,delta:e.delta}),e.type===`content`||e.type===`chunk`?h(t=>t?{...t,content:t.content+(e.delta||e.content||``),isComplete:!1,metadata:t.metadata}:{role:`assistant`,content:e.delta||e.content||``,timestamp:new Date().toISOString(),isComplete:!1}):e.type===`thinking`?h(t=>{let n=bM(t?.metadata?.reasoning,e.delta);return t?{...t,metadata:{...t.metadata||{},...n?{reasoning:n}:{}}}:{role:`assistant`,content:``,timestamp:new Date().toISOString(),isComplete:!1,metadata:n?{reasoning:n}:void 0}}):(e.type===`complete`||e.type===`done`)&&h(e=>{if(e){let t={...e,isComplete:!0};return d(e=>[...e,t]),p(!1),T.current=null,null}return null}))}function M(e,t,n){if(t===T.current){let e=Array.isArray(n)?[...n].reverse().find(e=>e?.role===`assistant`):null,t=yM(e),r=VD(e);h(e=>{if(e){let n={...e,content:t||e.content,isComplete:!0,metadata:{...e.metadata||{},...r||{}}};d(e=>[...e,n])}else t&&d(e=>[...e,{role:`assistant`,content:t,timestamp:new Date().toISOString(),isComplete:!0,metadata:r}]);return null}),p(!1),T.current=null}}function N(e){e.messageId===T.current&&(console.error(`WebSocket streaming error:`,e),y(e.error),p(!1),T.current=null,a&&a(Error(e.error)))}let P=(0,X.useCallback)(async(e,n={})=>{if(f)throw Error(`Cannot send message while streaming`);y(null);let r={role:`user`,content:e||(n.images?.length?`[${n.images.length} image${n.images.length===1?``:`s`} attached]`:``),timestamp:new Date().toISOString(),isComplete:!0};d(e=>[...e,r]),p(!0);let i={message:e,images:n.images,context:u.slice(-10),mcpContext:n.mcpContext??!0,maxTokens:n.maxTokens,temperature:n.temperature},m=Array.isArray(n.images)&&n.images.length>0,g=o&&E&&l!==`ollama`&&!m,v=s;if(l===`ollama`&&console.log(`🦙 Ollama detected: Using SSE streaming (WebSocket not supported by Ollama)`),g)try{console.log(`🔌 Attempting WebSocket streaming for ${l||`unknown`} provider...`);let e=D(t,i);T.current=e,_(`websocket`);return}catch(e){console.warn(`WebSocket streaming failed for ${l||`unknown`}, falling back to SSE:`,e)}if(v){let e=!1;try{console.log(`📡 ${l===`ollama`?`Using`:`Attempting`} SSE streaming for ${l||`unknown`} provider...`),_(`sse`),w.current=new AbortController;let r=``;await mO(t,i.message,{onStart:()=>{e=!0},onMessage:(e,t,n)=>{r+=e;let i=typeof n?.reasoningDelta==`string`?n.reasoningDelta:``;if(h(e=>{let a=n?.reasoning||bM(e?.metadata?.reasoning,i);return{role:`assistant`,content:r,timestamp:e?.timestamp||new Date().toISOString(),isComplete:t,metadata:xM({...e?.metadata||{},...n},a)}}),t){let e=n?.reasoning;d(t=>[...t,{role:`assistant`,content:r,timestamp:new Date().toISOString(),isComplete:!0,metadata:xM(n,e)}]),h(null),p(!1)}},onError:e=>{console.error(`SSE streaming error:`,e),y(e.message),p(!1),a&&a(e)},context:u.slice(-10).map(e=>({role:e.role,content:e.content,timestamp:e.timestamp,metadata:e.metadata})),images:n.images,mcpContext:n.mcpContext??!0,maxTokens:n.maxTokens,temperature:n.temperature});return}catch(t){if(e){console.warn(`SSE stream failed after server accepted prompt for ${l||`unknown`}; refusing REST fallback to avoid duplicate prompt.`);return}console.warn(`SSE streaming failed for ${l||`unknown`}, falling back to REST:`,t)}}if(c)try{console.log(`⚙️ Using REST API fallback for ${l||`unknown`} provider...`),_(`rest`);let r=await hO(t,{message:e,images:n.images,context:u.slice(-10).map(e=>({role:e.role,content:e.content,timestamp:e.timestamp,metadata:e.metadata})),mcpContext:n.mcpContext??!0,maxTokens:n.maxTokens,temperature:n.temperature}),i={role:`assistant`,content:r.content,timestamp:new Date().toISOString(),isComplete:!0,metadata:r.metadata};d(e=>[...e,i]),p(!1)}catch(e){console.error(`All chat methods failed:`,e);let t=e instanceof Error?e.message:`Failed to send message`;y(t),p(!1),a&&a(e instanceof Error?e:Error(t))}else y(`All streaming methods failed and fallback is disabled`),p(!1)},[t,u,f,E,D,o,s,c,l,a]),ee=(0,X.useCallback)(()=>{d([]),h(null),y(null)},[]),F=(0,X.useCallback)(()=>{w.current&&=(w.current.abort(),null),T.current=null,p(!1),h(null)},[]);return(0,X.useEffect)(()=>()=>{w.current&&w.current.abort()},[]),{messages:u,isStreaming:f,currentStreamingMessage:m,connectionStatus:g,error:v,sendMessage:P,clearMessages:ee,stopStreaming:F,allMessages:m?[...u,m]:u,isWebSocketConnected:g===`websocket`,isUsingSSE:g===`sse`,isUsingREST:g===`rest`}}function CM(e){let{sessions:t,create:n}=_M(e),r=(t?.sessions.length??0)>0;return{hasSession:r,ensureSession:async()=>r?null:n({mode:`persistent`})}}async function wM(e){let t=await new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let[,e=``]=(typeof r.result==`string`?r.result:``).split(`,`,2);t(e)},r.onerror=()=>n(r.error||Error(`Failed to read image`)),r.readAsDataURL(e)});return{id:`${e.name}-${e.size}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:`image`,data:t,mimeType:e.type||`image/png`,name:e.name}}function TM(e){return String(e||``).trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)}function EM({agentId:e,routeAgentId:t,initialMessages:n,llmProvider:r,sessionKey:i}){let{showToast:a}=wo(),{hasSession:o,ensureSession:s}=CM(e),c=ft(),l=(0,X.useRef)(null),u=(0,X.useRef)(null),[d,f]=(0,X.useState)(``),[p,m]=(0,X.useState)([]),{allMessages:h,isStreaming:g,currentStreamingMessage:_,connectionStatus:v,error:y,sendMessage:b,clearMessages:x,stopStreaming:S}=SM({agentId:e,initialMessages:n,historyKey:i,loadHistory:!1,llmProvider:r,enableWebSocket:!1,onError:e=>{a({title:`Chat Error`,description:e.message,variant:`destructive`})}});return(0,X.useEffect)(()=>{l.current?.scrollIntoView({behavior:`smooth`})},[h,_]),(0,X.useEffect)(()=>{g||u.current?.focus()},[g,i]),(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col rounded-lg border`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between border-b px-4 py-3`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Chat`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Current session conversation`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`span`,{children:v}),h.length>0&&(0,Z.jsx)(`button`,{type:`button`,onClick:x,disabled:g,className:`text-destructive hover:underline disabled:opacity-50`,children:`Clear visible chat`})]})]}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4 space-y-4`,children:[h.length===0?(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center text-center text-muted-foreground`,children:(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(Ea,{className:`mx-auto mb-4 h-10 w-10 opacity-40`}),(0,Z.jsx)(`p`,{className:`text-sm`,children:o?`No messages yet.`:`No session yet.`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs`,children:o?`Send a message to start the conversation.`:`Type a message to auto-create a session, or pick one in the Sessions panel.`})]})}):h.map((e,t)=>(0,Z.jsx)(hM,{message:e,isStreaming:g&&e===_,connectionStatus:v},`${e.timestamp}-${t}`)),y&&(0,Z.jsx)(`div`,{className:`rounded-lg bg-destructive/10 p-3 text-sm text-destructive`,children:y}),(0,Z.jsx)(`div`,{ref:l})]}),(0,Z.jsxs)(`div`,{className:`border-t p-4`,children:[p.length>0&&(0,Z.jsx)(`div`,{className:`mb-3 flex flex-wrap gap-2`,children:p.map(e=>(0,Z.jsxs)(`div`,{className:`group relative overflow-hidden rounded-md border bg-muted/20`,children:[(0,Z.jsx)(`img`,{src:`data:${e.mimeType};base64,${e.data}`,alt:e.name||`Pasted image`,className:`h-16 w-16 object-cover`}),(0,Z.jsx)(`div`,{className:`max-w-16 truncate px-2 py-1 text-[10px] text-muted-foreground`,children:e.name||e.mimeType}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>m(t=>t.filter(t=>t.id!==e.id)),className:`absolute right-1 top-1 flex h-5 w-5 items-center justify-center rounded-full bg-background/90 text-muted-foreground hover:text-foreground`,title:`Remove image`,children:(0,Z.jsx)(vr,{className:`h-3 w-3`})})]},e.id))}),(0,Z.jsxs)(`form`,{onSubmit:async e=>{e.preventDefault();let n=d.trim();if(!(!n&&p.length===0)){f(``);try{let e=await s();e?.current.sessionId&&c(`/agents/${encodeURIComponent(t)}/${encodeURIComponent(e.current.sessionId)}`,{replace:!0}),await b(n,{images:p.map(({id:e,...t})=>t)}),m([])}catch(e){a({title:`Chat Error`,description:e instanceof Error?e.message:`Failed to send message`,variant:`destructive`})}}},className:`flex gap-2`,children:[(0,Z.jsx)(`textarea`,{ref:u,value:d,onChange:e=>f(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),e.currentTarget.form?.requestSubmit())},onPaste:async e=>{let t=Array.from(e.clipboardData.items).filter(e=>e.kind===`file`&&e.type.startsWith(`image/`)).map(e=>e.getAsFile()).filter(e=>!!e);if(t.length!==0)try{let e=await Promise.all(t.map(wM));m(t=>[...t,...e])}catch(e){a({title:`Paste Error`,description:e instanceof Error?e.message:`Failed to read pasted image`,variant:`destructive`})}},placeholder:g?`Streaming in progress...`:o?`Type a message...`:`Type to start a new session…`,disabled:g,rows:2,className:`flex min-h-10 flex-1 resize-y rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50`}),g?(0,Z.jsx)(Y,{type:`button`,variant:`outline`,onClick:S,children:`Stop`}):(0,Z.jsx)(Y,{type:`submit`,disabled:!d.trim()&&p.length===0,children:`Send`})]}),(0,Z.jsxs)(`div`,{className:`mt-2 flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(zn,{className:`h-3.5 w-3.5`}),`Paste image files from clipboard directly into the input.`]})]})]})}function DM(){let{agentId:e,sessionId:t}=yt(),n=vn(),r=ft(),{showToast:i}=wo(),{selectEntity:a,goBack:o}=qC(),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(!0),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(!1),y=(0,X.useRef)(null),{current:b,sessions:x,refresh:S,select:C}=_M(e||``),w=(0,X.useMemo)(()=>x?.sessions?x.currentSessionId?x.sessions.find(e=>e.id===x.currentSessionId)||null:x.currentSessionPath?x.sessions.find(e=>e.path===x.currentSessionPath)||null:x.sessions.find(e=>e.isCurrent)||null:null,[x]),T=[b?.mode||`persistent`,b?.sessionId||b?.sessionFile||`initial`].join(`:`);return(0,X.useEffect)(()=>{e&&(async()=>{u(!0);try{let i=await QD(e);a(i.id),c(i);let o=i.name||i.id;if(o&&decodeURIComponent(e)!==o){let e=n.pathname.endsWith(`/settings`)?`/agents/${encodeURIComponent(o)}/settings`:t?`/agents/${encodeURIComponent(o)}/${encodeURIComponent(t)}`:`/agents/${encodeURIComponent(o)}`;r(e,{replace:!0})}await S(),g(null)}catch(e){let t=e instanceof Error?e.message:`Failed to load agent`;g(t),i({title:`Error`,description:t,variant:`destructive`})}finally{u(!1)}})()},[e,t,n.pathname,r,S,a,i]),(0,X.useEffect)(()=>{if(!e||!t||!x)return;let n=decodeURIComponent(t),r=TM(n),a=x.sessions.find(e=>e.id===n||e.slug===n||TM(e.name)===r),o=!!(a&&(x.currentSessionId===a.id||x.currentSessionPath===a.path||b?.sessionId===a.id||b?.sessionFile===a.path)),s=b?.sessionId===n||x.currentSessionId===n;if(b?.mode===`persistent`&&o){y.current=null;return}if(!a){b?.mode===`persistent`&&s&&(y.current=null);return}y.current!==a.id&&(y.current=a.id,C({mode:`persistent`,sessionId:a.id}).catch(e=>{i({title:`Session Error`,description:e instanceof Error?e.message:`Failed to select session`,variant:`destructive`})}).finally(()=>{y.current===a.id&&(y.current=null)}))},[e,t,x,b?.mode,b?.sessionId,b?.sessionFile,C,i]),(0,X.useEffect)(()=>{if(!e)return;let t=async()=>{try{let t=await pO(e);c(e=>e?{...e,isActive:t.isActive,status:t.status,lastAccessed:t.lastAccessed}:null)}catch{}};t();let n=setInterval(t,5e3);return()=>clearInterval(n)},[e]),l?(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,Z.jsxs)(`div`,{className:`text-center text-muted-foreground`,children:[(0,Z.jsx)(Nr,{className:`mx-auto mb-3 h-8 w-8 animate-pulse`}),(0,Z.jsx)(`p`,{children:`Loading agent...`})]})}):!s||h?(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,Z.jsxs)(`div`,{className:`text-center text-destructive`,children:[(0,Z.jsx)(Nr,{className:`mx-auto mb-3 h-8 w-8`}),(0,Z.jsx)(`p`,{children:h||`Agent not found`})]})}):(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Z.jsx)(lw,{title:`Back to previous view`,onBack:o}),(0,Z.jsx)(`span`,{className:`h-3 w-3 shrink-0 rounded-full`,style:{backgroundColor:s.color||`#9ca3af`}}),(0,Z.jsx)(`h1`,{className:`truncate text-xl font-semibold`,children:s.label||s.name}),(0,Z.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,children:s.status})]}),(0,Z.jsx)(`p`,{className:`mt-1 truncate text-sm text-muted-foreground`,children:s.description||`${s.llmProvider} / ${s.model}`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[s.isActive?(0,Z.jsxs)(Y,{variant:`outline`,onClick:async()=>{if(e){m(!0);try{let t=await fO(e);c(t),i({title:`Stopped`,description:`${t.label||t.name} is inactive`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to stop agent`,variant:`destructive`})}finally{m(!1)}}},disabled:p,children:[(0,Z.jsx)(Sa,{className:`mr-2 h-4 w-4`}),p?`Stopping...`:`Stop`]}):(0,Z.jsxs)(Y,{onClick:async()=>{if(e){f(!0);try{let t=await dO(e);c(t),i({title:`Started`,description:`${t.label||t.name} is active`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to start agent`,variant:`destructive`})}finally{f(!1)}}},disabled:d,children:[(0,Z.jsx)(Ar,{className:`mr-2 h-4 w-4`}),d?`Starting...`:`Start`]}),(0,Z.jsxs)(Y,{variant:`outline`,onClick:()=>{a(s.id),r(`/agents/${encodeURIComponent(s.name||s.id)}/settings/identity`)},children:[(0,Z.jsx)(Wi,{className:`mr-2 h-4 w-4`}),`Settings`]}),(0,Z.jsx)(cw,{className:`h-9 w-9`})]})]}),(0,Z.jsxs)(`div`,{className:`grid min-h-0 flex-1 grid-cols-1 gap-4 grid-rows-[minmax(0,1fr)_auto] xl:grid-rows-none xl:grid-cols-[minmax(0,1.2fr)_minmax(320px,0.8fr)]`,children:[(0,Z.jsx)(EM,{agentId:s.id,routeAgentId:s.name||s.id,initialMessages:b?.messages||[],llmProvider:s.llmProvider,sessionKey:T},T),(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-col rounded-lg border`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>v(e=>!e),"aria-expanded":_,className:K(`flex w-full items-center justify-between gap-2 px-4 py-3 text-left xl:pointer-events-none`,_?`border-b`:`xl:border-b`),children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Contextual Information`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Current session and runtime state.`})]}),(0,Z.jsx)(qr,{className:K(`h-4 w-4 shrink-0 text-muted-foreground transition-transform xl:hidden`,_&&`rotate-180`)})]}),(0,Z.jsxs)(`div`,{className:K(`space-y-4 overflow-y-auto p-4 text-sm max-xl:max-h-viewport-half`,!_&&`max-xl:hidden`),children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Mode`}),(0,Z.jsx)(`div`,{className:`mt-1`,children:b?.mode||x?.mode||`persistent`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Selected Session`}),(0,Z.jsx)(`div`,{className:`mt-1 break-all`,children:w?.name||(w?.isExperimental?`Experimental`:null)||b?.sessionId||`Default session`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Known Sessions`}),(0,Z.jsx)(`div`,{className:`mt-1`,children:x?.sessions.length||0})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Thinking Level`}),(0,Z.jsx)(`div`,{className:`mt-1`,children:b?.thinkingLevel||`high`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Model`}),(0,Z.jsx)(`div`,{className:`mt-1`,children:b?.model?.modelId||s.model||`Not set`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Session File`}),(0,Z.jsx)(`div`,{className:`mt-1 break-all text-xs text-muted-foreground`,children:b?.sessionFile||`In-memory / not persisted yet`})]}),(0,Z.jsxs)(`div`,{className:`rounded-lg border bg-muted/20 p-4 text-sm text-muted-foreground`,children:[(0,Z.jsxs)(`div`,{className:`mb-2 flex items-center gap-2 font-medium text-foreground`,children:[(0,Z.jsx)(yi,{className:`h-4 w-4`}),`Shape`]}),(0,Z.jsx)(`p`,{children:`Session selection lives in M2. Main content stays focused on the active conversation and its context.`})]})]})]})]})]})}var OM={anthropic:`claude-3-5-sonnet-20241022`,openai:`gpt-4o`,ollama:`qwen2.5-coder:latest`,"lm-studio":``,vllm:``,custom:``},kM={anthropic:`https://api.anthropic.com`,openai:`https://api.openai.com/v1`,ollama:`http://localhost:11434/v1`,"lm-studio":`http://localhost:1234/v1`,vllm:`http://localhost:8000/v1`,custom:``};function AM(e){return kM[e]||``}function jM({label:e,hint:t,children:n}){return(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`text-sm font-medium`,children:e}),t&&(0,Z.jsx)(`p`,{className:`mb-1 mt-0.5 text-xs text-muted-foreground`,children:t}),(0,Z.jsx)(`div`,{className:t?void 0:`mt-1`,children:n})]})}var MM=`w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring resize-y`,NM=`w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring`;function PM(){let{agentId:e,tab:t}=yt(),n=ft(),{showToast:r}=wo(),{selectEntity:i,goBack:a}=qC(),o=De(),s=FD(t);(0,X.useEffect)(()=>{t!==s&&e&&n(`/agents/${encodeURIComponent(e)}/settings/${s}`,{replace:!0})},[t,s,e,n]);let[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(!0),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(``),[b,x]=(0,X.useState)(``),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)(on()),[E,D]=(0,X.useState)(``),[O,k]=(0,X.useState)(``),[A,j]=(0,X.useState)(``),[M,N]=(0,X.useState)(``),[P,ee]=(0,X.useState)(`anthropic`),[F,I]=(0,X.useState)(``),[te,L]=(0,X.useState)(``),[R,ne]=(0,X.useState)(``),[re,ie]=(0,X.useState)(.7),[ae,z]=(0,X.useState)(4096),[oe,se]=(0,X.useState)(1),B=lM(P,F,te,c?.id),ce=B.models.find(e=>e.id===R),[V,le]=(0,X.useState)([]),[ue,de]=(0,X.useState)(``),[fe,pe]=(0,X.useState)(``),[me,he]=(0,X.useState)(``),[ge,_e]=(0,X.useState)(``),[ve,ye]=(0,X.useState)(!1),[be,xe]=(0,X.useState)(null),[H,Se]=(0,X.useState)(null),[Ce,U]=(0,X.useState)(null),[W,we]=(0,X.useState)(!1),[Te,Ee]=(0,X.useState)(null),[Oe,ke]=(0,X.useState)(`context`),[Ae,je]=(0,X.useState)(``),[Me,Ne]=(0,X.useState)(`/`),[Pe,Fe]=(0,X.useState)(``),[Ie,Le]=(0,X.useState)(!0),[Re,ze]=(0,X.useState)(!1),[Be,Ve]=(0,X.useState)([]),[He,Ue]=(0,X.useState)([]),[We,Ge]=(0,X.useState)(null),[Ke,G]=(0,X.useState)(`{}`),[qe,Je]=(0,X.useState)(null),[Ye,Xe]=(0,X.useState)(e);Ye!==e&&(Xe(e),d(!0),l(null)),(0,X.useEffect)(()=>{if(!e)return;let t=!1;return QD(e).then(async e=>{if(t)return;let n=e.config?.identity||{};l(e),i(e.id),y(e.name||``),x(e.label||``),C(e.description||``),T(e.color||on()),D(n.role||``),k(n.identity||``),j(n.instructions||``),N(e.config?.prompts?.system||``),ee(e.llmProvider||`anthropic`),I(e.config?.apiKey||``),L(e.config?.baseUrl||AM(e.llmProvider)),ne(e.model||OM[e.llmProvider]||``);let r=e.config?.connectors?.[e.llmProvider];r&&(ie(r.temperature??.7),z(r.maxTokens??4096),se(r.topP??1)),G(JSON.stringify(e.config?.tools??{},null,2)),Je(null),p(null);try{le(await aO(e.id))}catch{le([])}}).catch(e=>{t||p(e instanceof Error?e.message:`Failed to load agent`)}).finally(()=>{t||d(!1)}),()=>{t=!0}},[e,i]),(0,X.useEffect)(()=>{if(s!==`access`&&s!==`tools`||!c?.id)return;let e=c.id,t=!1;return Promise.all([KD(c.id).catch(()=>null),Uo().catch(()=>[]),ml().catch(()=>[]),XD(c.id).catch(()=>null)]).then(([n,r,i,a])=>{t||(Se(n),Ve(r),Ue(i),Ge(a?a.tools:[]),n&&(ke(n.binding.type),je(n.binding.workspace||``),Ne(n.binding.path||`/`),Fe(n.binding.context||``),Le(n.permissions.includes(`read`)),ze(n.permissions.includes(`write`))),U(e))}),()=>{t=!0}},[s,c?.id]);let Ze=()=>{let e=sM(E,O,A),t;try{let e=JSON.parse(Ke);e&&typeof e==`object`&&!Array.isArray(e)&&(t=e)}catch{}return{...t===void 0?{}:{tools:t},name:v.trim(),label:b.trim(),description:S.trim()||void 0,color:w,llmProvider:P,model:R,apiKey:F.trim()||(P===c?.llmProvider?void 0:``),baseUrl:te||void 0,config:{type:P,model:R,identity:{role:E.trim()||void 0,identity:O.trim()||void 0,instructions:A.trim()||void 0},prompts:M.trim()||e?{system:M.trim()||e}:void 0,connectors:{[P]:{...P===`anthropic`?{}:{temperature:re},maxTokens:ae,topP:oe}}}}},Qe=async e=>{if(e.preventDefault(),c){h(!0);try{let e=await lO(c.id,Ze());l(e),window.dispatchEvent(new CustomEvent(`agents:refresh`)),r({title:`Saved`,description:`Agent updated`}),e.name&&e.name!==c.name&&n(`/agents/${encodeURIComponent(e.name)}/settings/${s}`,{replace:!0})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{h(!1)}}},$e=async()=>{if(c&&window.confirm(`Delete agent "${c.label||c.name}"? This cannot be undone.`)){_(!0);try{await uO(c.id),window.dispatchEvent(new CustomEvent(`agents:refresh`)),r({title:`Deleted`,description:`Agent removed`}),n(`/agents`)}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Delete failed`,variant:`destructive`})}finally{_(!1)}}},et=()=>{de(``),pe(``),he(``),_e(``)},tt=async()=>{if(!(!c||!ge.trim()&&!me.trim())){ye(!0);try{let e=await oO(c.id,ge.trim()?{source:ge.trim()}:{name:ue,description:fe,content:me});le(e),et(),window.dispatchEvent(new CustomEvent(`agents:refresh`)),r({title:`Installed`,description:`Skill saved`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Skill install failed`,variant:`destructive`})}finally{ye(!1)}}},nt=async e=>{if(c){xe(e);try{let t=await sO(c.id,e);le(t),(ue===e||ge===e)&&et(),window.dispatchEvent(new CustomEvent(`agents:refresh`)),r({title:`Removed`,description:`Skill "${e}" removed`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Skill remove failed`,variant:`destructive`})}finally{xe(null)}}},rt=()=>Oe===`global`?{type:`global`}:Oe===`context`?Pe?{type:`context`,context:Pe}:null:Ae?Oe===`path`?{type:`path`,workspace:Ae,path:Me.trim()||`/`}:{type:`workspace`,workspace:Ae}:null,it=async()=>{if(!c||W)return;let e=rt(),t=[];if(Ie&&t.push(`read`),Re&&t.push(`write`),!e||t.length===0){r({title:`Invalid binding`,description:`Pick a scope target and at least one permission`,variant:`destructive`});return}if(!(e.type===`global`&&!window.confirm(`Global scope lets this agent ${Re?`read and write`:`read`} ALL your workspaces. Continue?`))){we(!0);try{let n=await qD(c.id,{binding:e,permissions:t});Se(n.access),Ee(n.token),r({title:`Bound`,description:`Access bound — copy the token now, it is not shown again`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Bind failed`,variant:`destructive`})}finally{we(!1)}}},at=async()=>{if(!(!c||W)){we(!0);try{let e=await JD(c.id);Se(e.access),Ee(e.token),r({title:`Rotated`,description:`New token minted — the previous one no longer works`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Rotate failed`,variant:`destructive`})}finally{we(!1)}}},ot=async()=>{if(!(!c||W)&&window.confirm(`Revoke this agent's canvas access? Its token stops working immediately.`)){we(!0);try{await YD(c.id),Se(null),Ee(null),r({title:`Revoked`,description:`Agent access removed`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Revoke failed`,variant:`destructive`})}finally{we(!1)}}},st=e=>{if(e.type===`global`)return`Global — all workspaces`;if(e.type===`context`){let t=He.find(t=>t.id===e.context);return`Context ${t?`${t.id} (${t.url})`:e.context} — follows the context live`}let t=e.workspaceName||e.workspace;return e.type===`path`?`Workspace ${t}, path ${e.path||`/`}`:`Workspace ${t} (whole tree)`};if(u)return(0,Z.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Loading...`});if(!c||f)return(0,Z.jsx)(`div`,{className:`p-6 text-sm text-destructive`,children:f||`Agent not found`});let ct=PD.find(e=>e.id===s),lt=encodeURIComponent(c.name||c.id),ut=s===`identity`||s===`provider`||s===`models`||s===`tools`;return(0,Z.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,Z.jsxs)(`div`,{className:`mx-auto max-w-5xl p-6 pb-12 max-md:px-4 max-md:pb-rail-stack`,children:[(0,Z.jsx)(sw,{compact:!0,className:`mb-6 border-b pb-4`,title:`${ct.label} - ${c.label||c.name}`,description:ct.description,backTo:`/agents/${lt}`,onBack:o?a:void 0}),(0,Z.jsxs)(`form`,{onSubmit:Qe,className:`space-y-6`,children:[s===`identity`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsx)(jM,{label:`Name`,hint:`ID: ${c.id}`,children:(0,Z.jsx)(q,{value:v,onChange:e=>y(e.target.value),placeholder:`lucy`})}),(0,Z.jsx)(jM,{label:`Label`,children:(0,Z.jsx)(q,{value:b,onChange:e=>x(e.target.value),placeholder:`Display name`})})]}),(0,Z.jsx)(jM,{label:`Description`,children:(0,Z.jsx)(q,{value:S,onChange:e=>C(e.target.value),placeholder:`Short description`})}),(0,Z.jsx)(jM,{label:`Color`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(q,{type:`color`,value:w,onChange:e=>T(e.target.value),className:`h-10 w-16 p-1`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>T(on()),children:`Randomize`})]})})]}),(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Persona`}),(0,Z.jsx)(jM,{label:`Role`,children:(0,Z.jsx)(q,{value:E,onChange:e=>D(e.target.value),placeholder:`e.g. Software Engineer`})}),(0,Z.jsx)(jM,{label:`Identity`,children:(0,Z.jsx)(`textarea`,{value:O,onChange:e=>k(e.target.value),placeholder:`Who this agent is…`,className:`${MM} min-h-[80px]`})}),(0,Z.jsx)(jM,{label:`Instructions`,children:(0,Z.jsx)(`textarea`,{value:A,onChange:e=>j(e.target.value),placeholder:`Behavioral instructions…`,className:`${MM} min-h-[80px]`})}),(0,Z.jsx)(jM,{label:`System Prompt`,hint:`Compiled from Role + Identity + Instructions. Override manually.`,children:(0,Z.jsx)(`textarea`,{value:M,onChange:e=>N(e.target.value),placeholder:`System prompt sent to the LLM…`,className:`${MM} min-h-[140px] font-mono text-xs`})})]}),(0,Z.jsxs)(`section`,{className:`rounded-lg border border-destructive/30 p-4`,children:[(0,Z.jsx)(`h2`,{className:`mb-3 text-sm font-semibold text-destructive`,children:`Danger Zone`}),(0,Z.jsxs)(Y,{type:`button`,variant:`destructive`,disabled:g,onClick:$e,children:[(0,Z.jsx)(Qr,{className:`mr-2 h-4 w-4`}),g?`Deleting...`:`Delete Agent`]})]})]}),s===`provider`&&(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(jM,{label:`Provider`,children:(0,Z.jsxs)(`select`,{value:P,onChange:e=>{let t=e.target.value;ee(t),I(``),ne(OM[t]||``),L(AM(t))},className:`w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring`,children:[(0,Z.jsx)(`option`,{value:`anthropic`,children:`Anthropic Claude`}),(0,Z.jsx)(`option`,{value:`openai`,children:`OpenAI GPT`}),(0,Z.jsx)(`option`,{value:`ollama`,children:`Ollama (Local)`}),(0,Z.jsx)(`option`,{value:`lm-studio`,children:`LM Studio (Local)`}),(0,Z.jsx)(`option`,{value:`vllm`,children:`vLLM (Local)`}),(0,Z.jsx)(`option`,{value:`custom`,children:`Custom`})]})}),(0,Z.jsx)(jM,{label:`API Key`,hint:[`ollama`,`lm-studio`,`vllm`].includes(P)?`Any value works for local providers.`:void 0,children:(0,Z.jsx)(q,{type:`password`,value:F,onChange:e=>I(e.target.value),placeholder:P===`ollama`?`ollama`:P===`lm-studio`?`lm-studio`:`sk-…`})}),(0,Z.jsx)(jM,{label:`Host / Base URL`,children:(0,Z.jsx)(q,{value:te,onChange:e=>L(e.target.value),placeholder:AM(P)||`https://api.example.com`})})]}),s===`models`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Main Model`}),(0,Z.jsx)(jM,{label:`Model`,children:(0,Z.jsx)(cM,{value:R,onChange:(e,t)=>{ne(e),t?.maxTokens&&z(t.maxTokens)},...B})}),(0,Z.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-3`,children:[P!==`anthropic`&&(0,Z.jsx)(jM,{label:`Temperature`,children:(0,Z.jsx)(q,{type:`number`,min:0,max:2,step:.1,value:re,onChange:e=>ie(Number.isNaN(e.target.valueAsNumber)?.7:e.target.valueAsNumber)})}),(0,Z.jsx)(jM,{label:`Max Output Tokens`,children:(0,Z.jsx)(q,{type:`number`,min:1,max:ce?.maxTokens,value:ae,onChange:e=>z(parseInt(e.target.value)||4096)})}),(0,Z.jsx)(jM,{label:`Top P`,children:(0,Z.jsx)(q,{type:`number`,min:0,max:1,step:.1,value:oe,onChange:e=>se(Number.isNaN(e.target.valueAsNumber)?1:e.target.valueAsNumber)})})]})]}),[`Governance`,`Memory Management`,`Subagent / Tool Use`].map(e=>(0,Z.jsxs)(`section`,{className:`rounded-lg border border-dashed p-4`,children:[(0,Z.jsxs)(`h2`,{className:`text-sm font-semibold text-muted-foreground`,children:[e,` Model`]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Coming soon`})]},e))]}),s===`tools`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Runtime Tools`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Injected at start (pi defineTool): coding tools plus canvas tools scoped by the token binding (Access / ACL). Definitions live in the runtime — read-only here until the agent-runtime workspace lands.`})]}),We===null?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Loading…`}):We.length===0?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`No tools resolved.`}):(0,Z.jsx)(`div`,{className:`space-y-1.5`,children:We.map(e=>(0,Z.jsxs)(`details`,{className:`rounded-md border px-3 py-2`,children:[(0,Z.jsxs)(`summary`,{className:`cursor-pointer text-sm`,children:[(0,Z.jsx)(`code`,{className:`font-mono text-xs font-medium`,children:e.name}),(0,Z.jsx)(`span`,{className:`ml-2 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,children:e.source})]}),e.description&&(0,Z.jsx)(`p`,{className:`mt-2 whitespace-pre-wrap text-xs text-muted-foreground`,children:e.description}),e.parameters!=null&&(0,Z.jsx)(`pre`,{className:`mt-2 overflow-x-auto rounded bg-muted p-2 font-mono text-[11px]`,children:JSON.stringify(e.parameters,null,2)})]},e.name))}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:H?st(H.binding):`Unbound — no canvas tools are injected. Bind under Access / ACL.`})]}),(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Tools Config`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`config.tools JSON, merged server-side — e.g. {"canvas": {"enabled": false}} gates the canvas tools. Saved with Save Changes.`})]}),(0,Z.jsx)(`textarea`,{value:Ke,onChange:e=>{G(e.target.value);try{JSON.parse(e.target.value),Je(null)}catch(e){Je(e instanceof Error?e.message:`Invalid JSON`)}},className:`${MM} min-h-[120px] font-mono text-xs`}),qe&&(0,Z.jsxs)(`p`,{className:`text-xs text-destructive`,children:[`Invalid JSON (not saved): `,qe]})]}),(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Skills`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Installed skills are saved immediately, independent of Save Changes.`})]}),V.length===0?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`No skills installed.`}):V.map(e=>(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3 rounded-md border p-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-medium`,children:e.name}),(0,Z.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:e.package?e.source:e.description||`No description`})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{de(e.name),pe(e.description||``),he(e.content||``),_e(e.source||``)},children:`Edit`}),(0,Z.jsx)(Y,{type:`button`,variant:`destructive`,size:`sm`,disabled:be===(e.source||e.name),onClick:()=>nt(e.source||e.name),children:be===(e.source||e.name)?`Removing…`:`Remove`})]})]},e.name)),(0,Z.jsxs)(`div`,{className:`space-y-4 rounded-md border p-4`,children:[(0,Z.jsx)(jM,{label:`Package Source`,hint:`Use this for whole pi packages. Leave empty to save inline SKILL.md content.`,children:(0,Z.jsx)(q,{value:ge,onChange:e=>_e(e.target.value),placeholder:`npm:@foo/pi-tools or git:github.com/badlogic/pi-doom`})}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsx)(jM,{label:`Name`,children:(0,Z.jsx)(q,{value:ue,onChange:e=>de(e.target.value),placeholder:`skill-name, or read from frontmatter`,disabled:!!ge.trim()})}),(0,Z.jsx)(jM,{label:`Description`,children:(0,Z.jsx)(q,{value:fe,onChange:e=>pe(e.target.value),placeholder:`What this skill helps with`,disabled:!!ge.trim()})})]}),(0,Z.jsx)(jM,{label:`SKILL.md Content`,children:(0,Z.jsx)(`textarea`,{value:me,onChange:e=>he(e.target.value),placeholder:`# Skill instructions…`,disabled:!!ge.trim(),className:`${MM} min-h-[160px] font-mono text-xs`})}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(Y,{type:`button`,disabled:ve||!ge.trim()&&!me.trim(),onClick:tt,children:ve?`Saving…`:`Install / Update Skill`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,onClick:et,children:`Clear`})]})]})]}),(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`MCP Servers`}),(c.config?.mcp?.servers||[]).length===0?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`No MCP servers configured.`}):(c.config?.mcp?.servers||[]).map((e,t)=>(0,Z.jsxs)(`div`,{className:`rounded-md border p-3`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium`,children:e.name}),(0,Z.jsxs)(`div`,{className:`font-mono text-xs text-muted-foreground`,children:[e.command,` `,(e.args||[]).join(` `)]})]},t))]})]}),s===`access`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Canvas Access`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The agent talks to canvas through its own scoped token; the server clamps every request to the binding. Bind, rotate and revoke apply immediately.`})]}),Ce===c.id?H?(0,Z.jsxs)(`div`,{className:`space-y-2 rounded-md border p-3`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium`,children:st(H.binding)}),(0,Z.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[`Permissions: `,H.permissions.join(`, `)||`none`,H.boundAt?` · bound ${new Date(H.boundAt).toLocaleString()}`:``,H.rotatedAt?` · token rotated ${new Date(H.rotatedAt).toLocaleString()}`:``]}),(0,Z.jsxs)(`div`,{className:`flex gap-2 pt-1`,children:[(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:W,onClick:at,children:`Rotate Token`}),(0,Z.jsx)(Y,{type:`button`,variant:`destructive`,size:`sm`,disabled:W,onClick:ot,children:`Revoke Access`})]})]}):(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Unbound — this agent has no canvas access.`}):(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Loading…`}),Te&&(0,Z.jsxs)(`div`,{className:`space-y-2 rounded-md border border-warning/50 bg-warning/10 p-3`,children:[(0,Z.jsx)(`div`,{className:`text-xs font-medium`,children:`Agent token — shown once, store it now`}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`code`,{className:`flex-1 truncate rounded bg-background px-2 py-1 font-mono text-xs`,children:Te}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>navigator.clipboard?.writeText(Te),children:`Copy`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>Ee(null),children:`Dismiss`})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`In-process agents receive it automatically (canvas.env); external runtimes (agentd) take it as CANVAS_TOKEN.`})]})]}),(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:H?`Rebind`:`Bind`}),(0,Z.jsx)(jM,{label:`Scope`,hint:`Context bindings follow the context live; global spans all workspaces.`,children:(0,Z.jsxs)(`select`,{value:Oe,onChange:e=>ke(e.target.value),className:NM,children:[(0,Z.jsx)(`option`,{value:`context`,children:`Context (follows live)`}),(0,Z.jsx)(`option`,{value:`workspace`,children:`Workspace`}),(0,Z.jsx)(`option`,{value:`path`,children:`Workspace path`}),(0,Z.jsx)(`option`,{value:`global`,children:`Global (all workspaces)`})]})}),Oe===`context`&&(0,Z.jsx)(jM,{label:`Context`,children:(0,Z.jsxs)(`select`,{value:Pe,onChange:e=>Fe(e.target.value),className:NM,children:[(0,Z.jsx)(`option`,{value:``,children:`Select a context…`}),He.map(e=>(0,Z.jsxs)(`option`,{value:e.id,children:[e.id,` — `,e.url]},e.id))]})}),(Oe===`workspace`||Oe===`path`)&&(0,Z.jsx)(jM,{label:`Workspace`,children:(0,Z.jsxs)(`select`,{value:Ae,onChange:e=>je(e.target.value),className:NM,children:[(0,Z.jsx)(`option`,{value:``,children:`Select a workspace…`}),Be.map(e=>(0,Z.jsx)(`option`,{value:e.name||e.id,children:e.label||e.name},e.id))]})}),Oe===`path`&&(0,Z.jsx)(jM,{label:`Base path`,hint:`The agent is clamped to this subtree.`,children:(0,Z.jsx)(q,{value:Me,onChange:e=>Ne(e.target.value),placeholder:`/work/projects/foo`})}),(0,Z.jsx)(jM,{label:`Permissions`,children:(0,Z.jsxs)(`div`,{className:`flex gap-4 text-sm`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:Ie,onChange:e=>Le(e.target.checked)}),` read`]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:Re,onChange:e=>ze(e.target.checked)}),` write`]})]})}),(0,Z.jsx)(Y,{type:`button`,disabled:W,onClick:it,children:W?`Working…`:H?`Rebind & Mint Token`:`Bind & Mint Token`})]})]}),s===`memory`&&(0,Z.jsxs)(`section`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold text-muted-foreground`,children:`Memory Engine`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Loop-based memory management. Settings coming soon.`})]}),s===`integrations`&&(0,Z.jsxs)(`section`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold text-muted-foreground`,children:`Integrations`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`IMAP, chat, SQL and REST API accounts. Coming soon.`})]}),ut&&(0,Z.jsx)(Y,{type:`submit`,disabled:m,children:m?`Saving…`:`Save Changes`})]})]})})}var FM=`workspace:backups`,IM=e=>`${no.workspaces}/${encodeURIComponent(e)}/db/backups`,LM=e=>J.get(IM(e)),RM=e=>J.post(IM(e),{action:`backup`}),zM=(e,t)=>J.post(IM(e),{action:`restore`,backupId:t,confirm:!0}),BM=new Map;function VM(e,t,n){let r=JSON.stringify([t,n.id]),i=BM.get(r);if(i)return i;let a=(async()=>{let r=n.action===`restore`,i=e({title:r?`Restoring workspace database`:`Backing up workspace database`,description:r?`Stopping the workspace and preserving its current database…`:`Copying and verifying all datasets…`});try{let e=n;for(;e.status===`running`;){let n=await LM(t),r=n.jobs.find(t=>t.id===e.id);if(!r)throw Error(`The server restarted. Refresh the backup list to check the result.`);e=r,window.dispatchEvent(new CustomEvent(FM,{detail:{workspace:t,status:n}})),e.status===`running`&&await new Promise(e=>setTimeout(e,1500))}if(e.status===`failed`)throw Error(e.error||`Database operation failed`);i.done({title:r?`Workspace database restored`:`Workspace backup verified`,description:r?`The workspace is stopped. Start it when you are ready; search indexes will rebuild.`:`Documents, relations and virtual tree placements are saved.`})}catch(e){throw i.fail({title:`Workspace backup needs attention`,description:e instanceof Error?e.message:String(e),variant:`destructive`}),e}})();return BM.set(r,a),a.finally(()=>BM.delete(r)).catch(()=>{}),a}var HM={startup:`Startup`,hourly:`Hourly`,manual:`Manual`,"pre-restore":`Before restore`};function UM({workspaceId:e,onRestored:t}){let{showToast:n,showProgress:r}=wo(),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(!1),f=(0,X.useRef)(!1),p=(0,X.useRef)(!1),m=(0,X.useRef)(0),h=(0,X.useCallback)(()=>{let t=++m.current;return LM(e).then(n=>{if(!(!f.current||t!==m.current)){a(n),s(null);for(let t of n.jobs.filter(e=>e.status===`running`))VM(r,e,t).catch(()=>{})}}).catch(e=>{f.current&&t===m.current&&s(e instanceof Error?e.message:String(e))})},[e,r]);(0,X.useEffect)(()=>{f.current=!0,h();let t=t=>{let n=t.detail;n.workspace===e&&a(n.status)};return window.addEventListener(FM,t),()=>{f.current=!1,window.removeEventListener(FM,t)}},[e,h]);let g=async i=>{if(!p.current){p.current=!0,d(!0);try{let n=i?await zM(e,i.id):await RM(e);f.current&&a(e=>e&&{...e,jobs:[n,...e.jobs]}),await VM(r,e,n),i&&t()}catch(e){n({title:`Database operation did not complete`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{p.current=!1,f.current&&(d(!1),h())}}},_=u||!!i?.jobs.some(e=>e.status===`running`),v=i?.jobs[0];return(0,Z.jsxs)(`div`,{className:`min-w-0 space-y-5`,children:[(0,Z.jsxs)(`section`,{className:`space-y-4 rounded border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Z.jsx)(ra,{className:`h-5 w-5 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`font-semibold`,children:`Workspace checkpoints`}),(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,className:`ml-auto`,disabled:_||!i||!!o,onClick:()=>void g(),children:[_?(0,Z.jsx)(Ti,{className:`mr-2 h-4 w-4 animate-spin`}):(0,Z.jsx)(ra,{className:`mr-2 h-4 w-4`}),`Back up now`]})]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Save a checkpoint before a bulk action. Each backup includes every document, relation and virtual tree placement in this workspace’s database.`}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-x-5 gap-y-2 text-sm`,children:[(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`strong`,{children:i?.retention.hourly??24}),` hourly backups`]}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`strong`,{children:i?.retention.startup??14}),` startup backups`]}),(0,Z.jsx)(`span`,{children:`Manual checkpoints kept`})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Hourly backups run while the workspace is active. These checkpoints cover the database only; files in storage backends and workspace settings need their own backups.`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsxs)(`h2`,{className:`text-sm font-semibold`,children:[`Verified checkpoints`,i?` · ${i.backups.length}`:``]}),(0,Z.jsx)(Y,{variant:`ghost`,size:`icon`,className:`h-8 w-8`,onClick:()=>void h(),"aria-label":`Refresh backups`,children:(0,Z.jsx)(Er,{className:`h-4 w-4`})})]}),o&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:o}),v&&(0,Z.jsx)(`p`,{role:`status`,className:`text-sm ${v.status===`failed`?`text-destructive`:`text-muted-foreground`}`,children:v.status===`running`?`Database operation in progress…`:v.status===`failed`?v.error:v.action===`restore`?`Database restored. The workspace is stopped and ready to start.`:`Backup complete and verified.`}),!i&&!o&&(0,Z.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:`Loading backups…`}),i?.backups.length===0&&(0,Z.jsx)(`p`,{className:`rounded border border-dashed p-6 text-sm text-muted-foreground`,children:`No verified checkpoints yet. Create one before your next bulk action.`}),(0,Z.jsx)(`div`,{className:`space-y-2`,children:i?.backups.map(e=>(0,Z.jsxs)(`article`,{className:`flex min-w-0 flex-wrap items-center gap-3 rounded border p-3`,children:[(0,Z.jsx)(sr,{className:`h-4 w-4 shrink-0 text-muted-foreground`,"aria-label":`Verified`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 basis-40`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:new Date(e.createdAt).toLocaleString()}),(0,Z.jsxs)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:[HM[e.kind],` · `,Ts(e.bytes),` · `,(e.datasets.documents?.count??0).toLocaleString(),` documents`]})]}),(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,disabled:_,onClick:()=>l(e),children:[(0,Z.jsx)(Vr,{className:`mr-2 h-3.5 w-3.5`}),`Restore`]})]},e.id))}),(0,Z.jsx)(vo,{open:!!c,onOpenChange:e=>{e||l(null)},children:(0,Z.jsxs)(lo,{className:`max-w-[calc(100vw-2rem)] sm:max-w-lg`,children:[(0,Z.jsxs)(_o,{children:[(0,Z.jsx)(io,{children:`Restore this workspace checkpoint?`}),(0,Z.jsxs)(ro,{children:[`The workspace will stop and its current database will be backed up first. Documents, relations and virtual tree placements will return to `,c?new Date(c.createdAt).toLocaleString():`the selected checkpoint`,`. Files in storage backends and workspace settings will stay as they are. The workspace stays stopped after restoration.`]})]}),(0,Z.jsxs)(mo,{children:[(0,Z.jsx)(go,{children:`Cancel`}),(0,Z.jsx)(po,{disabled:_,onClick:()=>{c&&g(c)},children:`Back up current & restore`})]})]})})]})}var WM={collect:`Collect unused blobs`,verify:`Verify integrity`,compact:`Compact index`},GM=e=>e.status===`queued`||e.status===`running`,KM=e=>`${no.workspaces}/${encodeURIComponent(e)}/cache/maintenance`,qM=e=>J.get(KM(e)),JM=(e,t,n)=>J.post(KM(e),{store:t,action:n,...n===`verify`?{confirm:!0}:{}});function YM(e){if(e.status===`failed`)return e.error||`Maintenance failed`;if(e.status===`queued`)return`Waiting for active storage operations…`;if(e.status===`running`)return e.action===`verify`?`Reading and checking stored content…`:`Processing the cache index…`;let t=e.result||{};return e.action===`compact`?`${(t.compactedCount||0).toLocaleString()} keys compacted`:e.action===`verify`?`${(t.verifiedContent||0).toLocaleString()} blobs verified · ${(t.badContentCount||0).toLocaleString()} corrupted blobs removed · ${Ts(t.reclaimedSize||0)} reclaimed`:`${(t.reclaimedCount||0).toLocaleString()} unused blobs removed · ${Ts(t.reclaimedSize||0)} reclaimed`}var XM=new Map,ZM=`workspace:cache-maintenance`;function QM(e,t,n){let r=JSON.stringify([t,n.id]),i=XM.get(r);if(i)return i;let a=(async()=>{let r=e({title:WM[n.action],description:`${n.store} · ${YM(n)}`});try{let e=n;for(;GM(e);){let i=await qM(t),a=i.jobs.find(e=>e.id===n.id);if(!a)throw Error(`Maintenance receipt is no longer available. The server may have restarted; refresh the cache settings.`);if(e=a,window.dispatchEvent(new CustomEvent(ZM,{detail:{workspace:t,status:i}})),!GM(e))break;r.update({title:WM[e.action],description:`${e.store} · ${YM(e)}`}),await new Promise(e=>setTimeout(e,2e3))}if(e.status===`failed`)throw Error(YM(e));r.done({title:`${WM[e.action]} complete`,description:`${e.store} · ${YM(e)}`})}catch(e){throw r.fail({title:`Cache maintenance needs attention`,description:`${n.store} · ${e instanceof Error?e.message:String(e)}`,variant:`destructive`}),e}})();return XM.set(r,a),a.finally(()=>{XM.get(r)===a&&XM.delete(r)}).catch(()=>{}),a}function $M({workspaceId:e,children:t}){let{showToast:n,showProgress:r}=wo(),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(`workspace:cache`),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(null),m=(0,X.useRef)(!1),h=(0,X.useRef)(!1),g=(0,X.useCallback)(()=>qM(e).then(t=>{if(h.current){a(t),p(null);for(let n of t.jobs.filter(GM))QM(r,e,n).catch(()=>{})}}).catch(e=>{h.current&&p(e instanceof Error?e.message:`Cannot load maintenance status`)}),[e,r]);(0,X.useEffect)(()=>{h.current=!0,g();let t=t=>{let{workspace:n,status:r}=t.detail;n===e&&(a(r),p(null))};return window.addEventListener(ZM,t),()=>{h.current=!1,window.removeEventListener(ZM,t)}},[e,g]);let _=async t=>{if(!(m.current||i?.jobs.some(GM))){m.current=!0,l(!0);try{let n=await JM(e,o,t);h.current&&a(e=>e&&{...e,jobs:[n,...e.jobs.filter(e=>e.id!==n.id)]}),QM(r,e,n).catch(()=>{})}catch(e){n({title:`Could not start maintenance`,description:e instanceof Error?e.message:String(e),variant:`destructive`}),g()}finally{m.current=!1,h.current&&l(!1)}}},v=c||!!i?.jobs.some(GM),y=i?.stores.find(e=>e.id===o),b=i?.jobs[0];return(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-(--panel-radius) border p-4`,"aria-label":`Workspace cache maintenance`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`h2`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[(0,Z.jsx)(Fa,{className:`h-4 w-4 shrink-0`}),`Workspace cache`]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Thumbnails, cached resources and pending transfers. Maintenance runs only when requested.`})]}),t&&(0,Z.jsx)(`fieldset`,{disabled:v,children:t})]}),(0,Z.jsxs)(`div`,{className:`space-y-3 border-t pt-3`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`label`,{htmlFor:`cache-maintenance-store`,className:`text-xs font-medium`,children:`Store`}),(0,Z.jsxs)(`select`,{id:`cache-maintenance-store`,value:o,onChange:e=>s(e.target.value),disabled:v,className:`min-w-0 max-w-full rounded-md border bg-background px-2 py-1.5 text-xs`,children:[(0,Z.jsx)(`option`,{value:`workspace:cache`,children:`workspace:cache`}),(0,Z.jsx)(`option`,{value:`workspace:data`,children:`workspace:data`})]}),(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`icon`,onClick:()=>void g(),"aria-label":`Refresh cache maintenance status`,className:`ml-auto h-8 w-8`,children:(0,Z.jsx)(Er,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:o===`workspace:data`?`Managed document blobs. Referenced content is kept during collection.`:`Working cache, including content awaiting transfer. Referenced content is kept during collection.`}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:v||!y?.canCollect||!!f,onClick:()=>void _(`collect`),children:[(0,Z.jsx)(Qr,{className:`mr-2 h-3.5 w-3.5`}),`Collect unused blobs`]}),(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:v||!y?.canCompact||!!f,onClick:()=>void _(`compact`),children:[(0,Z.jsx)(ra,{className:`mr-2 h-3.5 w-3.5`}),`Compact index`]}),(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:v||!y?.canVerify||!!f,onClick:()=>d(!0),children:[(0,Z.jsx)(Fi,{className:`mr-2 h-3.5 w-3.5`}),`Verify integrity`]})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Collection removes unreferenced blobs. Compaction trims index history. Verification reads every blob and may remove corrupted content. Storage writes may wait during maintenance.`}),!i&&!f&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,role:`status`,children:`Loading maintenance status…`}),y&&!y.canCollect&&!y.canVerify&&!y.canCompact&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Update canvas-stored to enable maintenance for this store.`}),f&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,role:`alert`,children:f}),b&&(0,Z.jsxs)(`div`,{className:`rounded-md bg-muted/50 p-3 text-xs`,role:`status`,"aria-live":`polite`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 font-medium`,children:[GM(b)&&(0,Z.jsx)(Ti,{className:`h-3.5 w-3.5 animate-spin`}),WM[b.action],` · `,b.store]}),(0,Z.jsx)(`p`,{className:`mt-1 ${b.status===`failed`?`text-destructive`:`text-muted-foreground`}`,children:YM(b)}),(0,Z.jsx)(`p`,{className:`mt-1 text-muted-foreground`,children:b.finishedAt?`Finished ${new Date(b.finishedAt).toLocaleString()}`:`Requested ${new Date(b.createdAt).toLocaleString()}`})]})]}),(0,Z.jsx)(vo,{open:u,onOpenChange:d,children:(0,Z.jsxs)(lo,{className:`max-w-[calc(100vw-2rem)] sm:max-w-lg`,children:[(0,Z.jsxs)(_o,{children:[(0,Z.jsxs)(io,{children:[`Verify `,o,`?`]}),(0,Z.jsx)(ro,{children:`This reads all stored content and can take a long time. Corrupted blobs and their index entries may be removed. Keep a recovery backup before running it. Storage writes may wait until it finishes.`})]}),(0,Z.jsxs)(mo,{children:[(0,Z.jsx)(go,{children:`Cancel`}),(0,Z.jsx)(po,{disabled:v,onClick:()=>void _(`verify`),children:`Verify and repair`})]})]})})]})}function eN({workspaceId:e,backend:t,onSaved:n}){let r=t?.config||{},i=()=>({name:String(r.label||``),bucket:String(r.bucket||``),prefix:String(r.prefix||``),endpoint:String(r.endpoint||``),region:String(r.region||`us-east-1`),accessKeyId:``,secretAccessKey:``,sessionToken:``}),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(i),[l,u]=(0,X.useState)(r.forcePathStyle!==!1),[d,f]=(0,X.useState)(r.readOnly===!0),[p,m]=(0,X.useState)(r.watch===!0),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(!1),{showToast:y}=wo(),b=e=>({value:s[e],onChange:t=>c(n=>({...n,[e]:t.target.value}))});return a?(0,Z.jsxs)(`form`,{onSubmit:async r=>{r.preventDefault(),v(!0);try{let r={label:s.name.trim(),bucket:s.bucket.trim(),prefix:s.prefix.trim(),endpoint:s.endpoint.trim(),region:s.region.trim()||`us-east-1`,forcePathStyle:l,readOnly:d,watch:p,...Object.fromEntries([`accessKeyId`,`secretAccessKey`,`sessionToken`].flatMap(e=>{let t=s[e].trim();return t?[[e,t]]:[]})),...h?{sessionToken:``}:{}};t?await Fo(e,`s3`,t.address,r):await Zs(e,`s3`,r),o(!1),c(i()),y({title:t?`S3 backend updated`:`S3 backend added`,description:`Use Re-sync to check indexing progress, and filing policies to automate copies.`}),await n()}catch(e){y({title:`Could not connect S3`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{v(!1)}},className:`w-full space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`h2`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[(0,Z.jsx)(Fa,{className:`h-4 w-4`}),t?`Edit S3 connection`:`Add S3-compatible bucket`]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Amazon S3, MinIO, Garage, RustFS or Ceph RGW. Connect an existing bucket, optionally scoped to a prefix. Supports browsing, reads and filing copies; mirror policies and overwrites are unavailable.`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs`,children:[`Name`,(0,Z.jsx)(q,{...b(`name`),required:!0,placeholder:`Accounting archive`})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs`,children:[`Bucket`,(0,Z.jsx)(q,{...b(`bucket`),disabled:!!t,required:!0,placeholder:`accounting`})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs`,children:[`Endpoint (blank for Amazon S3)`,(0,Z.jsx)(q,{...b(`endpoint`),disabled:!!t,type:`url`,placeholder:`https://s3.example.com`})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs`,children:[`Region`,(0,Z.jsx)(q,{...b(`region`),required:!0,placeholder:`us-east-1`})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs sm:col-span-2`,children:[`Prefix (optional)`,(0,Z.jsx)(q,{...b(`prefix`),disabled:!!t,placeholder:`Augmentd/Accounting`})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs`,children:[`Access key ID`,(0,Z.jsx)(q,{...b(`accessKeyId`),required:!t,autoComplete:`off`,placeholder:t?`Leave blank to keep stored value`:``})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs`,children:[`Secret access key`,(0,Z.jsx)(q,{...b(`secretAccessKey`),type:`password`,required:!t,autoComplete:`off`,placeholder:t?`Leave blank to keep stored value`:``})]}),(0,Z.jsxs)(`label`,{className:`space-y-1 text-xs sm:col-span-2`,children:[`Session token (optional)`,(0,Z.jsx)(q,{...b(`sessionToken`),disabled:h,type:`password`,autoComplete:`off`,placeholder:t?`Leave blank to keep stored value`:``})]}),t&&(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:h,onChange:e=>g(e.target.checked)}),`Clear stored session token`]})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-4 text-xs`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:l,onChange:e=>u(e.target.checked)}),`Path-style addressing`]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:d,onChange:e=>f(e.target.checked)}),`Read-only`]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:p,onChange:e=>m(e.target.checked)}),`Poll for changes`]})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Writable connections test conflict protection using a temporary object, then delete it. The key needs list/read/write access and delete access under .canvas-probe/. Initial indexing reads file bytes; polling can incur request and download charges. Upload limit: 5 GiB per file.`}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,disabled:_,onClick:()=>{o(!1),c(i())},children:`Cancel`}),(0,Z.jsx)(Y,{disabled:_,children:_?`Checking connection…`:`Save connection`})]})]}):(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:()=>{c(i()),u(r.forcePathStyle!==!1),f(r.readOnly===!0),m(r.watch===!0),g(!1),o(!0)},children:[t?(0,Z.jsx)(Lr,{className:`mr-2 h-3.5 w-3.5`}):(0,Z.jsx)(br,{className:`mr-2 h-3.5 w-3.5`}),t?`Edit S3 connection`:`Add S3 bucket`]})}function tN({workspaceId:e,isActive:t,currentMode:n,onChanged:r}){let[i,a]=(0,X.useState)(n===`workspace`?`workspace`:`secrets`),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(``),[f,p]=(0,X.useState)(``),[m,h]=(0,X.useState)(``),[g,_]=(0,X.useState)(!1);return(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`font-semibold text-sm`,children:`Workspace protection`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Protect service credentials with a PIN or password. Optionally require it to start the whole workspace. Files and document contents are not encrypted.`}),t&&(0,Z.jsx)(`p`,{className:`text-sm`,children:`Stop the workspace before changing protection.`}),(0,Z.jsxs)(`form`,{className:`space-y-3`,onSubmit:async t=>{if(t.preventDefault(),h(``),o!==c){h(`PIN/password confirmation does not match`);return}_(!0);try{let t=await J.put(`${no.workspaces}/${e}/protection`,{mode:i,passphrase:o,currentPassphrase:u||void 0});p(t.recoveryKey),s(``),l(``),d(``)}catch(e){h(e instanceof Error?e.message:`Could not save protection`)}finally{_(!1)}},children:[(0,Z.jsxs)(`label`,{className:`block text-sm space-y-1`,children:[`Protection mode`,(0,Z.jsxs)(`select`,{className:`block rounded border bg-background p-2 w-full`,value:i,onChange:e=>a(e.target.value),disabled:t||g,children:[(0,Z.jsx)(`option`,{value:`secrets`,children:`Secrets only — allow start without integrations`}),(0,Z.jsx)(`option`,{value:`workspace`,children:`Whole workspace — require PIN/password to start`})]})]}),(0,Z.jsxs)(`label`,{className:`block text-sm space-y-1`,children:[`Current PIN/password or recovery key (if already protected)`,(0,Z.jsx)(q,{type:`password`,autoComplete:`current-password`,value:u,onChange:e=>d(e.target.value),disabled:t||g})]}),(0,Z.jsxs)(`label`,{className:`block text-sm space-y-1`,children:[`New PIN/password`,(0,Z.jsx)(q,{type:`password`,autoComplete:`new-password`,minLength:4,maxLength:1024,required:!0,value:o,onChange:e=>s(e.target.value),disabled:t||g})]}),(0,Z.jsxs)(`label`,{className:`block text-sm space-y-1`,children:[`Confirm new PIN/password`,(0,Z.jsx)(q,{type:`password`,autoComplete:`new-password`,required:!0,value:c,onChange:e=>l(e.target.value),disabled:t||g})]}),(0,Z.jsx)(Y,{disabled:t||g||!!f,children:g?`Saving…`:`Save protection`})]}),m&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:m}),f&&(0,Z.jsxs)(`div`,{className:`space-y-2 rounded border p-3`,children:[(0,Z.jsx)(`p`,{className:`text-sm`,children:`Save this recovery key now. It is shown only once and replaces any previous recovery key.`}),(0,Z.jsx)(`code`,{className:`block break-all select-all`,children:f}),(0,Z.jsx)(Y,{variant:`outline`,onClick:()=>{p(``),r()},children:`I saved the recovery key`})]})]})}var nN=`h-8 rounded-md border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring`;function rN({title:e,hint:t,children:n}){let[r,i]=(0,X.useState)(!1);return(0,Z.jsxs)(`section`,{className:`overflow-hidden rounded-lg border`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>i(e=>!e),"aria-expanded":r,className:`flex w-full items-center justify-between gap-4 px-4 py-3 text-left transition-colors hover:bg-muted/40`,children:[(0,Z.jsxs)(`span`,{className:`min-w-0`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium`,children:e}),(0,Z.jsx)(`span`,{className:`mt-0.5 block text-xs text-muted-foreground`,children:t})]}),(0,Z.jsx)(qr,{className:K(`h-4 w-4 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none`,r&&`rotate-180`)})]}),r&&(0,Z.jsx)(`div`,{className:`border-t p-4`,children:n})]})}function iN({workspaceId:e,workspaceName:t,refreshKey:n,onRefresh:r}){let{showToast:i}=wo(),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),l=(0,X.useCallback)(()=>KA(e).then(e=>o(e.queue??null)).catch(()=>{}),[e]);(0,X.useEffect)(()=>{l();let e=window.setInterval(()=>{o(e=>(e&&(e.pending>0||e.draining)&&l(),e))},3e3);return()=>window.clearInterval(e)},[l,n]);let u=async()=>{if(a){c(!0);try{let e=await Oc(!a.paused,t);i({title:e.paused?`Embedding paused`:`Embedding resumed`,description:e.paused?`${e.pending.toLocaleString()} job(s) held for this workspace. Resume any time; a restart also resumes.`:`${e.pending.toLocaleString()} job(s) draining.`}),await l()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to toggle the embedding queue (admin only)`,variant:`destructive`})}finally{c(!1)}}},d=!!a?.draining,f=a?a.paused?`bg-warning`:d?`bg-success`:`bg-muted-foreground/40`:`bg-muted-foreground/40`;return(0,Z.jsxs)(`section`,{className:`flex flex-wrap items-center justify-between gap-x-4 gap-y-2 rounded-lg border bg-muted/30 px-4 py-2.5`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 text-sm`,children:[(0,Z.jsxs)(`span`,{className:`relative flex h-2 w-2 shrink-0`,"aria-hidden":!0,children:[d&&(0,Z.jsx)(`span`,{className:`absolute inline-flex h-full w-full animate-ping rounded-full bg-success opacity-60 motion-reduce:hidden`}),(0,Z.jsx)(`span`,{className:K(`relative inline-flex h-2 w-2 rounded-full`,f)})]}),(0,Z.jsx)(`span`,{className:`font-medium`,children:a?a.pending>0?(0,Z.jsxs)(Z.Fragment,{children:[a.pending.toLocaleString(),` `,(0,Z.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`pending`})]}):a.paused?`Paused`:`Idle`:`Queue unavailable`}),a?.paused&&a.pending>0&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`held`}),a?.ingestDisabled&&(0,Z.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,title:`CANVAS_INFERD_INGEST_DISABLED=true: nothing new is enqueued; existing vectors still serve search`,children:`ingest disabled`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1`,children:[a&&(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,disabled:s,onClick:u,title:a.paused?`Resume embedding; the held backlog drains`:`Pause after the current batch. Stops the CPU-heavy model inference; documents keep indexing and stay searchable by text.`,children:s?`…`:a.paused?`Resume`:`Pause`}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:r,title:`Reload config, queue and tables`,children:(0,Z.jsx)(Er,{className:`h-3.5 w-3.5`})})]})]})}function aN({workspaceId:e,tables:t,error:n,onChanged:r}){let{showToast:i}=wo(),[a,o]=(0,X.useState)(null),s=t.filter(e=>!e.active),c=async t=>{if(window.confirm(`Reclaim "${t.name}"?\n\nThis permanently deletes the vectors for ${t.model||`that model`} and its "already embedded" ledger. Switching back to it afterwards would cost a full re-embed rather than being instant.\n\nThis is the only irreversible step in the whole flow.`)){o(t.name);try{let n=await $A(e,t.name);if(!n.dropped)throw Error(n.error||`Failed to drop the vector table`);i({title:`Reclaimed`,description:`Dropped '${n.name||t.name}'.`}),r()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to reclaim`,variant:`destructive`})}finally{o(null)}}};return n?(0,Z.jsxs)(`section`,{className:`rounded-lg border border-destructive/40 bg-destructive-subtle p-4`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium text-destructive`,children:`Vector tables unavailable`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:n})]}):s.length===0?null:(0,Z.jsx)(rN,{title:`Previous models (${s.length})`,hint:`Kept on disk so switching back is instant. Reclaiming deletes their vectors for good (the only irreversible step here).`,children:(0,Z.jsx)(`div`,{className:`divide-y`,children:s.map(e=>(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-4 py-2 first:pt-0 last:pb-0`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`p`,{className:`truncate font-mono text-xs`,children:[e.model||`unknown model`,e.dim?` · ${e.dim}-d`:``]}),(0,Z.jsxs)(`p`,{className:`truncate font-mono text-[11px] text-muted-foreground`,children:[`└─ `,e.name]})]}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,className:`text-destructive hover:text-destructive`,disabled:a===e.name,onClick:()=>c(e),title:`Permanently delete this model's vectors and ledger`,children:[(0,Z.jsx)(Qr,{className:`mr-1.5 h-3.5 w-3.5`}),a===e.name?`Reclaiming…`:`Reclaim`]})]},e.name))})})}function oN({workspaceId:e,workspaceName:t,spaces:n,onDone:r}){let{showToast:i}=wo(),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(``),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1);return(0,Z.jsxs)(rN,{title:`Fill a space`,hint:`Embed documents that are missing from a space. Narrow it to one subtree to try a model on a single project first.`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Space`}),(0,Z.jsxs)(`select`,{className:`${nN} w-full`,value:a,onChange:e=>o(e.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:`all spaces`}),n.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`label`,{className:`text-xs font-medium`,children:[`Limit to a path `,(0,Z.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(optional)`})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:s,onChange:e=>c(e.target.value),placeholder:`ctx://work/project or dir://photos`,className:`h-8 font-mono text-sm`}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>m(!0),title:`Pick a context or directory path from the tree`,children:(0,Z.jsx)(fr,{className:`h-3.5 w-3.5`})})]})]})]}),(0,Z.jsxs)(`label`,{className:`mt-3 flex items-start gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:l,onChange:e=>u(e.target.checked)}),(0,Z.jsxs)(`span`,{children:[`Re-embed documents that are already embedded`,l&&s.trim()&&(0,Z.jsx)(`span`,{className:`mt-1 block text-[11px] text-warning`,children:`Combined with a path limit this clears the WHOLE space, not just that subtree. A partial clear is not expressible in the ledger. Leave this off unless you mean to redo everything.`})]})]}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,className:`mt-3`,onClick:async()=>{f(!0);try{let t=await ZA(e,{space:a||void 0,reindex:l,scope:s.trim()||void 0});t.ingestDisabled?i({title:`Ingest disabled`,description:`CANVAS_INFERD_INGEST_DISABLED=true: nothing was enqueued. Existing vectors still serve search.`,variant:`destructive`}):i({title:`Fill enqueued`,description:`${t.enqueued.toLocaleString()} document(s) queued${t.scope?` under ${t.scope}`:``}. The status line reports progress.`}),r()}catch(e){i({title:`Fill failed`,description:e instanceof Error?e.message:`Failed to enqueue`,variant:`destructive`})}finally{f(!1)}},disabled:d,children:d?`Queueing…`:`Start fill`}),p&&(0,Z.jsx)(Le,{onClose:()=>m(!1),children:(0,Z.jsx)(y,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,fixedWorkspaceName:t,multiple:!1,onClose:()=>m(!1),onConfirm:(e,t)=>{let n=e[0];if(n){let e=t.treeType===`directory`?`dir`:`ctx`;c(`${e}://${n.replace(/^\/+/,``)}`)}m(!1)}})})]})}var sN=[{provider:`blip`,model:`HuggingFaceTB/SmolVLM-500M-Instruct`,task:`instruct`,label:`SmolVLM 500M: prompted description (recommended)`,note:`~500 MB. Follows the prompt below, so architecture/materials/setting can be asked for.`},{provider:`blip`,model:`HuggingFaceTB/SmolVLM-256M-Instruct`,task:`instruct`,label:`SmolVLM 256M: prompted, smaller`,note:`~250 MB. Same prompting, weaker; for memory-tight boxes.`},{provider:`blip`,model:`onnx-community/Florence-2-base-ft`,task:`florence2`,label:`Florence-2 base: detailed caption`,note:`Detailed multi-sentence captions, but not steerable: no prompt, fixed task token.`},{provider:`blip`,model:`Xenova/vit-gpt2-image-captioning`,task:`caption`,label:`vit-gpt2: one short sentence (weakest)`,note:`The old default. Terse and repetition-prone; kept for continuity and low memory.`}],cN=`custom`,lN=[{value:`instruct`,label:`Instruct VLM (image + prompt)`},{value:`florence2`,label:`Florence-2 (task token)`},{value:`caption`,label:`Plain captioner (image only)`}],uN=`Describe this photograph in two or three sentences. If it shows a building or interior, name the architectural style, the main materials and the setting. Describe only what is visible.`;function dN({workspaceId:e,config:t,saving:n,onSave:r}){let{showToast:i}=wo(),a=t.workspace||{},o=t.effective||{},s=sN[0],c=a.summarize?.image||o.summarize?.image||{},[l,u]=(0,X.useState)(()=>o.summarize?.image?.enabled===!0||a.summarize?.image?.enabled===!0),[d,f]=(0,X.useState)(()=>{let e=sN.find(e=>e.provider===(c.provider||s.provider)&&e.model===c.model);return e?`${e.provider}::${e.model}`:c.model?cN:`${s.provider}::${s.model}`}),[p,m]=(0,X.useState)(()=>sN.some(e=>e.model===c.model)?``:c.model||``),[h,g]=(0,X.useState)(()=>c.task||`instruct`),[_,v]=(0,X.useState)(()=>c.prompt||``),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(null),[C,w]=(0,X.useState)(!1),[T,E]=(0,X.useState)(!1),[D,O]=(0,X.useState)(!1),k=sN.find(e=>`${e.provider}::${e.model}`===d),A=d===cN,j=A?{provider:s.provider,model:p.trim(),task:h,label:`Custom`,note:``}:k||s,M=j.task===`instruct`,N=(0,X.useCallback)(()=>KA(e).then(e=>S(e.summarize||null)).catch(()=>{}),[e]);(0,X.useEffect)(()=>{N();let e=window.setInterval(()=>{S(e=>(e?.running&&N(),e))},2e3);return()=>window.clearInterval(e)},[N]);let P=async()=>{await r({...a,summarize:{...a.summarize||{},image:{enabled:l,provider:j.provider,model:j.model,task:j.task,...M&&_.trim()?{prompt:_.trim()}:{}}}}),b(!1)},ee=async()=>{E(!0);try{S(await JA(e)),i({title:`Stopping image summaries`,description:`The image being captioned finishes first; the rest are left for a later run.`})}catch(e){i({title:`Could not stop`,description:e instanceof Error?e.message:`Failed to stop`,variant:`destructive`})}finally{E(!1)}},F=async(t=!1)=>{w(!0);try{let n=await qA(e,{force:t});S(n),i({title:t?`Rebuilding image summaries`:`Backfilling image summaries`,description:`${n.total.toLocaleString()} candidate image(s). First run downloads model weights.`})}catch(e){i({title:`Summaries failed to start`,description:e instanceof Error?e.message:`Failed to start`,variant:`destructive`})}finally{w(!1)}},I=o.summarize?.image?.enabled===!0,te=x?.running===!0,L=x?.errors?.[0]?.error;return(0,Z.jsx)(rN,{title:`Summaries`,hint:`Generate descriptions for indexed images (metadata.summary); searchable via full-text and dense search`,children:(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-sm`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:l,disabled:n,onChange:e=>{u(e.target.checked),b(!0)}}),`Images`]}),(0,Z.jsxs)(`select`,{className:nN,value:d,disabled:n||!l,onChange:e=>{f(e.target.value),b(!0)},children:[sN.map(e=>(0,Z.jsx)(`option`,{value:`${e.provider}::${e.model}`,children:e.label},`${e.provider}::${e.model}`)),(0,Z.jsx)(`option`,{value:cN,children:`Custom model…`})]}),!A&&(0,Z.jsx)(`span`,{className:`font-mono text-xs text-muted-foreground`,children:j.model})]}),A&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{className:`h-8 w-72 font-mono text-xs`,placeholder:`org/model-id (Transformers.js / ONNX)`,value:p,disabled:n||!l,onChange:e=>{m(e.target.value),b(!0)}}),(0,Z.jsx)(`select`,{className:nN,value:h,disabled:n||!l,onChange:e=>{g(e.target.value),b(!0)},children:lN.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))})]}),l&&j.note&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:j.note}),l&&M&&(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`textarea`,{className:`w-full rounded-md border border-input bg-transparent p-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,rows:3,placeholder:uN,value:_,disabled:n,onChange:e=>{v(e.target.value),b(!0)}}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`What to ask of every image. Empty uses the default shown above. Captions are indexed, so ask for the words you would search by.`})]}),x&&(x.running||x.total>0||x.finishedAt)&&(0,Z.jsxs)(`p`,{className:K(`text-xs`,x.aborted?`text-destructive`:`text-muted-foreground`),children:[te?`Running`:x.aborted?`Stopped`:x.cancelled?`Cancelled`:`Last run`,`: `,x.described,`/`,x.total,` described`,x.skipped?`, ${x.skipped} skipped`:``,x.failed?`, ${x.failed} failed`:``,x.aborted?`. ${x.abortedReason||`model worker died`}. Remaining images were not attempted; generate again to retry.`:x.cancelled?`. Stopped by you. The remaining images were left untouched; generate again to continue.`:L?`. ${L}`:``]}),(0,Z.jsxs)(`label`,{className:`flex items-start gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:D,disabled:n||te,onChange:e=>O(e.target.checked)}),(0,Z.jsxs)(`span`,{children:[`Re-caption images that already have a summary`,D&&(0,Z.jsxs)(`span`,{className:`mt-1 block text-[11px] text-warning`,children:[`Replaces every existing `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`metadata.summary`}),`, including ones written by a different model. Leave this off to fill in only what is missing.`]})]})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Enable + save, then run. Only the local caption provider is wired today. Candidates come from `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`data/mime/image`}),`.`]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>void P(),disabled:n||!y,children:`Save summaries`}),(0,Z.jsx)(Y,{size:`sm`,onClick:()=>void F(D),disabled:n||y||C||te||!I,title:I?y?`Save config first`:D?`Re-caption every image, replacing existing summaries`:`Caption images that have no summary yet`:`Enable image summaries and save first`,children:te||C?`Running…`:D?`Rebuild`:`Backfill`}),te&&(0,Z.jsx)(Y,{size:`sm`,variant:`destructive`,onClick:()=>void ee(),disabled:T,title:`Finish the current image, then stop. The rest are left for later.`,children:T?`Stopping…`:`Stop`})]})]})]})})}function fN({workspaceId:e,workspaceName:t}){let{showToast:n}=wo(),[r,i]=(0,X.useState)(null),[a,o]=(0,X.useState)([]),[s,c]=(0,X.useState)(),[l,u]=(0,X.useState)(!0),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)([]),[_,v]=(0,X.useState)(0),y=(0,X.useCallback)(()=>YA(e).then(e=>{i(e),m(null)}).catch(e=>m(e instanceof Error?e.message:`Failed to load the embedding config`)).finally(()=>u(!1)),[e]),b=(0,X.useCallback)(()=>QA(e).then(e=>{o(e.tables||[]),c(e.error)}).catch(e=>c(e instanceof Error?e.message:`Failed to list vector tables`)),[e]);(0,X.useEffect)(()=>{y(),b()},[y,b]);let x=()=>{u(!0),y(),b(),v(e=>e+1)},S=async t=>{f(!0);try{let r=await XA(e,t);g(r.movedSpaces||[]),r.movedSpaces?.length?n({title:`Saved; fill to finish`,description:`${r.movedSpaces.join(`, `)} now targets a new model. The switch is live, but the new table is empty until you fill it.`}):r.applied===!1?n({title:`Saved; applies on next start`,description:`The workspace is not running, so the new spaces take effect when it starts.`}):n({title:`Saved`,description:`Embedding config updated.`}),await y(),await b()}catch(e){n({title:`Save failed`,description:e instanceof Error?e.message:`Failed to save`,variant:`destructive`})}finally{f(!1)}},C=async t=>{try{let r=await ZA(e,{space:t});if(r.ingestDisabled){n({title:`Ingest disabled`,description:`CANVAS_INFERD_INGEST_DISABLED=true: nothing was enqueued. Existing vectors still serve search.`,variant:`destructive`});return}n({title:`Filling ${t}`,description:`${r.enqueued.toLocaleString()} document(s) queued. The status line reports progress.`}),g(e=>e.filter(e=>e!==t)),v(e=>e+1),b()}catch(e){n({title:`Fill failed`,description:e instanceof Error?e.message:`Failed to enqueue`,variant:`destructive`})}};if(l)return(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(Er,{className:`h-4 w-4 animate-spin`}),`Loading the embedding config…`]});if(p||!r)return(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`rounded-lg border border-destructive/40 bg-destructive-subtle p-4 text-sm`,children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Embedding config unavailable`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:p||`No config returned.`})]}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:x,children:`Try again`})]});let w=Object.keys(r.effective.spaces||{}).sort();return(0,Z.jsxs)(`div`,{className:`space-y-5`,children:[(0,Z.jsx)(iN,{workspaceId:e,workspaceName:t,refreshKey:_,onRefresh:x}),(0,Z.jsx)(bj,{value:r.workspace||{},effective:r.effective||{},inherited:r.inherited||{},resolvedSpaces:r.spaces,invalid:r.invalid,attention:h,onFill:C,saving:d,saveLabel:`Save embedding config`,onSave:S},JSON.stringify(r.workspace)),(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsx)(dN,{workspaceId:e,config:r,saving:d,onSave:S},`summarize:${JSON.stringify(r.workspace?.summarize||{})}`),(0,Z.jsx)(oN,{workspaceId:e,workspaceName:t,spaces:w,onDone:()=>{b(),v(e=>e+1)}}),(0,Z.jsx)(aN,{workspaceId:e,tables:a,error:s,onChanged:()=>{b()}})]}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Stored in this workspace's own `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`workspace.json`}),`, so it travels with the workspace. Settings resolve in layers: built-in, then server, then your defaults, then this workspace, which wins. Changes apply live, with no restart.`]})]})}function pN(e){let t=(e||``).split(`.`).pop()?.toLowerCase();switch(t){case`js`:case`mjs`:case`ts`:return[l({typescript:t===`ts`})];case`json`:return[c()];case`sh`:case`bash`:return[a.define(u)];default:return[]}}function mN({value:e,onChange:t,path:n,className:r=``}){let i=(0,X.useMemo)(()=>pN(n),[n]),{resolvedScheme:a}=Ll();return(0,Z.jsx)(o,{value:e,onChange:t,extensions:i,theme:a===`dark`?`dark`:`light`,className:r,basicSetup:{lineNumbers:!0,foldGutter:!0,highlightActiveLine:!0,bracketMatching:!0,autocompletion:!1}})}var hN=[`pending`,`approved`,`declined`,`failed`,`expired`,`all`],gN={pending:`text-warning dark:text-warning`,approved:`text-success dark:text-success`,declined:`text-muted-foreground`,failed:`text-destructive`,expired:`text-muted-foreground line-through`};function _N(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return`now`;if(n<60)return`${n}m`;let r=Math.floor(n/60);return r<24?`${r}h`:`${Math.floor(r/24)}d`}function vN(e,t){return t.split(`.`).reduce((e,t)=>typeof e==`object`&&e?e[t]:void 0,e)}function yN(e){let t=e.split(`.`);return t.slice(Math.max(t.length-2,2)).join(`.`)}var bN=/(body|content|message|text|prompt)$/i;function xN({workspaceId:e,id:t,children:n}){let{open:r}=I(),{showToast:i}=wo(),[a,o]=(0,X.useState)(!1),s=async n=>{n.stopPropagation(),o(!0);try{r(await xc(e,t),e)}catch(e){i({title:`Document ${t} not available`,description:e instanceof Error?e.message:void 0,variant:`destructive`})}finally{o(!1)}};return(0,Z.jsx)(`button`,{type:`button`,disabled:a,onClick:e=>void s(e),className:`text-primary underline-offset-2 hover:underline disabled:opacity-60`,title:`Open document ${t}`,children:n??`doc ${t}`})}function SN({workspaceId:e,text:t}){let n=t.split(/(\bdoc \d+\b)/);return(0,Z.jsx)(Z.Fragment,{children:n.map((t,n)=>{let r=/^doc (\d+)$/.exec(t);return r?(0,Z.jsx)(xN,{workspaceId:e,id:Number(r[1])},n):(0,Z.jsx)(X.Fragment,{children:t},n)})})}function CN({action:e,amend:t,onAmend:n}){return e.editable?.length?(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.editable.map(r=>{let i=vN(e,r),a=typeof i==`string`,o=r in t?t[r]:i,s=a?String(o??``):JSON.stringify(o,null,2),c=a&&(bN.test(r)||s.length>80);return(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[(0,Z.jsxs)(`span`,{className:`font-medium text-muted-foreground`,children:[yN(r),(0,Z.jsx)(`span`,{className:`ml-1.5 font-mono text-[10px] opacity-60`,children:r}),r in t&&(0,Z.jsx)(`span`,{className:`ml-1.5 text-warning dark:text-warning`,children:`edited`})]}),c?(0,Z.jsx)(`textarea`,{className:`mt-1 w-full rounded-md border bg-background px-2 py-1.5 font-mono text-xs outline-none focus:ring-2 focus:ring-ring min-h-[100px]`,value:s,onChange:e=>n(r,e.target.value)}):(0,Z.jsx)(`input`,{className:`mt-1 w-full h-8 rounded-md border bg-background px-2 font-mono text-xs outline-none focus:ring-2 focus:ring-ring`,value:s,onChange:e=>{if(a){n(r,e.target.value);return}try{n(r,JSON.parse(e.target.value))}catch{n(r,e.target.value)}}})]},r)})}):null}function wN({workspaceId:e,onPendingCount:t}){let{showToast:n}=wo(),r=Cw(),[i,a]=(0,X.useState)(`pending`),[o,s]=(0,X.useState)([]),[c,l]=(0,X.useState)(!0),[u,d]=(0,X.useState)(new Set),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)({}),[g,_]=(0,X.useState)(!1),v=(0,X.useCallback)(()=>en(e,{status:i===`all`?void 0:i,limit:200}).then(e=>{s(e),d(t=>new Set(e.filter(e=>e.status===`pending`&&t.has(e.actionId)).map(e=>e.actionId))),t?.(i===`pending`?e.length:e.filter(e=>e.status===`pending`).length)}).catch(()=>{n({title:`Error`,description:`Failed to load pending actions`,variant:`destructive`})}).finally(()=>l(!1)),[e,i]),y=(0,X.useCallback)(async()=>{l(!0),await v()},[v]),[b,x]=(0,X.useState)(`${e}|${i}`),S=`${e}|${i}`;S!==b&&(x(S),l(!0)),(0,X.useEffect)(()=>{v()},[v]),fw(r,`workspace:${e}`,(0,X.useMemo)(()=>{let e=()=>{y()};return{"action.proposed":e,"action.approved":e,"action.declined":e,"action.failed":e}},[y]));let C=o.filter(e=>e.status===`pending`),w=C.length>0&&C.every(e=>u.has(e.actionId)),T=()=>{d(w?new Set:new Set(C.map(e=>e.actionId)))},E=e=>{d(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},D=(e,t,n)=>{h(r=>({...r,[e]:{...r[e],[t]:n}}))},O=async(t,r)=>{if(!(!t.length&&!r.length)){_(!0);try{let i=await gt(e,{approve:t.map(e=>{let t=m[e];return t&&Object.keys(t).length?{actionId:e,amend:t}:e}),decline:r}),a=i.results.filter(e=>e.status===`error`||e.status===`failed`);a.length?n({title:`${a.length} of ${i.decided} failed`,description:a.map(e=>`${e.actionId}: ${e.error??`execution failed`}`).join(`; `),variant:`destructive`}):n({title:t.length&&r.length?`Decisions applied`:t.length?`Approved ${t.length}`:`Declined ${r.length}`,description:t.length?`Approved actions executed with their original provenance.`:void 0}),h(e=>{let n={...e};for(let e of[...t,...r])delete n[e];return n}),d(new Set),f&&[...t,...r].includes(f)&&p(null),await y()}catch(e){n({title:`Decision failed`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{_(!1)}}};return(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 flex-wrap`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`select`,{className:`h-8 rounded-md border bg-background px-2 text-xs outline-none focus:ring-2 focus:ring-ring`,value:i,onChange:e=>a(e.target.value),children:hN.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))}),(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,onClick:()=>void y(),title:`Reload`,children:(0,Z.jsx)(Er,{className:`h-4 w-4`})})]}),u.size>0&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[u.size,` selected`]}),(0,Z.jsxs)(Y,{size:`sm`,disabled:g,onClick:()=>void O([...u],[]),children:[(0,Z.jsx)(sr,{className:`mr-1 h-3.5 w-3.5`}),` Approve`]}),(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,disabled:g,onClick:()=>void O([],[...u]),children:[(0,Z.jsx)(vr,{className:`mr-1 h-3.5 w-3.5`}),` Decline`]})]})]}),(0,Z.jsx)(`div`,{className:`border rounded-lg overflow-auto max-h-[560px]`,children:c?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground p-3`,children:`Loading...`}):o.length===0?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground p-3`,children:i===`pending`?`Nothing waiting for review. Rules or hooks with approval enabled queue their actions here.`:`No ${i===`all`?``:i+` `}actions recorded.`}):(0,Z.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,Z.jsx)(`thead`,{className:`text-xs text-muted-foreground border-b sticky top-0 bg-background`,children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{className:`px-3 py-2 w-8`,children:C.length>0&&(0,Z.jsx)(`input`,{type:`checkbox`,checked:w,onChange:T,title:`Select all pending`})}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Proposed action`}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Handler`}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Age`}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Status`}),(0,Z.jsx)(`th`,{className:`px-2 py-2 w-40`})]})}),(0,Z.jsx)(`tbody`,{children:o.map(t=>{let n=t.status===`pending`||t.status===`failed`,r=f===t.actionId,i=t.envelope?.payload?.document;return(0,Z.jsxs)(X.Fragment,{children:[(0,Z.jsxs)(`tr`,{className:`border-b last:border-0 align-top hover:bg-muted/40 cursor-pointer`,onClick:()=>p(r?null:t.actionId),children:[(0,Z.jsx)(`td`,{className:`px-3 py-2`,onClick:e=>e.stopPropagation(),children:t.status===`pending`&&(0,Z.jsx)(`input`,{type:`checkbox`,checked:u.has(t.actionId),onChange:()=>E(t.actionId)})}),(0,Z.jsxs)(`td`,{className:`px-3 py-2`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-1 font-medium`,children:[r?(0,Z.jsx)(qr,{className:`h-3 w-3 shrink-0`}):(0,Z.jsx)(Xa,{className:`h-3 w-3 shrink-0`}),t.title,t.editable?.length>0&&(0,Z.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide rounded bg-muted-foreground/15 px-1 py-0.5 text-muted-foreground shrink-0`,children:`editable`})]}),t.summary&&(0,Z.jsx)(`span`,{className:`block text-xs text-muted-foreground pl-4`,children:(0,Z.jsx)(SN,{workspaceId:e,text:t.summary})})]}),(0,Z.jsxs)(`td`,{className:`px-3 py-2 font-mono text-xs whitespace-nowrap`,children:[(0,Z.jsxs)(`span`,{className:`text-muted-foreground`,children:[t.handlerType,`:`]}),t.handler,t.event&&(0,Z.jsxs)(`span`,{className:`block text-muted-foreground`,children:[t.event,i?.id!=null&&(0,Z.jsxs)(Z.Fragment,{children:[` · `,(0,Z.jsx)(xN,{workspaceId:e,id:i.id})]})]})]}),(0,Z.jsx)(`td`,{className:`px-3 py-2 text-xs whitespace-nowrap`,title:t.ts,children:_N(t.ts)}),(0,Z.jsxs)(`td`,{className:`px-3 py-2 text-xs`,children:[(0,Z.jsx)(`span`,{className:gN[t.status],children:t.status}),t.amended&&(0,Z.jsx)(`span`,{className:`block text-muted-foreground`,children:`amended`}),t.decidedBy&&(0,Z.jsx)(`span`,{className:`block text-muted-foreground truncate max-w-[120px]`,title:t.decidedBy,children:t.decidedBy})]}),(0,Z.jsx)(`td`,{className:`px-2 py-2 whitespace-nowrap text-right`,onClick:e=>e.stopPropagation(),children:n&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Y,{size:`sm`,className:`h-7 px-2`,disabled:g,title:t.status===`failed`?`Retry (re-approve)`:`Approve and execute`,onClick:()=>void O([t.actionId],[]),children:(0,Z.jsx)(sr,{className:`h-3.5 w-3.5`})}),t.status===`pending`&&(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,className:`h-7 px-2 text-muted-foreground`,disabled:g,title:`Decline`,onClick:()=>void O([],[t.actionId]),children:(0,Z.jsx)(vr,{className:`h-3.5 w-3.5`})})]})})]}),r&&(0,Z.jsxs)(`tr`,{className:`border-b last:border-0 bg-muted/20`,children:[(0,Z.jsx)(`td`,{className:`px-3 py-3`}),(0,Z.jsxs)(`td`,{className:`px-3 py-3 space-y-3`,colSpan:5,children:[n&&t.editable?.length>0&&(0,Z.jsx)(CN,{action:t,amend:m[t.actionId]??{},onAmend:(e,n)=>D(t.actionId,e,n)}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Actions on approve`}),(0,Z.jsx)(`pre`,{className:`mt-1 rounded border bg-background p-2 font-mono text-xs overflow-auto max-h-56`,children:JSON.stringify(t.actions,null,2)})]}),t.result&&t.result.length>0&&(0,Z.jsx)(`div`,{className:`text-xs font-mono`,children:t.result.map((e,t)=>(0,Z.jsxs)(`span`,{className:`mr-2 ${e.status===`error`?`text-destructive`:`text-muted-foreground`}`,children:[e.action,`:`,e.status,e.error?` (${e.error})`:``]},t))}),(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground font-mono`,children:[t.actionId,` · origin `,t.provenance?.origin,t.provenance?.causedBy?` · causedBy ${t.provenance.causedBy}`:``,t.expiresAt?` · expires ${new Date(t.expiresAt).toLocaleString()}`:``]})]})]})]},t.actionId)})})]})})]})}var TN=`#!/usr/bin/env bash
|
|
40
42
|
# Called from a hook via: spawn('bash', [script, ...args])
|
|
41
43
|
set -euo pipefail
|
|
42
44
|
`;function EN({workspaceId:e,prefillRule:t,onPrefillConsumed:n,initialSection:r,initialRunsHandler:i,initialRunId:a}){let{showToast:o}=wo(),[s,c]=(0,X.useState)(r??`rules`),[l,u]=(0,X.useState)(t);t!==l&&(u(t),t&&c(`rules`));let[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)([]),[h,g]=(0,X.useState)(!0),[v,y]=(0,X.useState)(null),[b,x]=(0,X.useState)(``),[S,C]=(0,X.useState)(!1),[w,T]=(0,X.useState)(!1),[E,D]=(0,X.useState)(!1),[O,k]=(0,X.useState)(null),[A,j]=(0,X.useState)(`document.inserted`),[M,N]=(0,X.useState)(``),[P,ee]=(0,X.useState)([]),[F,I]=(0,X.useState)(!1),[te,L]=(0,X.useState)([]),[R,re]=(0,X.useState)(!1),[ie,ae]=(0,X.useState)(i||null),[z,oe]=(0,X.useState)(a?{runId:a,run:null}:null),se=e=>{oe(t=>t?.runId===e?null:{runId:e,run:null})};(0,X.useEffect)(()=>{if(!z||z.run||z.error)return;let t=!1;return dn(e,z.runId).then(e=>{t||oe(t=>t?.runId===e.runId?{runId:e.runId,run:e}:t)}).catch(e=>{t||oe(t=>t?.runId===z.runId?{...t,error:e instanceof Error?e.message:`Failed to load run`}:t)}),()=>{t=!0}},[e,z]);let[B,V]=(0,X.useState)(null),[le,ue]=(0,X.useState)(!1),[de,fe]=(0,X.useState)(0),[pe,me]=(0,X.useState)(null),[he,ge]=(0,X.useState)(()=>At()),[_e,ve]=(0,X.useState)(()=>String(At())),ye=()=>{let e=jn(_(_e));ge(e),ve(String(e))};(0,X.useEffect)(()=>{let t=!1;return en(e,{status:`pending`,limit:500}).then(e=>{t||fe(e.length)}).catch(()=>{}),()=>{t=!0}},[e]),Ae(()=>ue(!1),le);let be=async t=>{if(confirm(`Replay ${t.handlerType} "${t.handler}" for ${t.event} (docs ${(t.docIds||[]).join(`, `)})?`)){V(t.runId);try{let n=await Et(e,t.runId);o({title:`Replayed`,description:`${t.handler} → ${n.status}`}),await Se()}catch(e){o({title:`Replay failed`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{V(null)}}},xe=s===`scripts`?{list:Fe,get:ne,save:Ve,del:Re}:{list:bt,get:rt,save:Sn,del:Kt},H=s===`hooks`||s===`scripts`,Se=async()=>{if(s!==`rules`&&s!==`pending`){if(s===`runs`){try{g(!0),L(await Ht(e,{limit:100,failed:R||void 0,handler:ie||void 0}))}catch{o({title:`Error`,description:`Failed to load hook runs`,variant:`destructive`})}finally{g(!1)}return}try{g(!0),m(await xe.list(e))}catch{o({title:`Error`,description:`Failed to load ${s}`,variant:`destructive`})}finally{g(!1)}}};(0,X.useEffect)(()=>{Se()},[e,s,R,ie]);let Ce=e=>{e!==s&&(S&&!confirm(`Discard unsaved changes?`)||(c(e),y(null),x(``),C(!1),D(!1)))},U=async t=>{if(!(S&&!confirm(`Discard unsaved changes?`)))try{y(t),x(await xe.get(e,t)),C(!1)}catch{o({title:`Error`,description:`Failed to open ${t}`,variant:`destructive`})}},we=async()=>{if(v)try{T(!0),await xe.save(e,v,b),C(!1),o({title:`Saved`,description:`${v} saved`}),await Se()}catch{o({title:`Error`,description:`Failed to save ${v}`,variant:`destructive`})}finally{T(!1)}},Te=async t=>{let n=pt(t);try{let r=await ot(e,t,!n);v===t&&y(r),await Se(),o({title:n?`Disabled`:`Enabled`,description:r})}catch{o({title:`Error`,description:`Failed to toggle ${t}`,variant:`destructive`})}},Ee=async t=>{let n=zt(t);if(!n||!pt(t)&&!confirm(`${t} is disabled. Run it anyway?`))return;let r=n.startsWith(`document.`);if(!(r&&!confirm(`Run ${t} against up to ${he} existing documents (event ${n})?`))){me(t);try{if(r){let r=await W(e,{hookFile:t,event:n,limit:he});o({title:`Run finished`,description:`${r.processed} documents processed, ${r.failed} failed. Details in the Runs tab`,...r.failed?{variant:`destructive`}:{}})}else{let r=await $e(e,{hookFile:t,event:n});o({title:r.status===`error`?`Run failed`:`Run finished`,description:r.status===`error`?`${t}: ${r.error||`see the Runs tab`}`:`${t} → ${r.status}${r.durationMs==null?``:` in ${r.durationMs}ms`}`,...r.status===`error`?{variant:`destructive`}:{}})}}catch(e){o({title:`Run failed`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{me(null)}}},De=async t=>{if(confirm(`Delete ${s===`hooks`?`hook`:`script`} ${t}?`))try{await xe.del(e,t),v===t&&(y(null),x(``),C(!1)),await Se(),o({title:`Deleted`,description:`${t} deleted`})}catch{o({title:`Error`,description:`Failed to delete ${t}`,variant:`destructive`})}},Oe=async()=>{if(!O)try{k(await Xt(e))}catch{o({title:`Error`,description:`Failed to load hook metadata`,variant:`destructive`})}},ke=async()=>{D(!E),s===`hooks`&&await Oe()},je=async()=>{f(!d),await Oe()},Me=async()=>{let t=M.trim().replace(/^\/+/,``);if(!t){o({title:`Error`,description:`Give the script a name (e.g. on-image.sh)`,variant:`destructive`});return}try{I(!0),await Ve(e,t,TN),D(!1),N(``),await Se(),await U(t)}catch{o({title:`Error`,description:`Failed to create script`,variant:`destructive`})}finally{I(!1)}},Ne=e=>{ee(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},Pe=async()=>{if(!M.trim()){o({title:`Error`,description:`Give the hook a name`,variant:`destructive`});return}try{I(!0);let{path:t}=await cn(e,{event:A,name:M.trim(),actions:P});D(!1),N(``),ee([]),await Se(),await U(t),o({title:`Created`,description:`${t}. Edit the TODOs, then enable it`})}catch{o({title:`Error`,description:`Failed to create hook`,variant:`destructive`})}finally{I(!1)}},Ie=s===`hooks`?lt(p):{scripts:p},Le=`${yo}/workspaces/${e}/git/internal`;return(0,Z.jsxs)(`div`,{className:`@container space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 @3xl:flex-row @3xl:items-start @3xl:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 @3xl:min-w-[18rem] @3xl:flex-1`,children:[(0,Z.jsx)(`h3`,{className:`text-lg font-medium`,children:`Automation`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Rules are simple click-to-build automations (Outlook-style). Hooks are their programmable big brother; scripts are the shell helpers hooks spawn. Everything commits to the workspace git repo.`})]}),(0,Z.jsx)(`div`,{className:`flex min-w-0 flex-col gap-2 @3xl:max-w-[60%] @3xl:flex-row @3xl:items-center`,children:(0,Z.jsx)(`div`,{className:`w-full min-w-0 @3xl:w-auto`,children:(0,Z.jsx)(ce,{className:`border-b-0`,active:s,onChange:Ce,tabs:[{id:`pending`,label:de>0?`Pending (${de})`:`Pending`,icon:wr},{id:`rules`,label:`Rules`,icon:Ta},{id:`hooks`,label:`Hooks`,icon:or},{id:`scripts`,label:`Scripts`,icon:ai},{id:`runs`,label:`Runs`,icon:xr}]})})})]}),(s===`runs`||H)&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[s===`runs`&&(0,Z.jsxs)(Z.Fragment,{children:[ie&&(0,Z.jsxs)(`button`,{type:`button`,className:`inline-flex items-center gap-1 rounded-full border bg-muted/50 px-2.5 py-1 font-mono text-xs hover:bg-muted`,title:`Showing runs of this rule / hook only — click to clear`,onClick:()=>ae(null),children:[ie,` `,(0,Z.jsx)(vr,{className:`h-3 w-3`})]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:R,onChange:e=>re(e.target.checked)}),`failed only`]}),(0,Z.jsxs)(Y,{size:`sm`,variant:`ghost`,onClick:Se,title:`Reload`,children:[(0,Z.jsx)(Er,{className:`mr-1.5 h-4 w-4`}),` Reload`]})]}),H&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(Y,{size:`sm`,variant:`ghost`,onClick:Se,title:`Reload`,children:[(0,Z.jsx)(Er,{className:`mr-1.5 h-4 w-4`}),` Reload`]}),(0,Z.jsxs)(Y,{size:`sm`,variant:`ghost`,onClick:je,title:`Hook context API & classifier reference`,children:[(0,Z.jsx)(Ln,{className:`mr-1.5 h-4 w-4`}),` Reference`]}),(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,onClick:ke,children:[(0,Z.jsx)(br,{className:`mr-2 h-4 w-4`}),` `,s===`hooks`?`New Hook`:`New Script`]})]})]}),s===`pending`&&(0,Z.jsx)(wN,{workspaceId:e,onPendingCount:fe}),s===`rules`&&(0,Z.jsx)(Mn,{workspaceId:e,backfillLimit:he,onShowRuns:e=>{ae(e),Ce(`runs`)},prefill:t,onPrefillConsumed:n,onOpenJson:async()=>{try{await rt(e,`rules.json`)}catch{await Sn(e,`rules.json`,JSON.stringify({$schema:`canvas.hook-rules/v1`,rules:[]},null,2)+`
|