@augmentd-labs/canvas-web 2.26.38 → 2.26.39

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 (73) hide show
  1. package/dist/assets/{CalendarApplet-7wqNCpcs.js → CalendarApplet-DVUCGIPB.js} +1 -1
  2. package/dist/assets/{FileForm-C35drQ_R.js → FileForm-CMuWZbUX.js} +1 -1
  3. package/dist/assets/{FiltersApplet-Dh4SUfjN.js → FiltersApplet-CvdFlyn1.js} +1 -1
  4. package/dist/assets/{HomeFab-W7y591CD.js → HomeFab-DRmbW2Uu.js} +1 -1
  5. package/dist/assets/{IdentityFields-DZRqtnIG.js → IdentityFields-C7sv9pMk.js} +1 -1
  6. package/dist/assets/{LensApplet-CddpZXRw.js → LensApplet-gIiGSdLb.js} +1 -1
  7. package/dist/assets/{LinkToCard-BQ1yoFDr.js → LinkToCard-DGpvNE_V.js} +1 -1
  8. package/dist/assets/{NextShell-BfQHKEKO.js → NextShell-DiyMsTp5.js} +1 -1
  9. package/dist/assets/{NotesApplet-Cyuirnp1.js → NotesApplet-BUXkez68.js} +1 -1
  10. package/dist/assets/ObjectPropertiesCard-pE3IL82x.js +8 -0
  11. package/dist/assets/{PathPickerField-B4yFUjgD.js → PathPickerField-D7SubxSh.js} +1 -1
  12. package/dist/assets/{PickDocumentsCard-CFDQL70e.js → PickDocumentsCard-BhJbPlxk.js} +1 -1
  13. package/dist/assets/{SketchApplet-14xrogy3.js → SketchApplet-CQexRECa.js} +1 -1
  14. package/dist/assets/{SketchEditor-B2LYe_MO.js → SketchEditor-DxIN-6wI.js} +1 -1
  15. package/dist/assets/{TerminalApplet-BNeLmNFF.js → TerminalApplet-D-F4-4Zt.js} +1 -1
  16. package/dist/assets/{TextDocumentEditor-CU5ersd_.js → TextDocumentEditor-YAeo69K7.js} +1 -1
  17. package/dist/assets/{TodosApplet-ASG9wXjL.js → TodosApplet-OBi0XUdm.js} +1 -1
  18. package/dist/assets/{TodosWidget-CYK5RbYD.js → TodosWidget-B_R-vHxf.js} +1 -1
  19. package/dist/assets/{UploadProgressList-Ci1akl_D.js → UploadProgressList-C9teR7r-.js} +1 -1
  20. package/dist/assets/{_agentId_-Dy7lgkJK.js → _agentId_-CYfkXrJk.js} +0 -0
  21. package/dist/assets/{_contextId_-BBpL3f_T.js → _contextId_-CkahAS5d.js} +1 -1
  22. package/dist/assets/{_workspaceName_-CU-hpvv7.js → _workspaceName_--lNvJpY1.js} +1 -1
  23. package/dist/assets/{about-Cns4GXCX.js → about-CCShKl-5.js} +1 -1
  24. package/dist/assets/{add-jGjbB0x1.js → add-G2dEzOng.js} +1 -1
  25. package/dist/assets/{agents-DsaNiZJc.js → agents-vx49b2X5.js} +1 -1
  26. package/dist/assets/{appearance-C1xkguK7.js → appearance-Dmzr0s9n.js} +1 -1
  27. package/dist/assets/{applet-target-I8w6EPj0.js → applet-target-DYrCD8BZ.js} +1 -1
  28. package/dist/assets/{apps-BCy4q37-.js → apps-B6DG6ZpO.js} +1 -1
  29. package/dist/assets/{backend-sync-progress-tUU2XWtW.js → backend-sync-progress-m7wUKTJn.js} +1 -1
  30. package/dist/assets/{context-DZ1Hn7tt.js → context-1vR30CeC.js} +1 -1
  31. package/dist/assets/{contexts-Df-cWUlj2.js → contexts-DFYjIhsj2.js} +1 -1
  32. package/dist/assets/{date-time-picker-txVhlNO0.js → date-time-picker-C40sYmga.js} +1 -1
  33. package/dist/assets/{document-CTvT2Qa5.js → document-BiNwuf1n.js} +1 -1
  34. package/dist/assets/document-list-ASCemk7T.js +2 -0
  35. package/dist/assets/{home-C8Wq8hsp.js → home-B1ilyR89.js} +1 -1
  36. package/dist/assets/index-Bi5-zGgp.css +2 -0
  37. package/dist/assets/{index-Cp75myNf.js → index-CXPA9Fj8.js} +4 -4
  38. package/dist/assets/{key-bindings-CA_ePKGA.js → key-bindings-DXepopri.js} +1 -1
  39. package/dist/assets/{offline-sNCjxnp-.js → offline-DonGsRsw.js} +1 -1
  40. package/dist/assets/{public-share-D5yz-Pmo.js → public-share-DLXh7Ie6.js} +1 -1
  41. package/dist/assets/{query-debug-CQ0I3cXX.js → query-debug-DhboV3qX.js} +1 -1
  42. package/dist/assets/{registry-QDfCL8gg.js → registry-eFbDXN9w.js} +2 -2
  43. package/dist/assets/{roles-DoR2drD1.js → roles-DDiKiRii.js} +1 -1
  44. package/dist/assets/{settings-Bz400KLm.js → settings-CcdxMKot.js} +1 -1
  45. package/dist/assets/{settings-aOogFA9n.js → settings-CgjGE01m.js} +1 -1
  46. package/dist/assets/{settings-jIm9JVC-.js → settings-CwyGwKFU.js} +1 -1
  47. package/dist/assets/{settings-tgfewl6I.js → settings-D-yPOLZk.js} +1 -1
  48. package/dist/assets/{share-target-cRZICq5X.js → share-target-BhGDitlj.js} +1 -1
  49. package/dist/assets/{shared-eIOEFQRM.js → shared-DimeKqW8.js} +1 -1
  50. package/dist/assets/{shared-BnpwVpxG.js → shared-XYVtCrC8.js} +1 -1
  51. package/dist/assets/{sketch-lazy-BbNgGbR3.js → sketch-lazy-6eEi8GIA.js} +2 -2
  52. package/dist/assets/{text-documents-BaXhu3ra.js → text-documents-DxVsu9zG.js} +1 -1
  53. package/dist/assets/{tree-folders-cmsIS19Z.js → tree-folders-whK_PK4c.js} +1 -1
  54. package/dist/assets/{use-applet-docs-B2dk__vk.js → use-applet-docs-FqhvvOWx.js} +1 -1
  55. package/dist/assets/{use-applet-target-ffIGaAqT.js → use-applet-target-1DU4mgJH.js} +1 -1
  56. package/dist/assets/{use-canvas-pins-DkWN9oEd.js → use-canvas-pins-DqkSe_aU.js} +1 -1
  57. package/dist/assets/{use-workspace-identity-B8gOMGj4.js → use-workspace-identity-KEG0VpcX.js} +1 -1
  58. package/dist/assets/{useAddTarget-B3b6TyZr.js → useAddTarget-BEgKjqGj.js} +1 -1
  59. package/dist/assets/{useAgentModels-B10Tbl6D.js → useAgentModels-CI7iZlUR.js} +1 -1
  60. package/dist/assets/{useDocumentThumbnail-wW0lSOEy.js → useDocumentThumbnail-DutrNFK3.js} +1 -1
  61. package/dist/assets/{useEditNoteFields-DXLTFEqL.js → useEditNoteFields-HAsbBak7.js} +1 -1
  62. package/dist/assets/{workspace-area-menu-BFw2yUHk.js → workspace-area-menu-CUqTxXmz.js} +1 -1
  63. package/dist/assets/{workspace-content-gate-NLuRPvbm.js → workspace-content-gate-B6T3nLfW.js} +1 -1
  64. package/dist/assets/workspace-cv6Hrfhh.js +1 -0
  65. package/dist/assets/{workspace-import-form-Bb6z42nw.js → workspace-import-form-D5qPcNFq.js} +1 -1
  66. package/dist/assets/{workspaces-DC19HlpI.js → workspaces-yHyufXqs.js} +1 -1
  67. package/dist/index.html +26 -26
  68. package/dist/sw.js +1 -1
  69. package/package.json +2 -2
  70. package/dist/assets/ObjectPropertiesCard-BTTwYnN9.js +0 -8
  71. package/dist/assets/document-list-CQ1_7Sja.js +0 -2
  72. package/dist/assets/index-_0FSwEvG.css +0 -2
  73. package/dist/assets/workspace-BJELPCNs.js +0 -1
@@ -1,9 +1,9 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/apps-BCy4q37-.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-BJELPCNs.js","assets/react-BHzhHVTZ.js","assets/button-SeUZ_Pvi.js","assets/ui-CDoK3F3U.js","assets/input-BOtCd4HP.js","assets/api-CA6WiiYM.js","assets/alert-dialog-CFeuDt0T.js","assets/context-DZ1Hn7tt.js","assets/registry-QDfCL8gg.js","assets/applet-target-I8w6EPj0.js","assets/use-applet-target-ffIGaAqT.js","assets/use-toolbox-Ck_cLGgf.js","assets/workspaces-DC19HlpI.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-DIP1zh7I.js","assets/last-path-BbXWC3b3.js","assets/url-params-n7kU_WZ-.js","assets/page-header-DrDt1sQ2.js","assets/form-panel-3p-ncEVK.js","assets/use-create-panel-DhSNIGtr.js","assets/useSocketSubscription-ifW-vnlb.js","assets/socket-hM4c-ZSl.js","assets/workspace-import-form-Bb6z42nw.js","assets/_workspaceName_-CU-hpvv7.js","assets/socket-CtH3EU9m.js","assets/use-canvas-pins-DkWN9oEd.js","assets/auth-Bx9fAZmz.js","assets/LinkToCard-BQ1yoFDr.js","assets/useEscapeClose-DR_xKT_k.js","assets/useToastHelpers-CRrpIIdY.js","assets/DocumentIcon-9i1uCMQa.js","assets/TodosWidget-CYK5RbYD.js","assets/ObjectPropertiesCard-BTTwYnN9.js","assets/label-BSTdjCWU.js","assets/IdentityFields-DZRqtnIG.js","assets/tags-YamdPoBK.js","assets/useAddTarget-B3b6TyZr.js","assets/date-time-picker-txVhlNO0.js","assets/relation-events-CKio19hE.js","assets/map-BxCwdK0d.js","assets/map-BcsP_QXj.css","assets/public-share-D5yz-Pmo.js","assets/text-documents-BaXhu3ra.js","assets/blobs-WiXP9QRi.js","assets/useDocumentThumbnail-wW0lSOEy.js","assets/markdown-view-BBBZtNSR.js","assets/sanitize-DrVcFY1Q.js","assets/MessageComposerDialog-CdPp-3GR.js","assets/markdown-it-DRESbtwK.js","assets/punycode.es6-ZbLrB_Dn.js","assets/lazy-editor-BUFAkTGl.js","assets/LinkToSidePanel-eCy3nW4R.js","assets/note-save-status-DPz4VzL6.js","assets/useEditNoteFields-DXLTFEqL.js","assets/DocumentBodyEditor-CVO5KPCs.js","assets/use-document-modal-PG8bQyIB.js","assets/sketch-lazy-BbNgGbR3.js","assets/geo-CZfs0E-x.js","assets/ObjectPropertiesCard-Docu7O5V.css","assets/document-list-CQ1_7Sja.js","assets/document-open-mode-DoImW-xs.js","assets/PickDocumentsCard-CFDQL70e.js","assets/backend-sync-progress-tUU2XWtW.js","assets/PathPickerField-B4yFUjgD.js","assets/backend-sync-progress-DU-e9TWi.css","assets/search-COMZIxA7.js","assets/use-sortable-data-BBKmqs79.js","assets/workspace-BydSRtST.js","assets/document-list-DAYdk5vh.css","assets/use-canvas-pins-C57Vbkrq.css","assets/workspace-area-menu-BFw2yUHk.js","assets/workspace-content-gate-NLuRPvbm.js","assets/tree-folders-cmsIS19Z.js","assets/FileForm-C35drQ_R.js","assets/UploadProgressList-Ci1akl_D.js","assets/sha256-65KIjGvZ.js","assets/query-debug-CQ0I3cXX.js","assets/document-CTvT2Qa5.js","assets/use-workspace-identity-B8gOMGj4.js","assets/home-C8Wq8hsp.js","assets/HomeFab-W7y591CD.js","assets/desk-dI_FvLsK.js","assets/share-target-cRZICq5X.js","assets/contexts-Df-cWUlj2.js","assets/_contextId_-BBpL3f_T.js","assets/api-tokens-drrVuCYc.js","assets/use-settings-back-DGmLAD63.js","assets/devices-BwU9M8-W.js","assets/devices-CAa1bRxk.js","assets/settings-aOogFA9n.js","assets/appearance-C1xkguK7.js","assets/use-theme-DaxpiICf.js","assets/key-bindings-CA_ePKGA.js","assets/offline-sNCjxnp-.js","assets/about-Cns4GXCX.js","assets/embedding-BvXcVfij.js","assets/inferd-config-editor-B8x_XPOt.js","assets/shared-eIOEFQRM.js","assets/workspaces-CqHYstZv.js","assets/admin-Bhg9QBHL.js","assets/contexts-DDJagU4j.js","assets/agents-DxqAi3vk.js","assets/logs-DjG8_wJ2.js","assets/roles-p2cRajz-.js","assets/role-C5I0Plgn.js","assets/users-DuVk-TEd.js","assets/embedding-D-I_ygUZ.js","assets/auth-PqttD05H.js","assets/agents-DsaNiZJc.js","assets/useAgentModels-B10Tbl6D.js","assets/_agentId_-Dy7lgkJK.js","assets/settings-tgfewl6I.js","assets/settings-Bz400KLm.js","assets/settings-jIm9JVC-.js","assets/roles-DoR2drD1.js","assets/remotes-RPGcw6fH.js","assets/add-jGjbB0x1.js","assets/NextShell-BfQHKEKO.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{$t as D,Ar as O,B as k,Bn as A,Br as j,Bt as M,C as N,Ct as ee,En as P,F,Fr as te,Ft as ne,Gr as re,Gt as I,H as ie,Hn as ae,Hr as oe,Ht as se,I as L,In as ce,It as le,J as R,Jn as ue,Jr 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,Qr as ye,Qt as be,R as U,Rt as xe,S as Se,Sn as Ce,Sr as we,Tr as Te,Tt as Ee,U as De,Un as Oe,Ur as ke,Ut as Ae,V as je,Vr as Me,Vt as Ne,W as Pe,Wn as Fe,Wr as Ie,X as W,Xt as Le,Yn as Re,Zn as ze,Zr as Be,_ as Ve,_i as He,_n as Ue,_t as We,ai as Ge,an as Ke,b as qe,bn as Je,br as Ye,cn as Xe,cr as Ze,ct as Qe,d as $e,dn as et,ei as tt,er as nt,f as rt,fn as it,fr as at,g as ot,gi as st,gr as ct,gt as lt,h as ut,hn as dt,hr as ft,ht as pt,in as mt,kr as ht,kt as gt,ln as _t,lt as vt,m as yt,mr as bt,mt as xt,nn as St,or as Ct,p as wt,pi as Tt,pn as Et,qn as Dt,rt as Ot,sn as kt,tr as At,tt as jt,u as Mt,ui as Nt,un as Pt,ut as Ft,v as It,vi as Lt,vn as Rt,vr as zt,vt as Bt,w as Vt,x as Ht,xn as Ut,xr as Wt,xt as Gt,y as Kt,yi as qt,yt as Jt,z as Yt,zr as Xt}from"./ui-CDoK3F3U.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-SeUZ_Pvi.js";import{t as en}from"./input-BOtCd4HP.js";import{t as q}from"./label-BSTdjCWU.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-BQ1yoFDr.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-BJELPCNs.js";import{r as vr,t as yr}from"./use-canvas-pins-DkWN9oEd.js";import{a as br,i as xr,n as Sr,o as Cr,r as wr}from"./ObjectPropertiesCard-BTTwYnN9.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-CQ1_7Sja.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-DZRqtnIG.js";import{n as Br,t as Vr}from"./public-share-D5yz-Pmo.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-B3b6TyZr.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-DZ1Hn7tt.js";import{r as fi}from"./relation-events-CKio19hE.js";import{l as pi}from"./date-time-picker-txVhlNO0.js";import{t as mi}from"./PickDocumentsCard-CFDQL70e.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-CdPp-3GR.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-DXLTFEqL.js";import{t as ji}from"./DocumentBodyEditor-CVO5KPCs.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-tUU2XWtW.js";import{t as Ji}from"./workspace-access-C9nZlBBZ.js";import{t as Yi}from"./PathPickerField-B4yFUjgD.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-DIP1zh7I.js";import{n as ha,t as ga}from"./registry-QDfCL8gg.js";import{n as _a}from"./use-applet-target-ffIGaAqT.js";import{r as va,t as ya}from"./last-path-BbXWC3b3.js";import{t as ba}from"./workspace-area-menu-BFw2yUHk.js";import{t as xa}from"./workspace-content-gate-NLuRPvbm.js";import{c as Sa,s as Ca}from"./UploadProgressList-Ci1akl_D.js";import{n as wa,r as Ta,t as Ea}from"./FileForm-C35drQ_R.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.38`,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)(Je,{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)(k,{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)(k,{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)(gt,{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)(zt,{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)(gt,{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-BCy4q37-.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-DC19HlpI.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_-CU-hpvv7.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-CTvT2Qa5.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-C8Wq8hsp.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-cRZICq5X.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-Df-cWUlj2.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_-BBpL3f_T.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-drrVuCYc.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-BwU9M8-W.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-aOogFA9n.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-C1xkguK7.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-CA_ePKGA.js`),__vite__mapDeps([103,1,2,28,3,4,10,8,5,6,97,25,21]))),Ro=(0,Z.lazy)(()=>c(()=>import(`./offline-sNCjxnp-.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-Cns4GXCX.js`),__vite__mapDeps([105,1,2,12,28,3,4,10,8,5,6,97,25,21]))),Bo=(0,Z.lazy)(()=>c(()=>import(`./embedding-BvXcVfij.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-eIOEFQRM.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-CqHYstZv.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-DDJagU4j.js`),__vite__mapDeps([111,1,2,37,6,12,35,32,28,3,4,10,8,5]))),Wo=(0,Z.lazy)(()=>c(()=>import(`./agents-DxqAi3vk.js`),__vite__mapDeps([112,1,2,37,6,12,35,32,28,3,4,10,8,5]))),Go=(0,Z.lazy)(()=>c(()=>import(`./logs-DjG8_wJ2.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-p2cRajz-.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-DuVk-TEd.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-D-I_ygUZ.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-PqttD05H.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-DsaNiZJc.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_-Dy7lgkJK.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-tgfewl6I.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-Bz400KLm.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-jIm9JVC-.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-DoR2drD1.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-RPGcw6fH.js`),__vite__mapDeps([126,2,1,28,3,4,10,8,5,6]))),rs=(0,Z.lazy)(()=>c(()=>import(`./add-jGjbB0x1.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)(k,{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=Se,Ss=N,Cs=Vt,ws=Z.forwardRef(({className:e,sideOffset:t=4,...n},r)=>(0,Q.jsx)(Ht,{children:(0,Q.jsx)(qe,{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=qe.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)(Kt,{ref:n,className:G(`aspect-square h-full w-full`,e),...t}));Es.displayName=Kt.displayName;var Ds=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(It,{ref:n,className:G(`flex h-full w-full items-center justify-center rounded-full bg-muted`,e),...t}));Ds.displayName=It.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)(mt,{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=e.m0Open&&!(e.m1Open&&e.m2Open),d=()=>{r.t1Open?a():i(`tools`),n(),t()},f=(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:[u&&(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`,u?`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)(Ce,{className:`w-5 h-5`}),label:`Contexts`}),(!l.local||l.workspace!==!1)&&(0,Q.jsx)(Os,{section:`workspaces`,icon:(0,Q.jsx)(Ut,{className:`w-5 h-5`}),label:`Workspaces`}),(!l.local||l.agent)&&(0,Q.jsx)(Os,{section:`agents`,icon:(0,Q.jsx)(ye,{className:`w-5 h-5`}),label:`Agents`}),(0,Q.jsx)(Os,{section:`apps`,icon:(0,Q.jsx)(Lt,{className:`w-5 h-5`}),label:`Apps`}),(!l.local||l.workspace!==!1)&&(0,Q.jsx)(ks,{path:`/roles`,section:null,icon:(0,Q.jsx)(Ft,{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)(ie,{className:`w-5 h-5`}),label:`All Users`}),(0,Q.jsx)(ks,{path:`/admin/logs`,icon:(0,Q.jsx)(Ct,{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)(ye,{className:`w-5 h-5`}),label:`All Agents`}),(0,Q.jsx)(ks,{path:`/admin/roles`,icon:(0,Q.jsx)(Ft,{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:d,"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)(U,{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:f,className:`flex items-center justify-center w-10 h-10 rounded-lg text-destructive hover:bg-destructive/10 transition-colors`,children:(0,Q.jsx)(_t,{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)(Tt,{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`?Oe:e.kind===`desktop`?Le:Ce;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)(W,{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`})})}var Ws=`input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="slider"], [role="dialog"], [aria-modal="true"], canvas, video, .canvas-navigation, .react-grid-item, .excalidraw, .xterm, [data-no-navigation-swipe]`;function Gs(e,t){if(e.closest(Ws))return!0;for(let n=e;n;n=n.parentElement){if(n.scrollWidth>n.clientWidth+1&&/auto|scroll/.test(getComputedStyle(n).overflowX))return!0;if(n===t)break}return!1}function Ks(e,t,n){let r=(0,Z.useRef)(null),i=(0,Z.useRef)(0);return{onTouchStart(t){if(r.current=null,!e||t.touches.length!==1||!(t.target instanceof Element)||Gs(t.target,t.currentTarget)||document.querySelector(`[aria-modal="true"], dialog[open]`))return;let n=t.touches[0];n.clientX<24||n.clientX>window.innerWidth-24||(r.current={x:n.clientX,y:n.clientY,time:Date.now()})},onTouchMove(e){r.current&&(e.touches.length!==1||Math.abs(e.touches[0].clientY-r.current.y)>40)&&(r.current=null)},onTouchCancel(){r.current=null},onTouchEnd(a){let o=r.current;if(r.current=null,!e||!o||!a.changedTouches.length)return;let s=a.changedTouches[0].clientX-o.x,c=a.changedTouches[0].clientY-o.y;Date.now()-o.time>800||Math.abs(s)<80||Math.abs(s)<Math.abs(c)*2||t===`right`==s>0&&(i.current=Date.now()+500,a.stopPropagation(),n())},onClickCapture(e){Date.now()<i.current&&(e.preventDefault(),e.stopPropagation())}}}function qs(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 Js(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 Ys(e,t,n){let r=[...e],[i]=r.splice(t,1);return r.splice(n,0,i),r}async function Xs(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 Zs(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 Qs(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)(()=>Js(t),[t]),isLoading:r,refresh:l}}function $s(){let{state:e,selectEntity:t,openM2:n,closeM2:r}=la(),a=Fr(),{contexts:o,isLoading:s}=Qs(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}=Zs((e,t)=>{let n=Ys(f,e,t);d({base:o,order:n}),Xs(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)(ae,{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)(Rt,{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 ec({title:e,onBack:t,backLabel:n=`Back to previous view`,action:r,className:a,icon:o,accentColor:s}){let{closeM1:c}=la(),l=Si(s);return(0,Q.jsxs)(`div`,{className:G(`flex items-center h-12 px-2 border-b border-border shrink-0 gap-1`,a),style:{borderBottomWidth:4,...l?{borderBottomColor:l}:{}},children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:t,className:`flex items-center gap-0.5 h-11 rounded px-1 hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors flex-1 min-w-0`,title:n,"aria-label":n,children:[(0,Q.jsx)(oe,{className:`w-4 h-4 shrink-0`}),o&&(0,Q.jsx)(i,{icon:o,width:16,height:16,color:l,className:G(`mr-1 shrink-0`,!l&&`text-muted-foreground`)}),(0,Q.jsx)(`span`,{className:`text-sm font-semibold truncate`,children:e})]}),r&&(0,Q.jsx)(`div`,{className:`shrink-0`,children:r}),(0,Q.jsx)(`button`,{type:`button`,onClick:c,className:`flex h-11 w-11 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 tc(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 nc(e){let t=[...e];return t.filter(e=>!t.some(t=>t!==e&&e.startsWith(`${t}/`)))}var rc=e(s(),1),ic=180;function ac({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,ic),[_,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,rc.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)(Et,{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 oc=[{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.`}],sc=`canvas:treeStyle`;function cc(){try{let e=localStorage.getItem(sc);return e===`accordion`||e===`accordion-mobile`?e:`cards`}catch{return`cards`}}var lc=cc(),uc=new Set;function dc(){return lc}function fc(e){try{e===`cards`?localStorage.removeItem(sc):localStorage.setItem(sc,e)}catch{}lc=e;for(let e of uc)e()}function pc(e){uc.add(e);let t=t=>{(t.key===sc||t.key===null)&&(lc=cc(),e())};return window.addEventListener(`storage`,t),()=>{uc.delete(e),window.removeEventListener(`storage`,t)}}function mc(){return(0,Z.useSyncExternalStore)(pc,dc,()=>`cards`)}function hc(){let e=mc(),t=Fr();return e===`accordion`||e===`accordion-mobile`&&t}var gc=22,_c=44,vc=4;function yc(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 bc(e,t){return!t||sr(e)!==null}var xc=e=>Array.from(e.dataTransfer.types).includes(`application/json`);function Sc(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 Cc({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:k,onSubtractDown:j,onResyncBackend:M,canResyncBackend:N,onAddRule:ee,onAddStoreRule:P,onStoragePolicy:F,onRenameBackendFolder:te,onDeleteBackendFolder:ne,onRestoreTrash:re,onDiscardTrash:ie,onCopy:ae,onCut:oe,onPaste:se,pastedDocumentIds:L,onPasteDocuments:ce,isPinned:le,onTogglePin:R}){let de=u&&d.size>0&&u.path===r,z=!i&&(k||j)&&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)(W,{className:`h-3 w-3`}),`Open Trash`,async()=>c(r)),r!==`/Trash`&&re&&H((0,Q.jsx)(Ee,{className:`h-3 w-3`}),`Restore original paths`,()=>re(r)),r!==`/Trash`&&ie&&H((0,Q.jsx)(W,{className:`h-3 w-3`}),`Empty Trash`,()=>ie(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)(at,{className:`w-3 h-3`}),`Show layer content`,async()=>{c(r,n.id||void 0)}),l&&H((0,Q.jsx)(at,{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)(xt,{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)??!!Sc(r,i))&&(0,Q.jsxs)(Q.Fragment,{children:[H((0,Q.jsx)(gt,{className:`w-3 h-3`}),`Refresh backend`,async()=>{await M(r)}),(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),i&&Sc(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&&yc(r,i)&&H((0,Q.jsx)(A,{className:`w-3 h-3`}),`Create storage rule…`,async()=>{P(r)}),(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),!i&&(P||F)&&r!==`/`&&(0,Q.jsxs)(Q.Fragment,{children:[P&&H((0,Q.jsx)(A,{className:`w-3 h-3`}),`Create rule…`,async()=>{P(r)}),P&&H((0,Q.jsx)(zt,{className:`w-3 h-3`}),`Create download rule…`,async()=>{P(r,`download`)}),F&&n.type!==`canvas`&&H((0,Q.jsx)(ue,{className:`w-3 h-3`}),`Storage policy…`,async()=>{F(r)}),(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),(!i||yc(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`]}),te&&yc(r,i)?.key&&H((0,Q.jsx)(Ne,{className:`w-3 h-3`}),`Rename folder`,async()=>{let e=r.split(`/`).pop()||``,t=prompt(`New folder name:`,e);!t||t===e||await te(r,t)}),ne&&i&&tr(r,o)&&H((0,Q.jsx)(W,{className:`w-3 h-3`}),`Delete from backend`,async()=>{confirm(`Delete folder "${r.split(`/`).pop()}" and its contents from the backend?`)&&await ne(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)(Je,{className:`w-3 h-3 text-primary`}),`New canvas here…`]}),r!==`/`&&R&&H(le?(0,Q.jsx)(xe,{className:`w-3 h-3`}):(0,Q.jsx)(V,{className:`w-3 h-3`}),le?`Unpin`:`Pin`,async()=>{await R()}),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)(I,{className:`w-3 h-3`}),`Change icon`]}),r!==`/`&&!n.locked&&v&&!i&&H((0,Q.jsx)(Ne,{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)(Te,{className:`w-3 h-3`}),`Copy`,async()=>ae(r)),!i&&H((0,Q.jsx)(Gt,{className:`w-3 h-3`}),`Cut`,async()=>oe(r)),f&&!i&&H((0,Q.jsx)(O,{className:`w-3 h-3`}),`Paste (${f.mode})`,async()=>se(r)),L&&L.length>0&&ce&&bc(r,i)&&H((0,Q.jsx)(O,{className:`w-3 h-3`}),i?`Move ${L.length} message(s) here`:`Paste ${L.length} document(s)`,async()=>{await ce(r,L)}),x&&H((0,Q.jsx)(Dt,{className:`w-3 h-3`}),`Import documents…`,()=>x(r)),S&&H((0,Q.jsx)(zt,{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)(zt,{className:`w-3 h-3`}),`Export subtree…`,()=>y(r)),b&&!i&&n.type!==`canvas`&&H((0,Q.jsx)(Dt,{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)(W,{className:`w-3 h-3`}),`Remove`,async()=>{confirm(`Remove "${r}"${a?` and all children`:``}?`)&&await _(r,a)},!0),!a&&H((0,Q.jsx)(W,{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)(et,{className:`w-3 h-3`}),`Unlock layer`,async()=>{await w(n.id)}):C&&H((0,Q.jsx)(Pt,{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)(et,{className:`w-3 h-3`})})]},e))]}),r!==`/`&&!n.locked&&T&&H((0,Q.jsx)(W,{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`}),k&&H((0,Q.jsx)(st,{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 k(r)}),j&&H((0,Q.jsx)(Nt,{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 j(r)})]}),de&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`}),E&&H((0,Q.jsx)(Ce,{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-B6DG6ZpO.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-cv6Hrfhh.js","assets/react-BHzhHVTZ.js","assets/button-SeUZ_Pvi.js","assets/ui-CDoK3F3U.js","assets/input-BOtCd4HP.js","assets/api-CA6WiiYM.js","assets/alert-dialog-CFeuDt0T.js","assets/context-1vR30CeC.js","assets/registry-eFbDXN9w.js","assets/applet-target-DYrCD8BZ.js","assets/use-applet-target-1DU4mgJH.js","assets/use-toolbox-Ck_cLGgf.js","assets/workspaces-yHyufXqs.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-DIP1zh7I.js","assets/last-path-BbXWC3b3.js","assets/url-params-n7kU_WZ-.js","assets/page-header-DrDt1sQ2.js","assets/form-panel-3p-ncEVK.js","assets/use-create-panel-DhSNIGtr.js","assets/useSocketSubscription-ifW-vnlb.js","assets/socket-hM4c-ZSl.js","assets/workspace-import-form-D5qPcNFq.js","assets/_workspaceName_--lNvJpY1.js","assets/socket-CtH3EU9m.js","assets/use-canvas-pins-DqkSe_aU.js","assets/auth-Bx9fAZmz.js","assets/LinkToCard-DGpvNE_V.js","assets/useEscapeClose-DR_xKT_k.js","assets/useToastHelpers-CRrpIIdY.js","assets/DocumentIcon-9i1uCMQa.js","assets/TodosWidget-B_R-vHxf.js","assets/ObjectPropertiesCard-pE3IL82x.js","assets/label-BSTdjCWU.js","assets/IdentityFields-C7sv9pMk.js","assets/tags-YamdPoBK.js","assets/useAddTarget-BEgKjqGj.js","assets/date-time-picker-C40sYmga.js","assets/relation-events-CKio19hE.js","assets/map-BxCwdK0d.js","assets/map-BcsP_QXj.css","assets/public-share-DLXh7Ie6.js","assets/text-documents-DxVsu9zG.js","assets/blobs-WiXP9QRi.js","assets/useDocumentThumbnail-DutrNFK3.js","assets/markdown-view-BBBZtNSR.js","assets/sanitize-DrVcFY1Q.js","assets/MessageComposerDialog-CdPp-3GR.js","assets/markdown-it-DRESbtwK.js","assets/punycode.es6-ZbLrB_Dn.js","assets/lazy-editor-BUFAkTGl.js","assets/LinkToSidePanel-eCy3nW4R.js","assets/note-save-status-DPz4VzL6.js","assets/useEditNoteFields-HAsbBak7.js","assets/DocumentBodyEditor-CVO5KPCs.js","assets/use-document-modal-PG8bQyIB.js","assets/sketch-lazy-6eEi8GIA.js","assets/geo-CZfs0E-x.js","assets/ObjectPropertiesCard-Docu7O5V.css","assets/document-list-ASCemk7T.js","assets/document-open-mode-DoImW-xs.js","assets/PickDocumentsCard-BhJbPlxk.js","assets/backend-sync-progress-m7wUKTJn.js","assets/PathPickerField-D7SubxSh.js","assets/backend-sync-progress-DU-e9TWi.css","assets/search-COMZIxA7.js","assets/use-sortable-data-BBKmqs79.js","assets/workspace-BydSRtST.js","assets/document-list-DAYdk5vh.css","assets/use-canvas-pins-C57Vbkrq.css","assets/workspace-area-menu-CUqTxXmz.js","assets/workspace-content-gate-B6T3nLfW.js","assets/tree-folders-whK_PK4c.js","assets/FileForm-CMuWZbUX.js","assets/UploadProgressList-C9teR7r-.js","assets/sha256-65KIjGvZ.js","assets/query-debug-DhboV3qX.js","assets/document-BiNwuf1n.js","assets/use-workspace-identity-KEG0VpcX.js","assets/home-B1ilyR89.js","assets/HomeFab-DRmbW2Uu.js","assets/desk-dI_FvLsK.js","assets/share-target-BhGDitlj.js","assets/contexts-DFYjIhsj2.js","assets/_contextId_-CkahAS5d.js","assets/api-tokens-drrVuCYc.js","assets/use-settings-back-DGmLAD63.js","assets/devices-BwU9M8-W.js","assets/devices-CAa1bRxk.js","assets/settings-CgjGE01m.js","assets/appearance-Dmzr0s9n.js","assets/use-theme-DaxpiICf.js","assets/key-bindings-DXepopri.js","assets/offline-DonGsRsw.js","assets/about-CCShKl-5.js","assets/embedding-BvXcVfij.js","assets/inferd-config-editor-B8x_XPOt.js","assets/shared-DimeKqW8.js","assets/workspaces-CqHYstZv.js","assets/admin-Bhg9QBHL.js","assets/contexts-DDJagU4j.js","assets/agents-DxqAi3vk.js","assets/logs-DjG8_wJ2.js","assets/roles-p2cRajz-.js","assets/role-C5I0Plgn.js","assets/users-DuVk-TEd.js","assets/embedding-D-I_ygUZ.js","assets/auth-PqttD05H.js","assets/agents-vx49b2X5.js","assets/useAgentModels-CI7iZlUR.js","assets/_agentId_-CYfkXrJk.js","assets/settings-D-yPOLZk.js","assets/settings-CcdxMKot.js","assets/settings-CwyGwKFU.js","assets/roles-DDiKiRii.js","assets/remotes-RPGcw6fH.js","assets/add-G2dEzOng.js","assets/NextShell-DiyMsTp5.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{$t as D,Ar as O,B as k,Bn as A,Br as j,Bt as M,C as N,Ct as ee,En as P,F,Fr as te,Ft as ne,Gr as re,Gt as I,H as ie,Hn as ae,Hr as oe,Ht as se,I as L,In as ce,It as le,J as R,Jn as ue,Jr 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,Qr as ye,Qt as be,R as U,Rt as xe,S as Se,Sn as Ce,Sr as we,Tr as Te,Tt as Ee,U as De,Un as Oe,Ur as ke,Ut as Ae,V as je,Vr as Me,Vt as Ne,W as Pe,Wn as Fe,Wr as Ie,X as W,Xt as Le,Yn as Re,Zn as ze,Zr as Be,_ as Ve,_i as He,_n as Ue,_t as We,ai as Ge,an as Ke,b as qe,bn as Je,br as Ye,cn as Xe,cr as Ze,ct as Qe,d as $e,dn as et,ei as tt,er as nt,f as rt,fn as it,fr as at,g as ot,gi as st,gr as ct,gt as lt,h as ut,hn as dt,hr as ft,ht as pt,in as mt,kr as ht,kt as gt,ln as _t,lt as vt,m as yt,mr as bt,mt as xt,nn as St,or as Ct,p as wt,pi as Tt,pn as Et,qn as Dt,rt as Ot,sn as kt,tr as At,tt as jt,u as Mt,ui as Nt,un as Pt,ut as Ft,v as It,vi as Lt,vn as Rt,vr as zt,vt as Bt,w as Vt,x as Ht,xn as Ut,xr as Wt,xt as Gt,y as Kt,yi as qt,yt as Jt,z as Yt,zr as Xt}from"./ui-CDoK3F3U.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-SeUZ_Pvi.js";import{t as en}from"./input-BOtCd4HP.js";import{t as q}from"./label-BSTdjCWU.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-DGpvNE_V.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-cv6Hrfhh.js";import{r as vr,t as yr}from"./use-canvas-pins-DqkSe_aU.js";import{a as br,i as xr,n as Sr,o as Cr,r as wr}from"./ObjectPropertiesCard-pE3IL82x.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-ASCemk7T.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-C7sv9pMk.js";import{n as Br,t as Vr}from"./public-share-DLXh7Ie6.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-BEgKjqGj.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-1vR30CeC.js";import{r as fi}from"./relation-events-CKio19hE.js";import{l as pi}from"./date-time-picker-C40sYmga.js";import{t as mi}from"./PickDocumentsCard-BhJbPlxk.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-CdPp-3GR.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-HAsbBak7.js";import{t as ji}from"./DocumentBodyEditor-CVO5KPCs.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-m7wUKTJn.js";import{t as Ji}from"./workspace-access-C9nZlBBZ.js";import{t as Yi}from"./PathPickerField-D7SubxSh.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-DIP1zh7I.js";import{n as ha,t as ga}from"./registry-eFbDXN9w.js";import{n as _a}from"./use-applet-target-1DU4mgJH.js";import{r as va,t as ya}from"./last-path-BbXWC3b3.js";import{t as ba}from"./workspace-area-menu-CUqTxXmz.js";import{t as xa}from"./workspace-content-gate-B6T3nLfW.js";import{c as Sa,s as Ca}from"./UploadProgressList-C9teR7r-.js";import{n as wa,r as Ta,t as Ea}from"./FileForm-CMuWZbUX.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.39`,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)(Je,{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)(k,{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)(k,{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)(gt,{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)(zt,{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)(gt,{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-B6DG6ZpO.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-yHyufXqs.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_--lNvJpY1.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-BiNwuf1n.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-B1ilyR89.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-BhGDitlj.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-DFYjIhsj2.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_-CkahAS5d.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-drrVuCYc.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-BwU9M8-W.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-CgjGE01m.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-Dmzr0s9n.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-DXepopri.js`),__vite__mapDeps([103,1,2,28,3,4,10,8,5,6,97,25,21]))),Ro=(0,Z.lazy)(()=>c(()=>import(`./offline-DonGsRsw.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-CCShKl-5.js`),__vite__mapDeps([105,1,2,12,28,3,4,10,8,5,6,97,25,21]))),Bo=(0,Z.lazy)(()=>c(()=>import(`./embedding-BvXcVfij.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-DimeKqW8.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-CqHYstZv.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-DDJagU4j.js`),__vite__mapDeps([111,1,2,37,6,12,35,32,28,3,4,10,8,5]))),Wo=(0,Z.lazy)(()=>c(()=>import(`./agents-DxqAi3vk.js`),__vite__mapDeps([112,1,2,37,6,12,35,32,28,3,4,10,8,5]))),Go=(0,Z.lazy)(()=>c(()=>import(`./logs-DjG8_wJ2.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-p2cRajz-.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-DuVk-TEd.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-D-I_ygUZ.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-PqttD05H.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-vx49b2X5.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_-CYfkXrJk.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-D-yPOLZk.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-CcdxMKot.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-CwyGwKFU.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-DDiKiRii.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-RPGcw6fH.js`),__vite__mapDeps([126,2,1,28,3,4,10,8,5,6]))),rs=(0,Z.lazy)(()=>c(()=>import(`./add-G2dEzOng.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)(k,{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=Se,Ss=N,Cs=Vt,ws=Z.forwardRef(({className:e,sideOffset:t=4,...n},r)=>(0,Q.jsx)(Ht,{children:(0,Q.jsx)(qe,{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=qe.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)(Kt,{ref:n,className:G(`aspect-square h-full w-full`,e),...t}));Es.displayName=Kt.displayName;var Ds=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(It,{ref:n,className:G(`flex h-full w-full items-center justify-center rounded-full bg-muted`,e),...t}));Ds.displayName=It.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)(mt,{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=e.m0Open&&!(e.m1Open&&e.m2Open),d=()=>{r.t1Open?a():i(`tools`),n(),t()},f=(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:[u&&(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`,u?`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)(Ce,{className:`w-5 h-5`}),label:`Contexts`}),(!l.local||l.workspace!==!1)&&(0,Q.jsx)(Os,{section:`workspaces`,icon:(0,Q.jsx)(Ut,{className:`w-5 h-5`}),label:`Workspaces`}),(!l.local||l.agent)&&(0,Q.jsx)(Os,{section:`agents`,icon:(0,Q.jsx)(ye,{className:`w-5 h-5`}),label:`Agents`}),(0,Q.jsx)(Os,{section:`apps`,icon:(0,Q.jsx)(Lt,{className:`w-5 h-5`}),label:`Apps`}),(!l.local||l.workspace!==!1)&&(0,Q.jsx)(ks,{path:`/roles`,section:null,icon:(0,Q.jsx)(Ft,{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)(ie,{className:`w-5 h-5`}),label:`All Users`}),(0,Q.jsx)(ks,{path:`/admin/logs`,icon:(0,Q.jsx)(Ct,{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)(ye,{className:`w-5 h-5`}),label:`All Agents`}),(0,Q.jsx)(ks,{path:`/admin/roles`,icon:(0,Q.jsx)(Ft,{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:d,"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)(U,{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:f,className:`flex items-center justify-center w-10 h-10 rounded-lg text-destructive hover:bg-destructive/10 transition-colors`,children:(0,Q.jsx)(_t,{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)(Tt,{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`?Oe:e.kind===`desktop`?Le:Ce;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)(W,{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`})})}var Ws=`input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="slider"], [role="dialog"], [aria-modal="true"], canvas, video, .canvas-navigation, .react-grid-item, .excalidraw, .xterm, [data-no-navigation-swipe]`;function Gs(e,t){if(e.closest(Ws))return!0;for(let n=e;n;n=n.parentElement){if(n.scrollWidth>n.clientWidth+1&&/auto|scroll/.test(getComputedStyle(n).overflowX))return!0;if(n===t)break}return!1}function Ks(e,t,n){let r=(0,Z.useRef)(null),i=(0,Z.useRef)(0);return{onTouchStart(t){if(r.current=null,!e||t.touches.length!==1||!(t.target instanceof Element)||Gs(t.target,t.currentTarget)||document.querySelector(`[aria-modal="true"], dialog[open]`))return;let n=t.touches[0];n.clientX<24||n.clientX>window.innerWidth-24||(r.current={x:n.clientX,y:n.clientY,time:Date.now()})},onTouchMove(e){r.current&&(e.touches.length!==1||Math.abs(e.touches[0].clientY-r.current.y)>40)&&(r.current=null)},onTouchCancel(){r.current=null},onTouchEnd(a){let o=r.current;if(r.current=null,!e||!o||!a.changedTouches.length)return;let s=a.changedTouches[0].clientX-o.x,c=a.changedTouches[0].clientY-o.y;Date.now()-o.time>800||Math.abs(s)<80||Math.abs(s)<Math.abs(c)*2||t===`right`==s>0&&(i.current=Date.now()+500,a.stopPropagation(),n())},onClickCapture(e){Date.now()<i.current&&(e.preventDefault(),e.stopPropagation())}}}function qs(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 Js(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 Ys(e,t,n){let r=[...e],[i]=r.splice(t,1);return r.splice(n,0,i),r}async function Xs(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 Zs(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 Qs(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)(()=>Js(t),[t]),isLoading:r,refresh:l}}function $s(){let{state:e,selectEntity:t,openM2:n,closeM2:r}=la(),a=Fr(),{contexts:o,isLoading:s}=Qs(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}=Zs((e,t)=>{let n=Ys(f,e,t);d({base:o,order:n}),Xs(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)(ae,{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)(Rt,{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 ec({title:e,onBack:t,backLabel:n=`Back to previous view`,action:r,className:a,icon:o,accentColor:s}){let{closeM1:c}=la(),l=Si(s);return(0,Q.jsxs)(`div`,{className:G(`flex items-center h-12 px-2 border-b border-border shrink-0 gap-1`,a),style:{borderBottomWidth:4,...l?{borderBottomColor:l}:{}},children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:t,className:`flex items-center gap-0.5 h-11 rounded px-1 hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors flex-1 min-w-0`,title:n,"aria-label":n,children:[(0,Q.jsx)(oe,{className:`w-4 h-4 shrink-0`}),o&&(0,Q.jsx)(i,{icon:o,width:16,height:16,color:l,className:G(`mr-1 shrink-0`,!l&&`text-muted-foreground`)}),(0,Q.jsx)(`span`,{className:`text-sm font-semibold truncate`,children:e})]}),r&&(0,Q.jsx)(`div`,{className:`shrink-0`,children:r}),(0,Q.jsx)(`button`,{type:`button`,onClick:c,className:`flex h-11 w-11 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 tc(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 nc(e){let t=[...e];return t.filter(e=>!t.some(t=>t!==e&&e.startsWith(`${t}/`)))}var rc=e(s(),1),ic=180;function ac({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,ic),[_,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,rc.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)(Et,{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 oc=[{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.`}],sc=`canvas:treeStyle`;function cc(){try{let e=localStorage.getItem(sc);return e===`accordion`||e===`accordion-mobile`?e:`cards`}catch{return`cards`}}var lc=cc(),uc=new Set;function dc(){return lc}function fc(e){try{e===`cards`?localStorage.removeItem(sc):localStorage.setItem(sc,e)}catch{}lc=e;for(let e of uc)e()}function pc(e){uc.add(e);let t=t=>{(t.key===sc||t.key===null)&&(lc=cc(),e())};return window.addEventListener(`storage`,t),()=>{uc.delete(e),window.removeEventListener(`storage`,t)}}function mc(){return(0,Z.useSyncExternalStore)(pc,dc,()=>`cards`)}function hc(){let e=mc(),t=Fr();return e===`accordion`||e===`accordion-mobile`&&t}var gc=22,_c=44,vc=4;function yc(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 bc(e,t){return!t||sr(e)!==null}var xc=e=>Array.from(e.dataTransfer.types).includes(`application/json`);function Sc(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 Cc({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:k,onSubtractDown:j,onResyncBackend:M,canResyncBackend:N,onAddRule:ee,onAddStoreRule:P,onStoragePolicy:F,onRenameBackendFolder:te,onDeleteBackendFolder:ne,onRestoreTrash:re,onDiscardTrash:ie,onCopy:ae,onCut:oe,onPaste:se,pastedDocumentIds:L,onPasteDocuments:ce,isPinned:le,onTogglePin:R}){let de=u&&d.size>0&&u.path===r,z=!i&&(k||j)&&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)(W,{className:`h-3 w-3`}),`Open Trash`,async()=>c(r)),r!==`/Trash`&&re&&H((0,Q.jsx)(Ee,{className:`h-3 w-3`}),`Restore original paths`,()=>re(r)),r!==`/Trash`&&ie&&H((0,Q.jsx)(W,{className:`h-3 w-3`}),`Empty Trash`,()=>ie(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)(at,{className:`w-3 h-3`}),`Show layer content`,async()=>{c(r,n.id||void 0)}),l&&H((0,Q.jsx)(at,{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)(xt,{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)??!!Sc(r,i))&&(0,Q.jsxs)(Q.Fragment,{children:[H((0,Q.jsx)(gt,{className:`w-3 h-3`}),`Refresh backend`,async()=>{await M(r)}),(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),i&&Sc(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&&yc(r,i)&&H((0,Q.jsx)(A,{className:`w-3 h-3`}),`Create storage rule…`,async()=>{P(r)}),(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),!i&&(P||F)&&r!==`/`&&(0,Q.jsxs)(Q.Fragment,{children:[P&&H((0,Q.jsx)(A,{className:`w-3 h-3`}),`Create rule…`,async()=>{P(r)}),P&&H((0,Q.jsx)(zt,{className:`w-3 h-3`}),`Create download rule…`,async()=>{P(r,`download`)}),F&&n.type!==`canvas`&&H((0,Q.jsx)(ue,{className:`w-3 h-3`}),`Storage policy…`,async()=>{F(r)}),(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),(!i||yc(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`]}),te&&yc(r,i)?.key&&H((0,Q.jsx)(Ne,{className:`w-3 h-3`}),`Rename folder`,async()=>{let e=r.split(`/`).pop()||``,t=prompt(`New folder name:`,e);!t||t===e||await te(r,t)}),ne&&i&&tr(r,o)&&H((0,Q.jsx)(W,{className:`w-3 h-3`}),`Delete from backend`,async()=>{confirm(`Delete folder "${r.split(`/`).pop()}" and its contents from the backend?`)&&await ne(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)(Je,{className:`w-3 h-3 text-primary`}),`New canvas here…`]}),r!==`/`&&R&&H(le?(0,Q.jsx)(xe,{className:`w-3 h-3`}):(0,Q.jsx)(V,{className:`w-3 h-3`}),le?`Unpin`:`Pin`,async()=>{await R()}),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)(I,{className:`w-3 h-3`}),`Change icon`]}),r!==`/`&&!n.locked&&v&&!i&&H((0,Q.jsx)(Ne,{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)(Te,{className:`w-3 h-3`}),`Copy`,async()=>ae(r)),!i&&H((0,Q.jsx)(Gt,{className:`w-3 h-3`}),`Cut`,async()=>oe(r)),f&&!i&&H((0,Q.jsx)(O,{className:`w-3 h-3`}),`Paste (${f.mode})`,async()=>se(r)),L&&L.length>0&&ce&&bc(r,i)&&H((0,Q.jsx)(O,{className:`w-3 h-3`}),i?`Move ${L.length} message(s) here`:`Paste ${L.length} document(s)`,async()=>{await ce(r,L)}),x&&H((0,Q.jsx)(Dt,{className:`w-3 h-3`}),`Import documents…`,()=>x(r)),S&&H((0,Q.jsx)(zt,{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)(zt,{className:`w-3 h-3`}),`Export subtree…`,()=>y(r)),b&&!i&&n.type!==`canvas`&&H((0,Q.jsx)(Dt,{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)(W,{className:`w-3 h-3`}),`Remove`,async()=>{confirm(`Remove "${r}"${a?` and all children`:``}?`)&&await _(r,a)},!0),!a&&H((0,Q.jsx)(W,{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)(et,{className:`w-3 h-3`}),`Unlock layer`,async()=>{await w(n.id)}):C&&H((0,Q.jsx)(Pt,{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)(et,{className:`w-3 h-3`})})]},e))]}),r!==`/`&&!n.locked&&T&&H((0,Q.jsx)(W,{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`}),k&&H((0,Q.jsx)(st,{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 k(r)}),j&&H((0,Q.jsx)(Nt,{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 j(r)})]}),de&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`my-1 h-px bg-border`}),E&&H((0,Q.jsx)(Ce,{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)(Ce,{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&&!de&&(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 wc({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)(Me,{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 Tc(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function Ec(e,t,n){let r=Tc(t,e.name);return r.toLowerCase().includes(n)||(e.label||``).toLowerCase().includes(n)?!0:e.children?.some(e=>Ec(e,r,n))??!1}function Dc({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:F,accordion:te=!1,trail:ne=[]}){let re=Er(),I=Tc(n,t.name),ie=P?.(I)??null,ae=T.get(I)??xi(t),[oe,se]=(0,Z.useState)(()=>e?.get(t.id||I)??(o!==`/`&&(o===I||o.startsWith(I+`/`)))),[L,ce]=(0,Z.useState)(o);if(L!==o&&(ce(o),o!==`/`&&o.startsWith(I+`/`)&&se(!0)),(0,Z.useEffect)(()=>{e?.set(t.id||I,oe)},[e,t.id,I,oe]),p&&!Ec(t,n,p))return null;let le=oe||m===I||p.length>0,R=t.children&&t.children.length>0,de=o===I||_.has(I),z=s===I,B=u?.path===I,V=d.has(I),fe=t.type===`canvas`,H=e=>{if(e.shiftKey){v(I,e);return}if(e.ctrlKey||e.metaKey){b(I,t.id);return}if(e.altKey&&g){g(I);return}h(I)},pe=e=>{!R||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=[...ne].reverse().find(Boolean)??null,he=ae.color||me,ge=te?[...ne,he]:ne,_e=o!==`/`&&o.startsWith(I+`/`),ve=!B&&!V,ye=ve&&de,be=(e,t)=>`color-mix(in oklab, ${e} ${t}%, var(--card))`,U=e=>`color-mix(in oklab, currentColor ${e}%, transparent)`,xe=Math.min(r,5),Se=le&&!!R,Ce=ve&&!ye&&!t.locked&&Se,we=Math.min(3+xe*2+(_e?4:0)+(z?3:0),18),Te=ye?`var(--primary)`:B?be(`var(--info)`,12):V?be(`var(--warning)`,12):Ce?`var(--accent)`:be(`var(--muted-foreground)`,we),Ee=ye?`text-primary-foreground`:Ce?`text-accent-foreground`:`text-foreground`,De=te&&le&&R&&r<vc,Oe=(0,Q.jsxs)(`div`,{"data-tree-path":I,"data-selected":_.has(I)||void 0,"data-active":de||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]`,Ee,B&&`ring-1 ring-inset ring-info/40`,V&&!B&&`ring-1 ring-inset ring-warning/40`,E===I&&!l&&!D&&`ring-2 ring-inset ring-info`,E===I&&!l&&D&&`ring-2 ring-inset ring-success`),style:{height:_c,background:Te,borderBottom:`1px solid var(--border)`,...De?{position:`sticky`,top:r*_c,zIndex:20-r}:{}},draggable:!l&&!t.metadata?.backendTrash,onClick:H,onDoubleClick:pe,...l?{}:re,onContextMenu:e=>{l||(e.preventDefault(),x(e,I,t))},onDragStart:e=>{l||O(I,e)},onDragEnter:e=>{l||k(I,e)},onDragOver:e=>{l||A(I,e)},onDragLeave:e=>j(I,e),onDragEnd:()=>M(),onDrop:e=>{l||N(I,e)},children:[ne.length>0&&(0,Q.jsx)(`span`,{className:`flex shrink-0 gap-px`,"aria-hidden":!0,children:ne.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=ae.color?{background:ae.color}:me?{background:`color-mix(in oklab, ${me} 45%, transparent)`}:{background:U(10)},n=(0,Q.jsx)(i,{icon:ae.icon||(fe?`ph:squares-four-fill`:`ph:folder-fill`),width:18,height:18,className:G(`shrink-0`,ae.color?Ci(ae.color):ye?`text-primary-foreground`:Ce?`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,I,t))},onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),w(e,I,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`,de||_e||Se?`font-semibold`:`font-medium`),title:t.description||void 0,children:t.label||t.name}),F.has(I)&&(0,Q.jsx)(gt,{className:`mr-1 h-3.5 w-3.5 shrink-0 animate-spin self-center`,"aria-label":F.get(I)}),ee?.has(I)&&(0,Q.jsx)(gt,{className:`mr-1 h-3.5 w-3.5 shrink-0 animate-spin self-center opacity-70`,"aria-label":`Indexing`}),ie&&(0,Q.jsx)(ue,{className:`mr-1 h-3 w-3 shrink-0 self-center text-muted-foreground`,"aria-label":ie,children:(0,Q.jsx)(`title`,{children:ie})}),!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,I,t)},children:(0,Q.jsx)(ct,{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)]`,!R&&m!==I&&`invisible`),style:{borderLeft:`1px solid ${U(16)}`},"aria-label":le?`Collapse`:`Expand`,"aria-expanded":le,title:le?`Collapse`:`Expand`,onClick:e=>{e.stopPropagation(),se(e=>!e)},children:le?(0,Q.jsx)(ke,{className:`h-5 w-5`,strokeWidth:2.25}):(0,Q.jsx)(Me,{className:`h-5 w-5`,strokeWidth:2.25})})]});return(0,Q.jsxs)(`div`,{className:`relative`,children:[te?Oe:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`pointer-events-none absolute top-0 w-px bg-border`,style:{left:`-${gc/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:`-${gc/2}px`,width:`${gc/2}px`}}),(0,Q.jsxs)(`div`,{"data-tree-path":I,"data-selected":_.has(I)||void 0,"data-active":de||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&&de&&!t.locked&&`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`,!B&&!V&&de&&t.locked&&`bg-warning/15 hover:bg-warning/20 before:bg-primary`,!B&&!V&&!de&&z&&`bg-primary/[0.03] before:bg-transparent`,!B&&!V&&!de&&!z&&!t.locked&&`bg-card hover:bg-primary/[0.04] before:bg-transparent`,!B&&!V&&!de&&t.locked&&`bg-warning/15 hover:bg-warning/20 before:bg-warning`,E===I&&!l&&!D&&`ring-2 ring-info bg-info-subtle/50`,E===I&&!l&&D&&`ring-2 ring-success bg-success-subtle/50`),style:{borderRight:ae.color?`4px solid ${ae.color}`:`4px solid transparent`},draggable:!l&&!t.metadata?.backendTrash,onClick:H,onDoubleClick:pe,...l?{}:re,onContextMenu:e=>{l||(e.preventDefault(),x(e,I,t))},onDragStart:e=>{l||O(I,e)},onDragEnter:e=>{l||k(I,e)},onDragOver:e=>{l||A(I,e)},onDragLeave:e=>j(I,e),onDragEnd:()=>M(),onDrop:e=>{l||N(I,e)},children:[(0,Q.jsx)(`button`,{type:`button`,className:G(`shrink-0 text-muted-foreground hover:text-foreground`,!R&&m!==I&&`invisible`),"aria-label":le?`Collapse`:`Expand`,"aria-expanded":le,onClick:e=>{e.stopPropagation(),se(e=>!e)},children:le?(0,Q.jsx)(ke,{className:`w-4 h-4`}):(0,Q.jsx)(Me,{className:`w-4 h-4`})}),(()=>{let e=(0,Q.jsx)(i,{icon:ae.icon||(fe?`ph:squares-four-fill`:`ph:folder-fill`),width:16,height:16,color:ae.color||void 0,className:G(`shrink-0`,!ae.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,I,t))},onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),w(e,I,t)},children:e}):e})(),(0,Q.jsx)(`span`,{className:`flex-1 truncate font-medium`,title:t.description||void 0,children:t.label||t.name}),F.has(I)&&(0,Q.jsx)(gt,{className:`h-3.5 w-3.5 shrink-0 animate-spin`,"aria-label":F.get(I)}),ee?.has(I)&&(0,Q.jsx)(gt,{className:`w-3.5 h-3.5 shrink-0 animate-spin text-muted-foreground`,"aria-label":`Indexing`}),ie&&(0,Q.jsx)(ue,{className:`w-3 h-3 shrink-0 text-muted-foreground`,"aria-label":ie,children:(0,Q.jsx)(`title`,{children:ie})}),!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,I,t)},children:(0,Q.jsx)(ct,{className:`w-4 h-4`})})]})]}),le&&(R||m===I)&&(0,Q.jsxs)(`div`,{className:te?void 0:`ml-[22px] mt-2 mb-1 space-y-1.5`,children:[m===I&&(0,Q.jsx)(wc,{onConfirm:e=>S(I,e),onCancel:C}),t.children?.map((n,i)=>(0,Q.jsx)(Dc,{node:n,expansionState:e,parentPath:I,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:F,accordion:te,trail:ge},n.id||n.name))]})]})}function Oc({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:F,onMergeLayer:te,onSubtractLayer:ne,onMergeDown:re,onSubtractDown:I,onResyncBackend:ie,canResyncBackend:ae,onCreateBackendFolder:oe,onRenameBackendFolder:se,onDeleteBackendFolder:L,onUpdateNode:ce,isPathPinned:le,onTogglePin:R,searchQuery:ue=``,resyncingPaths:de,backends:z}){let B=hc(),[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(tc(r,i,e)),H.current=r.includes(i)?i:e},[he,ge]=(0,Z.useState)(null),[_e,ve]=(0,Z.useState)(null),[ye,be]=(0,Z.useState)(new Map),[U,xe]=(0,Z.useState)(null),[Se,Ce]=(0,Z.useState)(new Map),we=(0,Z.useRef)(new Set),Te=(0,Z.useCallback)(async(e,t=!1,n=!1,a=!1)=>{if(!(i?L:w)||[...we.current].some(t=>t===e||t.startsWith(e+`/`)||e.startsWith(t+`/`)))return!1;we.current.add(e);let o=i?`Deleting from backend…`:a?`Removing documents and backend files…`:n?`Removing and purging documents…`:`Removing folder…`;Ce(t=>new Map(t).set(e,o));try{return i?await L(e):await w(e,r===`directory`||t,n,a)}finally{we.current.delete(e),Ce(t=>{let n=new Map(t);return n.delete(e),n})}},[w,L,i,r]),[Ee,De]=(0,Z.useState)(null),[Oe,Ae]=(0,Z.useState)(new Map),[je,Me]=(0,Z.useState)(e),Ne=(0,Z.useRef)(new Map),Pe=(0,Z.useRef)(null),[Fe,Ie]=(0,Z.useState)(null);if(e!==je){Me(e);let t=Fe;Ae(t?new Map([[t.path,t.style]]):new Map)}let[W,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(xc(t)&&!bc(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(xc(t)&&!bc(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&&bc(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&&!!re;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,re]),at=ue.toLowerCase().trim(),ot=(0,Z.useCallback)((e,t,n)=>{e.stopPropagation(),xe({x:e.clientX,y:e.clientY,path:t,node:n})},[]),st=(0,Z.useCallback)((e,t,n)=>{e.stopPropagation(),!n.metadata?.backendTrash&&(Pe.current=null,Ie(null),De({x:e.clientX,y:e.clientY,path:t,node:n}))},[]),lt=(0,Z.useCallback)(e=>{if(!Ee||!ce)return;let t=Ee.path,n={...Oe.get(t)??(Pe.current?.path===t?Pe.current.style:xi(Ee.node)),...e};Pe.current={path:t,style:n},Ie({path:t,style:n}),Ae(e=>new Map(e).set(t,n));let r=bi(Ee.node.metadata,n),i=Ne.current,a=i.get(t);a&&clearTimeout(a),i.set(t,setTimeout(()=>{i.delete(t),ce(t,{metadata:r}).catch(e=>alert(e instanceof Error?e.message:String(e)))},350))},[Ee,ce,Oe]),ut=(0,Z.useCallback)((e,t)=>{_e?e===_e.path?(ve(null),be(new Map)):be(n=>{let r=new Map(n);return r.has(e)?r.delete(e):r.set(e,t),r}):(ve({path:e,id:t}),be(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&&!!re;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,re]);(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{yc(e,i)&&oe?await oe(e,t)&&l(n):x&&await x(n,!0)&&l(n)}catch(e){alert(e instanceof Error?e.message:String(e))}},[x,oe,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&&bc(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?!L||!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`:``}?`)&&Te(s,!1).catch(e=>alert(e instanceof Error?e.message:String(e)))},[d,w,L,Te,s,e,M,N,he,dt,i,mt,r,z]),_t=(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||ye.size>0,yt={expansionState:t,accordion:B,selectedPath:s,pendingPath:c,contentPath:_,readOnly:d,sourceLayer:_e,targetLayers:ye,clipboard:he,searchQuery:at,inlineCreateParent:W,onSelect:pe,onAltSelect:b,selectedPaths:V,onRangeSelect:me,onShowContent:v,onCtrl:ut,onCtxMenu:ot,onConfirmCreate:ft,onCancelCreate:pt,onOpenPicker:ce?st: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:Se};return(0,Q.jsxs)(`div`,{"data-menu-tree":!0,className:`px-3 py-2 space-y-1.5 outline-none min-h-full max-md:w-max max-md:min-w-full`,tabIndex:0,onKeyDown:ht,onContextMenu:t=>{t.defaultPrevented||d||(t.preventDefault(),ot(t,`/`,e))},children:[Se.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:[...Se].map(([e,t])=>(0,Q.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Q.jsx)(gt,{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:_t,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`}),re&&!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} · ${ye.size} target(s)`:`Select source with ⌃-click`}),(0,Q.jsx)(`button`,{type:`button`,className:`hover:text-foreground underline`,onClick:()=>{ve(null),be(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(),xe({x:e.clientX,y:e.clientY,path:`/`,node:{id:``,name:`/`,label:`/`,type:`root`,description:``,color:null,locked:!1,children:[]}}))},children:[(0,Q.jsx)(ke,{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(),xe({x:e.clientX,y:e.clientY,path:`/`,node:{id:``,name:`/`,label:`/`,type:`root`,description:``,color:null,locked:!1,children:[]}})},children:(0,Q.jsx)(ct,{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:[W===`/`&&(0,Q.jsx)(wc,{onConfirm:e=>ft(`/`,e),onCancel:pt}),e.children?.map((t,n)=>(0,Q.jsx)(Dc,{node:t,parentPath:`/`,depth:0,isLast:n===(e.children?.length??0)-1,...yt},t.id||t.name)),!e.children?.length&&W!==`/`&&(0,Q.jsx)(`div`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})]}),U&&V.size>1&&V.has(U.path)?(0,Q.jsxs)(wn,{x:U.x,y:U.y,onClose:()=>xe(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
  `)),xe(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:()=>{xe(null);let e=nc(V);confirm(`Remove ${V.size} selected folders and their children?\n${e.join(`
6
- `)}`)&&(async()=>{for(let t of e)await Te(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),xe(null)},children:`Clear selection`})]}):U&&(0,Q.jsx)(Cc,{x:U.x,y:U.y,node:U.node,path:U.path,isBackendsTree:i,backends:z,isDirectoryTree:r===`directory`,onClose:()=>xe(null),onShowContent:U.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:ye,clipboard:he,onStartInlineCreate:e=>Le(e),onChangeIcon:ce?()=>st({clientX:U.x,clientY:U.y,stopPropagation:()=>{}},U.path,U.node):void 0,onNewCanvas:S,onShareCanvas:C,onImportDocuments:d?void 0:A,onExportDocuments:j,onExportSubtree:O,onImportSubtree:d?void 0:k,onRemove:!d&&w&&![...Se.keys()].some(e=>e===U.path||e.startsWith(U.path+`/`)||U.path.startsWith(e+`/`))?Te:void 0,onRename:d?void 0:T,onLock:d?void 0:ee,onUnlock:d?void 0:P,onDestroy:d?void 0:F,onMerge:d?void 0:te,onSubtract:d?void 0:ne,onMergeDown:d?void 0:re,onSubtractDown:d?void 0:I,canResyncBackend:ae,onResyncBackend:ie,onAddRule:f,onAddStoreRule:p,onStoragePolicy:!d&&!i?m:void 0,onRenameBackendFolder:se,onDeleteBackendFolder:!d&&L&&![...Se.keys()].some(e=>e===U.path||e.startsWith(U.path+`/`)||U.path.startsWith(e+`/`))?e=>Te(e,!0):void 0,onCopy:e=>mt(e,`copy`),onCut:e=>mt(e,`cut`),onPaste:dt,pastedDocumentIds:M,onPasteDocuments:N,isPinned:le?le(U.path):!1,onTogglePin:R?()=>R(U.path,U.node):void 0}),Ee&&ce&&(0,Q.jsx)(ac,{x:Ee.x,y:Ee.y,current:Oe.get(Ee.path)??xi(Ee.node),onChange:lt,onClose:()=>De(null)})]})}function kc(){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)(ec,{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)(Oc,{root:d,workspaceId:l?.workspaceName,searchQuery:v,selectedPath:b,pendingPath:S,onSelect:M,isLoading:w,rootLabel:l?.workspaceName,...j})]})]})}function Ac({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)(Me,{className:G(`h-3.5 w-3.5 shrink-0`,r?`opacity-100`:`opacity-0`)})]},e.id)})]})})}var jc=[{id:`general`,label:`Workspace details`,description:`Rename, change appearance or remove this workspace`,icon:lt},{id:`backups`,label:`Backups`,description:`Save or restore documents, relations and tree placements`,icon:He},{id:`data`,label:`Files & storage`,description:`Connect folders and data sources, check disk usage or restore trash`,icon:A},{id:`db`,label:`Search & indexing`,description:`How documents become searchable: AI models, image descriptions, index repairs`,icon:Ye},{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:gt},{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:Rt},{id:`policies`,label:`Storage policies`,description:`Mirror folders of the virtual tree to physical backends`,icon:ue},{id:`hooks`,label:`Automation`,description:`Run hooks in response to workspace events`,icon:je}],Mc={embedding:`db`,trash:`data`};function Nc(e){return e?Mc[e]?Mc[e]:jc.some(t=>t.id===e)?e:`general`:`general`}var Pc=[{id:`general`,label:`Context details`,description:`Change the name, description or color, or remove this context`,icon:lt},{id:`location`,label:`Tree & path`,description:`Choose the workspace, tree and path this context opens`,icon:Rt},{id:`shares`,label:`Sharing & permissions`,description:`Choose who can access this context`,icon:ie}];function Fc(e){return e&&Pc.some(t=>t.id===e)?e:`general`}var Ic=[{id:`identity`,label:`Identity & instructions`,description:`Set the agent’s name, role and instructions`,icon:lt},{id:`provider`,label:`AI connection`,description:`Connect a chat model provider and manage its credentials`,icon:ne},{id:`models`,label:`Chat model`,description:`Choose the model and tune how it responds`,icon:we},{id:`tools`,label:`Tools & skills`,description:`Choose the skills and MCP tools the agent can use`,icon:U},{id:`access`,label:`Access & permissions`,description:`Choose which Canvas content the agent can access`,icon:P},{id:`memory`,label:`Memory`,description:`Configure how the agent remembers information`,icon:ye},{id:`integrations`,label:`Integrations`,description:`Connect mail, chat, databases and external APIs`,icon:tt}];function Lc(e){return e&&Ic.some(t=>t.id===e)?e:`identity`}function Rc(){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`?Fc(c[3]):null,u=a?`/contexts/${a}`:null,d=(0,Z.useMemo)(()=>Pc.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)(ec,{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)(bt,{className:`h-3.5 w-3.5`})})}),(0,Q.jsx)(Ac,{items:d,activeId:l,onSelect:e=>a&&r(`/contexts/${a}/settings/${e}`)})]})}function zc(e){return e.isShared||e.type===`shared`?e.id:e.name}function Bc(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)(()=>Js(t),[t]),isLoading:r,refresh:c}}function Vc({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 Hc(){let[e,t]=(0,Z.useState)(null),n=ms(),{state:r,selectEntity:a,openM2:o,closeM2:s}=la(),c=Fr(),{workspaces:l,isLoading:u}=Bc(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}=Zs((e,t)=>{let n=Ys(C,e,t);S({base:l,order:n}),Xs(n,(e,t)=>Qn(zc(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(zc(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(zc(e)),o(`detail`,zc(e)),!c&&ya(zc(e))&&f(va(zc(e)))},j=async(e,t)=>{e.stopPropagation(),h(e=>new Set(e).add(zc(t)));try{await ur(zc(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(zc(t)),n})}},M=async(e,t)=>{e.stopPropagation(),h(e=>new Set(e).add(zc(t)));try{await fr(zc(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(zc(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===zc(e),s=Ji(e),l=p.has(zc(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)(ae,{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:zc(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:zc(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)(Vc,{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)(Ot,{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)(le,{className:`w-3.5 h-3.5`})}),(0,Q.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),a(zc(e)),c?o(`settings`,zc(e)):f(`/workspaces/${zc(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=>zc(e)===g.name);if(!e)return null;let t=O(e);return(0,Q.jsx)(ac,{x:g.x,y:g.y,current:t,onChange:e=>k(g.name,t,e),onClose:()=>_(null)})})()]})}var Uc={previousTree:`Alt+Q`,nextTree:`Alt+W`},Wc=`canvas:key-bindings`,Gc=/^(Alt|Alt\+Shift|Ctrl\+Shift|Meta\+Shift)\+[A-Z]$/;function Kc(){try{let e=JSON.parse(localStorage.getItem(Wc)||`{}`),t={...Uc};for(let n of Object.keys(t))(e[n]===``||Gc.test(e[n]))&&(t[n]=e[n]);return t.previousTree&&t.previousTree===t.nextTree?{...Uc}:t}catch{return{...Uc}}}function qc(e){localStorage.setItem(Wc,JSON.stringify(e))}function Jc(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 Yc(e,t,n){return e[(Math.max(0,e.indexOf(t))+n+e.length)%e.length]}function Xc(e,t){return Math.abs(e)>=48&&Math.abs(e)>Math.abs(t)*1.5?e<0?1:-1:0}function Zc(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=Jc(e);if(!r)return;let i=Kc(),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=Xc(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 Qc(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 $c(e,t,n,r=!1,i=`forward`,a=`copy`,o,s){let c=Qc(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 el(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 tl({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{el(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)(Rt,{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:el(t,await gr(e)),a=$c(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 nl=e=>`/workspaces/${e}/storage-policies`;function rl(){return`policy-${crypto.randomUUID().slice(0,8)}`}function il(e){return e.filter(e=>e.enabled&&e.capabilities?.upload&&!e.config?.readOnly&&e.driver!==`cacache`)}var al=new Set([`file`]);function ol(e,t){return`${e===`directory`?`dir`:`ctx`}:${t.startsWith(`/`)?t:`/${t}`}`}function sl(e){let t=/^(ctx|dir):(\/.*)$/.exec(e);return t?{tree:t[1]===`dir`?`directory`:`context`,path:t[2]}:null}function cl(e){return(sl(e)?.path??e).replace(/^\/+/,``)}function ll(e){return`${e.backend}:${e.folder||`/`}`}async function ul(e){let t=await Y.get(nl(e));return{...t,policies:t?.policies??[],revision:t.revision,blobBackend:t?.blobBackend??null}}async function dl(e,t,n){return Y.put(nl(e),{policies:t,revision:n})}async function fl(e,t,n={}){return await Y.post(`${nl(e)}/${encodeURIComponent(t)}/apply`,n)}async function pl(e,t,n){let{policies:r,revision:i}=n??await ul(e),a=r.findIndex(e=>e.id===t.id);return dl(e,a===-1?[...r,t]:r.map((e,n)=>n===a?t:e),i)}async function ml(e,t,n,r={}){let i={folders:0,processed:0,matched:0,failed:0},a=0;for(;a!==null;){let o=await fl(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 hl(e,t,n){let r=ol(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 gl(e){let t=new Set;for(let n of e)for(let e of n.targets)t.add(ll(e));return[...t].join(`, `)}async function _l(e,t){await Y.post(`${nl(e)}/operations/${encodeURIComponent(t)}/retry`,{})}function vl(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 yl(e,t){return{backend:e?.address??``,folder:t,recursive:!0,recreateDirectories:!!e&&al.has(e.driver),onConflict:`error`}}function bl({workspaceId:e,path:t,policy:n,onClose:r,onSaved:i}){let a=!!n,[o]=(0,Z.useState)(()=>n?.id??rl()),[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)(()=>vl(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,F]=(0,Z.useState)(0),[te,ne]=(0,Z.useState)(0);hi(r,!D);let re=()=>{D||r()},I=(0,Z.useMemo)(()=>cl(t),[t]),ie=(0,Z.useMemo)(()=>il(C??[]).filter(e=>s===`filing`||e.driver===`file`),[C,s]),ae=(0,Z.useMemo)(()=>new Map(ie.map(e=>[e.address,e])),[ie]);(0,Z.useEffect)(()=>{let t=!1;return Promise.all([gr(e),ul(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=il(e).find(e=>n?.kind===`filing`||e.driver===`file`);i&&b(e=>e.length?e:[yl(i,I)])}).catch(e=>{t||(w([]),M(e instanceof Error?e.message:`Could not load backends`))}),()=>{t=!0}},[e,I,n]);let oe=(e,t)=>b(n=>n.map((n,r)=>r===e?{...n,...t}:n)),se=(e,t)=>{let n=ae.get(t),r=!!n&&al.has(n.driver);oe(e,{backend:t,recreateDirectories:r?y[e].recreateDirectories:!1})},L=()=>{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}},ce=async()=>{if(!D){O(!0),M(``);try{let t=L();T||(await pl(e,t,x),E(!0),i?.(t)),ee(0),F(0),ne(0),await ml(e,o,(e,t)=>{ee(t.matched),F(t.folders),ne(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)}}},le=!!x&&y.length>0&&y.every(e=>e.backend);return(0,Q.jsx)(Ti,{onClose:re,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)(ue,{className:`h-4 w-4`}),a?`Edit storage policy`:`Storage policy`]}),(0,Q.jsx)(`button`,{type:`button`,onClick:re,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&&!ie.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=ae.get(e.backend),r=s===`mirror`&&!!n&&al.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…`}),ie.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=>oe(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=>oe(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=>oe(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=>oe(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=>oe(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||!ie.length,onClick:()=>b(e=>[...e,yl(ie.find(t=>!e.some(e=>e.backend===t.address))??ie[0],I)]),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.`]}),te>0&&(0,Q.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[te,` 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:re,children:`Cancel`}),k?(0,Q.jsx)(K,{onClick:r,children:`Done`}):(0,Q.jsx)(K,{disabled:D||!le,onClick:ce,children:D?`Applying…`:T?`Retry existing documents`:a?`Save policy`:`Enable policy`})]})]})})}var xl={policies:[],revision:``,loading:!1,error:``},Sl=new Map,Cl=new Set;function wl(){for(let e of Cl)e()}function Tl(e){return Cl.add(e),()=>{Cl.delete(e)}}function El(e,t){Sl.set(e,t),wl()}async function Dl(e){El(e,{...Sl.get(e)??xl,loading:!0,error:``});try{let{policies:t,revision:n,status:r}=await ul(e);El(e,{policies:t,revision:n,status:r,loading:!1,error:``})}catch(t){El(e,{policies:[],revision:``,loading:!1,error:t instanceof Error?t.message:`Could not load storage policies`})}}function Ol(e){Sl.delete(e),wl()}function kl(e){let t=(0,Z.useSyncExternalStore)(Tl,()=>e&&Sl.get(e)||xl),n=!!e&&!Sl.has(e);(0,Z.useEffect)(()=>{e&&n&&Dl(e)},[e,n]);let r=(0,Z.useCallback)(async()=>{e&&await Dl(e)},[e]);return(0,Z.useEffect)(()=>{if(!e||!t.policies.length)return;let n=window.setInterval(()=>{!document.hidden&&!Sl.get(e)?.loading&&Dl(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 Al(){return await Y.get(`${J}/users/me/config/webui`)??{}}async function jl(e){return await Y.put(`${J}/users/me/config/webui`,e)??e}var Ml=`application/x-canvas-workspace-pin`;function Nl({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(Ml,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)(Pt,{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)(Dt,{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)(xe,{className:`w-3.5 h-3.5`})})]}),!p&&(0,Q.jsx)(ae,{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 Pl=()=>({selectedPath:`/`,contentPath:null,searchQuery:``,expansion:new Map}),Fl=[`pins`,`context`,`layers`,`directory`,`backends`],Il=e=>typeof e==`string`&&Fl.includes(e),Ll=e=>{let t=Array.isArray(e)?e.filter(Il).filter((e,t,n)=>n.indexOf(e)===t):[];return[...t,...Fl.filter(e=>!t.includes(e))]},Rl={pins:(0,Q.jsx)(V,{className:`w-3.5 h-3.5`}),context:(0,Q.jsx)(Fe,{className:`w-3.5 h-3.5`}),layers:(0,Q.jsx)(Ce,{className:`w-3.5 h-3.5`}),directory:(0,Q.jsx)(Dt,{className:`w-3.5 h-3.5`}),backends:(0,Q.jsx)(Ye,{className:`w-3.5 h-3.5`})},zl={pins:`Pins`,context:`Context tree`,layers:`Context layers`,directory:`Directory tree`,backends:`Backends tree`},Bl=e=>e===`directory`||e===`backends`?e:Gn,Vl=(e,t)=>t?`layers`:e===`directory`?`directory`:e===`backends`?`backends`:`context`;function Hl(){let{state:e}=la();return e.selectedEntityId?(0,Q.jsx)(xa,{workspaceName:e.selectedEntityId,children:(0,Q.jsx)(Ul,{},e.selectedEntityId)}):null}function Ul(){let{state:e,closeM2:t,openM2:n,openM1Drawer:r,navigateFromMenu:i}=la(),a=xr(),o=Fr(),s=e.selectedEntityId,c=m(),l=h(),{treeName:u,path:d}=ra(l.pathname),f=new URLSearchParams(l.search).get(`layer`)===`1`,p=new URLSearchParams(l.search).get(`layerId`),g=/\/trees\/|\/path(\/|$)/.test(l.pathname)||!!p,_=g?Vl(u,p):Fl[0],[v,y]=(0,Z.useState)(!1),[b,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(null),[w,T]=(0,Z.useState)({icon:null,color:null}),[E,D]=(0,Z.useState)(_),[O,k]=(0,Z.useState)(null),[A,j]=(0,Z.useState)(null),[M,N]=(0,Z.useState)(null),[ee,P]=(0,Z.useState)([]),[F,te]=(0,Z.useState)(!1),[ne,re]=(0,Z.useState)(!1),[I,ie]=(0,Z.useState)(!1),[ae,oe]=(0,Z.useState)(!1),[se,L]=(0,Z.useState)(d),[ce,le]=(0,Z.useState)([]),[R,ue]=(0,Z.useState)(new Set),[de,z]=(0,Z.useState)(f&&d!==`/`?d:null),[B,V]=(0,Z.useState)(``),[fe,H]=(0,Z.useState)(null),[pe,me]=(0,Z.useState)(null),[he,ge]=(0,Z.useState)(null),{policies:_e,refresh:ve}=kl(s),ye=(0,Z.useCallback)(e=>{if(E!==`context`&&E!==`directory`||!_e.length)return null;let t=hl(_e,E,e);return t.length?`Storage policy targets: ${gl(t)} (see Settings for transfer status)`:null},[E,_e]),[be,U]=(0,Z.useState)([]),[xe,Se]=(0,Z.useState)(!1),[Ce,we]=(0,Z.useState)(!1),Te=(0,Z.useRef)(null),Ee=(0,Z.useRef)(new Map),[De,Oe]=(0,Z.useState)(()=>Object.fromEntries(Fl.map(e=>[e,Pl()])));(0,Z.useLayoutEffect)(()=>{Te.current&&(Te.current.scrollTop=Ee.current.get(E)??0)},[E]);let ke=De[E];(ke.selectedPath!==se||ke.contentPath!==de||ke.searchQuery!==B)&&Oe({...De,[E]:{...ke,selectedPath:se,contentPath:de,searchQuery:B}});let Ae=(0,Z.useRef)(!1),[je,Me]=(0,Z.useState)(!1),[Ne,Pe]=(0,Z.useState)(Fl),Fe=!g;(0,Z.useEffect)(()=>{let e=!1;return Al().then(t=>{if(e)return;let n=Ll(t?.m2?.tabOrder);Pe(n),Fe&&D(e=>e===Fl[0]?n[0]:e)}).catch(()=>{}),()=>{e=!0}},[]);let Ie=(0,Z.useCallback)(async e=>{let t=Ne;Pe(e);try{let t=await Al();await jl({...t,m2:{...t.m2,tabOrder:e}})}catch{Pe(t)}},[Ne]),[W,Le]=(0,Z.useState)(null),[Re,ze]=(0,Z.useState)(null),Be=()=>{Le(null),ze(null)},Ve=()=>{if(W&&Re&&W!==Re.id){let e=Ne.filter(e=>e!==W),t=e.indexOf(Re.id);t>=0&&(e.splice(Re.before?t:t+1,0,W),e.some((e,t)=>e!==Ne[t])&&Ie(e))}Be()};(0,Z.useEffect)(()=>{let e=e=>H(e.detail??null);return window.addEventListener(`documents:clipboard`,e),()=>window.removeEventListener(`documents:clipboard`,e)},[]);let[He,Ue]=(0,Z.useState)(d);d!==He&&(Ue(d),L(d));let We=(0,Z.useRef)(new Map),Ge=(0,Z.useCallback)(async(e,t,n=!1,r=!1)=>{let i=Symbol();We.current.set(t,i);let a=()=>We.current.get(t)===i,o=t===`context`?te:t===`directory`?re:ie,s=t===`context`?k:t===`directory`?j:N;n||o(!0);try{n&&!r&&ar(e,t);let i=await In(e,t);a()&&s(i)}catch{}finally{a()&&o(!1)}},[]),Ke=(0,Z.useCallback)(async(e,t=!1)=>{let n=Symbol();We.current.set(`pins`,n);let r=()=>We.current.get(`pins`)===n;t||Se(!0);try{let t=await Pn(e);r()&&U(t)}catch{}finally{r()&&Se(!1)}},[]),qe=(0,Z.useCallback)(async(e,t=!1)=>{let n=Symbol();We.current.set(`layers`,n);let r=()=>We.current.get(`layers`)===n;t||oe(!0);try{let t=await qn(e,`context`);r()&&P(t)}catch{}finally{r()&&oe(!1)}},[]);(0,Z.useEffect)(()=>{if(!s)return;let e=s,t=!1,n=We.current;async function r(){Un(e).then(e=>{t||(x(e.label||e.name),y(Ji(e)),C(e.id||null),T({icon:e.icon??null,color:e.color??null}))}).catch(()=>{}),await Promise.all([Ge(e,`context`),Ge(e,`directory`),Ge(e,`backends`),qe(e),Ke(e)])}return r(),()=>{t=!0,n.clear()}},[s,Ge,qe,Ke]);let Je=(0,Z.useCallback)((e,t,n=!1)=>{for(let r of[`context`,`directory`,`backends`])(!t||t===r)&&Ge(e,r,!0,n);(!t||t===`context`)&&qe(e,!0),Ke(e,!0)},[Ge,qe,Ke]),Ye=(0,Z.useCallback)(()=>{s&&Je(s)},[s,Je]);(0,Z.useEffect)(()=>{if(!s)return;let e=e=>{e.detail?.workspaceName&&e.detail.workspaceName!==s||Je(s,e.detail?.treeName,e.detail?.cacheInvalidated)};return window.addEventListener(`workspace:tree:refresh`,e),()=>window.removeEventListener(`workspace:tree:refresh`,e)},[s,Je]),(0,Z.useEffect)(()=>{if(!s)return;let e=!1,t=()=>gr(s).then(t=>{e||(le(t),ue(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!==s||(!n?.treeName||n.treeName===`backends`)&&t()};return window.addEventListener(`workspace:tree:refresh`,n),()=>{e=!0,window.removeEventListener(`workspace:tree:refresh`,n)}},[s]),(0,Z.useEffect)(()=>{if(!s)return;let e=[`workspace:${s}`,S?`workspace:${S}`:null].filter(Boolean),t=()=>e.forEach(e=>X.emit(`subscribe`,{channel:e})),n=X.on(`connect`,t);t();let r=Or(s,S),i=e=>{if(e?.workspaceId&&S&&e.workspaceId!==S)return;let t=e?.treePath;t&&ue(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&&S&&e.workspaceId!==S||Ke(s,!0)};return X.on(`pins.changed`,a),()=>{r(),n?.(),X.off(`backend.resync.changed`,i),X.off(`pins.changed`,a)}},[s,S,Ke]);let[Xe,Ze]=(0,Z.useState)(null),Qe=`${l.pathname}|${l.search}`;if(Qe!==Xe){Ze(Qe);let{treeName:e,path:t}=ra(l.pathname),n=new URLSearchParams(l.search).get(`layerId`),r=/\/trees\/|\/path(\/|$)/.test(l.pathname)||!!n;Ce?we(!1):D(r||je?r?Vl(e,n):E:Ne[0]),L(t),z(t===`/`?null:t)}let{showProgress:$e}=xn();(0,Z.useEffect)(()=>{s&&Ui($e,s)},[s,$e]);let et=Ar({workspaceId:s??void 0,treeName:Bl(E),onRefresh:Ye}),tt=(0,Z.useRef)(new Map);(0,Z.useEffect)(()=>{if(!s)return;let e=`${s}:${E}:${se}`,t=et;t.canResyncBackend(se)&&(Date.now()-(tt.current.get(e)||0)<6e4||(tt.current.set(e,Date.now()),t.onResyncBackend?.(se).catch(()=>{})))},[s,E,se,et]);let nt=new Set(be.map(e=>hr(e.tree,e.path))),rt=Bl(E),it=(0,Z.useCallback)(e=>nt.has(hr(rt,e)),[be,rt]),at=(0,Z.useCallback)(async e=>{if(!s)return;let t=be.find(t=>hr(t.tree,t.path)===hr(rt,e));t?await ir(s,t.id):await An(s,e,rt),await Ke(s)},[s,be,rt,Ke]),ot=(0,Z.useCallback)(async e=>{if(s){U(t=>t.filter(t=>t.id!==e.id));try{await ir(s,e.id)}finally{await Ke(s)}}},[s,Ke]),st=(0,Z.useCallback)(async(e,t)=>{if(!s)return;let n=be.find(t=>t.id===e);if(!n)return;let r=be.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===be[t])){U(a);try{U(await Xn(s,a.map(e=>e.id)))}catch(e){throw await Ke(s),e}}},[s,be,Ke]),ct=(0,Z.useCallback)(e=>{if(!s)return;we(!0),L(e.path),z(null);let t=ia(s,e.path,e.tree);if(a){a.activateRow(`pin:${s}:${e.id}`,e.label||e.name||e.path,t);return}i(t)},[s,i,a]),lt=(0,Z.useCallback)(e=>{!s||e.resolvable===!1||(we(!1),Me(!0),D(Vl(e.tree)),L(e.path),z(null),V(``),Ae.current=!0,a?.setFocus(`main`),i(ia(s,e.path,e.tree)))},[s,i,a]),ut=E===`context`?O:E===`directory`?A:E===`backends`?M:null,dt=E===`context`?F:E===`directory`?ne:E===`backends`&&I;(0,Z.useEffect)(()=>{if(!Ae.current||dt||E===`pins`)return;let e=Te.current?.querySelector(`[data-active="true"]`);e&&(e.scrollIntoView({block:`nearest`,inline:`nearest`}),Ae.current=!1)},[E,se,ut,dt]);let ft=(0,Z.useCallback)(e=>{Me(!0),D(e);let t=De[e];L(t.selectedPath),z(t.contentPath),V(t.searchQuery)},[De]),mt=(0,Z.useCallback)(e=>{ft(Yc(Ne,E,e))},[Ne,E,ft]),ht=Zc(e.m2Open,mt),gt=e=>{z(null),L(e);let t=Bl(E);a?.setFocus(`main`),i(ia(s,e,t))},_t=(0,Z.useCallback)((e,t)=>{L(e),z(e);let n=Bl(E),r=new URLSearchParams;r.set(`layer`,`1`),t&&r.set(`layerId`,t),a?.setFocus(`main`),i(`${ia(s,e,n)}?${r.toString()}`)},[s,E,i,a]),vt=(0,Z.useCallback)((e,t)=>{if(s){if(a){a.openCanvas({kind:`route`,location:ia(s,e,t)});return}window.dispatchEvent(new CustomEvent(`workspace:open-to-side`,{detail:{workspaceName:s,treeName:t,path:e}}))}},[s,a]),yt=(0,Z.useCallback)(async e=>{if(!s)return;let t=Bl(E),n=await Zn(s,e,t),r=`${window.location.origin}${n.url}`;await navigator.clipboard?.writeText(r),alert(`Canvas share link copied:\n${r}`)},[s,E]),xt=B.toLowerCase().trim(),St=xt?ee.filter(e=>e.name.toLowerCase().includes(xt)||(e.label||``).toLowerCase().includes(xt)||(e.description||``).toLowerCase().includes(xt)):ee;return(0,Q.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Q.jsx)(ec,{title:b||s||`Workspace`,icon:w.icon||`ph:stack-fill`,accentColor:w.color,onBack:o?()=>r(`workspaces`):t,backLabel:o?`Browse workspaces`:`Back to previous view`,action:(0,Q.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,Q.jsx)(`button`,{type:`button`,onClick:()=>s&&i(va(s)),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)(bt,{className:`w-3.5 h-3.5`})}),(0,Q.jsx)(`button`,{type:`button`,disabled:!v,onClick:()=>{o?n(`settings`,s??null):c(`/workspaces/${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 disabled:opacity-40 disabled:cursor-not-allowed`,title:v?`Settings`:`Workspace settings require admin access`,children:(0,Q.jsx)(pt,{className:`w-3.5 h-3.5`})})]})}),(0,Q.jsx)(`div`,{...ht,className:`flex border-b border-border shrink-0 touch-pan-y`,"aria-label":`Workspace trees`,children:Ne.map(e=>(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>ft(e),title:`${zl[e]} — drag to reorder; the first tab opens by default`,"aria-label":zl[e],"aria-pressed":E===e,draggable:!0,onDragStart:t=>{t.dataTransfer.setData(`text/plain`,e),t.dataTransfer.effectAllowed=`move`,Le(e)},onDragEnd:Be,onDragOver:t=>{if(!W||W===e)return;t.preventDefault(),t.dataTransfer.dropEffect=`move`;let n=t.currentTarget.getBoundingClientRect(),r=t.clientX<n.left+n.width/2;ze(t=>t?.id===e&&t.before===r?t:{id:e,before:r})},onDrop:e=>{e.preventDefault(),Ve()},className:G(`relative flex-1 flex items-center justify-center py-2 transition-colors`,E===e?`text-foreground border-b-2 border-foreground -mb-px`:`text-muted-foreground hover:text-foreground`,W===e&&`opacity-40`,Re?.id===e&&Re.before&&`shadow-[inset_2px_0_0_0_hsl(var(--primary))]`,Re?.id===e&&!Re.before&&`shadow-[inset_-2px_0_0_0_hsl(var(--primary))]`),children:[Rl[e],e===`pins`&&be.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:be.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:E===`layers`?`Search layers…`:E===`pins`?`Search pins…`:`Search paths…`,value:B,onChange:e=>V(e.target.value)})]})}),(0,Q.jsx)(`div`,{ref:Te,onScroll:e=>{Ee.current.set(E,e.currentTarget.scrollTop)},className:`flex-1 overflow-y-auto`,children:(0,Q.jsx)(ba,{workspaceId:s,treeName:Bl(E),readOnly:!v,className:`min-h-full`,children:E===`pins`?(0,Q.jsx)(Nl,{pins:be,isLoading:xe,searchQuery:B,activeKey:hr(u,d),onOpen:ct,onShowInTree:lt,onUnpin:ot,onMove:st}):E===`layers`?(0,Q.jsx)(Xl,{layers:St,isLoading:ae,wsName:s??``,onSelect:e=>{let t=new URLSearchParams;t.set(`layerId`,e.id),t.set(`layer`,`1`),i(`${ia(s,`/`)}?${t.toString()}`)},onLock:async e=>{await Hn(s,e.id,s,`context`),Je(s)},onUnlock:async e=>{await cr(s,e.id,s,`context`),Je(s)},onRename:async(e,t)=>{await Yn(s,e.id,t,`context`),Je(s)},onDestroy:async e=>{confirm(`Destroy layer "${e.label||e.name}"? This cannot be undone.`)&&(await zn(s,e.id,`context`),Je(s))}}):(0,Q.jsx)(Oc,{expansionState:De[E].expansion,root:ut,workspaceId:s??void 0,treeName:E,isBackendsTree:E===`backends`,onRestoreTrash:s?e=>Gi(s,e):void 0,onDiscardTrash:s?e=>Wi(s,e):void 0,onAltSelect:a?e=>vt(e,Bl(E)):void 0,selectedPath:se,contentPath:de,onSelect:gt,onShowContent:E===`context`?_t:void 0,onOpenToSide:vt,onShareCanvas:yt,onNewCanvas:s&&E!==`backends`?e=>{c(`${ia(s,e,E)}?createCanvas=1`)}:void 0,isLoading:dt,rootLabel:s??void 0,searchQuery:B,backends:ce,resyncingPaths:E===`backends`?R:void 0,onAddRule:s&&E===`backends`?me:void 0,onAddStoreRule:s?(e,t=`store`)=>{let n=E===`backends`?(()=>{let n=Bi(e);return{kind:t,storeTo:n?.backend||``,storeFolder:n?.rel||``}})():{kind:t,path:`${E===`directory`?`dir`:`ctx`}:${e}`,storeFolder:t===`download`?`Downloads`:zi(e)};c(`/workspaces/${s}/settings/hooks?${qi(n).toString()}`)}:void 0,onStoragePolicy:s&&(E===`context`||E===`directory`)?e=>ge(ol(E,e)):void 0,policyBadgeFor:ye,pastedDocumentIds:fe?.documentIds,isPathPinned:it,onTogglePin:s?at:void 0,onPasteDocuments:s&&E===`backends`?async(e,t)=>{let n=sr(e);if(!n)return!1;let r=e.split(`/`).filter(Boolean).slice(2).join(`/`),i=$e({title:`Moving…`,description:`${t.length} message(s) → ${r}`});try{let{moved:a,results:o}=await Ln(s,n.address,t,e),c=o.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}`}),fe&&a&&(H(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}))),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:s,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}}:s?async(e,t)=>{let n=Mn(E),r=E===`directory`?`directory`:Gn,i=$e({title:`Pasting…`,description:`${t.length} document(s) → "${e}"`}),a=!1;try{a=await _r(s,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&&(fe&&(H(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}))),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:s,path:e,treeName:r}}))),a}:void 0,...et},E)})}),pe&&s&&(0,Q.jsx)(tl,{workspaceId:s,sourcePath:pe,onClose:()=>me(null),onManageRules:()=>{me(null),c(`/workspaces/${s}/settings/hooks?section=rules`)}}),he&&s&&(0,Q.jsx)(bl,{workspaceId:s,path:he,onClose:()=>ge(null),onSaved:()=>{ve()}})]})}var Wl={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}},Gl=100,Kl=e=>e&&e.charAt(0).toUpperCase()+e.slice(1),ql=e=>Wl[e]??{label:`${Kl(e)} layers`,order:Gl};function Jl({type:e}){return e===`canvas`?(0,Q.jsx)(Je,{className:`w-3.5 h-3.5 shrink-0 text-primary`,"aria-label":`Canvas`}):e===`dataset`?(0,Q.jsx)(Ye,{className:`w-3.5 h-3.5 shrink-0 text-secondary`,"aria-label":`Dataset`}):(0,Q.jsx)(Ce,{className:`w-3.5 h-3.5 shrink-0 text-muted-foreground/60`,"aria-label":`Layer`})}function Yl(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:ql(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 Xl({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=Yl(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)(Jl,{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)(Pt,{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)(et,{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)(Pt,{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)(Ne,{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)(W,{className:`w-3 h-3`})})]})]},e.id))]},e.type))})}function Zl(){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`?Nc(d[3]):null,p=(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)(ec,{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)(bt,{className:`h-3.5 w-3.5`})})}),u?(0,Q.jsx)(Ac,{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 Ql=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 Te(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),xe(null)},children:`Clear selection`})]}):U&&(0,Q.jsx)(Cc,{x:U.x,y:U.y,node:U.node,path:U.path,isBackendsTree:i,backends:z,isDirectoryTree:r===`directory`,onClose:()=>xe(null),onShowContent:U.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:ye,clipboard:he,onStartInlineCreate:e=>Le(e),onChangeIcon:ce?()=>st({clientX:U.x,clientY:U.y,stopPropagation:()=>{}},U.path,U.node):void 0,onNewCanvas:S,onShareCanvas:C,onImportDocuments:d?void 0:A,onExportDocuments:j,onExportSubtree:O,onImportSubtree:d?void 0:k,onRemove:!d&&w&&![...Se.keys()].some(e=>e===U.path||e.startsWith(U.path+`/`)||U.path.startsWith(e+`/`))?Te:void 0,onRename:d?void 0:T,onLock:d?void 0:ee,onUnlock:d?void 0:P,onDestroy:d?void 0:F,onMerge:d?void 0:te,onSubtract:d?void 0:ne,onMergeDown:d?void 0:re,onSubtractDown:d?void 0:I,canResyncBackend:ae,onResyncBackend:ie,onAddRule:f,onAddStoreRule:p,onStoragePolicy:!d&&!i?m:void 0,onRenameBackendFolder:se,onDeleteBackendFolder:!d&&L&&![...Se.keys()].some(e=>e===U.path||e.startsWith(U.path+`/`)||U.path.startsWith(e+`/`))?e=>Te(e,!0):void 0,onCopy:e=>mt(e,`copy`),onCut:e=>mt(e,`cut`),onPaste:dt,pastedDocumentIds:M,onPasteDocuments:N,isPinned:le?le(U.path):!1,onTogglePin:R?()=>R(U.path,U.node):void 0}),Ee&&ce&&(0,Q.jsx)(ac,{x:Ee.x,y:Ee.y,current:Oe.get(Ee.path)??xi(Ee.node),onChange:lt,onClose:()=>De(null)})]})}function kc(){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)(ec,{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)(Oc,{root:d,workspaceId:l?.workspaceName,searchQuery:v,selectedPath:b,pendingPath:S,onSelect:M,isLoading:w,rootLabel:l?.workspaceName,...j})]})]})}function Ac({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)(Me,{className:G(`h-3.5 w-3.5 shrink-0`,r?`opacity-100`:`opacity-0`)})]},e.id)})]})})}var jc=[{id:`general`,label:`Workspace details`,description:`Rename, change appearance or remove this workspace`,icon:lt},{id:`backups`,label:`Backups`,description:`Save or restore documents, relations and tree placements`,icon:He},{id:`data`,label:`Files & storage`,description:`Connect folders and data sources, check disk usage or restore trash`,icon:A},{id:`db`,label:`Search & indexing`,description:`How documents become searchable: AI models, image descriptions, index repairs`,icon:Ye},{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:gt},{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:Rt},{id:`policies`,label:`Storage policies`,description:`Mirror folders of the virtual tree to physical backends`,icon:ue},{id:`hooks`,label:`Automation`,description:`Run hooks in response to workspace events`,icon:je}],Mc={embedding:`db`,trash:`data`};function Nc(e){return e?Mc[e]?Mc[e]:jc.some(t=>t.id===e)?e:`general`:`general`}var Pc=[{id:`general`,label:`Context details`,description:`Change the name, description or color, or remove this context`,icon:lt},{id:`location`,label:`Tree & path`,description:`Choose the workspace, tree and path this context opens`,icon:Rt},{id:`shares`,label:`Sharing & permissions`,description:`Choose who can access this context`,icon:ie}];function Fc(e){return e&&Pc.some(t=>t.id===e)?e:`general`}var Ic=[{id:`identity`,label:`Identity & instructions`,description:`Set the agent’s name, role and instructions`,icon:lt},{id:`provider`,label:`AI connection`,description:`Connect a chat model provider and manage its credentials`,icon:ne},{id:`models`,label:`Chat model`,description:`Choose the model and tune how it responds`,icon:we},{id:`tools`,label:`Tools & skills`,description:`Choose the skills and MCP tools the agent can use`,icon:U},{id:`access`,label:`Access & permissions`,description:`Choose which Canvas content the agent can access`,icon:P},{id:`memory`,label:`Memory`,description:`Configure how the agent remembers information`,icon:ye},{id:`integrations`,label:`Integrations`,description:`Connect mail, chat, databases and external APIs`,icon:tt}];function Lc(e){return e&&Ic.some(t=>t.id===e)?e:`identity`}function Rc(){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`?Fc(c[3]):null,u=a?`/contexts/${a}`:null,d=(0,Z.useMemo)(()=>Pc.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)(ec,{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)(bt,{className:`h-3.5 w-3.5`})})}),(0,Q.jsx)(Ac,{items:d,activeId:l,onSelect:e=>a&&r(`/contexts/${a}/settings/${e}`)})]})}function zc(e){return e.isShared||e.type===`shared`?e.id:e.name}function Bc(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)(()=>Js(t),[t]),isLoading:r,refresh:c}}function Vc({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 Hc(){let[e,t]=(0,Z.useState)(null),n=ms(),{state:r,selectEntity:a,openM2:o,closeM2:s}=la(),c=Fr(),{workspaces:l,isLoading:u}=Bc(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}=Zs((e,t)=>{let n=Ys(C,e,t);S({base:l,order:n}),Xs(n,(e,t)=>Qn(zc(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(zc(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(zc(e)),o(`detail`,zc(e)),!c&&ya(zc(e))&&f(va(zc(e)))},j=async(e,t)=>{e.stopPropagation(),h(e=>new Set(e).add(zc(t)));try{await ur(zc(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(zc(t)),n})}},M=async(e,t)=>{e.stopPropagation(),h(e=>new Set(e).add(zc(t)));try{await fr(zc(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(zc(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===zc(e),s=Ji(e),l=p.has(zc(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)(ae,{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:zc(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:zc(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)(Vc,{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)(Ot,{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)(le,{className:`w-3.5 h-3.5`})}),(0,Q.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),a(zc(e)),c?o(`settings`,zc(e)):f(`/workspaces/${zc(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=>zc(e)===g.name);if(!e)return null;let t=O(e);return(0,Q.jsx)(ac,{x:g.x,y:g.y,current:t,onChange:e=>k(g.name,t,e),onClose:()=>_(null)})})()]})}var Uc={previousTree:`Alt+Q`,nextTree:`Alt+W`},Wc=`canvas:key-bindings`,Gc=/^(Alt|Alt\+Shift|Ctrl\+Shift|Meta\+Shift)\+[A-Z]$/;function Kc(){try{let e=JSON.parse(localStorage.getItem(Wc)||`{}`),t={...Uc};for(let n of Object.keys(t))(e[n]===``||Gc.test(e[n]))&&(t[n]=e[n]);return t.previousTree&&t.previousTree===t.nextTree?{...Uc}:t}catch{return{...Uc}}}function qc(e){localStorage.setItem(Wc,JSON.stringify(e))}function Jc(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 Yc(e,t,n){return e[(Math.max(0,e.indexOf(t))+n+e.length)%e.length]}function Xc(e,t){return Math.abs(e)>=48&&Math.abs(e)>Math.abs(t)*1.5?e<0?1:-1:0}function Zc(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=Jc(e);if(!r)return;let i=Kc(),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=Xc(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 Qc(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 $c(e,t,n,r=!1,i=`forward`,a=`copy`,o,s){let c=Qc(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 el(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 tl({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{el(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)(Rt,{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:el(t,await gr(e)),a=$c(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 nl=e=>`/workspaces/${e}/storage-policies`;function rl(){return`policy-${crypto.randomUUID().slice(0,8)}`}function il(e){return e.filter(e=>e.enabled&&e.capabilities?.upload&&!e.config?.readOnly&&e.driver!==`cacache`)}var al=new Set([`file`]);function ol(e,t){return`${e===`directory`?`dir`:`ctx`}:${t.startsWith(`/`)?t:`/${t}`}`}function sl(e){let t=/^(ctx|dir):(\/.*)$/.exec(e);return t?{tree:t[1]===`dir`?`directory`:`context`,path:t[2]}:null}function cl(e){return(sl(e)?.path??e).replace(/^\/+/,``)}function ll(e){return`${e.backend}:${e.folder||`/`}`}async function ul(e){let t=await Y.get(nl(e));return{...t,policies:t?.policies??[],revision:t.revision,blobBackend:t?.blobBackend??null}}async function dl(e,t,n){return Y.put(nl(e),{policies:t,revision:n})}async function fl(e,t,n={}){return await Y.post(`${nl(e)}/${encodeURIComponent(t)}/apply`,n)}async function pl(e,t,n){let{policies:r,revision:i}=n??await ul(e),a=r.findIndex(e=>e.id===t.id);return dl(e,a===-1?[...r,t]:r.map((e,n)=>n===a?t:e),i)}async function ml(e,t,n,r={}){let i={folders:0,processed:0,matched:0,failed:0},a=0;for(;a!==null;){let o=await fl(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 hl(e,t,n){let r=ol(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 gl(e){let t=new Set;for(let n of e)for(let e of n.targets)t.add(ll(e));return[...t].join(`, `)}async function _l(e,t){await Y.post(`${nl(e)}/operations/${encodeURIComponent(t)}/retry`,{})}function vl(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 yl(e,t){return{backend:e?.address??``,folder:t,recursive:!0,recreateDirectories:!!e&&al.has(e.driver),onConflict:`error`}}function bl({workspaceId:e,path:t,policy:n,onClose:r,onSaved:i}){let a=!!n,[o]=(0,Z.useState)(()=>n?.id??rl()),[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)(()=>vl(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,F]=(0,Z.useState)(0),[te,ne]=(0,Z.useState)(0);hi(r,!D);let re=()=>{D||r()},I=(0,Z.useMemo)(()=>cl(t),[t]),ie=(0,Z.useMemo)(()=>il(C??[]).filter(e=>s===`filing`||e.driver===`file`),[C,s]),ae=(0,Z.useMemo)(()=>new Map(ie.map(e=>[e.address,e])),[ie]);(0,Z.useEffect)(()=>{let t=!1;return Promise.all([gr(e),ul(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=il(e).find(e=>n?.kind===`filing`||e.driver===`file`);i&&b(e=>e.length?e:[yl(i,I)])}).catch(e=>{t||(w([]),M(e instanceof Error?e.message:`Could not load backends`))}),()=>{t=!0}},[e,I,n]);let oe=(e,t)=>b(n=>n.map((n,r)=>r===e?{...n,...t}:n)),se=(e,t)=>{let n=ae.get(t),r=!!n&&al.has(n.driver);oe(e,{backend:t,recreateDirectories:r?y[e].recreateDirectories:!1})},L=()=>{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}},ce=async()=>{if(!D){O(!0),M(``);try{let t=L();T||(await pl(e,t,x),E(!0),i?.(t)),ee(0),F(0),ne(0),await ml(e,o,(e,t)=>{ee(t.matched),F(t.folders),ne(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)}}},le=!!x&&y.length>0&&y.every(e=>e.backend);return(0,Q.jsx)(Ti,{onClose:re,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)(ue,{className:`h-4 w-4`}),a?`Edit storage policy`:`Storage policy`]}),(0,Q.jsx)(`button`,{type:`button`,onClick:re,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&&!ie.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=ae.get(e.backend),r=s===`mirror`&&!!n&&al.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…`}),ie.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=>oe(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=>oe(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=>oe(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=>oe(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=>oe(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||!ie.length,onClick:()=>b(e=>[...e,yl(ie.find(t=>!e.some(e=>e.backend===t.address))??ie[0],I)]),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.`]}),te>0&&(0,Q.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[te,` 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:re,children:`Cancel`}),k?(0,Q.jsx)(K,{onClick:r,children:`Done`}):(0,Q.jsx)(K,{disabled:D||!le,onClick:ce,children:D?`Applying…`:T?`Retry existing documents`:a?`Save policy`:`Enable policy`})]})]})})}var xl={policies:[],revision:``,loading:!1,error:``},Sl=new Map,Cl=new Set;function wl(){for(let e of Cl)e()}function Tl(e){return Cl.add(e),()=>{Cl.delete(e)}}function El(e,t){Sl.set(e,t),wl()}async function Dl(e){El(e,{...Sl.get(e)??xl,loading:!0,error:``});try{let{policies:t,revision:n,status:r}=await ul(e);El(e,{policies:t,revision:n,status:r,loading:!1,error:``})}catch(t){El(e,{policies:[],revision:``,loading:!1,error:t instanceof Error?t.message:`Could not load storage policies`})}}function Ol(e){Sl.delete(e),wl()}function kl(e){let t=(0,Z.useSyncExternalStore)(Tl,()=>e&&Sl.get(e)||xl),n=!!e&&!Sl.has(e);(0,Z.useEffect)(()=>{e&&n&&Dl(e)},[e,n]);let r=(0,Z.useCallback)(async()=>{e&&await Dl(e)},[e]);return(0,Z.useEffect)(()=>{if(!e||!t.policies.length)return;let n=window.setInterval(()=>{!document.hidden&&!Sl.get(e)?.loading&&Dl(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 Al(){return await Y.get(`${J}/users/me/config/webui`)??{}}async function jl(e){return await Y.put(`${J}/users/me/config/webui`,e)??e}var Ml=`application/x-canvas-workspace-pin`;function Nl({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(Ml,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)(Pt,{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)(Dt,{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)(xe,{className:`w-3.5 h-3.5`})})]}),!p&&(0,Q.jsx)(ae,{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 Pl=()=>({selectedPath:`/`,contentPath:null,searchQuery:``,expansion:new Map}),Fl=[`pins`,`context`,`layers`,`directory`,`backends`],Il=e=>typeof e==`string`&&Fl.includes(e),Ll=e=>{let t=Array.isArray(e)?e.filter(Il).filter((e,t,n)=>n.indexOf(e)===t):[];return[...t,...Fl.filter(e=>!t.includes(e))]},Rl={pins:(0,Q.jsx)(V,{className:`w-3.5 h-3.5`}),context:(0,Q.jsx)(Fe,{className:`w-3.5 h-3.5`}),layers:(0,Q.jsx)(Ce,{className:`w-3.5 h-3.5`}),directory:(0,Q.jsx)(Dt,{className:`w-3.5 h-3.5`}),backends:(0,Q.jsx)(Ye,{className:`w-3.5 h-3.5`})},zl={pins:`Pins`,context:`Context tree`,layers:`Context layers`,directory:`Directory tree`,backends:`Backends tree`},Bl=e=>e===`directory`||e===`backends`?e:Gn,Vl=(e,t)=>t?`layers`:e===`directory`?`directory`:e===`backends`?`backends`:`context`;function Hl(){let{state:e}=la();return e.selectedEntityId?(0,Q.jsx)(xa,{workspaceName:e.selectedEntityId,children:(0,Q.jsx)(Ul,{},e.selectedEntityId)}):null}function Ul(){let{state:e,closeM2:t,openM2:n,openM1Drawer:r,navigateFromMenu:i}=la(),a=xr(),o=Fr(),s=e.selectedEntityId,c=m(),l=h(),{treeName:u,path:d}=ra(l.pathname),f=new URLSearchParams(l.search).get(`layer`)===`1`,p=new URLSearchParams(l.search).get(`layerId`),g=/\/trees\/|\/path(\/|$)/.test(l.pathname)||!!p,_=g?Vl(u,p):Fl[0],[v,y]=(0,Z.useState)(!1),[b,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(null),[w,T]=(0,Z.useState)({icon:null,color:null}),[E,D]=(0,Z.useState)(_),[O,k]=(0,Z.useState)(null),[A,j]=(0,Z.useState)(null),[M,N]=(0,Z.useState)(null),[ee,P]=(0,Z.useState)([]),[F,te]=(0,Z.useState)(!1),[ne,re]=(0,Z.useState)(!1),[I,ie]=(0,Z.useState)(!1),[ae,oe]=(0,Z.useState)(!1),[se,L]=(0,Z.useState)(d),[ce,le]=(0,Z.useState)([]),[R,ue]=(0,Z.useState)(new Set),[de,z]=(0,Z.useState)(f&&d!==`/`?d:null),[B,V]=(0,Z.useState)(``),[fe,H]=(0,Z.useState)(null),[pe,me]=(0,Z.useState)(null),[he,ge]=(0,Z.useState)(null),{policies:_e,refresh:ve}=kl(s),ye=(0,Z.useCallback)(e=>{if(E!==`context`&&E!==`directory`||!_e.length)return null;let t=hl(_e,E,e);return t.length?`Storage policy targets: ${gl(t)} (see Settings for transfer status)`:null},[E,_e]),[be,U]=(0,Z.useState)([]),[xe,Se]=(0,Z.useState)(!1),[Ce,we]=(0,Z.useState)(!1),Te=(0,Z.useRef)(null),Ee=(0,Z.useRef)(new Map),[De,Oe]=(0,Z.useState)(()=>Object.fromEntries(Fl.map(e=>[e,Pl()])));(0,Z.useLayoutEffect)(()=>{Te.current&&(Te.current.scrollTop=Ee.current.get(E)??0)},[E]);let ke=De[E];(ke.selectedPath!==se||ke.contentPath!==de||ke.searchQuery!==B)&&Oe({...De,[E]:{...ke,selectedPath:se,contentPath:de,searchQuery:B}});let Ae=(0,Z.useRef)(!1),[je,Me]=(0,Z.useState)(!1),[Ne,Pe]=(0,Z.useState)(Fl),Fe=!g;(0,Z.useEffect)(()=>{let e=!1;return Al().then(t=>{if(e)return;let n=Ll(t?.m2?.tabOrder);Pe(n),Fe&&D(e=>e===Fl[0]?n[0]:e)}).catch(()=>{}),()=>{e=!0}},[]);let Ie=(0,Z.useCallback)(async e=>{let t=Ne;Pe(e);try{let t=await Al();await jl({...t,m2:{...t.m2,tabOrder:e}})}catch{Pe(t)}},[Ne]),[W,Le]=(0,Z.useState)(null),[Re,ze]=(0,Z.useState)(null),Be=()=>{Le(null),ze(null)},Ve=()=>{if(W&&Re&&W!==Re.id){let e=Ne.filter(e=>e!==W),t=e.indexOf(Re.id);t>=0&&(e.splice(Re.before?t:t+1,0,W),e.some((e,t)=>e!==Ne[t])&&Ie(e))}Be()};(0,Z.useEffect)(()=>{let e=e=>H(e.detail??null);return window.addEventListener(`documents:clipboard`,e),()=>window.removeEventListener(`documents:clipboard`,e)},[]);let[He,Ue]=(0,Z.useState)(d);d!==He&&(Ue(d),L(d));let We=(0,Z.useRef)(new Map),Ge=(0,Z.useCallback)(async(e,t,n=!1,r=!1)=>{let i=Symbol();We.current.set(t,i);let a=()=>We.current.get(t)===i,o=t===`context`?te:t===`directory`?re:ie,s=t===`context`?k:t===`directory`?j:N;n||o(!0);try{n&&!r&&ar(e,t);let i=await In(e,t);a()&&s(i)}catch{}finally{a()&&o(!1)}},[]),Ke=(0,Z.useCallback)(async(e,t=!1)=>{let n=Symbol();We.current.set(`pins`,n);let r=()=>We.current.get(`pins`)===n;t||Se(!0);try{let t=await Pn(e);r()&&U(t)}catch{}finally{r()&&Se(!1)}},[]),qe=(0,Z.useCallback)(async(e,t=!1)=>{let n=Symbol();We.current.set(`layers`,n);let r=()=>We.current.get(`layers`)===n;t||oe(!0);try{let t=await qn(e,`context`);r()&&P(t)}catch{}finally{r()&&oe(!1)}},[]);(0,Z.useEffect)(()=>{if(!s)return;let e=s,t=!1,n=We.current;async function r(){Un(e).then(e=>{t||(x(e.label||e.name),y(Ji(e)),C(e.id||null),T({icon:e.icon??null,color:e.color??null}))}).catch(()=>{}),await Promise.all([Ge(e,`context`),Ge(e,`directory`),Ge(e,`backends`),qe(e),Ke(e)])}return r(),()=>{t=!0,n.clear()}},[s,Ge,qe,Ke]);let Je=(0,Z.useCallback)((e,t,n=!1)=>{for(let r of[`context`,`directory`,`backends`])(!t||t===r)&&Ge(e,r,!0,n);(!t||t===`context`)&&qe(e,!0),Ke(e,!0)},[Ge,qe,Ke]),Ye=(0,Z.useCallback)(()=>{s&&Je(s)},[s,Je]);(0,Z.useEffect)(()=>{if(!s)return;let e=e=>{e.detail?.workspaceName&&e.detail.workspaceName!==s||Je(s,e.detail?.treeName,e.detail?.cacheInvalidated)};return window.addEventListener(`workspace:tree:refresh`,e),()=>window.removeEventListener(`workspace:tree:refresh`,e)},[s,Je]),(0,Z.useEffect)(()=>{if(!s)return;let e=!1,t=()=>gr(s).then(t=>{e||(le(t),ue(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!==s||(!n?.treeName||n.treeName===`backends`)&&t()};return window.addEventListener(`workspace:tree:refresh`,n),()=>{e=!0,window.removeEventListener(`workspace:tree:refresh`,n)}},[s]),(0,Z.useEffect)(()=>{if(!s)return;let e=[`workspace:${s}`,S?`workspace:${S}`:null].filter(Boolean),t=()=>e.forEach(e=>X.emit(`subscribe`,{channel:e})),n=X.on(`connect`,t);t();let r=Or(s,S),i=e=>{if(e?.workspaceId&&S&&e.workspaceId!==S)return;let t=e?.treePath;t&&ue(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&&S&&e.workspaceId!==S||Ke(s,!0)};return X.on(`pins.changed`,a),()=>{r(),n?.(),X.off(`backend.resync.changed`,i),X.off(`pins.changed`,a)}},[s,S,Ke]);let[Xe,Ze]=(0,Z.useState)(null),Qe=`${l.pathname}|${l.search}`;if(Qe!==Xe){Ze(Qe);let{treeName:e,path:t}=ra(l.pathname),n=new URLSearchParams(l.search).get(`layerId`),r=/\/trees\/|\/path(\/|$)/.test(l.pathname)||!!n;Ce?we(!1):D(r||je?r?Vl(e,n):E:Ne[0]),L(t),z(t===`/`?null:t)}let{showProgress:$e}=xn();(0,Z.useEffect)(()=>{s&&Ui($e,s)},[s,$e]);let et=Ar({workspaceId:s??void 0,treeName:Bl(E),onRefresh:Ye}),tt=(0,Z.useRef)(new Map);(0,Z.useEffect)(()=>{if(!s)return;let e=`${s}:${E}:${se}`,t=et;t.canResyncBackend(se)&&(Date.now()-(tt.current.get(e)||0)<6e4||(tt.current.set(e,Date.now()),t.onCheckMailboxes?.(se).catch(()=>{})))},[s,E,se,et]);let nt=new Set(be.map(e=>hr(e.tree,e.path))),rt=Bl(E),it=(0,Z.useCallback)(e=>nt.has(hr(rt,e)),[be,rt]),at=(0,Z.useCallback)(async e=>{if(!s)return;let t=be.find(t=>hr(t.tree,t.path)===hr(rt,e));t?await ir(s,t.id):await An(s,e,rt),await Ke(s)},[s,be,rt,Ke]),ot=(0,Z.useCallback)(async e=>{if(s){U(t=>t.filter(t=>t.id!==e.id));try{await ir(s,e.id)}finally{await Ke(s)}}},[s,Ke]),st=(0,Z.useCallback)(async(e,t)=>{if(!s)return;let n=be.find(t=>t.id===e);if(!n)return;let r=be.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===be[t])){U(a);try{U(await Xn(s,a.map(e=>e.id)))}catch(e){throw await Ke(s),e}}},[s,be,Ke]),ct=(0,Z.useCallback)(e=>{if(!s)return;we(!0),L(e.path),z(null);let t=ia(s,e.path,e.tree);if(a){a.activateRow(`pin:${s}:${e.id}`,e.label||e.name||e.path,t);return}i(t)},[s,i,a]),lt=(0,Z.useCallback)(e=>{!s||e.resolvable===!1||(we(!1),Me(!0),D(Vl(e.tree)),L(e.path),z(null),V(``),Ae.current=!0,a?.setFocus(`main`),i(ia(s,e.path,e.tree)))},[s,i,a]),ut=E===`context`?O:E===`directory`?A:E===`backends`?M:null,dt=E===`context`?F:E===`directory`?ne:E===`backends`&&I;(0,Z.useEffect)(()=>{if(!Ae.current||dt||E===`pins`)return;let e=Te.current?.querySelector(`[data-active="true"]`);e&&(e.scrollIntoView({block:`nearest`,inline:`nearest`}),Ae.current=!1)},[E,se,ut,dt]);let ft=(0,Z.useCallback)(e=>{Me(!0),D(e);let t=De[e];L(t.selectedPath),z(t.contentPath),V(t.searchQuery)},[De]),mt=(0,Z.useCallback)(e=>{ft(Yc(Ne,E,e))},[Ne,E,ft]),ht=Zc(e.m2Open,mt),gt=e=>{z(null),L(e);let t=Bl(E);a?.setFocus(`main`),i(ia(s,e,t))},_t=(0,Z.useCallback)((e,t)=>{L(e),z(e);let n=Bl(E),r=new URLSearchParams;r.set(`layer`,`1`),t&&r.set(`layerId`,t),a?.setFocus(`main`),i(`${ia(s,e,n)}?${r.toString()}`)},[s,E,i,a]),vt=(0,Z.useCallback)((e,t)=>{if(s){if(a){a.openCanvas({kind:`route`,location:ia(s,e,t)});return}window.dispatchEvent(new CustomEvent(`workspace:open-to-side`,{detail:{workspaceName:s,treeName:t,path:e}}))}},[s,a]),yt=(0,Z.useCallback)(async e=>{if(!s)return;let t=Bl(E),n=await Zn(s,e,t),r=`${window.location.origin}${n.url}`;await navigator.clipboard?.writeText(r),alert(`Canvas share link copied:\n${r}`)},[s,E]),xt=B.toLowerCase().trim(),St=xt?ee.filter(e=>e.name.toLowerCase().includes(xt)||(e.label||``).toLowerCase().includes(xt)||(e.description||``).toLowerCase().includes(xt)):ee;return(0,Q.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Q.jsx)(ec,{title:b||s||`Workspace`,icon:w.icon||`ph:stack-fill`,accentColor:w.color,onBack:o?()=>r(`workspaces`):t,backLabel:o?`Browse workspaces`:`Back to previous view`,action:(0,Q.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,Q.jsx)(`button`,{type:`button`,onClick:()=>s&&i(va(s)),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)(bt,{className:`w-3.5 h-3.5`})}),(0,Q.jsx)(`button`,{type:`button`,disabled:!v,onClick:()=>{o?n(`settings`,s??null):c(`/workspaces/${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 disabled:opacity-40 disabled:cursor-not-allowed`,title:v?`Settings`:`Workspace settings require admin access`,children:(0,Q.jsx)(pt,{className:`w-3.5 h-3.5`})})]})}),(0,Q.jsx)(`div`,{...ht,className:`flex border-b border-border shrink-0 touch-pan-y`,"aria-label":`Workspace trees`,children:Ne.map(e=>(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>ft(e),title:`${zl[e]} — drag to reorder; the first tab opens by default`,"aria-label":zl[e],"aria-pressed":E===e,draggable:!0,onDragStart:t=>{t.dataTransfer.setData(`text/plain`,e),t.dataTransfer.effectAllowed=`move`,Le(e)},onDragEnd:Be,onDragOver:t=>{if(!W||W===e)return;t.preventDefault(),t.dataTransfer.dropEffect=`move`;let n=t.currentTarget.getBoundingClientRect(),r=t.clientX<n.left+n.width/2;ze(t=>t?.id===e&&t.before===r?t:{id:e,before:r})},onDrop:e=>{e.preventDefault(),Ve()},className:G(`relative flex-1 flex items-center justify-center py-2 transition-colors`,E===e?`text-foreground border-b-2 border-foreground -mb-px`:`text-muted-foreground hover:text-foreground`,W===e&&`opacity-40`,Re?.id===e&&Re.before&&`shadow-[inset_2px_0_0_0_hsl(var(--primary))]`,Re?.id===e&&!Re.before&&`shadow-[inset_-2px_0_0_0_hsl(var(--primary))]`),children:[Rl[e],e===`pins`&&be.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:be.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:E===`layers`?`Search layers…`:E===`pins`?`Search pins…`:`Search paths…`,value:B,onChange:e=>V(e.target.value)})]})}),(0,Q.jsx)(`div`,{ref:Te,onScroll:e=>{Ee.current.set(E,e.currentTarget.scrollTop)},className:`flex-1 overflow-y-auto`,children:(0,Q.jsx)(ba,{workspaceId:s,treeName:Bl(E),readOnly:!v,className:`min-h-full`,children:E===`pins`?(0,Q.jsx)(Nl,{pins:be,isLoading:xe,searchQuery:B,activeKey:hr(u,d),onOpen:ct,onShowInTree:lt,onUnpin:ot,onMove:st}):E===`layers`?(0,Q.jsx)(Xl,{layers:St,isLoading:ae,wsName:s??``,onSelect:e=>{let t=new URLSearchParams;t.set(`layerId`,e.id),t.set(`layer`,`1`),i(`${ia(s,`/`)}?${t.toString()}`)},onLock:async e=>{await Hn(s,e.id,s,`context`),Je(s)},onUnlock:async e=>{await cr(s,e.id,s,`context`),Je(s)},onRename:async(e,t)=>{await Yn(s,e.id,t,`context`),Je(s)},onDestroy:async e=>{confirm(`Destroy layer "${e.label||e.name}"? This cannot be undone.`)&&(await zn(s,e.id,`context`),Je(s))}}):(0,Q.jsx)(Oc,{expansionState:De[E].expansion,root:ut,workspaceId:s??void 0,treeName:E,isBackendsTree:E===`backends`,onRestoreTrash:s?e=>Gi(s,e):void 0,onDiscardTrash:s?e=>Wi(s,e):void 0,onAltSelect:a?e=>vt(e,Bl(E)):void 0,selectedPath:se,contentPath:de,onSelect:gt,onShowContent:E===`context`?_t:void 0,onOpenToSide:vt,onShareCanvas:yt,onNewCanvas:s&&E!==`backends`?e=>{c(`${ia(s,e,E)}?createCanvas=1`)}:void 0,isLoading:dt,rootLabel:s??void 0,searchQuery:B,backends:ce,resyncingPaths:E===`backends`?R:void 0,onAddRule:s&&E===`backends`?me:void 0,onAddStoreRule:s?(e,t=`store`)=>{let n=E===`backends`?(()=>{let n=Bi(e);return{kind:t,storeTo:n?.backend||``,storeFolder:n?.rel||``}})():{kind:t,path:`${E===`directory`?`dir`:`ctx`}:${e}`,storeFolder:t===`download`?`Downloads`:zi(e)};c(`/workspaces/${s}/settings/hooks?${qi(n).toString()}`)}:void 0,onStoragePolicy:s&&(E===`context`||E===`directory`)?e=>ge(ol(E,e)):void 0,policyBadgeFor:ye,pastedDocumentIds:fe?.documentIds,isPathPinned:it,onTogglePin:s?at:void 0,onPasteDocuments:s&&E===`backends`?async(e,t)=>{let n=sr(e);if(!n)return!1;let r=e.split(`/`).filter(Boolean).slice(2).join(`/`),i=$e({title:`Moving…`,description:`${t.length} message(s) → ${r}`});try{let{moved:a,results:o}=await Ln(s,n.address,t,e),c=o.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}`}),fe&&a&&(H(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}))),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:s,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}}:s?async(e,t)=>{let n=Mn(E),r=E===`directory`?`directory`:Gn,i=$e({title:`Pasting…`,description:`${t.length} document(s) → "${e}"`}),a=!1;try{a=await _r(s,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&&(fe&&(H(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}))),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:s,path:e,treeName:r}}))),a}:void 0,...et},E)})}),pe&&s&&(0,Q.jsx)(tl,{workspaceId:s,sourcePath:pe,onClose:()=>me(null),onManageRules:()=>{me(null),c(`/workspaces/${s}/settings/hooks?section=rules`)}}),he&&s&&(0,Q.jsx)(bl,{workspaceId:s,path:he,onClose:()=>ge(null),onSaved:()=>{ve()}})]})}var Wl={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}},Gl=100,Kl=e=>e&&e.charAt(0).toUpperCase()+e.slice(1),ql=e=>Wl[e]??{label:`${Kl(e)} layers`,order:Gl};function Jl({type:e}){return e===`canvas`?(0,Q.jsx)(Je,{className:`w-3.5 h-3.5 shrink-0 text-primary`,"aria-label":`Canvas`}):e===`dataset`?(0,Q.jsx)(Ye,{className:`w-3.5 h-3.5 shrink-0 text-secondary`,"aria-label":`Dataset`}):(0,Q.jsx)(Ce,{className:`w-3.5 h-3.5 shrink-0 text-muted-foreground/60`,"aria-label":`Layer`})}function Yl(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:ql(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 Xl({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=Yl(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)(Jl,{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)(Pt,{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)(et,{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)(Pt,{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)(Ne,{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)(W,{className:`w-3 h-3`})})]})]},e.id))]},e.type))})}function Zl(){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`?Nc(d[3]):null,p=(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)(ec,{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)(bt,{className:`h-3.5 w-3.5`})})}),u?(0,Q.jsx)(Ac,{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 Ql=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}},$l=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 Ql.handleStreamingResponse(t,{onChunk:e=>{try{Ql.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)}}},eu=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 tu(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 nu(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 ru(e){if(!e)return;let t=nu(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 iu(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 au(e=[]){return e.filter(e=>e?.role===`user`||e?.role===`assistant`).map(e=>({role:e.role,content:tu(e),timestamp:iu(e.timestamp),...e.role===`assistant`?{metadata:ru(e)}:{}})).filter(e=>e.content||e.metadata?.reasoning)}function ou(e){return{mode:e?.mode,sessionId:e?.sessionId,sessionFile:e?.sessionFile,thinkingLevel:e?.thinkingLevel,model:e?.model,messages:au(e?.messages||[])}}function su(e){return{current:ou(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 eu(e)}catch(e){console.warn(`WebSocket fallback not available:`,e)}}registerAgent(e){if(e.type===`anthropic`){let t=new $l(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 cu(e){return await Y.get(`${J}/agents/${e}/access`)||null}async function lu(e,t,n){return Y.put(`${J}/agents/${e}/access/grants/${encodeURIComponent(t)}`,n)}async function uu(e,t){return Y.post(`${J}/agents/${e}/access/grants/${encodeURIComponent(t)}/token`)}async function du(e,t){return Y.delete(`${J}/agents/${e}/access/grants/${encodeURIComponent(t)}`)}async function fu(e){await Y.delete(`${J}/agents/${e}/access`)}async function pu(e){return await Y.get(`${J}/agents/${e}/tools`)||{tools:[],config:{}}}async function mu(){try{return await Y.get(`${J}/agents`)||[]}catch(e){return console.error(`Failed to list agents:`,e),[]}}async function hu(e){return await Y.get(`${J}/agents/${e}`)}async function gu(e){return ou(await Y.get(`${J}/agents/${e}/session`))}async function _u(e){return await Y.get(`${J}/agents/${e}/sessions`)}async function vu(e,t){return su(await Y.post(`${J}/agents/${e}/sessions`,t))}async function yu(e,t){return su(await Y.put(`${J}/agents/${e}/session`,t))}async function bu(e,t,n){return su(await Y.patch(`${J}/agents/${e}/sessions/${t}`,n))}async function xu(e,t){return su(await Y.delete(`${J}/agents/${e}/sessions/${t}`))}async function Su(e){return await Y.get(`${J}/agents/${e}/skills`)||[]}async function Cu(e,t){return await Y.post(`${J}/agents/${e}/skills`,t)||[]}async function wu(e,t){return await Y.delete(`${J}/agents/${e}/skills/${encodeURIComponent(t)}`)||[]}async function Tu(e){return await Y.post(`${J}/agents`,e)}async function Eu(e,t){return await Y.put(`${J}/agents/${e}`,t)}async function Du(e){await Y.delete(`${J}/agents/${e}`)}async function Ou(e){return await Y.post(`${J}/agents/${e}/start`)}async function ku(e){return await Y.post(`${J}/agents/${e}/stop`)}async function Au(e){return await Y.get(`${J}/agents/${e}/status`)}async function ju(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(`
@@ -13,4 +13,4 @@ import{o as e,r as t}from"./rolldown-runtime-C0FnF6B9.js";import{l as n,u as r}f
13
13
 
14
14
  `:``}${r||`Prompt stream failed`}`:p?``:r;i?.(a,!0,{...n.metadata||{},...ru(e)||{}})}else n.type===`error`&&h(n.error||`Prompt stream failed`)}}},onError:a,onComplete:o})}async function Mu(e,t){let{message:n,onMessage:r,onError:i,onComplete:a,context:o,mcpContext:s,maxTokens:c,temperature:l,images:u}=t;try{let t=await Y.post(`${J}/agents/${e}/prompt`,{message:n,images:u,context:o,mcpContext:s,maxTokens:c,temperature:l}),i=Array.isArray(t.messages)?[...t.messages].reverse().find(e=>e?.role===`assistant`):null,d={content:tu(i),metadata:ru(i)};return r&&r(d.content,!0,d.metadata),a&&a(),d}catch(e){throw i&&i(e),e}}function Nu(e){return e.map(e=>({...e,timestamp:typeof e.timestamp==`string`?e.timestamp:new Date().toISOString()}))}async function Pu(){return await Y.get(`${J}/voice/status`)}async function Fu(e,t,n={}){let r=new FormData,i=(t.type.split(`/`)[1]||`webm`).split(`;`)[0];n.viewContext!==void 0&&r.append(`viewContext`,JSON.stringify(n.viewContext)),r.append(`file`,t,`voice.${i}`);let a=new URLSearchParams;n.tts===!1&&a.set(`tts`,`false`),n.voice&&a.set(`voice`,n.voice);let o=a.toString()?`?${a.toString()}`:``;return await Y.post(`${J}/agents/${e}/voice${o}`,r)}function Iu(e,t){return Y.post(`${J}/agents/models`,e,{signal:t})}function Lu(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 mu();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch agents:`,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:`agent`}),r=()=>X.emit(`unsubscribe`,{channel:`agent`}),i=X.on(`connect`,()=>{t(),s()});t();let a=e=>{let t=e?.agent??e;t?.id&&n(e=>e.some(e=>e.id===t.id)?e:[...e,t])},o=e=>{let t=e?.agent??e;t?.id&&n(e=>e.map(e=>e.id===t.id?{...e,...t}:e))},c=e=>{let t=e,r=t?.agentId??t?.id;r&&n(e=>e.filter(e=>e.id!==r))},l=e=>{let t=e,r=t?.agentId??t?.id,i=t?.status;!r||!i||n(e=>e.map(e=>e.id===r?{...e,status:i}:e))},u=[[`agent:created`,a],[`agent.created`,a],[`agent:updated`,o],[`agent.updated`,o],[`agent:deleted`,c],[`agent.deleted`,c],[`agent:status:changed`,l],[`agent.status.changed`,l]];return u.forEach(([e,t])=>X.on(e,t)),()=>{r(),i?.(),u.forEach(([e,t])=>X.off(e,t))}},[e,s]),(0,Z.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`agents:refresh`,e),()=>window.removeEventListener(`agents:refresh`,e)},[s]),{agents:t,isLoading:r,refresh:c}}function Ru({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`:e===`starting`||e===`stopping`?`bg-warning`:`bg-muted-foreground`),title:e})}function zu(){let e=ms(),{state:t,selectEntity:n,openM2:r,closeM2:i}=la(),a=Fr(),{agents:o,isLoading:s,refresh:c}=Lu(t.activeSection===`agents`),{showToast:l}=xn(),[u,d]=(0,Z.useState)(new Set),f=m(),p=e=>{n(e.id),r(`detail`,e.id),f(`/agents/${encodeURIComponent(e.name||e.id)}`)},h=async(e,t)=>{e.stopPropagation(),d(e=>new Set(e).add(t.id));try{await Ou(t.id),c(),l({title:`Success`,description:`${t.label||t.name} started`})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Start failed`,variant:`destructive`})}finally{d(e=>{let n=new Set(e);return n.delete(t.id),n})}},g=async(e,t)=>{e.stopPropagation(),d(e=>new Set(e).add(t.id));try{await ku(t.id),c(),l({title:`Success`,description:`${t.label||t.name} stopped`})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Stop failed`,variant:`destructive`})}finally{d(e=>{let n=new Set(e);return n.delete(t.id),n})}};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:`Agents`})]}),!e.local&&(0,Q.jsx)(`button`,{type:`button`,onClick:()=>{i(),f(`/agents?create=1`)},title:`Create agent`,"aria-label":`Create agent`,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 agents found`}):(0,Q.jsx)(`div`,{className:`space-y-1.5 px-2`,children:o.map(e=>{let i=t.selectedEntityId===e.id,o=u.has(e.id);return(0,Q.jsxs)(`div`,{"data-active":i||void 0,className:G(`group relative rounded-(--card-radius) px-3 py-2.5 cursor-pointer transition-all shadow-elevation-1 hover:shadow`,i?`bg-accent shadow`:`bg-card hover:bg-accent/50`),style:{borderRight:`6px solid ${e.color||`transparent`}`},onClick:()=>p(e),children:[(0,Q.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(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)(Ru,{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:o,onClick:t=>g(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)(Ot,{className:`w-3.5 h-3.5`})}):(0,Q.jsx)(`button`,{type:`button`,disabled:o,onClick:t=>h(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)(le,{className:`w-3.5 h-3.5`})}),(0,Q.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),n(e.id),a?r(`settings`,e.id):f(`/agents/${encodeURIComponent(e.name||e.id)}/settings/identity`)},className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground transition-colors`,title:`Settings`,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})]},e.id)})})})]})}var Bu=(0,Z.createContext)(null);function Vu(e){let t=(0,Z.useContext)(Bu);if(!t)throw Error(`useAgentSessions must be used within an AgentSessionProvider`);let{getState:n,refresh:r,create:i,select:a,rename:o,remove:s}=t,c=n(e),l=(0,Z.useCallback)(()=>r(e),[r,e]),u=(0,Z.useCallback)(t=>i(e,t),[i,e]),d=(0,Z.useCallback)(t=>a(e,t),[a,e]),f=(0,Z.useCallback)((t,n)=>o(e,t,n),[o,e]),p=(0,Z.useCallback)(t=>s(e,t),[s,e]);return(0,Z.useMemo)(()=>({...c,refresh:l,create:u,select:d,rename:f,remove:p}),[c,l,u,d,f,p])}function Hu(e){return e.name?.trim()?e.name.trim():e.firstMessage?.trim()?e.firstMessage.trim():e.isExperimental?`Experimental`:e.id.slice(0,8)}function Uu(e){let t=new Date(e.updatedAt).toLocaleString();return e.messageCount>0?`${e.messageCount} msg${e.messageCount===1?``:`s`} • ${t}`:`Empty • ${t}`}function Wu(e){return e.sessions.sessions.find(t=>t.id===e.current.sessionId||t.path===e.current.sessionFile||t.id===e.sessions.currentSessionId||t.path===e.sessions.currentSessionPath||t.isCurrent)||null}function Gu(){let{state:e,closeM2:t}=la(),n=e.selectedEntityId||``,r=m(),{showToast:i}=xn(),[a,o]=(0,Z.useState)(null),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(``),[d,f]=(0,Z.useState)(null),[p,h]=(0,Z.useState)(``),{current:g,sessions:_,isLoading:v,error:y,refresh:b,create:x,select:S,rename:C,remove:w}=Vu(n);(0,Z.useEffect)(()=>{n&&(hu(n).then(o).catch(()=>{}),b().catch(e=>{i({title:`Error`,description:e instanceof Error?e.message:`Failed to load sessions`,variant:`destructive`})}))},[n,b,i]);let T=(0,Z.useMemo)(()=>_?.sessions?_.currentSessionId?_.sessions.find(e=>e.id===_.currentSessionId)||null:_.currentSessionPath?_.sessions.find(e=>e.path===_.currentSessionPath)||null:_.sessions.find(e=>e.isCurrent)||null:null,[_]),E=a?.name||n,D=e=>e?.slug||e?.id,O=e=>{let t=typeof e==`string`?e:D(e);r(t?`/agents/${encodeURIComponent(E)}/${encodeURIComponent(t)}`:`/agents/${encodeURIComponent(E)}`)},k=async()=>{try{let e=await x({mode:`persistent`,name:l.trim()||void 0});c(!1),u(``),O(Wu(e))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to create session`,variant:`destructive`})}},A=async()=>{try{let e=await x({mode:`experimental`});O(Wu(e))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to open experimental session`,variant:`destructive`})}},j=async()=>{try{await x({mode:`incognito`}),O()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to open incognito session`,variant:`destructive`})}},M=async e=>{try{e.isExperimental?await S({mode:`experimental`}):await S({mode:`persistent`,sessionId:e.id}),O(e)}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to select session`,variant:`destructive`})}},N=async e=>{if(p.trim())try{let t=(await C(e.id,p.trim())).sessions.sessions.find(t=>t.id===e.id);f(null),h(``),T?.id===e.id&&O(t||e)}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to rename session`,variant:`destructive`})}},ee=async e=>{if(!e.isExperimental&&window.confirm(`Delete session "${Hu(e)}"?`))try{await w(e.id),O()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to delete session`,variant:`destructive`})}};return(0,Q.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Q.jsx)(ec,{title:a?.label||a?.name||n,onBack:t,action:(0,Q.jsx)(`button`,{type:`button`,onClick:()=>r(`/agents/${encodeURIComponent(E)}/settings`),className:`flex h-8 w-8 items-center justify-center rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Agent settings`,children:(0,Q.jsx)(pt,{className:`h-3.5 w-3.5`})})}),(0,Q.jsxs)(`div`,{className:`border-b border-border px-4 py-3`,children:[(0,Q.jsx)(`div`,{className:`text-sm font-semibold`,children:`Sessions`}),(0,Q.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:_?.mode===`incognito`?`Incognito mode`:_?.mode===`experimental`?`Experimental mode`:`Persistent history`}),(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[(0,Q.jsxs)(K,{size:`sm`,variant:s?`default`:`outline`,onClick:()=>{c(e=>!e),u(``)},disabled:v,children:[(0,Q.jsx)(ge,{className:`mr-1 h-3.5 w-3.5`}),`New`]}),(0,Q.jsxs)(K,{size:`sm`,variant:_?.mode===`experimental`?`default`:`outline`,onClick:A,disabled:v,children:[(0,Q.jsx)(me,{className:`mr-1 h-3.5 w-3.5`}),`Experimental`]}),(0,Q.jsx)(K,{size:`sm`,variant:_?.mode===`incognito`?`default`:`outline`,onClick:j,disabled:v,children:`Incognito`})]})]}),(0,Q.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-2`,children:[y&&(0,Q.jsx)(`div`,{className:`px-2 py-2 text-xs text-destructive`,children:y}),s&&(0,Q.jsxs)(`div`,{className:`mb-2 rounded-md border bg-muted/20 p-2`,children:[(0,Q.jsx)(`div`,{className:`mb-2 text-xs text-muted-foreground`,children:`Name the new session or leave it blank.`}),(0,Q.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Q.jsx)(en,{value:l,onChange:e=>u(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),k()),e.key===`Escape`&&(c(!1),u(``))},placeholder:`Debugging auth`,className:`h-8`}),(0,Q.jsx)(K,{size:`sm`,onClick:k,disabled:v,children:`Create`})]})]}),_?.sessions.length?(0,Q.jsx)(`div`,{className:`space-y-1.5`,children:_.sessions.map(e=>{let t=T?.id===e.id&&_.mode!==`incognito`,n=d===e.id;return(0,Q.jsx)(`div`,{onClick:()=>M(e),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),M(e))},role:`button`,tabIndex:v?-1:0,className:`group w-full rounded-md border px-3 py-2 text-left transition-colors ${t?`border-foreground bg-accent`:`border-transparent hover:bg-accent/50`} ${v?`opacity-60`:``}`,children:(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Q.jsx)(`div`,{className:`min-w-0 flex-1`,children:n?(0,Q.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Q.jsx)(en,{value:p,onChange:e=>h(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:t=>{t.key===`Enter`&&(t.preventDefault(),N(e)),t.key===`Escape`&&(f(null),h(``))},placeholder:`Session name`,className:`h-8`}),(0,Q.jsx)(K,{size:`sm`,onClick:t=>{t.stopPropagation(),N(e)},disabled:!p.trim()||v,children:`Save`})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`span`,{className:`truncate text-sm font-medium`,children:Hu(e)}),e.isExperimental&&(0,Q.jsx)(`span`,{className:`rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] text-primary`,children:`∞`}),e.isCurrent&&(0,Q.jsx)(`span`,{className:`rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:`Current`})]}),(0,Q.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:Uu(e)})]})}),!n&&(0,Q.jsxs)(`div`,{className:`flex items-center gap-0.5 reveal-on-hover`,children:[(0,Q.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),f(e.id),h(e.name||Hu(e))},className:`flex h-7 w-7 items-center justify-center rounded hover:bg-muted-foreground/10 text-muted-foreground touch-target`,title:`Rename`,children:(0,Q.jsx)(se,{className:`h-3.5 w-3.5`})}),!e.isExperimental&&(0,Q.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),ee(e)},className:`flex h-7 w-7 items-center justify-center rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive touch-target`,title:`Delete session`,children:(0,Q.jsx)(W,{className:`h-3.5 w-3.5`})})]})]})},e.id)})}):(0,Q.jsx)(`div`,{className:`flex h-full items-center justify-center text-center text-muted-foreground`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`text-sm`,children:v?`Loading sessions...`:`No persistent sessions yet.`}),(0,Q.jsx)(`div`,{className:`mt-1 text-xs`,children:"Use `New`, `Experimental`, or `Incognito`."})]})}),g?.mode===`incognito`&&(0,Q.jsx)(`div`,{className:`mt-3 rounded-md border border-dashed px-3 py-2 text-xs text-muted-foreground`,children:`Incognito session is active. It lives in memory and stays out of the session list.`})]})]})}function Ku(){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 hu(a).then(t=>{e||s(t)}).catch(()=>{}),()=>{e=!0}},[a]);let c=i.pathname.split(`/`).filter(Boolean),l=c[2]===`settings`?Lc(c[3]):null,u=encodeURIComponent(o?.name||a||``),d=(0,Z.useMemo)(()=>Ic.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)(ec,{title:`Settings: ${o?.label||o?.name||a||`Agent`}`,accentColor:o?.color??null,onBack:()=>{n||!u?t():r(`/agents/${u}`)},action:(0,Q.jsx)(`button`,{type:`button`,onClick:()=>u&&r(`/agents/${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 agent`,children:(0,Q.jsx)(bt,{className:`h-3.5 w-3.5`})})}),(0,Q.jsx)(Ac,{items:d,activeId:l,onSelect:e=>u&&r(`/agents/${u}/settings/${e}`)})]})}function qu(){let e=h(),{state:t}=la(),[n,r]=(0,Z.useState)(``),i=(0,Z.useRef)(null);(0,Z.useLayoutEffect)(()=>{let e=i.current,t=e?.querySelector(`[aria-current="page"]`);if(!e||!t)return;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();r.top<n.top?e.scrollTop+=r.top-n.top:r.bottom>n.bottom&&(e.scrollTop+=r.bottom-n.bottom)},[e.pathname,t.user?.userType]);let a=fa.filter(e=>e.id!==`server`||t.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(t=>ua(n,e.label,t.label,t.description))})).filter(e=>e.items.length);return(0,Q.jsxs)(`nav`,{"aria-label":`Settings`,className:`flex h-full flex-col`,children:[(0,Q.jsxs)(`div`,{className:`shrink-0 space-y-3 border-b border-border p-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center`,children:[(0,Q.jsx)(Ms,{}),(0,Q.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Settings`})]}),(0,Q.jsx)(en,{type:`search`,name:`settings-menu-filter`,autoComplete:`off`,"data-lpignore":`true`,"data-1p-ignore":`true`,"aria-label":`Search settings menu`,placeholder:`Find a setting…`,value:n,onChange:e=>r(e.target.value)})]}),(0,Q.jsxs)(`div`,{ref:i,className:`min-h-0 flex-1 space-y-4 overflow-y-auto p-2`,children:[a.map(t=>(0,Q.jsxs)(`section`,{"aria-label":t.label,children:[(0,Q.jsx)(`h2`,{className:`px-3 py-2 text-xs font-semibold text-muted-foreground`,children:t.label}),t.items.map(({path:t,icon:n,label:r,description:i})=>(0,Q.jsxs)(S,{to:t,"aria-current":e.pathname===t?`page`:void 0,className:G(`flex items-start gap-3 rounded-md px-3 py-2 text-left hover:bg-accent/50`,e.pathname===t&&`bg-accent`),children:[(0,Q.jsx)(n,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`block text-sm font-medium`,children:r}),(0,Q.jsx)(`span`,{className:`mt-0.5 block text-xs leading-relaxed text-muted-foreground`,children:i})]})]},t))]},t.id)),!a.length&&(0,Q.jsx)(`p`,{role:`status`,className:`p-3 text-sm text-muted-foreground`,children:`No settings match. Try “cache”, “model” or “token”.`})]})]})}var Ju=280;function Yu(){let{state:e}=la(),{activeSection:t,m2View:n}=e;if(t===`contexts`){if(n===`settings`)return(0,Q.jsx)(Rc,{});if(n===`detail`)return(0,Q.jsx)(kc,{})}if(t===`workspaces`){if(n===`settings`)return(0,Q.jsx)(Zl,{});if(n===`detail`)return(0,Q.jsx)(Hl,{})}if(t===`agents`){if(n===`settings`)return(0,Q.jsx)(Ku,{});if(n===`detail`)return(0,Q.jsx)(Gu,{})}return null}function Xu(){let{state:e,closeM1:t,closeM2:n}=la(),r=Ks(Fr()&&e.m1Open&&e.m2Open&&e.activeSection===`workspaces`&&e.m2View===`detail`,`left`,t);hi(t,e.m1Open&&!e.m2Open),hi(n,e.m1Open&&e.m2Open);let i=Fr(),a=(0,Z.useRef)(null),o=(0,Z.useRef)(null);qs(a,e.m1Open&&!e.m2Open,e.activeSection??``),qs(o,e.m1Open&&e.m2Open,`${e.activeSection}:${e.selectedEntityId}:${e.m2View}`);let[s,c]=(0,Z.useState)(Ju),[l,u]=(0,Z.useState)(!1),d=i&&e.m1Open;return(0,Q.jsxs)(Q.Fragment,{children:[d&&(0,Q.jsx)(`div`,{className:`fixed inset-0 z-40 bg-scrim animate-fade-in`,onClick:t,"aria-hidden":!0}),(0,Q.jsxs)(`div`,{style:e.m1Open&&!d?{width:s}:void 0,className:G(`flex-shrink-0 overflow-hidden bg-card surface-glass`,!l&&!d&&`transition-[width] duration-normal ease-out`,e.m1Open?`rounded-[var(--panel-radius)] shadow-elevation-2`:`w-0`,d?G(`fixed bottom-2 right-2 top-2 z-40 shadow-elevation-5`,e.m2Open?`left-2`:`left-[calc(0.5rem+var(--spacing-rail)+0.5rem)]`):`relative`),children:[(0,Q.jsxs)(`div`,{ref:a,"data-menu-view":`list`,inert:!e.m1Open||e.m2Open,className:G(`absolute inset-0 flex flex-col transition-opacity duration-normal ease-out`,e.m2Open&&`opacity-0 pointer-events-none`),style:d?void 0:{minWidth:s},children:[e.activeSection===`contexts`&&(0,Q.jsx)($s,{}),e.activeSection===`workspaces`&&(0,Q.jsx)(Hc,{}),e.activeSection===`agents`&&(0,Q.jsx)(zu,{}),e.activeSection===`admin`&&(0,Q.jsx)(qu,{}),e.activeSection===`apps`&&(0,Q.jsx)(Bs,{}),e.activeSection===`settings`&&(0,Q.jsx)(qu,{})]}),(0,Q.jsx)(`div`,{...r,ref:o,"data-menu-view":`detail`,inert:!e.m1Open||!e.m2Open,className:G(`absolute inset-0 z-10 bg-card flex flex-col md:transition-transform md:duration-normal md:ease-out`,e.m2Open?`translate-x-0`:`translate-x-full max-md:invisible`),children:e.m2Open&&(0,Q.jsx)(Yu,{})}),e.m1Open&&!d&&(0,Q.jsx)(Us,{width:s,onResize:c,onDragging:u})]})]})}function Zu(e){let[t]=e.split(`/`).filter(Boolean);return!t||t===`home`||t===`share-target`}function Qu(e){let[t,n]=e.split(`/`).filter(Boolean);return[`contexts`,`workspaces`,`agents`,`apps`].includes(t)&&!!n}var $u=`max-md:fixed max-md:left-2 max-md:right-2 max-md:top-2 max-md:bottom-2 max-md:z-side max-md:py-0 max-md:mr-0 max-md:rounded-(--panel-radius) max-md:shadow-elevation-5 max-md:animate-fade-in`,ed=`fixed inset-0 z-side-scrim bg-scrim animate-fade-in md:hidden`;function td(){let e=kr(),{pathname:t,search:n}=h(),{state:r,openM2Drawer:i}=la(),a=Fr(),o=pa(t),s=Ks(a&&!r.m1Open&&!r.m0Open&&o.section===`workspaces`&&!!o.entityId&&o.m2View===`detail`,`right`,()=>i(`workspaces`,`detail`,o.entityId?decodeURIComponent(o.entityId):null)),c=(0,Z.useRef)(null);qs(c,!r.m1Open,t+n,!r.m0Open);let l=Qu(t),u=Zu(t),{entry:d,loading:f,error:p,close:m}=Cr();return(0,Q.jsx)(`div`,{className:G(`relative flex flex-col flex-1 min-w-0`,!u&&`surface-sheet`),children:(0,Q.jsxs)(`div`,{className:`flex flex-1 min-h-0 gap-shell`,children:[(0,Q.jsx)(`main`,{...s,ref:c,id:`content-area`,className:G(`relative flex-1 min-h-0 min-w-0 overflow-auto`,!l&&!u&&`p-page max-md:pb-rail-stack`),children:(0,Q.jsx)(C,{})}),(d||f||p)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:ed,onClick:m,"aria-hidden":!0}),(0,Q.jsxs)(`div`,{"data-reader-pane":!0,style:{"--reader-width":`${e??420}px`},className:G(`relative z-10 flex shrink-0 items-stretch py-2 mr-2 md:w-[var(--reader-width)] md:max-w-[calc(100%_-_248px)]`,$u),children:[(0,Q.jsx)(Dr,{edge:`left`}),(0,Q.jsx)(jr,{},d?`${d.workspaceId}:${d.document.id}`:`loading`)]})]})]})})}function nd(){let{state:e,setView:t}=ti(),{pathname:n}=h();return e.t1Open||e.addOpen||!Zu(n)?null:(0,Q.jsx)(`button`,{type:`button`,onClick:()=>t(`tools`),"aria-label":`Open toolbox`,title:`Open toolbox`,className:`fixed z-50 hidden md:flex h-16 w-16 items-center justify-center rounded-full shadow-elevation-4 transition-colors bottom-fab-inset right-6 bg-foreground text-background hover:bg-foreground`,children:(0,Q.jsx)(Qe,{className:`h-7 w-7`,strokeWidth:1.75,"aria-hidden":!0})})}var rd={current:null,sessions:null,isLoading:!1,error:null};function id(e){return e instanceof Error?e.message:`Session request failed`}function ad({children:e}){let[t,n]=(0,Z.useState)({}),r=(0,Z.useCallback)((e,t)=>{n(n=>({...n,[e]:{...n[e]||rd,...t}}))},[]),i=(0,Z.useCallback)((e,t)=>(r(e,{current:t.current,sessions:t.sessions,isLoading:!1,error:null}),t),[r]),a=(0,Z.useCallback)(async e=>{if(e){r(e,{isLoading:!0,error:null});try{let[t,n]=await Promise.all([gu(e),_u(e)]);r(e,{current:t,sessions:n,isLoading:!1,error:null})}catch(t){throw r(e,{isLoading:!1,error:id(t)}),t}}},[r]),o=(0,Z.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await vu(e,t))}catch(t){throw r(e,{isLoading:!1,error:id(t)}),t}},[i,r]),s=(0,Z.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await yu(e,t))}catch(t){throw r(e,{isLoading:!1,error:id(t)}),t}},[i,r]),c=(0,Z.useCallback)(async(e,t,n)=>{r(e,{isLoading:!0,error:null});try{return i(e,await bu(e,t,{name:n}))}catch(t){throw r(e,{isLoading:!1,error:id(t)}),t}},[i,r]),l=(0,Z.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await xu(e,t))}catch(t){throw r(e,{isLoading:!1,error:id(t)}),t}},[i,r]),u=(0,Z.useMemo)(()=>({getState:e=>t[e]||rd,refresh:a,create:o,select:s,rename:c,remove:l}),[t,a,o,s,c,l]);return(0,Q.jsx)(Bu.Provider,{value:u,children:e})}var od=`data/schema/`,sd={"data/schema/file":{label:`Files`,icon:Ct},"data/schema/note":{label:`Notes`,icon:jt},"data/schema/task":{label:`Todos`,icon:dt},"data/schema/tab":{label:`Tabs`,icon:Oe},"data/schema/message/email":{label:`Emails`,icon:Xe},"data/schema/link":{label:`Links`,icon:Ue},"data/schema/identity":{label:`Identities`,icon:De},"data/schema/drawing":{label:`Sketches`,icon:Be}};function cd(e){return sd[e]??{label:e.startsWith(`data/schema/`)?e.slice(12).replace(/(^|\/)(\w)/g,(e,t,n)=>t+n.toUpperCase()):e,icon:_e}}function ld(e){return sd[e]?.icon??_e}function ud(e){return{...e,lens:na.lens}}function dd(e,t,n=!1){let r=n?e=>e:ud;return JSON.stringify(r(e))!==JSON.stringify(r(t??na))}var fd={savedGeoSelection:null,liveEnabled:!1,liveError:null,t1Open:!1,t1View:null,toolsTab:`features`,appsAppletId:null,t2Open:!1,t2AgentId:null,addModal:!1,addOpen:!1,addKind:null,addRelateTo:null,editDocument:null,editWorkspaceId:null,activeContextPath:null,activeContextType:null,activeWorkspaceName:null,activeTreeName:null,activeCanvasId:null,activeContextId:null,activeAccentColor:null,filters:na,geoSelection:null,mapDocuments:[],mapWorkspaceId:null,savedFilters:null,savedSearchQuery:null,isDirty:!1,isSaving:!1,availableBitmaps:[],bitmapsLoading:!1,availableTimelines:[],timelineScales:{},timelinesLoading:!1};function pd(e,t){switch(t.type){case`SET_VIEW`:return{...e,t1Open:t.view!==null,t1View:t.view,t2Open:!1,t2AgentId:null};case`TOGGLE_VIEW`:return e.t1View===t.view&&!e.t2Open?{...e,t1Open:!1,t1View:null}:{...e,t1Open:!0,t1View:t.view,t2Open:!1,t2AgentId:null};case`CLOSE_T1`:return{...e,t1Open:!1,t1View:null,t2Open:!1,t2AgentId:null};case`OPEN_T2_AGENT`:return{...e,t2Open:!0,t2AgentId:t.agentId};case`CLOSE_T2`:return{...e,t2Open:!1,t2AgentId:null};case`OPEN_ADD`:return{...e,addOpen:!0,addModal:t.modal??(e.addOpen&&e.addModal),addKind:t.kind,addRelateTo:t.relateTo===void 0?e.addRelateTo:t.relateTo,editDocument:null,editWorkspaceId:null};case`CLOSE_ADD`:return{...e,addOpen:!1,addModal:!1,addKind:null,addRelateTo:null,editDocument:null,editWorkspaceId:null};case`OPEN_EDIT`:return{...e,addOpen:!0,addModal:!1,addKind:null,addRelateTo:null,editDocument:t.document,editWorkspaceId:t.workspaceId};case`SET_TOOLS_TAB`:return{...e,toolsTab:t.tab};case`SET_APPS_APPLET`:return{...e,appsAppletId:t.appletId};case`SET_ACCENT_COLOR`:return e.activeAccentColor===t.color?e:{...e,activeAccentColor:t.color};case`SET_GEO_SELECTION`:return{...e,geoSelection:t.selection,isDirty:e.activeContextType===`context`?dd(e.filters,e.savedFilters,!0)||JSON.stringify(t.selection)!==JSON.stringify(e.savedGeoSelection):e.isDirty};case`SET_SAVED_GEO_SELECTION`:return{...e,savedGeoSelection:t.selection,isDirty:e.activeContextType===`context`?dd(e.filters,e.savedFilters,!0)||JSON.stringify(e.geoSelection)!==JSON.stringify(t.selection):e.isDirty};case`SET_MAP_DOCUMENTS`:return e.mapDocuments===t.documents&&e.mapWorkspaceId===t.workspaceId?e:{...e,mapDocuments:t.documents,mapWorkspaceId:t.workspaceId};case`SET_NAVIGATION`:{let n=e.activeContextType===t.contextType&&e.activeContextId===t.contextId&&e.activeCanvasId===t.canvasId;return{...e,activeWorkspaceName:t.workspaceName,activeTreeName:t.treeName,activeCanvasId:t.canvasId,activeContextId:t.contextId,activeContextType:t.contextType,activeContextPath:t.contextPath,geoSelection:null,...n?{}:{filters:na,savedFilters:null,savedSearchQuery:null,isDirty:!1,savedGeoSelection:null,liveEnabled:!1,liveError:null}}}case`SET_CONTEXT_SCOPE`:return e.activeContextType!==`context`||e.activeWorkspaceName===t.workspaceName&&e.activeContextPath===t.contextPath&&e.activeTreeName===t.treeId?e:{...e,activeWorkspaceName:t.workspaceName,activeContextPath:t.contextPath,activeTreeName:t.treeId};case`SET_LIVE`:return{...e,liveEnabled:t.enabled,liveError:null};case`SET_LIVE_ERROR`:return{...e,liveError:t.error};case`SET_FILTERS`:return{...e,filters:t.filters,isDirty:e.activeContextType===null?!1:dd(t.filters,e.savedFilters,e.activeContextType===`context`)||e.activeContextType===`context`&&JSON.stringify(e.geoSelection)!==JSON.stringify(e.savedGeoSelection)};case`SET_SAVED_FILTERS`:{let n=t.hydrating===!0&&e.isDirty,r=n?e.filters:t.savedFilters??na;return{...e,savedFilters:t.savedFilters,savedSearchQuery:t.savedSearchQuery??null,filters:r,isDirty:n?dd(r,t.savedFilters,e.activeContextType===`context`):!1}}case`SET_SAVING`:return{...e,isSaving:t.isSaving};case`SET_BITMAPS`:return{...e,availableBitmaps:t.keys,bitmapsLoading:!1};case`SET_BITMAPS_LOADING`:return{...e,bitmapsLoading:t.loading};case`SET_TIMELINES`:return{...e,availableTimelines:t.names,timelineScales:t.scales??e.timelineScales,timelinesLoading:!1};case`SET_TIMELINES_LOADING`:return{...e,timelinesLoading:t.loading};default:return e}}var md=`toolbox:session:filters`;function hd(){try{let e=localStorage.getItem(md);if(!e)return null;let t=JSON.parse(e);return{...na,...t,features:{...na.features,...t.features??{}},timeline:{...na.timeline,...t.timeline??{}},geo:{...na.geo,...t.geo??{}},lens:na.lens,sort:Zi(t.sort)}}catch{return null}}function gd(e){try{localStorage.setItem(md,JSON.stringify(ud(e)))}catch{}}function _d(e,t=!1){if(!e?.toolbox)return null;try{let n=e.toolbox;return{features:{allOf:n.features?.allOf??[],anyOf:n.features?.anyOf??[],noneOf:n.features?.noneOf??[]},timeline:{quickFilter:n.timeline?.quickFilter??null,customRanges:n.timeline?.customRanges??(n.timeline?.customRange?[n.timeline.customRange]:[]),indexCreated:n.timeline?.indexCreated??!0,indexUpdated:n.timeline?.indexUpdated??!0,indexDeleted:n.timeline?.indexDeleted??!1,contentEvents:n.timeline?.contentEvents??!1,selectedTimelines:n.timeline?.selectedTimelines??[]},geo:{bbox:n.geo?.bbox??null,includeUnlocated:n.geo?.includeUnlocated??!1},lens:t?{...na.lens,...n.lens??{}}:na.lens,sort:Zi(n.sort)}}catch{return null}}function vd(e,t){let n=e;for(let e of t.split(`/`).filter(Boolean))if(n=n?.children?.find(t=>t.name===e)??null,!n)break;return n}function yd({children:e,target:t}){let[n,r]=(0,Z.useState)(null),[i,a]=(0,Z.useReducer)(pd,fd),o=h(),s=m(),c=new URLSearchParams(o.search).get(`ownerId`)||void 0,l=(0,Z.useRef)(null),u=(0,Z.useRef)(i);(0,Z.useEffect)(()=>{u.current=i}),(0,Z.useEffect)(()=>{let e=!1,n=o.pathname.split(`/`).filter(Boolean),r=t===void 0?n[0]===`workspaces`&&decodeURIComponent(n[1]||``)||null:t?.mode===`workspace`?t.workspaceName:null,i=t===void 0?n[0]===`contexts`&&decodeURIComponent(n[1]||``)||null:t?.mode===`context`?t.contextId:null,{path:s,treeName:c}=t?.mode===`workspace`?t:r?ra(o.pathname):{path:`/`,treeName:``},l=t=>{if(e)return;let n=t?`canvas`:i?`context`:null,o=u.current;o.activeContextType!==null&&n===null&&gd(o.filters),a({type:`SET_NAVIGATION`,workspaceName:r,treeName:r?c:null,canvasId:t,contextId:i,contextType:n,contextPath:r?s:null})};return r&&s!==`/`?(In(r,c).then(t=>{if(e)return;let n=vd(t,s);l(n?.type===`canvas`?n.id:null)}).catch(()=>l(null)),()=>{e=!0}):(l(null),()=>{e=!0})},[o.pathname,t]),(0,Z.useEffect)(()=>{let e=i.activeWorkspaceName;e&&(a({type:`SET_BITMAPS_LOADING`,loading:!0}),Kn(e).then(e=>{a({type:`SET_BITMAPS`,keys:e})}))},[i.activeWorkspaceName]),(0,Z.useEffect)(()=>{let e=i.activeWorkspaceName;e&&(a({type:`SET_TIMELINES_LOADING`,loading:!0}),or(e).then(e=>{a({type:`SET_TIMELINES`,names:e.map(e=>e.name),scales:Object.fromEntries(e.filter(e=>e.scales?.length).map(e=>[e.name,e.scales]))})}))},[i.activeWorkspaceName]),(0,Z.useEffect)(()=>{let{activeContextType:e,activeCanvasId:t,activeWorkspaceName:n,activeTreeName:r,activeContextPath:o}=i;if(e!==`context`){if(e===`canvas`&&t&&n&&o)In(n,r||`context`).then(e=>{let t=vd(e,o),n=_d(t?.metadata);a({type:`SET_SAVED_FILTERS`,savedFilters:n,savedSearchQuery:t?.querySpec?.query??null,hydrating:!0})}).catch(()=>{a({type:`SET_SAVED_FILTERS`,savedFilters:null,savedSearchQuery:null,hydrating:!0})});else{let e=hd();a({type:`SET_SAVED_FILTERS`,savedFilters:e,savedSearchQuery:null})}}},[i.activeCanvasId,i.activeContextPath,i.activeContextType,i.activeTreeName,i.activeWorkspaceName]),(0,Z.useEffect)(()=>{let{activeContextType:e,activeContextId:t}=i;if(e!==`context`||!t)return;let n=!1;l.current=null;let r=0,d=e=>{let t=new URLSearchParams(window.location.search);t.delete(`q`),t.delete(`search`);for(let n of e)t.append(`q`,n);let n=t.toString();s(`${o.pathname}${n?`?${n}`:``}${window.location.hash}`,{replace:!0})},f=(e,t,n,r=null,i=n?[n]:[])=>{let o=e?.filters??t??na,s=e?.geoSelection??r;l.current=JSON.stringify({filters:o,geoSelection:s,queries:e?.queries??i}),a({type:`SET_SAVED_FILTERS`,savedFilters:t,savedSearchQuery:n}),a({type:`SET_FILTERS`,filters:o}),a({type:`SET_GEO_SELECTION`,selection:s}),a({type:`SET_SAVED_GEO_SELECTION`,selection:r}),a({type:`SET_LIVE`,enabled:e!==null}),d(e?.queries??i)},p=e=>{let i=++r;return si(t,c).then(t=>{if(n||i!==r)return;let o=t.metadata,s=_d(o,!0),c=typeof o?.toolboxSearchQuery==`string`?o.toolboxSearchQuery:null;if(a({type:`SET_CONTEXT_SCOPE`,workspaceName:t.workspaceName||t.workspaceId||null,contextPath:t.path||`/`,treeId:t.treeId||null}),t.liveQuery)f(t.liveQuery,s,c,o?.toolboxGeoSelection??null,t.queryOptions?.queries);else if(e){a({type:`SET_LIVE`,enabled:!1});let e=u.current.isDirty?u.current.filters:s??na,n=o?.toolboxGeoSelection??null;l.current=JSON.stringify({filters:e,geoSelection:n,queries:[]}),a({type:`SET_SAVED_FILTERS`,savedFilters:s,savedSearchQuery:c,hydrating:!0}),a({type:`SET_GEO_SELECTION`,selection:n}),a({type:`SET_SAVED_GEO_SELECTION`,selection:n});let r=new URLSearchParams(window.location.search),i=t.queryOptions?.queries?.length?t.queryOptions.queries:c?[c]:[];!r.has(`q`)&&!r.has(`search`)&&i.length&&d(i)}}).catch(e=>{n||i!==r||a({type:`SET_LIVE_ERROR`,error:e instanceof Error?e.message:`Could not load context`})})};p(!0);let m=()=>{p(!1)},h=X.on(`context.url.set`,e=>{e?.id===t&&m()}),g=X.on(`context.updated`,e=>{let n=e;if((n.contextId||n.id)!==t)return;if(!n.metadata){p(!0);return}++r;let i=_d(n.metadata,!0);f(n.liveQuery??null,i,typeof n.metadata.toolboxSearchQuery==`string`?n.metadata.toolboxSearchQuery:null,n.metadata.toolboxGeoSelection??null,n.queryOptions?.queries)}),_=X.on(`connect`,()=>{p(!0)}),v=X.on(`disconnect`,()=>{u.current.liveEnabled&&a({type:`SET_LIVE_ERROR`,error:`Disconnected — Live updates will resume when connected.`})});return window.addEventListener(`contexts:refresh`,m),()=>{n=!0,l.current=null,h(),g(),_(),v(),window.removeEventListener(`contexts:refresh`,m)}},[i.activeContextId,i.activeContextType,c]);let d=(0,Z.useMemo)(()=>{let e=new URLSearchParams(o.search),t=e.getAll(`q`).map(e=>e.trim()).filter(Boolean),n=(e.get(`search`)||``).trim();return t.length?t:n?[n]:[]},[o.search]),f=(0,Z.useRef)(d);(0,Z.useEffect)(()=>{f.current=d},[d]);let p=(0,Z.useRef)(!1),g=(0,Z.useRef)(null),[_,v]=(0,Z.useState)(0);(0,Z.useEffect)(()=>()=>{g.current!==null&&window.clearTimeout(g.current),g.current=null},[i.activeContextType,i.activeContextId,i.liveEnabled,c]),(0,Z.useEffect)(()=>{i.activeContextType!==`context`||!i.activeContextId||c||!i.liveEnabled||l.current===null||p.current||g.current!==null||!X.isConnected()||JSON.stringify({filters:i.filters,geoSelection:i.geoSelection,queries:d})!==l.current&&(g.current=window.setTimeout(()=>{g.current=null;let e=u.current;if(e.activeContextId!==i.activeContextId||!e.liveEnabled)return;let t=f.current,n=JSON.stringify({filters:e.filters,geoSelection:e.geoSelection,queries:t});if(n===l.current)return;let r=l.current;p.current=!0;let o={filters:e.filters,geoSelection:e.geoSelection,queries:t,binding:ea(e.filters,e.geoSelection,t)};X.request(`context.filters.set`,{contextId:e.activeContextId,liveQuery:o}).then(()=>{u.current.activeContextId===e.activeContextId&&l.current===r&&(l.current=n,a({type:`SET_LIVE_ERROR`,error:null}))}).catch(t=>{u.current.activeContextId===e.activeContextId&&a({type:`SET_LIVE_ERROR`,error:t instanceof Error?t.message:`Live update failed`})}).finally(()=>{p.current=!1,v(e=>e+1)})},i.liveError?1500:100))},[i.activeContextType,i.activeContextId,i.liveEnabled,i.filters,i.geoSelection,d,c,_,i.liveError]);let y=(0,Z.useCallback)(async e=>{let t=u.current;if(t.activeContextType!==`context`||!t.activeContextId||c)return;let n=d,r=e?{filters:t.filters,geoSelection:t.geoSelection,queries:n,binding:ea(t.filters,t.geoSelection,n)}:null;try{await X.request(`context.filters.set`,{contextId:t.activeContextId,liveQuery:r}),l.current=JSON.stringify({filters:t.filters,geoSelection:t.geoSelection,queries:n}),a({type:`SET_LIVE`,enabled:e})}catch(e){a({type:`SET_LIVE_ERROR`,error:e instanceof Error?e.message:`Could not change Live mode`})}},[c,d]);(0,Z.useEffect)(()=>{i.activeContextType===null&&gd(i.filters)},[i.filters,i.activeContextType]);let b=(0,Z.useCallback)(e=>a({type:`SET_VIEW`,view:e}),[]),x=(0,Z.useCallback)(e=>a({type:`TOGGLE_VIEW`,view:e}),[]),S=(0,Z.useCallback)(()=>a({type:`CLOSE_T1`}),[]),C=(0,Z.useCallback)(e=>a({type:`OPEN_T2_AGENT`,agentId:e}),[]),w=(0,Z.useCallback)(()=>a({type:`CLOSE_T2`}),[]),T=(0,Z.useCallback)(e=>a({type:`OPEN_ADD`,kind:e}),[]),E=(0,Z.useCallback)(e=>a({type:`OPEN_ADD`,kind:null,modal:e?.modal,relateTo:e?.fresh?null:void 0}),[]),D=(0,Z.useCallback)((e,t=!1)=>a({type:`OPEN_ADD`,kind:null,relateTo:e,modal:t}),[]),O=(0,Z.useCallback)(()=>a({type:`CLOSE_ADD`}),[]),k=(0,Z.useCallback)((e,t)=>a({type:`OPEN_EDIT`,document:e,workspaceId:t}),[]),A=(0,Z.useCallback)(e=>a({type:`SET_TOOLS_TAB`,tab:e}),[]),j=(0,Z.useCallback)(e=>a({type:`SET_APPS_APPLET`,appletId:e}),[]),M=(0,Z.useCallback)(e=>a({type:`SET_ACCENT_COLOR`,color:e}),[]),N=(0,Z.useCallback)(e=>{a({type:`SET_FILTERS`,filters:e})},[]),ee=(0,Z.useCallback)((e,t)=>{let{filters:n}=u.current,r=e.startsWith(od),i=r?n.features.allOf.filter(t=>t!==e):t?[...new Set([...n.features.allOf,e])]:n.features.allOf.filter(t=>t!==e),o=r&&t?[...new Set([...n.features.anyOf,e])]:n.features.anyOf.filter(t=>t!==e),s=n.features.noneOf.filter(t=>t!==e);a({type:`SET_FILTERS`,filters:{...n,features:{allOf:i,anyOf:o,noneOf:s}}})},[]),P=(0,Z.useCallback)((e,t)=>{let{filters:n}=u.current,r=n.features.allOf.filter(t=>t!==e),i=n.features.anyOf.filter(t=>t!==e),o=n.features.noneOf.filter(t=>t!==e);t===`allOf`?r.push(e):t===`anyOf`?i.push(e):t===`noneOf`&&o.push(e),a({type:`SET_FILTERS`,filters:{...n,features:{allOf:r,anyOf:i,noneOf:o}}})},[]),F=(0,Z.useCallback)(()=>{let{filters:e}=u.current;a({type:`SET_GEO_SELECTION`,selection:null}),a({type:`SET_FILTERS`,filters:{...na,timeline:{...e.timeline,quickFilter:null,customRanges:[],customRange:null,selectedTimelines:[]}}});let t=new URLSearchParams(o.search);t.delete(`q`),t.delete(`search`),t.set(`q`,``),s({pathname:o.pathname,search:t.toString(),hash:o.hash},{replace:!0})},[o.pathname,o.search,o.hash,s]),te=(0,Z.useCallback)(e=>{let{filters:t}=u.current;a({type:`SET_FILTERS`,filters:{...t,sort:e}})},[]),ne=(0,Z.useCallback)(e=>{let{filters:t}=u.current;a({type:`SET_FILTERS`,filters:{...t,timeline:{...t.timeline,...e}}})},[]),re=(0,Z.useCallback)(e=>{let{filters:t}=u.current;a({type:`SET_FILTERS`,filters:{...t,geo:{...t.geo,bbox:e}}})},[]),I=(0,Z.useCallback)(e=>{let{filters:t}=u.current;a({type:`SET_FILTERS`,filters:{...t,lens:{...t.lens,gps:e}}})},[]),ie=(0,Z.useCallback)(e=>{let{filters:t}=u.current;a({type:`SET_FILTERS`,filters:{...t,lens:{...t.lens,ids:e}}})},[]),ae=(0,Z.useCallback)(e=>{a({type:`SET_GEO_SELECTION`,selection:e})},[]),oe=(0,Z.useCallback)((e,t=null)=>{a({type:`SET_MAP_DOCUMENTS`,documents:e,workspaceId:t})},[]),se=(0,Z.useCallback)(async()=>{let{activeContextType:e,activeContextId:t,activeWorkspaceName:n,activeTreeName:r,activeContextPath:i,filters:s,geoSelection:l,isSaving:f}=u.current;if(!f){a({type:`SET_SAVING`,isSaving:!0});try{if(e===`canvas`&&n&&i){let e=r||`context`,t=vd(await In(n,e),i),a=new URLSearchParams(o.search).get(`q`)||new URLSearchParams(o.search).get(`search`)||``;await er(n,i,{metadata:{...t?.metadata||{},toolbox:ud(s)},querySpec:{features:s.features,filters:[...Qi(s.timeline),...Xi(s.geo)],query:a.trim()||void 0,sort:s.sort?.sortBy?s.sort:null}},e),ar(n,e)}else if(e===`context`&&t){let e=(await si(t,c)).metadata||{},n=new URLSearchParams(o.search).get(`q`)||new URLSearchParams(o.search).get(`search`)||``;await ui(t,{metadata:{...e,toolbox:s,toolboxGeoSelection:l,toolboxSearchQuery:n.trim()||void 0},...ea(s,l,d)},c)}let u=new URLSearchParams(o.search).get(`q`)||new URLSearchParams(o.search).get(`search`)||``;a({type:`SET_SAVED_FILTERS`,savedFilters:s,savedSearchQuery:u.trim()||null,hydrating:!0}),e===`context`&&a({type:`SET_SAVED_GEO_SELECTION`,selection:l})}finally{a({type:`SET_SAVING`,isSaving:!1})}}},[o.search,c,d]),L=(0,Z.useCallback)(e=>{let t=u.current.availableBitmaps.filter(t=>t!==e);a({type:`SET_BITMAPS`,keys:t});let n=u.current.filters,r={...n,features:{allOf:n.features.allOf.filter(t=>t!==e),anyOf:n.features.anyOf.filter(t=>t!==e),noneOf:n.features.noneOf.filter(t=>t!==e)}};JSON.stringify(r.features)!==JSON.stringify(n.features)&&a({type:`SET_FILTERS`,filters:r})},[]),ce=(0,Z.useCallback)(async e=>{let t=u.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await Wn(t,e),L(e)},[L]),le=(0,Z.useCallback)(async e=>{let t=u.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);let n=await jn(t,e);return L(e),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:t}})),n.documentsDeleted},[L]),R=(0,Z.useCallback)(()=>{let e=u.current.activeWorkspaceName;e&&(a({type:`SET_TIMELINES_LOADING`,loading:!0}),or(e).then(e=>{a({type:`SET_TIMELINES`,names:e.map(e=>e.name),scales:Object.fromEntries(e.filter(e=>e.scales?.length).map(e=>[e.name,e.scales]))})}))},[]),ue=(0,Z.useCallback)(async e=>{let t=u.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await $n(t,e),R(),window.dispatchEvent(new CustomEvent(`workspace:timelines:changed`,{detail:{workspaceName:t}}))},[R]),de=(0,Z.useCallback)(async e=>{let t=u.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await Fn(t,e),window.dispatchEvent(new CustomEvent(`workspace:timelines:changed`,{detail:{workspaceName:t}}));let n=u.current.availableTimelines.filter(t=>t!==e);a({type:`SET_TIMELINES`,names:n});let r=u.current.filters,i=r.timeline.selectedTimelines.filter(t=>t!==e);i.length!==r.timeline.selectedTimelines.length&&a({type:`SET_FILTERS`,filters:{...r,timeline:{...r.timeline,selectedTimelines:i}}})},[]),{features:z,timeline:B,geo:V,lens:fe}=i.filters,H=z.allOf.length>0||z.anyOf.length>0||z.noneOf.length>0||B.quickFilter!==null||(B.customRanges?.length??0)>0||(B.selectedTimelines?.length??0)>0||V.bbox!==null||fe.gps!==null||fe.ids!==null||i.geoSelection!==null;return(0,Q.jsx)(ri.Provider,{value:{agentView:n,setAgentView:r,state:i,setView:b,toggleView:x,closeT1:S,openAgentT2:C,closeT2:w,openAdd:T,openAddPicker:E,openAddRelated:D,closeAdd:O,openEdit:k,setToolsTab:A,openApplet:j,setAccentColor:M,setFilters:N,setFeatureToggle:ee,setFeatureMode:P,clearFilters:F,hasActiveFilters:H,setTimelineFilter:ne,setGeoBBox:re,setLensGps:I,setLensIds:ie,setGeoSelection:ae,setMapDocuments:oe,setSort:te,setLiveEnabled:y,saveFilters:se,deleteBitmap:ce,deleteDataset:le,createTimeline:ue,deleteTimeline:de,refreshTimelines:R},children:e})}function bd(){let e=Qr(),{closeAdd:t}=ti(),{showSuccessToast:n,showErrorToast:r}=gi(),[i,a]=(0,Z.useState)(`Untitled.txt`),[o,s]=(0,Z.useState)(``),[c,l]=(0,Z.useState)(!1),u=!1;try{Jr(``,i.trim()),u=!0}catch{}return(0,Q.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(q,{htmlFor:`plaintext-filename`,children:`Filename`}),(0,Q.jsx)(en,{id:`plaintext-filename`,autoFocus:!0,value:i,onChange:e=>a(e.target.value)})]}),(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(q,{children:`Content`}),(0,Q.jsx)(ji,{kind:`text`,value:o,onChange:s,placeholder:`Write plain text…`})]}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Creates a file in the current storage folder. Existing files are never overwritten.`}),(0,Q.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Q.jsx)(K,{variant:`outline`,size:`sm`,onClick:t,disabled:c,children:`Cancel`}),(0,Q.jsx)(K,{size:`sm`,onClick:async()=>{if(!(c||!u||e?.mode!==`workspace`||e.treeName!==`backends`)){l(!0);try{let r=await qr(e.workspaceName,e.path);await Pi(e.workspaceName,{...r,key:Jr(r.key,i.trim())},new Blob([o],{type:`text/plain;charset=utf-8`}),{contentType:`text/plain;charset=utf-8`}),Zr(e),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`)),n(`Plaintext file created`),t()}catch(e){r(e instanceof Error?e.message:`Failed to create file`)}finally{l(!1)}}},disabled:c||!u,children:c?`Creating…`:`Create file`})]})]})}function xd(e){let t=new URLSearchParams;return e?.mode===`context`&&t.set(`context`,e.contextId),e?.mode===`workspace`&&(t.set(`workspace`,e.workspaceName),t.set(`path`,e.path),t.set(`tree`,e.treeName)),t}var Sd={id:`sketch`,label:`Sketch`,icon:Be,schemas:[Vn],canCreate:!0,canEdit:e=>e.schema===Vn,createUrl(e){let t=xd(e);return t.set(`add`,`1`),`/apps/sketch?${t.toString()}`},editUrl(e,t){let n=xd(t);return n.set(`doc`,String(e.id)),`/apps/sketch?${n.toString()}`}},Cd=[{kind:`message`,label:`New Message`,icon:St},{kind:`note`,label:`Note`,icon:jt},{kind:`link`,label:`Link`,icon:Ue},{kind:`todo`,label:`Todo`,icon:dt},{kind:`identity`,label:`Identity`,icon:De},{kind:`sketch`,label:`Sketch`,icon:Be},{kind:`plaintext`,label:`Plaintext file`,icon:Ct},{kind:`file`,label:`File`,icon:Pe},{kind:`photo`,label:`Photo/Video`,icon:re},{kind:`existing`,label:`Existing document`,icon:Ze},{kind:`folder`,label:`Folder`,icon:ze}];function wd(){return typeof navigator<`u`&&navigator.mediaDevices?.getUserMedia?Cd:Cd.filter(e=>e.kind!==`photo`)}function Td({onSelect:e,variant:t=`list`,omit:n}){let r=wd().filter(e=>!n?.includes(e.kind));return t===`stack`?(0,Q.jsx)(Q.Fragment,{children:r.map(({kind:t,label:n,icon:r})=>(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:`flex items-center gap-2 rounded-full bg-card px-3 py-1.5 text-sm font-medium shadow-elevation-3 transition-transform hover:scale-105`,children:[n,(0,Q.jsx)(r,{className:`h-3.5 w-3.5`})]},t))}):(0,Q.jsx)(`div`,{className:`p-2`,children:r.map(({kind:t,label:n,icon:r})=>(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:`flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium text-foreground transition-colors hover:bg-muted`,children:[(0,Q.jsx)(r,{className:`h-4 w-4 text-muted-foreground`}),n]},t))})}var Ed={title:``,content:``,comment:``,tags:[]};function Dd(e,t,n=`add`){let r=fi(),i=Oi(`new:${n}:${e?.mode===`workspace`?`${e.workspaceName}:${e.treeName}:${e.path}`:e?.contextId??`home`}`),a=e=>async(n,i,a)=>{let o=typeof i.workspace==`string`?i.workspace:(await Gr(e)).workspaceName,s=await r.capture(),c={schema:`data/schema/note`,schemaVersion:`2.0`,comment:n.comment,data:{title:n.title.trim(),content:n.content},metadata:{features:Ur(n.tags),...s?{geo:s}:{}}},l=typeof i.id==`number`?i.id:void 0;if(l==null){let t=await Xr(e,[c],{refresh:!1});if(!t.length)throw Error(`The server did not return the saved note`);l=t[0],a({id:l,workspace:o})}else await mr(o,{...c,id:l});await t?.([l]),Zr(e)},o=Di(i,Ed,{retainAfterSave:!0,valid:e=>!!e.content.trim(),save:e?a(e):void 0});async function s(e){await o.saveWith(a(e));let t=o.getSnapshot().meta.id;if(typeof t!=`number`)throw Error(`Write a note before saving`);return[t]}return{...o.value,status:o.status,error:o.error,storageError:o.storageError,setTitle:e=>o.update({title:e}),setContent:e=>o.update({content:e}),setComment:e=>o.update({comment:e}),setTags:e=>o.update({tags:e}),saving:o.status===`saving`,canSave:!!o.value.content.trim()&&o.status!==`saving`,save:s,finish:o.clear,retry:o.flush,geotag:r}}function Od(){let{closeAdd:e,state:t}=ti(),n=Qr(),{showSuccessToast:r,showErrorToast:i}=gi(),a=Ta(n,t.addRelateTo),o=Dd(n,a.write,t.addRelateTo?`related:${t.addRelateTo.documents.map(e=>e.id).sort().join(`,`)}`:`add`),s=Sa(t.activeWorkspaceName),c=!!n&&o.canSave,l=async()=>{if(n)try{let t=await o.save(n),i=await a.write(t);r(i?`Note created; some relations failed`:`Note created`),o.finish(),e()}catch(e){i(e instanceof Error?e.message:`Failed to create note`)}};return(0,Q.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(q,{htmlFor:`note-title`,children:`Title`}),(0,Q.jsx)(en,{id:`note-title`,value:o.title,onChange:e=>o.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(q,{children:`Body`}),(0,Q.jsx)(ji,{kind:`markdown`,value:o.content,onChange:o.setContent,placeholder:`Write your note…`})]}),(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(q,{htmlFor:`note-comment`,children:`Comment`}),(0,Q.jsx)(`textarea`,{id:`note-comment`,value:o.comment,onChange:e=>o.setComment(e.target.value),rows:2,placeholder:`Optional; context you can't infer from the body`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(q,{children:`Tags`}),(0,Q.jsx)(Rr,{tags:o.tags,onChange:o.setTags,suggestions:s})]}),(0,Q.jsx)(Ca,{geotag:o.geotag,idPrefix:`note-geotag`}),(0,Q.jsx)(wa,{f:a,idPrefix:`note`}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:$r(n)}),(0,Q.jsx)(ki,{...o,onRetry:o.retry}),(0,Q.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Q.jsx)(K,{variant:`outline`,size:`sm`,onClick:e,disabled:o.saving,children:`Close`}),(0,Q.jsx)(K,{size:`sm`,onClick:l,disabled:!c,children:o.saving?`Saving…`:`Done`})]})]})}var kd=`webapp`,Ad=[`Games`,`Productivity`,`Development`,`Communication`,`Media`,`Finance`,`Learning`];function jd({webapp:e,setWebapp:t,category:n,setCategory:r,idPrefix:i,alwaysShowCategory:a=!1}){let o=`${i}-category-list`;return(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsxs)(`label`,{className:`flex items-center gap-2 text-sm text-foreground cursor-pointer select-none`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:e,onChange:e=>t(e.target.checked),className:`h-4 w-4 accent-primary`}),`Web app`,(0,Q.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`launchable application, listed under Apps`})]}),(e||a)&&(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(q,{htmlFor:`${i}-category`,children:`Category`}),(0,Q.jsx)(en,{id:`${i}-category`,value:n,onChange:e=>r(e.target.value),placeholder:`Optional, e.g. Games`,list:o}),(0,Q.jsx)(`datalist`,{id:o,children:Ad.map(e=>(0,Q.jsx)(`option`,{value:e},e))})]})]})}var Md=`data/schema/tab`,Nd=`2.0`,Pd=`data/schema/link`,Fd=`3.0`;function Id(e){try{return new URL(e),!0}catch{return!1}}function Ld(){let[e,t]=(0,Z.useState)(``),[n,r]=(0,Z.useState)(``),[i,a]=(0,Z.useState)([]),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(``),[u,d]=(0,Z.useState)(!1),f=fi(),p=e.trim(),m=Id(p),h=p.length>0&&!m,g=m&&!u;async function _(e){if(!m)throw Error(`Enter a valid URL`);d(!0);try{let t=await f.capture(),r=i.map(e=>e.trim()).filter(Boolean),a={features:Ur(i),...t?{geo:t}:{}},s=o?{schema:Pd,schemaVersion:Fd,data:{uri:p,type:kd,...n.trim()?{label:n.trim()}:{},...c.trim()?{category:c.trim()}:{},...r.length?{tags:r}:{}},metadata:a}:{schema:Md,schemaVersion:Nd,data:{url:p,...n.trim()?{title:n.trim()}:{},...r.length?{tags:r}:{}},metadata:a};return await Xr(e,[s])}finally{d(!1)}}return{url:e,setUrl:t,title:n,setTitle:r,tags:i,setTags:a,webapp:o,setWebapp:s,category:c,setCategory:l,saving:u,canSave:g,urlValid:m,showUrlError:h,save:_,geotag:f}}function Rd(){let{closeAdd:e,state:t}=ti(),n=Qr(),{showSuccessToast:r,showErrorToast:i}=gi(),a=Ld(),o=Ta(n,t.addRelateTo),s=Sa(t.activeWorkspaceName),c=!!n&&a.canSave;return(0,Q.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(q,{htmlFor:`link-url`,children:`URL`}),(0,Q.jsx)(en,{id:`link-url`,value:a.url,onChange:e=>a.setUrl(e.target.value),placeholder:`https://example.com`,autoFocus:!0}),a.showUrlError&&(0,Q.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(q,{htmlFor:`link-title`,children:`Title`}),(0,Q.jsx)(en,{id:`link-title`,value:a.title,onChange:e=>a.setTitle(e.target.value),placeholder:`Optional display title`})]}),(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(q,{children:`Tags`}),(0,Q.jsx)(Rr,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,Q.jsx)(jd,{webapp:a.webapp,setWebapp:a.setWebapp,category:a.category,setCategory:a.setCategory,idPrefix:`link`}),(0,Q.jsx)(Ca,{geotag:a.geotag,idPrefix:`link-geotag`}),(0,Q.jsx)(wa,{f:o,idPrefix:`link`}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:$r(n)}),(0,Q.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Q.jsx)(K,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving,children:`Cancel`}),(0,Q.jsx)(K,{size:`sm`,onClick:async()=>{if(n)try{let t=await a.save(n),i=await o.write(t);r(i?`Link created; some relations failed`:`Link created`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create link`)}},disabled:!c,children:a.saving?`Saving…`:`Save link`})]})]})}function zd(e){let[t,n]=(0,Z.useState)({key:``,list:[]});return(0,Z.useEffect)(()=>{if(!e)return;let t=!1;return gr(e,`github`).then(async r=>{let i=r.filter(e=>e.capabilities?.write),a=[];for(let t of i){let n=await nr(e,`github`,t.address).catch(()=>[]);for(let e of n){if(e.writable===!1)continue;let n=e.id||e.name;a.push({driver:`github`,address:t.address,container:n,label:`GitHub: ${n}`})}}t||n({key:e,list:a})}).catch(()=>{t||n({key:e,list:[]})}),()=>{t=!0}},[e]),e&&t.key===e?t.list:[]}function Bd(){let{closeAdd:e,state:t}=ti(),n=Qr(),{showSuccessToast:r,showErrorToast:i}=gi(),a=pi(),o=Ta(n,t.addRelateTo),s=Sa(t.activeWorkspaceName),c=zd(t.activeWorkspaceName),[l,u]=(0,Z.useState)(`canvas`),[d,f]=(0,Z.useState)(!1),p=c.find(e=>`${e.driver}:${e.address}:${e.container}`===l),m=p?a.title.trim().length>0&&!d:!!n&&a.canSave,h=async()=>{if(p){f(!0);try{await rr(t.activeWorkspaceName||``,p.driver,p.address,p.container,{title:a.title.trim(),...a.description.trim()?{description:a.description.trim()}:{},...a.tags.length?{labels:a.tags}:{}}),r(`Issue created in ${p.container}`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create issue`)}finally{f(!1)}return}if(n)try{let t=await a.save(n),i=await o.write(t);r(i?`Todo created; some relations failed`:`Todo created`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create todo`)}};return(0,Q.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Q.jsx)(Ir,{...a}),(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(q,{children:`Tags`}),(0,Q.jsx)(Rr,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(q,{htmlFor:`todo-comment`,children:`Comment`}),(0,Q.jsx)(`textarea`,{id:`todo-comment`,value:a.comment,onChange:e=>a.setComment(e.target.value),rows:3,placeholder:`Optional context`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})]}),c.length>0&&(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(q,{htmlFor:`todo-destination`,children:`Save to`}),(0,Q.jsxs)(`select`,{id:`todo-destination`,value:l,onChange:e=>u(e.target.value),className:`flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-elevation-1 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`,children:[(0,Q.jsxs)(`option`,{value:`canvas`,children:[`Canvas: `,$r(n)]}),c.map(e=>(0,Q.jsx)(`option`,{value:`${e.driver}:${e.address}:${e.container}`,children:e.label},`${e.driver}:${e.address}:${e.container}`))]}),p&&(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Creates a GitHub issue (due date, priority and status stay Canvas-side until the issue syncs back).`})]}),(0,Q.jsx)(Ca,{geotag:a.geotag,idPrefix:`todo-geotag`}),!p&&(0,Q.jsx)(wa,{f:o,idPrefix:`todo`}),!p&&(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:$r(n)}),(0,Q.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Q.jsx)(K,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving||d,children:`Cancel`}),(0,Q.jsx)(K,{size:`sm`,onClick:h,disabled:!m,children:a.saving||d?`Saving…`:p?`Create issue`:`Save todo`})]})]})}function Vd(){let{closeAdd:e,state:t}=ti(),n=Qr(),{showSuccessToast:r,showErrorToast:i}=gi(),a=Lr(),o=Ta(n,t.addRelateTo),s=Sa(t.activeWorkspaceName),c=async()=>{if(n)try{let t=await a.save(n),i=await o.write(t);r(i?`Identity created; some relations failed`:`Identity created`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create identity`)}};return(0,Q.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Q.jsx)(zr,{idPrefix:`add-identity`,workspaceName:t.activeWorkspaceName??void 0,...a,emailValid:a.emailValid}),(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(q,{children:`Tags`}),(0,Q.jsx)(Rr,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(q,{htmlFor:`identity-comment`,children:`Comment`}),(0,Q.jsx)(`textarea`,{id:`identity-comment`,value:a.comment,onChange:e=>a.setComment(e.target.value),rows:3,placeholder:`How you know them, where they came from…`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})]}),(0,Q.jsx)(wa,{f:o,idPrefix:`identity`}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:$r(n)}),(0,Q.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Q.jsx)(K,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving,children:`Cancel`}),(0,Q.jsx)(K,{size:`sm`,onClick:c,disabled:!n||!a.canSave,children:a.saving?`Saving…`:`Save identity`})]})]})}function Hd(){let{closeAdd:e}=ti(),t=Qr(),{showSuccessToast:n,showErrorToast:r}=gi(),[i,a]=(0,Z.useState)(``),[o,s]=(0,Z.useState)(!1),c=i.trim().replace(/^\/+|\/+$/g,``),l=!!t&&!!c&&!o,u=async()=>{if(!(!l||!t)){s(!0);try{let{workspaceName:r,path:i,treeName:a}=await Gr(t),o=i===`/`?``:i;if(a===`backends`){let e=await qr(r,i);await dr(r,e.driver,e.address,[[e.key,c].filter(Boolean).join(`/`)]),Zr(t)}else await lr(r,`${o}/${c}`,!0,a);n(`Folder created`),e()}catch(e){r(e instanceof Error?e.message:`Failed to create folder`)}finally{s(!1)}}};return(0,Q.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(q,{htmlFor:`add-folder-name`,children:`Folder name`}),(0,Q.jsx)(en,{id:`add-folder-name`,value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&u()},placeholder:`e.g. projects/alpha`,autoFocus:!0}),(0,Q.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Nested paths are created as needed. Target: `,$r(t)]})]}),(0,Q.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Q.jsx)(K,{variant:`outline`,size:`sm`,onClick:e,disabled:o,children:`Cancel`}),(0,Q.jsx)(K,{size:`sm`,onClick:u,disabled:!l,children:o?`Creating…`:`Create folder`})]})]})}function Ud(){let{openAddPicker:e,closeAdd:t}=ti(),n=Qr(),{showSuccessToast:r,showErrorToast:i}=gi(),[a,o]=(0,Z.useState)(!1);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`fixed inset-0 z-picker-scrim bg-scrim animate-fade-in md:hidden`,onClick:()=>e(),"aria-hidden":!0}),(0,Q.jsx)(`div`,{className:`fixed inset-y-0 right-0 z-picker flex items-stretch py-2 pr-2 max-md:bottom-2 max-md:left-2 max-md:top-2 max-md:py-0 max-md:pr-0 max-md:animate-fade-in`,children:(0,Q.jsx)(mi,{sizeClassName:`h-full w-[420px] max-w-full max-md:w-full max-md:shadow-elevation-5`,fixedWorkspaceName:n?.mode===`workspace`?n.workspaceName:void 0,saving:a,onConfirm:async e=>{o(!0);try{await Yr(n,e),r(`${e.length} document${e.length===1?``:`s`} added`),t()}catch(e){i(e instanceof Error?e.message:`Failed to add documents`)}finally{o(!1)}},onClose:e})})]})}function Wd(){let{state:e,closeAdd:t}=ti(),{editDocument:n,editWorkspaceId:r}=e,{showSuccessToast:i,showErrorToast:a}=gi();return!n||!r?null:(0,Q.jsx)(Gd,{doc:n,workspaceId:r,onCancel:t,onSaved:t,showSuccessToast:i,showErrorToast:a},`${r}:${n.id}`)}function Gd({doc:e,workspaceId:t,onCancel:n,onSaved:r,showSuccessToast:i,showErrorToast:a}){let o=Ai(e,t),s=Sa(t),c=async()=>{try{await o.save(),i(`Note updated`),r()}catch(e){a(e instanceof Error?e.message:`Failed to update note`)}};return(0,Q.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(q,{htmlFor:`edit-note-title`,children:`Title`}),(0,Q.jsx)(en,{id:`edit-note-title`,value:o.title,onChange:e=>o.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,Q.jsxs)(`div`,{className:`flex flex-1 flex-col gap-1.5`,children:[(0,Q.jsx)(q,{children:`Body`}),(0,Q.jsx)(`div`,{className:`flex-1`,children:(0,Q.jsx)(ji,{kind:`markdown`,value:o.content,onChange:o.setContent,placeholder:`Write your note…`})})]}),(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(q,{children:`Tags`}),(0,Q.jsx)(Rr,{tags:o.tags,onChange:o.setTags,suggestions:s})]}),(0,Q.jsx)(ki,{...o,onRetry:o.save}),(0,Q.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2`,children:[(0,Q.jsx)(K,{variant:`outline`,size:`sm`,onClick:n,disabled:o.saving,children:`Close`}),(0,Q.jsx)(K,{size:`sm`,onClick:c,disabled:!o.canSave,children:o.saving?`Saving…`:`Done`})]})]})}function Kd(e,t){let n=Wr(e.metadata?.features),[r,i]=(0,Z.useState)(String(e.data?.label??``)),[a,o]=(0,Z.useState)(n.length?n:e.data?.tags??[]),[s,c]=(0,Z.useState)(e.data?.type===kd),[l,u]=(0,Z.useState)(String(e.data?.category??``)),[d,f]=(0,Z.useState)(!1),p=!d;async function m(){f(!0);try{let n=a.map(e=>e.trim()).filter(Boolean),{type:i,category:o,...c}=e.data??{},u=s?kd:i===`webapp`?void 0:i;await mr(t,{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,data:{...c,...r.trim()?{label:r.trim()}:{},...u?{type:u}:{},...l.trim()?{category:l.trim()}:{},tags:n},metadata:{features:Ur(a)}}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`))}finally{f(!1)}}return{url:String(e.data?.uri??e.data?.url??``),label:r,setLabel:i,tags:a,setTags:o,webapp:s,setWebapp:c,category:l,setCategory:u,saving:d,canSave:p,save:m}}function qd(){let{state:e,closeAdd:t}=ti(),{editDocument:n,editWorkspaceId:r}=e,{showSuccessToast:i,showErrorToast:a}=gi();return!n||!r?null:(0,Q.jsx)(Jd,{doc:n,workspaceId:r,onCancel:t,onSaved:t,showSuccessToast:i,showErrorToast:a})}function Jd({doc:e,workspaceId:t,onCancel:n,onSaved:r,showSuccessToast:i,showErrorToast:a}){let o=Kd(e,t),s=Sa(t);return(0,Q.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsxs)(q,{children:[`URL `,(0,Q.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`(frozen)`})]}),(0,Q.jsx)(en,{value:o.url,disabled:!0,className:`font-mono text-xs`})]}),(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(q,{htmlFor:`edit-link-label`,children:`Label`}),(0,Q.jsx)(en,{id:`edit-link-label`,value:o.label,onChange:e=>o.setLabel(e.target.value),placeholder:`Optional display name`,autoFocus:!0})]}),(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(q,{children:`Tags`}),(0,Q.jsx)(Rr,{tags:o.tags,onChange:o.setTags,suggestions:s})]}),(0,Q.jsx)(jd,{webapp:o.webapp,setWebapp:o.setWebapp,category:o.category,setCategory:o.setCategory,idPrefix:`edit-link`,alwaysShowCategory:!0}),(0,Q.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Q.jsx)(K,{variant:`outline`,size:`sm`,onClick:n,disabled:o.saving,children:`Cancel`}),(0,Q.jsx)(K,{size:`sm`,onClick:async()=>{try{await o.save(),i(`Link updated`),r()}catch(e){a(e instanceof Error?e.message:`Failed to update link`)}},disabled:!o.canSave,children:o.saving?`Saving…`:`Save link`})]})]})}var Yd=380,Xd=300,Zd=560,Qd={message:{label:`New Message`,icon:St},note:{label:`New Note`,icon:jt},link:{label:`New Link`,icon:Ue},todo:{label:`New Todo`,icon:dt},identity:{label:`New Identity`,icon:De},sketch:{label:`New Sketch`,icon:Be},plaintext:{label:`New Plaintext File`,icon:Ct},file:{label:`Add Files`,icon:Pe},photo:{label:`Photo/Video`,icon:re},existing:{label:`Add Existing`,icon:Ze},folder:{label:`New Folder`,icon:ze}};function $d(){let{state:e,openAdd:t,openAddPicker:n,closeAdd:r}=ti();hi(r,e.addOpen);let{addOpen:i,addKind:a,editDocument:o,addModal:s}=e,c=Qr(),l=Kr(c),u=l.isBackend&&!!a&&![`file`,`photo`,`folder`,`message`,`plaintext`].includes(a),d=e.activeWorkspaceName,f=!d||!!e.addRelateTo,p=u||a===`message`&&f,h=l.isBackend?[`note`,`link`,`todo`,`identity`,`sketch`,`existing`]:[`plaintext`];f&&h.push(`message`);let g=c?.mode===`workspace`?`${c.workspaceName}:${c.treeName}:${c.path}`:c?.contextId,_=m();(0,Z.useEffect)(()=>{!i||a!==`sketch`||l.isBackend||(r(),_(Sd.createUrl(c)))},[i,a,c,r,_,l.isBackend]);let v=Pr(),[y,b]=(0,Z.useState)(Yd),x=(0,Z.useRef)(null),S=(0,Z.useCallback)(e=>{e.preventDefault(),x.current={startX:e.clientX,startWidth:y};let t=e=>{if(!x.current)return;let t=x.current.startX-e.clientX,n=Math.min(Zd,Math.max(Xd,x.current.startWidth+t));b(n)},n=()=>{x.current=null,window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n)};window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)},[y]);if(!i)return null;let C=!!o,w=!C&&(!a||p),T,E;C?(T=o.schema===`data/schema/note`?`Edit Note`:`Edit Link`,E=o.schema===`data/schema/note`?jt:Ue):a&&!p?(T=Qd[a].label,E=Qd[a].icon):(T=`Add`,E=ge);let D=(0,Q.jsxs)(Q.Fragment,{children:[v&&!s&&(0,Q.jsx)(`div`,{className:`fixed inset-0 z-panel-scrim bg-scrim animate-fade-in`,onClick:r,"aria-hidden":!0}),(0,Q.jsxs)(`div`,{style:v||s?void 0:{width:y},className:G(`flex flex-col overflow-hidden rounded-[var(--panel-radius)] border bg-card surface-glass`,s?`h-full w-full`:v?`fixed bottom-2 left-2 right-2 top-2 z-panel shadow-elevation-5 animate-fade-in`:`relative shrink-0 shadow-elevation-3`),children:[!v&&!s&&(0,Q.jsx)(`div`,{onMouseDown:S,className:`absolute left-0 top-0 bottom-0 z-10 w-1 cursor-col-resize transition-colors hover:bg-primary/20`}),(0,Q.jsxs)(`div`,{className:`flex h-[calc(3rem-1px)] shrink-0 items-center gap-2 border-b-4 px-2`,style:e.activeAccentColor?{borderBottomColor:e.activeAccentColor}:void 0,children:[(0,Q.jsx)(`button`,{type:`button`,className:`canvas-nav-button`,"aria-label":`Back one level`,onClick:()=>w||C?r():n(),children:(0,Q.jsx)(Tt,{className:`h-5 w-5`})}),(0,Q.jsxs)(`span`,{className:`flex flex-1 items-center gap-2 text-sm font-medium`,children:[C?(0,Q.jsx)(M,{className:`h-4 w-4`}):(0,Q.jsx)(E,{className:`h-4 w-4`}),T]}),(0,Q.jsx)(`button`,{type:`button`,onClick:r,className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Close`,children:(0,Q.jsx)(z,{className:`h-4 w-4`})})]}),(0,Q.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,children:[C&&o.schema===`data/schema/note`&&(0,Q.jsx)(Wd,{}),C&&o.schema===`data/schema/link`&&(0,Q.jsx)(qd,{}),!C&&w&&e.addRelateTo&&(0,Q.jsxs)(`p`,{className:`border-b px-4 py-2 text-xs text-muted-foreground`,children:[`The new document will be related to `,e.addRelateTo.documents.length,` selected document`,e.addRelateTo.documents.length===1?``:`s`,`.`]}),!C&&l.isBackend&&a!==`message`&&(0,Q.jsx)(`p`,{className:`border-b px-4 py-3 text-xs text-muted-foreground`,children:l.loading?`Checking storage destination…`:l.error||`Files are saved directly to this backend folder. Notes and other database documents belong in context or directory trees.`}),!C&&w&&(!l.isBackend||l.destination)&&(0,Q.jsx)(Td,{onSelect:t,omit:h}),!C&&a===`message`&&!f&&d&&(0,Q.jsx)(wi,{workspaceId:d,onClose:r},d),!C&&!l.isBackend&&a===`note`&&(0,Q.jsx)(Od,{},g),!C&&!l.isBackend&&a===`link`&&(0,Q.jsx)(Rd,{}),!C&&!l.isBackend&&a===`todo`&&(0,Q.jsx)(Bd,{}),!C&&!l.isBackend&&a===`identity`&&(0,Q.jsx)(Vd,{}),!C&&l.destination&&a===`plaintext`&&(0,Q.jsx)(bd,{},g),!C&&(!l.isBackend||l.destination)&&a===`file`&&(0,Q.jsx)(Ea,{},g),!C&&(!l.isBackend||l.destination)&&a===`photo`&&(0,Q.jsx)(Ea,{capture:!0},g),!C&&!l.isBackend&&a===`existing`&&(0,Q.jsx)(Ud,{}),!C&&(!l.isBackend||l.destination)&&a===`folder`&&(0,Q.jsx)(Hd,{},g)]})]})]});return s?(0,Q.jsx)(Nr,{label:T,onClose:r,children:D}):D}var ef=(0,Z.createContext)(null);function tf(){return(0,Z.useContext)(ef)}function nf(){let e=tf(),t=e?.notifications??[];return(0,Q.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Q.jsx)(`div`,{className:`flex items-center justify-between px-4 h-12 bg-foreground shrink-0`,children:(0,Q.jsx)(`span`,{className:`text-sm font-medium text-background`,children:`Home`})}),(0,Q.jsx)(`div`,{className:`px-4 py-4 border-b border-border shrink-0`,children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,Q.jsx)(ht,{className:`w-4 h-4`}),(0,Q.jsx)(`span`,{className:`text-xs font-mono`,children:new Date().toLocaleTimeString()})]})}),(0,Q.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between mb-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(Ge,{className:`w-3.5 h-3.5 text-muted-foreground`}),(0,Q.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:`Notifications`})]}),t.length>0&&(0,Q.jsx)(K,{size:`sm`,variant:`ghost`,className:`h-6 px-1.5 text-xs text-muted-foreground`,onClick:()=>void e?.clear(),title:`Clear notifications`,children:(0,Q.jsx)(W,{className:`w-3 h-3`})})]}),t.length===0?(0,Q.jsx)(`div`,{className:`text-xs text-muted-foreground text-center py-10 border border-dashed rounded-(--card-radius)`,children:`No notifications`}):(0,Q.jsx)(`div`,{className:`space-y-2`,children:[...t].reverse().map(e=>(0,Q.jsxs)(`div`,{className:`rounded-(--card-radius) border p-2.5`,children:[(0,Q.jsx)(`p`,{className:`text-xs whitespace-pre-wrap break-words`,children:e.text}),(0,Q.jsx)(`p`,{className:`mt-1 text-[10px] text-muted-foreground`,children:new Date(e.timestamp).toLocaleString()})]},e.id))})]})]})}function rf(e){let t=new URLSearchParams(e),n=t.getAll(`q`).map(e=>e.trim()).filter(Boolean),r=(t.get(`search`)||``).trim();return t.has(`q`)?n:r?[r]:[]}function af(){let{state:e,setFilters:t}=ti();return(0,Q.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:e.filters.geo.includeUnlocated??!1,onChange:n=>t({...e.filters,geo:{...e.filters.geo,includeUnlocated:n.target.checked}})}),`Include documents without a location`]})}var of=a(),sf=e(Mi(),1);Ni();var cf=`#8b5cf6`,lf=`#94a3b8`,uf={color:cf,weight:2,fillColor:cf,fillOpacity:.12},df={color:cf,weight:2,dashArray:`5,5`,fillColor:cf,fillOpacity:.06},ff=e=>Math.round(e*1e6)/1e6;function pf(e){let t=e<10?32:e<100?38:44,n=`<div style="display:flex;align-items:center;justify-content:center;width:${t}px;height:${t}px;border-radius:9999px;background:${cf};color:#fff;border:2px solid #fff;box-shadow:0 1px 4px rgba(0,0,0,.4);font:600 12px system-ui,sans-serif;cursor:pointer">${e}</div>`;return sf.default.divIcon({html:n,className:`canvas-map-cluster`,iconSize:[t,t],iconAnchor:[t/2,t/2]})}var mf=e=>e.replace(/[&<>"']/g,e=>({"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`})[e]),hf=new Map;function gf(e){let t=hf.get(e);return t??(t=(0,of.renderToStaticMarkup)((0,Z.createElement)(ld(e),{width:13,height:13,strokeWidth:2.5})),hf.set(e,t)),t}var _f=new Map;function vf(e,t){let n=`${e}|${+!!t}`,r=_f.get(n);if(!r){let i=`<div style="display:flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:9999px;background:${t?cf:lf};color:#fff;border:2px solid #fff;box-shadow:0 1px 3px rgba(0,0,0,.4);cursor:pointer">${gf(e)}</div>`;r=sf.default.divIcon({html:i,className:`canvas-map-pin`,iconSize:[26,26],iconAnchor:[13,13]}),_f.set(n,r)}return r}function yf(){let{state:e,setGeoSelection:t,setGeoBBox:n}=ti(),{mapDocuments:r,geoSelection:i,mapWorkspaceId:a}=e,o=e.filters.geo.bbox,{open:s}=Fi(),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),u=(0,Z.useRef)(null),d=(0,Z.useRef)(null),f=(0,Z.useRef)(null),p=(0,Z.useRef)([]),m=(0,Z.useRef)(!1),[h,g]=(0,Z.useState)(`idle`),[_,v]=(0,Z.useState)(0),y=(0,Z.useRef)(h),b=(0,Z.useMemo)(()=>r.reduce((e,t)=>e+ +!!Ri(t),0),[r]),x=(0,Z.useMemo)(()=>i?r.reduce((e,t)=>{let n=Ri(t);return e+(n&&Li(n.lat,n.lon,i)?1:0)},0):0,[r,i]),S=(0,Z.useCallback)(()=>{let e=f.current;if(!e)return;e.clearLayers();let t=p.current;t.length!==0&&(t.length>=2&&sf.default.polyline(t,df).addTo(e),t.forEach(t=>sf.default.circleMarker(t,{radius:4,color:cf,weight:2,fillColor:`#fff`,fillOpacity:1}).addTo(e)))},[]),C=(0,Z.useCallback)(()=>{p.current=[],v(0),f.current?.clearLayers()},[]),w=(0,Z.useCallback)(()=>{let e=p.current;e.length>=3&&t({kind:`polygon`,points:e.map(e=>({lat:ff(e.lat),lon:ff(e.lng)}))}),C(),g(`idle`)},[t,C]),T=(0,Z.useCallback)(()=>{C(),g(`idle`),t(null),n(null)},[C,t,n]);(0,Z.useEffect)(()=>{let e=c.current;if(!e||l.current)return;let t=sf.default.map(e,{center:[20,0],zoom:2,worldCopyJump:!0});sf.default.tileLayer(`https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png`,{attribution:`&copy; OpenStreetMap contributors`,maxZoom:19}).addTo(t),u.current=sf.default.markerClusterGroup({showCoverageOnHover:!1,maxClusterRadius:44,spiderfyOnMaxZoom:!0,chunkedLoading:!0,iconCreateFunction:e=>pf(e.getChildCount())}).addTo(t),f.current=sf.default.layerGroup().addTo(t),l.current=t;let r=t.getContainer(),i=null,a=null,o=()=>{a&&=(a.remove(),null)},s=e=>{if(y.current===`rect`){e.preventDefault(),i=t.mouseEventToLatLng(e),o();try{r.setPointerCapture(e.pointerId)}catch{}}},m=e=>{if(y.current!==`rect`||!i)return;e.preventDefault();let n=sf.default.latLngBounds(i,t.mouseEventToLatLng(e));a?a.setBounds(n):a=sf.default.rectangle(n,df).addTo(t)},h=e=>{if(y.current!==`rect`||!i)return;let a=sf.default.latLngBounds(i,t.mouseEventToLatLng(e));i=null,o();try{r.releasePointerCapture(e.pointerId)}catch{}let s=a.getSouthWest(),c=a.getNorthEast();s.lat!==c.lat&&s.lng!==c.lng&&n({minLat:ff(s.lat),minLon:ff(s.lng),maxLat:ff(c.lat),maxLon:ff(c.lng)}),g(`idle`)};r.addEventListener(`pointerdown`,s),r.addEventListener(`pointermove`,m),r.addEventListener(`pointerup`,h),r.addEventListener(`pointercancel`,h);let _=e=>{y.current===`polygon`&&(p.current=[...p.current,e.latlng],v(p.current.length),S())};t.on(`click`,_);let b=new ResizeObserver(()=>t.invalidateSize());b.observe(e);let x=window.setTimeout(()=>t.invalidateSize(),120);return()=>{r.removeEventListener(`pointerdown`,s),r.removeEventListener(`pointermove`,m),r.removeEventListener(`pointerup`,h),r.removeEventListener(`pointercancel`,h),t.off(`click`,_),b.disconnect(),window.clearTimeout(x),t.remove(),l.current=null,u.current=null,f.current=null,d.current=null}},[t,n,S]),(0,Z.useEffect)(()=>{y.current=h;let e=l.current;if(!e)return;let t=e.getContainer();h!==`polygon`&&p.current.length&&C(),h===`rect`?(e.dragging.disable(),e.doubleClickZoom.disable(),t.style.cursor=`crosshair`,t.style.touchAction=`none`):h===`polygon`?(e.dragging.enable(),e.doubleClickZoom.disable(),t.style.cursor=`crosshair`,t.style.touchAction=``):(e.dragging.enable(),e.doubleClickZoom.enable(),t.style.cursor=``,t.style.touchAction=``)},[h,C]),(0,Z.useEffect)(()=>{let e=l.current,t=c.current;if(!e||!t)return;let n=new ResizeObserver(()=>e.invalidateSize());return n.observe(t),()=>n.disconnect()},[]),(0,Z.useEffect)(()=>{let e=l.current,t=u.current;if(!e||!t)return;t.clearLayers();let n=[],o=[];for(let e of r){let t=Ri(e);if(!t)continue;n.push([t.lat,t.lon]);let r=!i||Li(t.lat,t.lon,i),c=sf.default.marker([t.lat,t.lon],{icon:vf(e.schema,r),opacity:i&&!r?.55:1,zIndexOffset:r?1e3:0});c.bindTooltip(mf(On(e).title),{direction:`top`,offset:[0,-14]}),c.on(`click`,()=>{y.current===`idle`&&s(e,a??``)}),o.push(c)}t.addLayers(o),!m.current&&n.length&&!i&&(m.current=!0,e.fitBounds(sf.default.latLngBounds(n),{padding:[30,30],maxZoom:14,animate:!1}))},[r,i,s,a]),(0,Z.useEffect)(()=>{let e=l.current;if(!e||(d.current&&=(d.current.remove(),null),!o&&!i))return;let t=sf.default.layerGroup();o&&sf.default.rectangle(sf.default.latLngBounds([o.minLat,o.minLon],[o.maxLat,o.maxLon]),uf).addTo(t),i?.kind===`polygon`&&sf.default.polygon(i.points.map(e=>[e.lat,e.lon]),uf).addTo(t),t.addTo(e),d.current=t},[o,i]);let E=h===`rect`?`Drag a box on the map…`:h===`polygon`?`Tap to add points${_?` · ${_}`:``}`:o||i?`Area selected`:`Pan & pick an area`,D=`flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-xs font-medium transition-colors`;return(0,Q.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 border-b border-border px-3 py-2 shrink-0`,children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>g(h===`rect`?`idle`:`rect`),className:G(D,h===`rect`?`border-primary bg-primary/10 text-foreground`:`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Drag a rectangle to select an area`,children:[(0,Q.jsx)(Ot,{className:`h-3.5 w-3.5`}),`Box`]}),(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>g(h===`polygon`?`idle`:`polygon`),className:G(D,h===`polygon`?`border-primary bg-primary/10 text-foreground`:`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Tap points to enclose an area`,children:[(0,Q.jsx)(ce,{className:`h-3.5 w-3.5`}),`Polygon`]}),h===`polygon`&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:w,disabled:_<3,className:G(D,`border-primary bg-primary text-primary-foreground hover:bg-primary disabled:opacity-40 disabled:hover:bg-primary`),title:`Close the polygon and filter`,children:[(0,Q.jsx)(Ie,{className:`h-3.5 w-3.5`}),`Finish`]}),_>0&&(0,Q.jsx)(`button`,{type:`button`,onClick:C,className:G(D,`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Discard the points placed so far`,children:(0,Q.jsx)(z,{className:`h-3.5 w-3.5`})})]}),(0,Q.jsxs)(`button`,{type:`button`,onClick:T,disabled:!o&&!i&&h===`idle`,className:G(D,`border-border text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-40 disabled:hover:bg-transparent`),title:`Clear the area selection`,children:[(0,Q.jsx)(W,{className:`h-3.5 w-3.5`}),`Clear`]}),(0,Q.jsx)(`span`,{className:`ml-auto text-[11px] text-muted-foreground`,children:E})]}),(0,Q.jsxs)(`div`,{className:`relative isolate flex-1 min-h-0`,children:[(0,Q.jsx)(`div`,{ref:c,className:`absolute inset-0`}),b===0&&(0,Q.jsx)(`div`,{className:`pointer-events-none absolute inset-0 z-[2] flex items-center justify-center`,children:(0,Q.jsxs)(`div`,{className:`rounded-lg border bg-card/95 px-4 py-3 text-center shadow-elevation-2`,children:[(0,Q.jsx)(`p`,{className:`text-sm font-medium text-foreground`,children:`No located documents`}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None of the current results carry location metadata.`})]})})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5 border-t border-border px-3 py-2 shrink-0 text-[11px] text-muted-foreground`,children:[(0,Q.jsx)(kt,{className:`h-3 w-3`}),b,` of `,r.length,` located`,i&&(0,Q.jsxs)(`span`,{className:`text-foreground font-medium`,children:[`· `,x,` in area`]})]})]})}var bf=(0,Z.createContext)(null);function xf(){let e=(0,Z.useContext)(bf);if(!e)throw Error(`useLensFeed must be used within a LensFeedProvider`);return e}function Sf(e=!0){let{registerViewer:t}=xf();(0,Z.useEffect)(()=>{if(e)return t()},[e,t])}var Cf=[{id:`720p`,label:`720p`,width:1280,height:720},{id:`1080p`,label:`1080p`,width:1920,height:1080},{id:`4k`,label:`4K`,width:3840,height:2160}],wf=`canvas.lens.camera`,Tf={min:1,max:4,step:.1,hardware:!1};function Ef(){let e={deviceId:null,resolution:`1080p`};try{let t=JSON.parse(localStorage.getItem(wf)||`null`);return t?{deviceId:typeof t.deviceId==`string`?t.deviceId:null,resolution:Cf.some(e=>e.id===t.resolution)?t.resolution:e.resolution}:e}catch{return e}}function Df(e,t){let n=Cf.find(t=>t.id===e.resolution)??Cf[1];return{...t&&e.deviceId?{deviceId:{exact:e.deviceId}}:{facingMode:`environment`},width:{ideal:n.width},height:{ideal:n.height}}}function Of(e={}){let t=(0,Z.useRef)(null),n=(0,Z.useRef)(e.onEnded);(0,Z.useEffect)(()=>{n.current=e.onEnded});let r=(0,Z.useRef)(null),i=(0,Z.useRef)(null),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(null),[l,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)(Ef),p=(0,Z.useRef)(d),[m,h]=(0,Z.useState)([]),[g,_]=(0,Z.useState)(!1),[v,y]=(0,Z.useState)(null),[b,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(1),w=(0,Z.useRef)(1),[T,E]=(0,Z.useState)(!1),D=(0,Z.useRef)(null),O=()=>r.current?.getVideoTracks()[0]??null,k=(0,Z.useCallback)(async e=>{let t=O();if(!t)return!1;try{return await t.applyConstraints({advanced:[e]}),!0}catch{return!1}},[]),A=(0,Z.useCallback)(async()=>{try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`videoinput`&&e.deviceId);h(e.map((e,t)=>({deviceId:e.deviceId,label:e.label||`Camera ${t+1}`})))}catch{}},[]),j=(0,Z.useCallback)(()=>{D.current&&window.clearTimeout(D.current),r.current?.getTracks().forEach(e=>e.stop()),r.current=null,t.current&&(t.current.srcObject=null),c(null),o(!1),_(!1),y(null),x(null),C(1),w.current=1,E(!1)},[]),M=(0,Z.useCallback)(async(e,i)=>{r.current=e,e.getVideoTracks().forEach(e=>{e.onended=()=>{j(),n.current?.()}}),t.current&&(t.current.srcObject=e,await t.current.play().catch(()=>{}));let a=e.getVideoTracks()[0],s=a?.getSettings();if(x(s?.width&&s?.height?{width:s.width,height:s.height}:null),_(i),E(!1),i&&a){let e=a.getCapabilities?.()??{};y(e),e.focusMode?.includes(`continuous`)&&await k({focusMode:`continuous`});let t=a.getSettings().zoom;C(e.zoom?t??e.zoom.min:1),w.current=1,A()}c(e),o(!0)},[j,k,A]),N=(0,Z.useCallback)(async e=>{try{return await navigator.mediaDevices.getUserMedia({video:Df(e,!0),audio:!1})}catch(t){let n=t?.name;if(e.deviceId&&(n===`OverconstrainedError`||n===`NotFoundError`||n===`NotReadableError`))return navigator.mediaDevices.getUserMedia({video:Df(e,!1),audio:!1});throw t}},[]),ee=(0,Z.useCallback)(async()=>{if(u(null),!window.isSecureContext)return u(`Camera needs a secure context (https or localhost).`),!1;if(!navigator.mediaDevices?.getUserMedia)return u(`Camera API not available in this browser.`),!1;try{let e=await N(p.current);return await M(e,!0),!0}catch(e){let t=e?.name;return u(t===`NotAllowedError`?`Camera permission denied.`:t===`NotFoundError`?`No camera found.`:`Camera failed: ${e?.message||t||`unknown error`}`),o(!1),!1}},[M,N]),P=(0,Z.useCallback)(async()=>{if(u(null),!window.isSecureContext)return u(`Screen capture needs a secure context (https or localhost).`),!1;if(!navigator.mediaDevices?.getDisplayMedia)return u(`Screen capture API not available in this browser.`),!1;try{let e=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1280},height:{ideal:720}},audio:!1});return await M(e,!1),!0}catch(e){let t=e?.name;return u(t===`NotAllowedError`?`Screen capture cancelled.`:`Screen capture failed: ${e?.message||t||`unknown error`}`),o(!1),!1}},[M]),F=(0,Z.useCallback)(e=>{let t={...p.current,...e};p.current=t,f(t);try{localStorage.setItem(wf,JSON.stringify(t))}catch{}!r.current||!g||(r.current.getTracks().forEach(e=>{e.onended=null,e.stop()}),r.current=null,ee().then(e=>{e||(j(),n.current?.())}))},[g,ee,j]),te=(0,Z.useCallback)(e=>{C(e),v?.zoom?k({zoom:e}):w.current=e},[v,k]),ne=(0,Z.useCallback)(e=>{k({torch:e}).then(t=>{t&&E(e)})},[k]),re=!!v?.focusMode?.some(e=>e===`single-shot`||e===`continuous`),I=(0,Z.useCallback)(e=>{let t=v?.focusMode??[];if(!t.length)return;D.current&&window.clearTimeout(D.current);let n=navigator.mediaDevices.getSupportedConstraints(),r=e&&n.pointsOfInterest?{pointsOfInterest:[e]}:{};t.includes(`single-shot`)?(k({...r,focusMode:`single-shot`}),t.includes(`continuous`)&&(D.current=window.setTimeout(()=>void k({...r,focusMode:`continuous`}),1500))):k({...r,focusMode:`continuous`})},[v,k]),ie=(0,Z.useCallback)((e=640,n=.72)=>{let r=t.current;if(!r||r.readyState<2||!r.videoWidth)return null;let a=Math.max(1,w.current),o=r.videoWidth/a,s=r.videoHeight/a,c=(r.videoWidth-o)/2,l=(r.videoHeight-s)/2,u=Math.min(1,e/Math.max(o,s)),d=Math.round(o*u),f=Math.round(s*u);i.current||=document.createElement(`canvas`);let p=i.current;p.width=d,p.height=f;let m=p.getContext(`2d`);return m?(m.drawImage(r,c,l,o,s,0,0,d,f),p.toDataURL(`image/jpeg`,n)):null},[]);return(0,Z.useEffect)(()=>j,[j]),{videoRef:t,stream:s,active:a,error:l,start:ee,startScreen:P,stop:j,captureFrame:ie,camera:(0,Z.useMemo)(()=>g?{devices:m,prefs:d,setPrefs:F,size:b,zoomRange:v?.zoom?{min:v.zoom.min,max:v.zoom.max,step:v.zoom.step||.1,hardware:!0}:Tf,zoom:S,setZoom:te,torchSupported:!!v?.torch,torch:T,setTorch:ne,focusSupported:re,focusAt:I}:null,[g,m,d,F,b,v,S,te,T,ne,re,I])}}async function kf(e,t,n={}){let r={limit:n.limit??12,scope:n.contextPath?`path`:`workspace`};t&&(r.image=t),n.similarTo&&(r.similarTo=n.similarTo);let i=n.q?.trim();i&&(r.q=i),n.maxDistance!=null&&Number.isFinite(n.maxDistance)&&(r.maxDistance=n.maxDistance),n.minDistance!=null&&Number.isFinite(n.minDistance)&&(r.minDistance=n.minDistance),n.debug&&(r.debug=!0),n.idsOnly&&(r.idsOnly=!0),n.contextPath&&(r.context=n.contextPath),n.treeId&&(r.treeNameOrTreeId=n.treeId),n.features&&Object.assign(r,n.features),n.filters&&(r.filters=n.filters),n.applyCanvasQuerySpec!==void 0&&(r.applyCanvasQuerySpec=n.applyCanvasQuerySpec);let a=await Y.postEnvelope(`${nn.workspaces}/${encodeURIComponent(e)}/documents/search/image`,r,n.signal?{signal:n.signal}:void 0),o=a.payload??[],s=n.idsOnly===!0;return{documents:s?[]:o,ids:s?o:o.map(e=>e.id),count:a.count??o.length,totalCount:a.totalCount??o.length,distances:a.debug?.distances??a.debug?.imageDistances??null}}var Af=[{label:`0.5 fps`,ms:2e3},{label:`1 fps`,ms:1e3},{label:`2 fps`,ms:500},{label:`5 fps`,ms:200},{label:`10 fps`,ms:100},{label:`15 fps`,ms:67},{label:`30 fps`,ms:33}],jf=1e3,Mf=32,Nf=12,Pf=`canvas.lens.fit`;function Ff({className:e,interactive:t=!1}){let{stream:n,camera:r,fit:i}=xf(),a=(0,Z.useRef)(null),[o,s]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{let e=a.current;if(e)return e.srcObject=n,n&&e.play().catch(()=>{}),()=>{e.srcObject=null}},[n]),(0,Z.useEffect)(()=>{if(!o)return;let e=window.setTimeout(()=>s(null),900);return()=>window.clearTimeout(e)},[o]);let c=r&&!r.zoomRange.hardware?r.zoom:1;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`video`,{ref:a,muted:!0,playsInline:!0,onClick:t?e=>{let t=a.current;if(!t||!r?.focusSupported||!t.videoWidth)return;let n=t.getBoundingClientRect(),o=(e.clientX-n.left)/n.width,l=(e.clientY-n.top)/n.height,u=.5+(o-.5)/c,d=.5+(l-.5)/c,f=i===`contain`?Math.min(n.width/t.videoWidth,n.height/t.videoHeight):Math.max(n.width/t.videoWidth,n.height/t.videoHeight),p=t.videoWidth*f/n.width,m=t.videoHeight*f/n.height,h=.5+(u-.5)/p,g=.5+(d-.5)/m;h<0||h>1||g<0||g>1||(r.focusAt({x:h,y:g}),s({x:o,y:l,key:Date.now()}))}:void 0,style:c===1?void 0:{transform:`scale(${c})`},className:G(e,i===`contain`?`object-contain`:`object-cover`,t&&r?.focusSupported&&`cursor-crosshair`)}),o&&(0,Q.jsx)(`span`,{"aria-hidden":!0,className:`pointer-events-none absolute h-10 w-10 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white/90 animate-fade-in`,style:{left:`${o.x*100}%`,top:`${o.y*100}%`}},o.key)]})}function If({children:e}){let t=ni(),n=(0,Z.useRef)(t);(0,Z.useEffect)(()=>{n.current=t});let r=t?.state.activeWorkspaceName??null,i=t!==null,a=(0,Z.useRef)(()=>{}),{videoRef:o,stream:s,camera:c,error:l,start:u,startScreen:d,stop:f,captureFrame:p}=Of({onEnded:()=>a.current()}),[m,h]=(0,Z.useState)(null),g=(0,Z.useRef)(m);(0,Z.useEffect)(()=>{g.current=m},[m]);let[_,v]=(0,Z.useState)(null),[y,b]=(0,Z.useState)(!1),[x,S]=(0,Z.useState)(jf),[C,w]=(0,Z.useState)(``),[T,E]=(0,Z.useState)(``),[D,O]=(0,Z.useState)(null),[k,A]=(0,Z.useState)(null),[j,M]=(0,Z.useState)(null),[N,ee]=(0,Z.useState)([]),[P,F]=(0,Z.useState)(null),[te,ne]=(0,Z.useState)(null),re=te&&te.frame===P?te:null,I=(0,Z.useRef)(null),[ie,ae]=(0,Z.useState)(0),[oe,se]=(0,Z.useState)(``),[L,ce]=(0,Z.useState)(()=>{try{return localStorage.getItem(Pf)===`cover`?`cover`:`contain`}catch{return`contain`}}),le=(0,Z.useCallback)(e=>{ce(e);try{localStorage.setItem(Pf,e)}catch{}},[]),R=(0,Z.useRef)({running:!1,paused:!1,consumer:null,workspaceRef:``,contextPath:null,text:``,maxDistance:NaN,rateMs:jf,snapshot:!1}),ue=(0,Z.useRef)([]),de=(0,Z.useRef)(new Map),z=(0,Z.useRef)(null),B=(0,Z.useRef)(null),V=(0,Z.useRef)(null),fe=(0,Z.useRef)(0),H=(0,Z.useRef)(``),pe=(0,Z.useRef)(!1),me=(0,Z.useRef)(async()=>{}),he=(0,Z.useRef)(()=>{});(0,Z.useEffect)(()=>{R.current.text=T,R.current.maxDistance=C===``?NaN:Number(C),R.current.rateMs=x,R.current.paused=y},[T,C,x,y]);let ge=(0,Z.useCallback)(()=>(ae(e=>e+1),()=>ae(e=>Math.max(0,e-1))),[]),_e=(0,Z.useCallback)(e=>{ue.current=[...ue.current.slice(-2),e];let t=ue.current,r=[...new Set(t.flat())],i=t.length<2?e:r.filter(e=>t.filter(t=>t.includes(e)).length>=2);M(i.length);let a=z.current;(!a||a.length!==i.length||a.some((e,t)=>e!==i[t]))&&(z.current=i,n.current?.setLensIds(i))},[]),ve=(0,Z.useCallback)((e,t)=>{for(let n of e)de.current.set(n.id,{doc:n,distance:t.get(n.id)});let n=e.map(e=>e.id);ue.current=[...ue.current.slice(-2),n];let r=ue.current,i=r[r.length-1]??[],a=r.length<2?i:i.filter(e=>r.filter(t=>t.includes(e)).length>=2),o=[...de.current.keys()].filter(e=>!i.includes(e)&&r.filter(t=>t.includes(e)).length>=2),s=[...a,...o].map(e=>de.current.get(e)).filter(e=>!!e);M(s.length),ee(s)},[]),ye=(0,Z.useCallback)(async(e,t)=>{let r=performance.now(),i=t.consumer===`applet`;V.current?.abort();let a=new AbortController;V.current=a;try{let o=n.current?.state,s=!i&&o?.activeContextType===`context`,c=await kf(t.workspaceRef,e,{q:i&&t.text||void 0,maxDistance:Number.isFinite(t.maxDistance)?t.maxDistance:void 0,contextPath:s?o.activeContextPath:i?t.contextPath:null,treeId:s?o.activeTreeName:null,features:s?o.filters.features:void 0,filters:s?[...Qi(o.filters.timeline),...Xi(o.filters.geo),...$i(o.filters.lens,o.filters.geo.includeUnlocated)]:void 0,applyCanvasQuerySpec:!s&&void 0,limit:i?Nf:Mf,idsOnly:!i,debug:i,signal:a.signal});return a.signal.aborted||R.current!==t||!t.running?!1:(fe.current=0,A(Math.round(performance.now()-r)),O(null),i?ve(c.documents,new Map((c.distances??[]).map(e=>[e.id,e.distance]))):_e(c.ids),!0)}catch(e){return a.signal.aborted||R.current!==t||!t.running?!1:(fe.current++,e?.name!==`AbortError`&&O(e?.message||`search failed`),!1)}},[ve,_e]),be=(0,Z.useCallback)(async()=>{let e=R.current;if(!e.running)return;let t=performance.now();if(!e.paused&&!e.snapshot){let t=p();t&&e.workspaceRef&&await ye(t,e)}if(R.current.running){let e=Math.max(fe.current?Math.min(3e4,1e3*2**Math.min(fe.current-1,5)):0,R.current.rateMs-(performance.now()-t));B.current=window.setTimeout(()=>void me.current(),e)}},[p,ye]);(0,Z.useEffect)(()=>{me.current=be},[be]);let U=(0,Z.useCallback)(()=>{let e=R.current.consumer===`filter`;R.current.running=!1,fe.current=0,R.current.consumer=null,B.current&&window.clearTimeout(B.current),V.current?.abort(),f(),ue.current=[],de.current.clear(),z.current=null,h(null),v(null),b(!1),se(``),ee([]),F(null),M(null),A(null),O(null),e&&n.current?.state.activeContextType!==`context`&&n.current?.setLensIds(null)},[f]);(0,Z.useEffect)(()=>{a.current=U},[U]);let xe=(0,Z.useCallback)(async(e,t,r)=>{if(!r.workspaceRef||pe.current||(R.current.running&&U(),e===`photo`&&!r.image))return!1;pe.current=!0;let i=e===`photo`?!0:e===`camera`?await u():await d();return pe.current=!1,i?(ue.current=[],de.current.clear(),z.current=null,ee([]),M(null),O(null),se(r.workspaceRef),R.current={...R.current,running:!0,paused:!1,consumer:t,workspaceRef:r.workspaceRef,contextPath:r.contextPath??null,snapshot:e===`photo`},F(e===`photo`?r.image:null),h(e),v(t),b(!1),t===`filter`&&n.current?.setLensIds([]),e===`photo`?he.current(r.image):be(),!0):!1},[u,d,U,be]),Se=JSON.stringify(t?{contextId:t.state.activeContextId,path:t.state.activeContextPath,tree:t.state.activeTreeName,features:t.state.filters.features,timeline:t.state.filters.timeline,geo:t.state.filters.geo,gps:t.state.filters.lens.gps}:null);(0,Z.useEffect)(()=>{H.current!==Se&&(H.current=Se,R.current.consumer===`filter`&&(V.current?.abort(),ue.current=[],z.current=null,n.current?.setLensIds([])))},[Se]);let Ce=(0,Z.useCallback)(e=>{R.current.contextPath=e},[]),we=(0,Z.useCallback)(e=>{R.current.paused=e,b(e)},[]),Te=JSON.stringify([T,C,Se]),Ee=(0,Z.useRef)(Te);(0,Z.useEffect)(()=>{Ee.current=Te});let De=(0,Z.useCallback)(e=>{let t=R.current;!t.running||!t.workspaceRef||(I.current={frame:e,key:Ee.current},ue.current=[],de.current.clear(),z.current=null,M(null),ye(e,t))},[ye]);(0,Z.useEffect)(()=>{he.current=De},[De]);let Oe=(0,Z.useCallback)(()=>{let e=R.current;if(!e.running)return;let t=p(1280,.85);t&&(e.snapshot=!0,F(t),De(t))},[p,De]),ke=(0,Z.useCallback)(()=>{if(R.current.running&&g.current===`photo`){U();return}R.current.snapshot=!1,V.current?.abort(),ue.current=[],de.current.clear(),F(null)},[U]),Ae=(0,Z.useCallback)(async(e,t,n)=>{let r=R.current;return r.running&&r.consumer===t&&g.current===`camera`?(r.snapshot=!0,F(e),De(e),!0):xe(`photo`,t,{...n,image:e})},[xe,De]);(0,Z.useEffect)(()=>{if(!P)return;let e=!0,t=new Image;return t.onload=()=>{e&&ne({frame:P,width:t.naturalWidth,height:t.naturalHeight})},t.src=P,()=>{e=!1}},[P]),(0,Z.useEffect)(()=>{if(!P)return;let e=I.current;if(e&&e.frame===P&&e.key===Te)return;let t=window.setTimeout(()=>De(P),350);return()=>window.clearTimeout(t)},[P,Te,De]),(0,Z.useEffect)(()=>{!i||!R.current.running||r&&r===R.current.workspaceRef||U()},[i,r,U]);let je=(0,Z.useCallback)(()=>{let e=n.current;if(e){if(R.current.consumer===`applet`){e.setView(`apps`),e.openApplet(`lens`);return}e.setView(`tools`),e.setToolsTab(`lens`)}},[]);(0,Z.useEffect)(()=>U,[U]);let Me=(0,Z.useMemo)(()=>({source:m,running:m!==null,paused:y,consumer:_,stream:s,camera:c,fit:L,setFit:le,workspaceRef:oe,rateMs:x,setRateMs:S,maxDistance:C,setMaxDistance:w,text:T,setText:E,error:l||D,latencyMs:k,lastCount:j,hits:N,start:xe,setContextPath:Ce,stop:U,setPaused:we,snapshot:P,takeSnapshot:Oe,clearSnapshot:ke,snapshotSize:re,searchPhoto:Ae,reopen:je,hasViewer:ie>0,registerViewer:ge}),[m,y,_,s,c,L,le,oe,x,C,T,l,D,k,j,N,xe,Ce,U,we,P,Oe,ke,re,Ae,je,ie,ge]);return(0,Q.jsxs)(bf.Provider,{value:Me,children:[e,(0,Q.jsx)(`video`,{ref:o,muted:!0,playsInline:!0,"aria-hidden":!0,className:`pointer-events-none fixed bottom-0 left-0 h-px w-px opacity-0`})]})}var Lf=`h-7 min-w-0 rounded-md border border-input bg-transparent px-1.5 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,Rf=`flex h-7 items-center gap-1 rounded-md border border-border px-2 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,zf=e=>`${e<10?e.toFixed(1):Math.round(e)}×`;function Bf({className:e}){let{camera:t,fit:n,setFit:r}=xf();if(!t)return null;let{devices:i,prefs:a,setPrefs:o,size:s,zoomRange:c,zoom:l,setZoom:u}=t,d=c.max>c.min;return(0,Q.jsxs)(`div`,{className:G(`flex flex-col gap-2`,e),children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i.length>1&&(0,Q.jsxs)(`select`,{className:G(Lf,`max-w-[12rem] flex-1`),value:a.deviceId??``,onChange:e=>o({deviceId:e.target.value||null}),title:`Camera / lens. On phones with several rear cameras, pick the main or wide one if the picture is too zoomed in.`,"aria-label":`Camera`,children:[(0,Q.jsx)(`option`,{value:``,children:`Default rear camera`}),i.map(e=>(0,Q.jsx)(`option`,{value:e.deviceId,children:e.label},e.deviceId))]}),(0,Q.jsx)(`select`,{className:Lf,value:a.resolution,onChange:e=>o({resolution:e.target.value}),title:s?`Requested resolution — camera is delivering ${s.width}×${s.height}`:`Requested resolution`,"aria-label":`Resolution`,children:Cf.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.label},e.id))}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>r(n===`contain`?`cover`:`contain`),className:Rf,title:n===`contain`?`Showing the whole frame — switch to fill the preview`:`Filling the preview (edges cropped) — switch to the whole frame`,"aria-label":n===`contain`?`Fill preview`:`Fit whole frame`,children:n===`contain`?(0,Q.jsx)(ft,{className:`h-3.5 w-3.5`}):(0,Q.jsx)(vt,{className:`h-3.5 w-3.5`})}),t.focusSupported&&(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>t.focusAt(),className:Rf,title:`Refocus (or tap the preview to focus on a spot)`,children:[(0,Q.jsx)(Wt,{className:`h-3.5 w-3.5`}),` Focus`]}),t.torchSupported&&(0,Q.jsx)(`button`,{type:`button`,onClick:()=>t.setTorch(!t.torch),className:G(Rf,t.torch&&`border-foreground text-foreground`),"aria-pressed":t.torch,title:t.torch?`Torch off`:`Torch on`,children:t.torch?(0,Q.jsx)(nt,{className:`h-3.5 w-3.5`}):(0,Q.jsx)(At,{className:`h-3.5 w-3.5`})}),s&&(0,Q.jsxs)(`span`,{className:`text-[11px] tabular-nums text-muted-foreground`,children:[s.width,`×`,s.height]})]}),d&&(0,Q.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,title:c.hardware?`Optical/sensor zoom`:`Digital zoom — crops the searched frame too`,children:[(0,Q.jsx)(F,{className:`h-3.5 w-3.5 shrink-0`}),(0,Q.jsx)(`input`,{type:`range`,min:c.min,max:c.max,step:c.step,value:l,onChange:e=>u(Number(e.target.value)),onDoubleClick:()=>u(c.min),className:`h-1 min-w-0 flex-1 accent-foreground`,"aria-label":`Zoom`}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>u(c.min),className:`w-10 shrink-0 text-right tabular-nums hover:text-foreground`,title:`Reset zoom`,children:zf(l)})]})]})}function Vf(){let{running:e,source:t,snapshot:n,takeSnapshot:r,clearSnapshot:i,fit:a}=xf();return e?n?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`img`,{src:n,alt:`Snapshot being searched`,className:G(`absolute inset-0 h-full w-full bg-black`,a===`contain`?`object-contain`:`object-cover`)}),(0,Q.jsx)(`span`,{className:`pointer-events-none absolute left-2 top-2 rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-white`,children:t===`photo`?`Photo`:`Snapshot`}),(0,Q.jsx)(`button`,{type:`button`,onClick:i,className:`absolute bottom-2 left-1/2 flex h-9 -translate-x-1/2 items-center gap-1.5 rounded-full bg-black/60 px-3 text-xs font-medium text-white backdrop-blur transition-colors hover:bg-black/75`,title:t===`photo`?`Close the photo and clear its matches`:`Discard the snapshot and go back to the live feed`,children:t===`photo`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(z,{className:`h-3.5 w-3.5`}),` Close`]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Ee,{className:`h-3.5 w-3.5`}),` Live`]})})]}):t===`photo`?null:(0,Q.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Take a snapshot and search it`,title:`Snapshot: freeze this frame and search for similar items`,className:`absolute bottom-2 left-1/2 flex h-12 w-12 -translate-x-1/2 items-center justify-center rounded-full border-4 border-white/90 bg-white/25 text-white shadow-lg backdrop-blur transition-transform hover:bg-white/40 active:scale-90`,children:(0,Q.jsx)(qt,{className:`h-5 w-5`})}):null}async function Hf(e,t=1280,n=.85){let r,i=null;try{r=await createImageBitmap(e,{imageOrientation:`from-image`})}catch{i=URL.createObjectURL(e);let t=new Image;t.src=i,await t.decode(),r=t}try{let e=r.width,i=r.height,a=Math.min(1,t/Math.max(e,i)),o=document.createElement(`canvas`);o.width=Math.round(e*a),o.height=Math.round(i*a);let s=o.getContext(`2d`);if(!s)throw Error(`canvas unavailable`);return s.drawImage(r,0,0,o.width,o.height),o.toDataURL(`image/jpeg`,n)}finally{`close`in r&&r.close(),i&&URL.revokeObjectURL(i)}}function Uf({consumer:e,workspaceRef:t,contextPath:n,disabled:r,className:i}){let{searchPhoto:a}=xf(),o=(0,Z.useRef)(null),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(null),d=async r=>{if(r){c(!0),u(null);try{let i=await Hf(r);await a(i,e,{workspaceRef:t,contextPath:n})}catch{u(`Could not read that image.`)}finally{c(!1),o.current&&(o.current.value=``)}}};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>o.current?.click(),disabled:r||s||!t,className:i,title:l??`Search with a photo from the camera app or gallery`,children:[(0,Q.jsx)(H,{className:`h-3.5 w-3.5`}),` `,s?`Reading…`:`Photo`]}),(0,Q.jsx)(`input`,{ref:o,type:`file`,accept:`image/*`,className:`hidden`,onChange:e=>void d(e.target.files?.[0])}),l&&(0,Q.jsx)(`span`,{className:`text-xs text-destructive`,children:l})]})}var Wf=[{label:`25 m`,m:25},{label:`100 m`,m:100},{label:`500 m`,m:500},{label:`2 km`,m:2e3},{label:`10 km`,m:1e4}],Gf=`h-7 rounded-md border border-input bg-transparent px-1.5 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,Kf=`h-7 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,qf=e=>Math.round(e*1e4)/1e4;function Jf(){let{state:e,setLensGps:t,setLensIds:n}=ti(),r=e.filters.lens,i=e.activeWorkspaceName,a=r.gps?.radiusM??100,[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(r.gps?.radiusM??100),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(0),[m,h]=(0,Z.useState)(`prompt`),g=(0,Z.useRef)(null),_=(0,Z.useRef)(c);(0,Z.useEffect)(()=>{_.current=c},[c]);let v=`geolocation`in navigator&&window.isSecureContext;(0,Z.useEffect)(()=>{if(!navigator.permissions?.query)return;let e=null;return navigator.permissions.query({name:`geolocation`}).then(t=>{e=t,h(t.state===`granted`?`granted`:t.state===`denied`?`denied`:`prompt`),t.onchange=()=>h(t.state===`granted`?`granted`:t.state===`denied`?`denied`:`prompt`)}).catch(()=>{}),()=>{e&&(e.onchange=null)}},[]),(0,Z.useEffect)(()=>{if(!o||!v)return;let e=navigator.geolocation.watchPosition(e=>{let n=qf(e.coords.latitude),r=qf(e.coords.longitude);t({lat:n,lon:r,radiusM:_.current})},e=>d(e.code===e.PERMISSION_DENIED?`Location permission denied.`:e.message),{enableHighAccuracy:!0,maximumAge:15e3,timeout:2e4});return g.current=e,()=>{navigator.geolocation.clearWatch(e),g.current=null}},[o,v,f,t]);let y=e=>{s(e),d(null),e||t(null)},b=()=>{d(null),s(!0),p(e=>e+1)},x=e=>{l(e),r.gps&&t({...r.gps,radiusM:e})},S=xf(),{rateMs:C,setRateMs:w,maxDistance:T,setMaxDistance:E,error:D}=S,O=S.running&&S.consumer===`filter`,k=S.running&&S.consumer!==`filter`;Sf(O);let A=t=>{i&&S.start(t,`filter`,{workspaceRef:i,contextPath:e.activeContextPath})},j=O,M=S.snapshotSize??S.camera?.size,N=!!M&&M.height>M.width;return(0,Q.jsxs)(`div`,{className:`flex flex-col gap-4 p-3 text-sm`,children:[e.activeContextType===`context`&&(0,Q.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Point the camera at an object to find visually related content in this context. `,e.liveEnabled?`Bound devices follow your matches as you move.`:`Enable Live to show the matches on your other devices.`]}),(0,Q.jsx)(af,{}),(0,Q.jsxs)(`section`,{className:`space-y-2`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Q.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:o,disabled:!v,onChange:e=>y(e.target.checked)}),(0,Q.jsx)(it,{className:`h-4 w-4 text-muted-foreground`}),(0,Q.jsx)(`span`,{children:`Track this device’s GPS`})]}),(0,Q.jsx)(`select`,{className:Gf,value:c,onChange:e=>x(Number(e.target.value)),disabled:!o,children:Wf.map(e=>(0,Q.jsx)(`option`,{value:e.m,children:e.label},e.m))})]}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:v?m===`denied`?(0,Q.jsx)(`span`,{className:`text-destructive`,children:`Location is blocked for this site. Allow it in your browser/app settings, then retry.`}):u?(0,Q.jsxs)(`span`,{className:`text-destructive`,children:[u,` `,(0,Q.jsx)(`button`,{type:`button`,onClick:b,className:`underline hover:text-foreground`,children:`Request again`})]}):r.gps?`Showing documents within ${a>=1e3?`${a/1e3} km`:`${a} m`} of ${r.gps.lat}, ${r.gps.lon}.`:o?`Waiting for a position fix…`:`Resurface documents geotagged near your current position.`:`Needs a secure context (https or localhost) with location access.`})]}),(0,Q.jsxs)(`section`,{className:`space-y-2 border-t border-border pt-3`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[j?(0,Q.jsxs)(`button`,{type:`button`,onClick:S.stop,className:`flex h-7 items-center gap-1 rounded-md bg-destructive px-2.5 text-xs font-medium text-destructive-foreground hover:bg-destructive/90`,children:[(0,Q.jsx)(pe,{className:`h-3.5 w-3.5`}),` `,S.source===`photo`?`Close photo`:`Stop ${S.source===`camera`?`camera`:`recording`}`]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>A(`camera`),disabled:!i||k,className:`flex h-7 items-center gap-1 rounded-md bg-foreground px-2.5 text-xs font-medium text-background hover:bg-foreground/90 disabled:opacity-50`,children:[(0,Q.jsx)(re,{className:`h-3.5 w-3.5`}),` Camera`]}),(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>A(`screen`),disabled:!i||k,className:`flex h-7 items-center gap-1 rounded-md bg-foreground px-2.5 text-xs font-medium text-background hover:bg-foreground/90 disabled:opacity-50`,children:[(0,Q.jsx)(Le,{className:`h-3.5 w-3.5`}),` Desktop`]})]}),(0,Q.jsx)(Uf,{consumer:`filter`,workspaceRef:i??``,contextPath:e.activeContextPath,disabled:k,className:`flex h-7 items-center gap-1 rounded-md bg-foreground px-2.5 text-xs font-medium text-background hover:bg-foreground/90 disabled:opacity-50`}),(0,Q.jsx)(`select`,{className:Gf,value:C,onChange:e=>w(Number(e.target.value)),disabled:!i,title:`Frame rate. High rates (10–30 fps) are experimental; the loop never overlaps requests, so the effective rate is capped by search latency.`,children:Af.map(e=>(0,Q.jsx)(`option`,{value:e.ms,children:e.label},e.ms))}),(0,Q.jsx)(`input`,{className:G(Kf,`w-24`),placeholder:`max dist`,inputMode:`decimal`,value:T,onChange:e=>E(e.target.value),title:`Cosine-distance floor (0 = identical). Empty = top-K (loose but tunable).`})]}),(0,Q.jsxs)(`div`,{className:G(`relative overflow-hidden rounded-lg border border-border bg-black/80`,j?N?`aspect-[3/4] max-h-[60vh]`:`aspect-video`:`hidden`),children:[(0,Q.jsx)(Ff,{className:`h-full w-full`,interactive:!0}),(0,Q.jsx)(Vf,{})]}),j&&(0,Q.jsx)(Bf,{}),(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:D?(0,Q.jsx)(`span`,{className:`text-destructive`,children:D}):j?S.snapshot?`Snapshot: view narrowed to ${S.lastCount??`…`} match${S.lastCount===1?``:`es`}. The photo is not stored. Tap Live to resume the feed.`:`Live: view narrowed to ${S.lastCount??`…`} match${S.lastCount===1?``:`es`}. Tap the shutter to search one still frame. Frames are ephemeral, never stored. Closing the toolbox keeps it running.`:k?`The Lens applet is using the camera. Stop it there first.`:r.ids===null?i?`Point a camera (or share a screen). The view narrows to what the feed matches.`:`Open a workspace to refine with a live feed.`:`The current view holds ${r.ids.length} camera match${r.ids.length===1?``:`es`}. Save to keep this view, or clear matches to remove the camera filter.`}),!j&&r.ids!==null&&(0,Q.jsx)(`button`,{type:`button`,onClick:()=>n(null),className:`min-h-10 rounded-md border border-border px-3 text-xs hover:bg-muted`,children:`Clear matches`})]})]})}var Yf={"crud:created":`var(--data-5)`,"crud:updated":`var(--data-8)`,"crud:deleted":`var(--data-3)`,content:`var(--data-10)`,tasks:`var(--data-1)`};function Xf(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return(t%360+360)%360}function Zf(e){return Yf[e]??`oklch(var(--data-l) var(--data-c) ${Xf(e)})`}var Qf=[{label:`Day`,cells:[`yesterday`,`today`,`tomorrow`]},{label:`Week`,cells:[`lastWeek`,`thisWeek`,`nextWeek`]},{label:`Month`,cells:[`lastMonth`,`thisMonth`,`nextMonth`]},{label:`Year`,cells:[`lastYear`,`thisYear`,`nextYear`]}],$f=[{label:`Decade`,cells:[`lastDecade`,`thisDecade`,`nextDecade`]},{label:`Century`,cells:[`lastCentury`,`thisCentury`,`nextCentury`]},{label:`Millennium`,cells:[`lastMillennium`,`thisMillennium`,`nextMillennium`]}],ep=[`Yesterday`,`Today`,`Tomorrow`],tp=[{label:`Millennium`,unit:`millennium`},{label:`Century`,unit:`century`},{label:`Decade`,unit:`decade`},{label:`Year`,unit:`year`},{label:`Month`,unit:`month`},{label:`Week`,unit:`week`}],np=10,rp=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function ip(e,t){let n=new Date;switch(e){case`millennium`:{let e=Math.floor(n.getFullYear()/1e3)*1e3;return new Date(e-t*1e3,0,1)}case`century`:{let e=Math.floor(n.getFullYear()/100)*100;return new Date(e-t*100,0,1)}case`decade`:{let e=Math.floor(n.getFullYear()/10)*10;return new Date(e-t*10,0,1)}case`year`:return new Date(n.getFullYear()-t,0,1);case`month`:return new Date(n.getFullYear(),n.getMonth()-t,1);case`week`:{let e=(n.getDay()+6)%7,r=new Date(n.getFullYear(),n.getMonth(),n.getDate()-e);return r.setDate(r.getDate()-t*7),r}}}function ap(e,t){let n=new Date(t);switch(e){case`millennium`:n.setFullYear(n.getFullYear()+1e3);break;case`century`:n.setFullYear(n.getFullYear()+100);break;case`decade`:n.setFullYear(n.getFullYear()+10);break;case`year`:n.setFullYear(n.getFullYear()+1);break;case`month`:n.setMonth(n.getMonth()+1);break;case`week`:n.setDate(n.getDate()+7)}return n}function op(e,t,n){if(n===0)return`Now`;switch(e){case`millennium`:case`century`:case`decade`:{let e=t.getFullYear();return e<=0?`${1-e} BCE`:`${e}`}case`year`:return`${t.getFullYear()}`;case`month`:return`${rp[t.getMonth()]} ${t.getFullYear()}`;case`week`:{let e=new Date(t);return e.setDate(e.getDate()+6),`${t.getDate()} ${rp[t.getMonth()]} – ${e.getDate()} ${rp[e.getMonth()]}`}}}function sp(e,t){return Array.from({length:t},(t,n)=>{let r=ip(e,n),i=ap(e,r);return{offset:n,label:op(e,r,n),start:r,end:i,isNow:n===0}})}var cp={yesterday:5,today:5,tomorrow:5,lastWeek:5,thisWeek:5,nextWeek:5,lastMonth:4,thisMonth:4,nextMonth:4,lastYear:3,thisYear:3,nextYear:3,lastDecade:2,thisDecade:2,nextDecade:2,lastCentury:1,thisCentury:1,nextCentury:1,lastMillennium:0,thisMillennium:0,nextMillennium:0};function lp(e){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function up(e,t){let n=hp(e);return n?(n.setDate(n.getDate()+t),lp(n)):e}function dp(e){let t=[...e].sort((e,t)=>e.start.localeCompare(t.start)),n=[];for(let e of t){let t=n[n.length-1];t&&e.start<=up(t.end,1)?e.end>t.end&&(t.end=e.end):n.push({...e})}return n}function fp(e,t){let n=e.find(e=>t>=e.start&&t<=e.end);if(!n)return dp([...e,{start:t,end:t}]);let r=e.filter(e=>e!==n);return n.start<=up(t,-1)&&r.push({start:n.start,end:up(t,-1)}),up(t,1)<=n.end&&r.push({start:up(t,1),end:n.end}),r.sort((e,t)=>e.start.localeCompare(t.start))}function pp(e,t){if(e===`week`||e===`month`){let e=new Date(t.end);return e.setDate(e.getDate()-1),{start:lp(t.start),end:lp(e)}}return{start:String(t.start.getFullYear()),end:String(t.end.getFullYear()-1)}}function mp({quickFilterKey:e,activeRangeCount:t,onSelectRanges:n,histogramNames:r}){let{state:i}=ti(),{activeWorkspaceName:a,activeTreeName:o,activeContextPath:s,filters:c}=i,[l,u]=(0,Z.useState)(3),[d,f]=(0,Z.useState)(np),[p,m]=(0,Z.useState)(new Set),[h,g]=(0,Z.useState)([]),[_,v]=(0,Z.useState)(e);e!==_&&(v(e),e&&cp[e]!==void 0&&u(cp[e]),m(new Set));let[y,b]=(0,Z.useState)(t);t!==y&&(b(t),t===0&&m(new Set));let x=tp[l],S=sp(x.unit,d),C=JSON.stringify(c.features)+JSON.stringify(c.geo),w=r.join(`,`);(0,Z.useEffect)(()=>{if(!a||r.length===0)return;let e=!1,t=setTimeout(()=>{kn(a,{names:r,buckets:sp(x.unit,d).map(e=>pp(x.unit,e)),context:s??`/`,...o?{treeNameOrTreeId:o}:{},allOf:c.features.allOf,anyOf:c.features.anyOf,noneOf:c.features.noneOf,filters:Xi(c.geo),applyCanvasSpec:!1}).then(t=>{e||g(t)}).catch(()=>{e||g([])})},250);return()=>{e=!0,clearTimeout(t)}},[a,o,s,x.unit,d,w,C]);let T=a&&r.length>0?h:[],E=Math.max(1,...T.map(e=>e.total)),D=e=>{u(t=>Math.max(0,Math.min(5,t+e))),f(np),m(new Set)},O=(0,Z.useCallback)((e,t)=>{m(r=>{let i;if(t&&r.size>0){let t=Math.min(e,...r),n=Math.max(e,...r);i=new Set(r);for(let e=t;e<=n;e++)i.add(e)}else i=new Set(r),i.has(e)?i.delete(e):i.add(e);let a=[...i].sort((e,t)=>e-t),o=[];for(let e of a){let t=o[o.length-1];t&&e===t[1]+1?t[1]=e:o.push([e,e])}return n(o.map(([e,t])=>{let n=S.find(e=>e.offset===t).start,r=new Date(S.find(t=>t.offset===e).end);return r.setDate(r.getDate()-1),{start:lp(n),end:lp(r)}})),i})},[S,n]);return(0,Q.jsxs)(`div`,{className:`w-48 shrink-0 flex flex-col border-r border-border bg-muted/20`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-1 px-2 py-1.5 border-b border-border shrink-0`,children:[(0,Q.jsx)(`span`,{className:`text-[11px] font-semibold text-foreground/80 select-none`,children:x.label}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,Q.jsx)(`button`,{type:`button`,onClick:()=>D(1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Zoom in (finer periods)`,children:(0,Q.jsx)(F,{className:`w-3.5 h-3.5`})}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>D(-1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Zoom out (coarser periods)`,children:(0,Q.jsx)(he,{className:`w-3.5 h-3.5`})})]})]}),(0,Q.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto p-1.5 space-y-1 touch-target`,children:[S.map(e=>{let t=p.has(e.offset),n=T[e.offset],r=n?.total??0,i=r>0?Math.log1p(r)/Math.log1p(E):0,a=n&&r>0?`: ${r} doc${r===1?``:`s`} (${Object.entries(n.counts).map(([e,t])=>`${e}: ${t}`).join(`, `)})`:``;return(0,Q.jsxs)(`button`,{type:`button`,onClick:t=>O(e.offset,t.shiftKey),title:`${e.isNow?`Now`:e.label}${a}. Click to tag, shift-click to fill range`,className:G(`w-full flex items-center gap-2 rounded-2xl px-3 py-1.5 text-xs font-medium transition-colors select-none text-left`,t?`bg-primary text-primary-foreground`:e.isNow?`bg-primary/10 text-primary hover:bg-primary/20`:`bg-card text-foreground hover:bg-muted shadow-elevation-1`),children:[e.isNow&&(0,Q.jsx)(ht,{className:`w-3 h-3 shrink-0`}),(0,Q.jsxs)(`span`,{className:`flex-1 min-w-0 flex flex-col`,children:[(0,Q.jsxs)(`span`,{className:`flex items-baseline justify-between gap-1`,children:[(0,Q.jsx)(`span`,{className:`truncate`,children:e.label}),r>0&&(0,Q.jsx)(`span`,{className:G(`text-[9px] tabular-nums shrink-0`,t?`text-primary-foreground/80`:`text-muted-foreground/70`),children:r})]}),r>0&&(0,Q.jsx)(`span`,{className:`mt-1 flex h-[3px] overflow-hidden rounded-full`,style:{width:`${Math.max(8,i*100)}%`},children:Object.entries(n.counts).map(([e,t])=>(0,Q.jsx)(`span`,{style:{width:`${t/r*100}%`,backgroundColor:Zf(e)}},e))})]})]},e.offset)}),d<200&&(0,Q.jsx)(`button`,{type:`button`,onClick:()=>f(e=>e+np),className:`w-full text-[11px] text-muted-foreground/60 hover:text-muted-foreground py-1.5 transition-colors text-center`,children:`Show older…`})]})]})}function hp(e){let t=/^(-?\d{1,6})-(\d{2})-(\d{2})$/.exec(e);return t?new Date(Number(t[1]),Number(t[2])-1,Number(t[3])):null}function gp({ranges:e,onCommitRange:t,onToggleDay:n}){let r=new Date,[i,a]=(0,Z.useState)(()=>{let t=e[0]?.start&&hp(e[0].start)||r;return{y:t.getFullYear(),m:t.getMonth()}}),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(null),u=e=>a(t=>{let n=new Date(t.y,t.m+e,1);return{y:n.getFullYear(),m:n.getMonth()}}),d=(e,r)=>{if(r){n(e),s(null),l(null);return}if(!o){s(e);return}let[i,a]=o<=e?[o,e]:[e,o];t(i,a),s(null),l(null)},f=new Date(i.y,i.m,1),p=new Date(f);p.setDate(p.getDate()-(f.getDay()+6)%7);let m=Array.from({length:42},(e,t)=>{let n=new Date(p);return n.setDate(n.getDate()+t),n}),[h,g]=o?c&&c!==o?o<=c?[o,c]:[c,o]:[o,o]:[null,null],_=t=>e.some(e=>t>=e.start&&t<=e.end),v=t=>e.some(e=>t===e.start||t===e.end),y=lp(r);return(0,Q.jsxs)(`div`,{className:`select-none`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between mb-1.5`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center`,children:[(0,Q.jsx)(`button`,{type:`button`,onClick:()=>u(-12),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Previous year`,children:(0,Q.jsx)(j,{className:`w-3.5 h-3.5`})}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>u(-1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Previous month`,children:(0,Q.jsx)(oe,{className:`w-3.5 h-3.5`})})]}),(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>a({y:r.getFullYear(),m:r.getMonth()}),className:`text-xs font-semibold text-foreground hover:text-primary transition-colors`,title:`Jump to current month`,children:[rp[i.m],` `,i.y]}),(0,Q.jsxs)(`div`,{className:`flex items-center`,children:[(0,Q.jsx)(`button`,{type:`button`,onClick:()=>u(1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Next month`,children:(0,Q.jsx)(Me,{className:`w-3.5 h-3.5`})}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>u(12),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Next year`,children:(0,Q.jsx)(Xt,{className:`w-3.5 h-3.5`})})]})]}),(0,Q.jsx)(`div`,{className:`grid grid-cols-7 mb-0.5`,children:[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`].map(e=>(0,Q.jsx)(`span`,{className:`text-center text-[9px] font-semibold uppercase text-muted-foreground/60 py-0.5`,children:e},e))}),(0,Q.jsx)(`div`,{className:`grid grid-cols-7 gap-y-0.5`,children:m.map(e=>{let t=lp(e),n=e.getMonth()===i.m,r=h!==null&&g!==null&&t>=h&&t<=g,a=t===h||t===g,s=!o&&_(t),c=a||s&&v(t);return(0,Q.jsx)(`button`,{type:`button`,onClick:e=>d(t,e.ctrlKey||e.metaKey),onMouseEnter:()=>o&&l(t),className:G(`h-6 text-[11px] tabular-nums transition-colors`,c?`bg-primary text-primary-foreground rounded-md`:r||s?`bg-primary/15 text-foreground`:n?`text-foreground hover:bg-muted rounded-md`:`text-muted-foreground/40 hover:bg-muted rounded-md`,t===y&&!c&&`font-bold text-primary`),children:e.getDate()},t)})}),(0,Q.jsx)(`p`,{className:`mt-1.5 text-[10px] text-muted-foreground/70`,children:o?`From ${o}: pick the end date`:`Click start + end. Ctrl+click adds/removes single days.`})]})}function _p({label:e,checked:t,onChange:n,color:r}){return(0,Q.jsxs)(`div`,{role:`switch`,"aria-checked":t,tabIndex:0,onClick:()=>n(!t),onKeyDown:e=>(e.key===` `||e.key===`Enter`)&&n(!t),className:`flex items-center justify-between gap-3 cursor-pointer select-none outline-none focus-visible:ring-2 focus-visible:ring-ring rounded`,children:[(0,Q.jsxs)(`span`,{className:`flex items-center gap-2 min-w-0`,children:[(0,Q.jsx)(`span`,{className:`w-2 h-2 rounded-full shrink-0`,style:{backgroundColor:r}}),(0,Q.jsx)(`span`,{className:`text-sm text-foreground truncate`,children:e})]}),(0,Q.jsx)(`div`,{className:G(`relative w-10 h-5 rounded-full transition-colors shrink-0`,!t&&`bg-accent dark:bg-muted-foreground`),style:t?{backgroundColor:r}:void 0,children:(0,Q.jsx)(`div`,{className:G(`absolute top-[2px] w-4 h-4 rounded-full bg-background shadow-elevation-1 transition-transform`,t?`translate-x-[22px]`:`translate-x-[2px]`)})})]})}function vp(){let{state:e,setTimelineFilter:t,createTimeline:n,deleteTimeline:r,refreshTimelines:i}=ti(),{timeline:a}=e.filters,{availableTimelines:o,timelineScales:s,timelinesLoading:c}=e,[l,u]=(0,Z.useState)(``),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(`quick`),[_,v]=(0,Z.useState)(!1),{showToast:y}=xn(),b=new Set(a.selectedTimelines??[]),x=(0,Z.useMemo)(()=>{let e=[];return a.indexCreated&&e.push(`crud:created`),a.indexUpdated&&e.push(`crud:updated`),a.indexDeleted&&e.push(`crud:deleted`),a.contentEvents&&e.push(`content`),e.push(...a.selectedTimelines??[]),e.length>0?e:[`crud:created`]},[a.indexCreated,a.indexUpdated,a.indexDeleted,a.contentEvents,a.selectedTimelines]),S=e=>{let n=new Set(b);n.has(e)?n.delete(e):n.add(e),t({selectedTimelines:[...n]})},C=async()=>{let e=l.trim();if(e){f(!0);try{await n(e),u(``),y({title:`Timeline created`,description:e})}catch(e){y({title:`Failed to create timeline`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{f(!1)}}},w=async e=>{if(window.confirm(`Delete timeline "${e}"?\n\nThis removes all interval data for this timeline.`)){m(e);try{await r(e),y({title:`Timeline deleted`,description:e})}catch(e){y({title:`Failed to delete timeline`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{m(null)}}},T=o.filter(e=>!e.startsWith(`crud:`)&&e!==`content`),E=ta(a),D=E.length>0,O=(0,Z.useCallback)(e=>{t({customRanges:e,customRange:null,...e.length>0?{quickFilter:null}:{}})},[t]),k=e=>{t({quickFilter:a.quickFilter===e?null:e,customRanges:[],customRange:null})},A=e=>{t({customRanges:E.filter((t,n)=>n!==e),customRange:null})},j=(e,t)=>(0,Q.jsxs)(`div`,{className:`grid grid-cols-[3.5rem_1fr_1fr_1fr] gap-1 items-center`,children:[(0,Q.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:e.label}),e.cells.map((e,n)=>{let r=a.quickFilter===e&&!D;return(0,Q.jsx)(`button`,{type:`button`,onClick:()=>k(e),className:G(`text-xs px-1.5 py-1 rounded-md transition-colors truncate`,r?`bg-primary text-primary-foreground font-medium`:`bg-muted/50 text-foreground hover:bg-muted`),title:e,children:t?ep[n]:[`Last`,`This`,`Next`][n]},e)})]},e.label);return(0,Q.jsxs)(`div`,{className:`flex h-full min-h-0`,children:[(0,Q.jsx)(mp,{quickFilterKey:a.quickFilter,activeRangeCount:E.length,onSelectRanges:O,histogramNames:x}),(0,Q.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4 space-y-5`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,Q.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:h===`quick`?`Quick filter`:`Date range`}),(0,Q.jsxs)(`div`,{className:`flex rounded-md overflow-hidden border border-border divide-x divide-border`,children:[(0,Q.jsx)(`button`,{type:`button`,onClick:()=>g(`quick`),className:G(`px-2 py-0.5 transition-colors`,h===`quick`?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Quick filters`,children:(0,Q.jsx)(L,{className:`w-3 h-3`})}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>g(`calendar`),className:G(`px-2 py-0.5 transition-colors`,h===`calendar`?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Calendar range picker`,children:(0,Q.jsx)(de,{className:`w-3 h-3`})})]})]}),h===`quick`?(0,Q.jsxs)(`div`,{className:`space-y-1`,children:[(0,Q.jsxs)(`div`,{className:`grid grid-cols-[3.5rem_1fr_1fr_1fr] gap-1`,children:[(0,Q.jsx)(`span`,{}),[`Last`,`This`,`Next`].map(e=>(0,Q.jsx)(`span`,{className:`text-center text-[9px] font-semibold uppercase tracking-wide text-muted-foreground/60`,children:e},e))]}),Qf.map((e,t)=>j(e,t===0)),(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>v(e=>!e),className:`flex items-center gap-1 text-[11px] text-muted-foreground/70 hover:text-muted-foreground pt-1 transition-colors`,children:[(0,Q.jsx)(ke,{className:G(`w-3 h-3 transition-transform`,!_&&`-rotate-90`)}),`Deep time`]}),_&&$f.map(e=>j(e,!1))]}):(0,Q.jsx)(gp,{ranges:E,onCommitRange:(e,n)=>t({customRanges:[{start:e,end:n}],customRange:null,quickFilter:null}),onToggleDay:e=>t({customRanges:fp(E,e),customRange:null,quickFilter:null})}),D&&(0,Q.jsx)(`div`,{className:`mt-2 space-y-1`,children:E.map((e,t)=>(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded-md bg-primary/10 border border-primary/30 px-2.5 py-1.5`,children:[(0,Q.jsx)(`span`,{className:`text-xs text-foreground truncate`,children:e.start===e.end?e.start:`${e.start} → ${e.end}`}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>A(t),className:`text-muted-foreground hover:text-foreground shrink-0`,title:`Remove range`,children:(0,Q.jsx)(z,{className:`w-3.5 h-3.5`})})]},`${e.start}..${e.end}`))})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:`Apply to`}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(_p,{label:`crud:created`,checked:a.indexCreated,onChange:e=>t({indexCreated:e}),color:Zf(`crud:created`)}),(0,Q.jsx)(_p,{label:`crud:updated`,checked:a.indexUpdated,onChange:e=>t({indexUpdated:e}),color:Zf(`crud:updated`)}),(0,Q.jsx)(_p,{label:`crud:deleted`,checked:a.indexDeleted,onChange:e=>t({indexDeleted:e}),color:Zf(`crud:deleted`)}),(0,Q.jsx)(_p,{label:`content`,checked:a.contentEvents,onChange:e=>t({contentEvents:e}),color:Zf(`content`)})]}),(0,Q.jsx)(`p`,{className:`text-[10px] text-muted-foreground/70 mt-1`,children:`content = content-derived timestamps (EXIF, logs, extracted periods)`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,Q.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:`Domain timelines`}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>i(),className:`text-muted-foreground/60 hover:text-muted-foreground transition-colors`,title:`Refresh timelines`,children:(0,Q.jsx)(gt,{className:`w-3 h-3`})})]}),c?(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 py-2 text-xs text-muted-foreground`,children:[(0,Q.jsx)(Et,{className:`w-3 h-3 animate-spin`}),`Loading…`]}):T.length===0?(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground py-1`,children:`No domain timelines yet`}):(0,Q.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:T.map(e=>{let t=b.has(e),n=Zf(e);return(0,Q.jsxs)(`div`,{className:G(`flex items-center gap-2.5 group rounded-md px-2 py-1.5 cursor-pointer transition-colors`,t?`bg-muted/60`:`hover:bg-muted/30`),onClick:()=>S(e),children:[(0,Q.jsx)(`div`,{className:G(`shrink-0 w-4 h-4 rounded border-2 flex items-center justify-center transition-colors`,!t&&`border-muted-foreground/40 bg-transparent group-hover:border-muted-foreground/70`),style:t?{backgroundColor:n,borderColor:n}:void 0,children:t&&(0,Q.jsx)(`svg`,{className:G(`w-2.5 h-2.5`,Ci(n)),viewBox:`0 0 10 10`,fill:`none`,children:(0,Q.jsx)(`path`,{d:`M2 5l2.5 2.5L8 3`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),(0,Q.jsx)(`span`,{className:`flex-1 text-sm text-foreground truncate select-none`,children:e}),(s[e]?.length??0)>0&&(0,Q.jsx)(`span`,{className:`shrink-0 text-[10px] px-1 py-0.5 rounded bg-muted text-muted-foreground select-none`,title:`Observed granularity for "${e}" — each entry is indexed at its own precision (a bare year at year cells, a full date at day cells)`,children:(s[e]??[]).join(`·`)}),(0,Q.jsx)(`button`,{type:`button`,disabled:p===e,onClick:t=>{t.stopPropagation(),w(e)},className:`shrink-0 p-1 rounded text-muted-foreground/40 hover:text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-50 reveal-on-hover`,title:`Delete timeline "${e}"`,children:p===e?(0,Q.jsx)(Et,{className:`w-3 h-3 animate-spin`}):(0,Q.jsx)(W,{className:`w-3 h-3`})})]},e)})}),(0,Q.jsxs)(`div`,{className:`mt-3 flex gap-1.5`,children:[(0,Q.jsx)(`input`,{type:`text`,value:l,onChange:e=>u(e.target.value),onKeyDown:e=>e.key===`Enter`&&C(),placeholder:`New timeline (e.g. wikipedia, trips)…`,title:`A timeline is a named time axis. Entries index at their own precision — a bare year at year granularity, a full date at day granularity — nothing to configure.`,className:`flex-1 px-2 py-1 text-xs rounded-md bg-muted border border-transparent focus:border-ring focus:outline-none`}),(0,Q.jsx)(`button`,{type:`button`,onClick:C,disabled:d||!l.trim(),className:`shrink-0 p-1.5 rounded-md bg-muted hover:bg-muted/80 text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50 touch-target`,title:`Create timeline`,children:d?(0,Q.jsx)(Et,{className:`w-3.5 h-3.5 animate-spin`}):(0,Q.jsx)(ge,{className:`w-3.5 h-3.5`})})]})]})]})]})}var yp={data:`Data`,"data/backend":`Backends`,"data/mime":`MIME types`,"data/dataset":`Datasets`,client:`Client`,tag:`Tags`,device:`Device`,custom:`Custom`,feature:`Feature`},bp=`data/dataset/default`;function xp(e){let t=new Map;for(let n of e){let e=n.startsWith(`data/backend/`)?`data/backend`:n.startsWith(`data/mime/`)?`data/mime`:n.startsWith(`data/dataset/`)?`data/dataset`:n.split(`/`)[0];t.has(e)||t.set(e,[]),t.get(e).push(n)}return t}var Sp=[`off`,`anyOf`,`allOf`,`noneOf`];function Cp(e){return Sp[(Sp.indexOf(e)+1)%Sp.length]}var wp=[{m:`anyOf`,label:`any`,on:`bg-info text-info-foreground`},{m:`allOf`,label:`all`,on:`bg-success text-success-foreground`},{m:`noneOf`,label:`not`,on:`bg-destructive text-destructive-foreground`}];function Tp({mode:e,onSet:t}){return(0,Q.jsx)(`div`,{className:`flex shrink-0 rounded-md overflow-hidden border border-border divide-x divide-border`,children:wp.map(n=>(0,Q.jsx)(`button`,{type:`button`,onClick:()=>t(e===n.m?`off`:n.m),className:G(`px-2 py-0.5 text-[11px] font-medium transition-colors`,e===n.m?n.on:`bg-transparent text-muted-foreground hover:bg-muted hover:text-foreground`),title:`${n.label}: ${n.m}`,children:n.label},n.m))})}function Ep({keys:e,modeOf:t,onCycle:n}){return e.length?(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:`Document types`}),(0,Q.jsx)(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3`,children:e.map(e=>{let{label:r,icon:i}=cd(e),a=t(e),o=wp.find(e=>e.m===a);return(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>n(e),title:`${e}: ${a===`off`?`tap to filter`:a}`,className:G(`relative flex flex-col items-center justify-center gap-1.5 rounded-(--card-radius) border p-3 min-h-[4.5rem] transition-colors select-none`,a===`off`?`border-border bg-muted/40 text-foreground hover:bg-muted`:a===`anyOf`?`border-info bg-info/10 text-foreground`:a===`allOf`?`border-success bg-success/10 text-foreground`:`border-destructive bg-destructive/10 text-foreground`),children:[o&&(0,Q.jsx)(`span`,{className:G(`absolute right-1.5 top-1.5 rounded px-1 py-0.5 text-[9px] font-semibold leading-none`,o.on),children:o.label}),(0,Q.jsx)(i,{className:`h-5 w-5 text-muted-foreground`}),(0,Q.jsx)(`span`,{className:`text-xs font-medium leading-none`,children:r})]},e)})})]}):null}function Dp(){let{state:e,setFeatureMode:t,clearFilters:n,hasActiveFilters:r,deleteBitmap:i,deleteDataset:a}=ti(),{availableBitmaps:o,bitmapsLoading:s,filters:c}=e,l=new Set(c.features.allOf),u=new Set(c.features.anyOf),d=new Set(c.features.noneOf),f=e=>l.has(e)?`allOf`:u.has(e)?`anyOf`:d.has(e)?`noneOf`:`off`,[p,m]=(0,Z.useState)(``),[h,g]=(0,Z.useState)(null),{showToast:_}=xn(),v=async e=>{if(e.startsWith(`data/dataset/`)&&e!==bp){let t=e.slice(13);if(!window.confirm(`Drop dataset "${t}"?\n\nALL documents stamped with this dataset will be PERMANENTLY DELETED. Documents in other datasets (or the default dataset) are unaffected. Re-ingesting recreates the dataset from scratch.`))return;g(e);try{let n=await a(e);_({title:`Dataset dropped`,description:`"${t}": ${n} document(s) deleted`})}catch(e){_({title:`Dataset drop failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{g(null)}return}if(!e.startsWith(`data/`)&&window.confirm(`Delete bitmap "${e}"?\n\nThis removes the bitmap from the database. Documents are unaffected, but any features/filters relying on this bitmap will lose their grouping.`)){g(e);try{await i(e),_({title:`Bitmap deleted`,description:e})}catch(e){_({title:`Delete failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{g(null)}}};if(s)return(0,Q.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,Q.jsx)(Et,{className:`w-4 h-4 animate-spin text-muted-foreground`})});let y=[...c.features.allOf,...c.features.anyOf,...c.features.noneOf],b=[...new Set([...o,...y])];if(!b.length)return(0,Q.jsx)(`div`,{className:`p-4 text-xs text-muted-foreground text-center py-10`,children:`No feature bitmaps found`});let x=p.trim().toLowerCase(),S=x?b.filter(e=>e.toLowerCase().includes(x)):b,C=S.filter(e=>e.startsWith(od)).sort((e,t)=>{let n=Object.keys(sd),r=n.indexOf(e),i=n.indexOf(t);return(r===-1?n.length:r)-(i===-1?n.length:i)||e.localeCompare(t)}),w=xp(S.filter(e=>!e.startsWith(od))),T=w.get(`data/dataset`);return T&&!T.includes(bp)&&(!x||bp.includes(x))&&T.unshift(bp),(0,Q.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,Q.jsxs)(`div`,{className:`px-4 py-2 border-b border-border shrink-0 space-y-2`,children:[(0,Q.jsxs)(`div`,{className:`relative`,children:[(0,Q.jsx)(Jt,{className:`absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none`}),(0,Q.jsx)(`input`,{type:`text`,value:p,onChange:e=>m(e.target.value),placeholder:`Search features…`,className:`w-full pl-7 pr-3 py-1.5 text-xs rounded-md bg-muted border border-transparent focus:border-ring focus:outline-none`})]}),(0,Q.jsxs)(`button`,{type:`button`,onClick:n,disabled:!r,className:`flex items-center gap-1.5 w-full justify-center px-2.5 py-1.5 text-xs rounded-md border border-border text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-40 disabled:hover:bg-transparent`,children:[(0,Q.jsx)(z,{className:`w-3 h-3`}),`Clear all filters`]})]}),(0,Q.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto p-4 space-y-5`,children:[(0,Q.jsx)(Ep,{keys:C,modeOf:f,onCycle:e=>t(e,Cp(f(e)))}),w.size===0&&C.length===0?(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground text-center py-6`,children:`No matches`}):Array.from(w.entries()).map(([e,n])=>(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:yp[e]??e}),(0,Q.jsx)(`div`,{className:`flex flex-col gap-1`,children:n.map((e,n)=>{let r=e.startsWith(`data/`),i=e===bp,a=e.startsWith(`data/dataset/`)&&!i,o=f(e);return(0,Q.jsxs)(`div`,{onClick:()=>t(e,Cp(o)),role:`button`,tabIndex:0,onKeyDown:n=>{(n.key===`Enter`||n.key===` `)&&(n.preventDefault(),t(e,Cp(o)))},className:G(`flex items-center gap-2 group rounded-md pl-2 pr-1.5 py-1 border-l-2 transition-colors cursor-pointer select-none`,n%2==0?`bg-muted/50`:`bg-transparent`,`hover:bg-muted`,o===`off`?`border-l-transparent`:o===`anyOf`?`border-l-blue-500 !bg-info/10`:o===`allOf`?`border-l-emerald-500 !bg-success/10`:`border-l-rose-500 !bg-destructive/10`),children:[(0,Q.jsxs)(`span`,{className:`flex-1 min-w-0 text-xs font-mono text-foreground truncate`,title:i?`Virtual dataset: documents not stamped with any dataset. Included by default; "not" hides them, "all" shows only them.`:e,children:[e,i&&(0,Q.jsx)(`span`,{className:`ml-1.5 text-[10px] text-muted-foreground font-sans`,children:`virtual · on by default`})]}),(0,Q.jsx)(`span`,{onClick:e=>e.stopPropagation(),children:(0,Q.jsx)(Tp,{mode:o,onSet:n=>t(e,n)})}),(!r||a)&&(0,Q.jsx)(`button`,{type:`button`,disabled:h===e,onClick:t=>{t.stopPropagation(),v(e)},className:`shrink-0 p-1 rounded text-muted-foreground/40 hover:text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-50 reveal-on-hover`,title:a?`Drop dataset "${e.slice(13)}" (DELETES its documents)`:`Delete bitmap "${e}" from database`,"aria-label":a?`Drop dataset ${e}`:`Delete bitmap ${e}`,children:h===e?(0,Q.jsx)(Et,{className:`w-3.5 h-3.5 animate-spin`}):(0,Q.jsx)(W,{className:`w-3.5 h-3.5`})})]},e)})})]},e))]})]})}function Op(){let{state:e,setToolsTab:t,saveFilters:n,clearFilters:r,hasActiveFilters:i,setLiveEnabled:a}=ti(),{toolsTab:o,isDirty:s,isSaving:c,activeContextType:l,savedSearchQuery:u}=e,d=h(),f=(new URLSearchParams(d.search).has(`q`)||new URLSearchParams(d.search).has(`search`)?rf(d.search):u?[u]:[])[0]||``,p=l!==null&&f.trim()!==(u||``),m=e.filters.sort??na.sort,g=m.sortBy!==na.sort.sortBy||m.order!==na.sort.order,_=i||!!f.trim()||g,v=(0,Q.jsxs)(Q.Fragment,{children:[_&&(0,Q.jsxs)(`button`,{type:`button`,onClick:r,title:`Clear all active filters`,className:`flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,Q.jsx)(z,{className:`h-3 w-3`}),`Clear`]}),l!==null&&_&&(s||p)&&(0,Q.jsxs)(`button`,{type:`button`,onClick:n,disabled:c,className:`flex items-center gap-1.5 rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground transition-colors hover:bg-primary disabled:opacity-60`,children:[c?(0,Q.jsx)(Et,{className:`h-3 w-3 animate-spin`}):(0,Q.jsx)(ee,{className:`h-3 w-3`}),`Save filters`]})]});return(0,Q.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Q.jsx)(`div`,{className:`flex border-b border-border shrink-0`,children:[{id:`features`,label:`Features`},{id:`timeline`,label:`Timeline`},{id:`map`,label:`Map`},{id:`lens`,label:`Lens`}].map(e=>(0,Q.jsx)(`button`,{type:`button`,onClick:()=>t(e.id),className:G(`flex-1 py-2.5 text-xs transition-colors`,o===e.id?`-mb-px border-b-2 border-foreground font-semibold text-foreground`:`font-medium text-muted-foreground hover:text-foreground`),children:e.label},e.id))}),l===`context`&&(0,Q.jsxs)(`div`,{className:`shrink-0 space-y-1 border-b border-border px-3 py-1.5`,children:[(0,Q.jsxs)(`div`,{className:`flex min-h-8 flex-wrap items-center justify-between gap-x-3 gap-y-1`,children:[(0,Q.jsxs)(`label`,{className:`flex min-h-8 cursor-pointer items-center gap-2 text-sm font-medium`,title:`Live view updates every device bound to this context. Save filters to keep the current view.`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 accent-current`,checked:e.liveEnabled,disabled:new URLSearchParams(d.search).has(`ownerId`),onChange:e=>{a(e.target.checked)}}),`Live view`]}),(0,Q.jsx)(`div`,{className:`ml-auto flex items-center gap-2`,children:v})]}),e.liveError&&(0,Q.jsx)(`p`,{role:`status`,className:`text-xs text-destructive`,children:e.liveError})]}),l!==`context`&&_&&(0,Q.jsx)(`div`,{className:`flex items-center justify-end gap-2 border-b border-border px-3 py-1.5 shrink-0`,children:v}),(0,Q.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-hidden`,children:[o===`features`&&(0,Q.jsx)(Dp,{}),o===`timeline`&&(0,Q.jsx)(vp,{}),o===`map`&&(0,Q.jsx)(yf,{}),o===`lens`&&(0,Q.jsx)(Jf,{})]})]})}function kp({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`:e===`starting`||e===`stopping`?`bg-warning`:`bg-muted-foreground`),title:e})}function Ap(){let{openAgentT2:e}=ti(),{setSection:t}=la(),n=m(),{agents:r,isLoading:i,refresh:a}=Lu(!0),{showToast:o}=xn(),[s,c]=(0,Z.useState)(new Set),l=(e,t)=>c(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r}),u=async(e,t)=>{e.stopPropagation(),l(t.id,!0);try{await Ou(t.id),a()}catch(e){o({title:`Error`,description:e instanceof Error?e.message:`Failed`,variant:`destructive`})}finally{l(t.id,!1)}},d=async(e,t)=>{e.stopPropagation(),l(t.id,!0);try{await ku(t.id),a()}catch(e){o({title:`Error`,description:e instanceof Error?e.message:`Failed`,variant:`destructive`})}finally{l(t.id,!1)}};return(0,Q.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Q.jsx)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:(0,Q.jsx)(`span`,{className:`text-sm font-semibold`,children:`Agents`})}),(0,Q.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:i&&r.length===0?(0,Q.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading…`}):r.length===0?(0,Q.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-12 text-muted-foreground`,children:[(0,Q.jsx)(ye,{className:`w-8 h-8 opacity-30`}),(0,Q.jsx)(`span`,{className:`text-xs`,children:`No agents yet`}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>{t(`agents`),n(`/agents?create=1`)},className:`text-xs text-primary hover:underline`,children:`Create an agent`})]}):(0,Q.jsx)(`div`,{className:`space-y-1 px-2`,children:r.map(t=>{let n=s.has(t.id);return(0,Q.jsxs)(`div`,{className:`group relative px-3 py-2.5 cursor-pointer transition-colors bg-card hover:bg-accent/50`,style:{borderLeft:`6px solid ${t.color||`transparent`}`},onClick:()=>e(t.id),children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(kp,{status:t.status}),(0,Q.jsx)(`span`,{className:`text-sm font-medium flex-1 truncate`,children:t.label||t.name}),(0,Q.jsx)(`div`,{className:`flex items-center gap-0.5 shrink-0 reveal-on-hover`,children:t.status===`active`?(0,Q.jsx)(`button`,{type:`button`,disabled:n,onClick:e=>d(e,t),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50`,title:`Stop`,children:(0,Q.jsx)(Ot,{className:`w-3 h-3`})}):(0,Q.jsx)(`button`,{type:`button`,disabled:n,onClick:e=>u(e,t),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50`,title:`Start`,children:(0,Q.jsx)(le,{className:`w-3 h-3`})})})]}),t.description&&(0,Q.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-4`,children:t.description})]},t.id)})})})]})}function jp(){let e=tf(),[t,n]=(0,Z.useState)(50),r=e?.notifications??[],i=r.slice(-t).reverse();return(0,Q.jsxs)(`section`,{"aria-label":`Notification history`,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 px-4 py-3`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`h2`,{className:`text-sm font-semibold`,children:[`Notifications`,r.length>0&&(0,Q.jsx)(`span`,{className:`ml-2 font-normal text-muted-foreground`,children:r.length})]}),(0,Q.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground`,children:`Saved on this browser`})]}),r.length>0&&(0,Q.jsxs)(K,{variant:`ghost`,size:`sm`,onClick:()=>void e?.clear(),title:`Clear all notifications`,className:`shrink-0 gap-1.5`,children:[(0,Q.jsx)(W,{className:`h-3.5 w-3.5`}),`Clear all`]})]}),e?.storageError&&(0,Q.jsx)(`p`,{role:`alert`,className:`border-b px-4 py-3 text-xs text-destructive`,children:`Couldn’t access notification history in this browser.`}),e?.loading?(0,Q.jsx)(`p`,{role:`status`,className:`p-4 text-sm text-muted-foreground`,children:`Loading notifications…`}):r.length===0?(0,Q.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center gap-3 p-8 text-center`,children:[(0,Q.jsx)(`div`,{className:`flex h-12 w-12 items-center justify-center rounded-full bg-muted`,children:(0,Q.jsx)(Ge,{className:`h-5 w-5 text-muted-foreground`})}),(0,Q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No notifications yet`})]}):(0,Q.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3`,children:[(0,Q.jsx)(`ol`,{className:`space-y-2`,children:i.map(t=>{let n=t.status===`error`?B:t.status===`completed`?te:t.status===`started`?ht:Ge;return(0,Q.jsx)(`li`,{"data-notification-id":t.id,className:`rounded-(--card-radius) border bg-card p-3`,children:(0,Q.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Q.jsx)(n,{"aria-hidden":!0,className:`mt-0.5 h-4 w-4 shrink-0 ${t.status===`error`?`text-destructive`:`text-muted-foreground`}`}),(0,Q.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Q.jsx)(`p`,{className:`break-words text-sm font-medium`,children:t.title}),t.text&&(0,Q.jsx)(`p`,{className:`mt-1 whitespace-pre-wrap break-words text-xs text-muted-foreground`,children:t.text}),(0,Q.jsxs)(`p`,{className:`mt-2 text-[11px] text-muted-foreground`,children:[(0,Q.jsx)(`time`,{dateTime:t.timestamp,children:new Date(t.timestamp).toLocaleString()}),t.status===`started`&&(0,Q.jsx)(`span`,{children:` · Started`}),t.status===`completed`&&(0,Q.jsx)(`span`,{children:` · Completed`}),t.status===`error`&&(0,Q.jsx)(`span`,{children:` · Error`})]})]}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>void e?.remove(t.id),"aria-label":`Clear notification: ${t.title}`,title:`Clear notification`,className:`-mr-1 -mt-1 flex h-7 w-7 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-accent focus-ring touch-target`,children:(0,Q.jsx)(z,{className:`h-3.5 w-3.5`})})]})},t.id)})}),r.length>t&&(0,Q.jsx)(K,{variant:`ghost`,size:`sm`,className:`mt-3 w-full`,onClick:()=>n(e=>e+50),children:`Show older notifications`})]})]})}function Mp(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(`
15
15
  `)||``}function Np(e){let[t,n]=(0,Z.useState)([]),[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(null),s=(0,Z.useRef)(null),[c,l]=(0,Z.useState)(e);return c!==e&&(l(e),e||n([])),(0,Z.useEffect)(()=>{let t=!1;if(e)return gu(e).then(e=>{t||n(e.messages.map(e=>({role:e.role,content:e.content,isComplete:!0,...e.metadata?.reasoning?{reasoning:e.metadata.reasoning}:{},...e.metadata?{metadata:e.metadata}:{}})))}).catch(()=>{t||n([])}),()=>{t=!0}},[e]),{messages:t,isStreaming:r,error:a,send:(0,Z.useCallback)(async(t,a)=>{if(r||!t.trim()||!e)return;o(null),n(e=>[...e,{role:`user`,content:t,isComplete:!0},{role:`assistant`,content:``,isComplete:!1}]),i(!0);try{await Ou(e)}catch(e){let t=e instanceof Error?e.message:void 0;if(!t?.includes(`not active`)&&!t?.includes(`already`)){o(t??`Failed to start agent`),i(!1);return}}s.current=new AbortController;let c=``,l=``,u=``,d;try{await Y.stream(`${J}/agents/${e}/prompt/stream`,{message:t,viewContext:a},{signal:s.current.signal,onChunk:e=>{c+=e;let t=c.split(`
16
- `);c=t.pop()??``;for(let e of t){if(!e.startsWith(`data: `))continue;let t=e.slice(6).trim();if(t===`[DONE]`)return;try{let e=JSON.parse(t);if(e.type===`chunk`)l+=e.delta||``,n(e=>{let t=[...e];return t[t.length-1]={role:`assistant`,content:l,isComplete:!1,...u?{reasoning:u}:{},...d?{metadata:d}:{}},t});else if(e.type===`thinking`)u=`${u}${e.delta||``}`.trim(),n(e=>{let t=[...e],n=t[t.length-1]?.content||l;return t[t.length-1]={role:`assistant`,content:n,isComplete:!1,...u?{reasoning:u}:{},...d?{metadata:d}:{}},t});else if(e.type===`complete`){let t=Array.isArray(e.messages)?[...e.messages].reverse().find(e=>e?.role===`assistant`):null,r=Mp(t),i=nu(t)||u;d=ru(t),n(e=>{let t=[...e],n=l||t[t.length-1]?.content||``;return t[t.length-1]={role:`assistant`,content:r||n,isComplete:!0,...i?{reasoning:i}:{},...d?{metadata:d}:{}},t})}else e.type===`error`&&o(e.error)}catch{}}},onError:e=>{e.name!==`AbortError`&&o(e.message)},onComplete:()=>{n(e=>{let t=[...e],n=t[t.length-1];return n&&!n.isComplete&&(t[t.length-1]={...n,isComplete:!0}),t}),i(!1)}})}catch(e){let t=e instanceof Error?e:null;t?.name!==`AbortError`&&o(t?.message??`Stream failed`),n(e=>{let t=[...e],n=t[t.length-1];return n&&!n.isComplete&&(t[t.length-1]={...n,isComplete:!0}),t}),i(!1)}},[e,r]),sendVoice:(0,Z.useCallback)(async(t,a)=>{if(!(r||!e)){o(null),i(!0),n(e=>[...e,{role:`user`,content:`🎤 Transcribing…`,isComplete:!1}]);try{let r=await Fu(e,t,{viewContext:a});n(e=>{let t=[...e];return t[t.length-1]={role:`user`,content:`🎤 ${r.transcript}`,isComplete:!0},[...t,{role:`assistant`,content:r.reply,isComplete:!0}]}),r.audio&&r.audioMimeType&&new Audio(`data:${r.audioMimeType};base64,${r.audio}`).play().catch(()=>{})}catch(e){o(e instanceof Error?e.message:`Voice prompt failed`),n(e=>{let t=[...e],n=t[t.length-1];return n?.role===`user`&&!n.isComplete&&t.pop(),t})}finally{i(!1)}}},[e,r]),stop:(0,Z.useCallback)(()=>{s.current?.abort(),i(!1)},[]),clear:(0,Z.useCallback)(()=>{n([]),o(null)},[])}}function Pp(){let[e,t]=(0,Z.useState)(!1),[n,r]=(0,Z.useState)(null),i=(0,Z.useRef)(null),a=(0,Z.useRef)([]);return{isRecording:e,recorderError:n,start:(0,Z.useCallback)(async()=>{if(!i.current){if(r(null),!navigator.mediaDevices?.getUserMedia||typeof MediaRecorder>`u`){r(`Audio recording is not supported in this browser`);return}try{let e=await navigator.mediaDevices.getUserMedia({audio:!0}),n=MediaRecorder.isTypeSupported(`audio/webm;codecs=opus`)?`audio/webm;codecs=opus`:void 0,r=new MediaRecorder(e,n?{mimeType:n}:void 0);a.current=[],r.ondataavailable=e=>{e.data.size>0&&a.current.push(e.data)},r.start(),i.current=r,t(!0)}catch(e){let t=e instanceof Error?e:null;r(t?.name===`NotAllowedError`?`Microphone access denied`:t?.message??`Could not start recording`)}}},[]),stop:(0,Z.useCallback)(()=>{let e=i.current;return e?new Promise(n=>{e.onstop=()=>{e.stream.getTracks().forEach(e=>e.stop()),i.current=null,t(!1);let r=e.mimeType||`audio/webm`,o=new Blob(a.current,{type:r});a.current=[],n(o.size>0?o:null)},e.stop()}):Promise.resolve(null)},[]),cancel:(0,Z.useCallback)(()=>{let e=i.current;e&&(e.onstop=()=>{e.stream.getTracks().forEach(e=>e.stop())},e.stop(),i.current=null,a.current=[],t(!1))},[])}}function Fp(e){let t=e?.usage;if(!t)return null;let n=t.totalTokens,r=t.input,i=t.output;return typeof n==`number`&&typeof r==`number`&&typeof i==`number`?`${n} tok (${r} in / ${i} out)`:typeof n==`number`?`${n} tok`:null}function Ip(e){let t=e?.usage?.cost?.total;return typeof t==`number`?`$${t.toFixed(t<.01?6:4)}`:null}function Lp({reasoning:e,metadata:t,isStreaming:n=!1,compact:r=!1}){let i=t?.model,a=[t?.provider,i,Fp(t),Ip(t)].filter(Boolean);return!e&&a.length===0?null:(0,Q.jsxs)(Q.Fragment,{children:[e&&(0,Q.jsxs)(`details`,{open:n,className:`mb-2 rounded border border-border bg-background ${r?`px-2 py-1.5`:`px-3 py-2`}`,children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer font-medium text-foreground ${r?`text-[11px]`:`text-xs`}`,children:`Reasoning`}),(0,Q.jsx)(Hr,{content:e,className:`mt-1 text-foreground ${r?`text-[11px]`:`text-xs`}`})]}),a.length>0&&(0,Q.jsx)(`div`,{className:`mt-2 text-muted-foreground ${r?`text-[11px]`:`text-xs`}`,children:a.join(` • `)})]})}function Rp({text:e}){let[t,n]=(0,Z.useState)(null),r=(0,Z.useRef)(null);if((0,Z.useEffect)(()=>()=>{r.current&&clearTimeout(r.current)},[]),!e)return null;let i=t?.text===e?t.status:null;return(0,Q.jsx)(`button`,{type:`button`,"aria-label":`Copy reply text`,title:`Copy reply text`,className:`rounded px-1.5 py-1 text-[11px] text-muted-foreground hover:bg-accent hover:text-foreground [@media(hover:hover)]:opacity-0 group-hover/agent-reply:opacity-100 focus-visible:opacity-100`,onClick:async()=>{r.current&&clearTimeout(r.current);try{await navigator.clipboard.writeText(e),n({text:e,status:`copied`})}catch{n({text:e,status:`error`})}r.current=setTimeout(()=>n(null),2e3)},children:(0,Q.jsx)(`span`,{"aria-live":`polite`,children:i===`copied`?`Copied`:i===`error`?`Copy failed — retry`:`+ Copy text`})})}function zp({agentId:e,onClose:t}){let[n,r]=(0,Z.useState)(null),[i,a]=(0,Z.useState)(``),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(null),{showToast:m}=xn(),g=ni(),_=h(),v=g?.agentView?.pathname===_.pathname?g.agentView.view:null,y=g?.state.activeContextType===`context`?g.state.activeContextId:null,b=g?.state.activeContextPath??null,x=(0,Z.useRef)(null),S=(0,Z.useRef)(null),{messages:C,isStreaming:w,error:T,send:E,sendVoice:O,stop:k,clear:A}=Np(e),{isRecording:j,recorderError:M,start:N,stop:ee}=Pp();(0,Z.useEffect)(()=>{hu(e).then(r).catch(()=>{}),cu(e).then(l).catch(()=>l(null))},[e]),(0,Z.useEffect)(()=>{Pu().then(e=>s(!!(e.enabled&&e.stt))).catch(()=>s(!1))},[]),(0,Z.useEffect)(()=>{C.length!==0&&x.current?.scrollIntoView({behavior:`smooth`})},[C]);let P=!!(y&&c?.grants.some(e=>e.binding.type===`context`&&e.binding.context===y)),F=c?.grants.length?`Connections: ${c.grants.map(e=>e.label||e.id).join(`, `)}`:`no canvas access`,te=async()=>{if(!y||u)return;let t=y||b;if(window.confirm(`Add the current context (${t}) to "${n?.label||n?.name||e}"? Other connections remain unchanged. This restarts the agent if it is running.`)){d(!0);try{let t=await lu(e,`context-${crypto.randomUUID()}`,{label:`Context ${y}`,binding:{type:`context`,context:y},permissions:[`read`,`write`]});l(t.access),p(t.tokens[0]?.token??null)}catch(e){m({title:`Error`,description:e instanceof Error?e.message:`Bind failed`,variant:`destructive`})}finally{d(!1)}}},ne=async()=>{let e=i.trim();!e||w||(a(``),S.current?.focus(),await E(e,v))};return(0,Q.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 px-3 h-12 border-b border-border shrink-0`,children:[(0,Q.jsx)(`button`,{type:`button`,onClick:t,className:`p-1 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Back to agents`,children:(0,Q.jsx)(Tt,{className:`w-4 h-4`})}),n?.color&&(0,Q.jsx)(`span`,{className:`w-2.5 h-2.5 rounded-full shrink-0`,style:{backgroundColor:n.color}}),(0,Q.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Q.jsx)(`div`,{className:`text-sm font-medium truncate`,children:n?.label||n?.name||e}),(0,Q.jsx)(`div`,{className:`text-[10px] leading-tight text-muted-foreground truncate`,title:F,children:F})]}),(0,Q.jsx)(`button`,{type:`button`,onClick:A,className:`p-1 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Clear chat`,children:(0,Q.jsx)(W,{className:`w-3.5 h-3.5`})})]}),y&&!P&&(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 border-b border-border bg-muted/40 text-xs shrink-0`,children:[(0,Q.jsxs)(`span`,{className:`flex-1 truncate text-muted-foreground`,title:y||b||void 0,children:[`Toolbox context: `,y||b]}),(0,Q.jsx)(`button`,{type:`button`,disabled:u,onClick:te,className:`shrink-0 rounded border border-input px-2 py-1 hover:bg-accent disabled:opacity-50`,children:u?`Binding…`:`Add this context`})]}),f&&(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 border-b border-border bg-warning/10 text-xs shrink-0`,children:[(0,Q.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,children:`Token (shown once):`}),(0,Q.jsx)(`code`,{className:`flex-1 truncate font-mono`,children:f}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>navigator.clipboard?.writeText(f),className:`shrink-0 rounded border border-input px-2 py-1 hover:bg-accent`,children:`Copy`}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>p(null),className:`shrink-0 rounded px-1.5 py-1 hover:bg-accent`,title:`Dismiss`,children:`×`})]}),(0,Q.jsxs)(`div`,{className:`flex-1 overflow-y-auto px-4 py-3 space-y-3`,children:[C.length===0&&(0,Q.jsx)(`div`,{className:`text-xs text-muted-foreground text-center py-10`,children:n?`Chat with ${n.label||n.name}`:`Loading…`}),C.map((e,t)=>(0,Q.jsxs)(`div`,{className:G(`group/agent-reply text-sm rounded-lg px-3 py-2 max-w-[85%] break-words`,e.role===`user`?`ml-auto bg-foreground text-background`:`mr-auto bg-muted text-foreground`),children:[(0,Q.jsx)(Lp,{reasoning:e.role===`assistant`?e.reasoning:void 0,metadata:e.role===`assistant`?e.metadata:void 0,isStreaming:!e.isComplete,compact:!0}),e.role===`assistant`?(0,Q.jsx)(Hr,{content:e.content||(e.isComplete?``:`…`)}):(0,Q.jsx)(`span`,{className:`whitespace-pre-wrap`,children:e.content}),e.role===`assistant`&&(0,Q.jsx)(`div`,{className:`flex justify-end`,children:(0,Q.jsx)(Rp,{text:e.content})})]},t)),(T||M)&&(0,Q.jsx)(`div`,{className:`text-xs text-destructive text-center py-1`,children:T||M}),(0,Q.jsx)(`div`,{ref:x})]}),(0,Q.jsx)(`div`,{className:`p-3 border-t border-border shrink-0`,children:(0,Q.jsxs)(`div`,{className:`flex gap-2 items-end`,children:[(0,Q.jsx)(`textarea`,{ref:S,value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),ne())},placeholder:`Message…`,rows:2,className:`flex-1 resize-y text-sm px-3 py-2 border border-input bg-background rounded-md focus:outline-none focus:ring-1 focus:ring-ring min-h-[38px] max-h-[120px]`}),o&&(0,Q.jsx)(`button`,{type:`button`,onClick:async()=>{if(j){let e=await ee();e&&await O(e,v)}else w||await N()},disabled:w&&!j,className:G(`flex items-center justify-center w-9 h-9 rounded-md transition-opacity shrink-0 disabled:opacity-40`,j?`bg-destructive text-destructive-foreground hover:opacity-90 animate-pulse`:`bg-muted text-foreground hover:bg-accent`),title:j?`Stop recording and send`:`Record a voice message`,children:j?(0,Q.jsx)(Ot,{className:`w-4 h-4`}):(0,Q.jsx)(D,{className:`w-4 h-4`})}),w?(0,Q.jsx)(`button`,{type:`button`,onClick:k,className:`flex items-center justify-center w-9 h-9 rounded-md bg-destructive text-destructive-foreground hover:opacity-90 transition-opacity shrink-0`,title:`Stop`,children:(0,Q.jsx)(Ot,{className:`w-4 h-4`})}):(0,Q.jsx)(`button`,{type:`button`,onClick:ne,disabled:!i.trim(),className:`flex items-center justify-center w-9 h-9 rounded-md bg-foreground text-background hover:opacity-90 disabled:opacity-40 transition-opacity shrink-0`,title:`Send`,children:(0,Q.jsx)(Bt,{className:`w-4 h-4`})})]})})]})}function Bp(){let{state:e,openApplet:t}=ti(),[n,r]=(0,Z.useState)(`context`),i=e.appsAppletId,a=i?ga.find(e=>e.id===i):null;if(a)return(0,Q.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Q.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-2 py-1.5`,children:[(0,Q.jsx)(`button`,{type:`button`,onClick:()=>t(null),className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Back to applets`,title:`Back to applets`,children:(0,Q.jsx)(Tt,{className:`h-4 w-4`})}),(0,Q.jsx)(a.icon,{className:`h-4 w-4 text-muted-foreground`}),(0,Q.jsx)(`span`,{className:`text-sm font-medium`,children:a.label})]}),(0,Q.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,Q.jsx)(a.Component,{})})]});let o=ha(n);return(0,Q.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Q.jsx)(`div`,{className:`flex shrink-0 border-b border-border`,children:[`context`,`global`].map(e=>(0,Q.jsx)(`button`,{type:`button`,onClick:()=>r(e),className:G(`flex-1 py-2.5 text-xs capitalize transition-colors`,n===e?`-mb-px border-b-2 border-foreground font-semibold text-foreground`:`font-medium text-muted-foreground hover:text-foreground`),children:e},e))}),(0,Q.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3`,children:[!o.length&&(0,Q.jsxs)(`p`,{className:`py-10 text-center text-sm text-muted-foreground`,children:[`No `,n,` applets yet.`]}),(0,Q.jsx)(`div`,{className:`grid grid-cols-2 gap-2`,children:o.map(e=>(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>t(e.id),className:`flex min-h-[4.5rem] flex-col items-center justify-center gap-1.5 rounded-(--card-radius) border border-border bg-muted/40 p-3 text-foreground transition-colors hover:bg-muted`,title:e.description,children:[(0,Q.jsx)(e.icon,{className:`h-5 w-5 text-muted-foreground`}),(0,Q.jsx)(`span`,{className:`text-xs font-medium leading-none`,children:e.label})]},e.id))})]})]})}var Vp=[{view:`apps`,icon:Ut,label:`Apps`},{view:`tools`,icon:Qe,label:`Filters`},{view:`agents`,icon:ye,label:`Agents`},{view:`notifications`,icon:Ge,label:`Notifications`}],Hp=340,Up=`toolbox:width`,Wp=360,Gp=48,Kp=e=>{let t=typeof window<`u`?window.innerWidth:1600,n=Math.max(Hp,Math.min(Math.round(t*.7),t-Gp-Wp));return Math.max(Hp,Math.min(e,n))},qp=()=>typeof window<`u`?Math.round(window.innerWidth/2):720;function Jp(){let{state:e,setView:t,closeT1:n,closeT2:r}=ti();hi(n,e.t1Open&&!e.t2Open),hi(r,e.t2Open);let{t1Open:i,t1View:a,t2Open:o,t2AgentId:s,activeAccentColor:c}=e,l=Pr(),[u,d]=(0,Z.useState)(()=>{let e=typeof window<`u`?Number(localStorage.getItem(Up)):NaN;return Number.isFinite(e)&&e>0?e:420}),f=(0,Z.useCallback)(e=>{d(e);try{localStorage.setItem(Up,String(e))}catch{}},[]),p=(0,Z.useRef)(null),m=(0,Z.useCallback)(e=>{e.preventDefault(),p.current={startX:e.clientX,startWidth:u};let t=e=>{if(!p.current)return;let t=Kp(p.current.startWidth-(e.clientX-p.current.startX));d(t)},n=()=>{p.current=null,window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n),d(e=>{try{localStorage.setItem(Up,String(e))}catch{}return e})};window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)},[u]),h=u>=qp()*.9;return(0,Z.useEffect)(()=>{let e=()=>d(e=>Kp(e));return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),!i||!a?null:(0,Q.jsxs)(Q.Fragment,{children:[l&&(0,Q.jsx)(`div`,{className:`fixed inset-0 z-panel-scrim bg-scrim animate-fade-in`,onClick:n,"aria-hidden":!0}),(0,Q.jsxs)(`div`,{style:l?void 0:{width:u},className:G(`flex flex-col overflow-hidden rounded-(--panel-radius) border bg-card surface-glass text-foreground`,l?`fixed bottom-2 left-2 right-2 top-2 z-panel shadow-elevation-5 animate-fade-in`:`relative shrink-0 shadow-elevation-3`),children:[!l&&(0,Q.jsx)(`div`,{onMouseDown:m,className:`absolute left-0 top-0 z-20 h-full w-1.5 cursor-col-resize hover:bg-primary/20`,title:`Drag to resize`,"aria-hidden":!0}),(0,Q.jsxs)(`div`,{className:`flex h-[calc(3rem-1px)] shrink-0 items-center justify-between gap-1 border-b-4 px-2`,style:c?{borderBottomColor:c}:void 0,children:[(0,Q.jsx)(`div`,{className:`flex items-center gap-1`,children:Vp.map(({view:e,icon:n,label:r})=>(0,Q.jsx)(`button`,{type:`button`,onClick:()=>t(e),"aria-label":r,title:r,className:G(`flex h-10 w-11 items-center justify-center rounded-md transition-colors`,a===e?`bg-muted text-foreground`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:(0,Q.jsx)(n,{className:`h-4 w-4 shrink-0`})},e))}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[!l&&(0,Q.jsx)(`button`,{type:`button`,onClick:()=>f(h?420:Kp(qp())),className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,"aria-label":h?`Shrink toolbox`:`Expand toolbox`,title:h?`Shrink toolbox`:`Expand to half screen`,children:h?(0,Q.jsx)(be,{className:`h-4 w-4`}):(0,Q.jsx)(Ke,{className:`h-4 w-4`})}),(0,Q.jsx)(`button`,{type:`button`,onClick:n,className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,"aria-label":`Close toolbox`,children:(0,Q.jsx)(z,{className:`h-4 w-4`})})]})]}),(0,Q.jsxs)(`div`,{className:`relative flex min-h-0 flex-1 flex-col`,children:[(0,Q.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col ${o&&s?`invisible`:``}`,children:[a===`home`&&(0,Q.jsx)(nf,{}),a===`apps`&&(0,Q.jsx)(Bp,{}),a===`tools`&&(0,Q.jsx)(Op,{}),a===`agents`&&(0,Q.jsx)(Ap,{}),a===`notifications`&&(0,Q.jsx)(jp,{})]}),o&&s&&(0,Q.jsx)(`div`,{className:`absolute inset-0 z-10 flex flex-col bg-background`,children:(0,Q.jsx)(zp,{agentId:s,onClose:r})})]})]})]})}function Yp(){let{running:e,hasViewer:t,paused:n,snapshot:r,source:i,lastCount:a,error:o,setPaused:s,stop:c,reopen:l}=xf();if(!e||t)return null;let u=i===`screen`?Le:i===`photo`?fe:re;return(0,Q.jsxs)(`div`,{className:G(`fixed right-4 w-56 overflow-hidden rounded-(--panel-radius) border border-border bg-card shadow-elevation-4 z-panel animate-fade-in`,`bottom-fab-inset md:bottom-[calc(var(--spacing-fab-inset)+5rem)]`),role:`status`,"aria-label":`Lens feed running`,children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:l,title:`Back to Lens`,className:`relative block w-full cursor-pointer bg-black/80 aspect-video`,children:[(0,Q.jsx)(Ff,{className:`h-full w-full`}),r&&(0,Q.jsx)(`img`,{src:r,alt:``,className:`absolute inset-0 h-full w-full bg-black object-contain`}),n&&(0,Q.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center bg-black/50 text-xs font-medium text-white`,children:`paused`})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-1 px-2 py-1.5`,children:[(0,Q.jsx)(u,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Q.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-[11px] text-muted-foreground`,children:o?(0,Q.jsx)(`span`,{className:`text-destructive`,children:o}):n?`paused`:r?`${i===`photo`?`photo`:`snapshot`} · ${a??`…`} match${a===1?``:`es`}`:`live · ${a??`…`} match${a===1?``:`es`}`}),i!==`photo`&&(0,Q.jsx)(`button`,{type:`button`,onClick:()=>s(!n),"aria-label":n?`Resume Lens`:`Pause Lens`,title:n?`Resume searching`:`Pause searching (camera stays on)`,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:n?(0,Q.jsx)(le,{className:`h-3.5 w-3.5`}):(0,Q.jsx)(Ae,{className:`h-3.5 w-3.5`})}),(0,Q.jsx)(`button`,{type:`button`,onClick:l,"aria-label":`Reopen Lens panel`,title:`Reopen Lens`,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:(0,Q.jsx)(Ke,{className:`h-3.5 w-3.5`})}),(0,Q.jsx)(`button`,{type:`button`,onClick:c,"aria-label":`Stop Lens feed`,title:`Stop the feed`,className:`rounded p-1 text-destructive transition-colors hover:bg-destructive/10`,children:(0,Q.jsx)(pe,{className:`h-3.5 w-3.5`})})]})]})}var Xp=[`view`,`location`,`metadata`,`json`,`synapses`,`backends`];function Zp(e){let t=new URLSearchParams(e.replace(/^#/,``)),n=t.get(`document`)??``,r=t.get(`workspace`);if(!r||!/^\d+$/.test(n)||!Number.isSafeInteger(Number(n))||Number(n)<=0)return null;let i=t.get(`section`);return{workspaceId:r,documentId:Number(n),section:Xp.includes(i)?i:`view`,maximized:t.get(`fullscreen`)===`1`}}function Qp(e){let t=new URLSearchParams({document:String(e.documentId),workspace:e.workspaceId});return e.section!==`view`&&t.set(`section`,e.section),e.maximized&&t.set(`fullscreen`,`1`),`#${t}`}function $p({children:e}){let t=h(),n=m(),r=(0,Z.useMemo)(()=>Zp(t.hash),[t.hash]),i=r?.workspaceId,a=r?.documentId,o=i&&a?JSON.stringify([i,a]):null,[s,c]=(0,Z.useState)(0),[l,u]=(0,Z.useState)(null),d=l?.key===o&&l?.revision===s?l:null;(0,Z.useEffect)(()=>{if(!o||!i||!a||d)return;let e=!1;return pr(i,a).then(t=>{e||u({key:o,revision:s,document:t,error:t?void 0:`Document not found.`})}).catch(t=>{e||u({key:o,revision:s,document:null,error:t?.statusCode===404?`Document not found.`:`Unable to load this document.`})}),()=>{e=!0}},[o,i,a,s,d]);let f=(0,Z.useCallback)((e,r)=>{u({key:JSON.stringify([r,e.id]),revision:s,document:e}),n({pathname:t.pathname,search:t.search,hash:Qp({workspaceId:r,documentId:e.id,section:`view`,maximized:!1})},{state:t.state})},[n,t.pathname,t.search,t.state,s]),p=(0,Z.useCallback)(()=>{r&&n({pathname:t.pathname,search:t.search,hash:``},{replace:!0,state:t.state})},[r,n,t.pathname,t.search,t.state]),g=(0,Z.useCallback)((e,i)=>{r&&(u({key:JSON.stringify([i,e.id]),revision:s,document:e}),n({pathname:t.pathname,search:t.search,hash:Qp({...r,workspaceId:i,documentId:e.id})},{replace:!0,state:t.state}))},[r,s,n,t.pathname,t.search,t.state]),_=(0,Z.useCallback)(e=>{r&&n({pathname:t.pathname,search:t.search,hash:Qp({...r,...e})},{replace:!0,state:t.state})},[r,n,t.pathname,t.search,t.state]),v=(0,Z.useCallback)(()=>c(e=>e+1),[]),y=(0,Z.useMemo)(()=>({entry:d?.document&&i?{document:d.document,workspaceId:i}:null,location:r,loading:!!r&&!d,error:d?.error,open:f,replace:g,close:p,update:_,retry:v}),[d,i,r,f,g,p,_,v]);return(0,Q.jsx)(br.Provider,{value:y,children:e})}function em({children:e}){let[t,n]=(0,Z.useState)(null),r=(0,Z.useCallback)((e,t)=>n({document:e,workspaceId:t}),[]),i=(0,Z.useCallback)(()=>n(null),[]),a=(0,Z.useMemo)(()=>({open:r,close:i}),[r,i]);return(0,Q.jsxs)(Ii.Provider,{value:a,children:[e,(0,Q.jsx)(Mr,{document:t?.document??null,isOpen:!!t,onClose:i,workspaceId:t?.workspaceId})]})}var tm={key:`desk`,label:`Desk`,main:`/`,mainExpanded:!1,entries:[]},nm=0,rm=()=>`c${++nm}`;function im(e,t){return e.kind===`route`&&t.kind===`route`?e.location===t.location:e.kind===`document`&&t.kind===`document`&&e.document.id===t.document.id&&e.workspaceId===t.workspaceId}function am({children:e}){let t=h(),n=m(),[r,i]=(0,Z.useState)([tm]),[a,o]=(0,Z.useState)(0),[s,c]=(0,Z.useState)(wr),l=(0,Z.useRef)(r),u=(0,Z.useRef)(a),d=(0,Z.useRef)(s);(0,Z.useEffect)(()=>{l.current=r,u.current=a,d.current=s},[r,a,s]);let f=(0,Z.useCallback)((e,t)=>{let n=l.current.slice();n[e]=t,l.current=n,i(n)},[]),p=(0,Z.useCallback)(e=>{let t=u.current,n=l.current[t];n&&f(t,e(n))},[f]),g=t.pathname+t.search;(0,Z.useEffect)(()=>{p(e=>e.main===g?e:{...e,main:g})},[g,p]);let _=(0,Z.useCallback)(e=>{let t=l.current[u.current];if(!t)return;let n=t.entries.find(t=>im(e,t));if(n){c(n.id);return}let r={...e,id:rm()},i=t.entries.findIndex(e=>e.id===d.current),a=t.entries.slice();a.splice(i>=0?i+1:0,0,r),p(e=>({...e,entries:a})),d.current=r.id,c(r.id)},[p]),v=(0,Z.useCallback)((e,t)=>{_({kind:`document`,document:e,workspaceId:t})},[_]),y=(0,Z.useCallback)((e,t)=>{let n=`document-preview`;p(r=>{let i=r.entries.find(e=>e.id===n),a={kind:`document`,id:n,document:e,workspaceId:t,expanded:i?.expanded};return{...r,entries:[a,...r.entries.filter(e=>e.id!==n)]}}),d.current=n,c(n)},[p]),b=(0,Z.useCallback)(e=>{p(t=>({...t,entries:t.entries.filter(t=>t.id!==e)})),c(t=>t===e?wr:t)},[p]),x=(0,Z.useCallback)((e,t)=>{p(n=>({...n,entries:n.entries.map(n=>n.id===e&&n.kind===`route`?{...n,location:t}:n)}))},[p]),S=(0,Z.useCallback)(e=>{p(t=>e===`main`?{...t,mainExpanded:!t.mainExpanded}:{...t,entries:t.entries.map(t=>t.id===e?{...t,expanded:!t.expanded}:t)})},[p]),C=(0,Z.useCallback)(e=>{let t=l.current[e];t&&(u.current=e,o(e),c(wr),n(t.main))},[n]),w=(0,Z.useCallback)((e,t,n)=>{let r=l.current.findIndex(t=>t.key===e);if(r>=0){C(r);return}let a=[...l.current,{key:e,label:t,main:n,mainExpanded:!1,entries:[]}];l.current=a,i(a),C(a.length-1)},[C]),T=(0,Z.useCallback)(e=>{C(u.current+e)},[C]),E=(0,Z.useCallback)(e=>{let t=l.current.findIndex(t=>t.key===e);if(t<=0)return;let n=l.current.filter(t=>t.key!==e);l.current=n,i(n);let r=u.current;r===t?C(Math.min(t,n.length-1)):r>t&&(u.current=r-1,o(r-1))},[C]),D=(0,Z.useMemo)(()=>({rows:r,activeRow:a,focus:s,setFocus:c,openCanvas:_,openDocument:v,closeCanvas:b,navigateCanvas:x,toggleExpanded:S,activateRow:w,moveRow:T,closeRow:E}),[r,a,s,_,v,b,x,S,w,T,E]),O=(0,Z.useMemo)(()=>({entry:null,open:v,preview:y,close:()=>{}}),[v,y]);return(0,Q.jsx)(Sr.Provider,{value:D,children:(0,Q.jsx)(br.Provider,{value:O,children:e})})}function om(e){return f(typeof e==`string`?v(e):e)}function sm({location:e,onNavigate:t}){let n=(0,Z.useMemo)(()=>{let t=v(e);return{pathname:t.pathname||`/`,search:t.search||``,hash:t.hash||``,state:null,key:e}},[e]),r=(0,Z.useMemo)(()=>({basename:`/`,static:!1,useTransitions:void 0,future:{},navigator:{createHref:om,go:()=>{},push:e=>t(om(e)),replace:e=>t(om(e))}}),[t]);return(0,Q.jsx)(b.Provider,{value:r,children:(0,Q.jsx)(g.Provider,{value:{location:n,navigationType:w.Push},children:(0,Q.jsx)(_.Provider,{value:{outlet:null,matches:[],isDataRoute:!1},children:(0,Q.jsx)(T,{children:is})})})})}var cm=`input, textarea, select, [contenteditable=""], [contenteditable="true"]`,lm=420,um=e=>e<=0?0:e>=1?1:e<.5?2**(20*e-10)/2:(2-2**(-20*e+10))/2;function dm(e,t,n){if(window.matchMedia(`(prefers-reduced-motion: reduce)`).matches)return e.scrollLeft=t,n?.(),()=>{};let r=e.scrollLeft,i=t-r;if(Math.abs(i)<1)return n?.(),()=>{};let a=e.style.scrollSnapType;e.style.scrollSnapType=`none`;let o=performance.now(),s=0,c=t=>{let l=Math.min(1,(t-o)/lm);e.scrollLeft=r+i*um(l),l<1?s=requestAnimationFrame(c):(e.style.scrollSnapType=a,n?.())};return s=requestAnimationFrame(c),()=>{cancelAnimationFrame(s),e.style.scrollSnapType=a}}function fm(e,t){let n=parseFloat(getComputedStyle(e).gap)||0,r=t.getBoundingClientRect().left-e.getBoundingClientRect().left+e.scrollLeft,i=r+t.offsetWidth,a=e.scrollLeft,o=a+e.clientWidth;return r<a?Math.max(0,r-n):i>o?i+n-e.clientWidth:a}function pm({section:e}){return e===`contexts`?(0,Q.jsx)($s,{}):e===`workspaces`?(0,Q.jsx)(Hc,{}):e===`agents`?(0,Q.jsx)(zu,{}):e===`admin`?(0,Q.jsx)(qu,{}):e===`apps`?(0,Q.jsx)(Bs,{}):e===`settings`?(0,Q.jsx)(qu,{}):null}function mm(e,t,n){if(e?.kind===`document`)return On(e.document).title;let r=(e?.kind===`route`?e.location:t).split(/[?#]/)[0];if(r===`/settings`)return`Settings`;let i=fa.flatMap(e=>[...e.items]).find(e=>e.path===r);if(i)return i.label;let a=r.split(`/`).filter(Boolean);if(a.length===0)return`Desk`;if(a[0]===`workspaces`&&a.length===2){let e=decodeURIComponent(a[1]),t=n.find(t=>t.id===e)??n.find(t=>t.name===e);return t?.label||t?.name||`Workspace`}return decodeURIComponent(a[a.length-1])}function hm({id:e,title:t,expanded:n,focused:r,onFocus:i,onToggleExpanded:a,onClose:o,badge:s,contentHeader:c,children:l}){let u=kr();return(0,Q.jsxs)(`section`,{"data-reader-pane":c?!0:void 0,style:c&&!n?{"--reader-width":`${u??420}px`,...u?{transition:`none`}:{}}:void 0,"data-strip-col":e,className:G(`strip-canvas surface-sheet relative`,n&&`strip-canvas--wide`,r&&`strip-canvas--focused`),onPointerDownCapture:()=>i(e),"aria-label":t,children:[c&&!n&&(0,Q.jsx)(Dr,{edge:`right`}),!c&&(0,Q.jsxs)(`header`,{className:`strip-canvas-bar`,children:[s&&(0,Q.jsx)(`span`,{className:`strip-row-label`,children:s}),(0,Q.jsx)(`span`,{className:`strip-canvas-title`,title:t,children:t}),(0,Q.jsx)(`button`,{type:`button`,className:`strip-canvas-btn`,title:n?`Card size`:`Expand to full width`,"aria-pressed":n,onClick:()=>a(e),children:n?(0,Q.jsx)(be,{className:`size-3.5`}):(0,Q.jsx)(Ke,{className:`size-3.5`})}),o&&(0,Q.jsx)(`button`,{type:`button`,className:`strip-canvas-btn`,title:s?`Close row`:`Close canvas`,onClick:()=>o(e),children:(0,Q.jsx)(z,{className:`size-3.5`})})]}),(0,Q.jsx)(`div`,{className:`strip-canvas-body`,children:l})]})}function gm(e){return G(`relative flex-1 min-h-0 min-w-0 overflow-auto`,!Qu(e)&&!Zu(e)&&`p-page`)}function _m({row:e,pathname:t,rowLabel:n,onCloseRow:r,workspaces:i}){let{focus:a,setFocus:o,toggleExpanded:s,closeCanvas:c,navigateCanvas:l}=xr(),u=(0,Z.useCallback)(e=>t=>l(e,t),[l]);return(0,Q.jsxs)(Q.Fragment,{children:[t===`/`?(0,Q.jsx)(`div`,{hidden:!0,children:(0,Q.jsx)(C,{})}):(0,Q.jsx)(hm,{id:wr,title:mm(null,t,i),expanded:e.mainExpanded,focused:a===wr,onFocus:o,onToggleExpanded:s,badge:n,onClose:r,children:(0,Q.jsx)(`main`,{id:`content-area`,className:gm(t),children:(0,Q.jsx)(C,{})})}),e.entries.map(e=>(0,Q.jsx)(hm,{id:e.id,title:mm(e,t,i),expanded:!!e.expanded,focused:a===e.id,onFocus:o,onToggleExpanded:s,contentHeader:e.kind===`document`,onClose:c,children:e.kind===`route`?(0,Q.jsx)(`div`,{className:gm(e.location.split(`?`)[0]),children:(0,Q.jsx)(sm,{location:e.location,onNavigate:u(e.id)})}):(0,Q.jsx)(`div`,{className:`flex flex-1 min-h-0 min-w-0 items-stretch`,children:(0,Q.jsx)(jr,{entry:e,onClose:()=>c(e.id),frame:{expanded:!!e.expanded,onToggleExpanded:()=>s(e.id)}})})},e.id))]})}function vm({row:e,workspaces:t}){return(0,Q.jsxs)(`div`,{className:`strip-ghost-row`,"aria-hidden":!0,children:[(0,Q.jsx)(`span`,{className:`strip-ghost-chip strip-ghost-chip--main`,children:mm(null,e.main,t)}),e.entries.map(n=>(0,Q.jsx)(`span`,{className:`strip-ghost-chip`,children:mm(n,e.main,t)},n.id))]})}function ym(){let{state:e,closeM1:t,closeM2:n}=la(),[r,i]=(0,Z.useState)(280),{rows:a,activeRow:o,focus:s,setFocus:c,moveRow:l,closeRow:u}=xr(),{pathname:d}=h(),{workspaces:f}=Bc(d.startsWith(`/workspaces/`)||a.some(e=>e.main.startsWith(`/workspaces/`)||e.entries.some(e=>e.kind===`route`&&e.location.startsWith(`/workspaces/`)))),p=ca(),m=(0,Z.useRef)(null);hi(t,e.m1Open&&!e.m2Open),hi(n,e.m2Open),(0,Z.useLayoutEffect)(()=>{let e=m.current;if(!e)return;let t=()=>{e.style.setProperty(`--strip-w`,`${e.clientWidth}px`),e.style.setProperty(`--strip-h`,`${e.clientHeight}px`)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let g=(0,Z.useRef)(e.m1Open);(0,Z.useEffect)(()=>{e.m1Open&&!g.current&&!e.m2Open&&c(`m1`),g.current=e.m1Open},[e.m1Open,e.m2Open,c]);let _=(0,Z.useRef)(e.m2Open);(0,Z.useEffect)(()=>{e.m2Open&&!_.current&&c(`m2`),!e.m2Open&&_.current&&s===`m2`&&c(e.m1Open?`m1`:wr),_.current=e.m2Open},[e.m2Open,e.m1Open,s,c]),(0,Z.useEffect)(()=>{!e.m1Open&&s===`m1`&&c(wr)},[e.m1Open,s,c]),(0,Z.useEffect)(()=>{let e=m.current,t=e?.querySelector(`[data-strip-col="${CSS.escape(s)}"]`);if(!(!e||!t))return dm(e,fm(e,t))},[s,a,o,e.m1Open,e.m2Open]);let v=(0,Z.useCallback)(()=>{let t=a[o];return[...e.m1Open?[`m1`]:[],...e.m2Open?[`m2`]:[],...d===`/`?[]:[wr],...t?t.entries.map(e=>e.id):[]]},[a,o,e.m1Open,e.m2Open,d]);return(0,Z.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.isComposing||!e.key.startsWith(`Arrow`)||!oa(e,p))return;let t=e.target;if(!(t?.closest(cm)||t?.closest(`[role="dialog"]`))){if(e.key===`ArrowLeft`||e.key===`ArrowRight`){let t=v(),n=t[Math.max(0,t.indexOf(s))+(e.key===`ArrowRight`?1:-1)];if(!n)return;e.preventDefault(),c(n)}else(e.key===`ArrowUp`||e.key===`ArrowDown`)&&a.length>1&&(e.preventDefault(),l(e.key===`ArrowDown`?1:-1))}};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[v,s,c,l,a.length,p]),(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`strip-shell flex h-viewport w-full overflow-hidden surface-desk gap-shell p-shell`,children:[(0,Q.jsx)(js,{}),(0,Q.jsxs)(`div`,{ref:m,className:`strip-scroller`,style:{"--strip-menu-space":`${(e.m1Open?280:0)+(e.m2Open?r:0)}px`},children:[e.m1Open&&(0,Q.jsx)(`div`,{"data-strip-col":`m1`,className:G(`strip-col strip-menu-col`,s===`m1`&&`strip-col--focused`),onPointerDownCapture:()=>c(`m1`),children:(0,Q.jsx)(pm,{section:e.activeSection})}),e.m2Open&&(0,Q.jsxs)(`div`,{"data-strip-col":`m2`,style:{width:r,position:`relative`},className:G(`strip-col strip-menu-col`,s===`m2`&&`strip-col--focused`),onPointerDownCapture:()=>c(`m2`),children:[(0,Q.jsx)(Yu,{}),(0,Q.jsx)(Us,{width:r,onResize:i})]}),(0,Q.jsx)(`div`,{className:`strip-rows`,style:{transform:`translateY(${-o*100}%)`},children:a.map((e,t)=>(0,Q.jsx)(`div`,{className:G(`strip-row`,t===o&&`strip-row--active`),children:(0,Q.jsx)(`div`,{className:`strip-row-canvases`,children:t===o?(0,Q.jsx)(_m,{row:e,workspaces:f,pathname:d,rowLabel:a.length>1?e.label:void 0,onCloseRow:t>0?()=>u(e.key):void 0}):(0,Q.jsx)(vm,{row:e,workspaces:f})})},e.key))})]}),(0,Q.jsx)($d,{}),(0,Q.jsx)(Jp,{})]}),(0,Q.jsx)(nd,{}),(0,Q.jsx)(As,{}),(0,Q.jsx)(Yp,{})]})}function bm(){let e=sa();return(0,Q.jsx)(fs,{children:(0,Q.jsx)(ad,{children:(0,Q.jsx)(yd,{children:(0,Q.jsx)(If,{children:(0,Q.jsx)($p,{children:e===`strip`?(0,Q.jsx)(am,{children:(0,Q.jsx)(em,{children:(0,Q.jsx)(ym,{})})}):(0,Q.jsxs)(em,{children:[(0,Q.jsxs)(`div`,{className:`flex h-viewport w-full overflow-hidden surface-desk gap-shell p-shell`,children:[(0,Q.jsx)(js,{}),(0,Q.jsx)(Xu,{}),(0,Q.jsx)(td,{}),(0,Q.jsx)($d,{}),(0,Q.jsx)(Jp,{})]}),(0,Q.jsx)(nd,{}),(0,Q.jsx)(As,{}),(0,Q.jsx)(Yp,{})]})})})})})})}var xm=wt,Sm=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(ot,{ref:n,className:G(`fixed top-0 right-0 z-toast flex max-h-screen w-full flex-col-reverse gap-2 p-4 sm:right-0 sm:flex-col md:max-w-[420px]`,e),...t}));Sm.displayName=ot.displayName;var Cm=Zt(`group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-elevation-3 transition-all duration-normal data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full`,{variants:{variant:{default:`border bg-background`,destructive:`destructive group border-destructive bg-destructive text-destructive-foreground`}},defaultVariants:{variant:`default`}}),wm=Z.forwardRef(({className:e,variant:t,...n},r)=>(0,Q.jsx)(yt,{ref:r,className:G(Cm({variant:t}),e),...n}));wm.displayName=yt.displayName;var Tm=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(Mt,{ref:n,className:G(`inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive`,e),...t}));Tm.displayName=Mt.displayName;var Em=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)($e,{ref:n,className:G(`absolute right-2 top-2 rounded-md p-1 text-foreground/50 reveal-on-hover hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-[.destructive]:text-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive group-[.destructive]:focus:ring-offset-destructive`,e),"toast-close":``,...t,children:(0,Q.jsx)(z,{className:`h-4 w-4`})}));Em.displayName=$e.displayName;var Dm=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(ut,{ref:n,className:G(`text-sm font-semibold`,e),...t}));Dm.displayName=ut.displayName;var Om=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(rt,{ref:n,className:G(`text-sm opacity-90`,e),...t}));Om.displayName=rt.displayName;var km=`canvas-notifications`,Am=`notifications`,jm=`canvas:notification-history`,Mm,Nm;function Pm(){try{let e=localStorage.getItem(`authToken`);if(e){let t=Qt(e),n=t.sub||t.userId||t.id||t.email;if(typeof n==`string`||typeof n==`number`)return JSON.stringify([t.iss||``,n])}}catch{}return`anonymous`}function Fm(){return Mm||=new Promise((e,t)=>{let n=indexedDB.open(km,1);n.onupgradeneeded=()=>{n.result.createObjectStore(Am,{keyPath:[`account`,`id`]}).createIndex(`account`,`account`)},n.onsuccess=()=>{let t=n.result;t.onversionchange=()=>{t.close(),Mm=void 0},e(t)},n.onerror=()=>t(n.error)}).catch(e=>{throw Mm=void 0,e}),Mm}function Im(){return!Nm&&typeof BroadcastChannel<`u`&&(Nm=new BroadcastChannel(jm),Nm.onmessage=e=>window.dispatchEvent(new CustomEvent(jm,{detail:e.data}))),Nm}function Lm(e,t=!1){let n={account:e,error:t};window.dispatchEvent(new CustomEvent(jm,{detail:n})),t||Im()?.postMessage(n)}function Rm(e,t){Im();let n=n=>{let r=n.detail;r?.account===e&&t(!!r.error)};return window.addEventListener(jm,n),()=>window.removeEventListener(jm,n)}async function zm(e){let t=await Fm();return new Promise((n,r)=>{let i=t.transaction(Am,`readonly`),a=i.objectStore(Am).index(`account`).getAll(e);i.oncomplete=()=>n(a.result.sort((e,t)=>e.timestamp.localeCompare(t.timestamp)||e.id.localeCompare(t.id))),i.onabort=()=>r(i.error),i.onerror=()=>r(i.error)})}async function Bm(e,t){try{let n=await Fm();await new Promise((e,r)=>{let i=n.transaction(Am,`readwrite`);i.oncomplete=()=>e(),i.onabort=()=>r(i.error),i.onerror=()=>r(i.error),t(i.objectStore(Am))}),Lm(e)}catch(t){throw Lm(e,!0),t}}function Vm(e,t){return Bm(e,n=>{let r=n.get([e,t.id]);r.onsuccess=()=>{r.result||n.put({...t,account:e})}})}function Hm(e,t,n){return Bm(e,r=>{let i=r.get([e,t]);i.onsuccess=()=>{i.result&&r.put({...i.result,...n})}})}function Um(e,t){return Bm(e,n=>{n.delete([e,t])})}function Wm(e){return Bm(e,t=>{let n=t.index(`account`).openKeyCursor(e);n.onsuccess=()=>{n.result&&(t.delete(n.result.primaryKey),n.result.continue())}})}function Gm({children:e}){let[t,n]=(0,Z.useState)([]),r=(0,Z.useRef)(new Set),i=(0,Z.useCallback)((e,t=!0)=>{if(an(e.description)||an(e.title))return;let i=`${e.title}:${e.description??``}`;if(t&&(e.historyId||!r.current.has(i))){let t=e.timestamp?new Date(e.timestamp):new Date;Vm(Pm(),{id:e.historyId||crypto.randomUUID(),title:e.title,text:e.description||``,timestamp:Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString(),status:e.variant===`destructive`?`error`:`info`}).catch(()=>{})}if(r.current.has(i))return;r.current.add(i);let a=Math.random().toString(36).substring(2,9);n(t=>[...t,{...e,id:a}]),setTimeout(()=>{n(e=>e.filter(e=>e.id!==a)),r.current.delete(i)},5e3)},[]),a=(0,Z.useCallback)(e=>{let t=crypto.randomUUID(),r=Pm();Vm(r,{id:t,title:e.title,text:e.description||``,timestamp:new Date().toISOString(),status:`started`}).catch(()=>{}),n(n=>[...n,{...e,id:t,busy:!0}]);let a=!1,o=(e,o=!1)=>{a||(a=!0,n(e=>e.filter(e=>e.id!==t)),Hm(r,t,{...e?{title:e.title,text:e.description||``}:{},status:o||e?.variant===`destructive`?`error`:`completed`}).catch(()=>{}),e&&i(e,!1))};return{update:e=>{a||n(n=>n.map(n=>n.id===t?{...n,...e}:n))},done:e=>o(e),fail:e=>o(e,!0)}},[i]),o=(0,Z.useMemo)(()=>({showToast:i,showProgress:a}),[i,a]);return(0,Q.jsx)(Sn.Provider,{value:o,children:(0,Q.jsxs)(xm,{children:[e,t.map(e=>(0,Q.jsxs)(wm,{variant:e.variant,duration:e.busy?1/0:void 0,children:[(0,Q.jsxs)(`div`,{className:`grid gap-1`,children:[(0,Q.jsxs)(Dm,{className:`flex items-center gap-2`,children:[e.busy&&(0,Q.jsx)(Et,{className:`h-3.5 w-3.5 shrink-0 animate-spin`}),e.title]}),e.description!=null&&(0,Q.jsx)(Om,{children:e.description})]}),e.busy&&e.action&&(0,Q.jsx)(`button`,{type:`button`,className:`shrink-0 rounded-md border px-2 py-1 text-xs hover:bg-secondary`,onClick:e.action.onClick,children:e.action.label}),!e.busy&&(0,Q.jsx)(Em,{})]},e.id)),(0,Q.jsx)(Sm,{})]})})}function Km({children:e}){let[t]=(0,Z.useState)(Pm),[n,r]=(0,Z.useState)([]),[i,a]=(0,Z.useState)(!0),[o,s]=(0,Z.useState)(!1),{showToast:c}=xn();(0,Z.useEffect)(()=>{let e=!0,n=0,i=async()=>{let i=++n;try{let o=await zm(t);e&&i===n&&(r(o),a(!1))}catch{e&&(s(!0),a(!1))}},o=Rm(t,e=>{s(e),e||i()});return i(),()=>{e=!1,o()}},[t]),(0,Z.useEffect)(()=>X.on(`notification`,e=>{let t=e;!t||![`string`,`number`].includes(typeof t.id)||typeof t.text!=`string`||!t.text||c({title:`Notification`,description:t.text,historyId:`message:${t.id}`,timestamp:typeof t.timestamp==`string`?t.timestamp:void 0})}),[c]);let l=(0,Z.useCallback)(async()=>{try{await Wm(t)}catch{}},[t]),u=(0,Z.useCallback)(async e=>{try{await Um(t,e)}catch{}},[t]);return(0,Q.jsx)(ef.Provider,{value:{notifications:n,loading:i,storageError:o,clear:l,remove:u},children:e})}function qm(e,t,n){let r=Promise.resolve();return i=>{let a=r.then(async()=>{let r=await e(),a=i(r.home?.pinnedCanvases??[]);n(await t({...r,home:{...r.home,pinnedCanvases:a}}))});return r=a.catch(()=>{}),a}}function Jm(e,t){return e.minimized===!0||t.has(e.id)}var Ym=e=>`${e.workspaceName}\0${e.treeName}\0${e.path}`;function Xm({children:e}){let[t,n]=(0,Z.useState)(null),[r,i]=(0,Z.useState)(!0);(0,Z.useEffect)(()=>{let e=!1;return Al().then(t=>{e||n(t)}).catch(()=>{e||n({})}).finally(()=>{e||i(!1)}),()=>{e=!0}},[]);let a=(0,Z.useMemo)(()=>t?.home?.pinnedCanvases??[],[t]),[o]=(0,Z.useState)(()=>qm(Al,jl,n)),s=(0,Z.useCallback)(e=>a.some(t=>Ym(t)===Ym(e)),[a]),c=(0,Z.useCallback)(async e=>{let t=crypto.randomUUID();await o(n=>n.some(t=>Ym(t)===Ym(e))?n:[...n,{id:t,...e}])},[o]),l=(0,Z.useCallback)(async e=>{await o(t=>t.filter(t=>t.id!==e))},[o]),u=(0,Z.useCallback)(async(e,t)=>{await o(n=>n.map(n=>n.id===e?{...n,minimized:t}:n))},[o]),d=(0,Z.useCallback)(async(e,t)=>{await o(n=>{let r=n.find(t=>t.id===e);if(!r||e===t)return n;let i=n.filter(t=>t.id!==e),a=t===null?i.length:i.findIndex(e=>e.id===t);return a===-1?n:[...i.slice(0,a),r,...i.slice(a)]})},[o]),f=(0,Z.useMemo)(()=>({pins:a,isLoading:r,isPinned:s,pin:c,unpin:l,movePin:d,setMinimized:u}),[a,r,s,c,l,d,u]);return(0,Q.jsx)(yr.Provider,{value:f,children:e})}var Zm=[{id:`canvas`,name:`Canvas`,description:`Black and white with a teal accent. Sheets of paper on a grey desk.`,swatches:[`oklch(1 0 0)`,`oklch(0 0 0)`,`oklch(0.704 0.135 183)`]},{id:`nord`,name:`Nord`,description:`Cool arctic blues, lower contrast, softer corners.`,swatches:[`oklch(0.976 0.006 251)`,`oklch(0.588 0.056 244)`,`oklch(0.686 0.062 213)`]},{id:`contrast`,name:`High Contrast`,description:`WCAG AAA text contrast, square corners, hard borders, no shadows.`,swatches:[`oklch(1 0 0)`,`oklch(0 0 0)`,`oklch(0.32 0.16 258)`]},{id:`frost`,name:`Frosted Glass`,description:`Translucent, blurred surfaces over a soft backdrop. Best with a wallpaper.`,swatches:[`oklch(0.92 0.008 250)`,`oklch(0.31 0.025 255)`,`oklch(0.55 0.05 250)`]},{id:`terminal`,name:`Terminal`,description:`Monospaced and dense. Tighter rows and chrome for large displays.`,swatches:[`oklch(0.17 0.006 152)`,`oklch(0.8 0.19 148)`,`oklch(0.75 0.12 220)`]},{id:`halflife`,name:`Half-Life`,description:`Lambda orange on black steel. Square corners; the left rail is orange.`,swatches:[`oklch(0.724 0.181 52)`,`oklch(0 0 0)`,`oklch(1 0 0)`]}],Qm=Zm.map(e=>e.id),$m=[{id:`system`,name:`System`},{id:`light`,name:`Light`},{id:`dark`,name:`Dark`}],eh=[{id:`auto`,name:`Auto`,description:`Match the pointer: touch on phones, mouse on desktop`},{id:`compact`,name:`Compact`,description:`Maximum rows per screen`},{id:`comfortable`,name:`Comfortable`,description:`Balanced for mouse use`},{id:`touch`,name:`Touch`,description:`Large targets for finger input`}],th={theme:`canvas`,scheme:`light`,density:`auto`},nh=`canvas.ui.theme`;function rh(e){return typeof e==`string`&&Qm.includes(e)}function ih(e){return e===`light`||e===`dark`||e===`system`}function ah(e){return e===`auto`||e===`compact`||e===`comfortable`||e===`touch`}function oh(e){let t=typeof e==`object`&&e?e:{};return{theme:rh(t.theme)?t.theme:th.theme,scheme:ih(t.scheme)?t.scheme:th.scheme,density:ah(t.density)?t.density:th.density}}var sh=`(prefers-color-scheme: dark)`;function ch(){return typeof document<`u`}function lh(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(sh).matches}function uh(e){return e===`system`?lh()?`dark`:`light`:e}function dh(e){if(typeof window>`u`||typeof window.matchMedia!=`function`)return()=>{};let t=window.matchMedia(sh),n=t=>e(t.matches?`dark`:`light`);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)}function fh(e){return dh(e)}function ph(){return lh()?`dark`:`light`}function mh(){return`light`}function hh(e){let t=getComputedStyle(e).getPropertyValue(`--background`).trim();if(!t)return;let n=document.querySelector(`meta[name="theme-color"]`);n||(n=document.createElement(`meta`),n.name=`theme-color`,document.head.appendChild(n)),n.content=t}function gh(e,t=ch()?document.documentElement:void 0){let n=uh(e.scheme);return t?(t.dataset.theme=e.theme,t.dataset.scheme=n,t.dataset.density=e.density,hh(t),n):n}function _h(e,t=ch()?document.documentElement:void 0){if(!t||typeof window>`u`)return gh(e,t);let n=document.createElement(`style`);n.appendChild(document.createTextNode(`*,*::before,*::after{transition:none!important;animation:none!important}`)),document.head.appendChild(n);let r=gh(e,t);return window.getComputedStyle(n).opacity,document.head.removeChild(n),r}function vh(e){let t=e??xh();if(!t)return th;try{let e=t.getItem(nh);return e?oh(JSON.parse(e)):th}catch{return th}}function yh(e,t){let n=t??xh();if(n)try{n.setItem(nh,JSON.stringify(e))}catch{}}function bh(e){let t=e??xh();if(t)try{t.removeItem(nh)}catch{}}function xh(){try{return typeof localStorage<`u`?localStorage:void 0}catch{return}}function Sh({children:e,initial:t,storage:n,persist:r=!0}){let[i,a]=(0,Z.useState)(()=>({...vh(n),...t})),o=(0,Z.useSyncExternalStore)(fh,ph,mh),s=i.scheme===`system`?o:i.scheme;(0,Z.useEffect)(()=>{_h({...i,scheme:s})},[i,s]),(0,Z.useEffect)(()=>{r&&yh(i,n)},[i,r,n]);let c=(0,Z.useCallback)(e=>{a(t=>t.theme===e?t:{...t,theme:e})},[]),l=(0,Z.useCallback)(e=>{a(t=>t.scheme===e?t:{...t,scheme:e})},[]),u=(0,Z.useCallback)(e=>{a(t=>t.density===e?t:{...t,density:e})},[]),d=(0,Z.useCallback)(()=>{a(e=>({...e,scheme:(e.scheme===`system`?ph():e.scheme)===`dark`?`light`:`dark`}))},[]),f=(0,Z.useCallback)(()=>{bh(n),a(th)},[n]),p=(0,Z.useMemo)(()=>({...i,resolvedScheme:s,setTheme:c,setScheme:l,setDensity:u,toggleScheme:d,reset:f}),[i,s,c,l,u,d,f]);return(0,Q.jsx)(Da.Provider,{value:p,children:e})}var Ch=(0,Z.lazy)(()=>c(()=>import(`./NextShell-BfQHKEKO.js`),__vite__mapDeps([128,1,2,7,8,9,10,6,5,11,12,13,129])));function wh(){let{showToast:e}=xn();return(0,Z.useEffect)(()=>{cn((t,n)=>{e({title:`Error`,description:n?`${t.message} (${n})`:t.message,variant:`destructive`})})},[e]),(0,Z.useEffect)(()=>vs(),[]),(0,Q.jsxs)(y,{children:[(0,Q.jsx)(ls,{}),(0,Q.jsx)(So,{}),(0,Q.jsxs)(T,{children:[(0,Q.jsx)(d,{path:`/login`,element:(0,Q.jsx)(Za,{children:(0,Q.jsx)(qa,{})})}),(0,Q.jsx)(d,{path:`/register`,element:(0,Q.jsx)(Za,{children:(0,Q.jsx)(Ja,{})})}),(0,Q.jsx)(d,{path:`/auth/google/callback`,element:(0,Q.jsx)(Za,{children:(0,Q.jsx)(Ya,{})})}),(0,Q.jsx)(d,{path:`/pub/c/:code`,element:(0,Q.jsx)(lo,{})}),(0,Q.jsx)(d,{path:`/next/*`,element:(0,Q.jsx)(Xa,{children:(0,Q.jsx)(Z.Suspense,{fallback:null,children:(0,Q.jsx)(Ch,{})})})}),(0,Q.jsx)(d,{path:`/`,element:(0,Q.jsx)(Xa,{children:(0,Q.jsx)(Km,{children:(0,Q.jsx)(Xm,{children:(0,Q.jsx)(bm,{})})})}),children:is}),(0,Q.jsx)(d,{path:`*`,element:(0,Q.jsx)(u,{to:`/`,replace:!0})})]})]})}function Th(){return(0,Q.jsx)(Sh,{children:(0,Q.jsx)(Gm,{children:(0,Q.jsx)(wh,{})})})}var Eh=[{id:`canvas_1`,title:`Canvas Deep`,scheme:`dark`,background:`#032940`,accent:`#f2f2f2`,sources:[{type:`image/svg+xml`,src:`files/canvas_1.svg`},{type:`image/avif`,src:`files/canvas_1.avif`},{type:`image/webp`,src:`files/canvas_1.webp`}],thumb:`thumbs/canvas_1.webp`,author:`Canvas`,license:`LicenseRef-Canvas-Brand`},{id:`canvas_3`,title:`Canvas Mono Dark`,scheme:`dark`,background:`#000000`,accent:`#ffffff`,sources:[{type:`image/svg+xml`,src:`files/canvas_3.svg`},{type:`image/avif`,src:`files/canvas_3.avif`},{type:`image/webp`,src:`files/canvas_3.webp`}],thumb:`thumbs/canvas_3.webp`,author:`Canvas`,license:`LicenseRef-Canvas-Brand`},{id:`w1`,title:`Frost`,scheme:`dark`,background:`#164a6f`,accent:`#9ad9f0`,sources:[{type:`image/avif`,src:`files/w1.avif`},{type:`image/webp`,src:`files/w1.webp`},{type:`image/jpeg`,src:`files/w1.jpg`}],thumb:`thumbs/w1.webp`,author:`Peter Cui Bide`,source:`https://petercui.deviantart.com`,license:`LicenseRef-Attribution-Only`}],Dh=`/wallpapers`;function Oh(e){return Eh.find(t=>t.id===e)}function kh(e,t={}){let n=typeof e==`string`?Oh(e):e;if(!n)return null;let{base:r=Dh,types:i}=t,a=(i?n.sources.find(e=>i.includes(e.type)):n.sources[0])??n.sources[n.sources.length-1];return`${r.replace(/\/$/,``)}/${a.src}`}function Ah(e,t=Dh){let n=typeof e==`string`?Oh(e):e;return n?`${t.replace(/\/$/,``)}/${n.thumb}`:null}var jh=[{id:`cover`,label:`Scale and Crop`,description:`Fills the screen, cropping edges as needed`},{id:`fill`,label:`Fill`,description:`Stretches to the exact screen size`},{id:`center`,label:`Centered`,description:`Original size, centered on the desk`}],Mh=`canvas:wallpaper`,Nh=`canvas-wallpaper`,Ph=`settings`,Fh=`builtin:`,Ih=Eh;function Lh(e){return Ah(e)??``}function Rh(e){return`${Fh}${e}`}function zh(e){return e?.startsWith(Fh)?e.slice(8):null}function Bh(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.image!=`string`&&t.image!==null?null:{image:t.image,fit:t.fit===`fill`||t.fit===`center`?t.fit:`cover`}}function Vh(){try{let e=localStorage.getItem(Mh);if(e){let t=Bh(JSON.parse(e));if(t)return t}}catch{}return{image:null,fit:`cover`}}var Hh=Vh(),Uh=null;function Wh(){return Hh}async function Gh(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(Nh,1),r=!1;n.onupgradeneeded=()=>n.result.createObjectStore(Ph),n.onsuccess=()=>{if(r){n.result.close();return}n.result.onversionchange=()=>n.result.close(),e(n.result)},n.onerror=()=>t(n.error),n.onblocked=()=>{r=!0,t(Error(`Close other Canvas tabs and try again.`))}});try{return await new Promise((n,r)=>{let i=t.transaction(Ph,e?`readwrite`:`readonly`),a=i.objectStore(Ph),o=e?a.put(e,Mh):a.get(Mh);i.oncomplete=()=>n(o.result),i.onerror=()=>r(i.error),i.onabort=()=>r(i.error)})}finally{t.close()}}function Kh(){try{localStorage.removeItem(Mh)}catch{}}function qh(){return Uh||=(async()=>{try{let e=Bh(await Gh());e?Hh=e:await Gh(Hh),Kh()}catch{}return tg(Hh),Hh})(),Uh.then(()=>Hh)}async function Jh(e){await qh(),await Gh(e),Hh=e,Kh(),tg(e)}function Yh(e){if(e.size>10485760)return Promise.reject(Error(`Image too large. Choose one up to 10 MB.`));let t=e.type||(/\.gif$/i.test(e.name)?`image/gif`:``);return t.startsWith(`image/`)?new Promise((n,r)=>{let i=new FileReader;i.onload=()=>n(String(i.result)),i.onerror=()=>r(Error(`Could not read the image. Try selecting it again.`)),i.onabort=()=>r(Error(`Reading the image was cancelled.`)),i.readAsDataURL(e.type?e:e.slice(0,e.size,t))}):Promise.reject(Error(`Pick an image file (animated GIFs are supported).`))}var Xh=typeof CSS<`u`&&CSS.supports(`background-image`,`image-set(url("a.avif") type("image/avif"))`);function Zh(e){if(!e)return null;let t=zh(e);if(t===null)return`url("${e}")`;let n=Oh(t);if(!n)return null;let r=`url("${kh(n,{types:[n.sources[n.sources.length-1].type]})}")`;return!Xh||n.sources.length===1?r:`image-set(${n.sources.map(e=>`url("${kh(n,{types:[e.type]})}") type("${e.type}")`).join(`, `)})`}function Qh(e){return e===`fill`?`100% 100%`:e===`center`?`auto`:`cover`}var $h=null;function eg(e){let t=e.indexOf(`,`);if(t<0)throw Error(`Invalid wallpaper data URL`);let n=e.slice(5,t),r=e.slice(t+1),i;if(n.endsWith(`;base64`)){let e=atob(r);i=new Uint8Array(e.length);for(let t=0;t<e.length;t++)i[t]=e.charCodeAt(t)}else i=new TextEncoder().encode(decodeURIComponent(r));return new Blob([i],{type:n.split(`;`)[0]})}function tg(e=Wh()){let t=document.documentElement.style,n=$h,r=e.image;if(r?.startsWith(`data:`))try{$h?.dataUrl!==r&&($h={dataUrl:r,objectUrl:URL.createObjectURL(eg(r))}),r=$h.objectUrl}catch{$h=null,r=null}else $h=null;let i=Zh(r);i?(t.setProperty(`--wallpaper-image`,i),t.setProperty(`--wallpaper-size`,Qh(e.fit))):(t.removeProperty(`--wallpaper-image`),t.removeProperty(`--wallpaper-size`)),n&&n!==$h&&URL.revokeObjectURL(n.objectUrl)}tg(),qh(),(0,Oa.createRoot)(document.getElementById(`root`)).render((0,Q.jsx)(Z.StrictMode,{children:(0,Q.jsx)(Th,{})}));export{uu as $,Dd as A,Ua as At,Iu as B,If as C,mc as Ct,Sf as D,Js as Dt,xf as E,Xs as Et,Mu as F,ja as Ft,Au as G,hu as H,ju as I,Su as J,pu as K,Nu as L,Sd as M,Na as Mt,yd as N,Ma as Nt,Ld as O,Zs as Ot,Vu as P,Aa as Pt,du as Q,Tu as R,Vf as S,fc as St,Af as T,Ys as Tt,cu as U,ru as V,gu as W,wu as X,mu as Y,fu as Z,Lp as _,jc as _t,Lh as a,kl as at,Bf as b,Nc as bt,qh as c,ll as ct,Qh as d,Uc as dt,lu as et,eh as f,Kc as ft,Rp as g,Pc as gt,Jm as h,Ic as ht,Rh as i,Ol as it,Td as j,ka as jt,jd as k,ms as kt,Jh as l,_l as lt,Zm as m,zc as mt,jh as n,ku as nt,Wh as o,bl as ot,$m as p,qc as pt,Cu as q,zh as r,Eu as rt,Yh as s,ml as st,Ih as t,Ou as tt,Zh as u,dl as ut,Op as v,Lc as vt,Ff as w,ac as wt,Uf as x,oc as xt,Zf as y,Fc as yt,Du as z};
16
+ `);c=t.pop()??``;for(let e of t){if(!e.startsWith(`data: `))continue;let t=e.slice(6).trim();if(t===`[DONE]`)return;try{let e=JSON.parse(t);if(e.type===`chunk`)l+=e.delta||``,n(e=>{let t=[...e];return t[t.length-1]={role:`assistant`,content:l,isComplete:!1,...u?{reasoning:u}:{},...d?{metadata:d}:{}},t});else if(e.type===`thinking`)u=`${u}${e.delta||``}`.trim(),n(e=>{let t=[...e],n=t[t.length-1]?.content||l;return t[t.length-1]={role:`assistant`,content:n,isComplete:!1,...u?{reasoning:u}:{},...d?{metadata:d}:{}},t});else if(e.type===`complete`){let t=Array.isArray(e.messages)?[...e.messages].reverse().find(e=>e?.role===`assistant`):null,r=Mp(t),i=nu(t)||u;d=ru(t),n(e=>{let t=[...e],n=l||t[t.length-1]?.content||``;return t[t.length-1]={role:`assistant`,content:r||n,isComplete:!0,...i?{reasoning:i}:{},...d?{metadata:d}:{}},t})}else e.type===`error`&&o(e.error)}catch{}}},onError:e=>{e.name!==`AbortError`&&o(e.message)},onComplete:()=>{n(e=>{let t=[...e],n=t[t.length-1];return n&&!n.isComplete&&(t[t.length-1]={...n,isComplete:!0}),t}),i(!1)}})}catch(e){let t=e instanceof Error?e:null;t?.name!==`AbortError`&&o(t?.message??`Stream failed`),n(e=>{let t=[...e],n=t[t.length-1];return n&&!n.isComplete&&(t[t.length-1]={...n,isComplete:!0}),t}),i(!1)}},[e,r]),sendVoice:(0,Z.useCallback)(async(t,a)=>{if(!(r||!e)){o(null),i(!0),n(e=>[...e,{role:`user`,content:`🎤 Transcribing…`,isComplete:!1}]);try{let r=await Fu(e,t,{viewContext:a});n(e=>{let t=[...e];return t[t.length-1]={role:`user`,content:`🎤 ${r.transcript}`,isComplete:!0},[...t,{role:`assistant`,content:r.reply,isComplete:!0}]}),r.audio&&r.audioMimeType&&new Audio(`data:${r.audioMimeType};base64,${r.audio}`).play().catch(()=>{})}catch(e){o(e instanceof Error?e.message:`Voice prompt failed`),n(e=>{let t=[...e],n=t[t.length-1];return n?.role===`user`&&!n.isComplete&&t.pop(),t})}finally{i(!1)}}},[e,r]),stop:(0,Z.useCallback)(()=>{s.current?.abort(),i(!1)},[]),clear:(0,Z.useCallback)(()=>{n([]),o(null)},[])}}function Pp(){let[e,t]=(0,Z.useState)(!1),[n,r]=(0,Z.useState)(null),i=(0,Z.useRef)(null),a=(0,Z.useRef)([]);return{isRecording:e,recorderError:n,start:(0,Z.useCallback)(async()=>{if(!i.current){if(r(null),!navigator.mediaDevices?.getUserMedia||typeof MediaRecorder>`u`){r(`Audio recording is not supported in this browser`);return}try{let e=await navigator.mediaDevices.getUserMedia({audio:!0}),n=MediaRecorder.isTypeSupported(`audio/webm;codecs=opus`)?`audio/webm;codecs=opus`:void 0,r=new MediaRecorder(e,n?{mimeType:n}:void 0);a.current=[],r.ondataavailable=e=>{e.data.size>0&&a.current.push(e.data)},r.start(),i.current=r,t(!0)}catch(e){let t=e instanceof Error?e:null;r(t?.name===`NotAllowedError`?`Microphone access denied`:t?.message??`Could not start recording`)}}},[]),stop:(0,Z.useCallback)(()=>{let e=i.current;return e?new Promise(n=>{e.onstop=()=>{e.stream.getTracks().forEach(e=>e.stop()),i.current=null,t(!1);let r=e.mimeType||`audio/webm`,o=new Blob(a.current,{type:r});a.current=[],n(o.size>0?o:null)},e.stop()}):Promise.resolve(null)},[]),cancel:(0,Z.useCallback)(()=>{let e=i.current;e&&(e.onstop=()=>{e.stream.getTracks().forEach(e=>e.stop())},e.stop(),i.current=null,a.current=[],t(!1))},[])}}function Fp(e){let t=e?.usage;if(!t)return null;let n=t.totalTokens,r=t.input,i=t.output;return typeof n==`number`&&typeof r==`number`&&typeof i==`number`?`${n} tok (${r} in / ${i} out)`:typeof n==`number`?`${n} tok`:null}function Ip(e){let t=e?.usage?.cost?.total;return typeof t==`number`?`$${t.toFixed(t<.01?6:4)}`:null}function Lp({reasoning:e,metadata:t,isStreaming:n=!1,compact:r=!1}){let i=t?.model,a=[t?.provider,i,Fp(t),Ip(t)].filter(Boolean);return!e&&a.length===0?null:(0,Q.jsxs)(Q.Fragment,{children:[e&&(0,Q.jsxs)(`details`,{open:n,className:`mb-2 rounded border border-border bg-background ${r?`px-2 py-1.5`:`px-3 py-2`}`,children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer font-medium text-foreground ${r?`text-[11px]`:`text-xs`}`,children:`Reasoning`}),(0,Q.jsx)(Hr,{content:e,className:`mt-1 text-foreground ${r?`text-[11px]`:`text-xs`}`})]}),a.length>0&&(0,Q.jsx)(`div`,{className:`mt-2 text-muted-foreground ${r?`text-[11px]`:`text-xs`}`,children:a.join(` • `)})]})}function Rp({text:e}){let[t,n]=(0,Z.useState)(null),r=(0,Z.useRef)(null);if((0,Z.useEffect)(()=>()=>{r.current&&clearTimeout(r.current)},[]),!e)return null;let i=t?.text===e?t.status:null;return(0,Q.jsx)(`button`,{type:`button`,"aria-label":`Copy reply text`,title:`Copy reply text`,className:`rounded px-1.5 py-1 text-[11px] text-muted-foreground hover:bg-accent hover:text-foreground [@media(hover:hover)]:opacity-0 group-hover/agent-reply:opacity-100 focus-visible:opacity-100`,onClick:async()=>{r.current&&clearTimeout(r.current);try{await navigator.clipboard.writeText(e),n({text:e,status:`copied`})}catch{n({text:e,status:`error`})}r.current=setTimeout(()=>n(null),2e3)},children:(0,Q.jsx)(`span`,{"aria-live":`polite`,children:i===`copied`?`Copied`:i===`error`?`Copy failed — retry`:`+ Copy text`})})}function zp({agentId:e,onClose:t}){let[n,r]=(0,Z.useState)(null),[i,a]=(0,Z.useState)(``),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(null),{showToast:m}=xn(),g=ni(),_=h(),v=g?.agentView?.pathname===_.pathname?g.agentView.view:null,y=g?.state.activeContextType===`context`?g.state.activeContextId:null,b=g?.state.activeContextPath??null,x=(0,Z.useRef)(null),S=(0,Z.useRef)(null),{messages:C,isStreaming:w,error:T,send:E,sendVoice:O,stop:k,clear:A}=Np(e),{isRecording:j,recorderError:M,start:N,stop:ee}=Pp();(0,Z.useEffect)(()=>{hu(e).then(r).catch(()=>{}),cu(e).then(l).catch(()=>l(null))},[e]),(0,Z.useEffect)(()=>{Pu().then(e=>s(!!(e.enabled&&e.stt))).catch(()=>s(!1))},[]),(0,Z.useEffect)(()=>{C.length!==0&&x.current?.scrollIntoView({behavior:`smooth`})},[C]);let P=!!(y&&c?.grants.some(e=>e.binding.type===`context`&&e.binding.context===y)),F=c?.grants.length?`Connections: ${c.grants.map(e=>e.label||e.id).join(`, `)}`:`no canvas access`,te=async()=>{if(!y||u)return;let t=y||b;if(window.confirm(`Add the current context (${t}) to "${n?.label||n?.name||e}"? Other connections remain unchanged. This restarts the agent if it is running.`)){d(!0);try{let t=await lu(e,`context-${crypto.randomUUID()}`,{label:`Context ${y}`,binding:{type:`context`,context:y},permissions:[`read`,`write`]});l(t.access),p(t.tokens[0]?.token??null)}catch(e){m({title:`Error`,description:e instanceof Error?e.message:`Bind failed`,variant:`destructive`})}finally{d(!1)}}},ne=async()=>{let e=i.trim();!e||w||(a(``),S.current?.focus(),await E(e,v))};return(0,Q.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 px-3 h-12 border-b border-border shrink-0`,children:[(0,Q.jsx)(`button`,{type:`button`,onClick:t,className:`p-1 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Back to agents`,children:(0,Q.jsx)(Tt,{className:`w-4 h-4`})}),n?.color&&(0,Q.jsx)(`span`,{className:`w-2.5 h-2.5 rounded-full shrink-0`,style:{backgroundColor:n.color}}),(0,Q.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Q.jsx)(`div`,{className:`text-sm font-medium truncate`,children:n?.label||n?.name||e}),(0,Q.jsx)(`div`,{className:`text-[10px] leading-tight text-muted-foreground truncate`,title:F,children:F})]}),(0,Q.jsx)(`button`,{type:`button`,onClick:A,className:`p-1 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Clear chat`,children:(0,Q.jsx)(W,{className:`w-3.5 h-3.5`})})]}),y&&!P&&(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 border-b border-border bg-muted/40 text-xs shrink-0`,children:[(0,Q.jsxs)(`span`,{className:`flex-1 truncate text-muted-foreground`,title:y||b||void 0,children:[`Toolbox context: `,y||b]}),(0,Q.jsx)(`button`,{type:`button`,disabled:u,onClick:te,className:`shrink-0 rounded border border-input px-2 py-1 hover:bg-accent disabled:opacity-50`,children:u?`Binding…`:`Add this context`})]}),f&&(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 border-b border-border bg-warning/10 text-xs shrink-0`,children:[(0,Q.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,children:`Token (shown once):`}),(0,Q.jsx)(`code`,{className:`flex-1 truncate font-mono`,children:f}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>navigator.clipboard?.writeText(f),className:`shrink-0 rounded border border-input px-2 py-1 hover:bg-accent`,children:`Copy`}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>p(null),className:`shrink-0 rounded px-1.5 py-1 hover:bg-accent`,title:`Dismiss`,children:`×`})]}),(0,Q.jsxs)(`div`,{className:`flex-1 overflow-y-auto px-4 py-3 space-y-3`,children:[C.length===0&&(0,Q.jsx)(`div`,{className:`text-xs text-muted-foreground text-center py-10`,children:n?`Chat with ${n.label||n.name}`:`Loading…`}),C.map((e,t)=>(0,Q.jsxs)(`div`,{className:G(`group/agent-reply text-sm rounded-lg px-3 py-2 max-w-[85%] break-words`,e.role===`user`?`ml-auto bg-foreground text-background`:`mr-auto bg-muted text-foreground`),children:[(0,Q.jsx)(Lp,{reasoning:e.role===`assistant`?e.reasoning:void 0,metadata:e.role===`assistant`?e.metadata:void 0,isStreaming:!e.isComplete,compact:!0}),e.role===`assistant`?(0,Q.jsx)(Hr,{content:e.content||(e.isComplete?``:`…`)}):(0,Q.jsx)(`span`,{className:`whitespace-pre-wrap`,children:e.content}),e.role===`assistant`&&(0,Q.jsx)(`div`,{className:`flex justify-end`,children:(0,Q.jsx)(Rp,{text:e.content})})]},t)),(T||M)&&(0,Q.jsx)(`div`,{className:`text-xs text-destructive text-center py-1`,children:T||M}),(0,Q.jsx)(`div`,{ref:x})]}),(0,Q.jsx)(`div`,{className:`p-3 border-t border-border shrink-0`,children:(0,Q.jsxs)(`div`,{className:`flex gap-2 items-end`,children:[(0,Q.jsx)(`textarea`,{ref:S,value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),ne())},placeholder:`Message…`,rows:2,className:`flex-1 resize-y text-sm px-3 py-2 border border-input bg-background rounded-md focus:outline-none focus:ring-1 focus:ring-ring min-h-[38px] max-h-[120px]`}),o&&(0,Q.jsx)(`button`,{type:`button`,onClick:async()=>{if(j){let e=await ee();e&&await O(e,v)}else w||await N()},disabled:w&&!j,className:G(`flex items-center justify-center w-9 h-9 rounded-md transition-opacity shrink-0 disabled:opacity-40`,j?`bg-destructive text-destructive-foreground hover:opacity-90 animate-pulse`:`bg-muted text-foreground hover:bg-accent`),title:j?`Stop recording and send`:`Record a voice message`,children:j?(0,Q.jsx)(Ot,{className:`w-4 h-4`}):(0,Q.jsx)(D,{className:`w-4 h-4`})}),w?(0,Q.jsx)(`button`,{type:`button`,onClick:k,className:`flex items-center justify-center w-9 h-9 rounded-md bg-destructive text-destructive-foreground hover:opacity-90 transition-opacity shrink-0`,title:`Stop`,children:(0,Q.jsx)(Ot,{className:`w-4 h-4`})}):(0,Q.jsx)(`button`,{type:`button`,onClick:ne,disabled:!i.trim(),className:`flex items-center justify-center w-9 h-9 rounded-md bg-foreground text-background hover:opacity-90 disabled:opacity-40 transition-opacity shrink-0`,title:`Send`,children:(0,Q.jsx)(Bt,{className:`w-4 h-4`})})]})})]})}function Bp(){let{state:e,openApplet:t}=ti(),[n,r]=(0,Z.useState)(`context`),i=e.appsAppletId,a=i?ga.find(e=>e.id===i):null;if(a)return(0,Q.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Q.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-2 py-1.5`,children:[(0,Q.jsx)(`button`,{type:`button`,onClick:()=>t(null),className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Back to applets`,title:`Back to applets`,children:(0,Q.jsx)(Tt,{className:`h-4 w-4`})}),(0,Q.jsx)(a.icon,{className:`h-4 w-4 text-muted-foreground`}),(0,Q.jsx)(`span`,{className:`text-sm font-medium`,children:a.label})]}),(0,Q.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,Q.jsx)(a.Component,{})})]});let o=ha(n);return(0,Q.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Q.jsx)(`div`,{className:`flex shrink-0 border-b border-border`,children:[`context`,`global`].map(e=>(0,Q.jsx)(`button`,{type:`button`,onClick:()=>r(e),className:G(`flex-1 py-2.5 text-xs capitalize transition-colors`,n===e?`-mb-px border-b-2 border-foreground font-semibold text-foreground`:`font-medium text-muted-foreground hover:text-foreground`),children:e},e))}),(0,Q.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3`,children:[!o.length&&(0,Q.jsxs)(`p`,{className:`py-10 text-center text-sm text-muted-foreground`,children:[`No `,n,` applets yet.`]}),(0,Q.jsx)(`div`,{className:`grid grid-cols-2 gap-2`,children:o.map(e=>(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>t(e.id),className:`flex min-h-[4.5rem] flex-col items-center justify-center gap-1.5 rounded-(--card-radius) border border-border bg-muted/40 p-3 text-foreground transition-colors hover:bg-muted`,title:e.description,children:[(0,Q.jsx)(e.icon,{className:`h-5 w-5 text-muted-foreground`}),(0,Q.jsx)(`span`,{className:`text-xs font-medium leading-none`,children:e.label})]},e.id))})]})]})}var Vp=[{view:`apps`,icon:Ut,label:`Apps`},{view:`tools`,icon:Qe,label:`Filters`},{view:`agents`,icon:ye,label:`Agents`},{view:`notifications`,icon:Ge,label:`Notifications`}],Hp=340,Up=`toolbox:width`,Wp=360,Gp=48,Kp=e=>{let t=typeof window<`u`?window.innerWidth:1600,n=Math.max(Hp,Math.min(Math.round(t*.7),t-Gp-Wp));return Math.max(Hp,Math.min(e,n))},qp=()=>typeof window<`u`?Math.round(window.innerWidth/2):720;function Jp(){let{state:e,setView:t,closeT1:n,closeT2:r}=ti();hi(n,e.t1Open&&!e.t2Open),hi(r,e.t2Open);let{t1Open:i,t1View:a,t2Open:o,t2AgentId:s,activeAccentColor:c}=e,l=Pr(),[u,d]=(0,Z.useState)(()=>{let e=typeof window<`u`?Number(localStorage.getItem(Up)):NaN;return Number.isFinite(e)&&e>0?e:420}),f=(0,Z.useCallback)(e=>{d(e);try{localStorage.setItem(Up,String(e))}catch{}},[]),p=(0,Z.useRef)(null),m=(0,Z.useCallback)(e=>{e.preventDefault(),p.current={startX:e.clientX,startWidth:u};let t=e=>{if(!p.current)return;let t=Kp(p.current.startWidth-(e.clientX-p.current.startX));d(t)},n=()=>{p.current=null,window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n),d(e=>{try{localStorage.setItem(Up,String(e))}catch{}return e})};window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)},[u]),h=u>=qp()*.9;return(0,Z.useEffect)(()=>{let e=()=>d(e=>Kp(e));return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),!i||!a?null:(0,Q.jsxs)(Q.Fragment,{children:[l&&(0,Q.jsx)(`div`,{className:`fixed inset-0 z-panel-scrim bg-scrim animate-fade-in`,onClick:n,"aria-hidden":!0}),(0,Q.jsxs)(`div`,{style:l?void 0:{width:u},className:G(`flex flex-col overflow-hidden rounded-(--panel-radius) border bg-card surface-glass text-foreground`,l?`fixed bottom-2 left-2 right-2 top-2 z-panel shadow-elevation-5 animate-fade-in`:`relative shrink-0 shadow-elevation-3`),children:[!l&&(0,Q.jsx)(`div`,{onMouseDown:m,className:`absolute left-0 top-0 z-20 h-full w-1.5 cursor-col-resize hover:bg-primary/20`,title:`Drag to resize`,"aria-hidden":!0}),(0,Q.jsxs)(`div`,{className:`flex h-[calc(3rem-1px)] shrink-0 items-center justify-between gap-1 border-b-4 px-2`,style:c?{borderBottomColor:c}:void 0,children:[(0,Q.jsx)(`div`,{className:`flex items-center gap-1`,children:Vp.map(({view:e,icon:n,label:r})=>(0,Q.jsx)(`button`,{type:`button`,onClick:()=>t(e),"aria-label":r,title:r,className:G(`flex h-10 w-11 items-center justify-center rounded-md transition-colors`,a===e?`bg-muted text-foreground`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:(0,Q.jsx)(n,{className:`h-4 w-4 shrink-0`})},e))}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[!l&&(0,Q.jsx)(`button`,{type:`button`,onClick:()=>f(h?420:Kp(qp())),className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,"aria-label":h?`Shrink toolbox`:`Expand toolbox`,title:h?`Shrink toolbox`:`Expand to half screen`,children:h?(0,Q.jsx)(be,{className:`h-4 w-4`}):(0,Q.jsx)(Ke,{className:`h-4 w-4`})}),(0,Q.jsx)(`button`,{type:`button`,onClick:n,className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,"aria-label":`Close toolbox`,children:(0,Q.jsx)(z,{className:`h-4 w-4`})})]})]}),(0,Q.jsxs)(`div`,{className:`relative flex min-h-0 flex-1 flex-col`,children:[(0,Q.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col ${o&&s?`invisible`:``}`,children:[a===`home`&&(0,Q.jsx)(nf,{}),a===`apps`&&(0,Q.jsx)(Bp,{}),a===`tools`&&(0,Q.jsx)(Op,{}),a===`agents`&&(0,Q.jsx)(Ap,{}),a===`notifications`&&(0,Q.jsx)(jp,{})]}),o&&s&&(0,Q.jsx)(`div`,{className:`absolute inset-0 z-10 flex flex-col bg-background`,children:(0,Q.jsx)(zp,{agentId:s,onClose:r})})]})]})]})}function Yp(){let{running:e,hasViewer:t,paused:n,snapshot:r,source:i,lastCount:a,error:o,setPaused:s,stop:c,reopen:l}=xf();if(!e||t)return null;let u=i===`screen`?Le:i===`photo`?fe:re;return(0,Q.jsxs)(`div`,{className:G(`fixed right-4 w-56 overflow-hidden rounded-(--panel-radius) border border-border bg-card shadow-elevation-4 z-panel animate-fade-in`,`bottom-fab-inset md:bottom-[calc(var(--spacing-fab-inset)+5rem)]`),role:`status`,"aria-label":`Lens feed running`,children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:l,title:`Back to Lens`,className:`relative block w-full cursor-pointer bg-black/80 aspect-video`,children:[(0,Q.jsx)(Ff,{className:`h-full w-full`}),r&&(0,Q.jsx)(`img`,{src:r,alt:``,className:`absolute inset-0 h-full w-full bg-black object-contain`}),n&&(0,Q.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center bg-black/50 text-xs font-medium text-white`,children:`paused`})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-1 px-2 py-1.5`,children:[(0,Q.jsx)(u,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Q.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-[11px] text-muted-foreground`,children:o?(0,Q.jsx)(`span`,{className:`text-destructive`,children:o}):n?`paused`:r?`${i===`photo`?`photo`:`snapshot`} · ${a??`…`} match${a===1?``:`es`}`:`live · ${a??`…`} match${a===1?``:`es`}`}),i!==`photo`&&(0,Q.jsx)(`button`,{type:`button`,onClick:()=>s(!n),"aria-label":n?`Resume Lens`:`Pause Lens`,title:n?`Resume searching`:`Pause searching (camera stays on)`,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:n?(0,Q.jsx)(le,{className:`h-3.5 w-3.5`}):(0,Q.jsx)(Ae,{className:`h-3.5 w-3.5`})}),(0,Q.jsx)(`button`,{type:`button`,onClick:l,"aria-label":`Reopen Lens panel`,title:`Reopen Lens`,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:(0,Q.jsx)(Ke,{className:`h-3.5 w-3.5`})}),(0,Q.jsx)(`button`,{type:`button`,onClick:c,"aria-label":`Stop Lens feed`,title:`Stop the feed`,className:`rounded p-1 text-destructive transition-colors hover:bg-destructive/10`,children:(0,Q.jsx)(pe,{className:`h-3.5 w-3.5`})})]})]})}var Xp=[`view`,`location`,`metadata`,`json`,`synapses`,`backends`];function Zp(e){let t=new URLSearchParams(e.replace(/^#/,``)),n=t.get(`document`)??``,r=t.get(`workspace`);if(!r||!/^\d+$/.test(n)||!Number.isSafeInteger(Number(n))||Number(n)<=0)return null;let i=t.get(`section`);return{workspaceId:r,documentId:Number(n),section:Xp.includes(i)?i:`view`,maximized:t.get(`fullscreen`)===`1`}}function Qp(e){let t=new URLSearchParams({document:String(e.documentId),workspace:e.workspaceId});return e.section!==`view`&&t.set(`section`,e.section),e.maximized&&t.set(`fullscreen`,`1`),`#${t}`}function $p({children:e}){let t=h(),n=m(),r=(0,Z.useMemo)(()=>Zp(t.hash),[t.hash]),i=r?.workspaceId,a=r?.documentId,o=i&&a?JSON.stringify([i,a]):null,[s,c]=(0,Z.useState)(0),[l,u]=(0,Z.useState)(null),d=l?.key===o&&l?.revision===s?l:null;(0,Z.useEffect)(()=>{if(!o||!i||!a||d)return;let e=!1;return pr(i,a).then(t=>{e||u({key:o,revision:s,document:t,error:t?void 0:`Document not found.`})}).catch(t=>{e||u({key:o,revision:s,document:null,error:t?.statusCode===404?`Document not found.`:`Unable to load this document.`})}),()=>{e=!0}},[o,i,a,s,d]);let f=(0,Z.useCallback)((e,r)=>{u({key:JSON.stringify([r,e.id]),revision:s,document:e}),n({pathname:t.pathname,search:t.search,hash:Qp({workspaceId:r,documentId:e.id,section:`view`,maximized:!1})},{state:t.state})},[n,t.pathname,t.search,t.state,s]),p=(0,Z.useCallback)(()=>{r&&n({pathname:t.pathname,search:t.search,hash:``},{replace:!0,state:t.state})},[r,n,t.pathname,t.search,t.state]),g=(0,Z.useCallback)((e,i)=>{r&&(u({key:JSON.stringify([i,e.id]),revision:s,document:e}),n({pathname:t.pathname,search:t.search,hash:Qp({...r,workspaceId:i,documentId:e.id})},{replace:!0,state:t.state}))},[r,s,n,t.pathname,t.search,t.state]),_=(0,Z.useCallback)(e=>{r&&n({pathname:t.pathname,search:t.search,hash:Qp({...r,...e})},{replace:!0,state:t.state})},[r,n,t.pathname,t.search,t.state]),v=(0,Z.useCallback)(()=>c(e=>e+1),[]),y=(0,Z.useMemo)(()=>({entry:d?.document&&i?{document:d.document,workspaceId:i}:null,location:r,loading:!!r&&!d,error:d?.error,open:f,replace:g,close:p,update:_,retry:v}),[d,i,r,f,g,p,_,v]);return(0,Q.jsx)(br.Provider,{value:y,children:e})}function em({children:e}){let[t,n]=(0,Z.useState)(null),r=(0,Z.useCallback)((e,t)=>n({document:e,workspaceId:t}),[]),i=(0,Z.useCallback)(()=>n(null),[]),a=(0,Z.useMemo)(()=>({open:r,close:i}),[r,i]);return(0,Q.jsxs)(Ii.Provider,{value:a,children:[e,(0,Q.jsx)(Mr,{document:t?.document??null,isOpen:!!t,onClose:i,workspaceId:t?.workspaceId})]})}var tm={key:`desk`,label:`Desk`,main:`/`,mainExpanded:!1,entries:[]},nm=0,rm=()=>`c${++nm}`;function im(e,t){return e.kind===`route`&&t.kind===`route`?e.location===t.location:e.kind===`document`&&t.kind===`document`&&e.document.id===t.document.id&&e.workspaceId===t.workspaceId}function am({children:e}){let t=h(),n=m(),[r,i]=(0,Z.useState)([tm]),[a,o]=(0,Z.useState)(0),[s,c]=(0,Z.useState)(wr),l=(0,Z.useRef)(r),u=(0,Z.useRef)(a),d=(0,Z.useRef)(s);(0,Z.useEffect)(()=>{l.current=r,u.current=a,d.current=s},[r,a,s]);let f=(0,Z.useCallback)((e,t)=>{let n=l.current.slice();n[e]=t,l.current=n,i(n)},[]),p=(0,Z.useCallback)(e=>{let t=u.current,n=l.current[t];n&&f(t,e(n))},[f]),g=t.pathname+t.search;(0,Z.useEffect)(()=>{p(e=>e.main===g?e:{...e,main:g})},[g,p]);let _=(0,Z.useCallback)(e=>{let t=l.current[u.current];if(!t)return;let n=t.entries.find(t=>im(e,t));if(n){c(n.id);return}let r={...e,id:rm()},i=t.entries.findIndex(e=>e.id===d.current),a=t.entries.slice();a.splice(i>=0?i+1:0,0,r),p(e=>({...e,entries:a})),d.current=r.id,c(r.id)},[p]),v=(0,Z.useCallback)((e,t)=>{_({kind:`document`,document:e,workspaceId:t})},[_]),y=(0,Z.useCallback)((e,t)=>{let n=`document-preview`;p(r=>{let i=r.entries.find(e=>e.id===n),a={kind:`document`,id:n,document:e,workspaceId:t,expanded:i?.expanded};return{...r,entries:[a,...r.entries.filter(e=>e.id!==n)]}}),d.current=n,c(n)},[p]),b=(0,Z.useCallback)(e=>{p(t=>({...t,entries:t.entries.filter(t=>t.id!==e)})),c(t=>t===e?wr:t)},[p]),x=(0,Z.useCallback)((e,t)=>{p(n=>({...n,entries:n.entries.map(n=>n.id===e&&n.kind===`route`?{...n,location:t}:n)}))},[p]),S=(0,Z.useCallback)(e=>{p(t=>e===`main`?{...t,mainExpanded:!t.mainExpanded}:{...t,entries:t.entries.map(t=>t.id===e?{...t,expanded:!t.expanded}:t)})},[p]),C=(0,Z.useCallback)(e=>{let t=l.current[e];t&&(u.current=e,o(e),c(wr),n(t.main))},[n]),w=(0,Z.useCallback)((e,t,n)=>{let r=l.current.findIndex(t=>t.key===e);if(r>=0){C(r);return}let a=[...l.current,{key:e,label:t,main:n,mainExpanded:!1,entries:[]}];l.current=a,i(a),C(a.length-1)},[C]),T=(0,Z.useCallback)(e=>{C(u.current+e)},[C]),E=(0,Z.useCallback)(e=>{let t=l.current.findIndex(t=>t.key===e);if(t<=0)return;let n=l.current.filter(t=>t.key!==e);l.current=n,i(n);let r=u.current;r===t?C(Math.min(t,n.length-1)):r>t&&(u.current=r-1,o(r-1))},[C]),D=(0,Z.useMemo)(()=>({rows:r,activeRow:a,focus:s,setFocus:c,openCanvas:_,openDocument:v,closeCanvas:b,navigateCanvas:x,toggleExpanded:S,activateRow:w,moveRow:T,closeRow:E}),[r,a,s,_,v,b,x,S,w,T,E]),O=(0,Z.useMemo)(()=>({entry:null,open:v,preview:y,close:()=>{}}),[v,y]);return(0,Q.jsx)(Sr.Provider,{value:D,children:(0,Q.jsx)(br.Provider,{value:O,children:e})})}function om(e){return f(typeof e==`string`?v(e):e)}function sm({location:e,onNavigate:t}){let n=(0,Z.useMemo)(()=>{let t=v(e);return{pathname:t.pathname||`/`,search:t.search||``,hash:t.hash||``,state:null,key:e}},[e]),r=(0,Z.useMemo)(()=>({basename:`/`,static:!1,useTransitions:void 0,future:{},navigator:{createHref:om,go:()=>{},push:e=>t(om(e)),replace:e=>t(om(e))}}),[t]);return(0,Q.jsx)(b.Provider,{value:r,children:(0,Q.jsx)(g.Provider,{value:{location:n,navigationType:w.Push},children:(0,Q.jsx)(_.Provider,{value:{outlet:null,matches:[],isDataRoute:!1},children:(0,Q.jsx)(T,{children:is})})})})}var cm=`input, textarea, select, [contenteditable=""], [contenteditable="true"]`,lm=420,um=e=>e<=0?0:e>=1?1:e<.5?2**(20*e-10)/2:(2-2**(-20*e+10))/2;function dm(e,t,n){if(window.matchMedia(`(prefers-reduced-motion: reduce)`).matches)return e.scrollLeft=t,n?.(),()=>{};let r=e.scrollLeft,i=t-r;if(Math.abs(i)<1)return n?.(),()=>{};let a=e.style.scrollSnapType;e.style.scrollSnapType=`none`;let o=performance.now(),s=0,c=t=>{let l=Math.min(1,(t-o)/lm);e.scrollLeft=r+i*um(l),l<1?s=requestAnimationFrame(c):(e.style.scrollSnapType=a,n?.())};return s=requestAnimationFrame(c),()=>{cancelAnimationFrame(s),e.style.scrollSnapType=a}}function fm(e,t){let n=parseFloat(getComputedStyle(e).gap)||0,r=t.getBoundingClientRect().left-e.getBoundingClientRect().left+e.scrollLeft,i=r+t.offsetWidth,a=e.scrollLeft,o=a+e.clientWidth;return r<a?Math.max(0,r-n):i>o?i+n-e.clientWidth:a}function pm({section:e}){return e===`contexts`?(0,Q.jsx)($s,{}):e===`workspaces`?(0,Q.jsx)(Hc,{}):e===`agents`?(0,Q.jsx)(zu,{}):e===`admin`?(0,Q.jsx)(qu,{}):e===`apps`?(0,Q.jsx)(Bs,{}):e===`settings`?(0,Q.jsx)(qu,{}):null}function mm(e,t,n){if(e?.kind===`document`)return On(e.document).title;let r=(e?.kind===`route`?e.location:t).split(/[?#]/)[0];if(r===`/settings`)return`Settings`;let i=fa.flatMap(e=>[...e.items]).find(e=>e.path===r);if(i)return i.label;let a=r.split(`/`).filter(Boolean);if(a.length===0)return`Desk`;if(a[0]===`workspaces`&&a.length===2){let e=decodeURIComponent(a[1]),t=n.find(t=>t.id===e)??n.find(t=>t.name===e);return t?.label||t?.name||`Workspace`}return decodeURIComponent(a[a.length-1])}function hm({id:e,title:t,expanded:n,focused:r,onFocus:i,onToggleExpanded:a,onClose:o,badge:s,contentHeader:c,children:l}){let u=kr();return(0,Q.jsxs)(`section`,{"data-reader-pane":c?!0:void 0,style:c&&!n?{"--reader-width":`${u??420}px`,...u?{transition:`none`}:{}}:void 0,"data-strip-col":e,className:G(`strip-canvas surface-sheet relative`,n&&`strip-canvas--wide`,r&&`strip-canvas--focused`),onPointerDownCapture:()=>i(e),"aria-label":t,children:[c&&!n&&(0,Q.jsx)(Dr,{edge:`right`}),!c&&(0,Q.jsxs)(`header`,{className:`strip-canvas-bar`,children:[s&&(0,Q.jsx)(`span`,{className:`strip-row-label`,children:s}),(0,Q.jsx)(`span`,{className:`strip-canvas-title`,title:t,children:t}),(0,Q.jsx)(`button`,{type:`button`,className:`strip-canvas-btn`,title:n?`Card size`:`Expand to full width`,"aria-pressed":n,onClick:()=>a(e),children:n?(0,Q.jsx)(be,{className:`size-3.5`}):(0,Q.jsx)(Ke,{className:`size-3.5`})}),o&&(0,Q.jsx)(`button`,{type:`button`,className:`strip-canvas-btn`,title:s?`Close row`:`Close canvas`,onClick:()=>o(e),children:(0,Q.jsx)(z,{className:`size-3.5`})})]}),(0,Q.jsx)(`div`,{className:`strip-canvas-body`,children:l})]})}function gm(e){return G(`relative flex-1 min-h-0 min-w-0 overflow-auto`,!Qu(e)&&!Zu(e)&&`p-page`)}function _m({row:e,pathname:t,rowLabel:n,onCloseRow:r,workspaces:i}){let{focus:a,setFocus:o,toggleExpanded:s,closeCanvas:c,navigateCanvas:l}=xr(),u=(0,Z.useCallback)(e=>t=>l(e,t),[l]);return(0,Q.jsxs)(Q.Fragment,{children:[t===`/`?(0,Q.jsx)(`div`,{hidden:!0,children:(0,Q.jsx)(C,{})}):(0,Q.jsx)(hm,{id:wr,title:mm(null,t,i),expanded:e.mainExpanded,focused:a===wr,onFocus:o,onToggleExpanded:s,badge:n,onClose:r,children:(0,Q.jsx)(`main`,{id:`content-area`,className:gm(t),children:(0,Q.jsx)(C,{})})}),e.entries.map(e=>(0,Q.jsx)(hm,{id:e.id,title:mm(e,t,i),expanded:!!e.expanded,focused:a===e.id,onFocus:o,onToggleExpanded:s,contentHeader:e.kind===`document`,onClose:c,children:e.kind===`route`?(0,Q.jsx)(`div`,{className:gm(e.location.split(`?`)[0]),children:(0,Q.jsx)(sm,{location:e.location,onNavigate:u(e.id)})}):(0,Q.jsx)(`div`,{className:`flex flex-1 min-h-0 min-w-0 items-stretch`,children:(0,Q.jsx)(jr,{entry:e,onClose:()=>c(e.id),frame:{expanded:!!e.expanded,onToggleExpanded:()=>s(e.id)}})})},e.id))]})}function vm({row:e,workspaces:t}){return(0,Q.jsxs)(`div`,{className:`strip-ghost-row`,"aria-hidden":!0,children:[(0,Q.jsx)(`span`,{className:`strip-ghost-chip strip-ghost-chip--main`,children:mm(null,e.main,t)}),e.entries.map(n=>(0,Q.jsx)(`span`,{className:`strip-ghost-chip`,children:mm(n,e.main,t)},n.id))]})}function ym(){let{state:e,closeM1:t,closeM2:n}=la(),[r,i]=(0,Z.useState)(280),{rows:a,activeRow:o,focus:s,setFocus:c,moveRow:l,closeRow:u}=xr(),{pathname:d}=h(),{workspaces:f}=Bc(d.startsWith(`/workspaces/`)||a.some(e=>e.main.startsWith(`/workspaces/`)||e.entries.some(e=>e.kind===`route`&&e.location.startsWith(`/workspaces/`)))),p=ca(),m=(0,Z.useRef)(null);hi(t,e.m1Open&&!e.m2Open),hi(n,e.m2Open),(0,Z.useLayoutEffect)(()=>{let e=m.current;if(!e)return;let t=()=>{e.style.setProperty(`--strip-w`,`${e.clientWidth}px`),e.style.setProperty(`--strip-h`,`${e.clientHeight}px`)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let g=(0,Z.useRef)(e.m1Open);(0,Z.useEffect)(()=>{e.m1Open&&!g.current&&!e.m2Open&&c(`m1`),g.current=e.m1Open},[e.m1Open,e.m2Open,c]);let _=(0,Z.useRef)(e.m2Open);(0,Z.useEffect)(()=>{e.m2Open&&!_.current&&c(`m2`),!e.m2Open&&_.current&&s===`m2`&&c(e.m1Open?`m1`:wr),_.current=e.m2Open},[e.m2Open,e.m1Open,s,c]),(0,Z.useEffect)(()=>{!e.m1Open&&s===`m1`&&c(wr)},[e.m1Open,s,c]),(0,Z.useEffect)(()=>{let e=m.current,t=e?.querySelector(`[data-strip-col="${CSS.escape(s)}"]`);if(!(!e||!t))return dm(e,fm(e,t))},[s,a,o,e.m1Open,e.m2Open]);let v=(0,Z.useCallback)(()=>{let t=a[o];return[...e.m1Open?[`m1`]:[],...e.m2Open?[`m2`]:[],...d===`/`?[]:[wr],...t?t.entries.map(e=>e.id):[]]},[a,o,e.m1Open,e.m2Open,d]);return(0,Z.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.isComposing||!e.key.startsWith(`Arrow`)||!oa(e,p))return;let t=e.target;if(!(t?.closest(cm)||t?.closest(`[role="dialog"]`))){if(e.key===`ArrowLeft`||e.key===`ArrowRight`){let t=v(),n=t[Math.max(0,t.indexOf(s))+(e.key===`ArrowRight`?1:-1)];if(!n)return;e.preventDefault(),c(n)}else(e.key===`ArrowUp`||e.key===`ArrowDown`)&&a.length>1&&(e.preventDefault(),l(e.key===`ArrowDown`?1:-1))}};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[v,s,c,l,a.length,p]),(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`strip-shell flex h-viewport w-full overflow-hidden surface-desk gap-shell p-shell`,children:[(0,Q.jsx)(js,{}),(0,Q.jsxs)(`div`,{ref:m,className:`strip-scroller`,style:{"--strip-menu-space":`${(e.m1Open?280:0)+(e.m2Open?r:0)}px`},children:[e.m1Open&&(0,Q.jsx)(`div`,{"data-strip-col":`m1`,className:G(`strip-col strip-menu-col`,s===`m1`&&`strip-col--focused`),onPointerDownCapture:()=>c(`m1`),children:(0,Q.jsx)(pm,{section:e.activeSection})}),e.m2Open&&(0,Q.jsxs)(`div`,{"data-strip-col":`m2`,style:{width:r,position:`relative`},className:G(`strip-col strip-menu-col`,s===`m2`&&`strip-col--focused`),onPointerDownCapture:()=>c(`m2`),children:[(0,Q.jsx)(Yu,{}),(0,Q.jsx)(Us,{width:r,onResize:i})]}),(0,Q.jsx)(`div`,{className:`strip-rows`,style:{transform:`translateY(${-o*100}%)`},children:a.map((e,t)=>(0,Q.jsx)(`div`,{className:G(`strip-row`,t===o&&`strip-row--active`),children:(0,Q.jsx)(`div`,{className:`strip-row-canvases`,children:t===o?(0,Q.jsx)(_m,{row:e,workspaces:f,pathname:d,rowLabel:a.length>1?e.label:void 0,onCloseRow:t>0?()=>u(e.key):void 0}):(0,Q.jsx)(vm,{row:e,workspaces:f})})},e.key))})]}),(0,Q.jsx)($d,{}),(0,Q.jsx)(Jp,{})]}),(0,Q.jsx)(nd,{}),(0,Q.jsx)(As,{}),(0,Q.jsx)(Yp,{})]})}function bm(){let e=sa();return(0,Q.jsx)(fs,{children:(0,Q.jsx)(ad,{children:(0,Q.jsx)(yd,{children:(0,Q.jsx)(If,{children:(0,Q.jsx)($p,{children:e===`strip`?(0,Q.jsx)(am,{children:(0,Q.jsx)(em,{children:(0,Q.jsx)(ym,{})})}):(0,Q.jsxs)(em,{children:[(0,Q.jsxs)(`div`,{className:`flex h-viewport w-full overflow-hidden surface-desk gap-shell p-shell`,children:[(0,Q.jsx)(js,{}),(0,Q.jsx)(Xu,{}),(0,Q.jsx)(td,{}),(0,Q.jsx)($d,{}),(0,Q.jsx)(Jp,{})]}),(0,Q.jsx)(nd,{}),(0,Q.jsx)(As,{}),(0,Q.jsx)(Yp,{})]})})})})})})}var xm=wt,Sm=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(ot,{ref:n,className:G(`fixed top-0 right-0 z-toast flex max-h-screen w-full flex-col-reverse gap-2 p-4 sm:right-0 sm:flex-col md:max-w-[420px]`,e),...t}));Sm.displayName=ot.displayName;var Cm=Zt(`group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-elevation-3 transition-all duration-normal data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full`,{variants:{variant:{default:`border bg-background`,destructive:`destructive group border-destructive bg-destructive text-destructive-foreground`}},defaultVariants:{variant:`default`}}),wm=Z.forwardRef(({className:e,variant:t,...n},r)=>(0,Q.jsx)(yt,{ref:r,className:G(Cm({variant:t}),e),...n}));wm.displayName=yt.displayName;var Tm=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(Mt,{ref:n,className:G(`inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive`,e),...t}));Tm.displayName=Mt.displayName;var Em=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)($e,{ref:n,className:G(`absolute right-2 top-2 rounded-md p-1 text-foreground/50 reveal-on-hover hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-[.destructive]:text-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive group-[.destructive]:focus:ring-offset-destructive`,e),"toast-close":``,...t,children:(0,Q.jsx)(z,{className:`h-4 w-4`})}));Em.displayName=$e.displayName;var Dm=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(ut,{ref:n,className:G(`text-sm font-semibold`,e),...t}));Dm.displayName=ut.displayName;var Om=Z.forwardRef(({className:e,...t},n)=>(0,Q.jsx)(rt,{ref:n,className:G(`text-sm opacity-90`,e),...t}));Om.displayName=rt.displayName;var km=`canvas-notifications`,Am=`notifications`,jm=`canvas:notification-history`,Mm,Nm;function Pm(){try{let e=localStorage.getItem(`authToken`);if(e){let t=Qt(e),n=t.sub||t.userId||t.id||t.email;if(typeof n==`string`||typeof n==`number`)return JSON.stringify([t.iss||``,n])}}catch{}return`anonymous`}function Fm(){return Mm||=new Promise((e,t)=>{let n=indexedDB.open(km,1);n.onupgradeneeded=()=>{n.result.createObjectStore(Am,{keyPath:[`account`,`id`]}).createIndex(`account`,`account`)},n.onsuccess=()=>{let t=n.result;t.onversionchange=()=>{t.close(),Mm=void 0},e(t)},n.onerror=()=>t(n.error)}).catch(e=>{throw Mm=void 0,e}),Mm}function Im(){return!Nm&&typeof BroadcastChannel<`u`&&(Nm=new BroadcastChannel(jm),Nm.onmessage=e=>window.dispatchEvent(new CustomEvent(jm,{detail:e.data}))),Nm}function Lm(e,t=!1){let n={account:e,error:t};window.dispatchEvent(new CustomEvent(jm,{detail:n})),t||Im()?.postMessage(n)}function Rm(e,t){Im();let n=n=>{let r=n.detail;r?.account===e&&t(!!r.error)};return window.addEventListener(jm,n),()=>window.removeEventListener(jm,n)}async function zm(e){let t=await Fm();return new Promise((n,r)=>{let i=t.transaction(Am,`readonly`),a=i.objectStore(Am).index(`account`).getAll(e);i.oncomplete=()=>n(a.result.sort((e,t)=>e.timestamp.localeCompare(t.timestamp)||e.id.localeCompare(t.id))),i.onabort=()=>r(i.error),i.onerror=()=>r(i.error)})}async function Bm(e,t){try{let n=await Fm();await new Promise((e,r)=>{let i=n.transaction(Am,`readwrite`);i.oncomplete=()=>e(),i.onabort=()=>r(i.error),i.onerror=()=>r(i.error),t(i.objectStore(Am))}),Lm(e)}catch(t){throw Lm(e,!0),t}}function Vm(e,t){return Bm(e,n=>{let r=n.get([e,t.id]);r.onsuccess=()=>{r.result||n.put({...t,account:e})}})}function Hm(e,t,n){return Bm(e,r=>{let i=r.get([e,t]);i.onsuccess=()=>{i.result&&r.put({...i.result,...n})}})}function Um(e,t){return Bm(e,n=>{n.delete([e,t])})}function Wm(e){return Bm(e,t=>{let n=t.index(`account`).openKeyCursor(e);n.onsuccess=()=>{n.result&&(t.delete(n.result.primaryKey),n.result.continue())}})}function Gm({children:e}){let[t,n]=(0,Z.useState)([]),r=(0,Z.useRef)(new Set),i=(0,Z.useCallback)((e,t=!0)=>{if(an(e.description)||an(e.title))return;let i=`${e.title}:${e.description??``}`;if(t&&(e.historyId||!r.current.has(i))){let t=e.timestamp?new Date(e.timestamp):new Date;Vm(Pm(),{id:e.historyId||crypto.randomUUID(),title:e.title,text:e.description||``,timestamp:Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString(),status:e.variant===`destructive`?`error`:`info`}).catch(()=>{})}if(r.current.has(i))return;r.current.add(i);let a=Math.random().toString(36).substring(2,9);n(t=>[...t,{...e,id:a}]),setTimeout(()=>{n(e=>e.filter(e=>e.id!==a)),r.current.delete(i)},5e3)},[]),a=(0,Z.useCallback)(e=>{let t=crypto.randomUUID(),r=Pm();Vm(r,{id:t,title:e.title,text:e.description||``,timestamp:new Date().toISOString(),status:`started`}).catch(()=>{}),n(n=>[...n,{...e,id:t,busy:!0}]);let a=!1,o=(e,o=!1)=>{a||(a=!0,n(e=>e.filter(e=>e.id!==t)),Hm(r,t,{...e?{title:e.title,text:e.description||``}:{},status:o||e?.variant===`destructive`?`error`:`completed`}).catch(()=>{}),e&&i(e,!1))};return{update:e=>{a||n(n=>n.map(n=>n.id===t?{...n,...e}:n))},done:e=>o(e),fail:e=>o(e,!0)}},[i]),o=(0,Z.useMemo)(()=>({showToast:i,showProgress:a}),[i,a]);return(0,Q.jsx)(Sn.Provider,{value:o,children:(0,Q.jsxs)(xm,{children:[e,t.map(e=>(0,Q.jsxs)(wm,{variant:e.variant,duration:e.busy?1/0:void 0,children:[(0,Q.jsxs)(`div`,{className:`grid gap-1`,children:[(0,Q.jsxs)(Dm,{className:`flex items-center gap-2`,children:[e.busy&&(0,Q.jsx)(Et,{className:`h-3.5 w-3.5 shrink-0 animate-spin`}),e.title]}),e.description!=null&&(0,Q.jsx)(Om,{children:e.description})]}),e.busy&&e.action&&(0,Q.jsx)(`button`,{type:`button`,className:`shrink-0 rounded-md border px-2 py-1 text-xs hover:bg-secondary`,onClick:e.action.onClick,children:e.action.label}),!e.busy&&(0,Q.jsx)(Em,{})]},e.id)),(0,Q.jsx)(Sm,{})]})})}function Km({children:e}){let[t]=(0,Z.useState)(Pm),[n,r]=(0,Z.useState)([]),[i,a]=(0,Z.useState)(!0),[o,s]=(0,Z.useState)(!1),{showToast:c}=xn();(0,Z.useEffect)(()=>{let e=!0,n=0,i=async()=>{let i=++n;try{let o=await zm(t);e&&i===n&&(r(o),a(!1))}catch{e&&(s(!0),a(!1))}},o=Rm(t,e=>{s(e),e||i()});return i(),()=>{e=!1,o()}},[t]),(0,Z.useEffect)(()=>X.on(`notification`,e=>{let t=e;!t||![`string`,`number`].includes(typeof t.id)||typeof t.text!=`string`||!t.text||c({title:`Notification`,description:t.text,historyId:`message:${t.id}`,timestamp:typeof t.timestamp==`string`?t.timestamp:void 0})}),[c]);let l=(0,Z.useCallback)(async()=>{try{await Wm(t)}catch{}},[t]),u=(0,Z.useCallback)(async e=>{try{await Um(t,e)}catch{}},[t]);return(0,Q.jsx)(ef.Provider,{value:{notifications:n,loading:i,storageError:o,clear:l,remove:u},children:e})}function qm(e,t,n){let r=Promise.resolve();return i=>{let a=r.then(async()=>{let r=await e(),a=i(r.home?.pinnedCanvases??[]);n(await t({...r,home:{...r.home,pinnedCanvases:a}}))});return r=a.catch(()=>{}),a}}function Jm(e,t){return e.minimized===!0||t.has(e.id)}var Ym=e=>`${e.workspaceName}\0${e.treeName}\0${e.path}`;function Xm({children:e}){let[t,n]=(0,Z.useState)(null),[r,i]=(0,Z.useState)(!0);(0,Z.useEffect)(()=>{let e=!1;return Al().then(t=>{e||n(t)}).catch(()=>{e||n({})}).finally(()=>{e||i(!1)}),()=>{e=!0}},[]);let a=(0,Z.useMemo)(()=>t?.home?.pinnedCanvases??[],[t]),[o]=(0,Z.useState)(()=>qm(Al,jl,n)),s=(0,Z.useCallback)(e=>a.some(t=>Ym(t)===Ym(e)),[a]),c=(0,Z.useCallback)(async e=>{let t=crypto.randomUUID();await o(n=>n.some(t=>Ym(t)===Ym(e))?n:[...n,{id:t,...e}])},[o]),l=(0,Z.useCallback)(async e=>{await o(t=>t.filter(t=>t.id!==e))},[o]),u=(0,Z.useCallback)(async(e,t)=>{await o(n=>n.map(n=>n.id===e?{...n,minimized:t}:n))},[o]),d=(0,Z.useCallback)(async(e,t)=>{await o(n=>{let r=n.find(t=>t.id===e);if(!r||e===t)return n;let i=n.filter(t=>t.id!==e),a=t===null?i.length:i.findIndex(e=>e.id===t);return a===-1?n:[...i.slice(0,a),r,...i.slice(a)]})},[o]),f=(0,Z.useMemo)(()=>({pins:a,isLoading:r,isPinned:s,pin:c,unpin:l,movePin:d,setMinimized:u}),[a,r,s,c,l,d,u]);return(0,Q.jsx)(yr.Provider,{value:f,children:e})}var Zm=[{id:`canvas`,name:`Canvas`,description:`Black and white with a teal accent. Sheets of paper on a grey desk.`,swatches:[`oklch(1 0 0)`,`oklch(0 0 0)`,`oklch(0.704 0.135 183)`]},{id:`nord`,name:`Nord`,description:`Cool arctic blues, lower contrast, softer corners.`,swatches:[`oklch(0.976 0.006 251)`,`oklch(0.588 0.056 244)`,`oklch(0.686 0.062 213)`]},{id:`contrast`,name:`High Contrast`,description:`WCAG AAA text contrast, square corners, hard borders, no shadows.`,swatches:[`oklch(1 0 0)`,`oklch(0 0 0)`,`oklch(0.32 0.16 258)`]},{id:`frost`,name:`Frosted Glass`,description:`Translucent, blurred surfaces over a soft backdrop. Best with a wallpaper.`,swatches:[`oklch(0.92 0.008 250)`,`oklch(0.31 0.025 255)`,`oklch(0.55 0.05 250)`]},{id:`terminal`,name:`Terminal`,description:`Monospaced and dense. Tighter rows and chrome for large displays.`,swatches:[`oklch(0.17 0.006 152)`,`oklch(0.8 0.19 148)`,`oklch(0.75 0.12 220)`]},{id:`halflife`,name:`Half-Life`,description:`Lambda orange on black steel. Square corners; the left rail is orange.`,swatches:[`oklch(0.724 0.181 52)`,`oklch(0 0 0)`,`oklch(1 0 0)`]}],Qm=Zm.map(e=>e.id),$m=[{id:`system`,name:`System`},{id:`light`,name:`Light`},{id:`dark`,name:`Dark`}],eh=[{id:`auto`,name:`Auto`,description:`Match the pointer: touch on phones, mouse on desktop`},{id:`compact`,name:`Compact`,description:`Maximum rows per screen`},{id:`comfortable`,name:`Comfortable`,description:`Balanced for mouse use`},{id:`touch`,name:`Touch`,description:`Large targets for finger input`}],th={theme:`canvas`,scheme:`light`,density:`auto`},nh=`canvas.ui.theme`;function rh(e){return typeof e==`string`&&Qm.includes(e)}function ih(e){return e===`light`||e===`dark`||e===`system`}function ah(e){return e===`auto`||e===`compact`||e===`comfortable`||e===`touch`}function oh(e){let t=typeof e==`object`&&e?e:{};return{theme:rh(t.theme)?t.theme:th.theme,scheme:ih(t.scheme)?t.scheme:th.scheme,density:ah(t.density)?t.density:th.density}}var sh=`(prefers-color-scheme: dark)`;function ch(){return typeof document<`u`}function lh(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(sh).matches}function uh(e){return e===`system`?lh()?`dark`:`light`:e}function dh(e){if(typeof window>`u`||typeof window.matchMedia!=`function`)return()=>{};let t=window.matchMedia(sh),n=t=>e(t.matches?`dark`:`light`);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)}function fh(e){return dh(e)}function ph(){return lh()?`dark`:`light`}function mh(){return`light`}function hh(e){let t=getComputedStyle(e).getPropertyValue(`--background`).trim();if(!t)return;let n=document.querySelector(`meta[name="theme-color"]`);n||(n=document.createElement(`meta`),n.name=`theme-color`,document.head.appendChild(n)),n.content=t}function gh(e,t=ch()?document.documentElement:void 0){let n=uh(e.scheme);return t?(t.dataset.theme=e.theme,t.dataset.scheme=n,t.dataset.density=e.density,hh(t),n):n}function _h(e,t=ch()?document.documentElement:void 0){if(!t||typeof window>`u`)return gh(e,t);let n=document.createElement(`style`);n.appendChild(document.createTextNode(`*,*::before,*::after{transition:none!important;animation:none!important}`)),document.head.appendChild(n);let r=gh(e,t);return window.getComputedStyle(n).opacity,document.head.removeChild(n),r}function vh(e){let t=e??xh();if(!t)return th;try{let e=t.getItem(nh);return e?oh(JSON.parse(e)):th}catch{return th}}function yh(e,t){let n=t??xh();if(n)try{n.setItem(nh,JSON.stringify(e))}catch{}}function bh(e){let t=e??xh();if(t)try{t.removeItem(nh)}catch{}}function xh(){try{return typeof localStorage<`u`?localStorage:void 0}catch{return}}function Sh({children:e,initial:t,storage:n,persist:r=!0}){let[i,a]=(0,Z.useState)(()=>({...vh(n),...t})),o=(0,Z.useSyncExternalStore)(fh,ph,mh),s=i.scheme===`system`?o:i.scheme;(0,Z.useEffect)(()=>{_h({...i,scheme:s})},[i,s]),(0,Z.useEffect)(()=>{r&&yh(i,n)},[i,r,n]);let c=(0,Z.useCallback)(e=>{a(t=>t.theme===e?t:{...t,theme:e})},[]),l=(0,Z.useCallback)(e=>{a(t=>t.scheme===e?t:{...t,scheme:e})},[]),u=(0,Z.useCallback)(e=>{a(t=>t.density===e?t:{...t,density:e})},[]),d=(0,Z.useCallback)(()=>{a(e=>({...e,scheme:(e.scheme===`system`?ph():e.scheme)===`dark`?`light`:`dark`}))},[]),f=(0,Z.useCallback)(()=>{bh(n),a(th)},[n]),p=(0,Z.useMemo)(()=>({...i,resolvedScheme:s,setTheme:c,setScheme:l,setDensity:u,toggleScheme:d,reset:f}),[i,s,c,l,u,d,f]);return(0,Q.jsx)(Da.Provider,{value:p,children:e})}var Ch=(0,Z.lazy)(()=>c(()=>import(`./NextShell-DiyMsTp5.js`),__vite__mapDeps([128,1,2,7,8,9,10,6,5,11,12,13,129])));function wh(){let{showToast:e}=xn();return(0,Z.useEffect)(()=>{cn((t,n)=>{e({title:`Error`,description:n?`${t.message} (${n})`:t.message,variant:`destructive`})})},[e]),(0,Z.useEffect)(()=>vs(),[]),(0,Q.jsxs)(y,{children:[(0,Q.jsx)(ls,{}),(0,Q.jsx)(So,{}),(0,Q.jsxs)(T,{children:[(0,Q.jsx)(d,{path:`/login`,element:(0,Q.jsx)(Za,{children:(0,Q.jsx)(qa,{})})}),(0,Q.jsx)(d,{path:`/register`,element:(0,Q.jsx)(Za,{children:(0,Q.jsx)(Ja,{})})}),(0,Q.jsx)(d,{path:`/auth/google/callback`,element:(0,Q.jsx)(Za,{children:(0,Q.jsx)(Ya,{})})}),(0,Q.jsx)(d,{path:`/pub/c/:code`,element:(0,Q.jsx)(lo,{})}),(0,Q.jsx)(d,{path:`/next/*`,element:(0,Q.jsx)(Xa,{children:(0,Q.jsx)(Z.Suspense,{fallback:null,children:(0,Q.jsx)(Ch,{})})})}),(0,Q.jsx)(d,{path:`/`,element:(0,Q.jsx)(Xa,{children:(0,Q.jsx)(Km,{children:(0,Q.jsx)(Xm,{children:(0,Q.jsx)(bm,{})})})}),children:is}),(0,Q.jsx)(d,{path:`*`,element:(0,Q.jsx)(u,{to:`/`,replace:!0})})]})]})}function Th(){return(0,Q.jsx)(Sh,{children:(0,Q.jsx)(Gm,{children:(0,Q.jsx)(wh,{})})})}var Eh=[{id:`canvas_1`,title:`Canvas Deep`,scheme:`dark`,background:`#032940`,accent:`#f2f2f2`,sources:[{type:`image/svg+xml`,src:`files/canvas_1.svg`},{type:`image/avif`,src:`files/canvas_1.avif`},{type:`image/webp`,src:`files/canvas_1.webp`}],thumb:`thumbs/canvas_1.webp`,author:`Canvas`,license:`LicenseRef-Canvas-Brand`},{id:`canvas_3`,title:`Canvas Mono Dark`,scheme:`dark`,background:`#000000`,accent:`#ffffff`,sources:[{type:`image/svg+xml`,src:`files/canvas_3.svg`},{type:`image/avif`,src:`files/canvas_3.avif`},{type:`image/webp`,src:`files/canvas_3.webp`}],thumb:`thumbs/canvas_3.webp`,author:`Canvas`,license:`LicenseRef-Canvas-Brand`},{id:`w1`,title:`Frost`,scheme:`dark`,background:`#164a6f`,accent:`#9ad9f0`,sources:[{type:`image/avif`,src:`files/w1.avif`},{type:`image/webp`,src:`files/w1.webp`},{type:`image/jpeg`,src:`files/w1.jpg`}],thumb:`thumbs/w1.webp`,author:`Peter Cui Bide`,source:`https://petercui.deviantart.com`,license:`LicenseRef-Attribution-Only`}],Dh=`/wallpapers`;function Oh(e){return Eh.find(t=>t.id===e)}function kh(e,t={}){let n=typeof e==`string`?Oh(e):e;if(!n)return null;let{base:r=Dh,types:i}=t,a=(i?n.sources.find(e=>i.includes(e.type)):n.sources[0])??n.sources[n.sources.length-1];return`${r.replace(/\/$/,``)}/${a.src}`}function Ah(e,t=Dh){let n=typeof e==`string`?Oh(e):e;return n?`${t.replace(/\/$/,``)}/${n.thumb}`:null}var jh=[{id:`cover`,label:`Scale and Crop`,description:`Fills the screen, cropping edges as needed`},{id:`fill`,label:`Fill`,description:`Stretches to the exact screen size`},{id:`center`,label:`Centered`,description:`Original size, centered on the desk`}],Mh=`canvas:wallpaper`,Nh=`canvas-wallpaper`,Ph=`settings`,Fh=`builtin:`,Ih=Eh;function Lh(e){return Ah(e)??``}function Rh(e){return`${Fh}${e}`}function zh(e){return e?.startsWith(Fh)?e.slice(8):null}function Bh(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.image!=`string`&&t.image!==null?null:{image:t.image,fit:t.fit===`fill`||t.fit===`center`?t.fit:`cover`}}function Vh(){try{let e=localStorage.getItem(Mh);if(e){let t=Bh(JSON.parse(e));if(t)return t}}catch{}return{image:null,fit:`cover`}}var Hh=Vh(),Uh=null;function Wh(){return Hh}async function Gh(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(Nh,1),r=!1;n.onupgradeneeded=()=>n.result.createObjectStore(Ph),n.onsuccess=()=>{if(r){n.result.close();return}n.result.onversionchange=()=>n.result.close(),e(n.result)},n.onerror=()=>t(n.error),n.onblocked=()=>{r=!0,t(Error(`Close other Canvas tabs and try again.`))}});try{return await new Promise((n,r)=>{let i=t.transaction(Ph,e?`readwrite`:`readonly`),a=i.objectStore(Ph),o=e?a.put(e,Mh):a.get(Mh);i.oncomplete=()=>n(o.result),i.onerror=()=>r(i.error),i.onabort=()=>r(i.error)})}finally{t.close()}}function Kh(){try{localStorage.removeItem(Mh)}catch{}}function qh(){return Uh||=(async()=>{try{let e=Bh(await Gh());e?Hh=e:await Gh(Hh),Kh()}catch{}return tg(Hh),Hh})(),Uh.then(()=>Hh)}async function Jh(e){await qh(),await Gh(e),Hh=e,Kh(),tg(e)}function Yh(e){if(e.size>10485760)return Promise.reject(Error(`Image too large. Choose one up to 10 MB.`));let t=e.type||(/\.gif$/i.test(e.name)?`image/gif`:``);return t.startsWith(`image/`)?new Promise((n,r)=>{let i=new FileReader;i.onload=()=>n(String(i.result)),i.onerror=()=>r(Error(`Could not read the image. Try selecting it again.`)),i.onabort=()=>r(Error(`Reading the image was cancelled.`)),i.readAsDataURL(e.type?e:e.slice(0,e.size,t))}):Promise.reject(Error(`Pick an image file (animated GIFs are supported).`))}var Xh=typeof CSS<`u`&&CSS.supports(`background-image`,`image-set(url("a.avif") type("image/avif"))`);function Zh(e){if(!e)return null;let t=zh(e);if(t===null)return`url("${e}")`;let n=Oh(t);if(!n)return null;let r=`url("${kh(n,{types:[n.sources[n.sources.length-1].type]})}")`;return!Xh||n.sources.length===1?r:`image-set(${n.sources.map(e=>`url("${kh(n,{types:[e.type]})}") type("${e.type}")`).join(`, `)})`}function Qh(e){return e===`fill`?`100% 100%`:e===`center`?`auto`:`cover`}var $h=null;function eg(e){let t=e.indexOf(`,`);if(t<0)throw Error(`Invalid wallpaper data URL`);let n=e.slice(5,t),r=e.slice(t+1),i;if(n.endsWith(`;base64`)){let e=atob(r);i=new Uint8Array(e.length);for(let t=0;t<e.length;t++)i[t]=e.charCodeAt(t)}else i=new TextEncoder().encode(decodeURIComponent(r));return new Blob([i],{type:n.split(`;`)[0]})}function tg(e=Wh()){let t=document.documentElement.style,n=$h,r=e.image;if(r?.startsWith(`data:`))try{$h?.dataUrl!==r&&($h={dataUrl:r,objectUrl:URL.createObjectURL(eg(r))}),r=$h.objectUrl}catch{$h=null,r=null}else $h=null;let i=Zh(r);i?(t.setProperty(`--wallpaper-image`,i),t.setProperty(`--wallpaper-size`,Qh(e.fit))):(t.removeProperty(`--wallpaper-image`),t.removeProperty(`--wallpaper-size`)),n&&n!==$h&&URL.revokeObjectURL(n.objectUrl)}tg(),qh(),(0,Oa.createRoot)(document.getElementById(`root`)).render((0,Q.jsx)(Z.StrictMode,{children:(0,Q.jsx)(Th,{})}));export{uu as $,Dd as A,Ua as At,Iu as B,If as C,mc as Ct,Sf as D,Js as Dt,xf as E,Xs as Et,Mu as F,ja as Ft,Au as G,hu as H,ju as I,Su as J,pu as K,Nu as L,Sd as M,Na as Mt,yd as N,Ma as Nt,Ld as O,Zs as Ot,Vu as P,Aa as Pt,du as Q,Tu as R,Vf as S,fc as St,Af as T,Ys as Tt,cu as U,ru as V,gu as W,wu as X,mu as Y,fu as Z,Lp as _,jc as _t,Lh as a,kl as at,Bf as b,Nc as bt,qh as c,ll as ct,Qh as d,Uc as dt,lu as et,eh as f,Kc as ft,Rp as g,Pc as gt,Jm as h,Ic as ht,Rh as i,Ol as it,Td as j,ka as jt,jd as k,ms as kt,Jh as l,_l as lt,Zm as m,zc as mt,jh as n,ku as nt,Wh as o,bl as ot,$m as p,qc as pt,Cu as q,zh as r,Eu as rt,Yh as s,ml as st,Ih as t,Ou as tt,Zh as u,dl as ut,Op as v,Lc as vt,Ff as w,ac as wt,Uf as x,oc as xt,Zf as y,Fc as yt,Du as z};