@augmentd-labs/canvas-web 2.26.29 → 2.26.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/assets/CalendarApplet-1-_9Pqfs.js +1 -0
  2. package/dist/assets/{FiltersApplet-C6-D-MEW.js → FiltersApplet-bF_7ntZU.js} +1 -1
  3. package/dist/assets/{HomeFab-DZbi60PC.js → HomeFab-B_AndThd.js} +1 -1
  4. package/dist/assets/{LensApplet-B9OaePzA.js → LensApplet-FoQc4ieR.js} +1 -1
  5. package/dist/assets/{NotesApplet-BM7ksdXl.js → NotesApplet-DfagszMP.js} +1 -1
  6. package/dist/assets/{_agentId_-CweMTe-q.js → _agentId_-GsPtoz9i.js} +0 -0
  7. package/dist/assets/{_contextId_-HAAoVKBa.js → _contextId_-xoan5Zgw.js} +1 -1
  8. package/dist/assets/{_workspaceName_-D79RwRsV.js → _workspaceName_-DfNeZ188.js} +1 -1
  9. package/dist/assets/{about-dr4T4ju8.js → about-DWl4-RY1.js} +1 -1
  10. package/dist/assets/{add-fha_SoND.js → add-AHQUHZBr.js} +1 -1
  11. package/dist/assets/{agents-CZgEe18J.js → agents-DT1XtFUN.js} +1 -1
  12. package/dist/assets/{appearance-SqhMHD_S.js → appearance-C8m9uEmD.js} +1 -1
  13. package/dist/assets/{apps-stCO1N5r.js → apps-DbYkQgyL.js} +1 -1
  14. package/dist/assets/backend-sync-progress-BJsLP7o5.js +7 -0
  15. package/dist/assets/{content-app-view-CotdPc2q.js → content-app-view-B4ada874.js} +1 -1
  16. package/dist/assets/{document-list-Cq4rdquK.js → document-list-CwStaizB.js} +1 -1
  17. package/dist/assets/{home-w5SlrNH7.js → home-BWAoF6jL.js} +1 -1
  18. package/dist/assets/{index-DGCnvWMM.js → index-D-y76fV7.js} +3 -3
  19. package/dist/assets/{key-bindings-5HbdLjsz.js → key-bindings-C3rMnRos.js} +1 -1
  20. package/dist/assets/{query-debug-B3pFyO8g.js → query-debug-CZacGe0M.js} +1 -1
  21. package/dist/assets/{registry-BRI7e6jw.js → registry-BEyieXxp.js} +2 -2
  22. package/dist/assets/{settings-Btb3SUu6.js → settings-BZsdOcHy.js} +1 -1
  23. package/dist/assets/{settings-UMBkdMdX.js → settings-CFbSvlXK.js} +1 -1
  24. package/dist/assets/{settings-y5FovQxO.js → settings-DD2zxZ8C.js} +1 -1
  25. package/dist/assets/{settings-D55sWdd2.js → settings-QL_HG2aL.js} +1 -1
  26. package/dist/assets/{share-target-5HoF3Y5a.js → share-target-pA9r0Obg.js} +1 -1
  27. package/dist/assets/{shared-B24deTOM.js → shared-ZTRGU8MK.js} +1 -1
  28. package/dist/assets/{use-canvas-pins-BZMaPpb7.js → use-canvas-pins-D-zi5fqQ.js} +1 -1
  29. package/dist/assets/{useAgentModels-vTfsjAwS.js → useAgentModels-fXPBeHX2.js} +1 -1
  30. package/dist/assets/{workspace-area-menu-COdiU0Xn.js → workspace-area-menu-DtsodEXC.js} +1 -1
  31. package/dist/assets/{workspaces-BBq3LOwy.js → workspaces-BZ395Y1p.js} +1 -1
  32. package/dist/index.html +6 -6
  33. package/dist/sw.js +1 -1
  34. package/package.json +2 -2
  35. package/dist/assets/CalendarApplet-CXG7O1QW.js +0 -1
  36. package/dist/assets/backend-sync-progress-DyvV8N9D.js +0 -7
@@ -1,9 +1,9 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/apps-stCO1N5r.js","assets/rolldown-runtime-C0FnF6B9.js","assets/code-editor-BOIngd5F.js","assets/chunk-62JRHF6Z-vspAGgtK.js","assets/preload-helper-Czpn1I53.js","assets/utils-2pl1SbIp.js","assets/utils-BxVxyehK.js","assets/workspace-46EFyEKZ.js","assets/react-BHzhHVTZ.js","assets/button-Bum-POPT.js","assets/ui-76Hw0NU_.js","assets/input-BOtCd4HP.js","assets/api-CA6WiiYM.js","assets/alert-dialog-CShuAcnP.js","assets/context-BGgz0Y_q.js","assets/registry-BRI7e6jw.js","assets/applet-target-Bl9Je1N-.js","assets/use-applet-target-DmIdCxa_.js","assets/use-toolbox-Ck_cLGgf.js","assets/workspaces-BBq3LOwy.js","assets/use-toast-BlLDqSUO.js","assets/use-mobile-Db-vWu9Y.js","assets/layer-style-Byl5LNFR.js","assets/color-DFEH4BfK.js","assets/workspace-access-C9nZlBBZ.js","assets/use-menu-CaiLyPdw.js","assets/last-path-BbXWC3b3.js","assets/url-params-n7kU_WZ-.js","assets/page-header-BoCaZiqu.js","assets/form-panel-DZj3WZ3z.js","assets/use-create-panel-DhSNIGtr.js","assets/useSocketSubscription-ifW-vnlb.js","assets/socket-hM4c-ZSl.js","assets/workspace-import-form-Bu1nlv8u.js","assets/_workspaceName_-D79RwRsV.js","assets/socket-CtH3EU9m.js","assets/use-canvas-pins-BZMaPpb7.js","assets/auth-Bx9fAZmz.js","assets/LinkToCard-VXpoeMDH.js","assets/useEscapeClose-DR_xKT_k.js","assets/useToastHelpers-CRrpIIdY.js","assets/DocumentIcon-ByDAILhm.js","assets/TodosWidget-CX4lgk-9.js","assets/ObjectPropertiesCard-CFZ_LqzX.js","assets/label-DJc8-3CQ.js","assets/IdentityFields-CEDxU-Hd.js","assets/tags-YamdPoBK.js","assets/useAddTarget-D4ra50Am.js","assets/date-time-picker-Bzu8H_Oa.js","assets/relation-events-CKio19hE.js","assets/map-BxCwdK0d.js","assets/map-BcsP_QXj.css","assets/public-share-D2S8DEsv.js","assets/text-documents-CFW8MWES.js","assets/blobs-WiXP9QRi.js","assets/useDocumentThumbnail-Bs2Ju0eb.js","assets/markdown-view-BBBZtNSR.js","assets/sanitize-DrVcFY1Q.js","assets/MessageComposerDialog-BKGlI7jO.js","assets/markdown-it-DRESbtwK.js","assets/punycode.es6-ZbLrB_Dn.js","assets/lazy-editor-Bdm5JEXv.js","assets/LinkToSidePanel-eCy3nW4R.js","assets/note-save-status-DPz4VzL6.js","assets/useEditNoteFields-CKYMBf8V.js","assets/DocumentBodyEditor-DRFQgBNB.js","assets/use-document-modal-PG8bQyIB.js","assets/sketch-lazy-BOFTGGTA.js","assets/geo-CZfs0E-x.js","assets/ObjectPropertiesCard-JArcZXXv.css","assets/document-list-Cq4rdquK.js","assets/document-open-mode-DoImW-xs.js","assets/PickDocumentsCard-B72XNYh3.js","assets/backend-sync-progress-DyvV8N9D.js","assets/PathPickerField-B58yeJGw.js","assets/backend-sync-progress-DU-e9TWi.css","assets/search-COMZIxA7.js","assets/use-sortable-data-W2inLcb5.js","assets/workspace-BydSRtST.js","assets/document-list-DAYdk5vh.css","assets/use-canvas-pins-C57Vbkrq.css","assets/workspace-area-menu-COdiU0Xn.js","assets/workspace-content-gate-CGZmT2kw.js","assets/content-app-view-CotdPc2q.js","assets/FileForm-B6eFRKG-.js","assets/UploadProgressList-CHQ-Kn-e.js","assets/sha256-65KIjGvZ.js","assets/query-debug-B3pFyO8g.js","assets/document-Ds_P5v-f.js","assets/use-workspace-identity-KxY9injc.js","assets/home-w5SlrNH7.js","assets/HomeFab-DZbi60PC.js","assets/desk-dI_FvLsK.js","assets/share-target-5HoF3Y5a.js","assets/contexts-CwGdjtXy2.js","assets/_contextId_-HAAoVKBa.js","assets/api-tokens-CmHhwd58.js","assets/use-settings-back-DE0SPb7h.js","assets/devices-CmVlYbam.js","assets/devices-CAa1bRxk.js","assets/settings-UMBkdMdX.js","assets/appearance-SqhMHD_S.js","assets/use-theme-DaxpiICf.js","assets/key-bindings-5HbdLjsz.js","assets/offline-yfQ63Zr7.js","assets/about-dr4T4ju8.js","assets/embedding-2EjzoVFT.js","assets/inferd-config-editor-CyDCQJRs.js","assets/shared-B24deTOM.js","assets/workspaces-p959p9BR.js","assets/admin-Bhg9QBHL.js","assets/contexts-Dtl9oERX.js","assets/agents-DEJU4O1Z.js","assets/logs-DUeiDqCX.js","assets/roles-BHJYWaBs.js","assets/role-C5I0Plgn.js","assets/users-DInwKAxz.js","assets/embedding-BqI3l5RB.js","assets/auth-_bmIEN02.js","assets/agents-CZgEe18J.js","assets/useAgentModels-vTfsjAwS.js","assets/_agentId_-CweMTe-q.js","assets/settings-Btb3SUu6.js","assets/settings-y5FovQxO.js","assets/settings-D55sWdd2.js","assets/roles-CuqCEPC7.js","assets/remotes-BjjlqN_M.js","assets/add-fha_SoND.js","assets/NextShell-BvKyH2Oj.js","assets/NextShell-BT6-_CFY.css"])))=>i.map(i=>d[i]);
2
- import{o as e,r as t}from"./rolldown-runtime-C0FnF6B9.js";import{l as n,u as r}from"./code-editor-BOIngd5F.js";import{_t as i,st as a,vt as o,yt as s}from"./react-BHzhHVTZ.js";import{t as c}from"./preload-helper-Czpn1I53.js";import{_ as l,a as u,c as d,d as f,f as p,g as m,h,i as g,l as _,m as v,n as y,o as b,p as x,r as S,s as C,t as w,u as T,v as E}from"./chunk-62JRHF6Z-vspAGgtK.js";import{$r as D,$t as O,Ar as k,B as A,Bn as j,Br as M,Bt as N,C as ee,Ct as P,En as te,F as ne,Fr as re,Ft as ie,Gr as F,Gt as ae,H as oe,Hn as I,Hr as se,Ht as ce,I as le,In as ue,It as L,J as R,Jn as de,L as z,Lr as B,Lt as V,Mn as fe,Nn as H,Nr as pe,On as me,P as he,Pt as ge,Q as _e,Qn as ve,Qt as U,R as ye,Rt as W,S as be,Sn as xe,Sr as Se,Tr as Ce,Tt as we,U as Te,Un as Ee,Ur as De,Ut as Oe,V as ke,Vr as Ae,Vt as je,W as Me,Wn as Ne,Wr as Pe,X as Fe,Xr as Ie,Xt as Le,Yn as Re,Zn as ze,Zr as Be,_ as Ve,_i as He,_n as Ue,_t as We,an as Ge,b as Ke,bn as qe,br as Je,cn as Ye,cr as Xe,ct as Ze,d as Qe,dn as $e,er as et,f as tt,fi as nt,fn as rt,fr as it,g as at,gi as ot,gr as st,gt as ct,h as lt,hi as ut,hn as dt,hr as ft,ht as pt,ii as mt,in as ht,kr as gt,kt as _t,li as vt,ln as yt,lt as bt,m as xt,mr as St,mt as Ct,nn as wt,or as Tt,p as Et,pn as Dt,qn as Ot,qr as kt,rt as At,sn as jt,tr as Mt,tt as Nt,u as Pt,un as Ft,ut as It,v as Lt,vi as Rt,vn as zt,vr as Bt,vt as Vt,w as Ht,x as Ut,xn as Wt,xr as Gt,xt as Kt,y as qt,yt as Jt,z as Yt,zr as Xt}from"./ui-76Hw0NU_.js";import{i as Zt,r as Qt}from"./utils-BxVxyehK.js";import{n as $t,t as G}from"./utils-2pl1SbIp.js";import{t as K}from"./button-Bum-POPT.js";import{t as en}from"./input-BOtCd4HP.js";import{t as q}from"./label-DJc8-3CQ.js";import{a as tn,c as nn,i as rn,l as J,n as an,o as on,r as sn,s as cn,t as Y,u as ln}from"./api-CA6WiiYM.js";import{t as un}from"./socket-hM4c-ZSl.js";import{t as X}from"./socket-CtH3EU9m.js";import{a as dn,c as fn,d as pn,i as mn,l as hn,n as gn,o as _n,r as vn,s as yn,t as bn}from"./auth-Bx9fAZmz.js";import{n as xn,t as Sn}from"./use-toast-BlLDqSUO.js";import{_ as Cn,h as wn,m as Tn,p as En,t as Dn}from"./LinkToCard-VXpoeMDH.js";import{An as On,B as kn,Bt as An,C as jn,Cn as Mn,Dn as Nn,Dt as Pn,E as Fn,G as In,Lt as Ln,Nt as Rn,O as zn,On as Bn,Pn as Vn,Pt as Hn,Q as Un,S as Wn,Sn as Gn,St as Kn,Tt as qn,V as Jn,Xt as Yn,Zt as Xn,_ as Zn,_n as Qn,b as $n,bn as er,c as tr,gt as nr,h as rr,hn as ir,ht as ar,jt as or,lt as sr,mn as cr,mt as lr,on as ur,r as dr,sn as fr,tt as pr,vn as mr,xn as hr,yt as gr,zt as _r}from"./workspace-46EFyEKZ.js";import{r as vr,t as yr}from"./use-canvas-pins-BZMaPpb7.js";import{a as br,i as xr,n as Sr,o as Cr,r as wr}from"./ObjectPropertiesCard-CFZ_LqzX.js";import{c as Tr,d as Er,f as Dr,i as Or,m as kr,n as Ar,p as jr,s as Mr,u as Nr}from"./document-list-Cq4rdquK.js";import{n as Pr,t as Fr}from"./use-mobile-Db-vWu9Y.js";import{a as Ir,i as Lr,s as Rr,t as zr}from"./IdentityFields-CEDxU-Hd.js";import{n as Br,t as Vr}from"./public-share-D2S8DEsv.js";import{t as Hr}from"./markdown-view-BBBZtNSR.js";import{n as Ur,t as Wr}from"./tags-YamdPoBK.js";import{a as Gr,c as Kr,i as qr,l as Jr,n as Yr,o as Xr,r as Zr,s as Qr,t as $r,u as ei}from"./useAddTarget-D4ra50Am.js";import{n as ti,r as ni,t as ri}from"./use-toolbox-Ck_cLGgf.js";import{D as ii,E as ai,O as oi,a as si,p as ci,s as li,v as ui,w as di}from"./context-BGgz0Y_q.js";import{r as fi}from"./relation-events-CKio19hE.js";import{c as pi}from"./date-time-picker-Bzu8H_Oa.js";import{t as mi}from"./PickDocumentsCard-B72XNYh3.js";import{t as hi}from"./useEscapeClose-DR_xKT_k.js";import{t as gi}from"./useToastHelpers-CRrpIIdY.js";import{a as _i,c as vi,d as yi,l as bi,s as xi}from"./layer-style-Byl5LNFR.js";import{i as Si,r as Ci}from"./color-DFEH4BfK.js";import{n as wi}from"./MessageComposerDialog-BKGlI7jO.js";import{n as Ti,t as Ei}from"./LinkToSidePanel-eCy3nW4R.js";import{n as Di,r as Oi,t as ki}from"./note-save-status-DPz4VzL6.js";import{t as Ai}from"./useEditNoteFields-CKYMBf8V.js";import{t as ji}from"./DocumentBodyEditor-DRFQgBNB.js";import{n as Mi,t as Ni}from"./map-BxCwdK0d.js";import{o as Pi}from"./blobs-WiXP9QRi.js";import{n as Fi,t as Ii}from"./use-document-modal-PG8bQyIB.js";import{n as Li,r as Ri}from"./geo-CZfs0E-x.js";import{C as zi,W as Bi,_ as Vi,c as Hi,g as Ui,i as Wi,s as Gi,y as Ki,z as qi}from"./backend-sync-progress-DyvV8N9D.js";import{t as Ji}from"./workspace-access-C9nZlBBZ.js";import{t as Yi}from"./PathPickerField-B58yeJGw.js";import{a as Xi,c as Zi,i as Qi,o as $i,r as ea,s as ta,t as na}from"./workspace-BydSRtST.js";import{n as ra,t as ia}from"./url-params-n7kU_WZ-.js";import{a as aa,c as oa,d as sa,f as ca,i as la,m as ua,n as da,p as fa,r as pa,t as ma}from"./use-menu-CaiLyPdw.js";import{n as ha,t as ga}from"./registry-BRI7e6jw.js";import{n as _a}from"./use-applet-target-DmIdCxa_.js";import{r as va,t as ya}from"./last-path-BbXWC3b3.js";import{t as ba}from"./workspace-area-menu-COdiU0Xn.js";import{t as xa}from"./workspace-content-gate-CGZmT2kw.js";import{c as Sa,s as Ca}from"./UploadProgressList-CHQ-Kn-e.js";import{n as wa,r as Ta,t as Ea}from"./FileForm-B6eFRKG-.js";import{n as Da}from"./use-theme-DaxpiICf.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 Z=e(r(),1),Oa=o(),Q=n(),ka=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(`div`,{ref:n,className:G(`rounded-(--card-radius) border bg-card text-card-foreground shadow-elevation-1`,e),...t}));ka.displayName=`Card`;var Aa=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(`div`,{ref:n,className:G(`flex flex-col space-y-1.5 p-6`,e),...t}));Aa.displayName=`CardHeader`;var ja=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(`h3`,{ref:n,className:G(`text-2xl font-semibold leading-none tracking-tight`,e),...t}));ja.displayName=`CardTitle`;var Ma=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(`p`,{ref:n,className:G(`text-sm text-muted-foreground`,e),...t}));Ma.displayName=`CardDescription`;var Na=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(`div`,{ref:n,className:G(`p-6 pt-0`,e),...t}));Na.displayName=`CardContent`;var Pa=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(`div`,{ref:n,className:G(`flex items-center p-6 pt-0`,e),...t}));Pa.displayName=`CardFooter`;var Fa=`2.26.29`,Ia=e=>{window.particlesJS.load(e,`/js/particles.config.json`,()=>{console.log(`particles.js config loaded for`,e)})};function La(e){(0,Z.useEffect)(()=>{if(window.particlesJS!==void 0)Ia(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`),Ia(e)},document.head.appendChild(t)}return()=>{window.pJS&&window.pJS[e]?.destroy&&window.pJS[e].destroy()}},[e])}function Ra(){let[e,t]=(0,Z.useState)(null),[n,r]=(0,Z.useState)(!0),[i,a]=(0,Z.useState)(null);return(0,Z.useEffect)(()=>{let e=!0;async function n(){try{r(!0),a(null);let n=await Y.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 za=`https://github.com/canvas-ui/canvas-server`,Ba=null;function Va(){return Ba||=Y.get(`/ping`,{skipAuth:!0}).then(e=>{let t=e??{};return{sourceUrl:t.sourceUrl||za,version:t.version??null,commit:t.commit??null,license:t.license??null}}).catch(e=>(console.error(`Failed to fetch server source info:`,e),Ba=null,{sourceUrl:za,version:null,commit:null,license:null})),Ba}function Ha(){let[e,t]=(0,Z.useState)(null);return(0,Z.useEffect)(()=>{let e=!0;return Va().then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function Ua({className:e=``}){let t=Ha();if(!t)return null;let n=[t.version?`v${t.version}`:null,t.commit?.slice(0,7)].filter(Boolean).join(` `);return(0,Q.jsxs)(`p`,{className:`text-xs text-muted-foreground ${e}`,children:[`Powered by`,` `,(0,Q.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,Q.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})}function Wa({children:e}){La(`particle-js`);let{serverVersion:t,isLoading:n,error:r}=Ra();return(0,Q.jsx)(`div`,{className:`flex min-h-viewport w-full items-center justify-center p-4 flex-col`,children:(0,Q.jsxs)(ka,{className:`flex w-[95vw] h-viewport-modal overflow-hidden`,children:[(0,Q.jsxs)(`div`,{className:`hidden md:block w-1/2 relative bg-background`,"data-scheme":`dark`,id:`particle-js`,children:[(0,Q.jsxs)(S,{className:`absolute top-8 left-8 font-bold text-foreground flex items-center z-raised`,to:`/`,children:[(0,Q.jsx)(`img`,{src:`/images/logo-wr_128x128.png`,alt:`Canvas Logo`,className:`mr-2 h-6 w-6 touch-target`}),(0,Q.jsx)(`span`,{className:`text-2xl font-bold text-foreground`,children:`Canvas`})]}),(0,Q.jsxs)(`div`,{className:`absolute bottom-8 left-8 text-sm text-foreground max-w-[80%] z-raised`,children:[`Web UI: v`,Fa,`, Server: `,n?`Loading...`:r?`Unavailable`:t?`v${t}`:`Unknown`]})]}),(0,Q.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,Q.jsxs)(`div`,{className:`mx-auto w-full max-w-sm`,children:[e,(0,Q.jsxs)(`div`,{className:`mt-8 border-t pt-6`,children:[(0,Q.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,Q.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,Q.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,Q.jsx)(`span`,{children:`View on GitHub`})]}),(0,Q.jsx)(Ua,{className:`mt-4 text-center`})]})]})})]})})}var Ga=e=>e?.strategies?.local?.enabled!==!1,Ka=e=>e?.allowUserRegistrations!==!1;function qa(){let e=m(),[t,n]=Z.useState(!1),[r,a]=Z.useState(``),[o,s]=Z.useState(``),[c,l]=Z.useState(!1),[u,d]=Z.useState({}),[f,p]=Z.useState(null),[h,g]=Z.useState({email:``,password:``,strategy:`auto`});Z.useEffect(()=>{dn()&&e(`/workspaces`),fetch(`${J}/runtime/capabilities`).then(e=>e.ok?e.json():null).then(e=>n(e?.payload?.local===!0)).catch(()=>{}),gn().then(e=>{p(e)}).catch(e=>{console.error(`Failed to load auth config:`,e)})},[e]);let _=()=>{let e={};return h.email?/\S+@\S+\.\S+/.test(h.email)||(e.email=`Email is invalid`):e.email=`Email is required`,h.password||(e.password=`Password is required`),d(e),Object.keys(e).length===0},v=e=>{let{name:t,value:n}=e.target;g(e=>({...e,[t]:n}))};async function y(t){if(t.preventDefault(),_()){l(!0);try{console.log(`Attempting login with:`,h.email,`strategy:`,h.strategy);let t=await fn(h.email,h.password,h.strategy);console.log(`Login successful, received token:`,`token`in t?!!t.token:!!t.payload?.token),d({}),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)}d({password:t})}finally{l(!1)}}}return t?(0,Q.jsx)(Wa,{children:(0,Q.jsxs)(`form`,{className:`grid gap-4`,onSubmit:async t=>{t.preventDefault(),l(!0),s(``);try{if(Y.setAuthToken(r.trim()),!await vn())throw Error(`The local token was not accepted`);e(`/workspaces`)}catch(e){Y.clearAuthToken(),s(e instanceof Error?e.message:`Authentication failed`)}finally{l(!1)}},children:[(0,Q.jsx)(`h1`,{className:`text-2xl font-semibold`,children:`Connect to your local runtime`}),(0,Q.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Enter the token shown by `,(0,Q.jsx)(`code`,{children:`canvas runtime token`}),` in the runtime folder.`]}),(0,Q.jsx)(q,{htmlFor:`local-token`,children:`Local access token`}),(0,Q.jsx)(en,{id:`local-token`,type:`password`,autoComplete:`off`,value:r,onChange:e=>a(e.target.value),required:!0}),o&&(0,Q.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:o}),(0,Q.jsx)(K,{disabled:c,children:c?`Connecting…`:`Connect`})]})}):(0,Q.jsx)(Wa,{children:(0,Q.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Q.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Welcome back`}),(0,Q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your credentials to access your account`})]}),(0,Q.jsx)(`form`,{onSubmit:y,children:(0,Q.jsxs)(`div`,{className:`grid gap-4`,children:[f?.strategies?.imap?.enabled&&f.strategies.imap.domains.length>0&&(0,Q.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Q.jsx)(q,{htmlFor:`strategy`,children:`Authentication Method`}),(0,Q.jsxs)(`select`,{id:`strategy`,name:`strategy`,value:h.strategy,onChange:v,disabled:c,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,Q.jsx)(`option`,{value:`auto`,children:`Auto-detect`}),(0,Q.jsx)(`option`,{value:`local`,children:`Local Account`}),(0,Q.jsx)(`option`,{value:`imap`,children:`Email Server (IMAP)`})]})]}),(0,Q.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Q.jsx)(q,{htmlFor:`email`,children:`Email`}),(0,Q.jsx)(en,{id:`email`,name:`email`,placeholder:`name@example.com`,type:`email`,autoCapitalize:`none`,autoComplete:`email`,autoCorrect:`off`,disabled:c,value:h.email,onChange:v}),u.email&&(0,Q.jsx)(`p`,{className:`text-sm text-destructive`,children:u.email})]}),(0,Q.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Q.jsx)(q,{htmlFor:`password`,children:`Password`}),(0,Q.jsx)(en,{id:`password`,name:`password`,type:`password`,disabled:c,value:h.password,onChange:v}),u.password&&(0,Q.jsx)(`p`,{className:`text-sm text-destructive`,children:u.password})]}),(0,Q.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,Q.jsx)(K,{type:`submit`,disabled:c,children:c?`Signing in...`:`Sign In`}),f?.strategies?.google?.enabled&&(0,Q.jsxs)(K,{type:`button`,variant:`outline`,disabled:c,onClick:()=>pn(),children:[(0,Q.jsx)(i,{icon:`logos:google-icon`,width:16,height:16,className:`mr-2`}),`Sign in with Google`]}),Ga(f)&&Ka(f)&&(0,Q.jsx)(K,{variant:`outline`,type:`button`,disabled:c,onClick:()=>e(`/register`),children:`Don't have an account? Sign up`})]})]})})]})})}function Ja(){let e=m(),{showToast:t}=xn(),[n,r]=Z.useState(!1),[i,a]=Z.useState({}),[o,s]=Z.useState({name:``,email:``,password:``}),[c,l]=Z.useState(!1),[u,d]=Z.useState(!1),[f,p]=Z.useState(null);Z.useEffect(()=>{(async()=>{let t=await gn(),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 h=Z.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]),g=()=>{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},_=e=>{let t={...o,[e.target.id]:e.target.value};s(t),(e.target.id===`name`||e.target.id===`email`||e.target.id===`password`)&&g()};return c?(0,Q.jsxs)(Wa,{children:[(0,Q.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Q.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Registration Successful!`}),(0,Q.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,Q.jsx)(`div`,{className:`space-y-6 text-center pt-6`,children:!u&&(0,Q.jsx)(K,{asChild:!0,className:`w-full`,children:(0,Q.jsx)(S,{to:`/login`,children:`Go to Login`})})})]}):(0,Q.jsxs)(Wa,{children:[(0,Q.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Q.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Create an account`}),(0,Q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your email below to create your account`})]}),(0,Q.jsxs)(`form`,{onSubmit:async e=>{if(e.preventDefault(),g()){r(!0);try{let e=await hn(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,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(q,{htmlFor:`name`,children:`Username`}),(0,Q.jsx)(en,{id:`name`,type:`text`,placeholder:`Enter your username (e.g., john_doe)`,value:o.name,onChange:_,disabled:n,className:i.name?`border-destructive`:``}),i.name&&(0,Q.jsx)(`p`,{className:`text-sm text-destructive`,children:i.name}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`3-39 characters, lowercase letters, numbers, underscores, and hyphens only`})]}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(q,{htmlFor:`email`,children:`Email`}),(0,Q.jsx)(en,{id:`email`,type:`email`,placeholder:`name@example.com`,value:o.email,onChange:_,disabled:n,className:i.email?`border-destructive`:``}),i.email&&(0,Q.jsx)(`p`,{className:`text-sm text-destructive`,children:i.email})]}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(q,{htmlFor:`password`,children:`Password`}),(0,Q.jsx)(en,{id:`password`,type:`password`,placeholder:`Enter your password`,value:o.password,onChange:_,disabled:n,className:i.password?`border-destructive`:``}),i.password&&(0,Q.jsx)(`p`,{className:`text-sm text-destructive`,children:i.password}),f&&h&&(0,Q.jsxs)(`ul`,{className:`text-xs list-disc pl-4 space-y-1`,children:[(0,Q.jsxs)(`li`,{className:h.minLength?`text-success`:`text-muted-foreground`,children:[`At least `,f.minLength,` characters`]}),f.requireUppercase&&(0,Q.jsx)(`li`,{className:h.uppercase?`text-success`:`text-muted-foreground`,children:`At least one uppercase letter`}),f.requireLowercase&&(0,Q.jsx)(`li`,{className:h.lowercase?`text-success`:`text-muted-foreground`,children:`At least one lowercase letter`}),f.requireNumbers&&(0,Q.jsx)(`li`,{className:h.number?`text-success`:`text-muted-foreground`,children:`At least one number`}),f.requireSpecialChars&&(0,Q.jsx)(`li`,{className:h.special?`text-success`:`text-muted-foreground`,children:`At least one special character`}),f.maxLength&&(0,Q.jsxs)(`li`,{className:h.maxLength?`text-success`:`text-muted-foreground`,children:[`No more than `,f.maxLength,` characters`]})]})]}),(0,Q.jsx)(K,{type:`submit`,className:`w-full`,disabled:n,children:n?`Creating Account...`:`Create Account`})]}),(0,Q.jsxs)(`div`,{className:`mt-4 text-center text-sm`,children:[`Already have an account?`,` `,(0,Q.jsx)(S,{to:`/login`,className:`underline`,children:`Sign in`})]}),(0,Q.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,Q.jsx)(S,{to:`/terms`,className:`underline underline-offset-4 hover:text-primary`,children:`Terms of Service`}),` `,`and`,` `,(0,Q.jsx)(S,{to:`/privacy`,className:`underline underline-offset-4 hover:text-primary`,children:`Privacy Policy`}),`.`]})]})}function Ya(){let e=m(),[t]=E(),[n,r]=Z.useState(t.get(`error`)),i=Z.useRef(!1);return Z.useEffect(()=>{let n=t.get(`code`);!n||i.current||(i.current=!0,bn(n).then(()=>e(`/home`,{replace:!0})).catch(e=>r(e instanceof Error?e.message:`Google sign-in failed`)))},[t,e]),(0,Q.jsx)(Wa,{children:(0,Q.jsx)(`div`,{className:`flex flex-col space-y-4 text-center`,children:n?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Google sign-in failed`}),(0,Q.jsx)(`p`,{className:`text-sm text-destructive`,children:n}),(0,Q.jsx)(K,{type:`button`,variant:`outline`,onClick:()=>e(`/login`,{replace:!0}),children:`Back to sign in`})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Signing you in…`}),(0,Q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Completing Google sign-in.`})]})})})}function Xa({children:e}){let[t,n]=(0,Z.useState)(`loading`);return(0,Z.useEffect)(()=>{(async()=>{try{if(!_n()){console.log(`No authentication token found, redirecting to login`),n(`unauthenticated`);return}let e=await vn();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),yn(e)){if(dn()){n(`authenticated`);return}Y.clearAuthToken(),n(`unauthenticated`);return}e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from ProtectedRoute`),Y.clearAuthToken()),n(`unauthenticated`)}})()},[]),t===`loading`?(0,Q.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,Q.jsx)(Cn,{className:`h-8 w-8`})}):t===`unauthenticated`?(0,Q.jsx)(u,{to:`/login`,replace:!0}):(0,Q.jsx)(Q.Fragment,{children:e})}function Za({children:e}){let[t,n]=(0,Z.useState)(null);return(0,Z.useEffect)(()=>{(async()=>{try{await Y.get(`/auth/me`),n(!0)}catch(e){e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from PublicRoute`),Y.clearAuthToken()),n(!1)}})()},[]),t===null?null:t?(0,Q.jsx)(u,{to:`/workspaces`,replace:!0}):(0,Q.jsx)(Q.Fragment,{children:e})}var Qa=`data/schema/file`;function $a(e){return String(e.locations?.[0]?.url||``).trim()}function eo(e){let t=$a(e);if(!t)return``;let n=t.split(/[?#]/)[0].split(`/`).filter(Boolean).pop()||``;try{return decodeURIComponent(n)}catch{return n}}function to(e){return e.schema===Qa&&String(e.metadata?.contentType||``).startsWith(`image/`)}function no(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 ro(e){if(e.schema!==Qa)return On(e);let t=eo(e),n=String(e.metadata?.contentType||``).trim(),r=no(e.metadata?.size);return{...On(e),title:t||`File ${e.id}`,preview:[n,r].filter(Boolean).join(` · `),subtitle:$a(e),schemaLabel:`file`}}function io(e){return/^https?:\/\/[^\s]+$/i.test(e)}function ao(e,t){if(e.schema===`data/schema/tab`){let t=String(e.data?.url||``).trim();return io(t)?t:null}return t.isExternal&&io(t.subtitle)?t.subtitle:io(t.title)?t.title:null}function oo(e,t,n=!1){return Br(e,t,{download:n})}function so(e){return e.split(/(https?:\/\/[^\s]+)/gi).map((e,t)=>io(e)?(0,Q.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 co(e){return e?new Date(e).toLocaleString():``}function lo(){let{code:e=``}=l(),[t,n]=(0,Z.useState)(null),[r,i]=(0,Z.useState)(!0),[a,o]=(0,Z.useState)(null),[s,c]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(``),f=(0,Z.useMemo)(()=>t?.documents?Array.isArray(t.documents)?t.documents:t.documents.data||[]:[],[t]),p=(0,Z.useMemo)(()=>{let e=u.trim().toLowerCase();return e?f.filter(t=>{let n=ro(t);return[t.schema,n.title,n.preview,n.subtitle,eo(t),t.metadata?.contentType].join(` `).toLowerCase().includes(e)}):f},[f,u]),m=(0,Z.useCallback)(async()=>{if(e){i(!0);try{let t=await Y.get(`${J}/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,Z.useEffect)(()=>{m()},[m]),(0,Z.useEffect)(()=>{if(!e)return;let t=un(`${ln}/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`,()=>m()),()=>{t?.disconnect(),t=null}},[e,m]);let h=(0,Z.useCallback)(e=>{e?.preventDefault(),d(u.trim())},[u]),g=(0,Z.useCallback)(()=>{d(``)},[]),_=(0,Z.useCallback)(async e=>({payload:Nn(e?.sortBy)?Bn(f,e.sortBy,e?.order):f,totalCount:t?.stats.documentCount??f.length}),[f,t]);if(r&&!t)return(0,Q.jsx)(`main`,{className:`min-h-screen bg-muted flex items-center justify-center p-6`,children:(0,Q.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Loading canvas...`})});if(a||!t)return(0,Q.jsxs)(`main`,{className:`min-h-screen bg-muted flex flex-col items-center justify-center p-6`,children:[(0,Q.jsxs)(ka,{className:`max-w-md bg-card`,children:[(0,Q.jsx)(Aa,{children:(0,Q.jsx)(ja,{children:`Canvas unavailable`})}),(0,Q.jsx)(Na,{className:`text-sm text-muted-foreground`,children:a||`This public canvas does not exist.`})]}),(0,Q.jsx)(Ua,{className:`mt-6 text-center`})]});let v=t.canvas.metadata?.ui??{},y=!!v.widgets&&Object.keys(v.widgets).length>0;return(0,Q.jsx)(Vr.Provider,{value:e,children:(0,Q.jsx)(`main`,{className:`min-h-screen bg-muted p-2 text-foreground sm:p-4 md:p-10`,children:(0,Q.jsxs)(`div`,{className:`mx-auto max-w-6xl`,children:[(0,Q.jsxs)(ka,{className:`bg-card shadow-elevation-3`,children:[(0,Q.jsx)(Aa,{className:`border-b p-3 sm:p-6`,children:(0,Q.jsxs)(`div`,{className:`flex flex-col gap-3 md:flex-row md:items-start md:justify-between md:gap-4`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 gap-3 sm:gap-4`,children:[(0,Q.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,Q.jsx)(qe,{className:`h-5 w-5 sm:h-6 sm:w-6`})}),(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`span`,{className:`truncate text-xs uppercase tracking-wide text-muted-foreground`,children:t.workspace.label||t.workspace.name}),(0,Q.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,Q.jsx)(Yt,{className:`h-3 w-3 text-success`}):(0,Q.jsx)(A,{className:`h-3 w-3 text-muted-foreground`}),s?`Live`:`Offline`]})]}),(0,Q.jsx)(ja,{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,Q.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,Q.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,Q.jsx)(Yt,{className:`h-3.5 w-3.5 text-success`}):(0,Q.jsx)(A,{className:`h-3.5 w-3.5 text-muted-foreground`}),s?`Live`:`Offline`]})]})}),(0,Q.jsxs)(Na,{className:`space-y-4 p-3 sm:space-y-6 sm:p-6 md:p-8`,children:[(0,Q.jsxs)(`section`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1 text-xs text-muted-foreground md:hidden`,children:[(0,Q.jsx)(`span`,{className:`w-full truncate font-mono text-foreground`,children:t.share.path}),(0,Q.jsxs)(`span`,{className:`tabular-nums`,children:[t.stats.documentCount,` docs`]}),p.length!==t.stats.documentCount&&(0,Q.jsxs)(`span`,{className:`tabular-nums`,children:[`· `,p.length,` shown`]}),(0,Q.jsxs)(`span`,{className:`truncate`,children:[`· `,co(t.stats.refreshedAt)]})]}),(0,Q.jsxs)(`section`,{className:`hidden gap-3 md:grid md:grid-cols-4`,children:[(0,Q.jsx)(uo,{label:`Path`,value:t.share.path,mono:!0}),(0,Q.jsx)(uo,{label:`Documents`,value:String(t.stats.documentCount)}),(0,Q.jsx)(uo,{label:`Shown`,value:String(p.length)}),(0,Q.jsx)(uo,{label:`Refreshed`,value:co(t.stats.refreshedAt)})]}),y&&(0,Q.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,Q.jsx)(vr,{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:_},JSON.stringify(v))}),!y&&(0,Q.jsxs)(`section`,{className:`rounded-2xl border`,children:[(0,Q.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,Q.jsx)(`h2`,{className:`font-semibold`,children:`Content`}),(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2 md:flex-row md:items-center`,children:[(0,Q.jsxs)(`form`,{onSubmit:h,className:`flex min-w-0 items-center gap-2`,children:[(0,Q.jsxs)(`div`,{className:`relative min-w-0`,children:[(0,Q.jsx)(Jt,{className:`pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground`}),(0,Q.jsx)(`input`,{type:`search`,value:u,onChange:e=>d(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`}),u&&(0,Q.jsx)(`button`,{type:`button`,onClick:g,className:`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,"aria-label":`Clear search`,children:(0,Q.jsx)(z,{className:`h-4 w-4`})})]}),(0,Q.jsx)(`button`,{type:`submit`,className:`rounded-md border px-3 py-1.5 text-xs hover:bg-muted`,children:`Search`})]}),(0,Q.jsxs)(`button`,{type:`button`,onClick:m,className:`inline-flex items-center justify-center gap-2 rounded-md border px-3 py-1.5 text-xs hover:bg-muted`,children:[(0,Q.jsx)(_t,{className:`h-3.5 w-3.5 ${r?`animate-spin`:``}`}),`Refresh`]})]})]}),u.trim()&&(0,Q.jsxs)(`div`,{className:`border-b bg-muted px-4 py-2 text-xs text-muted-foreground`,children:[`Local search: `,(0,Q.jsxs)(`span`,{className:`font-mono`,children:[`"`,u.trim(),`"`]})]}),(0,Q.jsx)(`div`,{className:`divide-y`,children:p.length===0?(0,Q.jsx)(`div`,{className:`p-8 text-center text-sm text-muted-foreground`,children:u.trim()?`No loaded documents match your search.`:`No documents yet.`}):p.map(t=>{let n=ro(t),r=ao(t,n),i=t.schema===Qa,a=i?oo(e,t.id):null,o=a||r;return(0,Q.jsxs)(`article`,{className:`p-4`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col gap-1 md:flex-row md:items-start md:justify-between`,children:[(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`h3`,{className:`truncate font-medium`,children:o?(0,Q.jsx)(`a`,{href:o,target:`_blank`,rel:`noreferrer`,className:`hover:text-primary hover:underline`,children:n.title}):n.title}),(0,Q.jsx)(`div`,{className:`mt-1 font-mono text-xs text-muted-foreground`,children:n.schemaLabel})]}),(0,Q.jsxs)(`div`,{className:`flex shrink-0 items-center gap-3`,children:[i&&(0,Q.jsxs)(`a`,{href:oo(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,Q.jsx)(Bt,{className:`h-3.5 w-3.5`}),`Download`]}),(0,Q.jsx)(`time`,{className:`text-xs text-muted-foreground`,children:co(t.updatedAt||t.createdAt)})]})]}),n.preview&&(0,Q.jsx)(`p`,{className:`mt-3 line-clamp-3 text-sm leading-6 text-foreground`,children:so(n.preview)}),to(t)&&(0,Q.jsx)(`a`,{href:a||void 0,target:`_blank`,rel:`noreferrer`,className:`mt-3 block w-fit`,children:(0,Q.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,Q.jsx)(Ua,{className:`mt-6 text-center`})]})})})}function uo({label:e,value:t,mono:n=!1}){return(0,Q.jsxs)(`div`,{className:`min-w-0 rounded-xl border bg-muted p-4`,children:[(0,Q.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:e}),(0,Q.jsx)(`div`,{className:`mt-2 truncate text-lg font-semibold ${n?`font-mono text-sm`:``}`,children:t||`-`})]})}var fo=`false`,po=`false`,mo=fo===`true`,ho=po===`true`;function go(e={}){let{immediate:t=!1,onNeedReload:n,onNeedRefresh:r,onOfflineReady:i,onRegistered:a,onRegisteredSW:o,onRegisterError:s}=e,l,u,d,f=async(e=!0)=>{await u,mo||d?.()};async function p(){if(`serviceWorker`in navigator){if(l=await c(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)}),!l)return;if(d=()=>{l?.messageSkipWaiting()},!ho){if(mo)l.addEventListener(`activated`,e=>{(e.isUpdate||e.isExternal)&&(n?n():window.location.reload())}),l.addEventListener(`installed`,e=>{e.isUpdate||i?.()});else{let e=!1,t=()=>{e=!0,l?.addEventListener(`controlling`,e=>{e.isUpdate&&(n?n():window.location.reload())}),r?.()};l.addEventListener(`installed`,n=>{n.isUpdate===void 0?n.isExternal===void 0?!e&&i?.():n.isExternal?t():!e&&i?.():n.isUpdate||i?.()}),l.addEventListener(`waiting`,t)}}l.register({immediate:t}).then(e=>{o?o(`/sw.js`,e):a?.(e)}).catch(e=>{s?.(e)})}}return u=p(),f}var _o=new Set,vo=!1,yo=go({immediate:!0,onRegisteredSW(e,t){t&&setInterval(()=>{t.update()},36e5)},onNeedRefresh(){vo=!0,_o.forEach(e=>e())}});function bo(e){return _o.add(e),vo&&e(),()=>{_o.delete(e)}}function xo(){yo(!0)}function So(){let[e,t]=(0,Z.useState)(!1),[n,r]=(0,Z.useState)(!1);return(0,Z.useEffect)(()=>bo(()=>t(!0)),[]),!e||n?null:(0,Q.jsx)(`div`,{className:`fixed bottom-4 left-1/2 z-50 -translate-x-1/2`,children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-3 rounded-full border border-border bg-card px-4 py-2 shadow-elevation-2`,children:[(0,Q.jsx)(`span`,{className:`text-sm`,children:`A new version of Canvas is ready`}),(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>xo(),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,Q.jsx)(_t,{className:`h-3 w-3`}),` Reload`]}),(0,Q.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,Q.jsx)(z,{className:`h-3.5 w-3.5`})})]})})}var Co=(0,Z.lazy)(()=>c(()=>import(`./apps-stCO1N5r.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]))),wo=(0,Z.lazy)(()=>c(()=>Promise.resolve().then(()=>Ls).then(e=>({default:e.AppsMenu})),void 0)),To=(0,Z.lazy)(()=>c(()=>import(`./workspaces-BBq3LOwy.js`),__vite__mapDeps([19,1,2,8,3,4,10,9,6,5,11,12,20,7,13,21,22,23,24,25,26,27,28,29,30,31,32,33]))),Eo=(0,Z.lazy)(()=>c(()=>import(`./_workspaceName_-D79RwRsV.js`),__vite__mapDeps([34,1,2,3,4,10,8,5,6,9,12,35,32,20,7,11,13,36,37,38,39,40,22,23,41,42,43,44,21,45,46,47,18,14,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,24,76,77,78,79,27,80,25,26,81,82,29,83,15,84,85,86,16,17,87]))),Do=(0,Z.lazy)(()=>c(()=>import(`./document-Ds_P5v-f.js`),__vite__mapDeps([88,1,2,3,4,9,10,8,6,5,7,11,12,13,43,44,38,39,40,20,22,23,41,21,45,46,47,18,14,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,27,25,82,35,32,24,89]))),Oo=(0,Z.lazy)(()=>c(()=>import(`./home-w5SlrNH7.js`),__vite__mapDeps([90,1,2,3,4,10,8,7,9,6,5,11,12,13,36,35,32,37,38,39,40,20,22,23,41,42,43,44,21,45,46,47,18,14,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,24,76,77,78,79,27,80,91,85,86]))),ko=(0,Z.lazy)(()=>c(()=>import(`./desk-dI_FvLsK.js`),__vite__mapDeps([92,2,1]))),Ao=(0,Z.lazy)(()=>c(()=>import(`./share-target-5HoF3Y5a.js`),__vite__mapDeps([93,1,2,3,4,91,8,10,5,6,11,44,38,9,7,12,13,39,40,20,22,23,41,21,45,46,47,18,14,48,49,50,51,72,63,65,61,85,54,86]))),jo=(0,Z.lazy)(()=>c(()=>import(`./contexts-CwGdjtXy2.js`),__vite__mapDeps([94,1,2,3,4,10,8,9,6,5,11,35,12,32,20,7,13,14,74,38,39,40,22,23,41,62,77,28,29,30]))),Mo=(0,Z.lazy)(()=>c(()=>import(`./_contextId_-HAAoVKBa.js`),__vite__mapDeps([95,1,2,3,4,35,12,32,20,38,8,10,5,6,9,7,11,13,39,40,22,23,41,70,43,44,21,45,46,47,18,14,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,71,72,73,74,75,24,76,77,78,79,25,83,42,15,84,85,86,16,17,89]))),No=(0,Z.lazy)(()=>c(()=>import(`./api-tokens-CmHhwd58.js`),__vite__mapDeps([96,1,2,10,8,9,6,5,11,12,20,28,3,4,97,25,21]))),Po=(0,Z.lazy)(()=>c(()=>import(`./devices-CmVlYbam.js`),__vite__mapDeps([98,1,2,10,8,9,6,5,11,20,28,3,4,97,25,21,99,12]))),Fo=(0,Z.lazy)(()=>c(()=>import(`./settings-UMBkdMdX.js`),__vite__mapDeps([100,1,2,3,4,10,8,11,5,6,7,9,12,13,14,25,21,28]))),Io=(0,Z.lazy)(()=>c(()=>import(`./appearance-SqhMHD_S.js`),__vite__mapDeps([101,1,2,10,8,5,6,71,25,3,4,21,102,28,97]))),Lo=(0,Z.lazy)(()=>c(()=>import(`./key-bindings-5HbdLjsz.js`),__vite__mapDeps([103,1,2,28,3,4,10,8,5,6,97,25,21]))),Ro=(0,Z.lazy)(()=>c(()=>import(`./offline-yfQ63Zr7.js`),__vite__mapDeps([104,1,2,10,8,5,6,9,12,38,7,11,13,39,40,20,22,23,41,62,28,3,4,97,25,21]))),zo=(0,Z.lazy)(()=>c(()=>import(`./about-dr4T4ju8.js`),__vite__mapDeps([105,1,2,12,28,3,4,10,8,5,6,97,25,21]))),Bo=(0,Z.lazy)(()=>c(()=>import(`./embedding-2EjzoVFT.js`),__vite__mapDeps([106,1,2,10,8,9,6,5,20,28,3,4,97,25,21,107,11,12]))),Vo=(0,Z.lazy)(()=>c(()=>import(`./shared-B24deTOM.js`),__vite__mapDeps([108,1,2,3,4,9,10,8,6,5,11,12,20,28,97,25,21]))),Ho=(0,Z.lazy)(()=>c(()=>import(`./workspaces-p959p9BR.js`),__vite__mapDeps([109,1,2,10,8,9,6,5,11,44,37,12,35,32,20,39,28,3,4,110]))),Uo=(0,Z.lazy)(()=>c(()=>import(`./contexts-Dtl9oERX.js`),__vite__mapDeps([111,1,2,37,6,12,35,32,28,3,4,10,8,5]))),Wo=(0,Z.lazy)(()=>c(()=>import(`./agents-DEJU4O1Z.js`),__vite__mapDeps([112,1,2,37,6,12,35,32,28,3,4,10,8,5]))),Go=(0,Z.lazy)(()=>c(()=>import(`./logs-DUeiDqCX.js`),__vite__mapDeps([113,1,2,10,8,9,6,5,11,44,37,12,35,32,20,28,3,4,97,25,21,110]))),Ko=(0,Z.lazy)(()=>c(()=>import(`./roles-BHJYWaBs.js`),__vite__mapDeps([114,1,2,10,8,9,6,5,11,44,37,12,35,32,20,39,28,3,4,97,25,21,115]))),qo=(0,Z.lazy)(()=>c(()=>import(`./users-DInwKAxz.js`),__vite__mapDeps([116,1,2,10,8,9,6,5,11,44,37,12,35,32,20,39,28,3,4,97,25,21,110]))),Jo=(0,Z.lazy)(()=>c(()=>import(`./embedding-BqI3l5RB.js`),__vite__mapDeps([117,1,2,10,8,9,6,5,11,37,12,35,32,20,28,3,4,97,25,21,107]))),Yo=(0,Z.lazy)(()=>c(()=>import(`./auth-_bmIEN02.js`),__vite__mapDeps([118,1,2,10,8,5,6,9,11,12,37,35,32,20,28,3,4,97,25,21]))),Xo=(0,Z.lazy)(()=>c(()=>import(`./agents-CZgEe18J.js`),__vite__mapDeps([119,1,2,3,4,10,8,9,6,5,11,20,23,28,120,29,30,31,12,32]))),Zo=(0,Z.lazy)(()=>c(()=>import(`./_agentId_-CweMTe-q.js`),__vite__mapDeps([121,1,2,3,4,10,8,5,6,9,12,32,20,56,25,21,28]))),Qo=(0,Z.lazy)(()=>c(()=>import(`./settings-Btb3SUu6.js`),__vite__mapDeps([122,1,2,3,4,10,8,9,6,5,11,20,7,12,13,21,14,23,25,28,120]))),$o=(0,Z.lazy)(()=>c(()=>import(`./settings-y5FovQxO.js`),__vite__mapDeps([123,1,2,8,3,4,10,5,6,9,11,44,12,35,32,20,38,7,13,39,40,22,23,41,21,58,59,60,61,62,66,73,74,75,24,25,102,28,107,31,99,87,33]))),es=(0,Z.lazy)(()=>c(()=>import(`./settings-D55sWdd2.js`),__vite__mapDeps([124,1,2,3,4,10,8,5,6,9,11,20,21,14,12,7,13,74,38,39,40,22,23,41,62,25,28]))),ts=(0,Z.lazy)(()=>c(()=>import(`./roles-CuqCEPC7.js`),__vite__mapDeps([125,1,2,10,8,9,6,5,11,37,12,35,32,20,7,13,39,28,3,4,115,29,30]))),ns=(0,Z.lazy)(()=>c(()=>import(`./remotes-BjjlqN_M.js`),__vite__mapDeps([126,2,1,28,3,4,10,8,5,6]))),rs=(0,Z.lazy)(()=>c(()=>import(`./add-fha_SoND.js`),__vite__mapDeps([127,2,1,3,4,91,8,10,5,6,11,44,38,9,7,12,13,39,40,20,22,23,41,21,45,46,47,18,14,48,49,50,51,72,63,65,61,85,54,86])));function $(e){return(0,Q.jsx)(Z.Suspense,{fallback:(0,Q.jsx)(`div`,{className:`flex h-full items-center justify-center p-4 text-sm text-muted-foreground`,role:`status`,children:`Opening…`}),children:(0,Q.jsx)(e,{})})}var is=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(d,{index:!0,element:$(ko)},`r1`),(0,Q.jsx)(d,{path:`home`,element:$(Oo)},`r2`),(0,Q.jsx)(d,{path:`share-target`,element:$(Ao)},`r3`),(0,Q.jsx)(d,{path:`apps`,element:$(wo)},`apps-index`),(0,Q.jsx)(d,{path:`apps/:appletId`,element:$(Co)},`apps-host`),(0,Q.jsx)(d,{path:`apps/add/:kind`,element:$(rs)},`r4`),(0,Q.jsx)(d,{path:`workspaces`,element:$(To)},`r5`),(0,Q.jsx)(d,{path:`workspaces/:workspaceName`,element:$(Eo)},`r6`),(0,Q.jsx)(d,{path:`workspaces/:workspaceName/documents/by-id/:documentId`,element:$(Do)},`workspace-document-by-id`),(0,Q.jsx)(d,{path:`workspaces/:workspaceName/documents/:documentId`,element:$(Do)},`workspace-document`),(0,Q.jsx)(d,{path:`workspaces/:workspaceName/documents/by-hash/:algo/:checksum`,element:$(Do)},`workspace-document-by-hash`),(0,Q.jsx)(d,{path:`workspaces/:workspaceName/documents/by-checksum/:algo/:checksum`,element:$(Do)},`workspace-document-by-checksum`),(0,Q.jsx)(d,{path:`workspaces/:workspaceName/settings`,element:$($o)},`r7`),(0,Q.jsx)(d,{path:`workspaces/:workspaceName/settings/:tab`,element:$($o)},`r8`),(0,Q.jsx)(d,{path:`workspaces/:workspaceName/path/*`,element:$(Eo)},`r9`),(0,Q.jsx)(d,{path:`workspaces/:workspaceName/trees/:treeName`,element:$(Eo)},`r10`),(0,Q.jsx)(d,{path:`workspaces/:workspaceName/trees/:treeName/path/*`,element:$(Eo)},`r11`),(0,Q.jsx)(d,{path:`contexts`,element:$(jo)},`r12`),(0,Q.jsx)(d,{path:`contexts/:contextId`,element:$(Mo)},`r13`),(0,Q.jsx)(d,{path:`contexts/:contextId/settings`,element:$(es)},`r14`),(0,Q.jsx)(d,{path:`contexts/:contextId/settings/:tab`,element:$(es)},`r15`),(0,Q.jsx)(d,{path:`agents`,element:$(Xo)},`r16`),(0,Q.jsx)(d,{path:`agents/:agentId`,element:$(Zo)},`r17`),(0,Q.jsx)(d,{path:`agents/:agentId/:sessionId`,element:$(Zo)},`r18`),(0,Q.jsx)(d,{path:`agents/:agentId/settings`,element:$(Qo)},`r19`),(0,Q.jsx)(d,{path:`agents/:agentId/settings/:tab`,element:$(Qo)},`r20`),(0,Q.jsx)(d,{path:`roles`,element:$(ts)},`r21`),(0,Q.jsx)(d,{path:`remotes`,element:$(ns)},`r22`),(0,Q.jsx)(d,{path:`settings`,element:$(Fo)},`settings`),(0,Q.jsx)(d,{path:`appearance`,element:$(Io)},`r23`),(0,Q.jsx)(d,{path:`key-bindings`,element:$(Lo)},`key-bindings`),(0,Q.jsx)(d,{path:`offline`,element:$(Ro)},`r24`),(0,Q.jsx)(d,{path:`about`,element:$(zo)},`r25`),(0,Q.jsx)(d,{path:`api-tokens`,element:$(No)},`r26`),(0,Q.jsx)(d,{path:`devices`,element:$(Po)},`r27`),(0,Q.jsx)(d,{path:`embedding`,element:$(Bo)},`r28`),(0,Q.jsx)(d,{path:`shared`,element:$(Vo)},`r29`),(0,Q.jsx)(d,{path:`admin/users`,element:$(qo)},`r30`),(0,Q.jsx)(d,{path:`admin/contexts`,element:$(Uo)},`r31`),(0,Q.jsx)(d,{path:`admin/workspaces`,element:$(Ho)},`r32`),(0,Q.jsx)(d,{path:`admin/agents`,element:$(Wo)},`r33`),(0,Q.jsx)(d,{path:`admin/logs`,element:$(Go)},`r34`),(0,Q.jsx)(d,{path:`admin/roles`,element:$(Ko)},`r35`),(0,Q.jsx)(d,{path:`admin/embedding`,element:$(Jo)},`r36`),(0,Q.jsx)(d,{path:`admin/auth`,element:$(Yo)},`r37`)]});function as(e){if(typeof e!=`string`||!e.startsWith(`/`)||e.startsWith(`//`)||/[\\\u0000-\u0020]/.test(e))return null;let t=new URL(e,`https://canvas.invalid`);return t.origin!==`https://canvas.invalid`||/^\/(?:login|register|pub|share-target|apps|next)(?:\/|$)/.test(t.pathname)||t.pathname===`/`||[...t.searchParams.keys()].some(e=>/token|password|secret|code/i.test(e))?null:t.pathname+t.search+t.hash}function os(e){let t=2166136261;for(let n of e)t=Math.imul(t^n.charCodeAt(0),16777619);return`canvas:last-screen:${t>>>0}`}var ss=p(is),cs=e=>{let t=as(e);return t&&x(ss,t)?t:null};function ls(){let e=h(),[t]=(0,Z.useState)(()=>{if(e.pathname!==`/`||e.search||e.hash)return null;try{let t=localStorage.getItem(`authToken`);return t?{key:e.key,path:cs(localStorage.getItem(os(t)))||`/home`}:null}catch{return{key:e.key,path:`/home`}}}),n=t&&e.key===t.key&&e.pathname===`/`;return(0,Z.useEffect)(()=>{if(n)return;let t=cs(e.pathname+e.search+e.hash);if(t)try{let e=localStorage.getItem(`authToken`);e&&localStorage.setItem(os(e),t)}catch{}},[e.pathname,e.search,e.hash,n]),n?(0,Q.jsx)(u,{to:t.path,replace:!0}):null}var us={activeSection:null,m0Open:!1,m1Open:!1,m2Open:!1,m2View:null,selectedEntityId:null,user:null};function ds(e,t){switch(t.type){case`RESTORE_MENU`:return{...e,...t.menu,user:e.user};case`SET_SECTION`:return{...e,activeSection:t.section,m1Open:t.section!==null,m2Open:!1,m2View:null,selectedEntityId:null};case`TOGGLE_SECTION`:return e.activeSection===t.section&&e.m1Open?{...e,activeSection:null,m1Open:!1,m2Open:!1,m2View:null}:{...e,activeSection:t.section,m1Open:!0,m2Open:!1,m2View:null,selectedEntityId:null};case`TOGGLE_M0`:return e.m0Open?{...e,m0Open:!1,activeSection:null,m1Open:!1,m2Open:!1,m2View:null}:{...e,m0Open:!0};case`CLOSE_M0`:return{...e,m0Open:!1};case`CLOSE_M1`:return{...e,activeSection:null,m1Open:!1,m2Open:!1,m2View:null};case`OPEN_M2`:return{...e,m2Open:!0,m2View:t.view,selectedEntityId:t.entityId===void 0?e.selectedEntityId:t.entityId};case`OPEN_M2_DRAWER`:return{...e,m0Open:!0,activeSection:t.section,m1Open:!0,m2Open:!0,m2View:t.view,selectedEntityId:t.entityId};case`OPEN_M1_DRAWER`:return{...e,m0Open:!0,activeSection:t.section,m1Open:!0,m2Open:!1,m2View:null,selectedEntityId:null};case`CLOSE_M2`:return{...e,m2Open:!1,m2View:null};case`SELECT_ENTITY`:return{...e,selectedEntityId:t.entityId};case`SYNC_FROM_URL`:{let n=!t.mobile&&!e.m2Open&&e.m2View===null&&t.section===e.activeSection&&t.entityId===e.selectedEntityId;return t.section===e.activeSection&&t.entityId===e.selectedEntityId&&t.m2View===e.m2View&&!(t.mobile&&(e.m1Open||e.m0Open))?e:{...e,activeSection:t.section,m0Open:!t.mobile&&e.m0Open,m1Open:!t.mobile&&t.section!==null,selectedEntityId:t.entityId,m2Open:!n&&t.m2View!==null,m2View:n?null:t.m2View}}case`SET_USER`:return{...e,user:t.user};default:return e}}function fs({children:e}){let[t,n]=(0,Z.useReducer)(ds,us),r=h(),i=m(),a=(0,Z.useRef)(t);(0,Z.useLayoutEffect)(()=>{a.current=t},[t]),aa(t,n);let o=(0,Z.useCallback)((e,t=!1,o=!1)=>{let s=ds(a.current,e);if(a.current=s,n(e),!da())return;let{activeSection:c,m0Open:l,m1Open:u,m2Open:d,m2View:f,selectedEntityId:p}=s;i({pathname:r.pathname,search:r.search,hash:r.hash},{replace:t,state:{...r.state,canvasMenu:{activeSection:c,m0Open:l,m1Open:u,m2Open:d,m2View:f,selectedEntityId:p},canvasMenuBack:o}})},[r,i]),s=(0,Z.useCallback)(e=>{if(da()&&a.current.m1Open){let{activeSection:t,m0Open:n,m1Open:o,m2Open:s,m2View:c,selectedEntityId:l}=a.current;i(e,{replace:!0,state:{...r.state,canvasMenu:{activeSection:t,m0Open:n,m1Open:o,m2Open:s,m2View:c,selectedEntityId:l},canvasMenuBack:!1}})}i(e)},[r.state,i]),c=(0,Z.useCallback)(()=>{if(window.history.state?.idx>0){i(-1);return}let e=a.current;if(e.m1Open&&e.m2Open)o({type:`CLOSE_M2`},!0,!0);else if(e.m1Open)o({type:`CLOSE_M1`},!0,!0);else if(e.m0Open)o({type:`CLOSE_M0`},!0,!0);else{let{section:e,entityId:t,m2View:n}=pa(r.pathname);if(!da()){i(e?`/${e}`:`/`);return}o(e&&t?{type:`OPEN_M2_DRAWER`,section:e,view:n,entityId:t}:{type:`TOGGLE_M0`},!0,!0)}},[o,r.pathname,i]);(0,Z.useEffect)(()=>{let e=mn();if(e){n({type:`SET_USER`,user:e});return}let t=!1;return vn().then(e=>{!t&&e&&n({type:`SET_USER`,user:e})}).catch(()=>{}),()=>{t=!0}},[]);let l={state:t,dispatch:n,setSection:(0,Z.useCallback)(e=>{o({type:`SET_SECTION`,section:e})},[o]),toggleSection:(0,Z.useCallback)(e=>{o({type:`TOGGLE_SECTION`,section:e})},[o]),toggleM0:(0,Z.useCallback)(()=>{o({type:`TOGGLE_M0`},a.current.m0Open)},[o]),closeM0:(0,Z.useCallback)(()=>{o({type:`CLOSE_M0`},!0)},[o]),closeM1:(0,Z.useCallback)(()=>{o({type:`CLOSE_M1`},!0)},[o]),openM2:(0,Z.useCallback)((e,t)=>{o({type:`OPEN_M2`,view:e,entityId:t})},[o]),openM2Drawer:(0,Z.useCallback)((e,t,n)=>{o({type:`OPEN_M2_DRAWER`,section:e,view:t,entityId:n})},[o]),openM1Drawer:(0,Z.useCallback)(e=>{o({type:`OPEN_M1_DRAWER`,section:e})},[o]),closeM2:(0,Z.useCallback)(()=>{da()&&a.current.m1Open&&a.current.m2Open?c():n({type:`CLOSE_M2`})},[c]),selectEntity:(0,Z.useCallback)(e=>{n({type:`SELECT_ENTITY`,entityId:e})},[]),goBack:c,navigateFromMenu:s};return(0,Q.jsx)(ma.Provider,{value:l,children:e})}var ps;function ms(){let[e,t]=(0,Z.useState)({local:!1});return(0,Z.useEffect)(()=>{ps??=fetch(`${J}/runtime/capabilities`).then(async e=>e.ok?(await e.json()).payload:{local:!1}).catch(()=>({local:!1}));let e=!0;return ps.then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function hs(){return(0,Z.useSyncExternalStore)(rn,sn,()=>!1)}function gs(e,t){let n=null,r=!1,i,a;function o(){clearTimeout(i),!r&&sn()&&(i=setTimeout(()=>{s()},3e4))}function s(s=!1){if(n)return n;if(r)return Promise.resolve(!1);clearTimeout(i),a=new AbortController;let c=setTimeout(()=>a?.abort(),5e3);return n=(async()=>{try{let n=await fetch(e,{cache:`no-store`,credentials:`omit`,signal:a.signal});if(!n.ok||n.headers.get(`x-canvas-offline`)===`fallback`)throw Error(`Unavailable`);if((await n.json()).status!==`success`)throw Error(`Not a Canvas response`);if(r)return!1;let i=sn();return on(),(i||s)&&t(),!0}catch{return r||tn(),!1}finally{clearTimeout(c),n=null,o()}})(),n}let c=rn(o),l=()=>{s()};return window.addEventListener(`online`,l),o(),{retry:s,stop(){r=!0,clearTimeout(i),a?.abort(),c(),window.removeEventListener(`online`,l)}}}var _s;function vs(){_s=gs(`${J}/ping`,()=>X.retryNow());let e=()=>{_s?.retry()},t=X.on(`connect_error`,e),n=X.on(`disconnect`,e);return()=>{t(),n(),_s?.stop(),_s=void 0}}function ys(){return _s?.retry(!0)??Promise.resolve(!1)}function bs(){let e=hs(),[t,n]=(0,Z.useState)(!1);return e?(0,Q.jsxs)(`details`,{className:`relative`,children:[(0,Q.jsx)(`summary`,{"aria-label":`Offline — connection options`,title:`Offline — cached content available`,className:`flex h-10 w-10 cursor-pointer list-none items-center justify-center rounded-lg text-amber-600 hover:bg-accent/50 [&::-webkit-details-marker]:hidden`,children:(0,Q.jsx)(A,{className:`h-5 w-5`})}),(0,Q.jsxs)(`div`,{className:`absolute bottom-0 left-full z-50 ml-2 w-60 max-w-[calc(100vw-5rem)] rounded-lg border bg-popover p-3 text-popover-foreground shadow-lg`,children:[(0,Q.jsx)(`p`,{className:`text-sm font-medium`,role:`status`,children:`Offline`}),(0,Q.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`You can browse cached documents. We’ll reconnect automatically when the server is available.`}),(0,Q.jsx)(`button`,{type:`button`,disabled:t,onClick:async()=>{n(!0);try{await ys()}finally{n(!1)}},className:`mt-3 rounded-md bg-secondary px-3 py-2 text-xs font-medium hover:bg-accent disabled:opacity-50`,children:t?`Checking…`:`Retry now`})]})]}):null}var xs=be,Ss=ee,Cs=Ht,ws=Z.forwardRef(({className:e,sideOffset:t=4,...n},r)=>(0,Q.jsx)(Ut,{children:(0,Q.jsx)(Ke,{ref:r,sideOffset:t,className:G(`z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in duration-fast fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin]`,e),...n})}));ws.displayName=Ke.displayName;var Ts=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(Ve,{ref:n,className:G(`relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full`,e),...t}));Ts.displayName=Ve.displayName;var Es=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(qt,{ref:n,className:G(`aspect-square h-full w-full`,e),...t}));Es.displayName=qt.displayName;var Ds=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(Lt,{ref:n,className:G(`flex h-full w-full items-center justify-center rounded-full bg-muted`,e),...t}));Ds.displayName=Lt.displayName;function Os({section:e,icon:t,label:n,disabled:r}){let{state:i,toggleSection:a}=la(),o=i.activeSection===e;return(0,Q.jsxs)(Ss,{children:[(0,Q.jsx)(Cs,{asChild:!0,children:(0,Q.jsxs)(`button`,{type:`button`,disabled:r,"aria-label":n,onClick:()=>!r&&e&&a(e),className:G(`relative flex items-center justify-center w-10 h-10 rounded-lg transition-colors`,o?`bg-accent text-foreground`:`text-muted-foreground hover:text-foreground hover:bg-accent/50`,r&&`opacity-30 cursor-not-allowed`),children:[o&&(0,Q.jsx)(`span`,{className:`absolute right-0 top-1/2 -translate-y-1/2 w-0.5 h-5 bg-foreground rounded-l`}),t]})}),(0,Q.jsx)(ws,{side:`right`,sideOffset:8,children:n})]})}function ks({path:e,icon:t,label:n,section:r=`settings`}){let i=m(),{setSection:a}=la();return(0,Q.jsxs)(Ss,{children:[(0,Q.jsx)(Cs,{asChild:!0,children:(0,Q.jsx)(`button`,{type:`button`,"aria-label":n,onClick:()=>{a(r),i(e)},className:`flex items-center justify-center w-10 h-10 rounded-lg text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors`,children:t})}),(0,Q.jsx)(ws,{side:`right`,sideOffset:8,children:n})]})}function As(){let{state:e,toggleM0:t}=la(),n=hs();return(0,Q.jsxs)(`button`,{type:`button`,onClick:t,"aria-label":`${e.m0Open?`Close menu`:`Open menu`}${n?` — offline, connection options in menu`:``}`,"data-shell":`rail`,className:`fixed bottom-rail-inset left-2 z-nav flex h-rail w-rail items-center justify-center rounded-full bg-foreground text-background shadow-elevation-4 md:hidden`,children:[e.m0Open?(0,Q.jsx)(z,{className:`h-5 w-5`}):(0,Q.jsx)(ht,{className:`h-5 w-5`}),n&&(0,Q.jsx)(`span`,{"aria-hidden":!0,className:`absolute right-0 top-0 h-3 w-3 rounded-full border-2 border-background bg-amber-500`})]})}function js(){let{state:e,closeM0:t,closeM1:n}=la(),{state:r,setView:i,closeT1:a}=ti(),o=m(),{showToast:s}=xn(),c=e.user?.userType===`admin`,l=ms(),u=()=>{r.t1Open?a():i(`tools`),n(),t()},d=(0,Z.useCallback)(async()=>{try{await Y.post(`/auth/logout`),localStorage.removeItem(`authToken`),o(`/login`)}catch{s({title:`Error`,description:`Logout failed`,variant:`destructive`})}},[o,s]);return(0,Q.jsxs)(xs,{delayDuration:200,children:[e.m0Open&&(0,Q.jsx)(`div`,{className:`fixed inset-0 z-nav-scrim bg-scrim animate-fade-in md:hidden`,onClick:t,"aria-hidden":!0}),(0,Q.jsxs)(`div`,{"data-shell":`rail`,className:G(`flex flex-col items-center w-rail h-full rounded-(--panel-radius) bg-transparent shrink-0`,e.m0Open?`max-md:fixed max-md:left-2 max-md:top-2 max-md:bottom-rail-stack max-md:z-rail max-md:h-auto max-md:bg-card max-md:surface-glass max-md:shadow-elevation-5`:`max-md:hidden`),children:[(0,Q.jsx)(`div`,{className:`flex items-center justify-center h-12 w-full shrink-0`,children:(0,Q.jsx)(`button`,{type:`button`,"aria-label":`Canvas home`,onClick:()=>o(`/home`),className:`flex items-center justify-center w-10 h-10 rounded-lg hover:bg-accent/50 transition-colors`,children:(0,Q.jsx)(`img`,{src:`/images/logo-br_128x128.png`,alt:``,className:`w-6 h-6`})})}),(0,Q.jsxs)(`nav`,{className:`flex flex-col items-center gap-1 py-2 flex-1 min-h-0 overflow-y-auto`,children:[(!l.local||l.workspace!==!1)&&(0,Q.jsx)(Os,{section:`contexts`,icon:(0,Q.jsx)(xe,{className:`w-5 h-5`}),label:`Contexts`}),(!l.local||l.workspace!==!1)&&(0,Q.jsx)(Os,{section:`workspaces`,icon:(0,Q.jsx)(Wt,{className:`w-5 h-5`}),label:`Workspaces`}),(!l.local||l.agent)&&(0,Q.jsx)(Os,{section:`agents`,icon:(0,Q.jsx)(Be,{className:`w-5 h-5`}),label:`Agents`}),(0,Q.jsx)(Os,{section:`apps`,icon:(0,Q.jsx)(He,{className:`w-5 h-5`}),label:`Apps`}),(!l.local||l.workspace!==!1)&&(0,Q.jsx)(ks,{path:`/roles`,section:null,icon:(0,Q.jsx)(It,{className:`w-5 h-5`}),label:`Roles`}),c&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`w-6 h-px bg-border my-2`}),(0,Q.jsx)(ks,{path:`/admin/users`,icon:(0,Q.jsx)(oe,{className:`w-5 h-5`}),label:`All Users`}),(0,Q.jsx)(ks,{path:`/admin/logs`,icon:(0,Q.jsx)(Tt,{className:`w-5 h-5`}),label:`Server Logs`}),(0,Q.jsx)(ks,{path:`/admin/workspaces`,icon:(0,Q.jsx)(ve,{className:`w-5 h-5`}),label:`All Workspaces`}),(0,Q.jsx)(ks,{path:`/admin/agents`,icon:(0,Q.jsx)(Be,{className:`w-5 h-5`}),label:`All Agents`}),(0,Q.jsx)(ks,{path:`/admin/roles`,icon:(0,Q.jsx)(It,{className:`w-5 h-5`}),label:`All Roles`})]})]}),(0,Q.jsxs)(`div`,{className:`flex flex-col items-center gap-1 py-2 shrink-0`,children:[(0,Q.jsx)(`div`,{className:`w-6 h-px bg-border mb-2`}),(0,Q.jsx)(bs,{}),(0,Q.jsxs)(Ss,{children:[(0,Q.jsx)(Cs,{asChild:!0,children:(0,Q.jsx)(`button`,{type:`button`,onClick:u,"aria-label":r.t1Open?`Close toolbox`:`Open toolbox`,className:G(`flex items-center justify-center w-10 h-10 rounded-lg transition-colors`,r.t1Open?`bg-accent text-foreground`:`text-muted-foreground hover:text-foreground hover:bg-accent/50`),children:(0,Q.jsx)(ye,{className:`w-5 h-5`})})}),(0,Q.jsx)(ws,{side:`right`,sideOffset:8,children:`Toolbox`})]}),!l.local&&(0,Q.jsx)(ks,{path:`/settings`,section:`settings`,icon:(0,Q.jsx)(pt,{className:`w-5 h-5`}),label:`Settings`}),(0,Q.jsxs)(Ss,{children:[(0,Q.jsx)(Cs,{asChild:!0,children:(0,Q.jsx)(`button`,{type:`button`,"aria-label":e.user?.email?`Profile: ${e.user.email}`:`Profile`,onClick:()=>o(`/home`),className:`flex items-center justify-center w-10 h-10 rounded-lg hover:bg-accent/50 transition-colors`,children:(0,Q.jsx)(Ts,{className:`h-7 w-7 touch-target`,children:(0,Q.jsx)(Ds,{className:`text-[10px] bg-muted`,children:e.user?.email?(e=>e.split(`@`)[0].split(`.`).map(e=>e.charAt(0).toUpperCase()).join(``).slice(0,2))(e.user.email):`U`})})})}),(0,Q.jsx)(ws,{side:`right`,sideOffset:8,children:e.user?.email?.split(`@`)[0]||`Profile`})]}),(0,Q.jsxs)(Ss,{children:[(0,Q.jsx)(Cs,{asChild:!0,children:(0,Q.jsx)(`button`,{type:`button`,"aria-label":`Log out`,onClick:d,className:`flex items-center justify-center w-10 h-10 rounded-lg text-destructive hover:bg-destructive/10 transition-colors`,children:(0,Q.jsx)(yt,{className:`w-5 h-5`})})}),(0,Q.jsx)(ws,{side:`right`,sideOffset:8,children:`Logout`})]})]})]})]})}function Ms(){let{goBack:e}=la();return(0,Q.jsx)(`button`,{type:`button`,onClick:e,"aria-label":`Back to previous view`,title:`Back to previous view`,className:`-ml-2 mr-1 flex h-11 w-11 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-accent md:hidden`,children:(0,Q.jsx)(nt,{className:`h-5 w-5`})})}var Ns=[{id:`productivity`,label:`Productivity`},{id:`creative`,label:`Creative`},{id:`media`,label:`Media & capture`},{id:`utilities`,label:`Utilities`}];function Ps(e,t){let n=t.trim().toLocaleLowerCase();return Ns.map(t=>({...t,apps:e.filter(e=>e.category===t.id&&`${e.name} ${e.description} ${e.kind} ${t.label}`.toLocaleLowerCase().includes(n)).sort((e,t)=>e.name.localeCompare(t.name)||e.id.localeCompare(t.id))})).filter(e=>e.apps.length)}function Fs(e){let t=new URL(e);if(![`http:`,`https:`].includes(t.protocol)||t.username||t.password)throw Error(`Enter an HTTP or HTTPS URL without embedded credentials.`);return t.href}function Is({apps:e,query:t,activeId:n,onLaunch:r,onRemove:i}){let a=Ps(e,t);return(0,Q.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-3 overflow-y-auto p-2`,children:[a.map(e=>(0,Q.jsxs)(`section`,{"aria-label":e.label,children:[(0,Q.jsx)(`h3`,{className:`px-2 py-2 text-xs font-semibold text-muted-foreground`,children:e.label}),e.apps.map(e=>{let t=e.kind===`web`?Ee:e.kind===`desktop`?Le:xe;return(0,Q.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>r(e),"aria-current":n===e.id?`page`:void 0,className:`flex min-w-0 flex-1 items-start gap-2 rounded-md p-2 text-left hover:bg-accent/50 ${n===e.id?`bg-accent`:``}`,children:[(0,Q.jsx)(t,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,Q.jsxs)(`span`,{className:`min-w-0`,children:[(0,Q.jsx)(`span`,{className:`block truncate text-sm font-medium`,children:e.name}),(0,Q.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:e.description}),(0,Q.jsx)(`span`,{className:`mt-1 block text-[10px] text-muted-foreground`,children:e.kind===`canvas`?`Canvas`:e.kind===`web`?`Web app · opens in browser`:`Desktop app`})]})]}),e.kind===`web`&&i&&(0,Q.jsx)(`button`,{type:`button`,onClick:()=>i(e),"aria-label":`Remove ${e.name}`,className:`rounded p-2 text-muted-foreground hover:bg-accent`,children:(0,Q.jsx)(Fe,{className:`h-3.5 w-3.5`})})]},e.id)})]},e.id)),!a.length&&(0,Q.jsx)(`p`,{role:`status`,className:`p-3 text-sm text-muted-foreground`,children:`No matching apps.`})]})}var Ls=t({AppsMenu:()=>Bs}),Rs=`canvas:webApps`;function zs(){try{let e=JSON.parse(localStorage.getItem(Rs)||`[]`);return Array.isArray(e)?e.filter(e=>{if(!e||typeof e.id!=`string`||typeof e.name!=`string`||typeof e.description!=`string`||e.kind!==`web`||!Ns.some(t=>t.id===e.category))return!1;try{return typeof e.target==`string`&&!!Fs(e.target)}catch{return!1}}):[]}catch{return[]}}function Bs(){let{navigateFromMenu:e}=la(),t=h(),n=_a(),[r,i]=(0,Z.useState)(``),[a,o]=(0,Z.useState)(zs),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(``);(0,Z.useEffect)(()=>{let e=()=>o(zs());return window.addEventListener(`storage`,e),window.addEventListener(`canvas:apps-changed`,e),()=>{window.removeEventListener(`storage`,e),window.removeEventListener(`canvas:apps-changed`,e)}},[]);let d=e=>{try{return localStorage.setItem(Rs,JSON.stringify(e)),o(e),window.dispatchEvent(new Event(`canvas:apps-changed`)),!0}catch{return u(`Unable to save web apps on this device.`),!1}},f=[...ga.map(e=>({id:`canvas:${e.id}`,name:e.label,description:e.description,category:e.category,kind:`canvas`,target:`/apps/${e.id}`})),...a];return(0,Q.jsxs)(`nav`,{"aria-label":`Apps`,className:`flex h-full min-h-0 flex-col`,children:[(0,Q.jsxs)(`div`,{className:`shrink-0 space-y-3 border-b p-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(Ms,{}),(0,Q.jsx)(`h2`,{className:`flex-1 text-sm font-semibold`,children:`Apps`}),(0,Q.jsx)(`button`,{type:`button`,"aria-label":`Add web app`,title:`Add web app`,onClick:()=>{c(!s),u(``)},className:`rounded p-1 hover:bg-accent`,children:(0,Q.jsx)(ge,{className:`h-4 w-4`})})]}),(0,Q.jsx)(`input`,{type:`search`,"aria-label":`Search apps`,placeholder:`Find an app…`,value:r,onChange:e=>i(e.target.value),className:`w-full rounded-md border bg-background px-2 py-1.5 text-sm`}),s&&(0,Q.jsxs)(`form`,{className:`space-y-2`,onSubmit:e=>{e.preventDefault();let t=new FormData(e.currentTarget);try{let e=String(t.get(`name`)||``).trim();if(!e)throw Error(`Enter an app name.`);let n={id:`web:${crypto.randomUUID()}`,name:e,description:``,category:t.get(`category`),kind:`web`,target:Fs(String(t.get(`url`)||``))};d([...zs(),n])&&(c(!1),u(``))}catch(e){u(e instanceof Error?e.message:`Unable to add app.`)}},children:[(0,Q.jsx)(`input`,{name:`name`,required:!0,"aria-label":`App name`,placeholder:`App name`,className:`w-full rounded border bg-background p-1 text-sm`}),(0,Q.jsx)(`input`,{name:`url`,type:`url`,required:!0,"aria-label":`App URL`,placeholder:`https://…`,className:`w-full rounded border bg-background p-1 text-sm`}),(0,Q.jsx)(`select`,{name:`category`,"aria-label":`App category`,className:`w-full rounded border bg-background p-1 text-sm`,children:Ns.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.label},e.id))}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Saved on this device. Opens in your browser.`}),(0,Q.jsx)(`button`,{type:`submit`,className:`rounded border px-2 py-1 text-sm hover:bg-accent`,children:`Add app`})]}),l&&(0,Q.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,children:l})]}),(0,Q.jsx)(Is,{apps:f,query:r,activeId:f.find(e=>e.kind===`canvas`&&e.target===t.pathname)?.id,onLaunch:r=>{if(r.kind===`web`){window.open(Fs(r.target),`_blank`,`noopener,noreferrer`);return}let i=new URLSearchParams;if(t.pathname.startsWith(`/apps/`)){let e=new URLSearchParams(t.search);for(let t of[`context`,`workspace`,`path`,`tree`])e.has(t)&&i.set(t,e.get(t))}else n?.mode===`context`?i.set(`context`,n.contextId):n?.mode===`workspace`&&(i.set(`workspace`,n.workspaceName),i.set(`path`,n.path),i.set(`tree`,n.treeName));e(`${r.target}${i.size?`?${i}`:``}`)},onRemove:e=>{d(zs().filter(t=>t.id!==e.id))}})]})}var Vs=220,Hs=560;function Us({width:e,onResize:t,onDragging:n}){let r=(0,Z.useRef)(null),i=e=>t(Math.min(Hs,Math.max(Vs,e))),a=()=>{r.current=null,n?.(!1)};return(0,Q.jsx)(`div`,{role:`separator`,"aria-label":`Resize menu`,"aria-orientation":`vertical`,"aria-valuemin":Vs,"aria-valuemax":Hs,"aria-valuenow":e,tabIndex:0,title:`Drag to resize; use arrow keys to adjust; Home resets width`,className:`absolute inset-y-0 right-0 z-30 flex w-3 touch-none select-none cursor-col-resize items-center justify-center hover:bg-primary/10 focus-visible:bg-primary/10 focus-visible:outline-none [@media(pointer:coarse)]:w-6`,onPointerDown:t=>{t.button!==0||r.current||(t.preventDefault(),t.stopPropagation(),r.current={id:t.pointerId,x:t.clientX,width:e},t.currentTarget.setPointerCapture(t.pointerId),n?.(!0))},onPointerMove:e=>{r.current?.id===e.pointerId&&i(r.current.width+e.clientX-r.current.x)},onPointerUp:e=>{r.current?.id===e.pointerId&&(a(),e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId))},onPointerCancel:a,onLostPointerCapture:a,onDoubleClick:()=>i(280),onKeyDown:t=>{[`ArrowLeft`,`ArrowRight`,`Home`].includes(t.key)&&(t.preventDefault(),t.stopPropagation(),i(t.key===`Home`?280:e+(t.key===`ArrowRight`?1:-1)*(t.shiftKey?64:16)))},children:(0,Q.jsx)(`span`,{"aria-hidden":!0,className:`h-10 w-1 rounded-full bg-border`})})}function Ws(e,t,n,r=!0){let i=Fr(),a=h(),o=(0,Z.useRef)(null);(0,Z.useLayoutEffect)(()=>{let s=window.history.state?.idx??0,c=o.current,l=a.state?.canvasMenuBack||!!c&&(s<c.index||s===c.index&&c.backwards);if(o.current={active:t,viewKey:n,index:s,backwards:l},!r||!i||!t||!c||c.active&&c.viewKey===n)return;let u=e.current;if(!u||window.matchMedia(`(prefers-reduced-motion: reduce)`).matches)return;let d=Number.parseFloat(getComputedStyle(u).getPropertyValue(`--motion-scale`)),f=Number.isFinite(d)?Math.max(0,d):1,p=u.animate([{transform:`translateX(${l?`-100%`:`100%`})`},{transform:`translateX(0)`}],{duration:70*f,easing:`cubic-bezier(0.2, 0, 0, 1)`});return()=>p.cancel()},[r,i,t,n,a.key,a.state,e])}function Gs(e){return[...e].sort((e,t)=>{let n=typeof e.order==`number`&&Number.isFinite(e.order)?e.order:2**53-1,r=typeof t.order==`number`&&Number.isFinite(t.order)?t.order:2**53-1;if(n!==r)return n-r;let i=e.createdAt??``,a=t.createdAt??``;return i===a?(e.name??``).localeCompare(t.name??``):i<a?-1:1})}function Ks(e,t,n){let r=[...e],[i]=r.splice(t,1);return r.splice(n,0,i),r}async function qs(e,t){return{failed:(await Promise.allSettled(e.map((e,n)=>e.order===n?Promise.resolve():t(e,n)))).filter(e=>e.status===`rejected`).length}}function Js(e){let[t,n]=(0,Z.useState)(null),[r,i]=(0,Z.useState)(null);return{rowProps:e=>({"data-reorder-index":e}),handleProps:t=>({onPointerDown:r=>{if(r.pointerType===`mouse`&&r.button!==0)return;r.preventDefault(),r.stopPropagation();let a=r.currentTarget.closest(`[data-reorder-index]`);if(!a)return;let o=a.parentElement,s=(o?[...o.querySelectorAll(`:scope > [data-reorder-index]`)]:[a]).map(e=>({index:Number(e.dataset.reorderIndex),rect:e.getBoundingClientRect()})).filter(e=>Number.isFinite(e.index)).sort((e,t)=>e.index-t.index).map(e=>e.rect.top+e.rect.height/2),c=a.getBoundingClientRect(),l=a.cloneNode(!0);Object.assign(l.style,{position:`fixed`,left:`${c.left}px`,top:`${c.top}px`,width:`${c.width}px`,height:`${c.height}px`,margin:`0`,pointerEvents:`none`,zIndex:`100`,opacity:`0.92`,boxShadow:`0 12px 32px rgba(0,0,0,.28)`,willChange:`transform`}),document.body.appendChild(l);let u={x:r.clientX,y:r.clientY},d=t;n(t),i(t);let f={x:r.clientX,y:r.clientY},p=0,m=()=>{p=0,l.style.transform=`translate(${f.x-u.x}px, ${f.y-u.y}px) scale(1.02)`;let e=s.length;for(let t=0;t<s.length;t++)if(f.y<s[t]){e=t;break}e!==d&&(d=e,i(e))},h=e=>{f={x:e.clientX,y:e.clientY},p||=requestAnimationFrame(m)},g=()=>{window.removeEventListener(`pointermove`,h),window.removeEventListener(`pointerup`,g),window.removeEventListener(`pointercancel`,g),p&&cancelAnimationFrame(p),l.remove(),n(null),i(null),d!==t&&d!==t+1&&e(t,d>t?d-1:d)};window.addEventListener(`pointermove`,h),window.addEventListener(`pointerup`,g),window.addEventListener(`pointercancel`,g)},onClick:e=>{e.preventDefault(),e.stopPropagation()},style:{touchAction:`none`}}),insertIndex:r,draggingIndex:t,insertLineClass:(e,n)=>r===null||t===null?!1:r===e?`shadow-[0_-3px_0_0_var(--color-primary)]`:r===n&&e===n-1&&`shadow-[0_3px_0_0_var(--color-primary)]`}}function Ys(e){let[t,n]=(0,Z.useState)([]),[r,i]=(0,Z.useState)(!1),a=(0,Z.useRef)(!1),o=(0,Z.useRef)(!1),s=(0,Z.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await ci();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch contexts:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,Z.useRef)(s);(0,Z.useEffect)(()=>{c.current=s});let l=(0,Z.useCallback)(()=>{a.current=!1,s()},[s]);return(0,Z.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,Z.useEffect)(()=>{if(!e)return;let t=()=>X.emit(`subscribe`,{channel:`context`}),r=()=>X.emit(`unsubscribe`,{channel:`context`}),i=X.on(`connect`,()=>{t(),s()});t();let o=e=>{let t=e;!t?.id||!t?.userId||n(e=>e.some(e=>e.id===t.id&&e.userId===t.userId)?e:[...e,t])},l=e=>{let t=e;!t?.id||!t?.userId||n(e=>e.map(e=>e.id===t.id&&e.userId===t.userId?{...e,...t}:e))},u=e=>{let t=e,r=t?.contextId??t?.id;r&&n(e=>e.filter(e=>e.id!==r))},d=e=>{let t=e;!t?.id||!t?.userId||n(e=>e.map(e=>e.id===t.id&&e.userId===t.userId?{...e,...t}:e))},f=()=>{a.current=!1,c.current()},p=[[`context:created`,o],[`context.created`,o],[`context:updated`,l],[`context.updated`,l],[`context:deleted`,u],[`context.deleted`,u],[`context:url:changed`,d],[`context.url.set`,d],[`context:url:set`,d],[`workspace:status:changed`,f],[`workspace.status.changed`,f]];return p.forEach(([e,t])=>X.on(e,t)),()=>{r(),i?.(),p.forEach(([e,t])=>X.off(e,t))}},[e,s]),(0,Z.useEffect)(()=>{let e=e=>{let t=e.detail;n(e=>e.filter(e=>!oi(e,t)))};return window.addEventListener(ii,e),()=>window.removeEventListener(ii,e)},[]),(0,Z.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`contexts:refresh`,e),()=>window.removeEventListener(`contexts:refresh`,e)},[s]),{contexts:(0,Z.useMemo)(()=>Gs(t),[t]),isLoading:r,refresh:l}}function Xs(){let{state:e,selectEntity:t,openM2:n,closeM2:r}=la(),a=Fr(),{contexts:o,isLoading:s}=Ys(e.activeSection===`contexts`),{showToast:c}=xn(),l=m(),[u,d]=(0,Z.useState)(null),f=u&&u.base===o?u.order:o,p=e=>e.isShared===!0||e.type===`shared`,{rowProps:h,handleProps:g,draggingIndex:_,insertLineClass:v}=Js((e,t)=>{let n=Ks(f,e,t);d({base:o,order:n}),qs(n,(e,t)=>p(e)?Promise.resolve():di(e.id,{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`contexts:refresh`)),e&&c({title:`Partial reorder`,description:`${e} context(s) could not be reordered`,variant:`destructive`})})}),y=e=>{t(e.id),l(`/contexts/${e.id}`)};return(0,Q.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 items-center`,children:[(0,Q.jsx)(Ms,{}),(0,Q.jsx)(`span`,{className:`text-sm font-semibold`,children:`Contexts`})]}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>{r(),l(`/contexts?create=1`)},title:`Create context`,"aria-label":`Create context`,className:`flex items-center justify-center w-6 h-6 rounded-full bg-foreground text-background hover:opacity-80 transition-opacity`,children:(0,Q.jsx)(ge,{className:`w-3.5 h-3.5`})})]}),(0,Q.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:s&&o.length===0?(0,Q.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):o.length===0?(0,Q.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No contexts found`}):(0,Q.jsx)(`div`,{className:`space-y-1.5 px-2`,children:f.map((r,o)=>{let s=e.selectedEntityId===r.id,c=p(r),u=r.workspaceActive!==!1,d=Si(r.color);return(0,Q.jsxs)(`div`,{...h(o),"data-active":s||void 0,className:G(`group relative rounded-(--card-radius) py-2.5 pl-3 pr-7 transition-all shadow-elevation-1`,u?`cursor-pointer hover:shadow `+(s?`bg-accent shadow`:`bg-card hover:bg-accent/50`):`cursor-not-allowed opacity-50 bg-card`,v(o,f.length),_===o&&`opacity-60`),onClick:()=>u&&y(r),title:u?void 0:`Workspace "${r.workspaceName}" is not active`,children:[c?(0,Q.jsx)(`div`,{className:G(`absolute inset-y-0 right-0 w-4 rounded-r-(--card-radius)`,!d&&`bg-muted`),style:d?{backgroundColor:d}:void 0}):(0,Q.jsx)(`button`,{type:`button`,...g(o),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:G(`absolute inset-y-0 right-0 flex w-4 cursor-grab items-center justify-center rounded-r-(--card-radius) active:cursor-grabbing`,!d&&`bg-muted`),style:d?{backgroundColor:d}:void 0,children:(0,Q.jsx)(I,{className:G(`h-3.5 w-3.5`,Ci(d))})}),(0,Q.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Q.jsx)(i,{icon:r.icon||`ph:stack-fill`,width:16,height:16,color:d,className:G(`mt-0.5 shrink-0`,!d&&`text-muted-foreground`)}),(0,Q.jsx)(`span`,{className:`text-sm font-medium truncate flex-1`,children:r.name||r.id}),c&&(0,Q.jsx)(`span`,{className:`rounded-full bg-info/10 px-1.5 py-0.5 text-[9px] text-info shrink-0`,children:`Shared`}),u&&(0,Q.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),t(r.id),n(`detail`,r.id)},className:`reveal-on-hover shrink-0 mt-0.5`,title:`Switch context URL`,children:(0,Q.jsx)(zt,{className:`w-3.5 h-3.5 text-muted-foreground hover:text-foreground`})}),(0,Q.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),t(r.id),a?n(`settings`,r.id):l(`/contexts/${r.id}/settings/general`)},className:`reveal-on-hover shrink-0 mt-0.5`,title:`Settings`,children:(0,Q.jsx)(pt,{className:`w-3.5 h-3.5 text-muted-foreground hover:text-foreground`})})]}),r.name&&(0,Q.jsx)(`div`,{className:`text-[10px] text-muted-foreground/60 truncate font-mono`,children:r.id}),(0,Q.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5`,children:r.url||`/`}),r.ownerEmail&&(0,Q.jsx)(`div`,{className:`text-[10px] text-muted-foreground truncate mt-0.5`,children:r.ownerEmail})]},`${r.userId||`u`}-${r.id}`)})})})]})}function Zs({title:e,onBack:t,action:n,className:r,icon:a,accentColor:o}){let{closeM1:s}=la(),c=Si(o);return(0,Q.jsxs)(`div`,{className:G(`flex items-center h-12 px-2 border-b border-border shrink-0 gap-1`,r),style:{borderBottomWidth:4,...c?{borderBottomColor:c}:{}},children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:t,className:`flex items-center gap-0.5 h-8 rounded px-1 hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors flex-1 min-w-0`,title:`Back`,"aria-label":`Back to previous view`,children:[(0,Q.jsx)(se,{className:`w-4 h-4 shrink-0`}),a&&(0,Q.jsx)(i,{icon:a,width:16,height:16,color:c,className:G(`mr-1 shrink-0`,!c&&`text-muted-foreground`)}),(0,Q.jsx)(`span`,{className:`text-sm font-semibold truncate`,children:e})]}),n&&(0,Q.jsx)(`div`,{className:`shrink-0`,children:n}),(0,Q.jsx)(`button`,{type:`button`,onClick:s,className:`flex h-8 w-8 shrink-0 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground`,title:`Close menu`,"aria-label":`Close menu`,children:(0,Q.jsx)(z,{className:`w-4 h-4`})})]})}function Qs(e,t,n){let r=e.indexOf(n);if(r<0)return new Set;let i=t===null?-1:e.indexOf(t);return new Set(i<0?[n]:e.slice(Math.min(i,r),Math.max(i,r)+1))}function $s(e){let t=[...e];return t.filter(e=>!t.some(t=>t!==e&&e.startsWith(`${t}/`)))}var ec=e(s(),1),tc=180;function nc({x:e,y:t,current:n,onChange:r,onClose:a}){hi(a);let[o,s]=(0,Z.useState)(``),[c,l]=(0,Z.useState)([]),[u,d]=(0,Z.useState)({q:``,list:[]}),[f,p]=(0,Z.useState)(!0),m=(0,Z.useRef)(null),h=(0,Z.useRef)({name:``,t:0}),g=(e,t)=>{r({icon:e}),h.current.name===e&&t-h.current.t<350&&a(),h.current={name:e,t}};(0,Z.useEffect)(()=>{m.current?.focus()},[]),(0,Z.useEffect)(()=>{let e=!0;return vi().then(t=>{e&&(l(t),p(!1))}),()=>{e=!1}},[]),(0,Z.useEffect)(()=>{let e=o.trim();if(!e)return;let t=setTimeout(()=>{yi(e).then(t=>{d({q:e,list:t})})},250);return()=>clearTimeout(t)},[o]);let _=o.trim(),v=u.q===_,y=_!==``&&!v,b=(0,Z.useMemo)(()=>(_?v?u.list:[]:c).slice(0,tc),[_,v,u.list,c]),x=(0,Z.useRef)(null),[S,C]=(0,Z.useState)({x:e,y:t});return(0,Z.useLayoutEffect)(()=>{let n=x.current;if(!n)return;let r=()=>{let{width:r,height:i}=n.getBoundingClientRect();C({x:Math.max(8,Math.min(e,window.innerWidth-r-8)),y:Math.max(8,Math.min(t,window.innerHeight-i-8))})};r();let i=new ResizeObserver(r);return i.observe(n),window.addEventListener(`resize`,r),()=>{i.disconnect(),window.removeEventListener(`resize`,r)}},[e,t]),(0,ec.createPortal)((0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`fixed inset-0 z-40`,onClick:a}),(0,Q.jsxs)(`div`,{ref:x,className:`fixed z-50 w-[270px] max-w-[90vw] rounded-md border bg-popover p-2 shadow-elevation-4`,style:{left:S.x,top:S.y},children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between px-1 pb-1.5`,children:[(0,Q.jsx)(`span`,{className:`text-xs font-medium`,children:`Icon & color`}),(0,Q.jsx)(`button`,{type:`button`,onClick:a,className:`text-muted-foreground hover:text-foreground`,children:(0,Q.jsx)(z,{className:`w-3.5 h-3.5`})})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap gap-1.5 px-1 pb-2`,children:[_i.map(e=>(0,Q.jsx)(`button`,{type:`button`,title:e,onClick:()=>r({color:e}),className:G(`w-5 h-5 rounded-full border transition-transform hover:scale-110`,n.color===e?`ring-2 ring-offset-1 ring-foreground`:`border-border`),style:{backgroundColor:e}},e)),(0,Q.jsx)(`button`,{type:`button`,title:`No color`,onClick:()=>r({color:void 0}),className:G(`w-5 h-5 rounded-full border flex items-center justify-center text-muted-foreground hover:scale-110 transition-transform`,!n.color&&`ring-2 ring-offset-1 ring-foreground`),children:(0,Q.jsx)(z,{className:`w-3 h-3`})}),(0,Q.jsx)(`label`,{title:`Custom color`,className:G(`relative w-5 h-5 rounded-full border border-border cursor-pointer hover:scale-110 transition-transform overflow-hidden`,n.color&&!_i.includes(n.color)&&`ring-2 ring-offset-1 ring-foreground`),style:{background:n.color&&!_i.includes(n.color)?n.color:`conic-gradient(from 0deg, #ef4444, #eab308, #22c55e, #06b6d4, #6366f1, #ec4899, #ef4444)`},children:(0,Q.jsx)(`input`,{type:`color`,value:n.color??`#3b82f6`,onChange:e=>r({color:e.target.value}),className:`absolute inset-0 opacity-0 cursor-pointer`})})]}),(0,Q.jsx)(`input`,{ref:m,value:o,onChange:e=>s(e.target.value),placeholder:`Search icons…`,className:`w-full mb-2 rounded-sm border bg-background px-2 py-1 text-xs outline-none focus:ring-1 focus:ring-primary`}),f||y?(0,Q.jsxs)(`div`,{className:`flex items-center justify-center gap-2 py-8 text-xs text-muted-foreground`,children:[(0,Q.jsx)(Dt,{className:`w-4 h-4 animate-spin`}),` `,y?`Searching…`:`Loading icons…`]}):(0,Q.jsxs)(`div`,{className:`grid grid-cols-7 gap-0.5 max-h-[200px] overflow-y-auto`,children:[(0,Q.jsx)(`button`,{type:`button`,title:`No icon`,onClick:()=>r({icon:void 0}),className:G(`aspect-square flex items-center justify-center rounded-sm hover:bg-accent text-muted-foreground`,!n.icon&&`bg-accent ring-1 ring-primary`),children:(0,Q.jsx)(z,{className:`w-4 h-4`})}),b.map(e=>(0,Q.jsx)(`button`,{type:`button`,title:e.replace(/^[^:]+:/,``).replace(`-fill`,``),onClick:t=>g(e,t.timeStamp),className:G(`aspect-square flex items-center justify-center rounded-sm hover:bg-accent`,n.icon===e&&`bg-accent ring-1 ring-primary`),children:(0,Q.jsx)(i,{icon:e,width:18,height:18,color:n.color})},e))]}),!f&&!y&&b.length===0&&(0,Q.jsxs)(`div`,{className:`px-1 py-3 text-center text-[11px] text-muted-foreground`,children:[`No icons match “`,o,`”`]})]})]}),document.body)}var rc=[{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.`}],ic=`canvas:treeStyle`;function ac(){try{let e=localStorage.getItem(ic);return e===`accordion`||e===`accordion-mobile`?e:`cards`}catch{return`cards`}}var oc=ac(),sc=new Set;function cc(){return oc}function lc(e){try{e===`cards`?localStorage.removeItem(ic):localStorage.setItem(ic,e)}catch{}oc=e;for(let e of sc)e()}function uc(e){sc.add(e);let t=t=>{(t.key===ic||t.key===null)&&(oc=ac(),e())};return window.addEventListener(`storage`,t),()=>{sc.delete(e),window.removeEventListener(`storage`,t)}}function dc(){return(0,Z.useSyncExternalStore)(uc,cc,()=>`cards`)}function fc(){let e=dc(),t=Fr();return e===`accordion`||e===`accordion-mobile`&&t}var pc=22,mc=44,hc=4;function gc(e,t){if(!t)return null;let n=String(e||``).split(`/`).filter(Boolean);return n[0]===`workspace`&&n[1]===`git`?null:n[0]===`workspace`&&n.length>=2?{address:`workspace:${n[1]}`,key:n.slice(2).join(`/`)}:n[0]===`device`&&n.length>=3?{address:n[2],key:n.slice(3).join(`/`)}:n[0]===`file`&&n.length>=2?{address:n[1],key:n.slice(2).join(`/`)}:null}function _c(e,t){return!t||sr(e)!==null}var vc=e=>Array.from(e.dataTransfer.types).includes(`application/json`);function yc(e,t){if(!t)return null;let n=String(e||``).split(`/`).filter(Boolean);return n[0]===`workspace`&&n[1]===`git`?n[2]||null:n[0]===`workspace`&&n.length>=2?`workspace:${n[1]}`:n[0]===`device`?n.length>=3?n[2]:null:n.length>=2?n[1]:null}function bc({x:e,y:t,node:n,path:r,isBackendsTree:i,isDirectoryTree:a,backends:o,onClose:s,onShowContent:c,onOpenToSide:l,sourceLayer:u,targetLayers:d,clipboard:f,onStartInlineCreate:p,onChangeIcon:m,onNewCanvas:h,onShareCanvas:g,onRemove:_,onRename:v,onExportSubtree:y,onImportSubtree:b,onImportDocuments:x,onExportDocuments:S,onLock:C,onUnlock:w,onDestroy:T,onMerge:E,onSubtract:D,onMergeDown:O,onSubtractDown:A,onResyncBackend:M,canResyncBackend:N,onAddRule:ee,onAddStoreRule:P,onStoragePolicy:te,onRenameBackendFolder:ne,onDeleteBackendFolder:re,onRestoreTrash:ie,onDiscardTrash:F,onCopy:oe,onCut:I,onPaste:se,pastedDocumentIds:ce,onPasteDocuments:le,isPinned:ue,onTogglePin:L}){let R=u&&d.size>0&&u.path===r,z=!i&&(O||A)&&r!==`/`&&n.type!==`canvas`&&r.split(`/`).filter(Boolean).length>1,B=u&&d.size>0&&(u.path===r||d.has(r)),fe=async e=>{s();try{await e()}catch(e){alert(e instanceof Error?e.message:String(e))}},H=(e,t,n,r=!1)=>(0,Q.jsxs)(`button`,{type:`button`,className:G(`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,r&&`text-destructive hover:bg-destructive/10`),onClick:()=>fe(n),children:[e,t]});return i&&n.metadata?.backendTrash?(0,Q.jsxs)(wn,{x:e,y:t,onClose:s,className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[c&&H((0,Q.jsx)(Fe,{className:`h-3 w-3`}),`Open Trash`,async()=>c(r)),r!==`/Trash`&&ie&&H((0,Q.jsx)(we,{className:`h-3 w-3`}),`Restore original paths`,()=>ie(r)),r!==`/Trash`&&F&&H((0,Q.jsx)(Fe,{className:`h-3 w-3`}),`Empty Trash`,()=>F(r),!0)]}):(0,Q.jsxs)(wn,{x:e,y:t,onClose:s,className:`min-w-[11rem] rounded-md border bg-popover p-1 shadow-elevation-3`,children:[c&&H((0,Q.jsx)(it,{className:`w-3 h-3`}),`Show layer content`,async()=>{c(r,n.id||void 0)}),l&&H((0,Q.jsx)(it,{className:`w-3 h-3`}),`Open to the side`,async()=>{l(r)}),(c||l)&&(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`}),n.type===`canvas`&&g&&H((0,Q.jsx)(Ct,{className:`w-3 h-3`}),`Share canvas`,async()=>{await g(r)}),n.type===`canvas`&&g&&(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`}),M&&(N?.(r)??!!yc(r,i))&&(0,Q.jsxs)(Q.Fragment,{children:[H((0,Q.jsx)(_t,{className:`w-3 h-3`}),`Refresh backend`,async()=>{await M(r)}),(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),i&&yc(r,i)&&(ee||P)&&(0,Q.jsxs)(Q.Fragment,{children:[ee&&H((0,Q.jsx)(Re,{className:`w-3 h-3`}),`Auto-Link documents to…`,async()=>{ee(r)}),P&&gc(r,i)&&H((0,Q.jsx)(j,{className:`w-3 h-3`}),`Create storage rule…`,async()=>{P(r)}),(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),!i&&(P||te)&&r!==`/`&&(0,Q.jsxs)(Q.Fragment,{children:[P&&H((0,Q.jsx)(j,{className:`w-3 h-3`}),`Create rule…`,async()=>{P(r)}),P&&H((0,Q.jsx)(Bt,{className:`w-3 h-3`}),`Create download rule…`,async()=>{P(r,`download`)}),te&&n.type!==`canvas`&&H((0,Q.jsx)(de,{className:`w-3 h-3`}),`Storage policy…`,async()=>{te(r)}),(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),(!i||gc(r,i))&&(0,Q.jsxs)(`button`,{type:`button`,className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,onClick:()=>{p(r),s()},children:[(0,Q.jsx)(ge,{className:`w-3 h-3`}),`New folder here`]}),ne&&gc(r,i)?.key&&H((0,Q.jsx)(je,{className:`w-3 h-3`}),`Rename folder`,async()=>{let e=r.split(`/`).pop()||``,t=prompt(`New folder name:`,e);!t||t===e||await ne(r,t)}),re&&i&&tr(r,o)&&H((0,Q.jsx)(Fe,{className:`w-3 h-3`}),`Delete from backend`,async()=>{confirm(`Delete folder "${r.split(`/`).pop()}" and its contents from the backend?`)&&await re(r)},!0),h&&!i&&(0,Q.jsxs)(`button`,{type:`button`,className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,onClick:()=>{h(r),s()},children:[(0,Q.jsx)(qe,{className:`w-3 h-3 text-primary`}),`New canvas here…`]}),r!==`/`&&L&&H(ue?(0,Q.jsx)(W,{className:`w-3 h-3`}):(0,Q.jsx)(V,{className:`w-3 h-3`}),ue?`Unpin`:`Pin`,async()=>{await L()}),r!==`/`&&m&&(0,Q.jsxs)(`button`,{type:`button`,className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,onClick:()=>{m(),s()},children:[(0,Q.jsx)(ae,{className:`w-3 h-3`}),`Change icon`]}),r!==`/`&&!n.locked&&v&&!i&&H((0,Q.jsx)(je,{className:`w-3 h-3`}),`Rename`,async()=>{let e=r.split(`/`).pop()||``,t=prompt(`New name:`,e);!t||t===e||await v(r,t)}),(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`}),H((0,Q.jsx)(Ce,{className:`w-3 h-3`}),`Copy`,async()=>oe(r)),!i&&H((0,Q.jsx)(Kt,{className:`w-3 h-3`}),`Cut`,async()=>I(r)),f&&!i&&H((0,Q.jsx)(k,{className:`w-3 h-3`}),`Paste (${f.mode})`,async()=>se(r)),ce&&ce.length>0&&le&&_c(r,i)&&H((0,Q.jsx)(k,{className:`w-3 h-3`}),i?`Move ${ce.length} message(s) here`:`Paste ${ce.length} document(s)`,async()=>{await le(r,ce)}),x&&H((0,Q.jsx)(Ot,{className:`w-3 h-3`}),`Import documents…`,()=>x(r)),S&&H((0,Q.jsx)(Bt,{className:`w-3 h-3`}),`Export documents…`,()=>S(r)),(y||b)&&(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`}),y&&n.type!==`canvas`&&H((0,Q.jsx)(Bt,{className:`w-3 h-3`}),`Export subtree…`,()=>y(r)),b&&!i&&n.type!==`canvas`&&H((0,Q.jsx)(Ot,{className:`w-3 h-3`}),`Import subtree here…`,()=>b(r)),!i&&r!==`/`&&!n.locked&&_&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`}),H((0,Q.jsx)(Fe,{className:`w-3 h-3`}),`Remove`,async()=>{confirm(`Remove "${r}"${a?` and all children`:``}?`)&&await _(r,a)},!0),!a&&H((0,Q.jsx)(Fe,{className:`w-3 h-3`}),`Remove recursive`,async()=>{confirm(`Remove "${r}" and all children?`)&&await _(r,!0)},!0)]}),!i&&(C||w||T)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`}),n.locked?w&&H((0,Q.jsx)($e,{className:`w-3 h-3`}),`Unlock layer`,async()=>{await w(n.id)}):C&&H((0,Q.jsx)(Ft,{className:`w-3 h-3`}),`Lock layer`,async()=>{await C(n.id)}),n.locked&&n.lockedBy&&n.lockedBy.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`px-3 pt-1 pb-0.5 text-[10px] uppercase tracking-wide text-muted-foreground`,children:`Locked by`}),n.lockedBy.map(e=>(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-2 px-3 py-1 text-xs`,children:[(0,Q.jsx)(`span`,{className:`truncate`,title:e,children:e}),w&&(0,Q.jsx)(`button`,{type:`button`,title:`Remove lock held by ${e}`,className:`shrink-0 text-muted-foreground hover:text-destructive`,onClick:()=>fe(async()=>{await w(n.id,e)}),children:(0,Q.jsx)($e,{className:`w-3 h-3`})})]},e))]}),r!==`/`&&!n.locked&&T&&H((0,Q.jsx)(Fe,{className:`w-3 h-3`}),`Destroy layer`,async()=>{confirm(`Permanently destroy layer "${n.label||n.name}" and its bitmap?`)&&await T(n.id)},!0)]}),z&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`}),O&&H((0,Q.jsx)(ut,{className:`w-3 h-3`}),`Merge down (into ancestors)`,async()=>{confirm(`Merge "${n.label||n.name}" into every layer above it on\n${r}\n\nAfter this, ${r} lists its documents.`)&&await O(r)}),A&&H((0,Q.jsx)(vt,{className:`w-3 h-3`}),`Subtract from ancestors`,async()=>{confirm(`Remove "${n.label||n.name}"'s documents from every layer above it on\n${r}\n\nUndo of "Merge down". Documents an ancestor holds for other reasons are removed from it too.`)&&await A(r)})]}),R&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`}),E&&H((0,Q.jsx)(xe,{className:`w-3 h-3`}),`Merge this layer into ${d.size} selected`,async()=>{confirm(`Merge "${r}" (source) INTO:\n${Array.from(d.keys()).join(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/apps-DbYkQgyL.js","assets/rolldown-runtime-C0FnF6B9.js","assets/code-editor-BOIngd5F.js","assets/chunk-62JRHF6Z-vspAGgtK.js","assets/preload-helper-Czpn1I53.js","assets/utils-2pl1SbIp.js","assets/utils-BxVxyehK.js","assets/workspace-46EFyEKZ.js","assets/react-BHzhHVTZ.js","assets/button-Bum-POPT.js","assets/ui-76Hw0NU_.js","assets/input-BOtCd4HP.js","assets/api-CA6WiiYM.js","assets/alert-dialog-CShuAcnP.js","assets/context-BGgz0Y_q.js","assets/registry-BEyieXxp.js","assets/applet-target-Bl9Je1N-.js","assets/use-applet-target-DmIdCxa_.js","assets/use-toolbox-Ck_cLGgf.js","assets/workspaces-BZ395Y1p.js","assets/use-toast-BlLDqSUO.js","assets/use-mobile-Db-vWu9Y.js","assets/layer-style-Byl5LNFR.js","assets/color-DFEH4BfK.js","assets/workspace-access-C9nZlBBZ.js","assets/use-menu-CaiLyPdw.js","assets/last-path-BbXWC3b3.js","assets/url-params-n7kU_WZ-.js","assets/page-header-BoCaZiqu.js","assets/form-panel-DZj3WZ3z.js","assets/use-create-panel-DhSNIGtr.js","assets/useSocketSubscription-ifW-vnlb.js","assets/socket-hM4c-ZSl.js","assets/workspace-import-form-Bu1nlv8u.js","assets/_workspaceName_-DfNeZ188.js","assets/socket-CtH3EU9m.js","assets/use-canvas-pins-D-zi5fqQ.js","assets/auth-Bx9fAZmz.js","assets/LinkToCard-VXpoeMDH.js","assets/useEscapeClose-DR_xKT_k.js","assets/useToastHelpers-CRrpIIdY.js","assets/DocumentIcon-ByDAILhm.js","assets/TodosWidget-CX4lgk-9.js","assets/ObjectPropertiesCard-CFZ_LqzX.js","assets/label-DJc8-3CQ.js","assets/IdentityFields-CEDxU-Hd.js","assets/tags-YamdPoBK.js","assets/useAddTarget-D4ra50Am.js","assets/date-time-picker-Bzu8H_Oa.js","assets/relation-events-CKio19hE.js","assets/map-BxCwdK0d.js","assets/map-BcsP_QXj.css","assets/public-share-D2S8DEsv.js","assets/text-documents-CFW8MWES.js","assets/blobs-WiXP9QRi.js","assets/useDocumentThumbnail-Bs2Ju0eb.js","assets/markdown-view-BBBZtNSR.js","assets/sanitize-DrVcFY1Q.js","assets/MessageComposerDialog-BKGlI7jO.js","assets/markdown-it-DRESbtwK.js","assets/punycode.es6-ZbLrB_Dn.js","assets/lazy-editor-Bdm5JEXv.js","assets/LinkToSidePanel-eCy3nW4R.js","assets/note-save-status-DPz4VzL6.js","assets/useEditNoteFields-CKYMBf8V.js","assets/DocumentBodyEditor-DRFQgBNB.js","assets/use-document-modal-PG8bQyIB.js","assets/sketch-lazy-BOFTGGTA.js","assets/geo-CZfs0E-x.js","assets/ObjectPropertiesCard-JArcZXXv.css","assets/document-list-CwStaizB.js","assets/document-open-mode-DoImW-xs.js","assets/PickDocumentsCard-B72XNYh3.js","assets/backend-sync-progress-BJsLP7o5.js","assets/PathPickerField-B58yeJGw.js","assets/backend-sync-progress-DU-e9TWi.css","assets/search-COMZIxA7.js","assets/use-sortable-data-W2inLcb5.js","assets/workspace-BydSRtST.js","assets/document-list-DAYdk5vh.css","assets/use-canvas-pins-C57Vbkrq.css","assets/workspace-area-menu-DtsodEXC.js","assets/workspace-content-gate-CGZmT2kw.js","assets/content-app-view-B4ada874.js","assets/FileForm-B6eFRKG-.js","assets/UploadProgressList-CHQ-Kn-e.js","assets/sha256-65KIjGvZ.js","assets/query-debug-CZacGe0M.js","assets/document-Ds_P5v-f.js","assets/use-workspace-identity-KxY9injc.js","assets/home-BWAoF6jL.js","assets/HomeFab-B_AndThd.js","assets/desk-dI_FvLsK.js","assets/share-target-pA9r0Obg.js","assets/contexts-CwGdjtXy2.js","assets/_contextId_-xoan5Zgw.js","assets/api-tokens-CmHhwd58.js","assets/use-settings-back-DE0SPb7h.js","assets/devices-CmVlYbam.js","assets/devices-CAa1bRxk.js","assets/settings-CFbSvlXK.js","assets/appearance-C8m9uEmD.js","assets/use-theme-DaxpiICf.js","assets/key-bindings-C3rMnRos.js","assets/offline-yfQ63Zr7.js","assets/about-DWl4-RY1.js","assets/embedding-2EjzoVFT.js","assets/inferd-config-editor-CyDCQJRs.js","assets/shared-ZTRGU8MK.js","assets/workspaces-p959p9BR.js","assets/admin-Bhg9QBHL.js","assets/contexts-Dtl9oERX.js","assets/agents-DEJU4O1Z.js","assets/logs-DUeiDqCX.js","assets/roles-BHJYWaBs.js","assets/role-C5I0Plgn.js","assets/users-DInwKAxz.js","assets/embedding-BqI3l5RB.js","assets/auth-_bmIEN02.js","assets/agents-DT1XtFUN.js","assets/useAgentModels-fXPBeHX2.js","assets/_agentId_-GsPtoz9i.js","assets/settings-BZsdOcHy.js","assets/settings-DD2zxZ8C.js","assets/settings-QL_HG2aL.js","assets/roles-CuqCEPC7.js","assets/remotes-BjjlqN_M.js","assets/add-AHQUHZBr.js","assets/NextShell-BvKyH2Oj.js","assets/NextShell-BT6-_CFY.css"])))=>i.map(i=>d[i]);
2
+ import{o as e,r as t}from"./rolldown-runtime-C0FnF6B9.js";import{l as n,u as r}from"./code-editor-BOIngd5F.js";import{_t as i,st as a,vt as o,yt as s}from"./react-BHzhHVTZ.js";import{t as c}from"./preload-helper-Czpn1I53.js";import{_ as l,a as u,c as d,d as f,f as p,g as m,h,i as g,l as _,m as v,n as y,o as b,p as x,r as S,s as C,t as w,u as T,v as E}from"./chunk-62JRHF6Z-vspAGgtK.js";import{$r as D,$t as O,Ar as k,B as A,Bn as j,Br as M,Bt as N,C as ee,Ct as P,En as te,F as ne,Fr as re,Ft as ie,Gr as F,Gt as ae,H as oe,Hn as I,Hr as se,Ht as ce,I as le,In as ue,It as L,J as R,Jn as de,L as z,Lr as B,Lt as V,Mn as fe,Nn as H,Nr as pe,On as me,P as he,Pt as ge,Q as _e,Qn as ve,Qt as U,R as ye,Rt as W,S as be,Sn as xe,Sr as Se,Tr as Ce,Tt as we,U as Te,Un as Ee,Ur as De,Ut as Oe,V as ke,Vr as Ae,Vt as je,W as Me,Wn as Ne,Wr as Pe,X as Fe,Xr as Ie,Xt as Le,Yn as Re,Zn as ze,Zr as Be,_ as Ve,_i as He,_n as Ue,_t as We,an as Ge,b as Ke,bn as qe,br as Je,cn as Ye,cr as Xe,ct as Ze,d as Qe,dn as $e,er as et,f as tt,fi as nt,fn as rt,fr as it,g as at,gi as ot,gr as st,gt as ct,h as lt,hi as ut,hn as dt,hr as ft,ht as pt,ii as mt,in as ht,kr as gt,kt as _t,li as vt,ln as yt,lt as bt,m as xt,mr as St,mt as Ct,nn as wt,or as Tt,p as Et,pn as Dt,qn as Ot,qr as kt,rt as At,sn as jt,tr as Mt,tt as Nt,u as Pt,un as Ft,ut as It,v as Lt,vi as Rt,vn as zt,vr as Bt,vt as Vt,w as Ht,x as Ut,xn as Wt,xr as Gt,xt as Kt,y as qt,yt as Jt,z as Yt,zr as Xt}from"./ui-76Hw0NU_.js";import{i as Zt,r as Qt}from"./utils-BxVxyehK.js";import{n as $t,t as G}from"./utils-2pl1SbIp.js";import{t as K}from"./button-Bum-POPT.js";import{t as en}from"./input-BOtCd4HP.js";import{t as q}from"./label-DJc8-3CQ.js";import{a as tn,c as nn,i as rn,l as J,n as an,o as on,r as sn,s as cn,t as Y,u as ln}from"./api-CA6WiiYM.js";import{t as un}from"./socket-hM4c-ZSl.js";import{t as X}from"./socket-CtH3EU9m.js";import{a as dn,c as fn,d as pn,i as mn,l as hn,n as gn,o as _n,r as vn,s as yn,t as bn}from"./auth-Bx9fAZmz.js";import{n as xn,t as Sn}from"./use-toast-BlLDqSUO.js";import{_ as Cn,h as wn,m as Tn,p as En,t as Dn}from"./LinkToCard-VXpoeMDH.js";import{An as On,B as kn,Bt as An,C as jn,Cn as Mn,Dn as Nn,Dt as Pn,E as Fn,G as In,Lt as Ln,Nt as Rn,O as zn,On as Bn,Pn as Vn,Pt as Hn,Q as Un,S as Wn,Sn as Gn,St as Kn,Tt as qn,V as Jn,Xt as Yn,Zt as Xn,_ as Zn,_n as Qn,b as $n,bn as er,c as tr,gt as nr,h as rr,hn as ir,ht as ar,jt as or,lt as sr,mn as cr,mt as lr,on as ur,r as dr,sn as fr,tt as pr,vn as mr,xn as hr,yt as gr,zt as _r}from"./workspace-46EFyEKZ.js";import{r as vr,t as yr}from"./use-canvas-pins-D-zi5fqQ.js";import{a as br,i as xr,n as Sr,o as Cr,r as wr}from"./ObjectPropertiesCard-CFZ_LqzX.js";import{c as Tr,d as Er,f as Dr,i as Or,m as kr,n as Ar,p as jr,s as Mr,u as Nr}from"./document-list-CwStaizB.js";import{n as Pr,t as Fr}from"./use-mobile-Db-vWu9Y.js";import{a as Ir,i as Lr,s as Rr,t as zr}from"./IdentityFields-CEDxU-Hd.js";import{n as Br,t as Vr}from"./public-share-D2S8DEsv.js";import{t as Hr}from"./markdown-view-BBBZtNSR.js";import{n as Ur,t as Wr}from"./tags-YamdPoBK.js";import{a as Gr,c as Kr,i as qr,l as Jr,n as Yr,o as Xr,r as Zr,s as Qr,t as $r,u as ei}from"./useAddTarget-D4ra50Am.js";import{n as ti,r as ni,t as ri}from"./use-toolbox-Ck_cLGgf.js";import{D as ii,E as ai,O as oi,a as si,p as ci,s as li,v as ui,w as di}from"./context-BGgz0Y_q.js";import{r as fi}from"./relation-events-CKio19hE.js";import{c as pi}from"./date-time-picker-Bzu8H_Oa.js";import{t as mi}from"./PickDocumentsCard-B72XNYh3.js";import{t as hi}from"./useEscapeClose-DR_xKT_k.js";import{t as gi}from"./useToastHelpers-CRrpIIdY.js";import{a as _i,c as vi,d as yi,l as bi,s as xi}from"./layer-style-Byl5LNFR.js";import{i as Si,r as Ci}from"./color-DFEH4BfK.js";import{n as wi}from"./MessageComposerDialog-BKGlI7jO.js";import{n as Ti,t as Ei}from"./LinkToSidePanel-eCy3nW4R.js";import{n as Di,r as Oi,t as ki}from"./note-save-status-DPz4VzL6.js";import{t as Ai}from"./useEditNoteFields-CKYMBf8V.js";import{t as ji}from"./DocumentBodyEditor-DRFQgBNB.js";import{n as Mi,t as Ni}from"./map-BxCwdK0d.js";import{o as Pi}from"./blobs-WiXP9QRi.js";import{n as Fi,t as Ii}from"./use-document-modal-PG8bQyIB.js";import{n as Li,r as Ri}from"./geo-CZfs0E-x.js";import{C as zi,W as Bi,_ as Vi,c as Hi,g as Ui,i as Wi,s as Gi,y as Ki,z as qi}from"./backend-sync-progress-BJsLP7o5.js";import{t as Ji}from"./workspace-access-C9nZlBBZ.js";import{t as Yi}from"./PathPickerField-B58yeJGw.js";import{a as Xi,c as Zi,i as Qi,o as $i,r as ea,s as ta,t as na}from"./workspace-BydSRtST.js";import{n as ra,t as ia}from"./url-params-n7kU_WZ-.js";import{a as aa,c as oa,d as sa,f as ca,i as la,m as ua,n as da,p as fa,r as pa,t as ma}from"./use-menu-CaiLyPdw.js";import{n as ha,t as ga}from"./registry-BEyieXxp.js";import{n as _a}from"./use-applet-target-DmIdCxa_.js";import{r as va,t as ya}from"./last-path-BbXWC3b3.js";import{t as ba}from"./workspace-area-menu-DtsodEXC.js";import{t as xa}from"./workspace-content-gate-CGZmT2kw.js";import{c as Sa,s as Ca}from"./UploadProgressList-CHQ-Kn-e.js";import{n as wa,r as Ta,t as Ea}from"./FileForm-B6eFRKG-.js";import{n as Da}from"./use-theme-DaxpiICf.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 Z=e(r(),1),Oa=o(),Q=n(),ka=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(`div`,{ref:n,className:G(`rounded-(--card-radius) border bg-card text-card-foreground shadow-elevation-1`,e),...t}));ka.displayName=`Card`;var Aa=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(`div`,{ref:n,className:G(`flex flex-col space-y-1.5 p-6`,e),...t}));Aa.displayName=`CardHeader`;var ja=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(`h3`,{ref:n,className:G(`text-2xl font-semibold leading-none tracking-tight`,e),...t}));ja.displayName=`CardTitle`;var Ma=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(`p`,{ref:n,className:G(`text-sm text-muted-foreground`,e),...t}));Ma.displayName=`CardDescription`;var Na=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(`div`,{ref:n,className:G(`p-6 pt-0`,e),...t}));Na.displayName=`CardContent`;var Pa=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(`div`,{ref:n,className:G(`flex items-center p-6 pt-0`,e),...t}));Pa.displayName=`CardFooter`;var Fa=`2.26.31`,Ia=e=>{window.particlesJS.load(e,`/js/particles.config.json`,()=>{console.log(`particles.js config loaded for`,e)})};function La(e){(0,Z.useEffect)(()=>{if(window.particlesJS!==void 0)Ia(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`),Ia(e)},document.head.appendChild(t)}return()=>{window.pJS&&window.pJS[e]?.destroy&&window.pJS[e].destroy()}},[e])}function Ra(){let[e,t]=(0,Z.useState)(null),[n,r]=(0,Z.useState)(!0),[i,a]=(0,Z.useState)(null);return(0,Z.useEffect)(()=>{let e=!0;async function n(){try{r(!0),a(null);let n=await Y.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 za=`https://github.com/canvas-ui/canvas-server`,Ba=null;function Va(){return Ba||=Y.get(`/ping`,{skipAuth:!0}).then(e=>{let t=e??{};return{sourceUrl:t.sourceUrl||za,version:t.version??null,commit:t.commit??null,license:t.license??null}}).catch(e=>(console.error(`Failed to fetch server source info:`,e),Ba=null,{sourceUrl:za,version:null,commit:null,license:null})),Ba}function Ha(){let[e,t]=(0,Z.useState)(null);return(0,Z.useEffect)(()=>{let e=!0;return Va().then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function Ua({className:e=``}){let t=Ha();if(!t)return null;let n=[t.version?`v${t.version}`:null,t.commit?.slice(0,7)].filter(Boolean).join(` `);return(0,Q.jsxs)(`p`,{className:`text-xs text-muted-foreground ${e}`,children:[`Powered by`,` `,(0,Q.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,Q.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})}function Wa({children:e}){La(`particle-js`);let{serverVersion:t,isLoading:n,error:r}=Ra();return(0,Q.jsx)(`div`,{className:`flex min-h-viewport w-full items-center justify-center p-4 flex-col`,children:(0,Q.jsxs)(ka,{className:`flex w-[95vw] h-viewport-modal overflow-hidden`,children:[(0,Q.jsxs)(`div`,{className:`hidden md:block w-1/2 relative bg-background`,"data-scheme":`dark`,id:`particle-js`,children:[(0,Q.jsxs)(S,{className:`absolute top-8 left-8 font-bold text-foreground flex items-center z-raised`,to:`/`,children:[(0,Q.jsx)(`img`,{src:`/images/logo-wr_128x128.png`,alt:`Canvas Logo`,className:`mr-2 h-6 w-6 touch-target`}),(0,Q.jsx)(`span`,{className:`text-2xl font-bold text-foreground`,children:`Canvas`})]}),(0,Q.jsxs)(`div`,{className:`absolute bottom-8 left-8 text-sm text-foreground max-w-[80%] z-raised`,children:[`Web UI: v`,Fa,`, Server: `,n?`Loading...`:r?`Unavailable`:t?`v${t}`:`Unknown`]})]}),(0,Q.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,Q.jsxs)(`div`,{className:`mx-auto w-full max-w-sm`,children:[e,(0,Q.jsxs)(`div`,{className:`mt-8 border-t pt-6`,children:[(0,Q.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,Q.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,Q.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,Q.jsx)(`span`,{children:`View on GitHub`})]}),(0,Q.jsx)(Ua,{className:`mt-4 text-center`})]})]})})]})})}var Ga=e=>e?.strategies?.local?.enabled!==!1,Ka=e=>e?.allowUserRegistrations!==!1;function qa(){let e=m(),[t,n]=Z.useState(!1),[r,a]=Z.useState(``),[o,s]=Z.useState(``),[c,l]=Z.useState(!1),[u,d]=Z.useState({}),[f,p]=Z.useState(null),[h,g]=Z.useState({email:``,password:``,strategy:`auto`});Z.useEffect(()=>{dn()&&e(`/workspaces`),fetch(`${J}/runtime/capabilities`).then(e=>e.ok?e.json():null).then(e=>n(e?.payload?.local===!0)).catch(()=>{}),gn().then(e=>{p(e)}).catch(e=>{console.error(`Failed to load auth config:`,e)})},[e]);let _=()=>{let e={};return h.email?/\S+@\S+\.\S+/.test(h.email)||(e.email=`Email is invalid`):e.email=`Email is required`,h.password||(e.password=`Password is required`),d(e),Object.keys(e).length===0},v=e=>{let{name:t,value:n}=e.target;g(e=>({...e,[t]:n}))};async function y(t){if(t.preventDefault(),_()){l(!0);try{console.log(`Attempting login with:`,h.email,`strategy:`,h.strategy);let t=await fn(h.email,h.password,h.strategy);console.log(`Login successful, received token:`,`token`in t?!!t.token:!!t.payload?.token),d({}),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)}d({password:t})}finally{l(!1)}}}return t?(0,Q.jsx)(Wa,{children:(0,Q.jsxs)(`form`,{className:`grid gap-4`,onSubmit:async t=>{t.preventDefault(),l(!0),s(``);try{if(Y.setAuthToken(r.trim()),!await vn())throw Error(`The local token was not accepted`);e(`/workspaces`)}catch(e){Y.clearAuthToken(),s(e instanceof Error?e.message:`Authentication failed`)}finally{l(!1)}},children:[(0,Q.jsx)(`h1`,{className:`text-2xl font-semibold`,children:`Connect to your local runtime`}),(0,Q.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Enter the token shown by `,(0,Q.jsx)(`code`,{children:`canvas runtime token`}),` in the runtime folder.`]}),(0,Q.jsx)(q,{htmlFor:`local-token`,children:`Local access token`}),(0,Q.jsx)(en,{id:`local-token`,type:`password`,autoComplete:`off`,value:r,onChange:e=>a(e.target.value),required:!0}),o&&(0,Q.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:o}),(0,Q.jsx)(K,{disabled:c,children:c?`Connecting…`:`Connect`})]})}):(0,Q.jsx)(Wa,{children:(0,Q.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Q.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Welcome back`}),(0,Q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your credentials to access your account`})]}),(0,Q.jsx)(`form`,{onSubmit:y,children:(0,Q.jsxs)(`div`,{className:`grid gap-4`,children:[f?.strategies?.imap?.enabled&&f.strategies.imap.domains.length>0&&(0,Q.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Q.jsx)(q,{htmlFor:`strategy`,children:`Authentication Method`}),(0,Q.jsxs)(`select`,{id:`strategy`,name:`strategy`,value:h.strategy,onChange:v,disabled:c,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,Q.jsx)(`option`,{value:`auto`,children:`Auto-detect`}),(0,Q.jsx)(`option`,{value:`local`,children:`Local Account`}),(0,Q.jsx)(`option`,{value:`imap`,children:`Email Server (IMAP)`})]})]}),(0,Q.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Q.jsx)(q,{htmlFor:`email`,children:`Email`}),(0,Q.jsx)(en,{id:`email`,name:`email`,placeholder:`name@example.com`,type:`email`,autoCapitalize:`none`,autoComplete:`email`,autoCorrect:`off`,disabled:c,value:h.email,onChange:v}),u.email&&(0,Q.jsx)(`p`,{className:`text-sm text-destructive`,children:u.email})]}),(0,Q.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Q.jsx)(q,{htmlFor:`password`,children:`Password`}),(0,Q.jsx)(en,{id:`password`,name:`password`,type:`password`,disabled:c,value:h.password,onChange:v}),u.password&&(0,Q.jsx)(`p`,{className:`text-sm text-destructive`,children:u.password})]}),(0,Q.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,Q.jsx)(K,{type:`submit`,disabled:c,children:c?`Signing in...`:`Sign In`}),f?.strategies?.google?.enabled&&(0,Q.jsxs)(K,{type:`button`,variant:`outline`,disabled:c,onClick:()=>pn(),children:[(0,Q.jsx)(i,{icon:`logos:google-icon`,width:16,height:16,className:`mr-2`}),`Sign in with Google`]}),Ga(f)&&Ka(f)&&(0,Q.jsx)(K,{variant:`outline`,type:`button`,disabled:c,onClick:()=>e(`/register`),children:`Don't have an account? Sign up`})]})]})})]})})}function Ja(){let e=m(),{showToast:t}=xn(),[n,r]=Z.useState(!1),[i,a]=Z.useState({}),[o,s]=Z.useState({name:``,email:``,password:``}),[c,l]=Z.useState(!1),[u,d]=Z.useState(!1),[f,p]=Z.useState(null);Z.useEffect(()=>{(async()=>{let t=await gn(),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 h=Z.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]),g=()=>{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},_=e=>{let t={...o,[e.target.id]:e.target.value};s(t),(e.target.id===`name`||e.target.id===`email`||e.target.id===`password`)&&g()};return c?(0,Q.jsxs)(Wa,{children:[(0,Q.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Q.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Registration Successful!`}),(0,Q.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,Q.jsx)(`div`,{className:`space-y-6 text-center pt-6`,children:!u&&(0,Q.jsx)(K,{asChild:!0,className:`w-full`,children:(0,Q.jsx)(S,{to:`/login`,children:`Go to Login`})})})]}):(0,Q.jsxs)(Wa,{children:[(0,Q.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Q.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Create an account`}),(0,Q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your email below to create your account`})]}),(0,Q.jsxs)(`form`,{onSubmit:async e=>{if(e.preventDefault(),g()){r(!0);try{let e=await hn(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,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(q,{htmlFor:`name`,children:`Username`}),(0,Q.jsx)(en,{id:`name`,type:`text`,placeholder:`Enter your username (e.g., john_doe)`,value:o.name,onChange:_,disabled:n,className:i.name?`border-destructive`:``}),i.name&&(0,Q.jsx)(`p`,{className:`text-sm text-destructive`,children:i.name}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`3-39 characters, lowercase letters, numbers, underscores, and hyphens only`})]}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(q,{htmlFor:`email`,children:`Email`}),(0,Q.jsx)(en,{id:`email`,type:`email`,placeholder:`name@example.com`,value:o.email,onChange:_,disabled:n,className:i.email?`border-destructive`:``}),i.email&&(0,Q.jsx)(`p`,{className:`text-sm text-destructive`,children:i.email})]}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(q,{htmlFor:`password`,children:`Password`}),(0,Q.jsx)(en,{id:`password`,type:`password`,placeholder:`Enter your password`,value:o.password,onChange:_,disabled:n,className:i.password?`border-destructive`:``}),i.password&&(0,Q.jsx)(`p`,{className:`text-sm text-destructive`,children:i.password}),f&&h&&(0,Q.jsxs)(`ul`,{className:`text-xs list-disc pl-4 space-y-1`,children:[(0,Q.jsxs)(`li`,{className:h.minLength?`text-success`:`text-muted-foreground`,children:[`At least `,f.minLength,` characters`]}),f.requireUppercase&&(0,Q.jsx)(`li`,{className:h.uppercase?`text-success`:`text-muted-foreground`,children:`At least one uppercase letter`}),f.requireLowercase&&(0,Q.jsx)(`li`,{className:h.lowercase?`text-success`:`text-muted-foreground`,children:`At least one lowercase letter`}),f.requireNumbers&&(0,Q.jsx)(`li`,{className:h.number?`text-success`:`text-muted-foreground`,children:`At least one number`}),f.requireSpecialChars&&(0,Q.jsx)(`li`,{className:h.special?`text-success`:`text-muted-foreground`,children:`At least one special character`}),f.maxLength&&(0,Q.jsxs)(`li`,{className:h.maxLength?`text-success`:`text-muted-foreground`,children:[`No more than `,f.maxLength,` characters`]})]})]}),(0,Q.jsx)(K,{type:`submit`,className:`w-full`,disabled:n,children:n?`Creating Account...`:`Create Account`})]}),(0,Q.jsxs)(`div`,{className:`mt-4 text-center text-sm`,children:[`Already have an account?`,` `,(0,Q.jsx)(S,{to:`/login`,className:`underline`,children:`Sign in`})]}),(0,Q.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,Q.jsx)(S,{to:`/terms`,className:`underline underline-offset-4 hover:text-primary`,children:`Terms of Service`}),` `,`and`,` `,(0,Q.jsx)(S,{to:`/privacy`,className:`underline underline-offset-4 hover:text-primary`,children:`Privacy Policy`}),`.`]})]})}function Ya(){let e=m(),[t]=E(),[n,r]=Z.useState(t.get(`error`)),i=Z.useRef(!1);return Z.useEffect(()=>{let n=t.get(`code`);!n||i.current||(i.current=!0,bn(n).then(()=>e(`/home`,{replace:!0})).catch(e=>r(e instanceof Error?e.message:`Google sign-in failed`)))},[t,e]),(0,Q.jsx)(Wa,{children:(0,Q.jsx)(`div`,{className:`flex flex-col space-y-4 text-center`,children:n?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Google sign-in failed`}),(0,Q.jsx)(`p`,{className:`text-sm text-destructive`,children:n}),(0,Q.jsx)(K,{type:`button`,variant:`outline`,onClick:()=>e(`/login`,{replace:!0}),children:`Back to sign in`})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Signing you in…`}),(0,Q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Completing Google sign-in.`})]})})})}function Xa({children:e}){let[t,n]=(0,Z.useState)(`loading`);return(0,Z.useEffect)(()=>{(async()=>{try{if(!_n()){console.log(`No authentication token found, redirecting to login`),n(`unauthenticated`);return}let e=await vn();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),yn(e)){if(dn()){n(`authenticated`);return}Y.clearAuthToken(),n(`unauthenticated`);return}e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from ProtectedRoute`),Y.clearAuthToken()),n(`unauthenticated`)}})()},[]),t===`loading`?(0,Q.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,Q.jsx)(Cn,{className:`h-8 w-8`})}):t===`unauthenticated`?(0,Q.jsx)(u,{to:`/login`,replace:!0}):(0,Q.jsx)(Q.Fragment,{children:e})}function Za({children:e}){let[t,n]=(0,Z.useState)(null);return(0,Z.useEffect)(()=>{(async()=>{try{await Y.get(`/auth/me`),n(!0)}catch(e){e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from PublicRoute`),Y.clearAuthToken()),n(!1)}})()},[]),t===null?null:t?(0,Q.jsx)(u,{to:`/workspaces`,replace:!0}):(0,Q.jsx)(Q.Fragment,{children:e})}var Qa=`data/schema/file`;function $a(e){return String(e.locations?.[0]?.url||``).trim()}function eo(e){let t=$a(e);if(!t)return``;let n=t.split(/[?#]/)[0].split(`/`).filter(Boolean).pop()||``;try{return decodeURIComponent(n)}catch{return n}}function to(e){return e.schema===Qa&&String(e.metadata?.contentType||``).startsWith(`image/`)}function no(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 ro(e){if(e.schema!==Qa)return On(e);let t=eo(e),n=String(e.metadata?.contentType||``).trim(),r=no(e.metadata?.size);return{...On(e),title:t||`File ${e.id}`,preview:[n,r].filter(Boolean).join(` · `),subtitle:$a(e),schemaLabel:`file`}}function io(e){return/^https?:\/\/[^\s]+$/i.test(e)}function ao(e,t){if(e.schema===`data/schema/tab`){let t=String(e.data?.url||``).trim();return io(t)?t:null}return t.isExternal&&io(t.subtitle)?t.subtitle:io(t.title)?t.title:null}function oo(e,t,n=!1){return Br(e,t,{download:n})}function so(e){return e.split(/(https?:\/\/[^\s]+)/gi).map((e,t)=>io(e)?(0,Q.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 co(e){return e?new Date(e).toLocaleString():``}function lo(){let{code:e=``}=l(),[t,n]=(0,Z.useState)(null),[r,i]=(0,Z.useState)(!0),[a,o]=(0,Z.useState)(null),[s,c]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(``),f=(0,Z.useMemo)(()=>t?.documents?Array.isArray(t.documents)?t.documents:t.documents.data||[]:[],[t]),p=(0,Z.useMemo)(()=>{let e=u.trim().toLowerCase();return e?f.filter(t=>{let n=ro(t);return[t.schema,n.title,n.preview,n.subtitle,eo(t),t.metadata?.contentType].join(` `).toLowerCase().includes(e)}):f},[f,u]),m=(0,Z.useCallback)(async()=>{if(e){i(!0);try{let t=await Y.get(`${J}/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,Z.useEffect)(()=>{m()},[m]),(0,Z.useEffect)(()=>{if(!e)return;let t=un(`${ln}/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`,()=>m()),()=>{t?.disconnect(),t=null}},[e,m]);let h=(0,Z.useCallback)(e=>{e?.preventDefault(),d(u.trim())},[u]),g=(0,Z.useCallback)(()=>{d(``)},[]),_=(0,Z.useCallback)(async e=>({payload:Nn(e?.sortBy)?Bn(f,e.sortBy,e?.order):f,totalCount:t?.stats.documentCount??f.length}),[f,t]);if(r&&!t)return(0,Q.jsx)(`main`,{className:`min-h-screen bg-muted flex items-center justify-center p-6`,children:(0,Q.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Loading canvas...`})});if(a||!t)return(0,Q.jsxs)(`main`,{className:`min-h-screen bg-muted flex flex-col items-center justify-center p-6`,children:[(0,Q.jsxs)(ka,{className:`max-w-md bg-card`,children:[(0,Q.jsx)(Aa,{children:(0,Q.jsx)(ja,{children:`Canvas unavailable`})}),(0,Q.jsx)(Na,{className:`text-sm text-muted-foreground`,children:a||`This public canvas does not exist.`})]}),(0,Q.jsx)(Ua,{className:`mt-6 text-center`})]});let v=t.canvas.metadata?.ui??{},y=!!v.widgets&&Object.keys(v.widgets).length>0;return(0,Q.jsx)(Vr.Provider,{value:e,children:(0,Q.jsx)(`main`,{className:`min-h-screen bg-muted p-2 text-foreground sm:p-4 md:p-10`,children:(0,Q.jsxs)(`div`,{className:`mx-auto max-w-6xl`,children:[(0,Q.jsxs)(ka,{className:`bg-card shadow-elevation-3`,children:[(0,Q.jsx)(Aa,{className:`border-b p-3 sm:p-6`,children:(0,Q.jsxs)(`div`,{className:`flex flex-col gap-3 md:flex-row md:items-start md:justify-between md:gap-4`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 gap-3 sm:gap-4`,children:[(0,Q.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,Q.jsx)(qe,{className:`h-5 w-5 sm:h-6 sm:w-6`})}),(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`span`,{className:`truncate text-xs uppercase tracking-wide text-muted-foreground`,children:t.workspace.label||t.workspace.name}),(0,Q.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,Q.jsx)(Yt,{className:`h-3 w-3 text-success`}):(0,Q.jsx)(A,{className:`h-3 w-3 text-muted-foreground`}),s?`Live`:`Offline`]})]}),(0,Q.jsx)(ja,{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,Q.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,Q.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,Q.jsx)(Yt,{className:`h-3.5 w-3.5 text-success`}):(0,Q.jsx)(A,{className:`h-3.5 w-3.5 text-muted-foreground`}),s?`Live`:`Offline`]})]})}),(0,Q.jsxs)(Na,{className:`space-y-4 p-3 sm:space-y-6 sm:p-6 md:p-8`,children:[(0,Q.jsxs)(`section`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1 text-xs text-muted-foreground md:hidden`,children:[(0,Q.jsx)(`span`,{className:`w-full truncate font-mono text-foreground`,children:t.share.path}),(0,Q.jsxs)(`span`,{className:`tabular-nums`,children:[t.stats.documentCount,` docs`]}),p.length!==t.stats.documentCount&&(0,Q.jsxs)(`span`,{className:`tabular-nums`,children:[`· `,p.length,` shown`]}),(0,Q.jsxs)(`span`,{className:`truncate`,children:[`· `,co(t.stats.refreshedAt)]})]}),(0,Q.jsxs)(`section`,{className:`hidden gap-3 md:grid md:grid-cols-4`,children:[(0,Q.jsx)(uo,{label:`Path`,value:t.share.path,mono:!0}),(0,Q.jsx)(uo,{label:`Documents`,value:String(t.stats.documentCount)}),(0,Q.jsx)(uo,{label:`Shown`,value:String(p.length)}),(0,Q.jsx)(uo,{label:`Refreshed`,value:co(t.stats.refreshedAt)})]}),y&&(0,Q.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,Q.jsx)(vr,{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:_},JSON.stringify(v))}),!y&&(0,Q.jsxs)(`section`,{className:`rounded-2xl border`,children:[(0,Q.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,Q.jsx)(`h2`,{className:`font-semibold`,children:`Content`}),(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2 md:flex-row md:items-center`,children:[(0,Q.jsxs)(`form`,{onSubmit:h,className:`flex min-w-0 items-center gap-2`,children:[(0,Q.jsxs)(`div`,{className:`relative min-w-0`,children:[(0,Q.jsx)(Jt,{className:`pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground`}),(0,Q.jsx)(`input`,{type:`search`,value:u,onChange:e=>d(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`}),u&&(0,Q.jsx)(`button`,{type:`button`,onClick:g,className:`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,"aria-label":`Clear search`,children:(0,Q.jsx)(z,{className:`h-4 w-4`})})]}),(0,Q.jsx)(`button`,{type:`submit`,className:`rounded-md border px-3 py-1.5 text-xs hover:bg-muted`,children:`Search`})]}),(0,Q.jsxs)(`button`,{type:`button`,onClick:m,className:`inline-flex items-center justify-center gap-2 rounded-md border px-3 py-1.5 text-xs hover:bg-muted`,children:[(0,Q.jsx)(_t,{className:`h-3.5 w-3.5 ${r?`animate-spin`:``}`}),`Refresh`]})]})]}),u.trim()&&(0,Q.jsxs)(`div`,{className:`border-b bg-muted px-4 py-2 text-xs text-muted-foreground`,children:[`Local search: `,(0,Q.jsxs)(`span`,{className:`font-mono`,children:[`"`,u.trim(),`"`]})]}),(0,Q.jsx)(`div`,{className:`divide-y`,children:p.length===0?(0,Q.jsx)(`div`,{className:`p-8 text-center text-sm text-muted-foreground`,children:u.trim()?`No loaded documents match your search.`:`No documents yet.`}):p.map(t=>{let n=ro(t),r=ao(t,n),i=t.schema===Qa,a=i?oo(e,t.id):null,o=a||r;return(0,Q.jsxs)(`article`,{className:`p-4`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col gap-1 md:flex-row md:items-start md:justify-between`,children:[(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`h3`,{className:`truncate font-medium`,children:o?(0,Q.jsx)(`a`,{href:o,target:`_blank`,rel:`noreferrer`,className:`hover:text-primary hover:underline`,children:n.title}):n.title}),(0,Q.jsx)(`div`,{className:`mt-1 font-mono text-xs text-muted-foreground`,children:n.schemaLabel})]}),(0,Q.jsxs)(`div`,{className:`flex shrink-0 items-center gap-3`,children:[i&&(0,Q.jsxs)(`a`,{href:oo(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,Q.jsx)(Bt,{className:`h-3.5 w-3.5`}),`Download`]}),(0,Q.jsx)(`time`,{className:`text-xs text-muted-foreground`,children:co(t.updatedAt||t.createdAt)})]})]}),n.preview&&(0,Q.jsx)(`p`,{className:`mt-3 line-clamp-3 text-sm leading-6 text-foreground`,children:so(n.preview)}),to(t)&&(0,Q.jsx)(`a`,{href:a||void 0,target:`_blank`,rel:`noreferrer`,className:`mt-3 block w-fit`,children:(0,Q.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,Q.jsx)(Ua,{className:`mt-6 text-center`})]})})})}function uo({label:e,value:t,mono:n=!1}){return(0,Q.jsxs)(`div`,{className:`min-w-0 rounded-xl border bg-muted p-4`,children:[(0,Q.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:e}),(0,Q.jsx)(`div`,{className:`mt-2 truncate text-lg font-semibold ${n?`font-mono text-sm`:``}`,children:t||`-`})]})}var fo=`false`,po=`false`,mo=fo===`true`,ho=po===`true`;function go(e={}){let{immediate:t=!1,onNeedReload:n,onNeedRefresh:r,onOfflineReady:i,onRegistered:a,onRegisteredSW:o,onRegisterError:s}=e,l,u,d,f=async(e=!0)=>{await u,mo||d?.()};async function p(){if(`serviceWorker`in navigator){if(l=await c(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)}),!l)return;if(d=()=>{l?.messageSkipWaiting()},!ho){if(mo)l.addEventListener(`activated`,e=>{(e.isUpdate||e.isExternal)&&(n?n():window.location.reload())}),l.addEventListener(`installed`,e=>{e.isUpdate||i?.()});else{let e=!1,t=()=>{e=!0,l?.addEventListener(`controlling`,e=>{e.isUpdate&&(n?n():window.location.reload())}),r?.()};l.addEventListener(`installed`,n=>{n.isUpdate===void 0?n.isExternal===void 0?!e&&i?.():n.isExternal?t():!e&&i?.():n.isUpdate||i?.()}),l.addEventListener(`waiting`,t)}}l.register({immediate:t}).then(e=>{o?o(`/sw.js`,e):a?.(e)}).catch(e=>{s?.(e)})}}return u=p(),f}var _o=new Set,vo=!1,yo=go({immediate:!0,onRegisteredSW(e,t){t&&setInterval(()=>{t.update()},36e5)},onNeedRefresh(){vo=!0,_o.forEach(e=>e())}});function bo(e){return _o.add(e),vo&&e(),()=>{_o.delete(e)}}function xo(){yo(!0)}function So(){let[e,t]=(0,Z.useState)(!1),[n,r]=(0,Z.useState)(!1);return(0,Z.useEffect)(()=>bo(()=>t(!0)),[]),!e||n?null:(0,Q.jsx)(`div`,{className:`fixed bottom-4 left-1/2 z-50 -translate-x-1/2`,children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-3 rounded-full border border-border bg-card px-4 py-2 shadow-elevation-2`,children:[(0,Q.jsx)(`span`,{className:`text-sm`,children:`A new version of Canvas is ready`}),(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>xo(),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,Q.jsx)(_t,{className:`h-3 w-3`}),` Reload`]}),(0,Q.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,Q.jsx)(z,{className:`h-3.5 w-3.5`})})]})})}var Co=(0,Z.lazy)(()=>c(()=>import(`./apps-DbYkQgyL.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]))),wo=(0,Z.lazy)(()=>c(()=>Promise.resolve().then(()=>Ls).then(e=>({default:e.AppsMenu})),void 0)),To=(0,Z.lazy)(()=>c(()=>import(`./workspaces-BZ395Y1p.js`),__vite__mapDeps([19,1,2,8,3,4,10,9,6,5,11,12,20,7,13,21,22,23,24,25,26,27,28,29,30,31,32,33]))),Eo=(0,Z.lazy)(()=>c(()=>import(`./_workspaceName_-DfNeZ188.js`),__vite__mapDeps([34,1,2,3,4,10,8,5,6,9,12,35,32,20,7,11,13,36,37,38,39,40,22,23,41,42,43,44,21,45,46,47,18,14,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,24,76,77,78,79,27,80,25,26,81,82,29,83,15,84,85,86,16,17,87]))),Do=(0,Z.lazy)(()=>c(()=>import(`./document-Ds_P5v-f.js`),__vite__mapDeps([88,1,2,3,4,9,10,8,6,5,7,11,12,13,43,44,38,39,40,20,22,23,41,21,45,46,47,18,14,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,27,25,82,35,32,24,89]))),Oo=(0,Z.lazy)(()=>c(()=>import(`./home-BWAoF6jL.js`),__vite__mapDeps([90,1,2,3,4,10,8,7,9,6,5,11,12,13,36,35,32,37,38,39,40,20,22,23,41,42,43,44,21,45,46,47,18,14,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,24,76,77,78,79,27,80,91,85,86]))),ko=(0,Z.lazy)(()=>c(()=>import(`./desk-dI_FvLsK.js`),__vite__mapDeps([92,2,1]))),Ao=(0,Z.lazy)(()=>c(()=>import(`./share-target-pA9r0Obg.js`),__vite__mapDeps([93,1,2,3,4,91,8,10,5,6,11,44,38,9,7,12,13,39,40,20,22,23,41,21,45,46,47,18,14,48,49,50,51,72,63,65,61,85,54,86]))),jo=(0,Z.lazy)(()=>c(()=>import(`./contexts-CwGdjtXy2.js`),__vite__mapDeps([94,1,2,3,4,10,8,9,6,5,11,35,12,32,20,7,13,14,74,38,39,40,22,23,41,62,77,28,29,30]))),Mo=(0,Z.lazy)(()=>c(()=>import(`./_contextId_-xoan5Zgw.js`),__vite__mapDeps([95,1,2,3,4,35,12,32,20,38,8,10,5,6,9,7,11,13,39,40,22,23,41,70,43,44,21,45,46,47,18,14,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,71,72,73,74,75,24,76,77,78,79,25,83,42,15,84,85,86,16,17,89]))),No=(0,Z.lazy)(()=>c(()=>import(`./api-tokens-CmHhwd58.js`),__vite__mapDeps([96,1,2,10,8,9,6,5,11,12,20,28,3,4,97,25,21]))),Po=(0,Z.lazy)(()=>c(()=>import(`./devices-CmVlYbam.js`),__vite__mapDeps([98,1,2,10,8,9,6,5,11,20,28,3,4,97,25,21,99,12]))),Fo=(0,Z.lazy)(()=>c(()=>import(`./settings-CFbSvlXK.js`),__vite__mapDeps([100,1,2,3,4,10,8,11,5,6,7,9,12,13,14,25,21,28]))),Io=(0,Z.lazy)(()=>c(()=>import(`./appearance-C8m9uEmD.js`),__vite__mapDeps([101,1,2,10,8,5,6,71,25,3,4,21,102,28,97]))),Lo=(0,Z.lazy)(()=>c(()=>import(`./key-bindings-C3rMnRos.js`),__vite__mapDeps([103,1,2,28,3,4,10,8,5,6,97,25,21]))),Ro=(0,Z.lazy)(()=>c(()=>import(`./offline-yfQ63Zr7.js`),__vite__mapDeps([104,1,2,10,8,5,6,9,12,38,7,11,13,39,40,20,22,23,41,62,28,3,4,97,25,21]))),zo=(0,Z.lazy)(()=>c(()=>import(`./about-DWl4-RY1.js`),__vite__mapDeps([105,1,2,12,28,3,4,10,8,5,6,97,25,21]))),Bo=(0,Z.lazy)(()=>c(()=>import(`./embedding-2EjzoVFT.js`),__vite__mapDeps([106,1,2,10,8,9,6,5,20,28,3,4,97,25,21,107,11,12]))),Vo=(0,Z.lazy)(()=>c(()=>import(`./shared-ZTRGU8MK.js`),__vite__mapDeps([108,1,2,3,4,9,10,8,6,5,11,12,20,28,97,25,21]))),Ho=(0,Z.lazy)(()=>c(()=>import(`./workspaces-p959p9BR.js`),__vite__mapDeps([109,1,2,10,8,9,6,5,11,44,37,12,35,32,20,39,28,3,4,110]))),Uo=(0,Z.lazy)(()=>c(()=>import(`./contexts-Dtl9oERX.js`),__vite__mapDeps([111,1,2,37,6,12,35,32,28,3,4,10,8,5]))),Wo=(0,Z.lazy)(()=>c(()=>import(`./agents-DEJU4O1Z.js`),__vite__mapDeps([112,1,2,37,6,12,35,32,28,3,4,10,8,5]))),Go=(0,Z.lazy)(()=>c(()=>import(`./logs-DUeiDqCX.js`),__vite__mapDeps([113,1,2,10,8,9,6,5,11,44,37,12,35,32,20,28,3,4,97,25,21,110]))),Ko=(0,Z.lazy)(()=>c(()=>import(`./roles-BHJYWaBs.js`),__vite__mapDeps([114,1,2,10,8,9,6,5,11,44,37,12,35,32,20,39,28,3,4,97,25,21,115]))),qo=(0,Z.lazy)(()=>c(()=>import(`./users-DInwKAxz.js`),__vite__mapDeps([116,1,2,10,8,9,6,5,11,44,37,12,35,32,20,39,28,3,4,97,25,21,110]))),Jo=(0,Z.lazy)(()=>c(()=>import(`./embedding-BqI3l5RB.js`),__vite__mapDeps([117,1,2,10,8,9,6,5,11,37,12,35,32,20,28,3,4,97,25,21,107]))),Yo=(0,Z.lazy)(()=>c(()=>import(`./auth-_bmIEN02.js`),__vite__mapDeps([118,1,2,10,8,5,6,9,11,12,37,35,32,20,28,3,4,97,25,21]))),Xo=(0,Z.lazy)(()=>c(()=>import(`./agents-DT1XtFUN.js`),__vite__mapDeps([119,1,2,3,4,10,8,9,6,5,11,20,23,28,120,29,30,31,12,32]))),Zo=(0,Z.lazy)(()=>c(()=>import(`./_agentId_-GsPtoz9i.js`),__vite__mapDeps([121,1,2,3,4,10,8,5,6,9,12,32,20,56,25,21,28]))),Qo=(0,Z.lazy)(()=>c(()=>import(`./settings-BZsdOcHy.js`),__vite__mapDeps([122,1,2,3,4,10,8,9,6,5,11,20,7,12,13,21,14,23,25,28,120]))),$o=(0,Z.lazy)(()=>c(()=>import(`./settings-DD2zxZ8C.js`),__vite__mapDeps([123,1,2,8,3,4,10,5,6,9,11,44,12,35,32,20,38,7,13,39,40,22,23,41,21,58,59,60,61,62,66,73,74,75,24,25,102,28,107,31,99,87,33]))),es=(0,Z.lazy)(()=>c(()=>import(`./settings-QL_HG2aL.js`),__vite__mapDeps([124,1,2,3,4,10,8,5,6,9,11,20,21,14,12,7,13,74,38,39,40,22,23,41,62,25,28]))),ts=(0,Z.lazy)(()=>c(()=>import(`./roles-CuqCEPC7.js`),__vite__mapDeps([125,1,2,10,8,9,6,5,11,37,12,35,32,20,7,13,39,28,3,4,115,29,30]))),ns=(0,Z.lazy)(()=>c(()=>import(`./remotes-BjjlqN_M.js`),__vite__mapDeps([126,2,1,28,3,4,10,8,5,6]))),rs=(0,Z.lazy)(()=>c(()=>import(`./add-AHQUHZBr.js`),__vite__mapDeps([127,2,1,3,4,91,8,10,5,6,11,44,38,9,7,12,13,39,40,20,22,23,41,21,45,46,47,18,14,48,49,50,51,72,63,65,61,85,54,86])));function $(e){return(0,Q.jsx)(Z.Suspense,{fallback:(0,Q.jsx)(`div`,{className:`flex h-full items-center justify-center p-4 text-sm text-muted-foreground`,role:`status`,children:`Opening…`}),children:(0,Q.jsx)(e,{})})}var is=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(d,{index:!0,element:$(ko)},`r1`),(0,Q.jsx)(d,{path:`home`,element:$(Oo)},`r2`),(0,Q.jsx)(d,{path:`share-target`,element:$(Ao)},`r3`),(0,Q.jsx)(d,{path:`apps`,element:$(wo)},`apps-index`),(0,Q.jsx)(d,{path:`apps/:appletId`,element:$(Co)},`apps-host`),(0,Q.jsx)(d,{path:`apps/add/:kind`,element:$(rs)},`r4`),(0,Q.jsx)(d,{path:`workspaces`,element:$(To)},`r5`),(0,Q.jsx)(d,{path:`workspaces/:workspaceName`,element:$(Eo)},`r6`),(0,Q.jsx)(d,{path:`workspaces/:workspaceName/documents/by-id/:documentId`,element:$(Do)},`workspace-document-by-id`),(0,Q.jsx)(d,{path:`workspaces/:workspaceName/documents/:documentId`,element:$(Do)},`workspace-document`),(0,Q.jsx)(d,{path:`workspaces/:workspaceName/documents/by-hash/:algo/:checksum`,element:$(Do)},`workspace-document-by-hash`),(0,Q.jsx)(d,{path:`workspaces/:workspaceName/documents/by-checksum/:algo/:checksum`,element:$(Do)},`workspace-document-by-checksum`),(0,Q.jsx)(d,{path:`workspaces/:workspaceName/settings`,element:$($o)},`r7`),(0,Q.jsx)(d,{path:`workspaces/:workspaceName/settings/:tab`,element:$($o)},`r8`),(0,Q.jsx)(d,{path:`workspaces/:workspaceName/path/*`,element:$(Eo)},`r9`),(0,Q.jsx)(d,{path:`workspaces/:workspaceName/trees/:treeName`,element:$(Eo)},`r10`),(0,Q.jsx)(d,{path:`workspaces/:workspaceName/trees/:treeName/path/*`,element:$(Eo)},`r11`),(0,Q.jsx)(d,{path:`contexts`,element:$(jo)},`r12`),(0,Q.jsx)(d,{path:`contexts/:contextId`,element:$(Mo)},`r13`),(0,Q.jsx)(d,{path:`contexts/:contextId/settings`,element:$(es)},`r14`),(0,Q.jsx)(d,{path:`contexts/:contextId/settings/:tab`,element:$(es)},`r15`),(0,Q.jsx)(d,{path:`agents`,element:$(Xo)},`r16`),(0,Q.jsx)(d,{path:`agents/:agentId`,element:$(Zo)},`r17`),(0,Q.jsx)(d,{path:`agents/:agentId/:sessionId`,element:$(Zo)},`r18`),(0,Q.jsx)(d,{path:`agents/:agentId/settings`,element:$(Qo)},`r19`),(0,Q.jsx)(d,{path:`agents/:agentId/settings/:tab`,element:$(Qo)},`r20`),(0,Q.jsx)(d,{path:`roles`,element:$(ts)},`r21`),(0,Q.jsx)(d,{path:`remotes`,element:$(ns)},`r22`),(0,Q.jsx)(d,{path:`settings`,element:$(Fo)},`settings`),(0,Q.jsx)(d,{path:`appearance`,element:$(Io)},`r23`),(0,Q.jsx)(d,{path:`key-bindings`,element:$(Lo)},`key-bindings`),(0,Q.jsx)(d,{path:`offline`,element:$(Ro)},`r24`),(0,Q.jsx)(d,{path:`about`,element:$(zo)},`r25`),(0,Q.jsx)(d,{path:`api-tokens`,element:$(No)},`r26`),(0,Q.jsx)(d,{path:`devices`,element:$(Po)},`r27`),(0,Q.jsx)(d,{path:`embedding`,element:$(Bo)},`r28`),(0,Q.jsx)(d,{path:`shared`,element:$(Vo)},`r29`),(0,Q.jsx)(d,{path:`admin/users`,element:$(qo)},`r30`),(0,Q.jsx)(d,{path:`admin/contexts`,element:$(Uo)},`r31`),(0,Q.jsx)(d,{path:`admin/workspaces`,element:$(Ho)},`r32`),(0,Q.jsx)(d,{path:`admin/agents`,element:$(Wo)},`r33`),(0,Q.jsx)(d,{path:`admin/logs`,element:$(Go)},`r34`),(0,Q.jsx)(d,{path:`admin/roles`,element:$(Ko)},`r35`),(0,Q.jsx)(d,{path:`admin/embedding`,element:$(Jo)},`r36`),(0,Q.jsx)(d,{path:`admin/auth`,element:$(Yo)},`r37`)]});function as(e){if(typeof e!=`string`||!e.startsWith(`/`)||e.startsWith(`//`)||/[\\\u0000-\u0020]/.test(e))return null;let t=new URL(e,`https://canvas.invalid`);return t.origin!==`https://canvas.invalid`||/^\/(?:login|register|pub|share-target|apps|next)(?:\/|$)/.test(t.pathname)||t.pathname===`/`||[...t.searchParams.keys()].some(e=>/token|password|secret|code/i.test(e))?null:t.pathname+t.search+t.hash}function os(e){let t=2166136261;for(let n of e)t=Math.imul(t^n.charCodeAt(0),16777619);return`canvas:last-screen:${t>>>0}`}var ss=p(is),cs=e=>{let t=as(e);return t&&x(ss,t)?t:null};function ls(){let e=h(),[t]=(0,Z.useState)(()=>{if(e.pathname!==`/`||e.search||e.hash)return null;try{let t=localStorage.getItem(`authToken`);return t?{key:e.key,path:cs(localStorage.getItem(os(t)))||`/home`}:null}catch{return{key:e.key,path:`/home`}}}),n=t&&e.key===t.key&&e.pathname===`/`;return(0,Z.useEffect)(()=>{if(n)return;let t=cs(e.pathname+e.search+e.hash);if(t)try{let e=localStorage.getItem(`authToken`);e&&localStorage.setItem(os(e),t)}catch{}},[e.pathname,e.search,e.hash,n]),n?(0,Q.jsx)(u,{to:t.path,replace:!0}):null}var us={activeSection:null,m0Open:!1,m1Open:!1,m2Open:!1,m2View:null,selectedEntityId:null,user:null};function ds(e,t){switch(t.type){case`RESTORE_MENU`:return{...e,...t.menu,user:e.user};case`SET_SECTION`:return{...e,activeSection:t.section,m1Open:t.section!==null,m2Open:!1,m2View:null,selectedEntityId:null};case`TOGGLE_SECTION`:return e.activeSection===t.section&&e.m1Open?{...e,activeSection:null,m1Open:!1,m2Open:!1,m2View:null}:{...e,activeSection:t.section,m1Open:!0,m2Open:!1,m2View:null,selectedEntityId:null};case`TOGGLE_M0`:return e.m0Open?{...e,m0Open:!1,activeSection:null,m1Open:!1,m2Open:!1,m2View:null}:{...e,m0Open:!0};case`CLOSE_M0`:return{...e,m0Open:!1};case`CLOSE_M1`:return{...e,activeSection:null,m1Open:!1,m2Open:!1,m2View:null};case`OPEN_M2`:return{...e,m2Open:!0,m2View:t.view,selectedEntityId:t.entityId===void 0?e.selectedEntityId:t.entityId};case`OPEN_M2_DRAWER`:return{...e,m0Open:!0,activeSection:t.section,m1Open:!0,m2Open:!0,m2View:t.view,selectedEntityId:t.entityId};case`OPEN_M1_DRAWER`:return{...e,m0Open:!0,activeSection:t.section,m1Open:!0,m2Open:!1,m2View:null,selectedEntityId:null};case`CLOSE_M2`:return{...e,m2Open:!1,m2View:null};case`SELECT_ENTITY`:return{...e,selectedEntityId:t.entityId};case`SYNC_FROM_URL`:{let n=!t.mobile&&!e.m2Open&&e.m2View===null&&t.section===e.activeSection&&t.entityId===e.selectedEntityId;return t.section===e.activeSection&&t.entityId===e.selectedEntityId&&t.m2View===e.m2View&&!(t.mobile&&(e.m1Open||e.m0Open))?e:{...e,activeSection:t.section,m0Open:!t.mobile&&e.m0Open,m1Open:!t.mobile&&t.section!==null,selectedEntityId:t.entityId,m2Open:!n&&t.m2View!==null,m2View:n?null:t.m2View}}case`SET_USER`:return{...e,user:t.user};default:return e}}function fs({children:e}){let[t,n]=(0,Z.useReducer)(ds,us),r=h(),i=m(),a=(0,Z.useRef)(t);(0,Z.useLayoutEffect)(()=>{a.current=t},[t]),aa(t,n);let o=(0,Z.useCallback)((e,t=!1,o=!1)=>{let s=ds(a.current,e);if(a.current=s,n(e),!da())return;let{activeSection:c,m0Open:l,m1Open:u,m2Open:d,m2View:f,selectedEntityId:p}=s;i({pathname:r.pathname,search:r.search,hash:r.hash},{replace:t,state:{...r.state,canvasMenu:{activeSection:c,m0Open:l,m1Open:u,m2Open:d,m2View:f,selectedEntityId:p},canvasMenuBack:o}})},[r,i]),s=(0,Z.useCallback)(e=>{if(da()&&a.current.m1Open){let{activeSection:t,m0Open:n,m1Open:o,m2Open:s,m2View:c,selectedEntityId:l}=a.current;i(e,{replace:!0,state:{...r.state,canvasMenu:{activeSection:t,m0Open:n,m1Open:o,m2Open:s,m2View:c,selectedEntityId:l},canvasMenuBack:!1}})}i(e)},[r.state,i]),c=(0,Z.useCallback)(()=>{if(window.history.state?.idx>0){i(-1);return}let e=a.current;if(e.m1Open&&e.m2Open)o({type:`CLOSE_M2`},!0,!0);else if(e.m1Open)o({type:`CLOSE_M1`},!0,!0);else if(e.m0Open)o({type:`CLOSE_M0`},!0,!0);else{let{section:e,entityId:t,m2View:n}=pa(r.pathname);if(!da()){i(e?`/${e}`:`/`);return}o(e&&t?{type:`OPEN_M2_DRAWER`,section:e,view:n,entityId:t}:{type:`TOGGLE_M0`},!0,!0)}},[o,r.pathname,i]);(0,Z.useEffect)(()=>{let e=mn();if(e){n({type:`SET_USER`,user:e});return}let t=!1;return vn().then(e=>{!t&&e&&n({type:`SET_USER`,user:e})}).catch(()=>{}),()=>{t=!0}},[]);let l={state:t,dispatch:n,setSection:(0,Z.useCallback)(e=>{o({type:`SET_SECTION`,section:e})},[o]),toggleSection:(0,Z.useCallback)(e=>{o({type:`TOGGLE_SECTION`,section:e})},[o]),toggleM0:(0,Z.useCallback)(()=>{o({type:`TOGGLE_M0`},a.current.m0Open)},[o]),closeM0:(0,Z.useCallback)(()=>{o({type:`CLOSE_M0`},!0)},[o]),closeM1:(0,Z.useCallback)(()=>{o({type:`CLOSE_M1`},!0)},[o]),openM2:(0,Z.useCallback)((e,t)=>{o({type:`OPEN_M2`,view:e,entityId:t})},[o]),openM2Drawer:(0,Z.useCallback)((e,t,n)=>{o({type:`OPEN_M2_DRAWER`,section:e,view:t,entityId:n})},[o]),openM1Drawer:(0,Z.useCallback)(e=>{o({type:`OPEN_M1_DRAWER`,section:e})},[o]),closeM2:(0,Z.useCallback)(()=>{da()&&a.current.m1Open&&a.current.m2Open?c():n({type:`CLOSE_M2`})},[c]),selectEntity:(0,Z.useCallback)(e=>{n({type:`SELECT_ENTITY`,entityId:e})},[]),goBack:c,navigateFromMenu:s};return(0,Q.jsx)(ma.Provider,{value:l,children:e})}var ps;function ms(){let[e,t]=(0,Z.useState)({local:!1});return(0,Z.useEffect)(()=>{ps??=fetch(`${J}/runtime/capabilities`).then(async e=>e.ok?(await e.json()).payload:{local:!1}).catch(()=>({local:!1}));let e=!0;return ps.then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function hs(){return(0,Z.useSyncExternalStore)(rn,sn,()=>!1)}function gs(e,t){let n=null,r=!1,i,a;function o(){clearTimeout(i),!r&&sn()&&(i=setTimeout(()=>{s()},3e4))}function s(s=!1){if(n)return n;if(r)return Promise.resolve(!1);clearTimeout(i),a=new AbortController;let c=setTimeout(()=>a?.abort(),5e3);return n=(async()=>{try{let n=await fetch(e,{cache:`no-store`,credentials:`omit`,signal:a.signal});if(!n.ok||n.headers.get(`x-canvas-offline`)===`fallback`)throw Error(`Unavailable`);if((await n.json()).status!==`success`)throw Error(`Not a Canvas response`);if(r)return!1;let i=sn();return on(),(i||s)&&t(),!0}catch{return r||tn(),!1}finally{clearTimeout(c),n=null,o()}})(),n}let c=rn(o),l=()=>{s()};return window.addEventListener(`online`,l),o(),{retry:s,stop(){r=!0,clearTimeout(i),a?.abort(),c(),window.removeEventListener(`online`,l)}}}var _s;function vs(){_s=gs(`${J}/ping`,()=>X.retryNow());let e=()=>{_s?.retry()},t=X.on(`connect_error`,e),n=X.on(`disconnect`,e);return()=>{t(),n(),_s?.stop(),_s=void 0}}function ys(){return _s?.retry(!0)??Promise.resolve(!1)}function bs(){let e=hs(),[t,n]=(0,Z.useState)(!1);return e?(0,Q.jsxs)(`details`,{className:`relative`,children:[(0,Q.jsx)(`summary`,{"aria-label":`Offline — connection options`,title:`Offline — cached content available`,className:`flex h-10 w-10 cursor-pointer list-none items-center justify-center rounded-lg text-amber-600 hover:bg-accent/50 [&::-webkit-details-marker]:hidden`,children:(0,Q.jsx)(A,{className:`h-5 w-5`})}),(0,Q.jsxs)(`div`,{className:`absolute bottom-0 left-full z-50 ml-2 w-60 max-w-[calc(100vw-5rem)] rounded-lg border bg-popover p-3 text-popover-foreground shadow-lg`,children:[(0,Q.jsx)(`p`,{className:`text-sm font-medium`,role:`status`,children:`Offline`}),(0,Q.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`You can browse cached documents. We’ll reconnect automatically when the server is available.`}),(0,Q.jsx)(`button`,{type:`button`,disabled:t,onClick:async()=>{n(!0);try{await ys()}finally{n(!1)}},className:`mt-3 rounded-md bg-secondary px-3 py-2 text-xs font-medium hover:bg-accent disabled:opacity-50`,children:t?`Checking…`:`Retry now`})]})]}):null}var xs=be,Ss=ee,Cs=Ht,ws=Z.forwardRef(({className:e,sideOffset:t=4,...n},r)=>(0,Q.jsx)(Ut,{children:(0,Q.jsx)(Ke,{ref:r,sideOffset:t,className:G(`z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in duration-fast fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin]`,e),...n})}));ws.displayName=Ke.displayName;var Ts=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(Ve,{ref:n,className:G(`relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full`,e),...t}));Ts.displayName=Ve.displayName;var Es=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(qt,{ref:n,className:G(`aspect-square h-full w-full`,e),...t}));Es.displayName=qt.displayName;var Ds=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(Lt,{ref:n,className:G(`flex h-full w-full items-center justify-center rounded-full bg-muted`,e),...t}));Ds.displayName=Lt.displayName;function Os({section:e,icon:t,label:n,disabled:r}){let{state:i,toggleSection:a}=la(),o=i.activeSection===e;return(0,Q.jsxs)(Ss,{children:[(0,Q.jsx)(Cs,{asChild:!0,children:(0,Q.jsxs)(`button`,{type:`button`,disabled:r,"aria-label":n,onClick:()=>!r&&e&&a(e),className:G(`relative flex items-center justify-center w-10 h-10 rounded-lg transition-colors`,o?`bg-accent text-foreground`:`text-muted-foreground hover:text-foreground hover:bg-accent/50`,r&&`opacity-30 cursor-not-allowed`),children:[o&&(0,Q.jsx)(`span`,{className:`absolute right-0 top-1/2 -translate-y-1/2 w-0.5 h-5 bg-foreground rounded-l`}),t]})}),(0,Q.jsx)(ws,{side:`right`,sideOffset:8,children:n})]})}function ks({path:e,icon:t,label:n,section:r=`settings`}){let i=m(),{setSection:a}=la();return(0,Q.jsxs)(Ss,{children:[(0,Q.jsx)(Cs,{asChild:!0,children:(0,Q.jsx)(`button`,{type:`button`,"aria-label":n,onClick:()=>{a(r),i(e)},className:`flex items-center justify-center w-10 h-10 rounded-lg text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors`,children:t})}),(0,Q.jsx)(ws,{side:`right`,sideOffset:8,children:n})]})}function As(){let{state:e,toggleM0:t}=la(),n=hs();return(0,Q.jsxs)(`button`,{type:`button`,onClick:t,"aria-label":`${e.m0Open?`Close menu`:`Open menu`}${n?` — offline, connection options in menu`:``}`,"data-shell":`rail`,className:`fixed bottom-rail-inset left-2 z-nav flex h-rail w-rail items-center justify-center rounded-full bg-foreground text-background shadow-elevation-4 md:hidden`,children:[e.m0Open?(0,Q.jsx)(z,{className:`h-5 w-5`}):(0,Q.jsx)(ht,{className:`h-5 w-5`}),n&&(0,Q.jsx)(`span`,{"aria-hidden":!0,className:`absolute right-0 top-0 h-3 w-3 rounded-full border-2 border-background bg-amber-500`})]})}function js(){let{state:e,closeM0:t,closeM1:n}=la(),{state:r,setView:i,closeT1:a}=ti(),o=m(),{showToast:s}=xn(),c=e.user?.userType===`admin`,l=ms(),u=()=>{r.t1Open?a():i(`tools`),n(),t()},d=(0,Z.useCallback)(async()=>{try{await Y.post(`/auth/logout`),localStorage.removeItem(`authToken`),o(`/login`)}catch{s({title:`Error`,description:`Logout failed`,variant:`destructive`})}},[o,s]);return(0,Q.jsxs)(xs,{delayDuration:200,children:[e.m0Open&&(0,Q.jsx)(`div`,{className:`fixed inset-0 z-nav-scrim bg-scrim animate-fade-in md:hidden`,onClick:t,"aria-hidden":!0}),(0,Q.jsxs)(`div`,{"data-shell":`rail`,className:G(`flex flex-col items-center w-rail h-full rounded-(--panel-radius) bg-transparent shrink-0`,e.m0Open?`max-md:fixed max-md:left-2 max-md:top-2 max-md:bottom-rail-stack max-md:z-rail max-md:h-auto max-md:bg-card max-md:surface-glass max-md:shadow-elevation-5`:`max-md:hidden`),children:[(0,Q.jsx)(`div`,{className:`flex items-center justify-center h-12 w-full shrink-0`,children:(0,Q.jsx)(`button`,{type:`button`,"aria-label":`Canvas home`,onClick:()=>o(`/home`),className:`flex items-center justify-center w-10 h-10 rounded-lg hover:bg-accent/50 transition-colors`,children:(0,Q.jsx)(`img`,{src:`/images/logo-br_128x128.png`,alt:``,className:`w-6 h-6`})})}),(0,Q.jsxs)(`nav`,{className:`flex flex-col items-center gap-1 py-2 flex-1 min-h-0 overflow-y-auto`,children:[(!l.local||l.workspace!==!1)&&(0,Q.jsx)(Os,{section:`contexts`,icon:(0,Q.jsx)(xe,{className:`w-5 h-5`}),label:`Contexts`}),(!l.local||l.workspace!==!1)&&(0,Q.jsx)(Os,{section:`workspaces`,icon:(0,Q.jsx)(Wt,{className:`w-5 h-5`}),label:`Workspaces`}),(!l.local||l.agent)&&(0,Q.jsx)(Os,{section:`agents`,icon:(0,Q.jsx)(Be,{className:`w-5 h-5`}),label:`Agents`}),(0,Q.jsx)(Os,{section:`apps`,icon:(0,Q.jsx)(He,{className:`w-5 h-5`}),label:`Apps`}),(!l.local||l.workspace!==!1)&&(0,Q.jsx)(ks,{path:`/roles`,section:null,icon:(0,Q.jsx)(It,{className:`w-5 h-5`}),label:`Roles`}),c&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`w-6 h-px bg-border my-2`}),(0,Q.jsx)(ks,{path:`/admin/users`,icon:(0,Q.jsx)(oe,{className:`w-5 h-5`}),label:`All Users`}),(0,Q.jsx)(ks,{path:`/admin/logs`,icon:(0,Q.jsx)(Tt,{className:`w-5 h-5`}),label:`Server Logs`}),(0,Q.jsx)(ks,{path:`/admin/workspaces`,icon:(0,Q.jsx)(ve,{className:`w-5 h-5`}),label:`All Workspaces`}),(0,Q.jsx)(ks,{path:`/admin/agents`,icon:(0,Q.jsx)(Be,{className:`w-5 h-5`}),label:`All Agents`}),(0,Q.jsx)(ks,{path:`/admin/roles`,icon:(0,Q.jsx)(It,{className:`w-5 h-5`}),label:`All Roles`})]})]}),(0,Q.jsxs)(`div`,{className:`flex flex-col items-center gap-1 py-2 shrink-0`,children:[(0,Q.jsx)(`div`,{className:`w-6 h-px bg-border mb-2`}),(0,Q.jsx)(bs,{}),(0,Q.jsxs)(Ss,{children:[(0,Q.jsx)(Cs,{asChild:!0,children:(0,Q.jsx)(`button`,{type:`button`,onClick:u,"aria-label":r.t1Open?`Close toolbox`:`Open toolbox`,className:G(`flex items-center justify-center w-10 h-10 rounded-lg transition-colors`,r.t1Open?`bg-accent text-foreground`:`text-muted-foreground hover:text-foreground hover:bg-accent/50`),children:(0,Q.jsx)(ye,{className:`w-5 h-5`})})}),(0,Q.jsx)(ws,{side:`right`,sideOffset:8,children:`Toolbox`})]}),!l.local&&(0,Q.jsx)(ks,{path:`/settings`,section:`settings`,icon:(0,Q.jsx)(pt,{className:`w-5 h-5`}),label:`Settings`}),(0,Q.jsxs)(Ss,{children:[(0,Q.jsx)(Cs,{asChild:!0,children:(0,Q.jsx)(`button`,{type:`button`,"aria-label":e.user?.email?`Profile: ${e.user.email}`:`Profile`,onClick:()=>o(`/home`),className:`flex items-center justify-center w-10 h-10 rounded-lg hover:bg-accent/50 transition-colors`,children:(0,Q.jsx)(Ts,{className:`h-7 w-7 touch-target`,children:(0,Q.jsx)(Ds,{className:`text-[10px] bg-muted`,children:e.user?.email?(e=>e.split(`@`)[0].split(`.`).map(e=>e.charAt(0).toUpperCase()).join(``).slice(0,2))(e.user.email):`U`})})})}),(0,Q.jsx)(ws,{side:`right`,sideOffset:8,children:e.user?.email?.split(`@`)[0]||`Profile`})]}),(0,Q.jsxs)(Ss,{children:[(0,Q.jsx)(Cs,{asChild:!0,children:(0,Q.jsx)(`button`,{type:`button`,"aria-label":`Log out`,onClick:d,className:`flex items-center justify-center w-10 h-10 rounded-lg text-destructive hover:bg-destructive/10 transition-colors`,children:(0,Q.jsx)(yt,{className:`w-5 h-5`})})}),(0,Q.jsx)(ws,{side:`right`,sideOffset:8,children:`Logout`})]})]})]})]})}function Ms(){let{goBack:e}=la();return(0,Q.jsx)(`button`,{type:`button`,onClick:e,"aria-label":`Back to previous view`,title:`Back to previous view`,className:`-ml-2 mr-1 flex h-11 w-11 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-accent md:hidden`,children:(0,Q.jsx)(nt,{className:`h-5 w-5`})})}var Ns=[{id:`productivity`,label:`Productivity`},{id:`creative`,label:`Creative`},{id:`media`,label:`Media & capture`},{id:`utilities`,label:`Utilities`}];function Ps(e,t){let n=t.trim().toLocaleLowerCase();return Ns.map(t=>({...t,apps:e.filter(e=>e.category===t.id&&`${e.name} ${e.description} ${e.kind} ${t.label}`.toLocaleLowerCase().includes(n)).sort((e,t)=>e.name.localeCompare(t.name)||e.id.localeCompare(t.id))})).filter(e=>e.apps.length)}function Fs(e){let t=new URL(e);if(![`http:`,`https:`].includes(t.protocol)||t.username||t.password)throw Error(`Enter an HTTP or HTTPS URL without embedded credentials.`);return t.href}function Is({apps:e,query:t,activeId:n,onLaunch:r,onRemove:i}){let a=Ps(e,t);return(0,Q.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-3 overflow-y-auto p-2`,children:[a.map(e=>(0,Q.jsxs)(`section`,{"aria-label":e.label,children:[(0,Q.jsx)(`h3`,{className:`px-2 py-2 text-xs font-semibold text-muted-foreground`,children:e.label}),e.apps.map(e=>{let t=e.kind===`web`?Ee:e.kind===`desktop`?Le:xe;return(0,Q.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>r(e),"aria-current":n===e.id?`page`:void 0,className:`flex min-w-0 flex-1 items-start gap-2 rounded-md p-2 text-left hover:bg-accent/50 ${n===e.id?`bg-accent`:``}`,children:[(0,Q.jsx)(t,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,Q.jsxs)(`span`,{className:`min-w-0`,children:[(0,Q.jsx)(`span`,{className:`block truncate text-sm font-medium`,children:e.name}),(0,Q.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:e.description}),(0,Q.jsx)(`span`,{className:`mt-1 block text-[10px] text-muted-foreground`,children:e.kind===`canvas`?`Canvas`:e.kind===`web`?`Web app · opens in browser`:`Desktop app`})]})]}),e.kind===`web`&&i&&(0,Q.jsx)(`button`,{type:`button`,onClick:()=>i(e),"aria-label":`Remove ${e.name}`,className:`rounded p-2 text-muted-foreground hover:bg-accent`,children:(0,Q.jsx)(Fe,{className:`h-3.5 w-3.5`})})]},e.id)})]},e.id)),!a.length&&(0,Q.jsx)(`p`,{role:`status`,className:`p-3 text-sm text-muted-foreground`,children:`No matching apps.`})]})}var Ls=t({AppsMenu:()=>Bs}),Rs=`canvas:webApps`;function zs(){try{let e=JSON.parse(localStorage.getItem(Rs)||`[]`);return Array.isArray(e)?e.filter(e=>{if(!e||typeof e.id!=`string`||typeof e.name!=`string`||typeof e.description!=`string`||e.kind!==`web`||!Ns.some(t=>t.id===e.category))return!1;try{return typeof e.target==`string`&&!!Fs(e.target)}catch{return!1}}):[]}catch{return[]}}function Bs(){let{navigateFromMenu:e}=la(),t=h(),n=_a(),[r,i]=(0,Z.useState)(``),[a,o]=(0,Z.useState)(zs),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(``);(0,Z.useEffect)(()=>{let e=()=>o(zs());return window.addEventListener(`storage`,e),window.addEventListener(`canvas:apps-changed`,e),()=>{window.removeEventListener(`storage`,e),window.removeEventListener(`canvas:apps-changed`,e)}},[]);let d=e=>{try{return localStorage.setItem(Rs,JSON.stringify(e)),o(e),window.dispatchEvent(new Event(`canvas:apps-changed`)),!0}catch{return u(`Unable to save web apps on this device.`),!1}},f=[...ga.map(e=>({id:`canvas:${e.id}`,name:e.label,description:e.description,category:e.category,kind:`canvas`,target:`/apps/${e.id}`})),...a];return(0,Q.jsxs)(`nav`,{"aria-label":`Apps`,className:`flex h-full min-h-0 flex-col`,children:[(0,Q.jsxs)(`div`,{className:`shrink-0 space-y-3 border-b p-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(Ms,{}),(0,Q.jsx)(`h2`,{className:`flex-1 text-sm font-semibold`,children:`Apps`}),(0,Q.jsx)(`button`,{type:`button`,"aria-label":`Add web app`,title:`Add web app`,onClick:()=>{c(!s),u(``)},className:`rounded p-1 hover:bg-accent`,children:(0,Q.jsx)(ge,{className:`h-4 w-4`})})]}),(0,Q.jsx)(`input`,{type:`search`,"aria-label":`Search apps`,placeholder:`Find an app…`,value:r,onChange:e=>i(e.target.value),className:`w-full rounded-md border bg-background px-2 py-1.5 text-sm`}),s&&(0,Q.jsxs)(`form`,{className:`space-y-2`,onSubmit:e=>{e.preventDefault();let t=new FormData(e.currentTarget);try{let e=String(t.get(`name`)||``).trim();if(!e)throw Error(`Enter an app name.`);let n={id:`web:${crypto.randomUUID()}`,name:e,description:``,category:t.get(`category`),kind:`web`,target:Fs(String(t.get(`url`)||``))};d([...zs(),n])&&(c(!1),u(``))}catch(e){u(e instanceof Error?e.message:`Unable to add app.`)}},children:[(0,Q.jsx)(`input`,{name:`name`,required:!0,"aria-label":`App name`,placeholder:`App name`,className:`w-full rounded border bg-background p-1 text-sm`}),(0,Q.jsx)(`input`,{name:`url`,type:`url`,required:!0,"aria-label":`App URL`,placeholder:`https://…`,className:`w-full rounded border bg-background p-1 text-sm`}),(0,Q.jsx)(`select`,{name:`category`,"aria-label":`App category`,className:`w-full rounded border bg-background p-1 text-sm`,children:Ns.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.label},e.id))}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Saved on this device. Opens in your browser.`}),(0,Q.jsx)(`button`,{type:`submit`,className:`rounded border px-2 py-1 text-sm hover:bg-accent`,children:`Add app`})]}),l&&(0,Q.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,children:l})]}),(0,Q.jsx)(Is,{apps:f,query:r,activeId:f.find(e=>e.kind===`canvas`&&e.target===t.pathname)?.id,onLaunch:r=>{if(r.kind===`web`){window.open(Fs(r.target),`_blank`,`noopener,noreferrer`);return}let i=new URLSearchParams;if(t.pathname.startsWith(`/apps/`)){let e=new URLSearchParams(t.search);for(let t of[`context`,`workspace`,`path`,`tree`])e.has(t)&&i.set(t,e.get(t))}else n?.mode===`context`?i.set(`context`,n.contextId):n?.mode===`workspace`&&(i.set(`workspace`,n.workspaceName),i.set(`path`,n.path),i.set(`tree`,n.treeName));e(`${r.target}${i.size?`?${i}`:``}`)},onRemove:e=>{d(zs().filter(t=>t.id!==e.id))}})]})}var Vs=220,Hs=560;function Us({width:e,onResize:t,onDragging:n}){let r=(0,Z.useRef)(null),i=e=>t(Math.min(Hs,Math.max(Vs,e))),a=()=>{r.current=null,n?.(!1)};return(0,Q.jsx)(`div`,{role:`separator`,"aria-label":`Resize menu`,"aria-orientation":`vertical`,"aria-valuemin":Vs,"aria-valuemax":Hs,"aria-valuenow":e,tabIndex:0,title:`Drag to resize; use arrow keys to adjust; Home resets width`,className:`absolute inset-y-0 right-0 z-30 flex w-3 touch-none select-none cursor-col-resize items-center justify-center hover:bg-primary/10 focus-visible:bg-primary/10 focus-visible:outline-none [@media(pointer:coarse)]:w-6`,onPointerDown:t=>{t.button!==0||r.current||(t.preventDefault(),t.stopPropagation(),r.current={id:t.pointerId,x:t.clientX,width:e},t.currentTarget.setPointerCapture(t.pointerId),n?.(!0))},onPointerMove:e=>{r.current?.id===e.pointerId&&i(r.current.width+e.clientX-r.current.x)},onPointerUp:e=>{r.current?.id===e.pointerId&&(a(),e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId))},onPointerCancel:a,onLostPointerCapture:a,onDoubleClick:()=>i(280),onKeyDown:t=>{[`ArrowLeft`,`ArrowRight`,`Home`].includes(t.key)&&(t.preventDefault(),t.stopPropagation(),i(t.key===`Home`?280:e+(t.key===`ArrowRight`?1:-1)*(t.shiftKey?64:16)))},children:(0,Q.jsx)(`span`,{"aria-hidden":!0,className:`h-10 w-1 rounded-full bg-border`})})}function Ws(e,t,n,r=!0){let i=Fr(),a=h(),o=(0,Z.useRef)(null);(0,Z.useLayoutEffect)(()=>{let s=window.history.state?.idx??0,c=o.current,l=a.state?.canvasMenuBack||!!c&&(s<c.index||s===c.index&&c.backwards);if(o.current={active:t,viewKey:n,index:s,backwards:l},!r||!i||!t||!c||c.active&&c.viewKey===n)return;let u=e.current;if(!u||window.matchMedia(`(prefers-reduced-motion: reduce)`).matches)return;let d=Number.parseFloat(getComputedStyle(u).getPropertyValue(`--motion-scale`)),f=Number.isFinite(d)?Math.max(0,d):1,p=u.animate([{transform:`translateX(${l?`-100%`:`100%`})`},{transform:`translateX(0)`}],{duration:70*f,easing:`cubic-bezier(0.2, 0, 0, 1)`});return()=>p.cancel()},[r,i,t,n,a.key,a.state,e])}function Gs(e){return[...e].sort((e,t)=>{let n=typeof e.order==`number`&&Number.isFinite(e.order)?e.order:2**53-1,r=typeof t.order==`number`&&Number.isFinite(t.order)?t.order:2**53-1;if(n!==r)return n-r;let i=e.createdAt??``,a=t.createdAt??``;return i===a?(e.name??``).localeCompare(t.name??``):i<a?-1:1})}function Ks(e,t,n){let r=[...e],[i]=r.splice(t,1);return r.splice(n,0,i),r}async function qs(e,t){return{failed:(await Promise.allSettled(e.map((e,n)=>e.order===n?Promise.resolve():t(e,n)))).filter(e=>e.status===`rejected`).length}}function Js(e){let[t,n]=(0,Z.useState)(null),[r,i]=(0,Z.useState)(null);return{rowProps:e=>({"data-reorder-index":e}),handleProps:t=>({onPointerDown:r=>{if(r.pointerType===`mouse`&&r.button!==0)return;r.preventDefault(),r.stopPropagation();let a=r.currentTarget.closest(`[data-reorder-index]`);if(!a)return;let o=a.parentElement,s=(o?[...o.querySelectorAll(`:scope > [data-reorder-index]`)]:[a]).map(e=>({index:Number(e.dataset.reorderIndex),rect:e.getBoundingClientRect()})).filter(e=>Number.isFinite(e.index)).sort((e,t)=>e.index-t.index).map(e=>e.rect.top+e.rect.height/2),c=a.getBoundingClientRect(),l=a.cloneNode(!0);Object.assign(l.style,{position:`fixed`,left:`${c.left}px`,top:`${c.top}px`,width:`${c.width}px`,height:`${c.height}px`,margin:`0`,pointerEvents:`none`,zIndex:`100`,opacity:`0.92`,boxShadow:`0 12px 32px rgba(0,0,0,.28)`,willChange:`transform`}),document.body.appendChild(l);let u={x:r.clientX,y:r.clientY},d=t;n(t),i(t);let f={x:r.clientX,y:r.clientY},p=0,m=()=>{p=0,l.style.transform=`translate(${f.x-u.x}px, ${f.y-u.y}px) scale(1.02)`;let e=s.length;for(let t=0;t<s.length;t++)if(f.y<s[t]){e=t;break}e!==d&&(d=e,i(e))},h=e=>{f={x:e.clientX,y:e.clientY},p||=requestAnimationFrame(m)},g=()=>{window.removeEventListener(`pointermove`,h),window.removeEventListener(`pointerup`,g),window.removeEventListener(`pointercancel`,g),p&&cancelAnimationFrame(p),l.remove(),n(null),i(null),d!==t&&d!==t+1&&e(t,d>t?d-1:d)};window.addEventListener(`pointermove`,h),window.addEventListener(`pointerup`,g),window.addEventListener(`pointercancel`,g)},onClick:e=>{e.preventDefault(),e.stopPropagation()},style:{touchAction:`none`}}),insertIndex:r,draggingIndex:t,insertLineClass:(e,n)=>r===null||t===null?!1:r===e?`shadow-[0_-3px_0_0_var(--color-primary)]`:r===n&&e===n-1&&`shadow-[0_3px_0_0_var(--color-primary)]`}}function Ys(e){let[t,n]=(0,Z.useState)([]),[r,i]=(0,Z.useState)(!1),a=(0,Z.useRef)(!1),o=(0,Z.useRef)(!1),s=(0,Z.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await ci();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch contexts:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,Z.useRef)(s);(0,Z.useEffect)(()=>{c.current=s});let l=(0,Z.useCallback)(()=>{a.current=!1,s()},[s]);return(0,Z.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,Z.useEffect)(()=>{if(!e)return;let t=()=>X.emit(`subscribe`,{channel:`context`}),r=()=>X.emit(`unsubscribe`,{channel:`context`}),i=X.on(`connect`,()=>{t(),s()});t();let o=e=>{let t=e;!t?.id||!t?.userId||n(e=>e.some(e=>e.id===t.id&&e.userId===t.userId)?e:[...e,t])},l=e=>{let t=e;!t?.id||!t?.userId||n(e=>e.map(e=>e.id===t.id&&e.userId===t.userId?{...e,...t}:e))},u=e=>{let t=e,r=t?.contextId??t?.id;r&&n(e=>e.filter(e=>e.id!==r))},d=e=>{let t=e;!t?.id||!t?.userId||n(e=>e.map(e=>e.id===t.id&&e.userId===t.userId?{...e,...t}:e))},f=()=>{a.current=!1,c.current()},p=[[`context:created`,o],[`context.created`,o],[`context:updated`,l],[`context.updated`,l],[`context:deleted`,u],[`context.deleted`,u],[`context:url:changed`,d],[`context.url.set`,d],[`context:url:set`,d],[`workspace:status:changed`,f],[`workspace.status.changed`,f]];return p.forEach(([e,t])=>X.on(e,t)),()=>{r(),i?.(),p.forEach(([e,t])=>X.off(e,t))}},[e,s]),(0,Z.useEffect)(()=>{let e=e=>{let t=e.detail;n(e=>e.filter(e=>!oi(e,t)))};return window.addEventListener(ii,e),()=>window.removeEventListener(ii,e)},[]),(0,Z.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`contexts:refresh`,e),()=>window.removeEventListener(`contexts:refresh`,e)},[s]),{contexts:(0,Z.useMemo)(()=>Gs(t),[t]),isLoading:r,refresh:l}}function Xs(){let{state:e,selectEntity:t,openM2:n,closeM2:r}=la(),a=Fr(),{contexts:o,isLoading:s}=Ys(e.activeSection===`contexts`),{showToast:c}=xn(),l=m(),[u,d]=(0,Z.useState)(null),f=u&&u.base===o?u.order:o,p=e=>e.isShared===!0||e.type===`shared`,{rowProps:h,handleProps:g,draggingIndex:_,insertLineClass:v}=Js((e,t)=>{let n=Ks(f,e,t);d({base:o,order:n}),qs(n,(e,t)=>p(e)?Promise.resolve():di(e.id,{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`contexts:refresh`)),e&&c({title:`Partial reorder`,description:`${e} context(s) could not be reordered`,variant:`destructive`})})}),y=e=>{t(e.id),l(`/contexts/${e.id}`)};return(0,Q.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 items-center`,children:[(0,Q.jsx)(Ms,{}),(0,Q.jsx)(`span`,{className:`text-sm font-semibold`,children:`Contexts`})]}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>{r(),l(`/contexts?create=1`)},title:`Create context`,"aria-label":`Create context`,className:`flex items-center justify-center w-6 h-6 rounded-full bg-foreground text-background hover:opacity-80 transition-opacity`,children:(0,Q.jsx)(ge,{className:`w-3.5 h-3.5`})})]}),(0,Q.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:s&&o.length===0?(0,Q.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):o.length===0?(0,Q.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No contexts found`}):(0,Q.jsx)(`div`,{className:`space-y-1.5 px-2`,children:f.map((r,o)=>{let s=e.selectedEntityId===r.id,c=p(r),u=r.workspaceActive!==!1,d=Si(r.color);return(0,Q.jsxs)(`div`,{...h(o),"data-active":s||void 0,className:G(`group relative rounded-(--card-radius) py-2.5 pl-3 pr-7 transition-all shadow-elevation-1`,u?`cursor-pointer hover:shadow `+(s?`bg-accent shadow`:`bg-card hover:bg-accent/50`):`cursor-not-allowed opacity-50 bg-card`,v(o,f.length),_===o&&`opacity-60`),onClick:()=>u&&y(r),title:u?void 0:`Workspace "${r.workspaceName}" is not active`,children:[c?(0,Q.jsx)(`div`,{className:G(`absolute inset-y-0 right-0 w-4 rounded-r-(--card-radius)`,!d&&`bg-muted`),style:d?{backgroundColor:d}:void 0}):(0,Q.jsx)(`button`,{type:`button`,...g(o),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:G(`absolute inset-y-0 right-0 flex w-4 cursor-grab items-center justify-center rounded-r-(--card-radius) active:cursor-grabbing`,!d&&`bg-muted`),style:d?{backgroundColor:d}:void 0,children:(0,Q.jsx)(I,{className:G(`h-3.5 w-3.5`,Ci(d))})}),(0,Q.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Q.jsx)(i,{icon:r.icon||`ph:stack-fill`,width:16,height:16,color:d,className:G(`mt-0.5 shrink-0`,!d&&`text-muted-foreground`)}),(0,Q.jsx)(`span`,{className:`text-sm font-medium truncate flex-1`,children:r.name||r.id}),c&&(0,Q.jsx)(`span`,{className:`rounded-full bg-info/10 px-1.5 py-0.5 text-[9px] text-info shrink-0`,children:`Shared`}),u&&(0,Q.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),t(r.id),n(`detail`,r.id)},className:`reveal-on-hover shrink-0 mt-0.5`,title:`Switch context URL`,children:(0,Q.jsx)(zt,{className:`w-3.5 h-3.5 text-muted-foreground hover:text-foreground`})}),(0,Q.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),t(r.id),a?n(`settings`,r.id):l(`/contexts/${r.id}/settings/general`)},className:`reveal-on-hover shrink-0 mt-0.5`,title:`Settings`,children:(0,Q.jsx)(pt,{className:`w-3.5 h-3.5 text-muted-foreground hover:text-foreground`})})]}),r.name&&(0,Q.jsx)(`div`,{className:`text-[10px] text-muted-foreground/60 truncate font-mono`,children:r.id}),(0,Q.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5`,children:r.url||`/`}),r.ownerEmail&&(0,Q.jsx)(`div`,{className:`text-[10px] text-muted-foreground truncate mt-0.5`,children:r.ownerEmail})]},`${r.userId||`u`}-${r.id}`)})})})]})}function Zs({title:e,onBack:t,action:n,className:r,icon:a,accentColor:o}){let{closeM1:s}=la(),c=Si(o);return(0,Q.jsxs)(`div`,{className:G(`flex items-center h-12 px-2 border-b border-border shrink-0 gap-1`,r),style:{borderBottomWidth:4,...c?{borderBottomColor:c}:{}},children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:t,className:`flex items-center gap-0.5 h-8 rounded px-1 hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors flex-1 min-w-0`,title:`Back`,"aria-label":`Back to previous view`,children:[(0,Q.jsx)(se,{className:`w-4 h-4 shrink-0`}),a&&(0,Q.jsx)(i,{icon:a,width:16,height:16,color:c,className:G(`mr-1 shrink-0`,!c&&`text-muted-foreground`)}),(0,Q.jsx)(`span`,{className:`text-sm font-semibold truncate`,children:e})]}),n&&(0,Q.jsx)(`div`,{className:`shrink-0`,children:n}),(0,Q.jsx)(`button`,{type:`button`,onClick:s,className:`flex h-8 w-8 shrink-0 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground`,title:`Close menu`,"aria-label":`Close menu`,children:(0,Q.jsx)(z,{className:`w-4 h-4`})})]})}function Qs(e,t,n){let r=e.indexOf(n);if(r<0)return new Set;let i=t===null?-1:e.indexOf(t);return new Set(i<0?[n]:e.slice(Math.min(i,r),Math.max(i,r)+1))}function $s(e){let t=[...e];return t.filter(e=>!t.some(t=>t!==e&&e.startsWith(`${t}/`)))}var ec=e(s(),1),tc=180;function nc({x:e,y:t,current:n,onChange:r,onClose:a}){hi(a);let[o,s]=(0,Z.useState)(``),[c,l]=(0,Z.useState)([]),[u,d]=(0,Z.useState)({q:``,list:[]}),[f,p]=(0,Z.useState)(!0),m=(0,Z.useRef)(null),h=(0,Z.useRef)({name:``,t:0}),g=(e,t)=>{r({icon:e}),h.current.name===e&&t-h.current.t<350&&a(),h.current={name:e,t}};(0,Z.useEffect)(()=>{m.current?.focus()},[]),(0,Z.useEffect)(()=>{let e=!0;return vi().then(t=>{e&&(l(t),p(!1))}),()=>{e=!1}},[]),(0,Z.useEffect)(()=>{let e=o.trim();if(!e)return;let t=setTimeout(()=>{yi(e).then(t=>{d({q:e,list:t})})},250);return()=>clearTimeout(t)},[o]);let _=o.trim(),v=u.q===_,y=_!==``&&!v,b=(0,Z.useMemo)(()=>(_?v?u.list:[]:c).slice(0,tc),[_,v,u.list,c]),x=(0,Z.useRef)(null),[S,C]=(0,Z.useState)({x:e,y:t});return(0,Z.useLayoutEffect)(()=>{let n=x.current;if(!n)return;let r=()=>{let{width:r,height:i}=n.getBoundingClientRect();C({x:Math.max(8,Math.min(e,window.innerWidth-r-8)),y:Math.max(8,Math.min(t,window.innerHeight-i-8))})};r();let i=new ResizeObserver(r);return i.observe(n),window.addEventListener(`resize`,r),()=>{i.disconnect(),window.removeEventListener(`resize`,r)}},[e,t]),(0,ec.createPortal)((0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`fixed inset-0 z-40`,onClick:a}),(0,Q.jsxs)(`div`,{ref:x,className:`fixed z-50 w-[270px] max-w-[90vw] rounded-md border bg-popover p-2 shadow-elevation-4`,style:{left:S.x,top:S.y},children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between px-1 pb-1.5`,children:[(0,Q.jsx)(`span`,{className:`text-xs font-medium`,children:`Icon & color`}),(0,Q.jsx)(`button`,{type:`button`,onClick:a,className:`text-muted-foreground hover:text-foreground`,children:(0,Q.jsx)(z,{className:`w-3.5 h-3.5`})})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap gap-1.5 px-1 pb-2`,children:[_i.map(e=>(0,Q.jsx)(`button`,{type:`button`,title:e,onClick:()=>r({color:e}),className:G(`w-5 h-5 rounded-full border transition-transform hover:scale-110`,n.color===e?`ring-2 ring-offset-1 ring-foreground`:`border-border`),style:{backgroundColor:e}},e)),(0,Q.jsx)(`button`,{type:`button`,title:`No color`,onClick:()=>r({color:void 0}),className:G(`w-5 h-5 rounded-full border flex items-center justify-center text-muted-foreground hover:scale-110 transition-transform`,!n.color&&`ring-2 ring-offset-1 ring-foreground`),children:(0,Q.jsx)(z,{className:`w-3 h-3`})}),(0,Q.jsx)(`label`,{title:`Custom color`,className:G(`relative w-5 h-5 rounded-full border border-border cursor-pointer hover:scale-110 transition-transform overflow-hidden`,n.color&&!_i.includes(n.color)&&`ring-2 ring-offset-1 ring-foreground`),style:{background:n.color&&!_i.includes(n.color)?n.color:`conic-gradient(from 0deg, #ef4444, #eab308, #22c55e, #06b6d4, #6366f1, #ec4899, #ef4444)`},children:(0,Q.jsx)(`input`,{type:`color`,value:n.color??`#3b82f6`,onChange:e=>r({color:e.target.value}),className:`absolute inset-0 opacity-0 cursor-pointer`})})]}),(0,Q.jsx)(`input`,{ref:m,value:o,onChange:e=>s(e.target.value),placeholder:`Search icons…`,className:`w-full mb-2 rounded-sm border bg-background px-2 py-1 text-xs outline-none focus:ring-1 focus:ring-primary`}),f||y?(0,Q.jsxs)(`div`,{className:`flex items-center justify-center gap-2 py-8 text-xs text-muted-foreground`,children:[(0,Q.jsx)(Dt,{className:`w-4 h-4 animate-spin`}),` `,y?`Searching…`:`Loading icons…`]}):(0,Q.jsxs)(`div`,{className:`grid grid-cols-7 gap-0.5 max-h-[200px] overflow-y-auto`,children:[(0,Q.jsx)(`button`,{type:`button`,title:`No icon`,onClick:()=>r({icon:void 0}),className:G(`aspect-square flex items-center justify-center rounded-sm hover:bg-accent text-muted-foreground`,!n.icon&&`bg-accent ring-1 ring-primary`),children:(0,Q.jsx)(z,{className:`w-4 h-4`})}),b.map(e=>(0,Q.jsx)(`button`,{type:`button`,title:e.replace(/^[^:]+:/,``).replace(`-fill`,``),onClick:t=>g(e,t.timeStamp),className:G(`aspect-square flex items-center justify-center rounded-sm hover:bg-accent`,n.icon===e&&`bg-accent ring-1 ring-primary`),children:(0,Q.jsx)(i,{icon:e,width:18,height:18,color:n.color})},e))]}),!f&&!y&&b.length===0&&(0,Q.jsxs)(`div`,{className:`px-1 py-3 text-center text-[11px] text-muted-foreground`,children:[`No icons match “`,o,`”`]})]})]}),document.body)}var rc=[{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.`}],ic=`canvas:treeStyle`;function ac(){try{let e=localStorage.getItem(ic);return e===`accordion`||e===`accordion-mobile`?e:`cards`}catch{return`cards`}}var oc=ac(),sc=new Set;function cc(){return oc}function lc(e){try{e===`cards`?localStorage.removeItem(ic):localStorage.setItem(ic,e)}catch{}oc=e;for(let e of sc)e()}function uc(e){sc.add(e);let t=t=>{(t.key===ic||t.key===null)&&(oc=ac(),e())};return window.addEventListener(`storage`,t),()=>{sc.delete(e),window.removeEventListener(`storage`,t)}}function dc(){return(0,Z.useSyncExternalStore)(uc,cc,()=>`cards`)}function fc(){let e=dc(),t=Fr();return e===`accordion`||e===`accordion-mobile`&&t}var pc=22,mc=44,hc=4;function gc(e,t){if(!t)return null;let n=String(e||``).split(`/`).filter(Boolean);return n[0]===`workspace`&&n[1]===`git`?null:n[0]===`workspace`&&n.length>=2?{address:`workspace:${n[1]}`,key:n.slice(2).join(`/`)}:n[0]===`device`&&n.length>=3?{address:n[2],key:n.slice(3).join(`/`)}:n[0]===`file`&&n.length>=2?{address:n[1],key:n.slice(2).join(`/`)}:null}function _c(e,t){return!t||sr(e)!==null}var vc=e=>Array.from(e.dataTransfer.types).includes(`application/json`);function yc(e,t){if(!t)return null;let n=String(e||``).split(`/`).filter(Boolean);return n[0]===`workspace`&&n[1]===`git`?n[2]||null:n[0]===`workspace`&&n.length>=2?`workspace:${n[1]}`:n[0]===`device`?n.length>=3?n[2]:null:n.length>=2?n[1]:null}function bc({x:e,y:t,node:n,path:r,isBackendsTree:i,isDirectoryTree:a,backends:o,onClose:s,onShowContent:c,onOpenToSide:l,sourceLayer:u,targetLayers:d,clipboard:f,onStartInlineCreate:p,onChangeIcon:m,onNewCanvas:h,onShareCanvas:g,onRemove:_,onRename:v,onExportSubtree:y,onImportSubtree:b,onImportDocuments:x,onExportDocuments:S,onLock:C,onUnlock:w,onDestroy:T,onMerge:E,onSubtract:D,onMergeDown:O,onSubtractDown:A,onResyncBackend:M,canResyncBackend:N,onAddRule:ee,onAddStoreRule:P,onStoragePolicy:te,onRenameBackendFolder:ne,onDeleteBackendFolder:re,onRestoreTrash:ie,onDiscardTrash:F,onCopy:oe,onCut:I,onPaste:se,pastedDocumentIds:ce,onPasteDocuments:le,isPinned:ue,onTogglePin:L}){let R=u&&d.size>0&&u.path===r,z=!i&&(O||A)&&r!==`/`&&n.type!==`canvas`&&r.split(`/`).filter(Boolean).length>1,B=u&&d.size>0&&(u.path===r||d.has(r)),fe=async e=>{s();try{await e()}catch(e){alert(e instanceof Error?e.message:String(e))}},H=(e,t,n,r=!1)=>(0,Q.jsxs)(`button`,{type:`button`,className:G(`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,r&&`text-destructive hover:bg-destructive/10`),onClick:()=>fe(n),children:[e,t]});return i&&n.metadata?.backendTrash?(0,Q.jsxs)(wn,{x:e,y:t,onClose:s,className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[c&&H((0,Q.jsx)(Fe,{className:`h-3 w-3`}),`Open Trash`,async()=>c(r)),r!==`/Trash`&&ie&&H((0,Q.jsx)(we,{className:`h-3 w-3`}),`Restore original paths`,()=>ie(r)),r!==`/Trash`&&F&&H((0,Q.jsx)(Fe,{className:`h-3 w-3`}),`Empty Trash`,()=>F(r),!0)]}):(0,Q.jsxs)(wn,{x:e,y:t,onClose:s,className:`min-w-[11rem] rounded-md border bg-popover p-1 shadow-elevation-3`,children:[c&&H((0,Q.jsx)(it,{className:`w-3 h-3`}),`Show layer content`,async()=>{c(r,n.id||void 0)}),l&&H((0,Q.jsx)(it,{className:`w-3 h-3`}),`Open to the side`,async()=>{l(r)}),(c||l)&&(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`}),n.type===`canvas`&&g&&H((0,Q.jsx)(Ct,{className:`w-3 h-3`}),`Share canvas`,async()=>{await g(r)}),n.type===`canvas`&&g&&(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`}),M&&(N?.(r)??!!yc(r,i))&&(0,Q.jsxs)(Q.Fragment,{children:[H((0,Q.jsx)(_t,{className:`w-3 h-3`}),`Refresh backend`,async()=>{await M(r)}),(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),i&&yc(r,i)&&(ee||P)&&(0,Q.jsxs)(Q.Fragment,{children:[ee&&H((0,Q.jsx)(Re,{className:`w-3 h-3`}),`Auto-Link documents to…`,async()=>{ee(r)}),P&&gc(r,i)&&H((0,Q.jsx)(j,{className:`w-3 h-3`}),`Create storage rule…`,async()=>{P(r)}),(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),!i&&(P||te)&&r!==`/`&&(0,Q.jsxs)(Q.Fragment,{children:[P&&H((0,Q.jsx)(j,{className:`w-3 h-3`}),`Create rule…`,async()=>{P(r)}),P&&H((0,Q.jsx)(Bt,{className:`w-3 h-3`}),`Create download rule…`,async()=>{P(r,`download`)}),te&&n.type!==`canvas`&&H((0,Q.jsx)(de,{className:`w-3 h-3`}),`Storage policy…`,async()=>{te(r)}),(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),(!i||gc(r,i))&&(0,Q.jsxs)(`button`,{type:`button`,className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,onClick:()=>{p(r),s()},children:[(0,Q.jsx)(ge,{className:`w-3 h-3`}),`New folder here`]}),ne&&gc(r,i)?.key&&H((0,Q.jsx)(je,{className:`w-3 h-3`}),`Rename folder`,async()=>{let e=r.split(`/`).pop()||``,t=prompt(`New folder name:`,e);!t||t===e||await ne(r,t)}),re&&i&&tr(r,o)&&H((0,Q.jsx)(Fe,{className:`w-3 h-3`}),`Delete from backend`,async()=>{confirm(`Delete folder "${r.split(`/`).pop()}" and its contents from the backend?`)&&await re(r)},!0),h&&!i&&(0,Q.jsxs)(`button`,{type:`button`,className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,onClick:()=>{h(r),s()},children:[(0,Q.jsx)(qe,{className:`w-3 h-3 text-primary`}),`New canvas here…`]}),r!==`/`&&L&&H(ue?(0,Q.jsx)(W,{className:`w-3 h-3`}):(0,Q.jsx)(V,{className:`w-3 h-3`}),ue?`Unpin`:`Pin`,async()=>{await L()}),r!==`/`&&m&&(0,Q.jsxs)(`button`,{type:`button`,className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,onClick:()=>{m(),s()},children:[(0,Q.jsx)(ae,{className:`w-3 h-3`}),`Change icon`]}),r!==`/`&&!n.locked&&v&&!i&&H((0,Q.jsx)(je,{className:`w-3 h-3`}),`Rename`,async()=>{let e=r.split(`/`).pop()||``,t=prompt(`New name:`,e);!t||t===e||await v(r,t)}),(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`}),H((0,Q.jsx)(Ce,{className:`w-3 h-3`}),`Copy`,async()=>oe(r)),!i&&H((0,Q.jsx)(Kt,{className:`w-3 h-3`}),`Cut`,async()=>I(r)),f&&!i&&H((0,Q.jsx)(k,{className:`w-3 h-3`}),`Paste (${f.mode})`,async()=>se(r)),ce&&ce.length>0&&le&&_c(r,i)&&H((0,Q.jsx)(k,{className:`w-3 h-3`}),i?`Move ${ce.length} message(s) here`:`Paste ${ce.length} document(s)`,async()=>{await le(r,ce)}),x&&H((0,Q.jsx)(Ot,{className:`w-3 h-3`}),`Import documents…`,()=>x(r)),S&&H((0,Q.jsx)(Bt,{className:`w-3 h-3`}),`Export documents…`,()=>S(r)),(y||b)&&(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`}),y&&n.type!==`canvas`&&H((0,Q.jsx)(Bt,{className:`w-3 h-3`}),`Export subtree…`,()=>y(r)),b&&!i&&n.type!==`canvas`&&H((0,Q.jsx)(Ot,{className:`w-3 h-3`}),`Import subtree here…`,()=>b(r)),!i&&r!==`/`&&!n.locked&&_&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`}),H((0,Q.jsx)(Fe,{className:`w-3 h-3`}),`Remove`,async()=>{confirm(`Remove "${r}"${a?` and all children`:``}?`)&&await _(r,a)},!0),!a&&H((0,Q.jsx)(Fe,{className:`w-3 h-3`}),`Remove recursive`,async()=>{confirm(`Remove "${r}" and all children?`)&&await _(r,!0)},!0)]}),!i&&(C||w||T)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`}),n.locked?w&&H((0,Q.jsx)($e,{className:`w-3 h-3`}),`Unlock layer`,async()=>{await w(n.id)}):C&&H((0,Q.jsx)(Ft,{className:`w-3 h-3`}),`Lock layer`,async()=>{await C(n.id)}),n.locked&&n.lockedBy&&n.lockedBy.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`px-3 pt-1 pb-0.5 text-[10px] uppercase tracking-wide text-muted-foreground`,children:`Locked by`}),n.lockedBy.map(e=>(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-2 px-3 py-1 text-xs`,children:[(0,Q.jsx)(`span`,{className:`truncate`,title:e,children:e}),w&&(0,Q.jsx)(`button`,{type:`button`,title:`Remove lock held by ${e}`,className:`shrink-0 text-muted-foreground hover:text-destructive`,onClick:()=>fe(async()=>{await w(n.id,e)}),children:(0,Q.jsx)($e,{className:`w-3 h-3`})})]},e))]}),r!==`/`&&!n.locked&&T&&H((0,Q.jsx)(Fe,{className:`w-3 h-3`}),`Destroy layer`,async()=>{confirm(`Permanently destroy layer "${n.label||n.name}" and its bitmap?`)&&await T(n.id)},!0)]}),z&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`}),O&&H((0,Q.jsx)(ut,{className:`w-3 h-3`}),`Merge down (into ancestors)`,async()=>{confirm(`Merge "${n.label||n.name}" into every layer above it on\n${r}\n\nAfter this, ${r} lists its documents.`)&&await O(r)}),A&&H((0,Q.jsx)(vt,{className:`w-3 h-3`}),`Subtract from ancestors`,async()=>{confirm(`Remove "${n.label||n.name}"'s documents from every layer above it on\n${r}\n\nUndo of "Merge down". Documents an ancestor holds for other reasons are removed from it too.`)&&await A(r)})]}),R&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`}),E&&H((0,Q.jsx)(xe,{className:`w-3 h-3`}),`Merge this layer into ${d.size} selected`,async()=>{confirm(`Merge "${r}" (source) INTO:\n${Array.from(d.keys()).join(`
3
3
  `)}\n\nThe selected layers gain this layer's documents. This layer is unchanged.`)&&await E(n.id,Array.from(d.values()))}),D&&H((0,Q.jsx)(xe,{className:`w-3 h-3`}),`Subtract this layer from ${d.size} selected`,async()=>{confirm(`Subtract "${r}" (source) FROM:\n${Array.from(d.keys()).join(`
4
4
  `)}\n\nThe selected layers lose this layer's documents. This layer is unchanged.`)&&await D(n.id,Array.from(d.values()))})]}),B&&!R&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`}),(0,Q.jsxs)(`div`,{className:`px-3 py-1.5 text-[10px] text-muted-foreground italic`,children:[`This is a target. Right-click the source (`,u?.path,`) to merge/subtract`]})]})]})}function xc({onConfirm:e,onCancel:t,placeholder:n=`folder name…`}){let r=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{r.current?.focus()},[]);let i=()=>{let n=r.current?.value.trim()??``;n?e(n):t()};return(0,Q.jsxs)(`div`,{className:`flex min-h-11 items-center gap-2 rounded-(--card-radius) px-3 py-2.5 bg-card ring-1 ring-primary/50 shadow-elevation-3 text-sm font-medium`,children:[(0,Q.jsx)(Ae,{className:`w-4 h-4 opacity-0 shrink-0`}),(0,Q.jsx)(`input`,{ref:r,className:`flex-1 bg-transparent outline-none min-w-0 text-sm font-medium placeholder:font-normal placeholder:text-muted-foreground`,placeholder:n,onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),i()),e.key===`Escape`&&t()},onBlur:i})]})}function Sc(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function Cc(e,t,n){let r=Sc(t,e.name);return r.toLowerCase().includes(n)||(e.label||``).toLowerCase().includes(n)?!0:e.children?.some(e=>Cc(e,r,n))??!1}function wc({expansionState:e,node:t,parentPath:n,depth:r,isLast:a,selectedPath:o,pendingPath:s,contentPath:c,readOnly:l,sourceLayer:u,targetLayers:d,clipboard:f,searchQuery:p,inlineCreateParent:m,onSelect:h,onAltSelect:g,selectedPaths:_,onRangeSelect:v,onShowContent:y,onCtrl:b,onCtxMenu:x,onConfirmCreate:S,onCancelCreate:C,onOpenPicker:w,styleOverrides:T,dragOverPath:E,isCopyDrag:D,onDragStart:O,onDragEnter:k,onDragOver:A,onDragLeave:j,onDragEnd:M,onDrop:N,resyncingPaths:ee,policyBadgeFor:P,removingPaths:te,accordion:ne=!1,trail:re=[]}){let ie=Er(),F=Sc(n,t.name),ae=P?.(F)??null,oe=T.get(F)??xi(t),[I,se]=(0,Z.useState)(()=>e?.get(t.id||F)??(o!==`/`&&(o===F||o.startsWith(F+`/`)))),[ce,le]=(0,Z.useState)(o);if(ce!==o&&(le(o),o!==`/`&&o.startsWith(F+`/`)&&se(!0)),(0,Z.useEffect)(()=>{e?.set(t.id||F,I)},[e,t.id,F,I]),p&&!Cc(t,n,p))return null;let ue=I||m===F||p.length>0,L=t.children&&t.children.length>0,R=o===F||_.has(F),z=s===F,B=u?.path===F,V=d.has(F),fe=t.type===`canvas`,H=e=>{if(e.shiftKey){v(F,e);return}if(e.ctrlKey||e.metaKey){b(F,t.id);return}if(e.altKey&&g){g(F);return}h(F)},pe=e=>{!L||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||e.target.closest(`button, input, textarea, select, a, [contenteditable="true"]`)||(e.preventDefault(),e.stopPropagation(),se(e=>!e))},me=[...re].reverse().find(Boolean)??null,he=oe.color||me,ge=ne?[...re,he]:re,_e=o!==`/`&&o.startsWith(F+`/`),ve=!B&&!V,U=ve&&R,ye=(e,t)=>`color-mix(in oklab, ${e} ${t}%, var(--card))`,W=e=>`color-mix(in oklab, currentColor ${e}%, transparent)`,be=Math.min(r,5),xe=ue&&!!L,Se=ve&&!U&&!t.locked&&xe,Ce=Math.min(3+be*2+(_e?4:0)+(z?3:0),18),we=U?`var(--primary)`:B?ye(`var(--info)`,12):V?ye(`var(--warning)`,12):Se?`var(--accent)`:ye(`var(--muted-foreground)`,Ce),Te=U?`text-primary-foreground`:Se?`text-accent-foreground`:`text-foreground`,Ee=ne&&ue&&L&&r<hc,Oe=(0,Q.jsxs)(`div`,{"data-tree-path":F,"data-selected":_.has(F)||void 0,"data-active":R||void 0,className:G(`group relative flex cursor-pointer select-none items-stretch overflow-hidden text-sm`,`after:pointer-events-none after:absolute after:inset-0 after:bg-foreground/0 after:transition-colors hover:after:bg-foreground/[0.07]`,Te,B&&`ring-1 ring-inset ring-info/40`,V&&!B&&`ring-1 ring-inset ring-warning/40`,E===F&&!l&&!D&&`ring-2 ring-inset ring-info`,E===F&&!l&&D&&`ring-2 ring-inset ring-success`),style:{height:mc,background:we,borderBottom:`1px solid var(--border)`,...Ee?{position:`sticky`,top:r*mc,zIndex:20-r}:{}},draggable:!l&&!t.metadata?.backendTrash,onClick:H,onDoubleClick:pe,...l?{}:ie,onContextMenu:e=>{l||(e.preventDefault(),x(e,F,t))},onDragStart:e=>{l||O(F,e)},onDragEnter:e=>{l||k(F,e)},onDragOver:e=>{l||A(F,e)},onDragLeave:e=>j(F,e),onDragEnd:()=>M(),onDrop:e=>{l||N(F,e)},children:[re.length>0&&(0,Q.jsx)(`span`,{className:`flex shrink-0 gap-px`,"aria-hidden":!0,children:re.map((e,t)=>(0,Q.jsx)(`span`,{className:`w-[3px]`,style:{background:e?`color-mix(in oklab, ${e} 35%, var(--border))`:`var(--border)`}},t))}),(()=>{let e=oe.color?{background:oe.color}:me?{background:`color-mix(in oklab, ${me} 45%, transparent)`}:{background:W(10)},n=(0,Q.jsx)(i,{icon:oe.icon||(fe?`ph:squares-four-fill`:`ph:folder-fill`),width:18,height:18,className:G(`shrink-0`,oe.color?Ci(oe.color):U?`text-primary-foreground`:Se?`text-current`:`text-foreground/80`)}),r=`flex w-10 shrink-0 items-center justify-center`;return w?(0,Q.jsx)(`button`,{type:`button`,className:r,style:e,title:`Change icon`,onClick:e=>{$t()||(e.stopPropagation(),w(e,F,t))},onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),w(e,F,t)},children:n}):(0,Q.jsx)(`span`,{className:r,style:e,children:n})})(),(0,Q.jsx)(`span`,{className:G(`min-w-0 flex-1 self-center truncate px-2.5`,R||_e||xe?`font-semibold`:`font-medium`),title:t.description||void 0,children:t.label||t.name}),te.has(F)&&(0,Q.jsx)(_t,{className:`mr-1 h-3.5 w-3.5 shrink-0 animate-spin self-center`,"aria-label":te.get(F)}),ee?.has(F)&&(0,Q.jsx)(_t,{className:`mr-1 h-3.5 w-3.5 shrink-0 animate-spin self-center opacity-70`,"aria-label":`Indexing`}),ae&&(0,Q.jsx)(de,{className:`mr-1 h-3 w-3 shrink-0 self-center text-muted-foreground`,"aria-label":ae,children:(0,Q.jsx)(`title`,{children:ae})}),!l&&(0,Q.jsx)(`button`,{type:`button`,className:`reveal-on-hover shrink-0 self-center rounded p-1 hover:bg-foreground/10`,onClick:e=>{e.stopPropagation(),x(e,F,t)},children:(0,Q.jsx)(st,{className:`h-4 w-4`})}),(0,Q.jsx)(`button`,{type:`button`,className:G(`relative z-[1] flex w-12 shrink-0 cursor-pointer items-center justify-center transition-colors`,`bg-[color-mix(in_oklab,currentColor_9%,transparent)] hover:bg-[color-mix(in_oklab,currentColor_24%,transparent)] active:bg-[color-mix(in_oklab,currentColor_32%,transparent)]`,!L&&m!==F&&`invisible`),style:{borderLeft:`1px solid ${W(16)}`},"aria-label":ue?`Collapse`:`Expand`,"aria-expanded":ue,title:ue?`Collapse`:`Expand`,onClick:e=>{e.stopPropagation(),se(e=>!e)},children:ue?(0,Q.jsx)(De,{className:`h-5 w-5`,strokeWidth:2.25}):(0,Q.jsx)(Ae,{className:`h-5 w-5`,strokeWidth:2.25})})]});return(0,Q.jsxs)(`div`,{className:`relative`,children:[ne?Oe:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`pointer-events-none absolute top-0 w-px bg-border`,style:{left:`-${pc/2}px`,...a?{height:`1.375rem`}:{bottom:0}}}),(0,Q.jsx)(`div`,{className:`pointer-events-none absolute top-[1.375rem] h-px bg-border`,style:{left:`-${pc/2}px`,width:`${pc/2}px`}}),(0,Q.jsxs)(`div`,{"data-tree-path":F,"data-selected":_.has(F)||void 0,"data-active":R||void 0,className:G(`group relative flex min-h-11 items-center gap-2 rounded-(--card-radius) px-3 py-2.5 cursor-pointer transition-all select-none overflow-hidden`,`shadow-elevation-3 hover:shadow-elevation-4 text-sm`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,B&&`ring-1 ring-info/40 bg-info/10 before:bg-info`,V&&!B&&`ring-1 ring-warning/40 bg-warning/10 before:bg-warning`,!B&&!V&&R&&!t.locked&&`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`,!B&&!V&&R&&t.locked&&`bg-warning/15 hover:bg-warning/20 before:bg-primary`,!B&&!V&&!R&&z&&`bg-primary/[0.03] before:bg-transparent`,!B&&!V&&!R&&!z&&!t.locked&&`bg-card hover:bg-primary/[0.04] before:bg-transparent`,!B&&!V&&!R&&t.locked&&`bg-warning/15 hover:bg-warning/20 before:bg-warning`,E===F&&!l&&!D&&`ring-2 ring-info bg-info-subtle/50`,E===F&&!l&&D&&`ring-2 ring-success bg-success-subtle/50`),style:{borderRight:oe.color?`4px solid ${oe.color}`:`4px solid transparent`},draggable:!l&&!t.metadata?.backendTrash,onClick:H,onDoubleClick:pe,...l?{}:ie,onContextMenu:e=>{l||(e.preventDefault(),x(e,F,t))},onDragStart:e=>{l||O(F,e)},onDragEnter:e=>{l||k(F,e)},onDragOver:e=>{l||A(F,e)},onDragLeave:e=>j(F,e),onDragEnd:()=>M(),onDrop:e=>{l||N(F,e)},children:[(0,Q.jsx)(`button`,{type:`button`,className:G(`shrink-0 text-muted-foreground hover:text-foreground`,!L&&m!==F&&`invisible`),"aria-label":ue?`Collapse`:`Expand`,"aria-expanded":ue,onClick:e=>{e.stopPropagation(),se(e=>!e)},children:ue?(0,Q.jsx)(De,{className:`w-4 h-4`}):(0,Q.jsx)(Ae,{className:`w-4 h-4`})}),(()=>{let e=(0,Q.jsx)(i,{icon:oe.icon||(fe?`ph:squares-four-fill`:`ph:folder-fill`),width:16,height:16,color:oe.color||void 0,className:G(`shrink-0`,!oe.color&&(fe?`text-primary`:`text-muted-foreground`))});return w?(0,Q.jsx)(`button`,{type:`button`,className:`shrink-0 rounded p-0.5 -m-0.5 hover:bg-muted-foreground/10 touch-target`,title:`Change icon`,onClick:e=>{$t()||(e.stopPropagation(),w(e,F,t))},onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),w(e,F,t)},children:e}):e})(),(0,Q.jsx)(`span`,{className:`flex-1 truncate font-medium`,title:t.description||void 0,children:t.label||t.name}),te.has(F)&&(0,Q.jsx)(_t,{className:`h-3.5 w-3.5 shrink-0 animate-spin`,"aria-label":te.get(F)}),ee?.has(F)&&(0,Q.jsx)(_t,{className:`w-3.5 h-3.5 shrink-0 animate-spin text-muted-foreground`,"aria-label":`Indexing`}),ae&&(0,Q.jsx)(de,{className:`w-3 h-3 shrink-0 text-muted-foreground`,"aria-label":ae,children:(0,Q.jsx)(`title`,{children:ae})}),!l&&(0,Q.jsx)(`button`,{type:`button`,className:`shrink-0 reveal-on-hover p-1 rounded hover:bg-muted-foreground/10 text-muted-foreground`,onClick:e=>{e.stopPropagation(),x(e,F,t)},children:(0,Q.jsx)(st,{className:`w-4 h-4`})})]})]}),ue&&(L||m===F)&&(0,Q.jsxs)(`div`,{className:ne?void 0:`ml-[22px] mt-2 mb-1 space-y-1.5`,children:[m===F&&(0,Q.jsx)(xc,{onConfirm:e=>S(F,e),onCancel:C}),t.children?.map((n,i)=>(0,Q.jsx)(wc,{node:n,expansionState:e,parentPath:F,depth:r+1,isLast:i===(t.children?.length??0)-1,selectedPath:o,pendingPath:s,contentPath:c,readOnly:l,sourceLayer:u,targetLayers:d,clipboard:f,searchQuery:p,inlineCreateParent:m,onSelect:h,onAltSelect:g,selectedPaths:_,onRangeSelect:v,onShowContent:y,onCtrl:b,onCtxMenu:x,onConfirmCreate:S,onCancelCreate:C,onOpenPicker:w,styleOverrides:T,dragOverPath:E,isCopyDrag:D,onDragStart:O,onDragEnter:k,onDragOver:A,onDragLeave:j,onDragEnd:M,onDrop:N,resyncingPaths:ee,policyBadgeFor:P,removingPaths:te,accordion:ne,trail:ge},n.id||n.name))]})]})}function Tc({root:e,expansionState:t,workspaceId:n,treeName:r=`context`,isBackendsTree:i=!1,onRestoreTrash:a,onDiscardTrash:o,selectedPath:s,pendingPath:c,onSelect:l,isLoading:u=!1,readOnly:d=!1,onAddRule:f,onAddStoreRule:p,onStoragePolicy:m,policyBadgeFor:h,rootLabel:g,contentPath:_,onShowContent:v,onOpenToSide:y,onAltSelect:b,onInsertPath:x,onNewCanvas:S,onShareCanvas:C,onRemovePath:w,onRenamePath:T,onMovePath:E,onCopyPath:D,onExportSubtree:O,onImportSubtree:k,onImportDocuments:A,onExportDocuments:j,pastedDocumentIds:M,onPasteDocuments:N,onLockLayer:ee,onUnlockLayer:P,onDestroyLayer:te,onMergeLayer:ne,onSubtractLayer:re,onMergeDown:ie,onSubtractDown:F,onResyncBackend:ae,canResyncBackend:oe,onCreateBackendFolder:I,onRenameBackendFolder:se,onDeleteBackendFolder:ce,onUpdateNode:le,isPathPinned:ue,onTogglePin:L,searchQuery:R=``,resyncingPaths:de,backends:z}){let B=fc(),[V,fe]=(0,Z.useState)(new Set),H=(0,Z.useRef)(null),pe=e=>{H.current=e,fe(new Set),l(e)},me=(e,t)=>{t.preventDefault();let n=t.currentTarget.closest(`[data-menu-tree]`)?.querySelectorAll(`[data-tree-path]`),r=Array.from(n||[],e=>e.dataset.treePath),i=H.current||s;fe(Qs(r,i,e)),H.current=r.includes(i)?i:e},[he,ge]=(0,Z.useState)(null),[_e,ve]=(0,Z.useState)(null),[U,ye]=(0,Z.useState)(new Map),[W,be]=(0,Z.useState)(null),[xe,Se]=(0,Z.useState)(new Map),Ce=(0,Z.useRef)(new Set),we=(0,Z.useCallback)(async(e,t=!1,n=!1,a=!1)=>{if(!(i?ce:w)||[...Ce.current].some(t=>t===e||t.startsWith(e+`/`)||e.startsWith(t+`/`)))return!1;Ce.current.add(e);let o=i?`Deleting from backend…`:a?`Removing documents and backend files…`:n?`Removing and purging documents…`:`Removing folder…`;Se(t=>new Map(t).set(e,o));try{return i?await ce(e):await w(e,r===`directory`||t,n,a)}finally{Ce.current.delete(e),Se(t=>{let n=new Map(t);return n.delete(e),n})}},[w,ce,i,r]),[Te,Ee]=(0,Z.useState)(null),[Oe,ke]=(0,Z.useState)(new Map),[Ae,je]=(0,Z.useState)(e),Me=(0,Z.useRef)(new Map),Ne=(0,Z.useRef)(null),[Pe,Fe]=(0,Z.useState)(null);if(e!==Ae){je(e);let t=Pe;ke(t?new Map([[t.path,t.style]]):new Map)}let[Ie,Le]=(0,Z.useState)(null),[Re,ze]=(0,Z.useState)(null),[Be,Ve]=(0,Z.useState)(!1),[He,Ue]=(0,Z.useState)(!1),[We,Ge]=(0,Z.useState)(!0),Ke=(0,Z.useRef)(!0),qe=(0,Z.useRef)(null),Je=(0,Z.useRef)(r),Ye=(0,Z.useRef)(!1),Xe=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{let e=e=>{ge(e.detail??null)};return window.addEventListener(`tree:path-clipboard`,e),()=>window.removeEventListener(`tree:path-clipboard`,e)},[]),(0,Z.useEffect)(()=>{let e=e=>{let t=e.ctrlKey||e.altKey||Xe.current;Ye.current=t,Ve(t)};return window.addEventListener(`keydown`,e),window.addEventListener(`keyup`,e),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`keyup`,e)}},[]);let Ze=(0,Z.useCallback)((e,t,n)=>{if(Hi(Je.current,e)||Hi(r,t))return!1;if(Je.current!==r)return!0;let i=e.endsWith(`/`)?e.slice(0,-1):e,a=t.endsWith(`/`)?t.slice(0,-1):t,o=i.substring(0,i.lastIndexOf(`/`))||`/`;return!(a.startsWith(i+`/`)||i===a||!n&&a===o)},[r]),Qe=(0,Z.useCallback)((e,t)=>{if(Hi(r,e)){t.preventDefault();return}qe.current=e,Je.current=r,t.dataTransfer.setData(`text/plain`,e),t.dataTransfer.setData(`application/x-canvas-tree-path`,JSON.stringify({path:e,treeName:r})),t.dataTransfer.effectAllowed=`copyMove`},[r]),$e=e=>e.ctrlKey||e.altKey||Xe.current,et=(0,Z.useCallback)((e,t)=>{if(Hi(r,e))return;let n=qe.current,a=$e(t);if(a!==Ye.current&&(Ye.current=a,Ve(a)),n){if(!Ze(n,e,a))return}else if(vc(t)&&!_c(e,i))return;t.preventDefault(),ze(e)},[Ze,r,i]),tt=(0,Z.useCallback)((e,t)=>{if(Hi(r,e)){t.dataTransfer.dropEffect=`none`;return}let n=$e(t);n!==Ye.current&&(Ye.current=n,Ve(n));let a=qe.current;if(a){if(!Ze(a,e,n)){t.dataTransfer.dropEffect=`none`;return}}else if(vc(t)&&!_c(e,i)){t.dataTransfer.dropEffect=`none`;return}t.preventDefault(),t.dataTransfer.dropEffect=n&&!i?`copy`:`move`},[Ze,r,i]),nt=(0,Z.useCallback)((e,t)=>{t.currentTarget.contains(t.relatedTarget)||ze(t=>t===e?null:t)},[]),rt=(0,Z.useCallback)(()=>{qe.current=null,Je.current=r,Ye.current=!1,Ve(!1),ze(null)},[r]),it=(0,Z.useCallback)(async(e,t)=>{if(t.preventDefault(),t.stopPropagation(),Hi(r,e))return;let a=(()=>{try{return JSON.parse(t.dataTransfer.getData(`application/json`))}catch{return null}})();if(a?.type===`document`&&Array.isArray(a.documentIds)&&a.documentIds.length){if(qe.current=null,Ye.current=!1,Ve(!1),ze(null),Tr(a,n,r,e))return;if(N&&_c(e,i))try{await N(e,a.documentIds)}catch(e){alert(e instanceof Error?e.message:String(e))}return}let o=(()=>{try{return JSON.parse(t.dataTransfer.getData(`application/x-canvas-tree-path`))}catch{return null}})(),s=o?.path||t.dataTransfer.getData(`text/plain`),c=o?.treeName||Je.current||r;if(Hi(c,s))return;let l=$e(t)||Ye.current;if(qe.current=null,Je.current=r,Ye.current=!1,Ve(!1),ze(null),!s)return;let u=t.shiftKey,d=c!==r;if(!(!d&&s===e)&&!(!d&&!Ze(s,e,l)))try{if(l&&D)await D(s,e,u,c,r);else if(!l&&E){let t=Ke.current&&!i&&!!ie;await E(s,e,u,c,r,t?{mergeDown:t}:void 0)}}catch(e){alert(e instanceof Error?e.message:String(e))}},[Ze,D,E,N,n,r,i,ie]),at=R.toLowerCase().trim(),ot=(0,Z.useCallback)((e,t,n)=>{e.stopPropagation(),be({x:e.clientX,y:e.clientY,path:t,node:n})},[]),ct=(0,Z.useCallback)((e,t,n)=>{e.stopPropagation(),!n.metadata?.backendTrash&&(Ne.current=null,Fe(null),Ee({x:e.clientX,y:e.clientY,path:t,node:n}))},[]),lt=(0,Z.useCallback)(e=>{if(!Te||!le)return;let t=Te.path,n={...Oe.get(t)??(Ne.current?.path===t?Ne.current.style:xi(Te.node)),...e};Ne.current={path:t,style:n},Fe({path:t,style:n}),ke(e=>new Map(e).set(t,n));let r=bi(Te.node.metadata,n),i=Me.current,a=i.get(t);a&&clearTimeout(a),i.set(t,setTimeout(()=>{i.delete(t),le(t,{metadata:r}).catch(e=>alert(e instanceof Error?e.message:String(e)))},350))},[Te,le,Oe]),ut=(0,Z.useCallback)((e,t)=>{_e?e===_e.path?(ve(null),ye(new Map)):ye(n=>{let r=new Map(n);return r.has(e)?r.delete(e):r.set(e,t),r}):(ve({path:e,id:t}),ye(new Map))},[_e]),dt=(0,Z.useCallback)(async e=>{if(!(!he||!E||!D)&&!(he.treeName===r&&(e===he.path||e.startsWith(he.path+`/`)))){if(he.mode===`cut`){let t=Ke.current&&!i&&!!ie;await E(he.path,e,!1,he.treeName,r,t?{mergeDown:t}:void 0),ge(null),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:null}))}else await D(he.path,e,!0,he.treeName,r)}},[he,E,D,r,i,ie]);(0,Z.useEffect)(()=>{if(d)return;let e=e=>{let t=e.target;if(t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||e.key!==`F6`)return;if(e.preventDefault(),he?.mode===`cut`){dt(s);return}let n={mode:`cut`,path:s,treeName:r};ge(n),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:n}))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[he,dt,d,s,r]);let ft=(0,Z.useCallback)(async(e,t)=>{Le(null);let n=e===`/`?`/${t}`:`${e}/${t}`;try{gc(e,i)&&I?await I(e,t)&&l(n):x&&await x(n,!0)&&l(n)}catch(e){alert(e instanceof Error?e.message:String(e))}},[x,I,l,i]),pt=(0,Z.useCallback)(()=>{Le(null)},[]),mt=(0,Z.useCallback)((e,t)=>{let n={mode:t,path:e,treeName:r};ge(n),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:n}))},[r]),ht=(0,Z.useCallback)(t=>{if(d||En(t.target)||s&&Hi(r,s))return;if(Tn(t,`Mod+V`)){M?.length&&N&&s&&_c(s,i)?(t.preventDefault(),N(s,M).catch(()=>{})):he&&s&&(t.preventDefault(),dt(s).catch(e=>alert(e instanceof Error?e.message:String(e))));return}if(s&&s!==`/`&&(Tn(t,`Mod+C`)||!i&&Tn(t,`Mod+X`))){t.preventDefault(),mt(s,t.key.toLowerCase()===`x`?`cut`:`copy`);return}if((i?!ce||!tr(s||``,z):!w)||t.key!==`Delete`&&t.key!==`Backspace`||!s||s===`/`)return;t.preventDefault();let n=Jn(e,s);if(!i&&n?.locked){alert(`"${s}" is locked`);return}confirm(i?`Delete "${s}" and its contents from this backend?`:`Remove "${s}"${r===`directory`?` and all children`:``}?`)&&we(s,!1).catch(e=>alert(e instanceof Error?e.message:String(e)))},[d,w,ce,we,s,e,M,N,he,dt,i,mt,r,z]),gt=(0,Z.useCallback)(()=>{Ue(e=>{let t=!e;return Xe.current=t,Ye.current=t,Ve(t),t})},[]);if(u)return(0,Q.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading tree…`});if(!e)return(0,Q.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`No tree available`});let vt=_e||U.size>0,yt={expansionState:t,accordion:B,selectedPath:s,pendingPath:c,contentPath:_,readOnly:d,sourceLayer:_e,targetLayers:U,clipboard:he,searchQuery:at,inlineCreateParent:Ie,onSelect:pe,onAltSelect:b,selectedPaths:V,onRangeSelect:me,onShowContent:v,onCtrl:ut,onCtxMenu:ot,onConfirmCreate:ft,onCancelCreate:pt,onOpenPicker:le?ct:void 0,styleOverrides:Oe,dragOverPath:Re,isCopyDrag:Be,onDragStart:Qe,onDragEnter:et,onDragOver:tt,onDragLeave:nt,onDragEnd:rt,onDrop:it,resyncingPaths:de,backends:z,policyBadgeFor:i?void 0:h,removingPaths:xe};return(0,Q.jsxs)(`div`,{"data-menu-tree":!0,className:`px-3 py-2 space-y-1.5 outline-none min-h-full`,tabIndex:0,onKeyDown:ht,onContextMenu:t=>{t.defaultPrevented||d||(t.preventDefault(),ot(t,`/`,e))},children:[xe.size>0&&(0,Q.jsx)(`div`,{role:`status`,"aria-live":`polite`,className:`space-y-1 rounded-md border bg-muted/50 p-2 text-xs`,children:[...xe].map(([e,t])=>(0,Q.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Q.jsx)(_t,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin`,"aria-hidden":`true`}),(0,Q.jsxs)(`span`,{className:`min-w-0`,children:[(0,Q.jsx)(`span`,{className:`block`,children:t}),(0,Q.jsx)(`span`,{className:`block truncate text-muted-foreground`,title:e,children:e})]})]},e))}),!d&&(0,Q.jsxs)(`div`,{className:`flex items-center justify-end px-1 pb-0.5 text-[10px]`,children:[(0,Q.jsx)(`button`,{type:`button`,onClick:gt,title:`Toggle drag-drop mode (or hold Ctrl / Alt while dragging)`,className:G(`px-2 py-0.5 rounded-full border transition-colors select-none`,He?`border-success bg-success/15 text-success dark:text-success`:`border-border text-muted-foreground hover:bg-muted`),children:He?`Drag → Copy`:`Drag → Move`}),ie&&!i&&!He&&(0,Q.jsx)(`button`,{type:`button`,onClick:()=>Ge(e=>(Ke.current=!e,!e)),title:`When moving a layer, also merge it into its new ancestors so the new path lists its documents`,className:G(`ml-1 px-2 py-0.5 rounded-full border transition-colors select-none`,We?`border-info bg-info/15 text-info dark:text-info`:`border-border text-muted-foreground hover:bg-muted`),children:We?`+ merge down`:`merge down: off`})]}),vt&&(0,Q.jsxs)(`div`,{className:`flex items-center justify-between px-1 pb-1 text-[10px] text-muted-foreground`,children:[(0,Q.jsx)(`span`,{children:_e?`Source: ${_e.path} · ${U.size} target(s)`:`Select source with ⌃-click`}),(0,Q.jsx)(`button`,{type:`button`,className:`hover:text-foreground underline`,onClick:()=>{ve(null),ye(new Map)},children:`clear`})]}),(0,Q.jsxs)(`div`,{"data-active":s===`/`&&!_||void 0,className:G(`group relative flex min-h-11 items-center gap-2 rounded-(--card-radius) px-3 py-2.5 cursor-pointer transition-all select-none`,`shadow-elevation-3 hover:shadow-elevation-4 text-sm`,s===`/`&&!_?`bg-primary/[0.06]`:`bg-card hover:bg-primary/[0.04]`,Re===`/`&&!d&&!Be&&`ring-2 ring-info bg-info-subtle/50`,Re===`/`&&!d&&Be&&`ring-2 ring-success bg-success-subtle/50`),style:{borderRight:`4px solid transparent`},onClick:()=>pe(`/`),onDragEnter:e=>{d||et(`/`,e)},onDragOver:e=>{d||tt(`/`,e)},onDragLeave:e=>nt(`/`,e),onDrop:e=>{d||it(`/`,e)},onContextMenu:e=>{!d&&x&&(e.preventDefault(),be({x:e.clientX,y:e.clientY,path:`/`,node:{id:``,name:`/`,label:`/`,type:`root`,description:``,color:null,locked:!1,children:[]}}))},children:[(0,Q.jsx)(De,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,Q.jsxs)(`span`,{className:`flex-1 font-medium truncate`,children:[`/ `,g&&(0,Q.jsxs)(`span`,{className:`text-muted-foreground font-normal`,children:[`[`,g,`]`]})]}),!d&&x&&(0,Q.jsx)(`button`,{type:`button`,className:`shrink-0 reveal-on-hover p-1 rounded hover:bg-muted-foreground/10 text-muted-foreground`,onClick:e=>{e.stopPropagation(),be({x:e.clientX,y:e.clientY,path:`/`,node:{id:``,name:`/`,label:`/`,type:`root`,description:``,color:null,locked:!1,children:[]}})},children:(0,Q.jsx)(st,{className:`w-4 h-4`})})]}),(0,Q.jsxs)(`div`,{className:B?`mt-1.5 border-t border-border/60`:`ml-[22px] mt-1.5 space-y-1.5`,children:[Ie===`/`&&(0,Q.jsx)(xc,{onConfirm:e=>ft(`/`,e),onCancel:pt}),e.children?.map((t,n)=>(0,Q.jsx)(wc,{node:t,parentPath:`/`,depth:0,isLast:n===(e.children?.length??0)-1,...yt},t.id||t.name)),!e.children?.length&&Ie!==`/`&&(0,Q.jsx)(`div`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})]}),W&&V.size>1&&V.has(W.path)?(0,Q.jsxs)(wn,{x:W.x,y:W.y,onClose:()=>be(null),className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[(0,Q.jsxs)(`div`,{className:`px-3 py-1.5 text-xs text-muted-foreground`,children:[V.size,` folders selected`]}),(0,Q.jsx)(`button`,{type:`button`,className:`block w-full px-3 py-1.5 text-left text-xs hover:bg-accent`,onClick:()=>{navigator.clipboard?.writeText([...V].join(`
5
5
  `)),be(null)},children:`Copy paths`}),!d&&!i&&w&&(0,Q.jsx)(`button`,{type:`button`,className:`block w-full px-3 py-1.5 text-left text-xs text-destructive hover:bg-accent`,onClick:()=>{be(null);let e=$s(V);confirm(`Remove ${V.size} selected folders and their children?\n${e.join(`
6
- `)}`)&&(async()=>{for(let t of e)await we(t,!0);fe(new Set)})().catch(e=>alert(e instanceof Error?e.message:String(e)))},children:`Remove folders…`}),(0,Q.jsx)(`button`,{type:`button`,className:`block w-full px-3 py-1.5 text-left text-xs hover:bg-accent`,onClick:()=>{fe(new Set),be(null)},children:`Clear selection`})]}):W&&(0,Q.jsx)(bc,{x:W.x,y:W.y,node:W.node,path:W.path,isBackendsTree:i,backends:z,isDirectoryTree:r===`directory`,onClose:()=>be(null),onShowContent:W.node.metadata?.backendTrash?l:v,onRestoreTrash:d?void 0:a,onDiscardTrash:d?void 0:o,onOpenToSide:y?e=>y(e,r):void 0,sourceLayer:_e,targetLayers:U,clipboard:he,onStartInlineCreate:e=>Le(e),onChangeIcon:le?()=>ct({clientX:W.x,clientY:W.y,stopPropagation:()=>{}},W.path,W.node):void 0,onNewCanvas:S,onShareCanvas:C,onImportDocuments:d?void 0:A,onExportDocuments:j,onExportSubtree:O,onImportSubtree:d?void 0:k,onRemove:!d&&w&&![...xe.keys()].some(e=>e===W.path||e.startsWith(W.path+`/`)||W.path.startsWith(e+`/`))?we:void 0,onRename:d?void 0:T,onLock:d?void 0:ee,onUnlock:d?void 0:P,onDestroy:d?void 0:te,onMerge:d?void 0:ne,onSubtract:d?void 0:re,onMergeDown:d?void 0:ie,onSubtractDown:d?void 0:F,canResyncBackend:oe,onResyncBackend:ae,onAddRule:f,onAddStoreRule:p,onStoragePolicy:!d&&!i?m:void 0,onRenameBackendFolder:se,onDeleteBackendFolder:!d&&ce&&![...xe.keys()].some(e=>e===W.path||e.startsWith(W.path+`/`)||W.path.startsWith(e+`/`))?e=>we(e,!0):void 0,onCopy:e=>mt(e,`copy`),onCut:e=>mt(e,`cut`),onPaste:dt,pastedDocumentIds:M,onPasteDocuments:N,isPinned:ue?ue(W.path):!1,onTogglePin:L?()=>L(W.path,W.node):void 0}),Te&&le&&(0,Q.jsx)(nc,{x:Te.x,y:Te.y,current:Oe.get(Te.path)??xi(Te.node),onChange:lt,onClose:()=>Ee(null)})]})}function Ec(){let{state:e,closeM2:t,closeM1:n,closeM0:r,openM2:i}=la(),a=Fr(),o=m(),s=e.selectedEntityId,{showToast:c}=xn(),[l,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)(null),[p,h]=(0,Z.useState)(``),[g,_]=(0,Z.useState)(),[v,y]=(0,Z.useState)(``),[b,x]=(0,Z.useState)(`/`),[S,C]=(0,Z.useState)(null),[w,T]=(0,Z.useState)(!1),[E,D]=(0,Z.useState)(null),[O,k]=(0,Z.useState)(!1),A=(0,Z.useCallback)(async e=>{T(!0);try{let t=await li(e);f(t),D(null)}catch(e){D(e instanceof Error?e.message:`Failed to load the tree`)}finally{T(!1)}},[]);(0,Z.useEffect)(()=>{if(!s)return;let e=s,t=!1;async function n(){try{let n=await si(e);if(t)return;u(n),h(n.url||``),_(void 0),y(``),C(null),x(n.path||`/`),T(!0);try{let n=await li(e);t||(f(n),D(null))}catch(e){t||D(e instanceof Error?e.message:`Failed to load the tree`)}finally{t||T(!1)}}catch{t||c({title:`Error`,description:`Failed to load context`,variant:`destructive`})}}n();let r=t=>{t.detail?.contextId===e&&n()};return window.addEventListener(`contexts:refresh`,r),()=>{t=!0,window.removeEventListener(`contexts:refresh`,r)}},[s,c]);let j=Ar({contextId:s??void 0,onRefresh:()=>{s&&A(s)}}),M=e=>{_(void 0),C(e),h(l?.workspaceName?`${l.workspaceName}://${e.replace(/^\//,``)}`:e)},N=l!=null&&(p.trim()!==(l.url||``)||g!==void 0);return(0,Q.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Q.jsx)(Zs,{title:s||`Context`,icon:l?.icon||`ph:stack-fill`,accentColor:l?.color,onBack:t,action:(0,Q.jsx)(`button`,{type:`button`,onClick:()=>{s&&(a?i(`settings`,s):o(`/contexts/${s}/settings/general`))},className:`flex items-center justify-center w-8 h-8 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Settings`,children:(0,Q.jsx)(pt,{className:`w-3.5 h-3.5`})})}),(0,Q.jsxs)(`div`,{className:`p-3 border-b border-border shrink-0`,children:[(0,Q.jsx)(`div`,{className:`text-[10px] text-muted-foreground mb-1.5 font-medium uppercase tracking-wide`,children:`Context URL`}),(0,Q.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Q.jsx)(Yi,{presentation:`breadcrumbs`,value:p,fixedWorkspaceName:l?.workspaceName,pickerTitle:`Switch context to…`,onPickTarget:(e,t)=>{h(`${t.workspaceName}://${e.replace(/^\/+/,``)}`),_(t.treeName),C(null)},onChange:e=>{h(e),C(g?null:`/`+e.replace(/^.*?:\/\//,``).replace(/^\/+/,``))},disabled:O,className:`min-w-0 flex-1`,inputClassName:G(`text-xs transition-colors`,N&&`border-warning/60 bg-warning/10`),placeholder:`workspace://path`}),(0,Q.jsx)(K,{size:`sm`,className:`h-9 px-2 text-xs shrink-0`,onClick:async()=>{if(!s)return;let e=s;k(!0);try{await ai(e,p,void 0,g);let t=await si(e);u(t),h(t.url||``),x(t.path||`/`),C(null),_(void 0),window.dispatchEvent(new CustomEvent(`contexts:refresh`)),await A(e),c({title:`Saved`,description:`Context URL updated`}),window.matchMedia(`(max-width: 767px)`).matches&&(n(),r())}catch(e){c({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{k(!1)}},disabled:O||!N,children:O?`…`:`Set`})]})]}),g&&(0,Q.jsxs)(`p`,{className:`px-3 py-1 text-xs text-muted-foreground`,children:[`Destination tree: `,g,` · press Set to apply`]}),(0,Q.jsx)(`div`,{className:`px-3 py-2 border-b shrink-0`,children:(0,Q.jsx)(en,{type:`search`,name:`context-tree-filter`,autoComplete:`off`,"data-lpignore":`true`,"data-1p-ignore":`true`,"aria-label":`Search context tree`,placeholder:`Search paths…`,value:v,onChange:e=>y(e.target.value),className:`h-7 text-xs`})}),(0,Q.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,children:[(0,Q.jsxs)(`div`,{className:`text-[10px] text-muted-foreground px-3 pt-2 pb-1 font-medium uppercase tracking-wide shrink-0`,children:[l?.workspaceName||`Workspace`,` · `,d?.type===`directory`?`directory`:`context`,` tree`]}),E&&!d&&(0,Q.jsx)(`p`,{className:`px-3 pb-1 text-xs text-destructive`,children:E}),(0,Q.jsx)(Tc,{root:d,workspaceId:l?.workspaceName,searchQuery:v,selectedPath:b,pendingPath:S,onSelect:M,isLoading:w,rootLabel:l?.workspaceName,...j})]})]})}function Dc({items:e,activeId:t,onSelect:n}){let[r,i]=(0,Z.useState)(``),a=e.filter(e=>ua(r,e.label,e.description||``));return(0,Q.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:(0,Q.jsxs)(`div`,{className:`space-y-1 px-2`,children:[(0,Q.jsx)(en,{type:`search`,name:`settings-section-filter`,autoComplete:`off`,"data-lpignore":`true`,"data-1p-ignore":`true`,"aria-label":`Search settings sections`,placeholder:`Find a setting…`,className:`mb-3`,value:r,onChange:e=>i(e.target.value)}),!a.length&&(0,Q.jsx)(`p`,{role:`status`,className:`p-3 text-sm text-muted-foreground`,children:`No matching settings.`}),a.map(e=>{let r=e.id===t;return(0,Q.jsxs)(`button`,{type:`button`,"aria-current":r?`page`:void 0,onClick:()=>n(e.id),className:G(`flex w-full items-center gap-2.5 rounded-md px-3 py-2 text-left transition-colors`,r?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50 hover:text-foreground`),children:[(0,Q.jsx)(`span`,{className:G(`shrink-0`,r?`text-foreground`:`text-muted-foreground`),children:e.icon}),(0,Q.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Q.jsx)(`span`,{className:`block text-sm font-medium text-foreground`,children:e.label}),e.description&&(0,Q.jsx)(`span`,{className:`mt-1 block text-xs leading-relaxed text-muted-foreground`,children:e.description})]}),(0,Q.jsx)(Ae,{className:G(`h-3.5 w-3.5 shrink-0`,r?`opacity-100`:`opacity-0`)})]},e.id)})]})})}var Oc=[{id:`general`,label:`Workspace details`,description:`Rename, change appearance or remove this workspace`,icon:ct},{id:`backups`,label:`Backups`,description:`Save or restore documents, relations and tree placements`,icon:ot},{id:`data`,label:`Files & storage`,description:`Connect folders and data sources, check disk usage or restore trash`,icon:j},{id:`db`,label:`Search & indexing`,description:`How documents become searchable: AI models, image descriptions, index repairs`,icon:Je},{id:`devices`,label:`Devices`,description:`Link devices to this workspace`,icon:Le},{id:`sync`,label:`Synchronization`,description:`Manage device copies and resolve sync conflicts`,icon:_t},{id:`services`,label:`Connected services`,description:`Configure Git, WebDAV, IMAP and other connectors`,icon:We},{id:`shares`,label:`Sharing & permissions`,description:`Create public links and manage workspace access`,icon:zt},{id:`policies`,label:`Storage policies`,description:`Mirror folders of the virtual tree to physical backends`,icon:de},{id:`hooks`,label:`Automation`,description:`Run hooks in response to workspace events`,icon:ke}],kc={embedding:`db`,trash:`data`};function Ac(e){return e?kc[e]?kc[e]:Oc.some(t=>t.id===e)?e:`general`:`general`}var jc=[{id:`general`,label:`Context details`,description:`Change the name, description or color, or remove this context`,icon:ct},{id:`location`,label:`Tree & path`,description:`Choose the workspace, tree and path this context opens`,icon:zt},{id:`shares`,label:`Sharing & permissions`,description:`Choose who can access this context`,icon:oe}];function Mc(e){return e&&jc.some(t=>t.id===e)?e:`general`}var Nc=[{id:`identity`,label:`Identity & instructions`,description:`Set the agent’s name, role and instructions`,icon:ct},{id:`provider`,label:`AI connection`,description:`Connect a chat model provider and manage its credentials`,icon:ie},{id:`models`,label:`Chat model`,description:`Choose the model and tune how it responds`,icon:Se},{id:`tools`,label:`Tools & skills`,description:`Choose the skills and MCP tools the agent can use`,icon:ye},{id:`access`,label:`Access & permissions`,description:`Choose which Canvas content the agent can access`,icon:te},{id:`memory`,label:`Memory`,description:`Configure how the agent remembers information`,icon:Be},{id:`integrations`,label:`Integrations`,description:`Connect mail, chat, databases and external APIs`,icon:D}];function Pc(e){return e&&Nc.some(t=>t.id===e)?e:`identity`}function Fc(){let{state:e,closeM2:t}=la(),n=Fr(),r=m(),i=h(),a=e.selectedEntityId,[o,s]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{if(!a)return;let e=!1;return si(a).then(t=>{e||s(t)}).catch(()=>{}),()=>{e=!0}},[a]);let c=i.pathname.split(`/`).filter(Boolean),l=c[2]===`settings`?Mc(c[3]):null,u=a?`/contexts/${a}`:null,d=(0,Z.useMemo)(()=>jc.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,Q.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,Q.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Q.jsx)(Zs,{title:`Settings: ${o?.name||a||`Context`}`,icon:o?.icon||`ph:stack-fill`,accentColor:o?.color??null,onBack:()=>u&&!n?r(u):t(),action:(0,Q.jsx)(`button`,{type:`button`,onClick:()=>u&&r(u),className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground`,title:`Open context`,children:(0,Q.jsx)(St,{className:`h-3.5 w-3.5`})})}),(0,Q.jsx)(Dc,{items:d,activeId:l,onSelect:e=>a&&r(`/contexts/${a}/settings/${e}`)})]})}function Ic(e){return e.isShared||e.type===`shared`?e.id:e.name}function Lc(e){let[t,n]=(0,Z.useState)([]),[r,i]=(0,Z.useState)(!1),a=(0,Z.useRef)(!1),o=(0,Z.useRef)(!1),s=(0,Z.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await Rn();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch workspaces:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,Z.useCallback)(()=>{a.current=!1,s()},[s]);return(0,Z.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,Z.useEffect)(()=>{if(!e)return;let t=()=>X.emit(`subscribe`,{channel:`workspace`}),r=()=>X.emit(`unsubscribe`,{channel:`workspace`}),i=X.on(`connect`,()=>{t(),s()});t();let a=e=>{let t=e,r=t?.workspaceId??t?.id,i=t?.status;!r||!i||n(e=>e.map(e=>e.id===r?{...e,status:i}:e))},o=e=>{let t=e?.workspace??e;t?.id&&n(e=>e.some(e=>e.id===t.id)?e:[...e,t])},c=e=>{let t=e,r=t?.workspaceId??t?.id;r&&n(e=>e.filter(e=>e.id!==r))},l=[[`workspaces.scanned`,e=>{let t=e?.report;t&&(t.discovered.length||t.adopted.length||t.updated.length||t.missing.length)&&s()}],[`workspace:status:changed`,a],[`workspace.status.changed`,a],[`workspace:created`,o],[`workspace.created`,o],[`workspace:deleted`,c],[`workspace.deleted`,c]];return l.forEach(([e,t])=>X.on(e,t)),()=>{r(),i?.(),l.forEach(([e,t])=>X.off(e,t))}},[e,s]),(0,Z.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`workspaces:refresh`,e),()=>{window.removeEventListener(`workspaces:refresh`,e)}},[s]),{workspaces:(0,Z.useMemo)(()=>Gs(t),[t]),isLoading:r,refresh:c}}function Rc({status:e}){return(0,Q.jsx)(`span`,{className:G(`inline-block w-2 h-2 rounded-full shrink-0`,e===`active`?`bg-success`:e===`error`?`bg-destructive`:`bg-muted-foreground`),title:e})}function zc(){let[e,t]=(0,Z.useState)(null),n=ms(),{state:r,selectEntity:a,openM2:o,closeM2:s}=la(),c=Fr(),{workspaces:l,isLoading:u}=Lc(r.activeSection===`workspaces`),{showToast:d}=xn(),f=m(),[p,h]=(0,Z.useState)(new Set),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(new Map),b=(0,Z.useRef)(new Map),[x,S]=(0,Z.useState)(null),C=x&&x.base===l?x.order:l,{rowProps:w,handleProps:T,draggingIndex:E,insertLineClass:D}=Js((e,t)=>{let n=Ks(C,e,t);S({base:l,order:n}),qs(n,(e,t)=>Qn(Ic(e),{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),e&&d({title:`Partial reorder`,description:`${e} workspace(s) could not be reordered`,variant:`destructive`})})}),O=e=>v.get(Ic(e))??{icon:e.icon??void 0,color:e.color??void 0},k=(e,t,n)=>{let r={...t,...n};y(t=>new Map(t).set(e,r));let i=b.current,a=i.get(e);a&&clearTimeout(a),i.set(e,setTimeout(()=>{i.delete(e);let t={icon:r.icon??null};r.color&&(t.color=r.color),Qn(e,t).then(()=>window.dispatchEvent(new CustomEvent(`workspaces:refresh`))).catch(e=>d({title:`Error`,description:e instanceof Error?e.message:`Update failed`,variant:`destructive`}))},350))},A=e=>{a(Ic(e)),o(`detail`,Ic(e)),!c&&ya(Ic(e))&&f(va(Ic(e)))},j=async(e,t)=>{e.stopPropagation(),h(e=>new Set(e).add(Ic(t)));try{await ur(Ic(t)),d({title:`Success`,description:`${t.label||t.name} started`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){d({title:`Error`,description:e instanceof Error?e.message:`Start failed`,variant:`destructive`})}finally{h(e=>{let n=new Set(e);return n.delete(Ic(t)),n})}},M=async(e,t)=>{e.stopPropagation(),h(e=>new Set(e).add(Ic(t)));try{await fr(Ic(t)),d({title:`Success`,description:`${t.label||t.name} stopped`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){d({title:`Error`,description:e instanceof Error?e.message:`Stop failed`,variant:`destructive`})}finally{h(e=>{let n=new Set(e);return n.delete(Ic(t)),n})}};return(0,Q.jsxs)(`div`,{className:`flex flex-col h-full`,onContextMenu:e=>{e.defaultPrevented||n.local||e.target.closest(`[data-workspace-row]`)||(e.preventDefault(),t({x:e.clientX,y:e.clientY}))},children:[e&&(0,Q.jsx)(wn,{...e,onClose:()=>t(null),className:`rounded-md border bg-popover p-1 shadow-elevation-3`,children:(0,Q.jsx)(`button`,{type:`button`,className:`px-3 py-1.5 text-xs hover:bg-accent`,onClick:()=>{t(null),s(),f(`/workspaces?create=1`)},children:`Create workspace…`})}),(0,Q.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 items-center`,children:[(0,Q.jsx)(Ms,{}),(0,Q.jsx)(`span`,{className:`text-sm font-semibold`,children:`Workspaces`})]}),!n.local&&(0,Q.jsx)(`button`,{type:`button`,onClick:()=>{s(),f(`/workspaces?create=1`)},title:`Create workspace`,"aria-label":`Create workspace`,className:`flex items-center justify-center w-6 h-6 rounded-full bg-foreground text-background hover:opacity-80 transition-opacity`,children:(0,Q.jsx)(ge,{className:`w-3.5 h-3.5`})})]}),(0,Q.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:u&&l.length===0?(0,Q.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):l.length===0?(0,Q.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No workspaces found`}):(0,Q.jsx)(`div`,{className:`space-y-1.5 px-2`,children:C.map((e,t)=>{let n=r.selectedEntityId===Ic(e),s=Ji(e),l=p.has(Ic(e)),u=e.status!==`active`,d=O(e),m=Si(d.color);return(0,Q.jsxs)(`div`,{"data-workspace-row":!0,...w(t),"data-active":n||void 0,className:G(`group relative rounded-(--card-radius) py-2.5 pl-3 pr-7 transition-all shadow-elevation-1`,n?`bg-accent shadow cursor-pointer hover:shadow`:u?`bg-card opacity-60 cursor-not-allowed`:`bg-card hover:bg-accent/50 cursor-pointer hover:shadow`,D(t,C.length),E===t&&`opacity-60`),onClick:()=>{u||A(e)},children:[(0,Q.jsx)(`button`,{type:`button`,...T(t),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:G(`absolute inset-y-0 right-0 flex w-4 cursor-grab items-center justify-center rounded-r-(--card-radius) active:cursor-grabbing`,!m&&`bg-muted`),style:m?{backgroundColor:m}:void 0,children:(0,Q.jsx)(I,{className:G(`h-3.5 w-3.5`,Ci(m))})}),(0,Q.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Q.jsx)(`button`,{type:`button`,title:s?`Change icon`:`Workspace appearance requires admin access`,onClick:t=>{!s||$t()||(t.stopPropagation(),_({x:Math.min(t.clientX,window.innerWidth-290),y:Math.min(t.clientY,window.innerHeight-360),name:Ic(e)}))},onContextMenu:t=>{s&&(t.preventDefault(),t.stopPropagation(),_({x:Math.min(t.clientX,window.innerWidth-290),y:Math.min(t.clientY,window.innerHeight-360),name:Ic(e)}))},className:`shrink-0 rounded p-0.5 hover:bg-muted-foreground/10 touch-target`,children:(0,Q.jsx)(i,{icon:d.icon||`ph:stack-fill`,width:18,height:18,color:m,className:G(!m&&`text-muted-foreground`)})}),(0,Q.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(Rc,{status:e.status}),(0,Q.jsx)(`span`,{className:`text-sm font-medium truncate`,children:e.label||e.name})]})}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-0.5 shrink-0`,children:[e.status===`active`?(0,Q.jsx)(`button`,{type:`button`,disabled:l,onClick:t=>M(t,e),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50 transition-colors`,title:`Stop`,children:(0,Q.jsx)(At,{className:`w-3.5 h-3.5`})}):(0,Q.jsx)(`button`,{type:`button`,disabled:l,onClick:t=>j(t,e),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50 transition-colors`,title:`Start`,children:(0,Q.jsx)(L,{className:`w-3.5 h-3.5`})}),(0,Q.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),a(Ic(e)),c?o(`settings`,Ic(e)):f(`/workspaces/${Ic(e)}/settings/general`)},className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground transition-colors disabled:opacity-40 disabled:cursor-not-allowed`,disabled:!s,title:s?`Settings`:`Workspace settings require admin access`,children:(0,Q.jsx)(pt,{className:`w-3.5 h-3.5`})})]})]}),e.description&&(0,Q.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-3.5`,children:e.description}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 mt-1 pl-3.5`,children:[e.host&&(0,Q.jsx)(`span`,{className:`text-[10px] text-muted-foreground truncate`,children:e.host}),e.ownerEmail&&(0,Q.jsx)(`span`,{className:`text-[10px] text-muted-foreground truncate`,children:e.ownerEmail})]})]},e.id||e.name)})})}),g&&(()=>{let e=l.find(e=>Ic(e)===g.name);if(!e)return null;let t=O(e);return(0,Q.jsx)(nc,{x:g.x,y:g.y,current:t,onChange:e=>k(g.name,t,e),onClose:()=>_(null)})})()]})}var Bc={previousTree:`Alt+Q`,nextTree:`Alt+W`},Vc=`canvas:key-bindings`,Hc=/^(Alt|Alt\+Shift|Ctrl\+Shift|Meta\+Shift)\+[A-Z]$/;function Uc(){try{let e=JSON.parse(localStorage.getItem(Vc)||`{}`),t={...Bc};for(let n of Object.keys(t))(e[n]===``||Hc.test(e[n]))&&(t[n]=e[n]);return t.previousTree&&t.previousTree===t.nextTree?{...Bc}:t}catch{return{...Bc}}}function Wc(e){localStorage.setItem(Vc,JSON.stringify(e))}function Gc(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 Kc(e,t,n){return e[(Math.max(0,e.indexOf(t))+n+e.length)%e.length]}function qc(e,t){return Math.abs(e)>=48&&Math.abs(e)>Math.abs(t)*1.5?e<0?1:-1:0}function Jc(e,t){let n=(0,Z.useRef)(null),r=(0,Z.useRef)(0);return(0,Z.useEffect)(()=>{if(!e)return;let n=e=>{if(e.defaultPrevented||e.repeat||e.isComposing||e.getModifierState(`AltGraph`))return;let n=e.target;if(n instanceof Element&&n.closest(`input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="textbox"], [role="dialog"], [role="alertdialog"]`)||document.querySelector(`[aria-modal="true"], dialog[open]`))return;let r=Gc(e);if(!r)return;let i=Uc(),a=r===i.previousTree?-1:+(r===i.nextTree);a&&(e.preventDefault(),t(a))};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[e,t]),{onTouchStart(e){r.current=0,n.current=e.touches.length===1?{x:e.touches[0].clientX,y:e.touches[0].clientY}:null},onTouchMove(e){e.touches.length!==1&&(n.current=null)},onTouchCancel(){n.current=null},onTouchEnd(i){if(!n.current||!e)return;let a=i.changedTouches[0],o=qc(a.clientX-n.current.x,a.clientY-n.current.y);n.current=null,o&&(r.current=Date.now()+500,i.stopPropagation(),t(o))},onClickCapture(e){Date.now()<r.current&&(e.preventDefault(),e.stopPropagation(),r.current=0)}}}function Yc(e,t,n,r=!1){if(!t.startsWith(`/`)||!n.length)throw Error(`Choose a source folder and at least one destination.`);let i=new Map;for(let e of n){if(![`context`,`directory`].includes(e.tree)||!e.path.startsWith(`/`))throw Error(`Choose a context or directory destination.`);if(e.path.includes(`{{`))throw Error(`Auto-Link destinations cannot contain {{ template markers.`);i.set(`${e.tree}:${e.path}`,e)}return{id:e,enabled:!0,description:`Auto-Link backends:${t} → ${[...i.keys()].join(`, `)}`,cascade:!0,when:{event:[`document.inserted`,`document.updated`,`document.linked`],...r?{path:`backends:${t}`}:{pathExact:`backends:${t}`}},then:[...i.values()].map(e=>({action:`link`,paths:[`${e.tree===`context`?`ctx`:`dir`}:${e.path}`],...r?{recursive:!0}:{}}))}}function Xc(e,t,n,r=!1,i=`forward`,a=`copy`,o,s){let c=Yc(e,t,n,r);if(i===`forward`)return[c];if(a===`move`&&!s?.trim())throw Error(`Choose the source backend whose copy should be moved.`);if(r&&n.some(e=>e.tree===`context`))throw Error(`Recursive storage requires a directory source. Context paths can store files in a fixed backend folder.`);let l=t.split(`/`).filter(Boolean);if(l.length<2||t.includes(`{{`)||l.some(e=>e===`.`||e===`..`))throw Error(`Choose a backend folder with a valid storage address.`);if(!o)throw Error(`Choose a writable backend folder.`);let u=o.address,d=o.key,f=[...new Map(n.map(e=>[`${e.tree}:${e.path}`,e])).values()],p={id:`${e}-reverse`,enabled:!0,description:`Auto-Link ${f.map(e=>`${e.tree}:${e.path}`).join(`, `)} → backends:${t} (${a})`,cascade:!1,when:{event:[`document.inserted`,`document.linked`],[r?`path`:`pathExact`]:f.map(e=>`${e.tree}:${e.path}`)},then:[{action:`store`,to:u,folder:d,mode:a,...a===`move`?{from:s.trim()}:{},autoLink:!0,onConflict:`error`,...r?{recursive:!0}:{}}]};return i===`both`?[c,p]:[p]}function Zc(e,t){let n=ei(e,t);if(t.find(e=>e.driver===n.driver&&e.address===n.address)?.capabilities.paths!==!0)throw Error(`This backend has not reported support for folder paths. Choose a writable storage folder to copy or move files here.`);return n}function Qc({workspaceId:e,sourcePath:t,onClose:n,onManageRules:r}){let[i,a]=(0,Z.useState)([]),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(`forward`),u=c===`forward`||!i.some(e=>e.tree===`context`),[d,f]=(0,Z.useState)(`copy`),[p,m]=(0,Z.useState)(``),[h,g]=(0,Z.useState)([]),[_,v]=(0,Z.useState)(!0),[y,b]=(0,Z.useState)(!1),[x,S]=(0,Z.useState)(!0),[C]=(0,Z.useState)(()=>`autolink-${crypto.randomUUID()}`),[w,T]=(0,Z.useState)(!1),[E,D]=(0,Z.useState)(``),{showToast:O,showProgress:k}=xn(),A=()=>{w||n()},j=_?`Checking whether this backend can receive files…`:``;if(!_)try{Zc(t,h)}catch(e){j=e instanceof Error?e.message:`Choose a writable storage folder.`}let M=e=>{l(e),e!==`forward`&&(S(!1),i.some(e=>e.tree===`context`)&&b(!1))},N=e=>`${e.replace(/\/+$/,``)}/${y?`Subfolder/`:``}example.pdf`;return(0,Z.useEffect)(()=>{let t=!1;return gr(e).then(e=>{t||g(e)}).catch(()=>{t||D(`Could not load storage backends. Reopen Autolink to retry.`)}).finally(()=>{t||v(!1)}),()=>{t=!0}},[e]),(0,Q.jsx)(Nr,{label:o?`Choose virtual paths`:`Autolink documents`,onClose:o?()=>s(!1):A,children:o?(0,Q.jsx)(Dn,{fixedWorkspaceName:e,tabs:c!==`forward`&&y?[`directory`]:[`context`,`directory`],initialTab:c===`forward`?void 0:`directory`,title:`Choose virtual paths`,confirmLabel:`Add paths`,sizeClassName:`h-full w-full rounded-none border-0 shadow-none`,onClose:()=>s(!1),onConfirm:(e,t)=>{c!==`forward`&&t.treeType===`context`&&b(!1),a(n=>{let r=[...n];for(let n of e)r.some(e=>e.tree===t.treeType&&e.path===n)||r.push({tree:t.treeType,path:n});return r}),s(!1)}}):(0,Q.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,Q.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-3 border-b p-5`,children:[(0,Q.jsxs)(`h2`,{className:`flex items-center gap-2 text-lg font-semibold`,children:[(0,Q.jsx)(zt,{className:`h-5 w-5`}),`Autolink documents`]}),(0,Q.jsx)(`button`,{type:`button`,onClick:A,disabled:w,"aria-label":`Close`,className:`p-1 disabled:opacity-40`,children:(0,Q.jsx)(z,{className:`h-4 w-4`})})]}),(0,Q.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-5 overflow-y-auto p-5`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Current backend folder`}),(0,Q.jsxs)(`p`,{className:`mt-1 break-words text-sm`,children:[`backends:`,t]})]}),(0,Q.jsxs)(`fieldset`,{disabled:w,className:`space-y-2 text-sm`,children:[(0,Q.jsx)(`label`,{className:`block font-medium`,htmlFor:`autolink-direction`,children:`Direction`}),(0,Q.jsxs)(`select`,{id:`autolink-direction`,className:`w-full rounded-md border bg-background p-2`,value:c,onChange:e=>M(e.target.value),children:[(0,Q.jsx)(`option`,{value:`forward`,children:`Backend → virtual folders (link)`}),(0,Q.jsx)(`option`,{value:`reverse`,disabled:!!j,children:`Virtual folders → backend (Copy/Move)`}),(0,Q.jsx)(`option`,{value:`both`,disabled:!!j,children:`Both directions`})]}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c===`forward`?`Link documents from this backend folder into the selected virtual folders. Files stay where they are.`:`When a document is added or explicitly linked to a selected virtual folder, ${d} its file to the current backend folder.${c===`both`?` Documents arriving on the backend are also linked into the virtual folders.`:``}`}),j&&(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:_?j:`Reverse mapping unavailable: ${j}`}),c!==`forward`&&(0,Q.jsxs)(`div`,{className:`space-y-2 rounded-lg border p-3`,children:[(0,Q.jsx)(`label`,{className:`block font-medium`,htmlFor:`autolink-operation`,children:`File operation`}),(0,Q.jsxs)(`select`,{id:`autolink-operation`,className:`w-full rounded-md border bg-background p-2`,value:d,onChange:e=>f(e.target.value),children:[(0,Q.jsx)(`option`,{value:`copy`,children:`Copy files to this backend`}),(0,Q.jsx)(`option`,{value:`move`,children:`Move files to this backend`})]}),d===`copy`&&(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Keep the source file and its virtual-folder links.`}),d===`move`&&(0,Q.jsxs)(`div`,{className:`mt-2 space-y-2`,children:[(0,Q.jsx)(`label`,{className:`block`,htmlFor:`autolink-source-backend`,children:`Move files from`}),(0,Q.jsxs)(`select`,{id:`autolink-source-backend`,className:`w-full rounded-md border bg-background p-2`,value:p,onChange:e=>m(e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:`Choose a source backend…`}),h.filter(e=>e.kind===`storage`&&e.enabled&&e.config?.readOnly!==!0).map(e=>(0,Q.jsx)(`option`,{value:e.address,children:e.address},e.address))]}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Move the file from this source backend after it has been stored at the destination. Virtual-folder links stay in place. Files missing from this source are skipped; multiple source copies require Copy instead.`})]})]})]}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(`h3`,{className:`text-sm font-medium`,children:c===`reverse`?`Watch virtual folders`:`Virtual folders`}),i.map((e,t)=>(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 rounded-lg border p-2 text-sm`,children:[(0,Q.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Q.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.tree===`context`?`Context tree`:`Directory tree`}),(0,Q.jsx)(`p`,{className:`break-words`,children:e.path})]}),(0,Q.jsx)(`button`,{type:`button`,"aria-label":`Remove ${e.tree}:${e.path}`,disabled:w,onClick:()=>a(e=>e.filter((e,n)=>n!==t)),children:(0,Q.jsx)(z,{className:`h-4 w-4`})})]},`${e.tree}:${e.path}`)),(0,Q.jsxs)(K,{variant:`outline`,size:`sm`,disabled:w,onClick:()=>s(!0),children:[(0,Q.jsx)(ge,{className:`mr-1 h-4 w-4`}),`Add virtual path…`]}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c===`forward`?`Choose the virtual folders where backend documents should appear.`:`Choose a Directory tree folder to watch for newly added documents. Its files will be stored in the current backend folder.`})]}),(0,Q.jsxs)(`fieldset`,{disabled:w,className:`space-y-3 text-sm`,children:[(0,Q.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:y,disabled:!u,onChange:e=>b(e.target.checked),className:`mt-1`}),`Include subfolders and recreate their path in the destination`]}),!u&&(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Context membership has no single folder path. To preserve subfolders on a backend, choose a directory source. Context paths store files directly in the selected backend folder.`}),(0,Q.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:x,onChange:e=>S(e.target.checked),className:`mt-1`}),`Apply to existing documents`]})]}),!!i.length&&(0,Q.jsxs)(`div`,{className:`space-y-3 rounded-lg border bg-muted/30 p-3 text-sm`,"aria-label":`Mapping preview`,children:[(0,Q.jsx)(`h3`,{className:`font-medium`,children:`Example result`}),i.map(e=>(0,Q.jsxs)(`div`,{className:`space-y-2 break-all text-xs`,children:[c!==`reverse`&&(0,Q.jsxs)(`p`,{children:[(0,Q.jsx)(`span`,{className:`text-muted-foreground`,children:`Link `}),`backends:`,N(t),(0,Q.jsx)(`br`,{}),(0,Q.jsx)(`span`,{className:`text-muted-foreground`,children:`Into `}),e.tree===`context`?`ctx`:`dir`,`:`,N(e.path)]}),c!==`forward`&&(0,Q.jsxs)(`p`,{children:[(0,Q.jsxs)(`span`,{className:`text-muted-foreground`,children:[d===`move`?`Move`:`Copy`,` `]}),e.tree===`context`?`ctx`:`dir`,`:`,N(e.path),(0,Q.jsx)(`br`,{}),(0,Q.jsx)(`span`,{className:`text-muted-foreground`,children:`To `}),`backends:`,N(t)]})]},`preview:${e.tree}:${e.path}`)),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:y?`The selected folders are the roots. Only the subfolder path beneath each root is recreated at its destination.`:`Only direct folder contents are included.`})]}),(0,Q.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[x?`Existing matching documents are processed in the background on the server once enabled.`:c===`forward`?`Future backend arrivals and updates are linked automatically.`:`Newly added or explicitly linked virtual-folder documents are processed automatically.`,` `,c===`both`&&`Both directions creates two rules in workspace Rules. `,`Removing rules keeps existing files and links. Renames and deletions are not synchronized. Filename conflicts stop the transfer without overwriting.`]}),E&&(0,Q.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:E})]}),(0,Q.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2 border-t p-3`,children:[(0,Q.jsx)(K,{variant:`ghost`,disabled:w,onClick:r,children:`Manage rules`}),(0,Q.jsx)(K,{disabled:w||!i.length||c!==`forward`&&(!!j||d===`move`&&!p),onClick:async()=>{if(!w){T(!0),D(``);try{let r=c===`forward`?void 0:Zc(t,await gr(e)),a=Xc(C,t,i,y,c,d,r,p);await Ki(e,a),x?Vi(k,e,a.map(e=>e.id)):O({title:`Autolink enabled`,description:`Future documents are linked automatically.`}),n()}catch(e){D(e instanceof Error?e.message:`Could not configure Auto-Link`)}finally{T(!1)}}},children:w?`Saving…`:`Enable Autolink`})]})]})})}var $c=e=>`/workspaces/${e}/storage-policies`;function el(){return`policy-${crypto.randomUUID().slice(0,8)}`}function tl(e){return e.filter(e=>e.enabled&&e.capabilities?.upload&&!e.config?.readOnly&&e.driver!==`cacache`)}var nl=new Set([`file`]);function rl(e,t){return`${e===`directory`?`dir`:`ctx`}:${t.startsWith(`/`)?t:`/${t}`}`}function il(e){let t=/^(ctx|dir):(\/.*)$/.exec(e);return t?{tree:t[1]===`dir`?`directory`:`context`,path:t[2]}:null}function al(e){return(il(e)?.path??e).replace(/^\/+/,``)}function ol(e){return`${e.backend}:${e.folder||`/`}`}async function sl(e){let t=await Y.get($c(e));return{...t,policies:t?.policies??[],revision:t.revision,blobBackend:t?.blobBackend??null}}async function cl(e,t,n){return Y.put($c(e),{policies:t,revision:n})}async function ll(e,t,n={}){return await Y.post(`${$c(e)}/${encodeURIComponent(t)}/apply`,n)}async function ul(e,t,n){let{policies:r,revision:i}=n??await sl(e),a=r.findIndex(e=>e.id===t.id);return cl(e,a===-1?[...r,t]:r.map((e,n)=>n===a?t:e),i)}async function dl(e,t,n,r={}){let i={folders:0,processed:0,matched:0,failed:0},a=0;for(;a!==null;){let o=await ll(e,t,{limit:r.limit??100,offset:a,dryRun:r.dryRun});if(i.folders+=o.folders??0,i.processed+=o.processed??0,i.matched+=o.matched??0,i.failed+=o.failed??0,n?.(o,i),o.nextOffset===void 0)throw Error(`The policy is saved, but applying it to existing documents needs an updated server.`);a=o.nextOffset}return i}function fl(e,t,n){let r=rl(t,n),i=r.endsWith(`/`)?r:`${r}/`;return e.filter(e=>{if(!e.enabled)return!1;if(e.path===r)return!0;if(!e.recursive)return!1;let t=e.path.endsWith(`/`)?e.path:`${e.path}/`;return i.startsWith(t)})}function pl(e){let t=new Set;for(let n of e)for(let e of n.targets)t.add(ol(e));return[...t].join(`, `)}async function ml(e,t){await Y.post(`${$c(e)}/operations/${encodeURIComponent(t)}/retry`,{})}function hl(e){return!e||!e.mime&&!e.filename&&(!e.schema||e.schema===`file`)?`files`:e.mime===`image/*`&&!e.filename&&(!e.schema||e.schema===`file`)?`images`:`custom`}function gl(e,t){return{backend:e?.address??``,folder:t,recursive:!0,recreateDirectories:!!e&&nl.has(e.driver),onConflict:`error`}}function _l({workspaceId:e,path:t,policy:n,onClose:r,onSaved:i}){let a=!!n,[o]=(0,Z.useState)(()=>n?.id??el()),[s,c]=(0,Z.useState)(n?.kind||`mirror`),[l,u]=(0,Z.useState)(n?.description??``),[d,f]=(0,Z.useState)(n?.recursive??!0),[p,m]=(0,Z.useState)(()=>hl(n?.filter)),[h,g]=(0,Z.useState)(n?.filter?.mime??``),[_,v]=(0,Z.useState)(n?.filter?.filename??``),[y,b]=(0,Z.useState)(n?.targets??[]),[x,S]=(0,Z.useState)(null),[C,w]=(0,Z.useState)(null),[T,E]=(0,Z.useState)(!1),[D,O]=(0,Z.useState)(!1),[k,A]=(0,Z.useState)(!1),[j,M]=(0,Z.useState)(``),[N,ee]=(0,Z.useState)(0),[P,te]=(0,Z.useState)(0),[ne,re]=(0,Z.useState)(0);hi(r,!D);let ie=()=>{D||r()},F=(0,Z.useMemo)(()=>al(t),[t]),ae=(0,Z.useMemo)(()=>tl(C??[]).filter(e=>s===`filing`||e.driver===`file`),[C,s]),oe=(0,Z.useMemo)(()=>new Map(ae.map(e=>[e.address,e])),[ae]);(0,Z.useEffect)(()=>{let t=!1;return Promise.all([gr(e),sl(e)]).then(([e,r])=>{if(t)return;if(n&&JSON.stringify(r.policies.find(e=>e.id===n.id))!==JSON.stringify(n))throw Error(`This policy changed. Close and reopen the editor.`);S(r),w(e);let i=tl(e).find(e=>n?.kind===`filing`||e.driver===`file`);i&&b(e=>e.length?e:[gl(i,F)])}).catch(e=>{t||(w([]),M(e instanceof Error?e.message:`Could not load backends`))}),()=>{t=!0}},[e,F,n]);let I=(e,t)=>b(n=>n.map((n,r)=>r===e?{...n,...t}:n)),se=(e,t)=>{let n=oe.get(t),r=!!n&&nl.has(n.driver);I(e,{backend:t,recreateDirectories:r?y[e].recreateDirectories:!1})},ce=()=>{if(!y.length)throw Error(`Add at least one target.`);let e=y.map(e=>{if(!e.backend)throw Error(`Choose a backend for every target.`);let t={backend:e.backend,folder:e.folder.trim().replace(/^\/+|\/+$/g,``),recursive:e.recursive,recreateDirectories:e.recreateDirectories,onConflict:e.onConflict??`error`};if(s===`filing`&&e.key?.trim()&&(t.key=e.key.trim()),s===`filing`&&(t.recreateDirectories=!1),s===`mirror`&&t.folder.includes(`{{`))throw Error(`Folder templates require a filing policy.`);return t}),r;return p===`images`?r={schema:`file`,mime:`image/*`}:p===`custom`&&(r={schema:`file`},h.trim()&&(r.mime=h.trim()),_.trim()&&(r.filename=_.trim())),{id:o,kind:s,enabled:n?.enabled??!0,...l.trim()?{description:l.trim()}:{},path:t,recursive:d,...r?{filter:r}:{},targets:e}},le=async()=>{if(!D){O(!0),M(``);try{let t=ce();T||(await ul(e,t,x),E(!0),i?.(t)),ee(0),te(0),re(0),await dl(e,o,(e,t)=>{ee(t.matched),te(t.folders),re(t.failed)}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`)),A(!0)}catch(e){M(e instanceof Error?e.message:`Could not save the storage policy`)}finally{O(!1)}}},ue=!!x&&y.length>0&&y.every(e=>e.backend);return(0,Q.jsx)(Ti,{onClose:ie,children:(0,Q.jsxs)(`section`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-policy-title`,className:`${Ei} flex flex-col overflow-hidden rounded-(--panel-radius) border bg-card shadow-elevation-4`,children:[(0,Q.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,Q.jsxs)(`h2`,{id:`storage-policy-title`,className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Q.jsx)(de,{className:`h-4 w-4`}),a?`Edit storage policy`:`Storage policy`]}),(0,Q.jsx)(`button`,{type:`button`,onClick:ie,disabled:D,"aria-label":`Close`,className:`p-1 disabled:opacity-40`,children:(0,Q.jsx)(z,{className:`h-4 w-4`})})]}),(0,Q.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-5 overflow-y-auto p-4`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Virtual path`}),(0,Q.jsx)(`p`,{className:`mt-1 break-words text-sm`,children:t})]}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Documents filed here are copied to every target in order. Uploads stay local until every destination has been verified. Mirrors move removed copies to Trash; filing policies keep their copies.`}),(0,Q.jsxs)(`fieldset`,{disabled:D||T,className:`space-y-3 text-sm`,children:[(0,Q.jsxs)(`label`,{className:`block`,children:[`Behavior`,(0,Q.jsxs)(`select`,{"aria-label":`Storage behavior`,className:`ml-2 rounded border bg-background p-2`,value:s,onChange:e=>c(e.target.value),children:[(0,Q.jsx)(`option`,{value:`mirror`,children:`Mirror (recoverable removal)`}),(0,Q.jsx)(`option`,{value:`filing`,children:`File copies (keep after unlink)`})]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`block text-xs text-muted-foreground`,htmlFor:`policy-description`,children:`Description (optional)`}),(0,Q.jsx)(`input`,{id:`policy-description`,className:`mt-1 w-full rounded-md border bg-background p-2`,value:l,onChange:e=>u(e.target.value),placeholder:`e.g. Accounting archive`})]}),(0,Q.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:d,onChange:e=>f(e.target.checked),className:`mt-1`}),`Apply to subfolders`]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`block text-xs text-muted-foreground`,htmlFor:`policy-filter`,children:`Documents`}),(0,Q.jsxs)(`select`,{id:`policy-filter`,className:`mt-1 w-full rounded-md border bg-background p-2`,value:p,onChange:e=>m(e.target.value),children:[(0,Q.jsx)(`option`,{value:`files`,children:`Files`}),(0,Q.jsx)(`option`,{value:`images`,children:`Images`}),(0,Q.jsx)(`option`,{value:`custom`,children:`Custom…`})]}),p===`custom`&&(0,Q.jsxs)(`div`,{className:`mt-2 grid grid-cols-2 gap-2`,children:[(0,Q.jsx)(`input`,{"aria-label":`MIME type`,className:`rounded-md border bg-background p-2`,value:h,onChange:e=>g(e.target.value),placeholder:`image/*`}),(0,Q.jsx)(`input`,{"aria-label":`Filename glob`,className:`rounded-md border bg-background p-2`,value:_,onChange:e=>v(e.target.value),placeholder:`img*`})]})]})]}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(`h3`,{className:`text-sm font-medium`,children:`Targets`}),C===null&&(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading backends…`}),C!==null&&!ae.length&&(0,Q.jsx)(`p`,{className:`text-xs text-destructive`,children:`No writable backend available. Add a folder or drive under Files & storage first.`}),y.map((e,t)=>{let n=oe.get(e.backend),r=s===`mirror`&&!!n&&nl.has(n.driver);return(0,Q.jsxs)(`fieldset`,{disabled:D||T,className:`space-y-2 rounded-lg border p-2 text-sm`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsxs)(`select`,{"aria-label":`Backend`,className:`min-w-0 flex-1 rounded-md border bg-background p-2`,value:e.backend,onChange:e=>se(t,e.target.value),children:[!e.backend&&(0,Q.jsx)(`option`,{value:``,children:`Choose a backend…`}),ae.map(e=>(0,Q.jsxs)(`option`,{value:e.address,children:[e.address,` (`,e.driver,`)`]},e.address)),e.backend&&!n&&(0,Q.jsxs)(`option`,{value:e.backend,children:[e.backend,` (unavailable)`]})]}),(0,Q.jsx)(`button`,{type:`button`,"aria-label":`Remove target`,onClick:()=>b(e=>e.filter((e,n)=>n!==t)),className:`p-1 disabled:opacity-40`,children:(0,Q.jsx)(z,{className:`h-4 w-4`})})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`block text-xs text-muted-foreground`,htmlFor:`policy-folder-${t}`,children:`Folder on the backend`}),(0,Q.jsx)(`input`,{id:`policy-folder-${t}`,className:`mt-1 w-full rounded-md border bg-background p-2`,value:e.folder,onChange:e=>I(t,{folder:e.target.value}),placeholder:`(backend root)`})]}),(0,Q.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:e.recursive,onChange:e=>I(t,{recursive:e.target.checked}),className:`mt-1`}),`Recreate sub-folder path in destination`]}),(0,Q.jsxs)(`label`,{className:`flex items-start gap-2 ${r?``:`opacity-60`}`,title:r?void 0:`Empty folders require a mirror on a supported file backend.`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:r&&e.recreateDirectories,disabled:!r,onChange:e=>I(t,{recreateDirectories:e.target.checked}),className:`mt-1`}),`Create folders on the backend`]}),(0,Q.jsxs)(`details`,{children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer text-xs text-muted-foreground`,children:`Advanced`}),(0,Q.jsxs)(`div`,{className:`mt-2 space-y-2`,children:[s===`filing`&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`block text-xs text-muted-foreground`,htmlFor:`policy-key-${t}`,children:`File-name template (optional)`}),(0,Q.jsx)(`input`,{id:`policy-key-${t}`,className:`mt-1 w-full rounded-md border bg-background p-2 font-mono text-xs`,value:e.key??``,onChange:e=>I(t,{key:e.target.value}),placeholder:`{{YYYY}}{{MM}}{{DD}}_{{basename}}{{ext}}`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`block text-xs text-muted-foreground`,htmlFor:`policy-conflict-${t}`,children:`On name conflict`}),(0,Q.jsxs)(`select`,{id:`policy-conflict-${t}`,className:`mt-1 w-full rounded-md border bg-background p-2`,value:e.onConflict??`error`,onChange:e=>I(t,{onConflict:e.target.value}),children:[(0,Q.jsx)(`option`,{value:`error`,children:`Stop with an error`}),(0,Q.jsx)(`option`,{value:`rename`,children:`Rename the new file`}),n?.driver===`file`&&(0,Q.jsx)(`option`,{value:`overwrite`,children:`Overwrite (retain previous bytes)`})]})]})]})]})]},t)}),!T&&(0,Q.jsxs)(K,{variant:`outline`,size:`sm`,disabled:D||!ae.length,onClick:()=>b(e=>[...e,gl(ae.find(t=>!e.some(e=>e.backend===t.address))??ae[0],F)]),children:[(0,Q.jsx)(ge,{className:`mr-1 h-4 w-4`}),`Add target…`]})]}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Applies to existing and future documents. Transfer progress and errors appear in Storage policies settings.`}),D&&(0,Q.jsx)(`p`,{role:`status`,className:`text-sm`,children:T?`Applying to existing documents… ${N} planned, ${P} folders`:`Saving storage policy…`}),k&&(0,Q.jsxs)(`p`,{role:`status`,className:`text-sm`,children:[`Storage policy saved. `,N,` documents and `,P,` folders planned. Replication continues in the background.`]}),ne>0&&(0,Q.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[ne,` document operations failed. Check operation status in Storage policies settings.`]}),j&&(0,Q.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[T?`The policy is saved. `:``,j]})]}),(0,Q.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2 border-t p-3`,children:[(0,Q.jsx)(K,{variant:`ghost`,disabled:D,onClick:ie,children:`Cancel`}),k?(0,Q.jsx)(K,{onClick:r,children:`Done`}):(0,Q.jsx)(K,{disabled:D||!ue,onClick:le,children:D?`Applying…`:T?`Retry existing documents`:a?`Save policy`:`Enable policy`})]})]})})}var vl={policies:[],revision:``,loading:!1,error:``},yl=new Map,bl=new Set;function xl(){for(let e of bl)e()}function Sl(e){return bl.add(e),()=>{bl.delete(e)}}function Cl(e,t){yl.set(e,t),xl()}async function wl(e){Cl(e,{...yl.get(e)??vl,loading:!0,error:``});try{let{policies:t,revision:n,status:r}=await sl(e);Cl(e,{policies:t,revision:n,status:r,loading:!1,error:``})}catch(t){Cl(e,{policies:[],revision:``,loading:!1,error:t instanceof Error?t.message:`Could not load storage policies`})}}function Tl(e){yl.delete(e),xl()}function El(e){let t=(0,Z.useSyncExternalStore)(Sl,()=>e&&yl.get(e)||vl),n=!!e&&!yl.has(e);(0,Z.useEffect)(()=>{e&&n&&wl(e)},[e,n]);let r=(0,Z.useCallback)(async()=>{e&&await wl(e)},[e]);return(0,Z.useEffect)(()=>{if(!e||!t.policies.length)return;let n=window.setInterval(()=>{!document.hidden&&!yl.get(e)?.loading&&wl(e)},5e3);return()=>window.clearInterval(n)},[e,t.policies.length]),{policies:t.policies,revision:t.revision,status:t.status,loading:t.loading,error:t.error,refresh:r}}async function Dl(){return await Y.get(`${J}/users/me/config/webui`)??{}}async function Ol(e){return await Y.put(`${J}/users/me/config/webui`,e)??e}var kl=`application/x-canvas-workspace-pin`;function Al({pins:e,isLoading:t,searchQuery:n=``,activeKey:r,onOpen:a,onShowInTree:o,onUnpin:s,onMove:c}){let[l,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)(null),p=n.toLowerCase().trim(),m=p?e.filter(e=>(e.label||e.name||``).toLowerCase().includes(p)||e.path.toLowerCase().includes(p)||(e.description||``).toLowerCase().includes(p)):e,h=()=>{u(null),f(null)},g=async()=>{let t=d,n=l;if(h(),!n||!t||t.id===n)return;let r=t.id;if(t.id&&!t.before&&(r=e[e.findIndex(e=>e.id===t.id)+1]?.id??null),r!==n)try{await c(n,r)}catch(e){alert(e instanceof Error?e.message:String(e))}};return t&&!e.length?(0,Q.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading pins…`}):e.length?m.length?(0,Q.jsx)(`div`,{className:`p-2 flex flex-col gap-2`,onDragOver:e=>{l&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`)},onDrop:e=>{e.preventDefault(),l&&!d&&f({id:null,before:!1}),g()},children:m.map(e=>{let t=e.resolvable===!1,n=Si(e.color),c=e.icon||(e.type===`canvas`?`ph:squares-four-fill`:`ph:folder-fill`),m=r===hr(e.tree,e.path),_=d?.id===e.id&&d.before,v=d?.id===e.id&&!d.before;return(0,Q.jsxs)(`div`,{role:`button`,tabIndex:0,"data-active":m||void 0,draggable:!p,onDragStart:t=>{t.dataTransfer.setData(kl,e.id),t.dataTransfer.setData(`text/plain`,e.path),t.dataTransfer.effectAllowed=`move`,u(e.id)},onDragEnd:h,onDragOver:t=>{if(!l||l===e.id)return;t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=`move`;let n=t.currentTarget.getBoundingClientRect(),r=t.clientY<n.top+n.height/2;f(t=>t?.id===e.id&&t.before===r?t:{id:e.id,before:r})},onDrop:e=>{e.preventDefault(),e.stopPropagation(),g()},onClick:()=>{t||a(e)},onKeyDown:n=>{n.target===n.currentTarget&&(n.key===`Enter`||n.key===` `)&&!t&&(n.preventDefault(),a(e))},title:t?`${e.path} — folder no longer exists`:`Open ${e.tree}:${e.path}`,className:G(`group relative flex items-stretch gap-2.5 rounded-(--card-radius) border bg-card shadow-elevation-1 text-left transition-colors`,t?`opacity-70 cursor-default`:`cursor-pointer hover:bg-accent/40`,m&&`ring-1 ring-primary/60`,l===e.id&&`opacity-40`,_&&`border-t-2 border-t-primary`,v&&`border-b-2 border-b-primary`),style:{borderLeft:`5px solid ${n??`transparent`}`},children:[(0,Q.jsx)(`div`,{className:`flex items-center justify-center w-12 shrink-0 rounded-l-[5px] my-0 self-stretch`,style:n?{backgroundColor:`${n}22`}:void 0,children:t?(0,Q.jsx)(R,{className:`w-5 h-5 text-warning`}):(0,Q.jsx)(i,{icon:c,width:22,height:22,color:n,className:G(!n&&(e.type===`canvas`?`text-primary`:`text-muted-foreground`))})}),(0,Q.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1 py-2 pr-1`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5 min-w-0`,children:[(0,Q.jsx)(`span`,{className:`text-sm font-semibold leading-tight truncate`,children:e.label||e.name||e.path.split(`/`).pop()}),e.locked&&(0,Q.jsx)(Ft,{className:`w-3 h-3 shrink-0 text-warning`})]}),(0,Q.jsxs)(`span`,{className:`text-[11px] text-muted-foreground truncate leading-tight font-mono mt-0.5`,children:[e.tree,`:`,e.path]}),e.description&&(0,Q.jsx)(`span`,{className:`text-[11px] text-muted-foreground/80 truncate leading-tight mt-1`,children:e.description}),t&&(0,Q.jsx)(`span`,{className:`text-[11px] text-warning leading-tight mt-1`,children:`Folder no longer exists`})]}),(0,Q.jsxs)(`div`,{className:`flex flex-col items-center justify-between py-1.5 pr-1.5 shrink-0`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,Q.jsx)(`button`,{type:`button`,disabled:t,onClick:t=>{t.stopPropagation(),o(e)},title:`Show in tree`,"aria-label":`Show in tree`,className:`flex items-center justify-center w-6 h-6 rounded text-muted-foreground reveal-on-hover focus-visible:opacity-100 hover:bg-accent hover:text-foreground transition-colors disabled:opacity-40 disabled:cursor-default`,children:(0,Q.jsx)(Ot,{className:`w-3.5 h-3.5`})}),(0,Q.jsx)(`button`,{type:`button`,onClick:async t=>{t.stopPropagation();try{await s(e)}catch(e){alert(e instanceof Error?e.message:String(e))}},title:`Unpin`,"aria-label":`Unpin`,className:`flex items-center justify-center w-6 h-6 rounded text-muted-foreground reveal-on-hover hover:bg-destructive/10 hover:text-destructive transition-colors`,children:(0,Q.jsx)(W,{className:`w-3.5 h-3.5`})})]}),!p&&(0,Q.jsx)(I,{className:`w-3.5 h-3.5 text-muted-foreground/50 cursor-grab active:cursor-grabbing`,"aria-hidden":!0})]})]},e.id)})}):(0,Q.jsxs)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:[`No pins match “`,n,`”`]}):(0,Q.jsxs)(`div`,{className:`px-3 py-6 text-xs text-muted-foreground text-center space-y-1`,children:[(0,Q.jsx)(`p`,{children:`No pinned folders yet.`}),(0,Q.jsxs)(`p`,{className:`text-muted-foreground/70`,children:[`Right-click a folder in the context, directory or backends tree and choose `,(0,Q.jsx)(`span`,{className:`font-medium`,children:`Pin`}),`.`]})]})}var jl=()=>({selectedPath:`/`,contentPath:null,searchQuery:``,expansion:new Map}),Ml=[`pins`,`context`,`layers`,`directory`,`backends`],Nl=e=>typeof e==`string`&&Ml.includes(e),Pl=e=>{let t=Array.isArray(e)?e.filter(Nl).filter((e,t,n)=>n.indexOf(e)===t):[];return[...t,...Ml.filter(e=>!t.includes(e))]},Fl={pins:(0,Q.jsx)(V,{className:`w-3.5 h-3.5`}),context:(0,Q.jsx)(Ne,{className:`w-3.5 h-3.5`}),layers:(0,Q.jsx)(xe,{className:`w-3.5 h-3.5`}),directory:(0,Q.jsx)(Ot,{className:`w-3.5 h-3.5`}),backends:(0,Q.jsx)(Je,{className:`w-3.5 h-3.5`})},Il={pins:`Pins`,context:`Context tree`,layers:`Context layers`,directory:`Directory tree`,backends:`Backends tree`},Ll=e=>e===`directory`||e===`backends`?e:Gn,Rl=(e,t)=>t?`layers`:e===`directory`?`directory`:e===`backends`?`backends`:`context`;function zl(){let{state:e}=la();return e.selectedEntityId?(0,Q.jsx)(xa,{workspaceName:e.selectedEntityId,children:(0,Q.jsx)(Bl,{},e.selectedEntityId)}):null}function Bl(){let{state:e,closeM2:t,openM2:n,navigateFromMenu:r}=la(),i=xr(),a=Fr(),o=e.selectedEntityId,s=m(),c=h(),{treeName:l,path:u}=ra(c.pathname),d=new URLSearchParams(c.search).get(`layer`)===`1`,f=new URLSearchParams(c.search).get(`layerId`),p=/\/trees\/|\/path(\/|$)/.test(c.pathname)||!!f,g=p?Rl(l,f):Ml[0],[_,v]=(0,Z.useState)(!1),[y,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)(null),[C,w]=(0,Z.useState)({icon:null,color:null}),[T,E]=(0,Z.useState)(g),[D,O]=(0,Z.useState)(null),[k,A]=(0,Z.useState)(null),[j,M]=(0,Z.useState)(null),[N,ee]=(0,Z.useState)([]),[P,te]=(0,Z.useState)(!1),[ne,re]=(0,Z.useState)(!1),[ie,F]=(0,Z.useState)(!1),[ae,oe]=(0,Z.useState)(!1),[I,se]=(0,Z.useState)(u),[ce,le]=(0,Z.useState)([]),[ue,L]=(0,Z.useState)(new Set),[R,de]=(0,Z.useState)(d&&u!==`/`?u:null),[z,B]=(0,Z.useState)(``),[V,fe]=(0,Z.useState)(null),[H,pe]=(0,Z.useState)(null),[me,he]=(0,Z.useState)(null),{policies:ge,refresh:_e}=El(o),ve=(0,Z.useCallback)(e=>{if(T!==`context`&&T!==`directory`||!ge.length)return null;let t=fl(ge,T,e);return t.length?`Storage policy targets: ${pl(t)} (see Settings for transfer status)`:null},[T,ge]),[U,ye]=(0,Z.useState)([]),[W,be]=(0,Z.useState)(!1),[xe,Se]=(0,Z.useState)(!1),Ce=(0,Z.useRef)(null),we=(0,Z.useRef)(new Map),[Te,Ee]=(0,Z.useState)(()=>Object.fromEntries(Ml.map(e=>[e,jl()])));(0,Z.useLayoutEffect)(()=>{Ce.current&&(Ce.current.scrollTop=we.current.get(T)??0)},[T]);let De=Te[T];(De.selectedPath!==I||De.contentPath!==R||De.searchQuery!==z)&&Ee({...Te,[T]:{...De,selectedPath:I,contentPath:R,searchQuery:z}});let Oe=(0,Z.useRef)(!1),[ke,Ae]=(0,Z.useState)(!1),[je,Me]=(0,Z.useState)(Ml),Ne=!p;(0,Z.useEffect)(()=>{let e=!1;return Dl().then(t=>{if(e)return;let n=Pl(t?.m2?.tabOrder);Me(n),Ne&&E(e=>e===Ml[0]?n[0]:e)}).catch(()=>{}),()=>{e=!0}},[]);let Pe=(0,Z.useCallback)(async e=>{let t=je;Me(e);try{let t=await Dl();await Ol({...t,m2:{...t.m2,tabOrder:e}})}catch{Me(t)}},[je]),[Fe,Ie]=(0,Z.useState)(null),[Le,Re]=(0,Z.useState)(null),ze=()=>{Ie(null),Re(null)},Be=()=>{if(Fe&&Le&&Fe!==Le.id){let e=je.filter(e=>e!==Fe),t=e.indexOf(Le.id);t>=0&&(e.splice(Le.before?t:t+1,0,Fe),e.some((e,t)=>e!==je[t])&&Pe(e))}ze()};(0,Z.useEffect)(()=>{let e=e=>fe(e.detail??null);return window.addEventListener(`documents:clipboard`,e),()=>window.removeEventListener(`documents:clipboard`,e)},[]);let[Ve,He]=(0,Z.useState)(u);u!==Ve&&(He(u),se(u));let Ue=(0,Z.useRef)(new Map),We=(0,Z.useCallback)(async(e,t,n=!1,r=!1)=>{let i=Symbol();Ue.current.set(t,i);let a=()=>Ue.current.get(t)===i,o=t===`context`?te:t===`directory`?re:F,s=t===`context`?O:t===`directory`?A:M;n||o(!0);try{n&&!r&&ar(e,t);let i=await In(e,t);a()&&s(i)}catch{}finally{a()&&o(!1)}},[]),Ge=(0,Z.useCallback)(async(e,t=!1)=>{let n=Symbol();Ue.current.set(`pins`,n);let r=()=>Ue.current.get(`pins`)===n;t||be(!0);try{let t=await Pn(e);r()&&ye(t)}catch{}finally{r()&&be(!1)}},[]),Ke=(0,Z.useCallback)(async(e,t=!1)=>{let n=Symbol();Ue.current.set(`layers`,n);let r=()=>Ue.current.get(`layers`)===n;t||oe(!0);try{let t=await qn(e,`context`);r()&&ee(t)}catch{}finally{r()&&oe(!1)}},[]);(0,Z.useEffect)(()=>{if(!o)return;let e=o,t=!1,n=Ue.current;async function r(){Un(e).then(e=>{t||(b(e.label||e.name),v(Ji(e)),S(e.id||null),w({icon:e.icon??null,color:e.color??null}))}).catch(()=>{}),await Promise.all([We(e,`context`),We(e,`directory`),We(e,`backends`),Ke(e),Ge(e)])}return r(),()=>{t=!0,n.clear()}},[o,We,Ke,Ge]);let qe=(0,Z.useCallback)((e,t,n=!1)=>{for(let r of[`context`,`directory`,`backends`])(!t||t===r)&&We(e,r,!0,n);(!t||t===`context`)&&Ke(e,!0),Ge(e,!0)},[We,Ke,Ge]),Je=(0,Z.useCallback)(()=>{o&&qe(o)},[o,qe]);(0,Z.useEffect)(()=>{if(!o)return;let e=e=>{e.detail?.workspaceName&&e.detail.workspaceName!==o||qe(o,e.detail?.treeName,e.detail?.cacheInvalidated)};return window.addEventListener(`workspace:tree:refresh`,e),()=>window.removeEventListener(`workspace:tree:refresh`,e)},[o,qe]),(0,Z.useEffect)(()=>{if(!o)return;let e=!1,t=()=>gr(o).then(t=>{e||(le(t),L(new Set(t.filter(e=>e.resyncing&&e.treePath).map(e=>e.treePath))))}).catch(()=>{});t();let n=e=>{let n=e.detail;n?.workspaceName&&n.workspaceName!==o||(!n?.treeName||n.treeName===`backends`)&&t()};return window.addEventListener(`workspace:tree:refresh`,n),()=>{e=!0,window.removeEventListener(`workspace:tree:refresh`,n)}},[o]),(0,Z.useEffect)(()=>{if(!o)return;let e=[`workspace:${o}`,x?`workspace:${x}`:null].filter(Boolean),t=()=>e.forEach(e=>X.emit(`subscribe`,{channel:e})),n=X.on(`connect`,t);t();let r=Or(o,x),i=e=>{if(e?.workspaceId&&x&&e.workspaceId!==x)return;let t=e?.treePath;t&&L(n=>{let r=new Set(n);return e.resyncing?r.add(t):r.delete(t),r})};X.on(`backend.resync.changed`,i);let a=e=>{e?.workspaceId&&x&&e.workspaceId!==x||Ge(o,!0)};return X.on(`pins.changed`,a),()=>{r(),n?.(),X.off(`backend.resync.changed`,i),X.off(`pins.changed`,a)}},[o,x,Ge]);let[Ye,Xe]=(0,Z.useState)(null),Ze=`${c.pathname}|${c.search}`;if(Ze!==Ye){Xe(Ze);let{treeName:e,path:t}=ra(c.pathname),n=new URLSearchParams(c.search).get(`layerId`),r=/\/trees\/|\/path(\/|$)/.test(c.pathname)||!!n;xe?Se(!1):E(r||ke?r?Rl(e,n):T:je[0]),se(t),de(t===`/`?null:t)}let{showProgress:Qe}=xn();(0,Z.useEffect)(()=>{o&&Ui(Qe,o)},[o,Qe]);let $e=Ar({workspaceId:o??void 0,treeName:Ll(T),onRefresh:Je}),et=(0,Z.useRef)(new Map);(0,Z.useEffect)(()=>{if(!o)return;let e=`${o}:${T}:${I}`,t=$e;t.canResyncBackend(I)&&(Date.now()-(et.current.get(e)||0)<6e4||(et.current.set(e,Date.now()),t.onResyncBackend?.(I).catch(()=>{})))},[o,T,I,$e]);let tt=new Set(U.map(e=>hr(e.tree,e.path))),nt=Ll(T),rt=(0,Z.useCallback)(e=>tt.has(hr(nt,e)),[U,nt]),it=(0,Z.useCallback)(async e=>{if(!o)return;let t=U.find(t=>hr(t.tree,t.path)===hr(nt,e));t?await ir(o,t.id):await An(o,e,nt),await Ge(o)},[o,U,nt,Ge]),at=(0,Z.useCallback)(async e=>{if(o){ye(t=>t.filter(t=>t.id!==e.id));try{await ir(o,e.id)}finally{await Ge(o)}}},[o,Ge]),ot=(0,Z.useCallback)(async(e,t)=>{if(!o)return;let n=U.find(t=>t.id===e);if(!n)return;let r=U.filter(t=>t.id!==e),i=t===null?r.length:r.findIndex(e=>e.id===t);if(i===-1)return;let a=[...r.slice(0,i),n,...r.slice(i)];if(!a.every((e,t)=>e===U[t])){ye(a);try{ye(await Xn(o,a.map(e=>e.id)))}catch(e){throw await Ge(o),e}}},[o,U,Ge]),st=(0,Z.useCallback)(e=>{if(!o)return;Se(!0),se(e.path),de(null);let t=ia(o,e.path,e.tree);if(i){i.activateRow(`pin:${o}:${e.id}`,e.label||e.name||e.path,t);return}r(t)},[o,r,i]),ct=(0,Z.useCallback)(e=>{!o||e.resolvable===!1||(Se(!1),Ae(!0),E(Rl(e.tree)),se(e.path),de(null),B(``),Oe.current=!0,i?.setFocus(`main`),r(ia(o,e.path,e.tree)))},[o,r,i]),lt=T===`context`?D:T===`directory`?k:T===`backends`?j:null,ut=T===`context`?P:T===`directory`?ne:T===`backends`&&ie;(0,Z.useEffect)(()=>{if(!Oe.current||ut||T===`pins`)return;let e=Ce.current?.querySelector(`[data-active="true"]`);e&&(e.scrollIntoView({block:`nearest`,inline:`nearest`}),Oe.current=!1)},[T,I,lt,ut]);let dt=(0,Z.useCallback)(e=>{Ae(!0),E(e);let t=Te[e];se(t.selectedPath),de(t.contentPath),B(t.searchQuery)},[Te]),ft=(0,Z.useCallback)(e=>{dt(Kc(je,T,e))},[je,T,dt]),mt=Jc(e.m2Open,ft),ht=e=>{de(null),se(e);let t=Ll(T);i?.setFocus(`main`),r(ia(o,e,t))},gt=(0,Z.useCallback)((e,t)=>{se(e),de(e);let n=Ll(T),a=new URLSearchParams;a.set(`layer`,`1`),t&&a.set(`layerId`,t),i?.setFocus(`main`),r(`${ia(o,e,n)}?${a.toString()}`)},[o,T,r,i]),_t=(0,Z.useCallback)((e,t)=>{if(o){if(i){i.openCanvas({kind:`route`,location:ia(o,e,t)});return}window.dispatchEvent(new CustomEvent(`workspace:open-to-side`,{detail:{workspaceName:o,treeName:t,path:e}}))}},[o,i]),vt=(0,Z.useCallback)(async e=>{if(!o)return;let t=Ll(T),n=await Zn(o,e,t),r=`${window.location.origin}${n.url}`;await navigator.clipboard?.writeText(r),alert(`Canvas share link copied:\n${r}`)},[o,T]),yt=z.toLowerCase().trim(),bt=yt?N.filter(e=>e.name.toLowerCase().includes(yt)||(e.label||``).toLowerCase().includes(yt)||(e.description||``).toLowerCase().includes(yt)):N;return(0,Q.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Q.jsx)(Zs,{title:y||o||`Workspace`,icon:C.icon||`ph:stack-fill`,accentColor:C.color,onBack:t,action:(0,Q.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,Q.jsx)(`button`,{type:`button`,onClick:()=>o&&r(va(o)),className:`flex items-center justify-center w-8 h-8 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Open workspace`,children:(0,Q.jsx)(St,{className:`w-3.5 h-3.5`})}),(0,Q.jsx)(`button`,{type:`button`,disabled:!_,onClick:()=>{a?n(`settings`,o??null):s(`/workspaces/${o}/settings/general`)},className:`flex items-center justify-center w-8 h-8 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors disabled:opacity-40 disabled:cursor-not-allowed`,title:_?`Settings`:`Workspace settings require admin access`,children:(0,Q.jsx)(pt,{className:`w-3.5 h-3.5`})})]})}),(0,Q.jsx)(`div`,{...mt,className:`flex border-b border-border shrink-0 touch-pan-y`,"aria-label":`Workspace trees`,children:je.map(e=>(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>dt(e),title:`${Il[e]} — drag to reorder; the first tab opens by default`,"aria-label":Il[e],"aria-pressed":T===e,draggable:!0,onDragStart:t=>{t.dataTransfer.setData(`text/plain`,e),t.dataTransfer.effectAllowed=`move`,Ie(e)},onDragEnd:ze,onDragOver:t=>{if(!Fe||Fe===e)return;t.preventDefault(),t.dataTransfer.dropEffect=`move`;let n=t.currentTarget.getBoundingClientRect(),r=t.clientX<n.left+n.width/2;Re(t=>t?.id===e&&t.before===r?t:{id:e,before:r})},onDrop:e=>{e.preventDefault(),Be()},className:G(`relative flex-1 flex items-center justify-center py-2 transition-colors`,T===e?`text-foreground border-b-2 border-foreground -mb-px`:`text-muted-foreground hover:text-foreground`,Fe===e&&`opacity-40`,Le?.id===e&&Le.before&&`shadow-[inset_2px_0_0_0_hsl(var(--primary))]`,Le?.id===e&&!Le.before&&`shadow-[inset_-2px_0_0_0_hsl(var(--primary))]`),children:[Fl[e],e===`pins`&&U.length>0&&(0,Q.jsx)(`span`,{className:`absolute top-1 right-[calc(50%-14px)] min-w-[14px] h-[14px] px-0.5 rounded-full bg-primary text-primary-foreground text-[9px] leading-[14px] text-center font-medium`,children:U.length})]},e))}),(0,Q.jsx)(`div`,{className:`px-2 py-1.5 border-b border-border shrink-0 shadow-elevation-2 z-10`,children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5 rounded-md border bg-muted/40 px-2 py-1`,children:[(0,Q.jsx)(Jt,{className:`w-3 h-3 shrink-0 text-muted-foreground`}),(0,Q.jsx)(`input`,{type:`search`,name:`workspace-tree-filter`,"aria-label":`Search workspace tree`,autoComplete:`off`,"data-lpignore":`true`,"data-1p-ignore":`true`,className:`flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground min-w-0`,placeholder:T===`layers`?`Search layers…`:T===`pins`?`Search pins…`:`Search paths…`,value:z,onChange:e=>B(e.target.value)})]})}),(0,Q.jsx)(`div`,{ref:Ce,onScroll:e=>{we.current.set(T,e.currentTarget.scrollTop)},className:`flex-1 overflow-y-auto`,children:(0,Q.jsx)(ba,{workspaceId:o,treeName:Ll(T),readOnly:!_,className:`min-h-full`,children:T===`pins`?(0,Q.jsx)(Al,{pins:U,isLoading:W,searchQuery:z,activeKey:hr(l,u),onOpen:st,onShowInTree:ct,onUnpin:at,onMove:ot}):T===`layers`?(0,Q.jsx)(ql,{layers:bt,isLoading:ae,wsName:o??``,onSelect:e=>{let t=new URLSearchParams;t.set(`layerId`,e.id),t.set(`layer`,`1`),r(`${ia(o,`/`)}?${t.toString()}`)},onLock:async e=>{await Hn(o,e.id,o,`context`),qe(o)},onUnlock:async e=>{await cr(o,e.id,o,`context`),qe(o)},onRename:async(e,t)=>{await Yn(o,e.id,t,`context`),qe(o)},onDestroy:async e=>{confirm(`Destroy layer "${e.label||e.name}"? This cannot be undone.`)&&(await zn(o,e.id,`context`),qe(o))}}):(0,Q.jsx)(Tc,{expansionState:Te[T].expansion,root:lt,workspaceId:o??void 0,treeName:T,isBackendsTree:T===`backends`,onRestoreTrash:o?e=>Gi(o,e):void 0,onDiscardTrash:o?e=>Wi(o,e):void 0,onAltSelect:i?e=>_t(e,Ll(T)):void 0,selectedPath:I,contentPath:R,onSelect:ht,onShowContent:T===`context`?gt:void 0,onOpenToSide:_t,onShareCanvas:vt,onNewCanvas:o&&T!==`backends`?e=>{s(`${ia(o,e,T)}?createCanvas=1`)}:void 0,isLoading:ut,rootLabel:o??void 0,searchQuery:z,backends:ce,resyncingPaths:T===`backends`?ue:void 0,onAddRule:o&&T===`backends`?pe:void 0,onAddStoreRule:o?(e,t=`store`)=>{let n=T===`backends`?(()=>{let n=Bi(e);return{kind:t,storeTo:n?.backend||``,storeFolder:n?.rel||``}})():{kind:t,path:`${T===`directory`?`dir`:`ctx`}:${e}`,storeFolder:t===`download`?`Downloads`:zi(e)};s(`/workspaces/${o}/settings/hooks?${qi(n).toString()}`)}:void 0,onStoragePolicy:o&&(T===`context`||T===`directory`)?e=>he(rl(T,e)):void 0,policyBadgeFor:ve,pastedDocumentIds:V?.documentIds,isPathPinned:rt,onTogglePin:o?it:void 0,onPasteDocuments:o&&T===`backends`?async(e,t)=>{let n=sr(e);if(!n)return!1;let r=e.split(`/`).filter(Boolean).slice(2).join(`/`),i=Qe({title:`Moving…`,description:`${t.length} message(s) → ${r}`});try{let{moved:a,results:s}=await Ln(o,n.address,t,e),c=s.filter(e=>!e.ok);return c.length?i.fail({title:`${c.length} message(s) not moved`,description:c[0].error||`Move failed`,variant:`destructive`}):i.done({title:`Moved`,description:`${a} message(s) → ${r}`}),V&&a&&(fe(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}))),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:o,path:`/imap/${n.address}`,treeName:`backends`}})),a>0}catch(e){return i.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to move messages`,variant:`destructive`}),!1}}:o?async(e,t)=>{let n=Mn(T),r=T===`directory`?`directory`:Gn,i=Qe({title:`Pasting…`,description:`${t.length} document(s) → "${e}"`}),a=!1;try{a=await _r(o,e,t,r,n)}catch(e){return i.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}return i.done(a?{title:`Success`,description:`${t.length} document(s) pasted to "${e}"`}:void 0),a&&(V&&(fe(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}))),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:o,path:e,treeName:r}}))),a}:void 0,...$e},T)})}),H&&o&&(0,Q.jsx)(Qc,{workspaceId:o,sourcePath:H,onClose:()=>pe(null),onManageRules:()=>{pe(null),s(`/workspaces/${o}/settings/hooks?section=rules`)}}),me&&o&&(0,Q.jsx)(_l,{workspaceId:o,path:me,onClose:()=>he(null),onSaved:()=>{_e()}})]})}var Vl={canvas:{label:`Canvases`,order:0},dataset:{label:`Datasets`,order:1},context:{label:`Context layers`,order:2},workspace:{label:`Workspaces`,order:3},universe:{label:`Universe`,order:4},label:{label:`Labels`,order:5},system:{label:`System`,order:6}},Hl=100,Ul=e=>e&&e.charAt(0).toUpperCase()+e.slice(1),Wl=e=>Vl[e]??{label:`${Ul(e)} layers`,order:Hl};function Gl({type:e}){return e===`canvas`?(0,Q.jsx)(qe,{className:`w-3.5 h-3.5 shrink-0 text-primary`,"aria-label":`Canvas`}):e===`dataset`?(0,Q.jsx)(Je,{className:`w-3.5 h-3.5 shrink-0 text-secondary`,"aria-label":`Dataset`}):(0,Q.jsx)(xe,{className:`w-3.5 h-3.5 shrink-0 text-muted-foreground/60`,"aria-label":`Layer`})}function Kl(e){let t=new Map;for(let n of e){let e=n.type||`context`,r=t.get(e);r?r.push(n):t.set(e,[n])}return[...t.entries()].map(([e,t])=>({type:e,items:t,meta:Wl(e)})).sort((e,t)=>e.meta.order-t.meta.order||e.meta.label.localeCompare(t.meta.label)).map(({type:e,items:t,meta:n})=>({type:e,label:n.label,items:t}))}function ql({layers:e,isLoading:t,onSelect:n,onLock:r,onUnlock:i,onRename:a,onDestroy:o}){let[s,c]=(0,Z.useState)(null),l=(0,Z.useRef)(null);if((0,Z.useEffect)(()=>{s&&l.current?.focus()},[s]),t)return(0,Q.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading layers…`});if(!e.length)return(0,Q.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`No layers found`});let u=async(e,t)=>{e.stopPropagation();try{await t()}catch(e){alert(e instanceof Error?e.message:String(e))}},d=async(e,t)=>{c(null);let n=t.trim();if(!(!n||n===e.name))try{await a(e,n)}catch(e){alert(e instanceof Error?e.message:String(e))}},f=Kl(e);return(0,Q.jsx)(`div`,{className:`px-2 py-1.5 space-y-2`,children:f.map(e=>(0,Q.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,Q.jsxs)(`div`,{className:`px-1 pt-1 pb-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground`,children:[e.label,(0,Q.jsxs)(`span`,{className:`ml-1 text-muted-foreground/60`,children:[`(`,e.items.length,`)`]})]}),e.items.map(e=>(0,Q.jsxs)(`div`,{className:`group flex items-center gap-2 rounded-l-md px-2 py-1.5 text-xs bg-card shadow-elevation-1 cursor-pointer hover:bg-accent/40 transition-colors`,style:{borderRight:e.color?`4px solid ${e.color}`:`4px solid transparent`},onClick:()=>s!==e.id&&n(e),children:[(0,Q.jsx)(`div`,{className:G(`w-2 h-2 rounded-full shrink-0`,!e.color&&`bg-muted-foreground/20`),style:e.color?{backgroundColor:e.color}:void 0}),(0,Q.jsx)(Gl,{type:e.type}),s===e.id?(0,Q.jsx)(`input`,{ref:l,defaultValue:e.label||e.name,className:`flex-1 bg-transparent outline-none min-w-0 font-medium border-b border-primary`,onClick:e=>e.stopPropagation(),onKeyDown:t=>{t.key===`Enter`&&d(e,t.target.value),t.key===`Escape`&&c(null)},onBlur:t=>d(e,t.target.value)}):(0,Q.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:e.label||e.name}),e.locked&&s!==e.id&&(0,Q.jsx)(Ft,{className:`w-2.5 h-2.5 shrink-0 text-warning group-hover:hidden`}),s!==e.id&&(0,Q.jsxs)(`div`,{className:`flex items-center gap-0.5 reveal-on-hover`,children:[e.locked?(0,Q.jsx)(`button`,{type:`button`,title:`Unlock layer`,className:`p-0.5 rounded hover:bg-muted-foreground/10 text-warning hover:text-foreground touch-target`,onClick:t=>u(t,()=>i(e)),children:(0,Q.jsx)($e,{className:`w-3 h-3`})}):(0,Q.jsx)(`button`,{type:`button`,title:`Lock layer`,className:`p-0.5 rounded hover:bg-muted-foreground/10 text-muted-foreground hover:text-foreground touch-target`,onClick:t=>u(t,()=>r(e)),children:(0,Q.jsx)(Ft,{className:`w-3 h-3`})}),!e.locked&&(0,Q.jsx)(`button`,{type:`button`,title:`Rename layer`,className:`p-0.5 rounded hover:bg-muted-foreground/10 text-muted-foreground hover:text-foreground touch-target`,onClick:t=>{t.stopPropagation(),c(e.id)},children:(0,Q.jsx)(je,{className:`w-3 h-3`})}),!e.locked&&(0,Q.jsx)(`button`,{type:`button`,title:`Destroy layer`,className:`p-0.5 rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive touch-target`,onClick:t=>u(t,()=>o(e)),children:(0,Q.jsx)(Fe,{className:`w-3 h-3`})})]})]},e.id))]},e.type))})}function Jl(){let{state:e,closeM2:t}=la(),n=Fr(),r=m(),i=h(),a=e.selectedEntityId,[o,s]=(0,Z.useState)(null),c=o?.address===a?o.workspace:null,l=c?.label||c?.name,u=Ji(c);(0,Z.useEffect)(()=>{if(!a)return;let e=!1;return Un(a).then(t=>{e||s({address:a,workspace:t})}).catch(()=>{}),()=>{e=!0}},[a]);let d=i.pathname.split(`/`).filter(Boolean),f=d[2]===`settings`?Ac(d[3]):null,p=(0,Z.useMemo)(()=>Oc.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,Q.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,Q.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Q.jsx)(Zs,{title:`Settings: ${l||a||`Workspace`}`,icon:c?.icon||`ph:stack-fill`,accentColor:c?.color,onBack:()=>{n||!a?t():r(`/workspaces/${a}`)},action:(0,Q.jsx)(`button`,{type:`button`,onClick:()=>a&&r(`/workspaces/${a}`),className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground`,title:`Open workspace`,children:(0,Q.jsx)(St,{className:`h-3.5 w-3.5`})})}),u?(0,Q.jsx)(Dc,{items:p,activeId:f,onSelect:e=>a&&r(`/workspaces/${a}/settings/${e}`)}):(0,Q.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:c?`Workspace settings are available to owners and admins.`:`Loading workspace…`})]})}var Yl=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(`
6
+ `)}`)&&(async()=>{for(let t of e)await we(t,!0);fe(new Set)})().catch(e=>alert(e instanceof Error?e.message:String(e)))},children:`Remove folders…`}),(0,Q.jsx)(`button`,{type:`button`,className:`block w-full px-3 py-1.5 text-left text-xs hover:bg-accent`,onClick:()=>{fe(new Set),be(null)},children:`Clear selection`})]}):W&&(0,Q.jsx)(bc,{x:W.x,y:W.y,node:W.node,path:W.path,isBackendsTree:i,backends:z,isDirectoryTree:r===`directory`,onClose:()=>be(null),onShowContent:W.node.metadata?.backendTrash?l:v,onRestoreTrash:d?void 0:a,onDiscardTrash:d?void 0:o,onOpenToSide:y?e=>y(e,r):void 0,sourceLayer:_e,targetLayers:U,clipboard:he,onStartInlineCreate:e=>Le(e),onChangeIcon:le?()=>ct({clientX:W.x,clientY:W.y,stopPropagation:()=>{}},W.path,W.node):void 0,onNewCanvas:S,onShareCanvas:C,onImportDocuments:d?void 0:A,onExportDocuments:j,onExportSubtree:O,onImportSubtree:d?void 0:k,onRemove:!d&&w&&![...xe.keys()].some(e=>e===W.path||e.startsWith(W.path+`/`)||W.path.startsWith(e+`/`))?we:void 0,onRename:d?void 0:T,onLock:d?void 0:ee,onUnlock:d?void 0:P,onDestroy:d?void 0:te,onMerge:d?void 0:ne,onSubtract:d?void 0:re,onMergeDown:d?void 0:ie,onSubtractDown:d?void 0:F,canResyncBackend:oe,onResyncBackend:ae,onAddRule:f,onAddStoreRule:p,onStoragePolicy:!d&&!i?m:void 0,onRenameBackendFolder:se,onDeleteBackendFolder:!d&&ce&&![...xe.keys()].some(e=>e===W.path||e.startsWith(W.path+`/`)||W.path.startsWith(e+`/`))?e=>we(e,!0):void 0,onCopy:e=>mt(e,`copy`),onCut:e=>mt(e,`cut`),onPaste:dt,pastedDocumentIds:M,onPasteDocuments:N,isPinned:ue?ue(W.path):!1,onTogglePin:L?()=>L(W.path,W.node):void 0}),Te&&le&&(0,Q.jsx)(nc,{x:Te.x,y:Te.y,current:Oe.get(Te.path)??xi(Te.node),onChange:lt,onClose:()=>Ee(null)})]})}function Ec(){let{state:e,closeM2:t,closeM1:n,closeM0:r,openM2:i}=la(),a=Fr(),o=m(),s=e.selectedEntityId,{showToast:c}=xn(),[l,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)(null),[p,h]=(0,Z.useState)(``),[g,_]=(0,Z.useState)(),[v,y]=(0,Z.useState)(``),[b,x]=(0,Z.useState)(`/`),[S,C]=(0,Z.useState)(null),[w,T]=(0,Z.useState)(!1),[E,D]=(0,Z.useState)(null),[O,k]=(0,Z.useState)(!1),A=(0,Z.useCallback)(async e=>{T(!0);try{let t=await li(e);f(t),D(null)}catch(e){D(e instanceof Error?e.message:`Failed to load the tree`)}finally{T(!1)}},[]);(0,Z.useEffect)(()=>{if(!s)return;let e=s,t=!1;async function n(){try{let n=await si(e);if(t)return;u(n),h(n.url||``),_(void 0),y(``),C(null),x(n.path||`/`),T(!0);try{let n=await li(e);t||(f(n),D(null))}catch(e){t||D(e instanceof Error?e.message:`Failed to load the tree`)}finally{t||T(!1)}}catch{t||c({title:`Error`,description:`Failed to load context`,variant:`destructive`})}}n();let r=t=>{t.detail?.contextId===e&&n()};return window.addEventListener(`contexts:refresh`,r),()=>{t=!0,window.removeEventListener(`contexts:refresh`,r)}},[s,c]);let j=Ar({contextId:s??void 0,onRefresh:()=>{s&&A(s)}}),M=e=>{_(void 0),C(e),h(l?.workspaceName?`${l.workspaceName}://${e.replace(/^\//,``)}`:e)},N=l!=null&&(p.trim()!==(l.url||``)||g!==void 0);return(0,Q.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Q.jsx)(Zs,{title:s||`Context`,icon:l?.icon||`ph:stack-fill`,accentColor:l?.color,onBack:t,action:(0,Q.jsx)(`button`,{type:`button`,onClick:()=>{s&&(a?i(`settings`,s):o(`/contexts/${s}/settings/general`))},className:`flex items-center justify-center w-8 h-8 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Settings`,children:(0,Q.jsx)(pt,{className:`w-3.5 h-3.5`})})}),(0,Q.jsxs)(`div`,{className:`p-3 border-b border-border shrink-0`,children:[(0,Q.jsx)(`div`,{className:`text-[10px] text-muted-foreground mb-1.5 font-medium uppercase tracking-wide`,children:`Context URL`}),(0,Q.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Q.jsx)(Yi,{presentation:`breadcrumbs`,value:p,fixedWorkspaceName:l?.workspaceName,pickerTitle:`Switch context to…`,onPickTarget:(e,t)=>{h(`${t.workspaceName}://${e.replace(/^\/+/,``)}`),_(t.treeName),C(null)},onChange:e=>{h(e),C(g?null:`/`+e.replace(/^.*?:\/\//,``).replace(/^\/+/,``))},disabled:O,className:`min-w-0 flex-1`,inputClassName:G(`text-xs transition-colors`,N&&`border-warning/60 bg-warning/10`),placeholder:`workspace://path`}),(0,Q.jsx)(K,{size:`sm`,className:`h-9 px-2 text-xs shrink-0`,onClick:async()=>{if(!s)return;let e=s;k(!0);try{await ai(e,p,void 0,g);let t=await si(e);u(t),h(t.url||``),x(t.path||`/`),C(null),_(void 0),window.dispatchEvent(new CustomEvent(`contexts:refresh`)),await A(e),c({title:`Saved`,description:`Context URL updated`}),window.matchMedia(`(max-width: 767px)`).matches&&(n(),r())}catch(e){c({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{k(!1)}},disabled:O||!N,children:O?`…`:`Set`})]})]}),g&&(0,Q.jsxs)(`p`,{className:`px-3 py-1 text-xs text-muted-foreground`,children:[`Destination tree: `,g,` · press Set to apply`]}),(0,Q.jsx)(`div`,{className:`px-3 py-2 border-b shrink-0`,children:(0,Q.jsx)(en,{type:`search`,name:`context-tree-filter`,autoComplete:`off`,"data-lpignore":`true`,"data-1p-ignore":`true`,"aria-label":`Search context tree`,placeholder:`Search paths…`,value:v,onChange:e=>y(e.target.value),className:`h-7 text-xs`})}),(0,Q.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,children:[(0,Q.jsxs)(`div`,{className:`text-[10px] text-muted-foreground px-3 pt-2 pb-1 font-medium uppercase tracking-wide shrink-0`,children:[l?.workspaceName||`Workspace`,` · `,d?.type===`directory`?`directory`:`context`,` tree`]}),E&&!d&&(0,Q.jsx)(`p`,{className:`px-3 pb-1 text-xs text-destructive`,children:E}),(0,Q.jsx)(Tc,{root:d,workspaceId:l?.workspaceName,searchQuery:v,selectedPath:b,pendingPath:S,onSelect:M,isLoading:w,rootLabel:l?.workspaceName,...j})]})]})}function Dc({items:e,activeId:t,onSelect:n}){let[r,i]=(0,Z.useState)(``),a=e.filter(e=>ua(r,e.label,e.description||``));return(0,Q.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:(0,Q.jsxs)(`div`,{className:`space-y-1 px-2`,children:[(0,Q.jsx)(en,{type:`search`,name:`settings-section-filter`,autoComplete:`off`,"data-lpignore":`true`,"data-1p-ignore":`true`,"aria-label":`Search settings sections`,placeholder:`Find a setting…`,className:`mb-3`,value:r,onChange:e=>i(e.target.value)}),!a.length&&(0,Q.jsx)(`p`,{role:`status`,className:`p-3 text-sm text-muted-foreground`,children:`No matching settings.`}),a.map(e=>{let r=e.id===t;return(0,Q.jsxs)(`button`,{type:`button`,"aria-current":r?`page`:void 0,onClick:()=>n(e.id),className:G(`flex w-full items-center gap-2.5 rounded-md px-3 py-2 text-left transition-colors`,r?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50 hover:text-foreground`),children:[(0,Q.jsx)(`span`,{className:G(`shrink-0`,r?`text-foreground`:`text-muted-foreground`),children:e.icon}),(0,Q.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Q.jsx)(`span`,{className:`block text-sm font-medium text-foreground`,children:e.label}),e.description&&(0,Q.jsx)(`span`,{className:`mt-1 block text-xs leading-relaxed text-muted-foreground`,children:e.description})]}),(0,Q.jsx)(Ae,{className:G(`h-3.5 w-3.5 shrink-0`,r?`opacity-100`:`opacity-0`)})]},e.id)})]})})}var Oc=[{id:`general`,label:`Workspace details`,description:`Rename, change appearance or remove this workspace`,icon:ct},{id:`backups`,label:`Backups`,description:`Save or restore documents, relations and tree placements`,icon:ot},{id:`data`,label:`Files & storage`,description:`Connect folders and data sources, check disk usage or restore trash`,icon:j},{id:`db`,label:`Search & indexing`,description:`How documents become searchable: AI models, image descriptions, index repairs`,icon:Je},{id:`devices`,label:`Devices`,description:`Link devices to this workspace`,icon:Le},{id:`sync`,label:`Synchronization`,description:`Manage device copies and resolve sync conflicts`,icon:_t},{id:`services`,label:`Connected services`,description:`Configure Git, WebDAV, IMAP and other connectors`,icon:We},{id:`shares`,label:`Sharing & permissions`,description:`Create public links and manage workspace access`,icon:zt},{id:`policies`,label:`Storage policies`,description:`Mirror folders of the virtual tree to physical backends`,icon:de},{id:`hooks`,label:`Automation`,description:`Run hooks in response to workspace events`,icon:ke}],kc={embedding:`db`,trash:`data`};function Ac(e){return e?kc[e]?kc[e]:Oc.some(t=>t.id===e)?e:`general`:`general`}var jc=[{id:`general`,label:`Context details`,description:`Change the name, description or color, or remove this context`,icon:ct},{id:`location`,label:`Tree & path`,description:`Choose the workspace, tree and path this context opens`,icon:zt},{id:`shares`,label:`Sharing & permissions`,description:`Choose who can access this context`,icon:oe}];function Mc(e){return e&&jc.some(t=>t.id===e)?e:`general`}var Nc=[{id:`identity`,label:`Identity & instructions`,description:`Set the agent’s name, role and instructions`,icon:ct},{id:`provider`,label:`AI connection`,description:`Connect a chat model provider and manage its credentials`,icon:ie},{id:`models`,label:`Chat model`,description:`Choose the model and tune how it responds`,icon:Se},{id:`tools`,label:`Tools & skills`,description:`Choose the skills and MCP tools the agent can use`,icon:ye},{id:`access`,label:`Access & permissions`,description:`Choose which Canvas content the agent can access`,icon:te},{id:`memory`,label:`Memory`,description:`Configure how the agent remembers information`,icon:Be},{id:`integrations`,label:`Integrations`,description:`Connect mail, chat, databases and external APIs`,icon:D}];function Pc(e){return e&&Nc.some(t=>t.id===e)?e:`identity`}function Fc(){let{state:e,closeM2:t}=la(),n=Fr(),r=m(),i=h(),a=e.selectedEntityId,[o,s]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{if(!a)return;let e=!1;return si(a).then(t=>{e||s(t)}).catch(()=>{}),()=>{e=!0}},[a]);let c=i.pathname.split(`/`).filter(Boolean),l=c[2]===`settings`?Mc(c[3]):null,u=a?`/contexts/${a}`:null,d=(0,Z.useMemo)(()=>jc.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,Q.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,Q.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Q.jsx)(Zs,{title:`Settings: ${o?.name||a||`Context`}`,icon:o?.icon||`ph:stack-fill`,accentColor:o?.color??null,onBack:()=>u&&!n?r(u):t(),action:(0,Q.jsx)(`button`,{type:`button`,onClick:()=>u&&r(u),className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground`,title:`Open context`,children:(0,Q.jsx)(St,{className:`h-3.5 w-3.5`})})}),(0,Q.jsx)(Dc,{items:d,activeId:l,onSelect:e=>a&&r(`/contexts/${a}/settings/${e}`)})]})}function Ic(e){return e.isShared||e.type===`shared`?e.id:e.name}function Lc(e){let[t,n]=(0,Z.useState)([]),[r,i]=(0,Z.useState)(!1),a=(0,Z.useRef)(!1),o=(0,Z.useRef)(!1),s=(0,Z.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await Rn();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch workspaces:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,Z.useCallback)(()=>{a.current=!1,s()},[s]);return(0,Z.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,Z.useEffect)(()=>{if(!e)return;let t=()=>X.emit(`subscribe`,{channel:`workspace`}),r=()=>X.emit(`unsubscribe`,{channel:`workspace`}),i=X.on(`connect`,()=>{t(),s()});t();let a=e=>{let t=e,r=t?.workspaceId??t?.id,i=t?.status;!r||!i||n(e=>e.map(e=>e.id===r?{...e,status:i}:e))},o=e=>{let t=e?.workspace??e;t?.id&&n(e=>e.some(e=>e.id===t.id)?e:[...e,t])},c=e=>{let t=e,r=t?.workspaceId??t?.id;r&&n(e=>e.filter(e=>e.id!==r))},l=[[`workspaces.scanned`,e=>{let t=e?.report;t&&(t.discovered.length||t.adopted.length||t.updated.length||t.missing.length)&&s()}],[`workspace:status:changed`,a],[`workspace.status.changed`,a],[`workspace:created`,o],[`workspace.created`,o],[`workspace:deleted`,c],[`workspace.deleted`,c]];return l.forEach(([e,t])=>X.on(e,t)),()=>{r(),i?.(),l.forEach(([e,t])=>X.off(e,t))}},[e,s]),(0,Z.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`workspaces:refresh`,e),()=>{window.removeEventListener(`workspaces:refresh`,e)}},[s]),{workspaces:(0,Z.useMemo)(()=>Gs(t),[t]),isLoading:r,refresh:c}}function Rc({status:e}){return(0,Q.jsx)(`span`,{className:G(`inline-block w-2 h-2 rounded-full shrink-0`,e===`active`?`bg-success`:e===`error`?`bg-destructive`:`bg-muted-foreground`),title:e})}function zc(){let[e,t]=(0,Z.useState)(null),n=ms(),{state:r,selectEntity:a,openM2:o,closeM2:s}=la(),c=Fr(),{workspaces:l,isLoading:u}=Lc(r.activeSection===`workspaces`),{showToast:d}=xn(),f=m(),[p,h]=(0,Z.useState)(new Set),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(new Map),b=(0,Z.useRef)(new Map),[x,S]=(0,Z.useState)(null),C=x&&x.base===l?x.order:l,{rowProps:w,handleProps:T,draggingIndex:E,insertLineClass:D}=Js((e,t)=>{let n=Ks(C,e,t);S({base:l,order:n}),qs(n,(e,t)=>Qn(Ic(e),{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),e&&d({title:`Partial reorder`,description:`${e} workspace(s) could not be reordered`,variant:`destructive`})})}),O=e=>v.get(Ic(e))??{icon:e.icon??void 0,color:e.color??void 0},k=(e,t,n)=>{let r={...t,...n};y(t=>new Map(t).set(e,r));let i=b.current,a=i.get(e);a&&clearTimeout(a),i.set(e,setTimeout(()=>{i.delete(e);let t={icon:r.icon??null};r.color&&(t.color=r.color),Qn(e,t).then(()=>window.dispatchEvent(new CustomEvent(`workspaces:refresh`))).catch(e=>d({title:`Error`,description:e instanceof Error?e.message:`Update failed`,variant:`destructive`}))},350))},A=e=>{a(Ic(e)),o(`detail`,Ic(e)),!c&&ya(Ic(e))&&f(va(Ic(e)))},j=async(e,t)=>{e.stopPropagation(),h(e=>new Set(e).add(Ic(t)));try{await ur(Ic(t)),d({title:`Success`,description:`${t.label||t.name} started`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){d({title:`Error`,description:e instanceof Error?e.message:`Start failed`,variant:`destructive`})}finally{h(e=>{let n=new Set(e);return n.delete(Ic(t)),n})}},M=async(e,t)=>{e.stopPropagation(),h(e=>new Set(e).add(Ic(t)));try{await fr(Ic(t)),d({title:`Success`,description:`${t.label||t.name} stopped`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){d({title:`Error`,description:e instanceof Error?e.message:`Stop failed`,variant:`destructive`})}finally{h(e=>{let n=new Set(e);return n.delete(Ic(t)),n})}};return(0,Q.jsxs)(`div`,{className:`flex flex-col h-full`,onContextMenu:e=>{e.defaultPrevented||n.local||e.target.closest(`[data-workspace-row]`)||(e.preventDefault(),t({x:e.clientX,y:e.clientY}))},children:[e&&(0,Q.jsx)(wn,{...e,onClose:()=>t(null),className:`rounded-md border bg-popover p-1 shadow-elevation-3`,children:(0,Q.jsx)(`button`,{type:`button`,className:`px-3 py-1.5 text-xs hover:bg-accent`,onClick:()=>{t(null),s(),f(`/workspaces?create=1`)},children:`Create workspace…`})}),(0,Q.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 items-center`,children:[(0,Q.jsx)(Ms,{}),(0,Q.jsx)(`span`,{className:`text-sm font-semibold`,children:`Workspaces`})]}),!n.local&&(0,Q.jsx)(`button`,{type:`button`,onClick:()=>{s(),f(`/workspaces?create=1`)},title:`Create workspace`,"aria-label":`Create workspace`,className:`flex items-center justify-center w-6 h-6 rounded-full bg-foreground text-background hover:opacity-80 transition-opacity`,children:(0,Q.jsx)(ge,{className:`w-3.5 h-3.5`})})]}),(0,Q.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:u&&l.length===0?(0,Q.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):l.length===0?(0,Q.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No workspaces found`}):(0,Q.jsx)(`div`,{className:`space-y-1.5 px-2`,children:C.map((e,t)=>{let n=r.selectedEntityId===Ic(e),s=Ji(e),l=p.has(Ic(e)),u=e.status!==`active`,d=O(e),m=Si(d.color);return(0,Q.jsxs)(`div`,{"data-workspace-row":!0,...w(t),"data-active":n||void 0,className:G(`group relative rounded-(--card-radius) py-2.5 pl-3 pr-7 transition-all shadow-elevation-1`,n?`bg-accent shadow cursor-pointer hover:shadow`:u?`bg-card opacity-60 cursor-not-allowed`:`bg-card hover:bg-accent/50 cursor-pointer hover:shadow`,D(t,C.length),E===t&&`opacity-60`),onClick:()=>{u||A(e)},children:[(0,Q.jsx)(`button`,{type:`button`,...T(t),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:G(`absolute inset-y-0 right-0 flex w-4 cursor-grab items-center justify-center rounded-r-(--card-radius) active:cursor-grabbing`,!m&&`bg-muted`),style:m?{backgroundColor:m}:void 0,children:(0,Q.jsx)(I,{className:G(`h-3.5 w-3.5`,Ci(m))})}),(0,Q.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Q.jsx)(`button`,{type:`button`,title:s?`Change icon`:`Workspace appearance requires admin access`,onClick:t=>{!s||$t()||(t.stopPropagation(),_({x:Math.min(t.clientX,window.innerWidth-290),y:Math.min(t.clientY,window.innerHeight-360),name:Ic(e)}))},onContextMenu:t=>{s&&(t.preventDefault(),t.stopPropagation(),_({x:Math.min(t.clientX,window.innerWidth-290),y:Math.min(t.clientY,window.innerHeight-360),name:Ic(e)}))},className:`shrink-0 rounded p-0.5 hover:bg-muted-foreground/10 touch-target`,children:(0,Q.jsx)(i,{icon:d.icon||`ph:stack-fill`,width:18,height:18,color:m,className:G(!m&&`text-muted-foreground`)})}),(0,Q.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(Rc,{status:e.status}),(0,Q.jsx)(`span`,{className:`text-sm font-medium truncate`,children:e.label||e.name})]})}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-0.5 shrink-0`,children:[e.status===`active`?(0,Q.jsx)(`button`,{type:`button`,disabled:l,onClick:t=>M(t,e),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50 transition-colors`,title:`Stop`,children:(0,Q.jsx)(At,{className:`w-3.5 h-3.5`})}):(0,Q.jsx)(`button`,{type:`button`,disabled:l,onClick:t=>j(t,e),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50 transition-colors`,title:`Start`,children:(0,Q.jsx)(L,{className:`w-3.5 h-3.5`})}),(0,Q.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),a(Ic(e)),c?o(`settings`,Ic(e)):f(`/workspaces/${Ic(e)}/settings/general`)},className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground transition-colors disabled:opacity-40 disabled:cursor-not-allowed`,disabled:!s,title:s?`Settings`:`Workspace settings require admin access`,children:(0,Q.jsx)(pt,{className:`w-3.5 h-3.5`})})]})]}),e.description&&(0,Q.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-3.5`,children:e.description}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 mt-1 pl-3.5`,children:[e.host&&(0,Q.jsx)(`span`,{className:`text-[10px] text-muted-foreground truncate`,children:e.host}),e.ownerEmail&&(0,Q.jsx)(`span`,{className:`text-[10px] text-muted-foreground truncate`,children:e.ownerEmail})]})]},e.id||e.name)})})}),g&&(()=>{let e=l.find(e=>Ic(e)===g.name);if(!e)return null;let t=O(e);return(0,Q.jsx)(nc,{x:g.x,y:g.y,current:t,onChange:e=>k(g.name,t,e),onClose:()=>_(null)})})()]})}var Bc={previousTree:`Alt+Q`,nextTree:`Alt+W`},Vc=`canvas:key-bindings`,Hc=/^(Alt|Alt\+Shift|Ctrl\+Shift|Meta\+Shift)\+[A-Z]$/;function Uc(){try{let e=JSON.parse(localStorage.getItem(Vc)||`{}`),t={...Bc};for(let n of Object.keys(t))(e[n]===``||Hc.test(e[n]))&&(t[n]=e[n]);return t.previousTree&&t.previousTree===t.nextTree?{...Bc}:t}catch{return{...Bc}}}function Wc(e){localStorage.setItem(Vc,JSON.stringify(e))}function Gc(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 Kc(e,t,n){return e[(Math.max(0,e.indexOf(t))+n+e.length)%e.length]}function qc(e,t){return Math.abs(e)>=48&&Math.abs(e)>Math.abs(t)*1.5?e<0?1:-1:0}function Jc(e,t){let n=(0,Z.useRef)(null),r=(0,Z.useRef)(0);return(0,Z.useEffect)(()=>{if(!e)return;let n=e=>{if(e.defaultPrevented||e.repeat||e.isComposing||e.getModifierState(`AltGraph`))return;let n=e.target;if(n instanceof Element&&n.closest(`input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="textbox"], [role="dialog"], [role="alertdialog"]`)||document.querySelector(`[aria-modal="true"], dialog[open]`))return;let r=Gc(e);if(!r)return;let i=Uc(),a=r===i.previousTree?-1:+(r===i.nextTree);a&&(e.preventDefault(),t(a))};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[e,t]),{onTouchStart(e){r.current=0,n.current=e.touches.length===1?{x:e.touches[0].clientX,y:e.touches[0].clientY}:null},onTouchMove(e){e.touches.length!==1&&(n.current=null)},onTouchCancel(){n.current=null},onTouchEnd(i){if(!n.current||!e)return;let a=i.changedTouches[0],o=qc(a.clientX-n.current.x,a.clientY-n.current.y);n.current=null,o&&(r.current=Date.now()+500,i.stopPropagation(),t(o))},onClickCapture(e){Date.now()<r.current&&(e.preventDefault(),e.stopPropagation(),r.current=0)}}}function Yc(e,t,n,r=!1){if(!t.startsWith(`/`)||!n.length)throw Error(`Choose a source folder and at least one destination.`);let i=new Map;for(let e of n){if(![`context`,`directory`].includes(e.tree)||!e.path.startsWith(`/`))throw Error(`Choose a context or directory destination.`);if(e.path.includes(`{{`))throw Error(`Auto-Link destinations cannot contain {{ template markers.`);i.set(`${e.tree}:${e.path}`,e)}return{id:e,enabled:!0,description:`Auto-Link backends:${t} → ${[...i.keys()].join(`, `)}`,cascade:!0,when:{event:[`document.inserted`,`document.updated`,`document.linked`],...r?{path:`backends:${t}`}:{pathExact:`backends:${t}`}},then:[...i.values()].map(e=>({action:`link`,paths:[`${e.tree===`context`?`ctx`:`dir`}:${e.path}`],...r?{recursive:!0}:{}}))}}function Xc(e,t,n,r=!1,i=`forward`,a=`copy`,o,s){let c=Yc(e,t,n,r);if(i===`forward`)return[c];if(a===`move`&&!s?.trim())throw Error(`Choose the source backend whose copy should be moved.`);let l=t.split(`/`).filter(Boolean);if(l.length<2||t.includes(`{{`)||l.some(e=>e===`.`||e===`..`))throw Error(`Choose a backend folder with a valid storage address.`);if(!o)throw Error(`Choose a writable backend folder.`);let u=o.address,d=o.key,f=[...new Map(n.map(e=>[`${e.tree}:${e.path}`,e])).values()],p={id:`${e}-reverse`,enabled:!0,description:`Auto-Link ${f.map(e=>`${e.tree}:${e.path}`).join(`, `)} → backends:${t} (${a})`,cascade:!1,when:{event:[`document.inserted`,`document.linked`],[r?`path`:`pathExact`]:f.map(e=>`${e.tree}:${e.path}`)},then:[{action:`store`,to:u,folder:d,mode:a,...a===`move`?{from:s.trim()}:{},autoLink:!0,onConflict:`error`,...r?{recursive:!0}:{}}]};return i===`both`?[c,p]:[p]}function Zc(e,t){let n=ei(e,t);if(t.find(e=>e.driver===n.driver&&e.address===n.address)?.capabilities.paths!==!0)throw Error(`This backend has not reported support for folder paths. Choose a writable storage folder to copy or move files here.`);return n}function Qc({workspaceId:e,sourcePath:t,onClose:n,onManageRules:r}){let[i,a]=(0,Z.useState)([]),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(`forward`),[u,d]=(0,Z.useState)(`copy`),[f,p]=(0,Z.useState)(``),[m,h]=(0,Z.useState)([]),[g,_]=(0,Z.useState)(!0),[v,y]=(0,Z.useState)(!1),[b,x]=(0,Z.useState)(!0),[S]=(0,Z.useState)(()=>`autolink-${crypto.randomUUID()}`),[C,w]=(0,Z.useState)(!1),[T,E]=(0,Z.useState)(``),{showToast:D,showProgress:O}=xn(),k=()=>{C||n()},A=g?`Checking whether this backend can receive files…`:``;if(!g)try{Zc(t,m)}catch(e){A=e instanceof Error?e.message:`Choose a writable storage folder.`}let j=e=>{l(e),e!==`forward`&&x(!1)},M=e=>`${e.replace(/\/+$/,``)}/${v?`Subfolder/`:``}example.pdf`;return(0,Z.useEffect)(()=>{let t=!1;return gr(e).then(e=>{t||h(e)}).catch(()=>{t||E(`Could not load storage backends. Reopen Autolink to retry.`)}).finally(()=>{t||_(!1)}),()=>{t=!0}},[e]),(0,Q.jsx)(Nr,{label:o?`Choose virtual paths`:`Autolink documents`,onClose:o?()=>s(!1):k,children:o?(0,Q.jsx)(Dn,{fixedWorkspaceName:e,tabs:[`context`,`directory`],initialTab:c===`forward`?void 0:`directory`,title:`Choose virtual paths`,confirmLabel:`Add paths`,sizeClassName:`h-full w-full rounded-none border-0 shadow-none`,onClose:()=>s(!1),onConfirm:(e,t)=>{a(n=>{let r=[...n];for(let n of e)r.some(e=>e.tree===t.treeType&&e.path===n)||r.push({tree:t.treeType,path:n});return r}),s(!1)}}):(0,Q.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,Q.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-3 border-b p-5`,children:[(0,Q.jsxs)(`h2`,{className:`flex items-center gap-2 text-lg font-semibold`,children:[(0,Q.jsx)(zt,{className:`h-5 w-5`}),`Autolink documents`]}),(0,Q.jsx)(`button`,{type:`button`,onClick:k,disabled:C,"aria-label":`Close`,className:`p-1 disabled:opacity-40`,children:(0,Q.jsx)(z,{className:`h-4 w-4`})})]}),(0,Q.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-5 overflow-y-auto p-5`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Current backend folder`}),(0,Q.jsxs)(`p`,{className:`mt-1 break-words text-sm`,children:[`backends:`,t]})]}),(0,Q.jsxs)(`fieldset`,{disabled:C,className:`space-y-2 text-sm`,children:[(0,Q.jsx)(`label`,{className:`block font-medium`,htmlFor:`autolink-direction`,children:`Direction`}),(0,Q.jsxs)(`select`,{id:`autolink-direction`,className:`w-full rounded-md border bg-background p-2`,value:c,onChange:e=>j(e.target.value),children:[(0,Q.jsx)(`option`,{value:`forward`,children:`Backend → virtual folders (link)`}),(0,Q.jsx)(`option`,{value:`reverse`,disabled:!!A,children:`Virtual folders → backend (Copy/Move)`}),(0,Q.jsx)(`option`,{value:`both`,disabled:!!A,children:`Both directions`})]}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c===`forward`?`Link documents from this backend folder into the selected virtual folders. Files stay where they are.`:`When a document is added or explicitly linked to a selected virtual folder, ${u} its file to the current backend folder.${c===`both`?` Documents arriving on the backend are also linked into the virtual folders.`:``}`}),A&&(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:g?A:`Reverse mapping unavailable: ${A}`}),c!==`forward`&&(0,Q.jsxs)(`div`,{className:`space-y-2 rounded-lg border p-3`,children:[(0,Q.jsx)(`label`,{className:`block font-medium`,htmlFor:`autolink-operation`,children:`File operation`}),(0,Q.jsxs)(`select`,{id:`autolink-operation`,className:`w-full rounded-md border bg-background p-2`,value:u,onChange:e=>d(e.target.value),children:[(0,Q.jsx)(`option`,{value:`copy`,children:`Copy files to this backend`}),(0,Q.jsx)(`option`,{value:`move`,children:`Move files to this backend`})]}),u===`copy`&&(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Keep the source file and its virtual-folder links.`}),u===`move`&&(0,Q.jsxs)(`div`,{className:`mt-2 space-y-2`,children:[(0,Q.jsx)(`label`,{className:`block`,htmlFor:`autolink-source-backend`,children:`Move files from`}),(0,Q.jsxs)(`select`,{id:`autolink-source-backend`,className:`w-full rounded-md border bg-background p-2`,value:f,onChange:e=>p(e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:`Choose a source backend…`}),m.filter(e=>e.kind===`storage`&&e.enabled&&e.config?.readOnly!==!0).map(e=>(0,Q.jsx)(`option`,{value:e.address,children:e.address},e.address))]}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Move the file from this source backend after it has been stored at the destination. Virtual-folder links stay in place. Files missing from this source are skipped; multiple source copies require Copy instead.`})]})]})]}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(`h3`,{className:`text-sm font-medium`,children:c===`reverse`?`Watch virtual folders`:`Virtual folders`}),i.map((e,t)=>(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 rounded-lg border p-2 text-sm`,children:[(0,Q.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Q.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.tree===`context`?`Context tree`:`Directory tree`}),(0,Q.jsx)(`p`,{className:`break-words`,children:e.path})]}),(0,Q.jsx)(`button`,{type:`button`,"aria-label":`Remove ${e.tree}:${e.path}`,disabled:C,onClick:()=>a(e=>e.filter((e,n)=>n!==t)),children:(0,Q.jsx)(z,{className:`h-4 w-4`})})]},`${e.tree}:${e.path}`)),(0,Q.jsxs)(K,{variant:`outline`,size:`sm`,disabled:C,onClick:()=>s(!0),children:[(0,Q.jsx)(ge,{className:`mr-1 h-4 w-4`}),`Add virtual path…`]}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c===`forward`?`Choose the virtual folders where backend documents should appear.`:`Choose a Context or Directory tree folder to watch for newly filed documents. Its files will be stored in the current backend folder.`})]}),(0,Q.jsxs)(`fieldset`,{disabled:C,className:`space-y-3 text-sm`,children:[(0,Q.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:v,onChange:e=>y(e.target.checked),className:`mt-1`}),`Include subfolders and recreate their path in the destination`]}),(0,Q.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:b,onChange:e=>x(e.target.checked),className:`mt-1`}),`Apply to existing documents`]})]}),!!i.length&&(0,Q.jsxs)(`div`,{className:`space-y-3 rounded-lg border bg-muted/30 p-3 text-sm`,"aria-label":`Mapping preview`,children:[(0,Q.jsx)(`h3`,{className:`font-medium`,children:`Example result`}),i.map(e=>(0,Q.jsxs)(`div`,{className:`space-y-2 break-all text-xs`,children:[c!==`reverse`&&(0,Q.jsxs)(`p`,{children:[(0,Q.jsx)(`span`,{className:`text-muted-foreground`,children:`Link `}),`backends:`,M(t),(0,Q.jsx)(`br`,{}),(0,Q.jsx)(`span`,{className:`text-muted-foreground`,children:`Into `}),e.tree===`context`?`ctx`:`dir`,`:`,M(e.path)]}),c!==`forward`&&(0,Q.jsxs)(`p`,{children:[(0,Q.jsxs)(`span`,{className:`text-muted-foreground`,children:[u===`move`?`Move`:`Copy`,` `]}),e.tree===`context`?`ctx`:`dir`,`:`,M(e.path),(0,Q.jsx)(`br`,{}),(0,Q.jsx)(`span`,{className:`text-muted-foreground`,children:`To `}),`backends:`,M(t)]})]},`preview:${e.tree}:${e.path}`)),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:v?`The selected folders are the roots. Only the subfolder path beneath each root is recreated at its destination.`:`Only direct folder contents are included.`})]}),(0,Q.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[b?`Existing matching documents are processed in the background on the server once enabled.`:c===`forward`?`Future backend arrivals and updates are linked automatically.`:`Newly added or explicitly linked virtual-folder documents are processed automatically.`,` `,c===`both`&&`Both directions creates two rules in workspace Rules. `,`Removing rules keeps existing files and links. Renames and deletions are not synchronized. Filename conflicts stop the transfer without overwriting.`]}),T&&(0,Q.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:T})]}),(0,Q.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2 border-t p-3`,children:[(0,Q.jsx)(K,{variant:`ghost`,disabled:C,onClick:r,children:`Manage rules`}),(0,Q.jsx)(K,{disabled:C||!i.length||c!==`forward`&&(!!A||u===`move`&&!f),onClick:async()=>{if(!C){w(!0),E(``);try{let r=c===`forward`?void 0:Zc(t,await gr(e)),a=Xc(S,t,i,v,c,u,r,f);await Ki(e,a),b?Vi(O,e,a.map(e=>e.id)):D({title:`Autolink enabled`,description:`Future documents are linked automatically.`}),n()}catch(e){E(e instanceof Error?e.message:`Could not configure Auto-Link`)}finally{w(!1)}}},children:C?`Saving…`:`Enable Autolink`})]})]})})}var $c=e=>`/workspaces/${e}/storage-policies`;function el(){return`policy-${crypto.randomUUID().slice(0,8)}`}function tl(e){return e.filter(e=>e.enabled&&e.capabilities?.upload&&!e.config?.readOnly&&e.driver!==`cacache`)}var nl=new Set([`file`]);function rl(e,t){return`${e===`directory`?`dir`:`ctx`}:${t.startsWith(`/`)?t:`/${t}`}`}function il(e){let t=/^(ctx|dir):(\/.*)$/.exec(e);return t?{tree:t[1]===`dir`?`directory`:`context`,path:t[2]}:null}function al(e){return(il(e)?.path??e).replace(/^\/+/,``)}function ol(e){return`${e.backend}:${e.folder||`/`}`}async function sl(e){let t=await Y.get($c(e));return{...t,policies:t?.policies??[],revision:t.revision,blobBackend:t?.blobBackend??null}}async function cl(e,t,n){return Y.put($c(e),{policies:t,revision:n})}async function ll(e,t,n={}){return await Y.post(`${$c(e)}/${encodeURIComponent(t)}/apply`,n)}async function ul(e,t,n){let{policies:r,revision:i}=n??await sl(e),a=r.findIndex(e=>e.id===t.id);return cl(e,a===-1?[...r,t]:r.map((e,n)=>n===a?t:e),i)}async function dl(e,t,n,r={}){let i={folders:0,processed:0,matched:0,failed:0},a=0;for(;a!==null;){let o=await ll(e,t,{limit:r.limit??100,offset:a,dryRun:r.dryRun});if(i.folders+=o.folders??0,i.processed+=o.processed??0,i.matched+=o.matched??0,i.failed+=o.failed??0,n?.(o,i),o.nextOffset===void 0)throw Error(`The policy is saved, but applying it to existing documents needs an updated server.`);a=o.nextOffset}return i}function fl(e,t,n){let r=rl(t,n),i=r.endsWith(`/`)?r:`${r}/`;return e.filter(e=>{if(!e.enabled)return!1;if(e.path===r)return!0;if(!e.recursive)return!1;let t=e.path.endsWith(`/`)?e.path:`${e.path}/`;return i.startsWith(t)})}function pl(e){let t=new Set;for(let n of e)for(let e of n.targets)t.add(ol(e));return[...t].join(`, `)}async function ml(e,t){await Y.post(`${$c(e)}/operations/${encodeURIComponent(t)}/retry`,{})}function hl(e){return!e||!e.mime&&!e.filename&&(!e.schema||e.schema===`file`)?`files`:e.mime===`image/*`&&!e.filename&&(!e.schema||e.schema===`file`)?`images`:`custom`}function gl(e,t){return{backend:e?.address??``,folder:t,recursive:!0,recreateDirectories:!!e&&nl.has(e.driver),onConflict:`error`}}function _l({workspaceId:e,path:t,policy:n,onClose:r,onSaved:i}){let a=!!n,[o]=(0,Z.useState)(()=>n?.id??el()),[s,c]=(0,Z.useState)(n?.kind||`mirror`),[l,u]=(0,Z.useState)(n?.description??``),[d,f]=(0,Z.useState)(n?.recursive??!0),[p,m]=(0,Z.useState)(()=>hl(n?.filter)),[h,g]=(0,Z.useState)(n?.filter?.mime??``),[_,v]=(0,Z.useState)(n?.filter?.filename??``),[y,b]=(0,Z.useState)(n?.targets??[]),[x,S]=(0,Z.useState)(null),[C,w]=(0,Z.useState)(null),[T,E]=(0,Z.useState)(!1),[D,O]=(0,Z.useState)(!1),[k,A]=(0,Z.useState)(!1),[j,M]=(0,Z.useState)(``),[N,ee]=(0,Z.useState)(0),[P,te]=(0,Z.useState)(0),[ne,re]=(0,Z.useState)(0);hi(r,!D);let ie=()=>{D||r()},F=(0,Z.useMemo)(()=>al(t),[t]),ae=(0,Z.useMemo)(()=>tl(C??[]).filter(e=>s===`filing`||e.driver===`file`),[C,s]),oe=(0,Z.useMemo)(()=>new Map(ae.map(e=>[e.address,e])),[ae]);(0,Z.useEffect)(()=>{let t=!1;return Promise.all([gr(e),sl(e)]).then(([e,r])=>{if(t)return;if(n&&JSON.stringify(r.policies.find(e=>e.id===n.id))!==JSON.stringify(n))throw Error(`This policy changed. Close and reopen the editor.`);S(r),w(e);let i=tl(e).find(e=>n?.kind===`filing`||e.driver===`file`);i&&b(e=>e.length?e:[gl(i,F)])}).catch(e=>{t||(w([]),M(e instanceof Error?e.message:`Could not load backends`))}),()=>{t=!0}},[e,F,n]);let I=(e,t)=>b(n=>n.map((n,r)=>r===e?{...n,...t}:n)),se=(e,t)=>{let n=oe.get(t),r=!!n&&nl.has(n.driver);I(e,{backend:t,recreateDirectories:r?y[e].recreateDirectories:!1})},ce=()=>{if(!y.length)throw Error(`Add at least one target.`);let e=y.map(e=>{if(!e.backend)throw Error(`Choose a backend for every target.`);let t={backend:e.backend,folder:e.folder.trim().replace(/^\/+|\/+$/g,``),recursive:e.recursive,recreateDirectories:e.recreateDirectories,onConflict:e.onConflict??`error`};if(s===`filing`&&e.key?.trim()&&(t.key=e.key.trim()),s===`filing`&&(t.recreateDirectories=!1),s===`mirror`&&t.folder.includes(`{{`))throw Error(`Folder templates require a filing policy.`);return t}),r;return p===`images`?r={schema:`file`,mime:`image/*`}:p===`custom`&&(r={schema:`file`},h.trim()&&(r.mime=h.trim()),_.trim()&&(r.filename=_.trim())),{id:o,kind:s,enabled:n?.enabled??!0,...l.trim()?{description:l.trim()}:{},path:t,recursive:d,...r?{filter:r}:{},targets:e}},le=async()=>{if(!D){O(!0),M(``);try{let t=ce();T||(await ul(e,t,x),E(!0),i?.(t)),ee(0),te(0),re(0),await dl(e,o,(e,t)=>{ee(t.matched),te(t.folders),re(t.failed)}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`)),A(!0)}catch(e){M(e instanceof Error?e.message:`Could not save the storage policy`)}finally{O(!1)}}},ue=!!x&&y.length>0&&y.every(e=>e.backend);return(0,Q.jsx)(Ti,{onClose:ie,children:(0,Q.jsxs)(`section`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-policy-title`,className:`${Ei} flex flex-col overflow-hidden rounded-(--panel-radius) border bg-card shadow-elevation-4`,children:[(0,Q.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,Q.jsxs)(`h2`,{id:`storage-policy-title`,className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Q.jsx)(de,{className:`h-4 w-4`}),a?`Edit storage policy`:`Storage policy`]}),(0,Q.jsx)(`button`,{type:`button`,onClick:ie,disabled:D,"aria-label":`Close`,className:`p-1 disabled:opacity-40`,children:(0,Q.jsx)(z,{className:`h-4 w-4`})})]}),(0,Q.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-5 overflow-y-auto p-4`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Virtual path`}),(0,Q.jsx)(`p`,{className:`mt-1 break-words text-sm`,children:t})]}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Documents filed here are copied to every target in order. Uploads stay local until every destination has been verified. Mirrors move removed copies to Trash; filing policies keep their copies.`}),(0,Q.jsxs)(`fieldset`,{disabled:D||T,className:`space-y-3 text-sm`,children:[(0,Q.jsxs)(`label`,{className:`block`,children:[`Behavior`,(0,Q.jsxs)(`select`,{"aria-label":`Storage behavior`,className:`ml-2 rounded border bg-background p-2`,value:s,onChange:e=>c(e.target.value),children:[(0,Q.jsx)(`option`,{value:`mirror`,children:`Mirror (recoverable removal)`}),(0,Q.jsx)(`option`,{value:`filing`,children:`File copies (keep after unlink)`})]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`block text-xs text-muted-foreground`,htmlFor:`policy-description`,children:`Description (optional)`}),(0,Q.jsx)(`input`,{id:`policy-description`,className:`mt-1 w-full rounded-md border bg-background p-2`,value:l,onChange:e=>u(e.target.value),placeholder:`e.g. Accounting archive`})]}),(0,Q.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:d,onChange:e=>f(e.target.checked),className:`mt-1`}),`Apply to subfolders`]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`block text-xs text-muted-foreground`,htmlFor:`policy-filter`,children:`Documents`}),(0,Q.jsxs)(`select`,{id:`policy-filter`,className:`mt-1 w-full rounded-md border bg-background p-2`,value:p,onChange:e=>m(e.target.value),children:[(0,Q.jsx)(`option`,{value:`files`,children:`Files`}),(0,Q.jsx)(`option`,{value:`images`,children:`Images`}),(0,Q.jsx)(`option`,{value:`custom`,children:`Custom…`})]}),p===`custom`&&(0,Q.jsxs)(`div`,{className:`mt-2 grid grid-cols-2 gap-2`,children:[(0,Q.jsx)(`input`,{"aria-label":`MIME type`,className:`rounded-md border bg-background p-2`,value:h,onChange:e=>g(e.target.value),placeholder:`image/*`}),(0,Q.jsx)(`input`,{"aria-label":`Filename glob`,className:`rounded-md border bg-background p-2`,value:_,onChange:e=>v(e.target.value),placeholder:`img*`})]})]})]}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(`h3`,{className:`text-sm font-medium`,children:`Targets`}),C===null&&(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading backends…`}),C!==null&&!ae.length&&(0,Q.jsx)(`p`,{className:`text-xs text-destructive`,children:`No writable backend available. Add a folder or drive under Files & storage first.`}),y.map((e,t)=>{let n=oe.get(e.backend),r=s===`mirror`&&!!n&&nl.has(n.driver);return(0,Q.jsxs)(`fieldset`,{disabled:D||T,className:`space-y-2 rounded-lg border p-2 text-sm`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsxs)(`select`,{"aria-label":`Backend`,className:`min-w-0 flex-1 rounded-md border bg-background p-2`,value:e.backend,onChange:e=>se(t,e.target.value),children:[!e.backend&&(0,Q.jsx)(`option`,{value:``,children:`Choose a backend…`}),ae.map(e=>(0,Q.jsxs)(`option`,{value:e.address,children:[e.address,` (`,e.driver,`)`]},e.address)),e.backend&&!n&&(0,Q.jsxs)(`option`,{value:e.backend,children:[e.backend,` (unavailable)`]})]}),(0,Q.jsx)(`button`,{type:`button`,"aria-label":`Remove target`,onClick:()=>b(e=>e.filter((e,n)=>n!==t)),className:`p-1 disabled:opacity-40`,children:(0,Q.jsx)(z,{className:`h-4 w-4`})})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`block text-xs text-muted-foreground`,htmlFor:`policy-folder-${t}`,children:`Folder on the backend`}),(0,Q.jsx)(`input`,{id:`policy-folder-${t}`,className:`mt-1 w-full rounded-md border bg-background p-2`,value:e.folder,onChange:e=>I(t,{folder:e.target.value}),placeholder:`(backend root)`})]}),(0,Q.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:e.recursive,onChange:e=>I(t,{recursive:e.target.checked}),className:`mt-1`}),`Recreate sub-folder path in destination`]}),(0,Q.jsxs)(`label`,{className:`flex items-start gap-2 ${r?``:`opacity-60`}`,title:r?void 0:`Empty folders require a mirror on a supported file backend.`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:r&&e.recreateDirectories,disabled:!r,onChange:e=>I(t,{recreateDirectories:e.target.checked}),className:`mt-1`}),`Create folders on the backend`]}),(0,Q.jsxs)(`details`,{children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer text-xs text-muted-foreground`,children:`Advanced`}),(0,Q.jsxs)(`div`,{className:`mt-2 space-y-2`,children:[s===`filing`&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`block text-xs text-muted-foreground`,htmlFor:`policy-key-${t}`,children:`File-name template (optional)`}),(0,Q.jsx)(`input`,{id:`policy-key-${t}`,className:`mt-1 w-full rounded-md border bg-background p-2 font-mono text-xs`,value:e.key??``,onChange:e=>I(t,{key:e.target.value}),placeholder:`{{YYYY}}{{MM}}{{DD}}_{{basename}}{{ext}}`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`block text-xs text-muted-foreground`,htmlFor:`policy-conflict-${t}`,children:`On name conflict`}),(0,Q.jsxs)(`select`,{id:`policy-conflict-${t}`,className:`mt-1 w-full rounded-md border bg-background p-2`,value:e.onConflict??`error`,onChange:e=>I(t,{onConflict:e.target.value}),children:[(0,Q.jsx)(`option`,{value:`error`,children:`Stop with an error`}),(0,Q.jsx)(`option`,{value:`rename`,children:`Rename the new file`}),n?.driver===`file`&&(0,Q.jsx)(`option`,{value:`overwrite`,children:`Overwrite (retain previous bytes)`})]})]})]})]})]},t)}),!T&&(0,Q.jsxs)(K,{variant:`outline`,size:`sm`,disabled:D||!ae.length,onClick:()=>b(e=>[...e,gl(ae.find(t=>!e.some(e=>e.backend===t.address))??ae[0],F)]),children:[(0,Q.jsx)(ge,{className:`mr-1 h-4 w-4`}),`Add target…`]})]}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Applies to existing and future documents. Transfer progress and errors appear in Storage policies settings.`}),D&&(0,Q.jsx)(`p`,{role:`status`,className:`text-sm`,children:T?`Applying to existing documents… ${N} planned, ${P} folders`:`Saving storage policy…`}),k&&(0,Q.jsxs)(`p`,{role:`status`,className:`text-sm`,children:[`Storage policy saved. `,N,` documents and `,P,` folders planned. Replication continues in the background.`]}),ne>0&&(0,Q.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[ne,` document operations failed. Check operation status in Storage policies settings.`]}),j&&(0,Q.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[T?`The policy is saved. `:``,j]})]}),(0,Q.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2 border-t p-3`,children:[(0,Q.jsx)(K,{variant:`ghost`,disabled:D,onClick:ie,children:`Cancel`}),k?(0,Q.jsx)(K,{onClick:r,children:`Done`}):(0,Q.jsx)(K,{disabled:D||!ue,onClick:le,children:D?`Applying…`:T?`Retry existing documents`:a?`Save policy`:`Enable policy`})]})]})})}var vl={policies:[],revision:``,loading:!1,error:``},yl=new Map,bl=new Set;function xl(){for(let e of bl)e()}function Sl(e){return bl.add(e),()=>{bl.delete(e)}}function Cl(e,t){yl.set(e,t),xl()}async function wl(e){Cl(e,{...yl.get(e)??vl,loading:!0,error:``});try{let{policies:t,revision:n,status:r}=await sl(e);Cl(e,{policies:t,revision:n,status:r,loading:!1,error:``})}catch(t){Cl(e,{policies:[],revision:``,loading:!1,error:t instanceof Error?t.message:`Could not load storage policies`})}}function Tl(e){yl.delete(e),xl()}function El(e){let t=(0,Z.useSyncExternalStore)(Sl,()=>e&&yl.get(e)||vl),n=!!e&&!yl.has(e);(0,Z.useEffect)(()=>{e&&n&&wl(e)},[e,n]);let r=(0,Z.useCallback)(async()=>{e&&await wl(e)},[e]);return(0,Z.useEffect)(()=>{if(!e||!t.policies.length)return;let n=window.setInterval(()=>{!document.hidden&&!yl.get(e)?.loading&&wl(e)},5e3);return()=>window.clearInterval(n)},[e,t.policies.length]),{policies:t.policies,revision:t.revision,status:t.status,loading:t.loading,error:t.error,refresh:r}}async function Dl(){return await Y.get(`${J}/users/me/config/webui`)??{}}async function Ol(e){return await Y.put(`${J}/users/me/config/webui`,e)??e}var kl=`application/x-canvas-workspace-pin`;function Al({pins:e,isLoading:t,searchQuery:n=``,activeKey:r,onOpen:a,onShowInTree:o,onUnpin:s,onMove:c}){let[l,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)(null),p=n.toLowerCase().trim(),m=p?e.filter(e=>(e.label||e.name||``).toLowerCase().includes(p)||e.path.toLowerCase().includes(p)||(e.description||``).toLowerCase().includes(p)):e,h=()=>{u(null),f(null)},g=async()=>{let t=d,n=l;if(h(),!n||!t||t.id===n)return;let r=t.id;if(t.id&&!t.before&&(r=e[e.findIndex(e=>e.id===t.id)+1]?.id??null),r!==n)try{await c(n,r)}catch(e){alert(e instanceof Error?e.message:String(e))}};return t&&!e.length?(0,Q.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading pins…`}):e.length?m.length?(0,Q.jsx)(`div`,{className:`p-2 flex flex-col gap-2`,onDragOver:e=>{l&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`)},onDrop:e=>{e.preventDefault(),l&&!d&&f({id:null,before:!1}),g()},children:m.map(e=>{let t=e.resolvable===!1,n=Si(e.color),c=e.icon||(e.type===`canvas`?`ph:squares-four-fill`:`ph:folder-fill`),m=r===hr(e.tree,e.path),_=d?.id===e.id&&d.before,v=d?.id===e.id&&!d.before;return(0,Q.jsxs)(`div`,{role:`button`,tabIndex:0,"data-active":m||void 0,draggable:!p,onDragStart:t=>{t.dataTransfer.setData(kl,e.id),t.dataTransfer.setData(`text/plain`,e.path),t.dataTransfer.effectAllowed=`move`,u(e.id)},onDragEnd:h,onDragOver:t=>{if(!l||l===e.id)return;t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=`move`;let n=t.currentTarget.getBoundingClientRect(),r=t.clientY<n.top+n.height/2;f(t=>t?.id===e.id&&t.before===r?t:{id:e.id,before:r})},onDrop:e=>{e.preventDefault(),e.stopPropagation(),g()},onClick:()=>{t||a(e)},onKeyDown:n=>{n.target===n.currentTarget&&(n.key===`Enter`||n.key===` `)&&!t&&(n.preventDefault(),a(e))},title:t?`${e.path} — folder no longer exists`:`Open ${e.tree}:${e.path}`,className:G(`group relative flex items-stretch gap-2.5 rounded-(--card-radius) border bg-card shadow-elevation-1 text-left transition-colors`,t?`opacity-70 cursor-default`:`cursor-pointer hover:bg-accent/40`,m&&`ring-1 ring-primary/60`,l===e.id&&`opacity-40`,_&&`border-t-2 border-t-primary`,v&&`border-b-2 border-b-primary`),style:{borderLeft:`5px solid ${n??`transparent`}`},children:[(0,Q.jsx)(`div`,{className:`flex items-center justify-center w-12 shrink-0 rounded-l-[5px] my-0 self-stretch`,style:n?{backgroundColor:`${n}22`}:void 0,children:t?(0,Q.jsx)(R,{className:`w-5 h-5 text-warning`}):(0,Q.jsx)(i,{icon:c,width:22,height:22,color:n,className:G(!n&&(e.type===`canvas`?`text-primary`:`text-muted-foreground`))})}),(0,Q.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1 py-2 pr-1`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5 min-w-0`,children:[(0,Q.jsx)(`span`,{className:`text-sm font-semibold leading-tight truncate`,children:e.label||e.name||e.path.split(`/`).pop()}),e.locked&&(0,Q.jsx)(Ft,{className:`w-3 h-3 shrink-0 text-warning`})]}),(0,Q.jsxs)(`span`,{className:`text-[11px] text-muted-foreground truncate leading-tight font-mono mt-0.5`,children:[e.tree,`:`,e.path]}),e.description&&(0,Q.jsx)(`span`,{className:`text-[11px] text-muted-foreground/80 truncate leading-tight mt-1`,children:e.description}),t&&(0,Q.jsx)(`span`,{className:`text-[11px] text-warning leading-tight mt-1`,children:`Folder no longer exists`})]}),(0,Q.jsxs)(`div`,{className:`flex flex-col items-center justify-between py-1.5 pr-1.5 shrink-0`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,Q.jsx)(`button`,{type:`button`,disabled:t,onClick:t=>{t.stopPropagation(),o(e)},title:`Show in tree`,"aria-label":`Show in tree`,className:`flex items-center justify-center w-6 h-6 rounded text-muted-foreground reveal-on-hover focus-visible:opacity-100 hover:bg-accent hover:text-foreground transition-colors disabled:opacity-40 disabled:cursor-default`,children:(0,Q.jsx)(Ot,{className:`w-3.5 h-3.5`})}),(0,Q.jsx)(`button`,{type:`button`,onClick:async t=>{t.stopPropagation();try{await s(e)}catch(e){alert(e instanceof Error?e.message:String(e))}},title:`Unpin`,"aria-label":`Unpin`,className:`flex items-center justify-center w-6 h-6 rounded text-muted-foreground reveal-on-hover hover:bg-destructive/10 hover:text-destructive transition-colors`,children:(0,Q.jsx)(W,{className:`w-3.5 h-3.5`})})]}),!p&&(0,Q.jsx)(I,{className:`w-3.5 h-3.5 text-muted-foreground/50 cursor-grab active:cursor-grabbing`,"aria-hidden":!0})]})]},e.id)})}):(0,Q.jsxs)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:[`No pins match “`,n,`”`]}):(0,Q.jsxs)(`div`,{className:`px-3 py-6 text-xs text-muted-foreground text-center space-y-1`,children:[(0,Q.jsx)(`p`,{children:`No pinned folders yet.`}),(0,Q.jsxs)(`p`,{className:`text-muted-foreground/70`,children:[`Right-click a folder in the context, directory or backends tree and choose `,(0,Q.jsx)(`span`,{className:`font-medium`,children:`Pin`}),`.`]})]})}var jl=()=>({selectedPath:`/`,contentPath:null,searchQuery:``,expansion:new Map}),Ml=[`pins`,`context`,`layers`,`directory`,`backends`],Nl=e=>typeof e==`string`&&Ml.includes(e),Pl=e=>{let t=Array.isArray(e)?e.filter(Nl).filter((e,t,n)=>n.indexOf(e)===t):[];return[...t,...Ml.filter(e=>!t.includes(e))]},Fl={pins:(0,Q.jsx)(V,{className:`w-3.5 h-3.5`}),context:(0,Q.jsx)(Ne,{className:`w-3.5 h-3.5`}),layers:(0,Q.jsx)(xe,{className:`w-3.5 h-3.5`}),directory:(0,Q.jsx)(Ot,{className:`w-3.5 h-3.5`}),backends:(0,Q.jsx)(Je,{className:`w-3.5 h-3.5`})},Il={pins:`Pins`,context:`Context tree`,layers:`Context layers`,directory:`Directory tree`,backends:`Backends tree`},Ll=e=>e===`directory`||e===`backends`?e:Gn,Rl=(e,t)=>t?`layers`:e===`directory`?`directory`:e===`backends`?`backends`:`context`;function zl(){let{state:e}=la();return e.selectedEntityId?(0,Q.jsx)(xa,{workspaceName:e.selectedEntityId,children:(0,Q.jsx)(Bl,{},e.selectedEntityId)}):null}function Bl(){let{state:e,closeM2:t,openM2:n,navigateFromMenu:r}=la(),i=xr(),a=Fr(),o=e.selectedEntityId,s=m(),c=h(),{treeName:l,path:u}=ra(c.pathname),d=new URLSearchParams(c.search).get(`layer`)===`1`,f=new URLSearchParams(c.search).get(`layerId`),p=/\/trees\/|\/path(\/|$)/.test(c.pathname)||!!f,g=p?Rl(l,f):Ml[0],[_,v]=(0,Z.useState)(!1),[y,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)(null),[C,w]=(0,Z.useState)({icon:null,color:null}),[T,E]=(0,Z.useState)(g),[D,O]=(0,Z.useState)(null),[k,A]=(0,Z.useState)(null),[j,M]=(0,Z.useState)(null),[N,ee]=(0,Z.useState)([]),[P,te]=(0,Z.useState)(!1),[ne,re]=(0,Z.useState)(!1),[ie,F]=(0,Z.useState)(!1),[ae,oe]=(0,Z.useState)(!1),[I,se]=(0,Z.useState)(u),[ce,le]=(0,Z.useState)([]),[ue,L]=(0,Z.useState)(new Set),[R,de]=(0,Z.useState)(d&&u!==`/`?u:null),[z,B]=(0,Z.useState)(``),[V,fe]=(0,Z.useState)(null),[H,pe]=(0,Z.useState)(null),[me,he]=(0,Z.useState)(null),{policies:ge,refresh:_e}=El(o),ve=(0,Z.useCallback)(e=>{if(T!==`context`&&T!==`directory`||!ge.length)return null;let t=fl(ge,T,e);return t.length?`Storage policy targets: ${pl(t)} (see Settings for transfer status)`:null},[T,ge]),[U,ye]=(0,Z.useState)([]),[W,be]=(0,Z.useState)(!1),[xe,Se]=(0,Z.useState)(!1),Ce=(0,Z.useRef)(null),we=(0,Z.useRef)(new Map),[Te,Ee]=(0,Z.useState)(()=>Object.fromEntries(Ml.map(e=>[e,jl()])));(0,Z.useLayoutEffect)(()=>{Ce.current&&(Ce.current.scrollTop=we.current.get(T)??0)},[T]);let De=Te[T];(De.selectedPath!==I||De.contentPath!==R||De.searchQuery!==z)&&Ee({...Te,[T]:{...De,selectedPath:I,contentPath:R,searchQuery:z}});let Oe=(0,Z.useRef)(!1),[ke,Ae]=(0,Z.useState)(!1),[je,Me]=(0,Z.useState)(Ml),Ne=!p;(0,Z.useEffect)(()=>{let e=!1;return Dl().then(t=>{if(e)return;let n=Pl(t?.m2?.tabOrder);Me(n),Ne&&E(e=>e===Ml[0]?n[0]:e)}).catch(()=>{}),()=>{e=!0}},[]);let Pe=(0,Z.useCallback)(async e=>{let t=je;Me(e);try{let t=await Dl();await Ol({...t,m2:{...t.m2,tabOrder:e}})}catch{Me(t)}},[je]),[Fe,Ie]=(0,Z.useState)(null),[Le,Re]=(0,Z.useState)(null),ze=()=>{Ie(null),Re(null)},Be=()=>{if(Fe&&Le&&Fe!==Le.id){let e=je.filter(e=>e!==Fe),t=e.indexOf(Le.id);t>=0&&(e.splice(Le.before?t:t+1,0,Fe),e.some((e,t)=>e!==je[t])&&Pe(e))}ze()};(0,Z.useEffect)(()=>{let e=e=>fe(e.detail??null);return window.addEventListener(`documents:clipboard`,e),()=>window.removeEventListener(`documents:clipboard`,e)},[]);let[Ve,He]=(0,Z.useState)(u);u!==Ve&&(He(u),se(u));let Ue=(0,Z.useRef)(new Map),We=(0,Z.useCallback)(async(e,t,n=!1,r=!1)=>{let i=Symbol();Ue.current.set(t,i);let a=()=>Ue.current.get(t)===i,o=t===`context`?te:t===`directory`?re:F,s=t===`context`?O:t===`directory`?A:M;n||o(!0);try{n&&!r&&ar(e,t);let i=await In(e,t);a()&&s(i)}catch{}finally{a()&&o(!1)}},[]),Ge=(0,Z.useCallback)(async(e,t=!1)=>{let n=Symbol();Ue.current.set(`pins`,n);let r=()=>Ue.current.get(`pins`)===n;t||be(!0);try{let t=await Pn(e);r()&&ye(t)}catch{}finally{r()&&be(!1)}},[]),Ke=(0,Z.useCallback)(async(e,t=!1)=>{let n=Symbol();Ue.current.set(`layers`,n);let r=()=>Ue.current.get(`layers`)===n;t||oe(!0);try{let t=await qn(e,`context`);r()&&ee(t)}catch{}finally{r()&&oe(!1)}},[]);(0,Z.useEffect)(()=>{if(!o)return;let e=o,t=!1,n=Ue.current;async function r(){Un(e).then(e=>{t||(b(e.label||e.name),v(Ji(e)),S(e.id||null),w({icon:e.icon??null,color:e.color??null}))}).catch(()=>{}),await Promise.all([We(e,`context`),We(e,`directory`),We(e,`backends`),Ke(e),Ge(e)])}return r(),()=>{t=!0,n.clear()}},[o,We,Ke,Ge]);let qe=(0,Z.useCallback)((e,t,n=!1)=>{for(let r of[`context`,`directory`,`backends`])(!t||t===r)&&We(e,r,!0,n);(!t||t===`context`)&&Ke(e,!0),Ge(e,!0)},[We,Ke,Ge]),Je=(0,Z.useCallback)(()=>{o&&qe(o)},[o,qe]);(0,Z.useEffect)(()=>{if(!o)return;let e=e=>{e.detail?.workspaceName&&e.detail.workspaceName!==o||qe(o,e.detail?.treeName,e.detail?.cacheInvalidated)};return window.addEventListener(`workspace:tree:refresh`,e),()=>window.removeEventListener(`workspace:tree:refresh`,e)},[o,qe]),(0,Z.useEffect)(()=>{if(!o)return;let e=!1,t=()=>gr(o).then(t=>{e||(le(t),L(new Set(t.filter(e=>e.resyncing&&e.treePath).map(e=>e.treePath))))}).catch(()=>{});t();let n=e=>{let n=e.detail;n?.workspaceName&&n.workspaceName!==o||(!n?.treeName||n.treeName===`backends`)&&t()};return window.addEventListener(`workspace:tree:refresh`,n),()=>{e=!0,window.removeEventListener(`workspace:tree:refresh`,n)}},[o]),(0,Z.useEffect)(()=>{if(!o)return;let e=[`workspace:${o}`,x?`workspace:${x}`:null].filter(Boolean),t=()=>e.forEach(e=>X.emit(`subscribe`,{channel:e})),n=X.on(`connect`,t);t();let r=Or(o,x),i=e=>{if(e?.workspaceId&&x&&e.workspaceId!==x)return;let t=e?.treePath;t&&L(n=>{let r=new Set(n);return e.resyncing?r.add(t):r.delete(t),r})};X.on(`backend.resync.changed`,i);let a=e=>{e?.workspaceId&&x&&e.workspaceId!==x||Ge(o,!0)};return X.on(`pins.changed`,a),()=>{r(),n?.(),X.off(`backend.resync.changed`,i),X.off(`pins.changed`,a)}},[o,x,Ge]);let[Ye,Xe]=(0,Z.useState)(null),Ze=`${c.pathname}|${c.search}`;if(Ze!==Ye){Xe(Ze);let{treeName:e,path:t}=ra(c.pathname),n=new URLSearchParams(c.search).get(`layerId`),r=/\/trees\/|\/path(\/|$)/.test(c.pathname)||!!n;xe?Se(!1):E(r||ke?r?Rl(e,n):T:je[0]),se(t),de(t===`/`?null:t)}let{showProgress:Qe}=xn();(0,Z.useEffect)(()=>{o&&Ui(Qe,o)},[o,Qe]);let $e=Ar({workspaceId:o??void 0,treeName:Ll(T),onRefresh:Je}),et=(0,Z.useRef)(new Map);(0,Z.useEffect)(()=>{if(!o)return;let e=`${o}:${T}:${I}`,t=$e;t.canResyncBackend(I)&&(Date.now()-(et.current.get(e)||0)<6e4||(et.current.set(e,Date.now()),t.onResyncBackend?.(I).catch(()=>{})))},[o,T,I,$e]);let tt=new Set(U.map(e=>hr(e.tree,e.path))),nt=Ll(T),rt=(0,Z.useCallback)(e=>tt.has(hr(nt,e)),[U,nt]),it=(0,Z.useCallback)(async e=>{if(!o)return;let t=U.find(t=>hr(t.tree,t.path)===hr(nt,e));t?await ir(o,t.id):await An(o,e,nt),await Ge(o)},[o,U,nt,Ge]),at=(0,Z.useCallback)(async e=>{if(o){ye(t=>t.filter(t=>t.id!==e.id));try{await ir(o,e.id)}finally{await Ge(o)}}},[o,Ge]),ot=(0,Z.useCallback)(async(e,t)=>{if(!o)return;let n=U.find(t=>t.id===e);if(!n)return;let r=U.filter(t=>t.id!==e),i=t===null?r.length:r.findIndex(e=>e.id===t);if(i===-1)return;let a=[...r.slice(0,i),n,...r.slice(i)];if(!a.every((e,t)=>e===U[t])){ye(a);try{ye(await Xn(o,a.map(e=>e.id)))}catch(e){throw await Ge(o),e}}},[o,U,Ge]),st=(0,Z.useCallback)(e=>{if(!o)return;Se(!0),se(e.path),de(null);let t=ia(o,e.path,e.tree);if(i){i.activateRow(`pin:${o}:${e.id}`,e.label||e.name||e.path,t);return}r(t)},[o,r,i]),ct=(0,Z.useCallback)(e=>{!o||e.resolvable===!1||(Se(!1),Ae(!0),E(Rl(e.tree)),se(e.path),de(null),B(``),Oe.current=!0,i?.setFocus(`main`),r(ia(o,e.path,e.tree)))},[o,r,i]),lt=T===`context`?D:T===`directory`?k:T===`backends`?j:null,ut=T===`context`?P:T===`directory`?ne:T===`backends`&&ie;(0,Z.useEffect)(()=>{if(!Oe.current||ut||T===`pins`)return;let e=Ce.current?.querySelector(`[data-active="true"]`);e&&(e.scrollIntoView({block:`nearest`,inline:`nearest`}),Oe.current=!1)},[T,I,lt,ut]);let dt=(0,Z.useCallback)(e=>{Ae(!0),E(e);let t=Te[e];se(t.selectedPath),de(t.contentPath),B(t.searchQuery)},[Te]),ft=(0,Z.useCallback)(e=>{dt(Kc(je,T,e))},[je,T,dt]),mt=Jc(e.m2Open,ft),ht=e=>{de(null),se(e);let t=Ll(T);i?.setFocus(`main`),r(ia(o,e,t))},gt=(0,Z.useCallback)((e,t)=>{se(e),de(e);let n=Ll(T),a=new URLSearchParams;a.set(`layer`,`1`),t&&a.set(`layerId`,t),i?.setFocus(`main`),r(`${ia(o,e,n)}?${a.toString()}`)},[o,T,r,i]),_t=(0,Z.useCallback)((e,t)=>{if(o){if(i){i.openCanvas({kind:`route`,location:ia(o,e,t)});return}window.dispatchEvent(new CustomEvent(`workspace:open-to-side`,{detail:{workspaceName:o,treeName:t,path:e}}))}},[o,i]),vt=(0,Z.useCallback)(async e=>{if(!o)return;let t=Ll(T),n=await Zn(o,e,t),r=`${window.location.origin}${n.url}`;await navigator.clipboard?.writeText(r),alert(`Canvas share link copied:\n${r}`)},[o,T]),yt=z.toLowerCase().trim(),bt=yt?N.filter(e=>e.name.toLowerCase().includes(yt)||(e.label||``).toLowerCase().includes(yt)||(e.description||``).toLowerCase().includes(yt)):N;return(0,Q.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Q.jsx)(Zs,{title:y||o||`Workspace`,icon:C.icon||`ph:stack-fill`,accentColor:C.color,onBack:t,action:(0,Q.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,Q.jsx)(`button`,{type:`button`,onClick:()=>o&&r(va(o)),className:`flex items-center justify-center w-8 h-8 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Open workspace`,children:(0,Q.jsx)(St,{className:`w-3.5 h-3.5`})}),(0,Q.jsx)(`button`,{type:`button`,disabled:!_,onClick:()=>{a?n(`settings`,o??null):s(`/workspaces/${o}/settings/general`)},className:`flex items-center justify-center w-8 h-8 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors disabled:opacity-40 disabled:cursor-not-allowed`,title:_?`Settings`:`Workspace settings require admin access`,children:(0,Q.jsx)(pt,{className:`w-3.5 h-3.5`})})]})}),(0,Q.jsx)(`div`,{...mt,className:`flex border-b border-border shrink-0 touch-pan-y`,"aria-label":`Workspace trees`,children:je.map(e=>(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>dt(e),title:`${Il[e]} — drag to reorder; the first tab opens by default`,"aria-label":Il[e],"aria-pressed":T===e,draggable:!0,onDragStart:t=>{t.dataTransfer.setData(`text/plain`,e),t.dataTransfer.effectAllowed=`move`,Ie(e)},onDragEnd:ze,onDragOver:t=>{if(!Fe||Fe===e)return;t.preventDefault(),t.dataTransfer.dropEffect=`move`;let n=t.currentTarget.getBoundingClientRect(),r=t.clientX<n.left+n.width/2;Re(t=>t?.id===e&&t.before===r?t:{id:e,before:r})},onDrop:e=>{e.preventDefault(),Be()},className:G(`relative flex-1 flex items-center justify-center py-2 transition-colors`,T===e?`text-foreground border-b-2 border-foreground -mb-px`:`text-muted-foreground hover:text-foreground`,Fe===e&&`opacity-40`,Le?.id===e&&Le.before&&`shadow-[inset_2px_0_0_0_hsl(var(--primary))]`,Le?.id===e&&!Le.before&&`shadow-[inset_-2px_0_0_0_hsl(var(--primary))]`),children:[Fl[e],e===`pins`&&U.length>0&&(0,Q.jsx)(`span`,{className:`absolute top-1 right-[calc(50%-14px)] min-w-[14px] h-[14px] px-0.5 rounded-full bg-primary text-primary-foreground text-[9px] leading-[14px] text-center font-medium`,children:U.length})]},e))}),(0,Q.jsx)(`div`,{className:`px-2 py-1.5 border-b border-border shrink-0 shadow-elevation-2 z-10`,children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5 rounded-md border bg-muted/40 px-2 py-1`,children:[(0,Q.jsx)(Jt,{className:`w-3 h-3 shrink-0 text-muted-foreground`}),(0,Q.jsx)(`input`,{type:`search`,name:`workspace-tree-filter`,"aria-label":`Search workspace tree`,autoComplete:`off`,"data-lpignore":`true`,"data-1p-ignore":`true`,className:`flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground min-w-0`,placeholder:T===`layers`?`Search layers…`:T===`pins`?`Search pins…`:`Search paths…`,value:z,onChange:e=>B(e.target.value)})]})}),(0,Q.jsx)(`div`,{ref:Ce,onScroll:e=>{we.current.set(T,e.currentTarget.scrollTop)},className:`flex-1 overflow-y-auto`,children:(0,Q.jsx)(ba,{workspaceId:o,treeName:Ll(T),readOnly:!_,className:`min-h-full`,children:T===`pins`?(0,Q.jsx)(Al,{pins:U,isLoading:W,searchQuery:z,activeKey:hr(l,u),onOpen:st,onShowInTree:ct,onUnpin:at,onMove:ot}):T===`layers`?(0,Q.jsx)(ql,{layers:bt,isLoading:ae,wsName:o??``,onSelect:e=>{let t=new URLSearchParams;t.set(`layerId`,e.id),t.set(`layer`,`1`),r(`${ia(o,`/`)}?${t.toString()}`)},onLock:async e=>{await Hn(o,e.id,o,`context`),qe(o)},onUnlock:async e=>{await cr(o,e.id,o,`context`),qe(o)},onRename:async(e,t)=>{await Yn(o,e.id,t,`context`),qe(o)},onDestroy:async e=>{confirm(`Destroy layer "${e.label||e.name}"? This cannot be undone.`)&&(await zn(o,e.id,`context`),qe(o))}}):(0,Q.jsx)(Tc,{expansionState:Te[T].expansion,root:lt,workspaceId:o??void 0,treeName:T,isBackendsTree:T===`backends`,onRestoreTrash:o?e=>Gi(o,e):void 0,onDiscardTrash:o?e=>Wi(o,e):void 0,onAltSelect:i?e=>_t(e,Ll(T)):void 0,selectedPath:I,contentPath:R,onSelect:ht,onShowContent:T===`context`?gt:void 0,onOpenToSide:_t,onShareCanvas:vt,onNewCanvas:o&&T!==`backends`?e=>{s(`${ia(o,e,T)}?createCanvas=1`)}:void 0,isLoading:ut,rootLabel:o??void 0,searchQuery:z,backends:ce,resyncingPaths:T===`backends`?ue:void 0,onAddRule:o&&T===`backends`?pe:void 0,onAddStoreRule:o?(e,t=`store`)=>{let n=T===`backends`?(()=>{let n=Bi(e);return{kind:t,storeTo:n?.backend||``,storeFolder:n?.rel||``}})():{kind:t,path:`${T===`directory`?`dir`:`ctx`}:${e}`,storeFolder:t===`download`?`Downloads`:zi(e)};s(`/workspaces/${o}/settings/hooks?${qi(n).toString()}`)}:void 0,onStoragePolicy:o&&(T===`context`||T===`directory`)?e=>he(rl(T,e)):void 0,policyBadgeFor:ve,pastedDocumentIds:V?.documentIds,isPathPinned:rt,onTogglePin:o?it:void 0,onPasteDocuments:o&&T===`backends`?async(e,t)=>{let n=sr(e);if(!n)return!1;let r=e.split(`/`).filter(Boolean).slice(2).join(`/`),i=Qe({title:`Moving…`,description:`${t.length} message(s) → ${r}`});try{let{moved:a,results:s}=await Ln(o,n.address,t,e),c=s.filter(e=>!e.ok);return c.length?i.fail({title:`${c.length} message(s) not moved`,description:c[0].error||`Move failed`,variant:`destructive`}):i.done({title:`Moved`,description:`${a} message(s) → ${r}`}),V&&a&&(fe(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}))),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:o,path:`/imap/${n.address}`,treeName:`backends`}})),a>0}catch(e){return i.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to move messages`,variant:`destructive`}),!1}}:o?async(e,t)=>{let n=Mn(T),r=T===`directory`?`directory`:Gn,i=Qe({title:`Pasting…`,description:`${t.length} document(s) → "${e}"`}),a=!1;try{a=await _r(o,e,t,r,n)}catch(e){return i.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}return i.done(a?{title:`Success`,description:`${t.length} document(s) pasted to "${e}"`}:void 0),a&&(V&&(fe(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}))),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:o,path:e,treeName:r}}))),a}:void 0,...$e},T)})}),H&&o&&(0,Q.jsx)(Qc,{workspaceId:o,sourcePath:H,onClose:()=>pe(null),onManageRules:()=>{pe(null),s(`/workspaces/${o}/settings/hooks?section=rules`)}}),me&&o&&(0,Q.jsx)(_l,{workspaceId:o,path:me,onClose:()=>he(null),onSaved:()=>{_e()}})]})}var Vl={canvas:{label:`Canvases`,order:0},dataset:{label:`Datasets`,order:1},context:{label:`Context layers`,order:2},workspace:{label:`Workspaces`,order:3},universe:{label:`Universe`,order:4},label:{label:`Labels`,order:5},system:{label:`System`,order:6}},Hl=100,Ul=e=>e&&e.charAt(0).toUpperCase()+e.slice(1),Wl=e=>Vl[e]??{label:`${Ul(e)} layers`,order:Hl};function Gl({type:e}){return e===`canvas`?(0,Q.jsx)(qe,{className:`w-3.5 h-3.5 shrink-0 text-primary`,"aria-label":`Canvas`}):e===`dataset`?(0,Q.jsx)(Je,{className:`w-3.5 h-3.5 shrink-0 text-secondary`,"aria-label":`Dataset`}):(0,Q.jsx)(xe,{className:`w-3.5 h-3.5 shrink-0 text-muted-foreground/60`,"aria-label":`Layer`})}function Kl(e){let t=new Map;for(let n of e){let e=n.type||`context`,r=t.get(e);r?r.push(n):t.set(e,[n])}return[...t.entries()].map(([e,t])=>({type:e,items:t,meta:Wl(e)})).sort((e,t)=>e.meta.order-t.meta.order||e.meta.label.localeCompare(t.meta.label)).map(({type:e,items:t,meta:n})=>({type:e,label:n.label,items:t}))}function ql({layers:e,isLoading:t,onSelect:n,onLock:r,onUnlock:i,onRename:a,onDestroy:o}){let[s,c]=(0,Z.useState)(null),l=(0,Z.useRef)(null);if((0,Z.useEffect)(()=>{s&&l.current?.focus()},[s]),t)return(0,Q.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading layers…`});if(!e.length)return(0,Q.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`No layers found`});let u=async(e,t)=>{e.stopPropagation();try{await t()}catch(e){alert(e instanceof Error?e.message:String(e))}},d=async(e,t)=>{c(null);let n=t.trim();if(!(!n||n===e.name))try{await a(e,n)}catch(e){alert(e instanceof Error?e.message:String(e))}},f=Kl(e);return(0,Q.jsx)(`div`,{className:`px-2 py-1.5 space-y-2`,children:f.map(e=>(0,Q.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,Q.jsxs)(`div`,{className:`px-1 pt-1 pb-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground`,children:[e.label,(0,Q.jsxs)(`span`,{className:`ml-1 text-muted-foreground/60`,children:[`(`,e.items.length,`)`]})]}),e.items.map(e=>(0,Q.jsxs)(`div`,{className:`group flex items-center gap-2 rounded-l-md px-2 py-1.5 text-xs bg-card shadow-elevation-1 cursor-pointer hover:bg-accent/40 transition-colors`,style:{borderRight:e.color?`4px solid ${e.color}`:`4px solid transparent`},onClick:()=>s!==e.id&&n(e),children:[(0,Q.jsx)(`div`,{className:G(`w-2 h-2 rounded-full shrink-0`,!e.color&&`bg-muted-foreground/20`),style:e.color?{backgroundColor:e.color}:void 0}),(0,Q.jsx)(Gl,{type:e.type}),s===e.id?(0,Q.jsx)(`input`,{ref:l,defaultValue:e.label||e.name,className:`flex-1 bg-transparent outline-none min-w-0 font-medium border-b border-primary`,onClick:e=>e.stopPropagation(),onKeyDown:t=>{t.key===`Enter`&&d(e,t.target.value),t.key===`Escape`&&c(null)},onBlur:t=>d(e,t.target.value)}):(0,Q.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:e.label||e.name}),e.locked&&s!==e.id&&(0,Q.jsx)(Ft,{className:`w-2.5 h-2.5 shrink-0 text-warning group-hover:hidden`}),s!==e.id&&(0,Q.jsxs)(`div`,{className:`flex items-center gap-0.5 reveal-on-hover`,children:[e.locked?(0,Q.jsx)(`button`,{type:`button`,title:`Unlock layer`,className:`p-0.5 rounded hover:bg-muted-foreground/10 text-warning hover:text-foreground touch-target`,onClick:t=>u(t,()=>i(e)),children:(0,Q.jsx)($e,{className:`w-3 h-3`})}):(0,Q.jsx)(`button`,{type:`button`,title:`Lock layer`,className:`p-0.5 rounded hover:bg-muted-foreground/10 text-muted-foreground hover:text-foreground touch-target`,onClick:t=>u(t,()=>r(e)),children:(0,Q.jsx)(Ft,{className:`w-3 h-3`})}),!e.locked&&(0,Q.jsx)(`button`,{type:`button`,title:`Rename layer`,className:`p-0.5 rounded hover:bg-muted-foreground/10 text-muted-foreground hover:text-foreground touch-target`,onClick:t=>{t.stopPropagation(),c(e.id)},children:(0,Q.jsx)(je,{className:`w-3 h-3`})}),!e.locked&&(0,Q.jsx)(`button`,{type:`button`,title:`Destroy layer`,className:`p-0.5 rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive touch-target`,onClick:t=>u(t,()=>o(e)),children:(0,Q.jsx)(Fe,{className:`w-3 h-3`})})]})]},e.id))]},e.type))})}function Jl(){let{state:e,closeM2:t}=la(),n=Fr(),r=m(),i=h(),a=e.selectedEntityId,[o,s]=(0,Z.useState)(null),c=o?.address===a?o.workspace:null,l=c?.label||c?.name,u=Ji(c);(0,Z.useEffect)(()=>{if(!a)return;let e=!1;return Un(a).then(t=>{e||s({address:a,workspace:t})}).catch(()=>{}),()=>{e=!0}},[a]);let d=i.pathname.split(`/`).filter(Boolean),f=d[2]===`settings`?Ac(d[3]):null,p=(0,Z.useMemo)(()=>Oc.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,Q.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,Q.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Q.jsx)(Zs,{title:`Settings: ${l||a||`Workspace`}`,icon:c?.icon||`ph:stack-fill`,accentColor:c?.color,onBack:()=>{n||!a?t():r(`/workspaces/${a}`)},action:(0,Q.jsx)(`button`,{type:`button`,onClick:()=>a&&r(`/workspaces/${a}`),className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground`,title:`Open workspace`,children:(0,Q.jsx)(St,{className:`h-3.5 w-3.5`})})}),u?(0,Q.jsx)(Dc,{items:p,activeId:f,onSelect:e=>a&&r(`/workspaces/${a}/settings/${e}`)}):(0,Q.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:c?`Workspace settings are available to owners and admins.`:`Loading workspace…`})]})}var Yl=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(`
7
7
  `),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}},Xl=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 Yl.handleStreamingResponse(t,{onChunk:e=>{try{Yl.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)}}},Zl=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 Ql(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(`
8
8
  `)||``}function $l(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(`
9
9
  `).trim():``:``}function eu(e){if(!e)return;let t=$l(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 tu(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 nu(e=[]){return e.filter(e=>e?.role===`user`||e?.role===`assistant`).map(e=>({role:e.role,content:Ql(e),timestamp:tu(e.timestamp),...e.role===`assistant`?{metadata:eu(e)}:{}})).filter(e=>e.content||e.metadata?.reasoning)}function ru(e){return{mode:e?.mode,sessionId:e?.sessionId,sessionFile:e?.sessionFile,thinkingLevel:e?.thinkingLevel,model:e?.model,messages:nu(e?.messages||[])}}function iu(e){return{current:ru(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 Zl(e)}catch(e){console.warn(`WebSocket fallback not available:`,e)}}registerAgent(e){if(e.type===`anthropic`){let t=new Xl(e.apiKey||``,e.endpoint||`${J}/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 Y.stream(`${J}/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 Y.get(`${J}/agents`)).agents||[]}catch(e){return console.error(`Failed to fetch available agents:`,e),[]}}async createAgent(e){let t=await Y.post(`${J}/agents`,e);return this.registerAgent(t),t}dispose(){this.connectors.clear(),this.messageCallbacks.clear(),this.wsService&&this.wsService.disconnect()}};async function au(e){return await Y.get(`${J}/agents/${e}/access`)||null}async function ou(e,t,n){return Y.put(`${J}/agents/${e}/access/grants/${encodeURIComponent(t)}`,n)}async function su(e,t){return Y.post(`${J}/agents/${e}/access/grants/${encodeURIComponent(t)}/token`)}async function cu(e,t){return Y.delete(`${J}/agents/${e}/access/grants/${encodeURIComponent(t)}`)}async function lu(e){await Y.delete(`${J}/agents/${e}/access`)}async function uu(e){return await Y.get(`${J}/agents/${e}/tools`)||{tools:[],config:{}}}async function du(){try{return await Y.get(`${J}/agents`)||[]}catch(e){return console.error(`Failed to list agents:`,e),[]}}async function fu(e){return await Y.get(`${J}/agents/${e}`)}async function pu(e){return ru(await Y.get(`${J}/agents/${e}/session`))}async function mu(e){return await Y.get(`${J}/agents/${e}/sessions`)}async function hu(e,t){return iu(await Y.post(`${J}/agents/${e}/sessions`,t))}async function gu(e,t){return iu(await Y.put(`${J}/agents/${e}/session`,t))}async function _u(e,t,n){return iu(await Y.patch(`${J}/agents/${e}/sessions/${t}`,n))}async function vu(e,t){return iu(await Y.delete(`${J}/agents/${e}/sessions/${t}`))}async function yu(e){return await Y.get(`${J}/agents/${e}/skills`)||[]}async function bu(e,t){return await Y.post(`${J}/agents/${e}/skills`,t)||[]}async function xu(e,t){return await Y.delete(`${J}/agents/${e}/skills/${encodeURIComponent(t)}`)||[]}async function Su(e){return await Y.post(`${J}/agents`,e)}async function Cu(e,t){return await Y.put(`${J}/agents/${e}`,t)}async function wu(e){await Y.delete(`${J}/agents/${e}`)}async function Tu(e){return await Y.post(`${J}/agents/${e}/start`)}async function Eu(e){return await Y.post(`${J}/agents/${e}/stop`)}async function Du(e){return await Y.get(`${J}/agents/${e}/status`)}async function Ou(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 Y.stream(`${J}/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(`