@augmentd-labs/canvas-web 2.26.22 → 2.26.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{FileForm-DhQhVnoi.js → FileForm-CqJpRbXv.js} +1 -1
- package/dist/assets/{FiltersApplet-gbu4I1fK.js → FiltersApplet-CcYMBq-Q.js} +1 -1
- package/dist/assets/{HomeFab-CXaEEzXy.js → HomeFab-D2pLJ9oc.js} +1 -1
- package/dist/assets/{IdentityFields-OPEWPlZs.js → IdentityFields-Bti7ojF3.js} +1 -1
- package/dist/assets/{LensApplet-FifF2RUs.js → LensApplet-DibGKbKC.js} +1 -1
- package/dist/assets/LinkToCard-5dg0jvSY.js +1 -0
- package/dist/assets/{NextShell-BIYs9fCL.js → NextShell-UX4Efo0u.js} +1 -1
- package/dist/assets/{NotesApplet-D94iQKg6.js → NotesApplet-DJp9Wuwt.js} +1 -1
- package/dist/assets/{ObjectPropertiesCard-ChvWbOpZ.js → ObjectPropertiesCard-BIBMvx_i.js} +4 -4
- package/dist/assets/{PathPickerField-DBe7jykL.js → PathPickerField-fZazwxCN.js} +1 -1
- package/dist/assets/{PickDocumentsCard-Bo224P4q.js → PickDocumentsCard-DamtV7fN.js} +1 -1
- package/dist/assets/{SketchApplet-ADVOnSLI.js → SketchApplet-DDIg411i.js} +1 -1
- package/dist/assets/{SketchEditor-CkgRysCG.js → SketchEditor-CKPPuZt3.js} +1 -1
- package/dist/assets/{TerminalApplet-CkO4uaE3.js → TerminalApplet-wGJG1PPc.js} +1 -1
- package/dist/assets/{TextDocumentEditor-COvsHJXH.js → TextDocumentEditor-CRre32cj.js} +1 -1
- package/dist/assets/{TodosApplet-Bpf1OIH4.js → TodosApplet-CleBd4uU.js} +1 -1
- package/dist/assets/{TodosWidget-BIYqPXUp.js → TodosWidget-CxiqmDuJ.js} +1 -1
- package/dist/assets/{UploadProgressList-BXJr87lI.js → UploadProgressList-DRJzjy6A.js} +1 -1
- package/dist/assets/{_agentId_-wN8YJoTZ.js → _agentId_--jQP7aTv.js} +0 -0
- package/dist/assets/{_contextId_-CoJraYnP.js → _contextId_-D6nNA8hC.js} +1 -1
- package/dist/assets/_workspaceName_-DfHnlgVg.js +1 -0
- package/dist/assets/{about-CT6Ghfkb.js → about-DVlaoa-W.js} +1 -1
- package/dist/assets/{add-BzgCpo5S.js → add-Bq99uA2R.js} +1 -1
- package/dist/assets/{agents-DIJpWCkc.js → agents-CRnO7j5E.js} +1 -1
- package/dist/assets/{appearance-D1EpKWaK.js → appearance-BAH_8zeF.js} +1 -1
- package/dist/assets/{applet-target-ChiiXVdC.js → applet-target-C_gBgU-Z.js} +1 -1
- package/dist/assets/{apps-DX8oWukQ.js → apps-EwUooEtp.js} +1 -1
- package/dist/assets/backend-sync-progress-pZrhQPk3.js +7 -0
- package/dist/assets/{content-app-view-DS6Nrz6M.js → content-app-view-BF-k-5Y7.js} +1 -1
- package/dist/assets/{context-mfIOB8dN.js → context-DQoZFMDQ.js} +1 -1
- package/dist/assets/{contexts-CRWqFXzJ2.js → contexts-CvMtPd1N2.js} +1 -1
- package/dist/assets/{date-time-picker-B6mkWt-g.js → date-time-picker-DebNUTx3.js} +1 -1
- package/dist/assets/{document-CX543Kcz.js → document-DOp6AbOi.js} +1 -1
- package/dist/assets/document-list-Dsf1DVEx.js +2 -0
- package/dist/assets/embedding-B5JiUA9X.js +1 -0
- package/dist/assets/{embedding-BHnBCyUx.js → embedding-B7cWrpy0.js} +1 -1
- package/dist/assets/{home-3vhobmCu.js → home-Dc60CSIJ.js} +1 -1
- package/dist/assets/{index-CiBgHujl.js → index-D5Q9EUVc.js} +6 -6
- package/dist/assets/inferd-config-editor--MDmN_7w.js +1 -0
- package/dist/assets/{key-bindings-BNeY-GEg.js → key-bindings-Bqkl5tDH.js} +1 -1
- package/dist/assets/{offline-CsRyFUg7.js → offline-COOUcZsG.js} +1 -1
- package/dist/assets/{public-share-DXxVwHKT.js → public-share-g_wBd6BW.js} +1 -1
- package/dist/assets/{query-debug-BUUG3jpK.js → query-debug-CrPsUwT-.js} +1 -1
- package/dist/assets/{registry-DTWAywyJ.js → registry-DIfZf6LB.js} +2 -2
- package/dist/assets/{roles-BYHLwWCD.js → roles-Bo9GZdOk.js} +1 -1
- package/dist/assets/{settings-DNhy58i9.js → settings-BeN2UmZL.js} +1 -1
- package/dist/assets/{settings-DjnFAqIe.js → settings-CzxxI2yw.js} +1 -1
- package/dist/assets/{settings-jWfP7CP8.js → settings-Dl1FnW9g.js} +1 -1
- package/dist/assets/settings-DqHAUBU4.js +14 -0
- package/dist/assets/{share-target-CgHlnZLH.js → share-target-BWFFRO5O.js} +1 -1
- package/dist/assets/{shared-BMoiShd9.js → shared-B5Pvz8wr.js} +1 -1
- package/dist/assets/{shared-D2uRUNdC.js → shared-BQZGA3ph.js} +1 -1
- package/dist/assets/{sketch-lazy-pbG2cCpW.js → sketch-lazy-C4pjV1WK.js} +2 -2
- package/dist/assets/{text-documents-BvDFBVnC.js → text-documents-0P9jkIpu.js} +2 -2
- package/dist/assets/{use-applet-docs-o5NAUFBk.js → use-applet-docs-D5eXpITp.js} +1 -1
- package/dist/assets/{use-applet-target-cO-FiyPQ.js → use-applet-target-gXPvZGgx.js} +1 -1
- package/dist/assets/use-canvas-pins-CbAxLLTU.js +3 -0
- package/dist/assets/{use-workspace-identity-mgaofjsD.js → use-workspace-identity-BCrrvfeE.js} +1 -1
- package/dist/assets/{useAddTarget-DUjaZdBQ.js → useAddTarget-CqnDU0Om.js} +1 -1
- package/dist/assets/{useAgentModels-Sa4N8WFd.js → useAgentModels-CYDYTjgG.js} +1 -1
- package/dist/assets/{useDocumentThumbnail-DYLCC63L.js → useDocumentThumbnail-DunxmU1A.js} +1 -1
- package/dist/assets/{useEditNoteFields-zHEWwDfB.js → useEditNoteFields-BehI0vog.js} +1 -1
- package/dist/assets/workspace-CrSpR4xf.js +1 -0
- package/dist/assets/{workspace-area-menu-UamvRNfd.js → workspace-area-menu-CP5OWZNX.js} +1 -1
- package/dist/assets/{workspace-content-gate-Be4tLYiB.js → workspace-content-gate-9okuA7J7.js} +1 -1
- package/dist/assets/{workspace-import-form-BRwc_oVg.js → workspace-import-form-aR-DwHf6.js} +1 -1
- package/dist/assets/{workspaces-gQY1mczH.js → workspaces-B9gcHMCE.js} +1 -1
- package/dist/index.html +25 -25
- package/dist/sw.js +1 -1
- package/package.json +2 -2
- package/dist/assets/LinkToCard-nR7Lal_o.js +0 -1
- package/dist/assets/_workspaceName_-CXuIfG46.js +0 -1
- package/dist/assets/backend-sync-progress-BeI9mDEX.js +0 -7
- package/dist/assets/document-list-SsF3jmuq.js +0 -2
- package/dist/assets/embedding-CEGjemkq.js +0 -1
- package/dist/assets/inferd-config-editor-BHUUFArV.js +0 -1
- package/dist/assets/settings-DH3ZiQLR.js +0 -14
- package/dist/assets/use-canvas-pins-Bth_Q--t.js +0 -3
- package/dist/assets/workspace-DvxC7pw1.js +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{_t as r,yt as i}from"./react-BHzhHVTZ.js";import{Br as a,Cr as o,Hr as s,It as c,Kn as l,L as u,Un as d,Xn as f,_n as p,mt as m,yt as h,zn as g}from"./ui-Byg1cZDr.js";import{t as _}from"./utils-2pl1SbIp.js";import{t as v}from"./button-SgR3GVvV.js";import{K as y,Ot as b,Pn as x,Pt as S,Q as C,gt as w,ht as T,it as ee,q as te,t as ne}from"./workspace-DvxC7pw1.js";import{t as E}from"./useEscapeClose-DR_xKT_k.js";import{t as re}from"./useToastHelpers-CRrpIIdY.js";import{s as D}from"./layer-style-Byl5LNFR.js";import{i as O}from"./color-DFEH4BfK.js";import{t as ie}from"./DocumentIcon-x299QNu_.js";var k=e(n(),1),A=t();function j({className:e=`h-5 w-5`,...t}){return(0,A.jsxs)(`svg`,{className:`animate-spin ${e}`,xmlns:`http://www.w3.org/2000/svg`,fill:`none`,viewBox:`0 0 24 24`,...t,children:[(0,A.jsx)(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),(0,A.jsx)(`path`,{className:`opacity-75`,fill:`currentColor`,d:`M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z`})]})}var M=e(i(),1);function ae(e){let[t,n]=(0,k.useState)(null);(0,k.useEffect)(()=>{if(!e)return;let t=!1;return C(e).then(r=>{t||n({workspaceId:e,predicates:r,error:!1})},()=>{t||n({workspaceId:e,predicates:[],error:!0})}),()=>{t=!0}},[e]);let r=t?.workspaceId===e?t:null;return{predicates:r?.predicates??[],error:r?.error??!1,loading:!!e&&!r}}function N({x:e,y:t,onClose:n,className:r,children:i}){let a=(0,k.useRef)(null),[o,s]=(0,k.useState)({x:e,y:t});return E(n),(0,k.useLayoutEffect)(()=>{let n=a.current;if(!n)return;let{width:r,height:i}=n.getBoundingClientRect();s({x:Math.max(8,Math.min(e,window.innerWidth-r-8)),y:Math.max(8,Math.min(t,window.innerHeight-i-8))})},[e,t]),(0,M.createPortal)((0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:`fixed inset-0 z-menu-scrim`,onClick:n,onContextMenu:e=>{e.preventDefault(),n()}}),(0,A.jsx)(`div`,{ref:a,style:{left:o.x,top:o.y},className:_(`fixed z-menu max-h-viewport-modal overflow-y-auto`,r,`bg-popover text-popover-foreground`),children:i})]}),document.body)}var P=typeof navigator<`u`&&/Mac|iPhone|iPad/.test(navigator.platform||navigator.userAgent),F={Delete:`Del`,Backspace:`⌫`,Enter:`↵`,ArrowUp:`↑`,ArrowDown:`↓`};function I(e){let t=e.split(`+`),n=t.pop()||``,r=F[n]||(n.length===1?n.toUpperCase():n);if(P){let e={Mod:`⌘`,Shift:`⇧`,Alt:`⌥`,Ctrl:`⌃`};return[...[`Ctrl`,`Alt`,`Shift`,`Mod`].filter(e=>t.includes(e)).map(t=>e[t]),r].join(``)}return[...t.map(e=>e===`Mod`?`Ctrl`:e),r].join(`+`)}function L(e,t){let n=t.split(`+`),r=n.pop()||``;return(P?e.metaKey:e.ctrlKey)!==n.includes(`Mod`)||e.shiftKey!==n.includes(`Shift`)||e.altKey!==n.includes(`Alt`)||P&&e.ctrlKey!==n.includes(`Ctrl`)?!1:r.length===1?e.key.toLowerCase()===r.toLowerCase():e.key===r}function R(e){if(e?.closest?.(`input, textarea, select, [contenteditable="true"], [role="dialog"], [role="menu"]`))return!0;let t=typeof window<`u`?window.getSelection():null;return!!t&&!t.isCollapsed&&t.toString().length>0}function z(e,t){if(e.defaultPrevented||e.nativeEvent.isComposing||R(e.target))return!1;let n=t.find(t=>t.shortcut&&!t.disabled&&L(e,t.shortcut));return n?(e.preventDefault(),e.stopPropagation(),n.run({shiftKey:e.shiftKey}),!0):!1}function oe(e){return e.key===`ContextMenu`||e.key===`F10`&&e.shiftKey}function se(){return typeof window<`u`&&window.matchMedia(`(max-width: 767px)`).matches}function B(e,t=`below`){let n=e.getBoundingClientRect();return t===`below`?{x:n.left,y:n.bottom+4}:{x:n.left+Math.min(24,n.width/2),y:n.top+Math.min(24,n.height/2)}}function V(e){let t=[];for(let n of e){let e=t[t.length-1];e&&(e[0].group??``)===(n.group??``)?e.push(n):t.push([n])}return t}function ce(e,t,n){t(),setTimeout(()=>{e.run({shiftKey:n})},0)}function le({anchor:e,items:t,onClose:n,label:r}){let i=(0,k.useRef)(null);return(0,k.useEffect)(()=>{let e=document.activeElement;return i.current?.querySelector(`[role="menuitem"]:not([aria-disabled="true"])`)?.focus(),()=>{e?.isConnected&&e.focus({preventScroll:!0})}},[]),(0,A.jsx)(N,{x:e.x,y:e.y,onClose:n,className:`min-w-[200px] rounded-lg border bg-popover text-popover-foreground py-1 shadow-elevation-3`,children:(0,A.jsx)(`div`,{ref:i,role:`menu`,"aria-label":r,onKeyDown:e=>{let t=Array.from(i.current?.querySelectorAll(`[role="menuitem"]:not([aria-disabled="true"])`)??[]);if(t.length===0)return;let r=t.indexOf(document.activeElement),a=e=>t[(e+t.length)%t.length]?.focus();switch(e.key){case`ArrowDown`:e.preventDefault(),a(r+1);return;case`ArrowUp`:e.preventDefault(),a(r<0?-1:r-1);return;case`Home`:e.preventDefault(),a(0);return;case`End`:e.preventDefault(),a(-1);return;case`Tab`:e.preventDefault(),n();return}if(e.key.length===1&&!e.ctrlKey&&!e.metaKey&&!e.altKey){let n=e.key.toLowerCase(),i=[...t.slice(r+1),...t.slice(0,r+1)].find(e=>e.textContent?.trim().toLowerCase().startsWith(n));i&&(e.preventDefault(),i.focus())}},onContextMenu:e=>e.preventDefault(),children:V(t).map((e,t)=>(0,A.jsxs)(k.Fragment,{children:[t>0&&(0,A.jsx)(`div`,{role:`separator`,className:`my-1 h-px bg-border`}),e[0].groupLabel&&(0,A.jsx)(`div`,{className:`px-3 py-1 text-[10px] font-medium uppercase tracking-wide text-muted-foreground`,children:e[0].groupLabel}),e.map(e=>{let t=e.icon;return(0,A.jsxs)(`button`,{type:`button`,role:`menuitem`,tabIndex:-1,"aria-disabled":e.disabled||void 0,title:e.hint,onClick:t=>{e.disabled||ce(e,n,t.shiftKey)},className:_(`flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm outline-none`,e.disabled?`cursor-default opacity-50`:e.destructive?`text-destructive hover:bg-destructive hover:text-destructive-foreground focus:bg-destructive focus:text-destructive-foreground`:`hover:bg-muted focus:bg-muted`),children:[t?(0,A.jsx)(t,{className:`h-3.5 w-3.5 shrink-0`}):(0,A.jsx)(`span`,{className:`w-3.5 shrink-0`}),(0,A.jsx)(`span`,{className:`flex-1 truncate`,children:e.label}),e.shortcut&&(0,A.jsx)(`kbd`,{className:`ml-4 shrink-0 font-sans text-[11px] text-muted-foreground`,children:I(e.shortcut)})]},e.id)})]},`${e[0].group??``}:${t}`))})})}function H({items:e,onClose:t,header:n}){E(t);let r=`flex w-full items-center gap-3 rounded-xl border bg-card px-4 py-3.5 text-base font-medium transition-transform active:scale-[.98]`;return(0,M.createPortal)((0,A.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 z-fullscreen flex flex-col bg-popover text-popover-foreground animate-in slide-in-from-bottom-10 fade-in duration-normal`,onClick:t,onContextMenu:e=>e.preventDefault(),children:[(0,A.jsxs)(`div`,{className:`flex shrink-0 items-start gap-3 border-b p-4`,onClick:e=>e.stopPropagation(),children:[(0,A.jsx)(`div`,{className:`min-w-0 flex-1`,children:n}),(0,A.jsx)(`button`,{type:`button`,onClick:t,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,"aria-label":`Close`,children:(0,A.jsx)(u,{className:`h-5 w-5`})})]}),(0,A.jsx)(`div`,{className:`min-h-4 flex-1`}),(0,A.jsxs)(`div`,{className:`max-h-[75vh] shrink-0 space-y-2 overflow-y-auto px-4 pt-2`,style:{paddingBottom:`calc(var(--safe-bottom) + 1.25rem)`},onClick:e=>e.stopPropagation(),children:[V(e).map((e,n)=>(0,A.jsxs)(`div`,{className:_(`space-y-2`,n>0&&`pt-2`),children:[e[0].groupLabel&&(0,A.jsx)(`div`,{className:`px-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground`,children:e[0].groupLabel}),e.map(e=>{let n=e.icon;return(0,A.jsxs)(`button`,{type:`button`,disabled:e.disabled,onClick:n=>ce(e,t,n.shiftKey),className:_(r,e.destructive&&`border-destructive/30 text-destructive`,e.disabled&&`opacity-50`),children:[n&&(0,A.jsx)(n,{className:_(`h-5 w-5 shrink-0`,!e.destructive&&`text-muted-foreground`)}),e.label]},e.id)})]},`${e[0].group??``}:${n}`)),(0,A.jsx)(`button`,{type:`button`,onClick:t,className:`${r} justify-center bg-muted`,children:`Cancel`})]})]}),window.document.body)}function ue({anchor:e,items:t,onClose:n,label:r,header:i}){return t.length===0?null:se()?(0,A.jsx)(H,{items:t,onClose:n,header:i??(r&&(0,A.jsx)(`div`,{className:`truncate text-base font-semibold`,children:r}))}):(0,A.jsx)(le,{anchor:e,items:t,onClose:n,label:r})}function U({items:e,onNavigate:t,disabled:n,className:r,label:i=`Tree path`}){let a=(0,k.useRef)(null),o=e[e.length-1]?.path;return(0,k.useEffect)(()=>{let e=a.current;e&&(e.scrollLeft=e.scrollWidth)},[o]),(0,A.jsx)(`nav`,{"aria-label":i,className:_(`min-w-0 flex-1`,r),children:(0,A.jsx)(`ol`,{ref:a,className:`flex min-w-0 items-center gap-1 overflow-x-auto py-0.5 text-sm`,children:e.map((r,i)=>{let a=i===e.length-1,o=_(`block max-w-56 truncate rounded px-1.5 py-1`,a?`font-medium text-foreground`:`text-muted-foreground`);return(0,A.jsxs)(`li`,{className:`flex shrink-0 items-center gap-1`,children:[i>0&&(0,A.jsx)(`span`,{"aria-hidden":`true`,className:`text-muted-foreground/60`,children:`/`}),t&&!a?(0,A.jsx)(`button`,{type:`button`,title:r.path===`/`?`${r.label} (root)`:r.path,disabled:n,onClick:()=>t(r.path),className:_(o,`hover:bg-accent hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50`),children:r.label}):(0,A.jsx)(`span`,{title:r.path===`/`?r.label:r.path,"aria-current":a?`location`:void 0,className:o,children:r.label})]},r.path)})})})}function W(e,t){let n=e.split(`/`).filter(Boolean);return[{label:t,path:`/`},...n.map((e,t)=>({label:e,path:`/${n.slice(0,t+1).join(`/`)}`}))]}var de={context:(0,A.jsx)(d,{className:`h-3.5 w-3.5`}),directory:(0,A.jsx)(l,{className:`h-3.5 w-3.5`}),backends:(0,A.jsx)(g,{className:`h-3.5 w-3.5`}),relations:(0,A.jsx)(m,{className:`h-3.5 w-3.5`})},fe={context:`Context tree`,directory:`Directory tree`,backends:`Backends tree`,relations:`Relations`};function pe(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function me(e,t){let n=(0,k.useRef)(null),r=(0,k.useRef)(!1),i=()=>{n.current&&=(clearTimeout(n.current),null)},a=e=>t=>{if(r.current){r.current=!1;return}t.detail>1||e()};return t?{guardClick:a,handlers:{onContextMenu:n=>{n.preventDefault(),n.stopPropagation(),t({clientX:n.clientX,clientY:n.clientY,path:e})},onPointerDown:a=>{if(a.pointerType!==`touch`)return;let{clientX:o,clientY:s}=a;i(),n.current=setTimeout(()=>{r.current=!0,t({clientX:o,clientY:s,path:e})},500)},onPointerUp:i,onPointerLeave:i,onPointerMove:i}}:{handlers:{},guardClick:a}}function he(e,t,n){let r=pe(t,e.name);return r.toLowerCase().includes(n)||(e.label||``).toLowerCase().includes(n)?!0:e.children?.some(e=>he(e,r,n))??!1}var G=200;function ge({onConfirm:e,onCancel:t,busy:n}){let[r,i]=(0,k.useState)(``);return(0,A.jsxs)(`div`,{className:`flex min-h-11 items-center gap-2 rounded-(--card-radius) bg-card px-3 py-2.5 text-sm shadow-elevation-1`,children:[(0,A.jsx)(o,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,A.jsx)(`input`,{type:`text`,value:r,onChange:e=>i(e.target.value),onKeyDown:n=>{n.key===`Enter`&&r.trim()&&e(r.trim()),n.key===`Escape`&&t()},onBlur:()=>{n||t()},placeholder:`New folder name…`,autoFocus:!0,disabled:n,className:`w-full flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground`}),n&&(0,A.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:`Creating…`})]})}function _e({node:e,parentPath:t,query:n,selected:i,onToggle:o,onActivate:c,onRowMenu:l,createParent:u,onCreateConfirm:d,onCreateCancel:f,creating:p}){let m=pe(t,e.name),h=!!e.children?.length,[g,v]=(0,k.useState)(!1),{handlers:y,guardClick:b}=me(m,l);if(n&&!he(e,t,n))return null;let x=u===m,S=g||n.length>0||x,C=i.has(m),w=e.type===`canvas`,T=D(e);return(0,A.jsxs)(`div`,{children:[(0,A.jsxs)(`div`,{className:_(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none text-sm shadow-elevation-1 hover:shadow`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,C?`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),onClick:b(()=>o(m)),onDoubleClick:e=>{e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||e.target.closest(`button,input,textarea,select,a,[contenteditable="true"]`)||(e.preventDefault(),e.stopPropagation(),h?v(e=>!e):c?.(m))},title:m,...y,children:[(0,A.jsx)(`button`,{type:`button`,"aria-label":`${S?`Collapse`:`Expand`} ${e.label||e.name}`,"aria-expanded":h?S:void 0,disabled:!h,className:_(`shrink-0 text-muted-foreground hover:text-foreground`,!h&&`invisible`),onClick:e=>{e.stopPropagation(),e.detail<=1&&v(e=>!e)},children:S?(0,A.jsx)(s,{className:`w-4 h-4`}):(0,A.jsx)(a,{className:`w-4 h-4`})}),(0,A.jsx)(r,{icon:T.icon||(w?`ph:squares-four-fill`:`ph:folder-fill`),width:16,height:16,color:O(T.color),className:_(`shrink-0`,!O(T.color)&&(w?`text-primary`:`text-muted-foreground`))}),(0,A.jsx)(`span`,{className:`flex-1 truncate font-medium`,title:e.description||void 0,children:e.label||e.name})]}),S&&h||x?(0,A.jsxs)(`div`,{className:`ml-[22px] mt-1.5 space-y-1.5`,children:[x&&d&&f&&(0,A.jsx)(ge,{busy:p,onConfirm:e=>{v(!0),d(m,e)},onCancel:f}),S&&e.children?.map(e=>(0,A.jsx)(_e,{node:e,parentPath:m,query:n,selected:i,onToggle:o,onActivate:c,onRowMenu:l,createParent:u,onCreateConfirm:d,onCreateCancel:f,creating:p},e.id||e.name))]}):null]})}function ve({workspaces:e,loading:t,onPick:n}){return t&&e.length===0?(0,A.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):e.length===0?(0,A.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`No workspaces found`}):(0,A.jsx)(`div`,{className:`space-y-1.5`,children:e.map(e=>{let t=O(e.color);return(0,A.jsxs)(`div`,{onClick:()=>n(e.name),className:`group relative flex cursor-pointer items-center gap-2 rounded-(--card-radius) bg-card px-3 py-2.5 shadow-elevation-1 transition-all hover:bg-accent/50 hover:shadow`,style:{borderRight:`6px solid ${t||`transparent`}`},children:[(0,A.jsx)(r,{icon:e.icon||`ph:stack-fill`,width:18,height:18,color:t,className:_(`shrink-0`,!t&&`text-muted-foreground`)}),(0,A.jsx)(`span`,{className:`flex-1 truncate text-sm font-medium`,children:e.label||e.name}),(0,A.jsx)(a,{className:`h-4 w-4 shrink-0 text-muted-foreground`})]},e.id||e.name)})})}function ye({workspaceName:e,treeTab:t,onTreeTabChange:n,selectedDocIds:r,onToggleDoc:i,onNavigate:o,excludeDocumentIds:c}){let[l,d]=(0,k.useState)(`folder`),[f,p]=(0,k.useState)(``),m=f.trim().toLowerCase(),[g,v]=(0,k.useState)(`/`),[b,S]=(0,k.useState)(null),[C,w]=(0,k.useState)(!1),[T,E]=(0,k.useState)([]),[re,D]=(0,k.useState)(!1),[O,j]=(0,k.useState)(``),[M,ae]=(0,k.useState)(``),[N,P]=(0,k.useState)(t),F=n?t:N,I=e=>{v(`/`),d(`folder`),j(``),ae(``),o?.(`/`),n?n(e):P(e)},[L,R]=(0,k.useState)(F);F!==L&&(R(F),v(`/`),d(`folder`)),(0,k.useEffect)(()=>{let e=setTimeout(()=>ae(O.trim()),300);return()=>clearTimeout(e)},[O]),(0,k.useEffect)(()=>{let t=!1;async function n(){w(!0);try{let n=await y(e,F);t||S(n)}catch{t||S(null)}finally{t||w(!1)}}return n(),()=>{t=!0}},[e,F]),(0,k.useEffect)(()=>{if(l!==`documents`)return;let t=!1,n=F===`directory`?`directory`:ne,r=F===`context`?`context`:`directory`;async function i(){D(!0);try{let i=M?await ee(e,g,[],{treeName:n,treeType:r,q:M,limit:G}):await te(e,g,n,{limit:G});t||E(i.payload||[])}catch{t||E([])}finally{t||D(!1)}}return i(),()=>{t=!0}},[e,F,g,l,M]);let z=e=>{v(e),o?.(e)},oe=c?.size?T.filter(e=>!c.has(e.id)):T;return l===`folder`?(0,A.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,A.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-muted/30 px-3 py-2`,children:[!n&&(0,A.jsx)(`div`,{className:`flex items-center gap-1 rounded-md border border-input p-0.5`,children:[`context`,`directory`].map(e=>(0,A.jsxs)(`button`,{type:`button`,onClick:()=>I(e),className:_(`flex flex-1 items-center justify-center gap-1.5 rounded px-2 py-1 text-xs transition-colors`,F===e?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Browse the ${fe[e].toLowerCase()}`,children:[de[e],(0,A.jsx)(`span`,{className:`font-mono`,children:e===`directory`?`dir://`:`ctx://`})]},e))}),(0,A.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,A.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Step 1 of 2 · Pick a folder`}),(0,A.jsxs)(`button`,{type:`button`,onClick:()=>d(`documents`),className:`inline-flex items-center gap-1 rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground transition-opacity hover:opacity-90`,children:[`Next `,(0,A.jsx)(a,{className:`h-3.5 w-3.5`})]})]}),(0,A.jsx)(U,{items:W(g,e),onNavigate:z,label:`Folder path`}),(0,A.jsxs)(`div`,{className:`relative`,children:[(0,A.jsx)(h,{className:`pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,A.jsx)(`input`,{type:`text`,placeholder:`Filter folders…`,value:f,onChange:e=>p(e.target.value),className:`w-full rounded-md border border-input bg-background py-1.5 pl-8 pr-3 text-xs placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring`})]})]}),(0,A.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,children:C?(0,A.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:_(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none text-sm shadow-elevation-1 hover:shadow`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,g===`/`?`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),onClick:()=>z(`/`),onDoubleClick:()=>{z(`/`),d(`documents`)},title:`/`,children:[(0,A.jsx)(s,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,A.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:`/`})]}),(0,A.jsx)(`div`,{className:`ml-[22px] space-y-1.5`,children:b?.children?.length?b.children.map(e=>(0,A.jsx)(_e,{node:e,parentPath:`/`,query:m,selected:new Set([g]),onToggle:z,onActivate:e=>{z(e),d(`documents`)}},e.id||e.name)):(0,A.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})})]})})]}):(0,A.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,A.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-muted/30 px-3 py-2`,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,A.jsxs)(`button`,{type:`button`,onClick:()=>d(`folder`),className:`inline-flex min-w-0 items-center gap-1 rounded-md px-1.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:`Back to folders`,children:[(0,A.jsx)(a,{className:`h-3.5 w-3.5 shrink-0 rotate-180`}),(0,A.jsx)(`span`,{children:`Folders`})]}),(0,A.jsx)(`span`,{className:`ml-auto shrink-0 text-xs text-muted-foreground`,children:`Step 2 of 2 · Pick a document`})]}),(0,A.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,A.jsxs)(`span`,{className:`shrink-0 font-mono text-xs text-muted-foreground`,children:[`[`,F,`]`]}),(0,A.jsx)(U,{items:W(g,e),onNavigate:z,label:`Document folder path`})]}),(0,A.jsxs)(`div`,{className:`relative`,children:[(0,A.jsx)(h,{className:`pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,A.jsx)(`input`,{type:`text`,placeholder:`Search documents in this folder…`,value:O,onChange:e=>j(e.target.value),className:`w-full rounded-md border border-input bg-background py-1.5 pl-8 pr-7 text-xs placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring`}),O&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>j(``),className:`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,"aria-label":`Clear document search`,children:(0,A.jsx)(u,{className:`h-3.5 w-3.5`})})]})]}),(0,A.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1 overflow-y-auto p-3`,children:re?(0,A.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading documents…`}):oe.length===0?(0,A.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:M?`No documents match “${M}” here.`:`No documents in this folder.`}):oe.map(e=>{let t=x(e),n=r.has(e.id);return(0,A.jsxs)(`div`,{onClick:()=>i(e.id),className:_(`flex min-h-9 items-center gap-2 rounded-md px-3 py-1.5 cursor-pointer transition-all select-none text-sm`,n?`bg-primary/[0.08] hover:bg-primary/[0.12]`:`hover:bg-primary/[0.04]`),children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>i(e.id),className:`shrink-0`,onClick:e=>e.stopPropagation()}),(0,A.jsx)(ie,{document:e,size:3.5}),(0,A.jsx)(`span`,{className:`flex-1 truncate`,children:t.title})]},e.id)})})]})}function be({onClose:e,onConfirm:t,documentCount:n,fixedWorkspaceName:r,excludeWorkspace:i,multiple:o=!0,saving:l=!1,savingContent:d,sizeClassName:m,tabs:g=[`context`,`directory`],initialTab:x,title:C,confirmLabel:ee,backendFolderCreation:te,onConfirmRelation:D,relationWorkspaceName:O,relationPredicates:ie,relationExcludeIds:M}){let[N,P]=(0,k.useState)(r?`tree`:`workspace`),[F,I]=(0,k.useState)([]),[L,R]=(0,k.useState)(!r),[z,oe]=(0,k.useState)(r??null),se=x&&g.includes(x)?x:g.includes(`context`)||g.includes(`directory`)?`pins`:g[0]??`context`,[B,V]=(0,k.useState)(se),ce=ae(g.includes(`relations`)&&!ie?O??z:null),H=ie??ce.predicates,[ue,U]=(0,k.useState)(``),W=H.includes(ue)?ue:H[0]??``,[pe,he]=(0,k.useState)(`out`),[G,be]=(0,k.useState)(new Set),[xe,Se]=(0,k.useState)(null),[K,Ce]=(0,k.useState)(`context`),[we,Te]=(0,k.useState)(!1),Ee=B===`pins`?K:B;(0,k.useEffect)(()=>{if(!z)return;let e=!1;return b(z).then(t=>{e||Se(t)}).catch(()=>{e||Te(!0)}),()=>{e=!0}},[z]);let q=B===`relations`,[De,Oe]=(0,k.useState)(null),[ke,Ae]=(0,k.useState)(!1),[J,Y]=(0,k.useState)(new Set),[je,Me]=(0,k.useState)(``),Ne=je.trim().toLowerCase(),{showErrorToast:Pe}=re(),[X,Fe]=(0,k.useState)(null),[Ie,Z]=(0,k.useState)(null),[Q,Le]=(0,k.useState)(!1);E(e,!l&&!Q);let Re=me(`/`,e=>Fe(e)),ze=e=>!l&&(B===`backends`?te?.canCreate(e)===!0:B!==`pins`&&B!==`relations`),Be=async(e,t)=>{let n=t.trim().replace(/^\/+|\/+$/g,``);if(!(!n||!z||Q||!ze(e))){Le(!0);try{let t=`${e===`/`?``:e}/${n}`,r=B===`context`?ne:B;B===`backends`?await te.create(e,n):await T(z,t,!0,r),w(z,r),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:z,treeName:r,cacheInvalidated:!0}}));let i=await y(z,B);Oe(i),Y(e=>o?new Set([...e,t]):new Set([t])),Me(``),Z(null)}catch(e){Pe(e instanceof Error?e.message:`Failed to create folder`)}finally{Le(!1)}}},[Ve,He]=(0,k.useState)(r);r!==Ve&&(He(r),r||R(!0)),(0,k.useEffect)(()=>{r||S().then(e=>I(e.filter(e=>e.id!==i&&e.name!==i))).catch(()=>I([])).finally(()=>R(!1))},[r,i]),(0,k.useEffect)(()=>{if(!z||B===`relations`||B===`pins`)return;let e=!1,t=0;async function n(n=!1){let r=++t;n||Ae(!0);try{let n=await y(z,B);!e&&r===t&&Oe(n)}catch{!e&&r===t&&!n&&Oe(null)}finally{!e&&r===t&&Ae(!1)}}let r=e=>{let t=e.detail;t?.workspaceName&&t.workspaceName!==z||t?.treeName&&t.treeName!==B||(t?.cacheInvalidated||w(z,B),n(!0))};return window.addEventListener(`workspace:tree:refresh`,r),n(),()=>{e=!0,window.removeEventListener(`workspace:tree:refresh`,r)}},[z,B]);let Ue=e=>{e!==z&&(Se(null),Te(!1)),V(se),oe(e),Y(new Set),be(new Set),P(`tree`)},We=e=>{be(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},Ge=e=>{if(!o){Y(new Set([e]));return}Y(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},Ke=q?!!W&&G.size>0&&!!D:J.size>0,qe=async()=>{if(!(!z||l||!Ke)){if(q){await D?.({predicate:W,direction:pe,targetIds:Array.from(G)},{workspaceName:O??z});return}await t(Array.from(J),{workspaceName:z,treeName:Ee===`context`?ne:Ee,treeType:Ee===`context`?`context`:`directory`})}},$=n??1;return l&&d?(0,A.jsx)(`div`,{className:_(`flex flex-col overflow-hidden rounded-(--panel-radius) border bg-card shadow-elevation-4`,m||`h-viewport-card max-h-full w-[min(380px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`),children:d}):(0,A.jsxs)(`div`,{className:_(`flex flex-col overflow-hidden rounded-(--panel-radius) border bg-card shadow-elevation-4`,m||`h-viewport-card max-h-full w-[min(380px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`),children:[(0,A.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,A.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,A.jsx)(p,{className:`h-4 w-4`}),C??(N===`workspace`?`Link to…`:q?`Relate ${$} document${$===1?``:`s`} to…`:`Link ${$} document${$===1?``:`s`} to…`)]}),(0,A.jsx)(`button`,{type:`button`,onClick:e,disabled:l||Q,className:`text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40`,"aria-label":`Close`,children:(0,A.jsx)(u,{className:`h-4 w-4`})})]}),(0,A.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:(0,A.jsxs)(`div`,{className:`grid h-full w-[200%] grid-cols-2 transition-transform duration-normal`,style:{transform:N===`workspace`?`translateX(0)`:`translateX(-50%)`},children:[(0,A.jsx)(`div`,{className:`flex min-w-0 flex-col overflow-y-auto p-2`,children:(0,A.jsx)(ve,{workspaces:F,loading:L,onPick:Ue})}),(0,A.jsxs)(`div`,{className:`flex min-w-0 flex-col overflow-hidden`,children:[(0,A.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 overflow-x-auto border-b px-2 pt-2`,children:[!r&&(0,A.jsx)(`button`,{type:`button`,disabled:Q,onClick:()=>P(`workspace`),className:`mr-1 rounded p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground touch-target`,"aria-label":`Back to workspaces`,children:(0,A.jsx)(a,{className:`h-4 w-4 rotate-180`})}),(g.includes(`context`)||g.includes(`directory`))&&(0,A.jsxs)(`button`,{type:`button`,disabled:Q,onClick:()=>{V(`pins`),Y(new Set),Z(null)},className:_(`flex shrink-0 items-center gap-1.5 border-b-2 px-3 py-2 text-xs`,B===`pins`?`border-primary`:`border-transparent text-muted-foreground`),children:[(0,A.jsx)(c,{className:`h-3.5 w-3.5`}),`Pins`]}),g.map(e=>(0,A.jsxs)(`button`,{type:`button`,disabled:Q,onClick:()=>{V(e),Y(new Set),Z(null)},className:_(`flex shrink-0 items-center gap-1.5 rounded-t-md border-b-2 px-3 py-2 text-xs font-medium transition-colors`,B===e?`border-primary text-foreground`:`border-transparent text-muted-foreground hover:text-foreground`),children:[de[e],fe[e]]},e))]}),!q&&(0,A.jsx)(`div`,{className:`shrink-0 border-b p-2`,children:(0,A.jsxs)(`div`,{className:`relative`,children:[(0,A.jsx)(h,{className:`pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground`}),(0,A.jsx)(`input`,{type:`text`,placeholder:`Search paths…`,value:je,onChange:e=>Me(e.target.value),className:`w-full rounded-md border border-input bg-background py-2 pl-9 pr-3 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring`})]})}),q&&(0,A.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-primary/[0.04] px-3 py-2`,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(`label`,{htmlFor:`relation-predicate`,className:`shrink-0 text-xs text-muted-foreground`,children:`Predicate`}),(0,A.jsx)(`select`,{id:`relation-predicate`,value:W,onChange:e=>U(e.target.value),className:`min-w-0 flex-1 rounded-md border border-input bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-2 focus:ring-ring`,children:H.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})]}),(0,A.jsx)(`div`,{className:`flex items-center gap-1`,children:[{dir:`out`,label:`This → picked`,hint:`the ${$===1?`document`:`documents`} you started from ${W} the picked one(s)`},{dir:`in`,label:`Picked → this`,hint:`the picked document(s) ${W} the ${$===1?`one`:`ones`} you started from`}].map(({dir:e,label:t,hint:n})=>(0,A.jsx)(`button`,{type:`button`,title:n,onClick:()=>he(e),className:_(`flex-1 rounded-md border px-2 py-1.5 text-xs transition-colors`,pe===e?`border-primary bg-primary text-primary-foreground`:`border-input hover:bg-accent`),children:t},e))})]}),!q&&o&&(0,A.jsxs)(`div`,{className:`flex h-10 shrink-0 items-center gap-1.5 overflow-x-auto border-b bg-primary/[0.04] px-3`,children:[!J.size&&(0,A.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Selected folders appear here`}),Array.from(J).map(e=>(0,A.jsxs)(`span`,{className:`inline-flex max-w-full shrink-0 items-center gap-1 rounded-full bg-primary px-2 py-0.5 text-xs text-primary-foreground`,children:[(0,A.jsx)(`span`,{className:`truncate`,title:e,children:e}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>Ge(e),className:`shrink-0 rounded-full hover:bg-primary-foreground/20`,"aria-label":`Remove ${e}`,children:(0,A.jsx)(u,{className:`h-3 w-3`})})]},e))]}),q&&(O??z)&&(0,A.jsx)(ye,{workspaceName:O??z,treeTab:`context`,selectedDocIds:G,onToggleDoc:We,excludeDocumentIds:M}),B===`pins`&&(0,A.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3 space-y-2`,children:[!xe&&!we&&(0,A.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading pins…`}),we&&(0,A.jsx)(`p`,{className:`text-xs text-destructive`,children:`Could not load pins. You can still browse the trees.`}),!we&&xe?.length===0&&(0,A.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No pinned paths yet. Choose a path from a tree.`}),xe?.filter(e=>e.resolvable!==!1&&g.includes(e.tree===`context`?`context`:e.tree)&&`${e.label??e.name??``} ${e.path}`.toLowerCase().includes(Ne)).map(e=>{let t=e.tree===`context`?`context`:e.tree;return(0,A.jsxs)(`button`,{type:`button`,"aria-pressed":K===t&&J.has(e.path),className:_(`w-full rounded-md border p-3 text-left text-sm hover:bg-muted`,K===t&&J.has(e.path)&&`border-primary bg-primary/10`),onClick:()=>{K===t?Ge(e.path):(Ce(t),Y(new Set([e.path])))},children:[(0,A.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(c,{className:`h-3.5 w-3.5`}),e.label||e.name||e.path]}),(0,A.jsxs)(`span`,{className:`block truncate text-xs text-muted-foreground`,children:[t,` · `,e.path]})]},e.id)})]}),(0,A.jsx)(`div`,{className:_(`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,(q||B===`pins`)&&`hidden`),children:ke?(0,A.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:_(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none text-sm shadow-elevation-1 hover:shadow`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,J.has(`/`)?`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),onClick:Re.guardClick(()=>Ge(`/`)),title:`/`,...ze(`/`)?Re.handlers:{},children:[(0,A.jsx)(s,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,A.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:`/`})]}),(0,A.jsxs)(`div`,{className:`ml-[22px] space-y-1.5`,children:[Ie===`/`&&(0,A.jsx)(ge,{busy:Q,onConfirm:e=>Be(`/`,e),onCancel:()=>Z(null)}),De?.children?.length?De.children.map(e=>(0,A.jsx)(_e,{node:e,parentPath:`/`,query:Ne,selected:J,onToggle:Ge,onRowMenu:e=>{ze(e.path)&&Fe(e)},createParent:Ie,onCreateConfirm:Be,onCreateCancel:()=>Z(null),creating:Q},e.id||e.name)):Ie===`/`?null:(0,A.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})]})]})})]})]})}),N===`tree`&&(0,A.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between border-t px-4 py-3`,children:[(0,A.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:q?`${G.size} document${G.size===1?``:`s`} selected`:`${J.size} path${J.size===1?``:`s`} selected`}),(0,A.jsx)(v,{size:`sm`,onClick:qe,disabled:!Ke||l||Q,children:l?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(j,{className:`mr-1.5 h-3.5 w-3.5`}),q?`Relating…`:`Linking…`]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(p,{className:`mr-1 h-3.5 w-3.5`}),q?`Relate`:ee??`Link`]})})]}),X&&(0,A.jsx)(le,{anchor:{x:X.clientX,y:X.clientY},onClose:()=>Fe(null),items:[{id:`new-folder`,label:`New folder in ${X.path}`,icon:f,run:()=>Z(X.path)}]})]})}export{j as _,fe as a,ue as c,I as d,oe as f,ae as g,N as h,de as i,B as l,L as m,ye as n,W as o,R as p,ve as r,U as s,be as t,z as u};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{_ as r,g as i,h as a}from"./chunk-62JRHF6Z-vspAGgtK.js";import{Br as o,Hr as s,L as c,fn as l}from"./ui-Byg1cZDr.js";import{t as u}from"./utils-2pl1SbIp.js";import{t as d}from"./button-SgR3GVvV.js";import{c as f,t as p}from"./api-CA6WiiYM.js";import{t as m}from"./socket-CtH3EU9m.js";import{n as h}from"./use-toast-BlLDqSUO.js";import{$t as g,En as _,K as ee,Nt as te,O as ne,Qt as re,S as v,T as ie,Ut as y,Vt as b,Z as ae,at as oe,b as se,bt as ce,d as le,dn as ue,dt as de,gt as fe,it as pe,o as me,q as x,v as he,vt as ge,yn as S}from"./workspace-DvxC7pw1.js";import{n as _e,r as ve}from"./use-canvas-pins-Bth_Q--t.js";import{u as ye}from"./ObjectPropertiesCard-ChvWbOpZ.js";import{h as be,i as C,r as xe}from"./document-list-SsF3jmuq.js";import{n as Se}from"./use-toolbox-Ck_cLGgf.js";import{i as Ce}from"./color-DFEH4BfK.js";import{t as we}from"./geo-CZfs0E-x.js";import{c as Te}from"./backend-sync-progress-BeI9mDEX.js";import{a as Ee,i as De,n as Oe,o as ke}from"./workspace-BydSRtST.js";import{n as Ae,r as je,t as Me}from"./url-params-n7kU_WZ-.js";import{i as Ne}from"./use-menu-BiJ8N7sS.js";import{n as Pe}from"./last-path-BbXWC3b3.js";import{t as Fe}from"./workspace-area-menu-UamvRNfd.js";import{t as Ie}from"./workspace-content-gate-Be4tLYiB.js";import{t as Le}from"./form-panel-C34lByEH.js";import{a as Re,i as ze,n as Be,o as Ve,r as He,s as Ue,t as We}from"./content-app-view-DS6Nrz6M.js";import{i as Ge,o as Ke,r as qe}from"./query-debug-BUUG3jpK.js";var w=`session.open`,Je=`session.set`,Ye=`session.ids`,Xe=`session.materialize`,Ze=`session.close`,T=`session.delta`,E=e(n(),1),D=t();function Qe({workspaceId:e,workspaceName:t}){let[n,r]=(0,E.useState)([]),[i,a]=(0,E.useState)(new Set),o=t=>`${e}:${t.address}:${t.resyncStartedAt||``}`;(0,E.useEffect)(()=>{let t=!1,n=!1,i=!1,a=0,o=new Map,s=new Map,c=(e,t)=>{let n=e.filter(e=>e.address!==t.backend);if(!t.resyncing)return n;let r=e.find(e=>e.address===t.backend)||s.get(t.backend);return[...n,{address:t.backend,config:r?.config,resyncStartedAt:r?.resyncStartedAt||new Date().toISOString(),progress:t.progress??r?.progress}]},l=async()=>{if(n){i=!0;return}n=!0;let u=a;try{let n=await ce(e);if(!t){s=new Map(n.map(e=>[e.address,e]));let e=n.filter(e=>e.resyncing);for(let t of o.values())t.version>u&&(e=c(e,t.event));r(e)}}catch{}finally{n=!1,i&&!t&&(i=!1,l())}},u=t=>{t.workspaceId!==e||!t.backend||typeof t.resyncing!=`boolean`||(o.set(t.backend,{version:++a,event:t}),r(e=>c(e,t)))},d=t=>{t.workspaceId===e&&l()};l();let f=m.on(`connect`,l);return m.on(`backend.resync.changed`,u),m.on(`backend.changed`,d),window.addEventListener(`focus`,l),()=>{t=!0,f?.(),m.off(`backend.resync.changed`,u),m.off(`backend.changed`,d),window.removeEventListener(`focus`,l)}},[e]);let s=n.filter(e=>!i.has(o(e)));return s.length?(0,D.jsxs)(`aside`,{"aria-label":`Storage scans for ${t}`,className:`absolute bottom-5 right-5 z-50 w-72 max-w-[calc(100vw-2.5rem)] rounded-lg border bg-popover/95 p-3 text-popover-foreground shadow-lg backdrop-blur`,children:[(0,D.jsxs)(`div`,{role:`status`,className:`mb-2 flex items-center gap-2 text-sm font-medium`,children:[(0,D.jsx)(l,{"aria-hidden":`true`,className:`h-4 w-4 animate-spin`}),(0,D.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,D.jsx)(`span`,{className:`block`,children:`Scanning storage`}),(0,D.jsx)(`span`,{className:`block truncate text-xs font-normal text-muted-foreground`,title:t,children:t})]}),(0,D.jsx)(`button`,{type:`button`,"aria-label":`Hide scan progress for ${t}`,title:`Hide progress; scanning continues`,className:`rounded p-1 hover:bg-muted focus-visible:outline focus-visible:outline-2`,onClick:()=>a(e=>new Set([...e,...s.map(o)])),children:(0,D.jsx)(c,{"aria-hidden":`true`,className:`h-4 w-4`})})]}),(0,D.jsx)(`div`,{className:`max-h-48 space-y-3 overflow-y-auto`,children:s.map(e=>{let{scanned:t=0,total:n=null}=e.progress||{},r=n&&n>0?Math.min(100,Math.round(t/n*100)):null,i=typeof e.config?.label==`string`?e.config.label:e.address;return(0,D.jsxs)(`div`,{children:[(0,D.jsxs)(`div`,{className:`flex items-center justify-between gap-3 text-xs`,children:[(0,D.jsx)(`span`,{className:`truncate`,children:i}),(0,D.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,children:n===null?`${t} files`:`${t} / ${n}`})]}),(0,D.jsx)(`div`,{role:`progressbar`,"aria-label":`Scanning ${i}`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":r??void 0,className:`mt-1.5 h-1 overflow-hidden rounded-full bg-muted`,children:(0,D.jsx)(`div`,{className:`h-full rounded-full bg-primary ${r===null?`animate-pulse`:`transition-all`}`,style:{width:r===null?`35%`:`${r}%`}})})]},e.address)})})]}):null}var $e=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:null;function et(e){return`/${e}`.replace(/\/+/g,`/`).replace(/\/$/,``)||`/`}function tt(e,t,n){if(e==null)return[];if(Array.isArray(e))return e.flatMap(e=>tt(e,t,n));if(typeof e==`string`)return[{tree:null,kind:t,path:et(e)}];let r=$e(e);if(!r)return[];let i=r.tree??r.treeId,a=typeof i==`string`?n.get(i)??null:null;return[].concat(r.paths??r.path??`/`).filter(e=>typeof e==`string`).map(e=>({tree:a,kind:t,path:et(e)}))}function O(e){let t=[],n=e=>{let n=Number(e);Number.isSafeInteger(n)&&n>0&&t.push(n)};return Array.isArray(e.ids)&&e.ids.forEach(n),Array.isArray(e.documentIds)&&e.documentIds.forEach(n),e.id!=null&&n(e.id),e.documentId!=null&&n(e.documentId),t}function nt(e){let t=new Map;for(let n of e)t.set(n.id,n.name),t.set(n.name,n.name);return t}function rt(e,t,n=new Map){let r=$e(t);if(!r)return{targets:[],ids:[],unknown:!0};if(e.startsWith(`tree.`)){let e=typeof r.treeName==`string`?r.treeName:null,t=r.treeType===`directory`||r.treeType===`context`?r.treeType:null,n=r.contextSpec??r.path;return typeof n==`string`?{targets:[{tree:e,kind:t,path:et(n)}],ids:O(r),unknown:!1}:{targets:[],ids:[],unknown:!0}}let i=[...tt(r.context,`context`,n),...tt(r.directory,`directory`,n)],a=$e(r.changed);a&&i.push(...tt(a.context,`context`,n),...tt(a.directory,`directory`,n));let o=O(r);if(i.length)return{targets:i,ids:o,unknown:!1};let s=r.reason===`content`||r.reason===`relations`;return e.startsWith(`document.updated`)&&s&&o.length?{targets:[],ids:o,unknown:!1}:{targets:[],ids:o,unknown:!0}}function k(e,t){return e===t||e===`/`||t===`/`||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}function it(e,t){if(e.kind&&e.kind!==t.kind||e.tree&&e.tree!==t.tree)return!1;if(t.kind===`context`){let n=e=>et(e).split(`/`).filter(Boolean).map(e=>e.normalize(`NFKC`).trim().replace(/\s+/g,` `).replace(/[^\p{L}\p{N}\p{M} .+_@-]/gu,`_`).replace(/_+/g,`_`).toLowerCase()||`_`),r=new Set(n(e.path)),i=n(t.path);return r.size===0||i.length===0||i.some(e=>r.has(e))}return k(e.path,t.path)}function at(e){return rt(`tree.refresh`,{treeName:e?.treeName,path:e?.path||`/`})}function ot(e,t,n){if(e.unknown||e.targets.length&&(t.wholeWorkspace||e.targets.some(e=>it(e,t))))return!0;if(e.ids.length&&n){let t=n instanceof Set?n:new Set(n);if(e.ids.some(e=>t.has(e)))return!0}return!1}function st(e,t,n={}){return m.request(w,{workspace:e,specs:t,opts:n})}function ct(e,t,n){return m.request(Je,{sessionId:e,label:t,spec:n})}function lt(e){return m.request(Ye,{sessionId:e})}function A(e,t={}){return m.request(Xe,{sessionId:e,...t})}function ut(e){return m.request(Ze,{sessionId:e})}function dt(e){return m.on(T,e)}var ft=100;function pt({workspaceRef:e,specs:t,opts:n,enabled:r=!0}){let[i,a]=(0,E.useState)([]),[o,s]=(0,E.useState)(0),[c,l]=(0,E.useState)(null),[u,d]=(0,E.useState)(null),f=(0,E.useRef)([]),p=(0,E.useRef)(new Map),h=(0,E.useRef)(null),g=(0,E.useRef)(null),_=(0,E.useRef)(null),ee=(0,E.useRef)({}),te=(0,E.useRef)(null),ne=(0,E.useMemo)(()=>JSON.stringify(t),[t]),re=(0,E.useMemo)(()=>JSON.stringify(n??{}),[n]),v=(0,E.useCallback)(()=>{let e=p.current;a(f.current.map(t=>e.get(t)).filter(Boolean))},[]),ie=(0,E.useCallback)(async e=>{let t=g.current;if(!t||e.length===0)return[];let n=[];for(let r=0;r<e.length;r+=ft){let i=e.slice(r,r+ft),a=await pe(t,`/`,[],{ids:i,scope:`workspace`,limit:i.length});n.push(...a.payload||[])}return n},[]),y=(0,E.useCallback)(async(e,t,n)=>{if(t.length>0){let e=new Set(t);f.current=f.current.filter(t=>!e.has(t));for(let t of e)p.current.delete(t)}let r=e.filter(e=>!p.current.has(e)),i=new Set(f.current);for(let t of e)i.has(t)||(f.current.push(t),i.add(t));if(n!==null&&s(n),v(),r.length===0)return;let a=await ie(r);for(let e of a)p.current.set(e.id,e);let o=new Set(a.map(e=>e.id)),c=r.filter(e=>!o.has(e));if(c.length>0){let e=new Set(c);f.current=f.current.filter(t=>!e.has(t))}v()},[ie,v]),b=(0,E.useCallback)(async(e,t)=>{let n=e??[],r=new Set(n);f.current=f.current.filter(e=>r.has(e));for(let e of p.current.keys())r.has(e)||p.current.delete(e);let i=new Set(f.current),a=n.filter(e=>!i.has(e));await y(a,[],t)},[y]);(0,E.useEffect)(()=>{if(g.current=e??null,!r||!e)return;let t=!1,n=null,i=async()=>{try{let r=await st(e,JSON.parse(ne),JSON.parse(re));if(t){ut(r.sessionId).catch(()=>{});return}n=r.sessionId,h.current=r.sessionId,l(r.sessionId),d(null),f.current=[],p.current=new Map,await b(r.ids,r.count)}catch(e){if(t)return;d(e instanceof Error?e.message:`Failed to open query session`),l(null),h.current=null}};i();let o=m.on(`connect`,()=>{i()});return()=>{t=!0,o?.();let e=n??h.current;e&&ut(e).catch(()=>{}),h.current=null,f.current=[],p.current=new Map,l(null),a([]),s(0)}},[e,ne,re,r]),(0,E.useEffect)(()=>{if(!c)return;let e=dt(e=>{if(e.sessionId===c){if(_.current!==null){te.current?.(_.current,ee.current);return}e.ids===void 0?y(e.added??[],e.removed??[],e.count):b(e.ids,e.count)}});return()=>{e?.()}},[c,y,b]);let ae=(0,E.useCallback)(async()=>{let e=h.current;if(e)try{let t=await lt(e);await b(t.ids,t.count)}catch{}},[b]),oe=(0,E.useCallback)(async(e,t)=>{let n=h.current;if(!n)throw Error(`No open query session`);let r=await ct(n,e,t);if(_.current!==null){await te.current?.(_.current,ee.current);return}await b(r.ids,r.count)},[b]),se=(0,E.useCallback)(async(e,t={})=>{let n=h.current;if(!n)throw Error(`No open query session`);if(_.current=e,ee.current=t,e===null){await ae();return}let r=await A(n,{match:e,...t});for(let e of r.documents)p.current.set(e.id,e);f.current=r.ids,s(r.totalCount),v()},[v,ae]);(0,E.useEffect)(()=>{te.current=se},[se]);let ce=(0,E.useCallback)(async(e,t,n={})=>{let r=h.current;if(!r)throw Error(`No open query session`);let i=await A(r,{match:t,limit:n.limit??100,...n.mode?{mode:n.mode}:{}});for(let e of i.documents)p.current.set(e.id,e);let a=await ct(r,e,{ids:i.ids});return await b(a.ids,a.count),i.ids},[b]);return{documents:i,count:o,ready:c!==null,error:u,setCue:oe,resync:ae,rank:se,rankAndPin:ce}}function mt({data:e,className:t}){let[n,r]=(0,E.useState)(!0),{rows:i,gapIndex:a,span:c}=(0,E.useMemo)(()=>{let t=[...e.distances].sort((e,t)=>e.distance-t.distance),n=[];for(let e=1;e<t.length;e++)n.push(t[e].distance-t[e-1].distance);let r=n.length?[...n].sort((e,t)=>e-t)[Math.floor(n.length/2)]:0,i=-1,a=0;for(let e=0;e<n.length;e++)n[e]>a&&(a=n[e],i=e+1);let o=i>0&&a>=Math.max(r*4,1e-6),s=t[0]?.distance??0,c=t[t.length-1]?.distance??0;return{rows:t,gapIndex:o?i:-1,span:{first:s,last:c,biggest:a,median:r}}},[e.distances]);if(i.length===0)return(0,D.jsxs)(`div`,{className:u(`rounded-md border border-dashed border-border px-3 py-2 text-xs text-muted-foreground`,t),children:[`Query debug: no image distances for “`,e.query,`”. The dense side returned nothing: either no photos are embedded in this scope, or the image space is not ready.`]});let l=a>0?i[a].distance:null;return(0,D.jsxs)(`div`,{className:u(`rounded-md border border-border bg-muted/30 text-xs`,t),children:[(0,D.jsxs)(`button`,{type:`button`,onClick:()=>r(e=>!e),className:`flex w-full items-center gap-1.5 px-3 py-2 text-left font-medium`,children:[n?(0,D.jsx)(s,{className:`h-3.5 w-3.5`}):(0,D.jsx)(o,{className:`h-3.5 w-3.5`}),`Query debug`,(0,D.jsxs)(`span`,{className:`font-normal text-muted-foreground`,children:[`: image distances for “`,e.query,`” (`,i.length,` nearest, unfloored)`]})]}),n&&(0,D.jsxs)(`div`,{className:`space-y-2 border-t border-border px-3 py-2`,children:[(0,D.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Best-first cosine distance (0 = identical). Scroll to where the photos stop being relevant and set the image relevance floor just above that value in Settings → Database → Search tuning.`,l===null?(0,D.jsxs)(D.Fragment,{children:[` `,(0,D.jsx)(`span`,{className:`text-amber-600 dark:text-amber-500`,children:`No boundary in this window`}),`; the distances step evenly (typical Δ`,c.median.toFixed(4),`), so there is nothing here to set a floor from. Relevance probably ends further down the list than this window reaches, or the model is not separating this query at all.`]}):(0,D.jsxs)(D.Fragment,{children:[` A jump at `,(0,D.jsx)(`span`,{className:`font-mono`,children:l.toFixed(4)}),` (Δ`,c.biggest.toFixed(4),`, vs typical Δ`,c.median.toFixed(4),`) stands out (a likely boundary).`]})]}),(0,D.jsx)(`div`,{className:`max-h-56 overflow-y-auto`,children:(0,D.jsx)(`table`,{className:`w-full font-mono text-[11px]`,children:(0,D.jsx)(`tbody`,{children:i.map((e,t)=>(0,D.jsxs)(`tr`,{className:u(`border-b border-border/40 last:border-0`,t===a&&`border-t-2 border-t-amber-500/70`),children:[(0,D.jsx)(`td`,{className:`py-0.5 pr-3 text-muted-foreground`,children:t+1}),(0,D.jsxs)(`td`,{className:`py-0.5 pr-3`,children:[`#`,e.id]}),(0,D.jsx)(`td`,{className:`py-0.5 tabular-nums`,children:e.distance.toFixed(4)}),t===a&&(0,D.jsx)(`td`,{className:`py-0.5 pl-2 font-sans text-[10px] text-amber-600 dark:text-amber-500`,children:`← biggest gap`})]},e.id))})})}),(0,D.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Range `,c.first.toFixed(4),` – `,c.last.toFixed(4),` (spread `,(c.last-c.first).toFixed(4),`) over `,i.length,` rows. Absolute values shift with the model and are not comparable across models. After a re-embed every floor has to be picked again. A spread this narrow relative to the range means ranking is doing the work, not distance.`]})]})]})}function ht(e,t){if(!e)return[];let n=t.split(`/`).filter(Boolean),r=e;for(let e of n)if(r=r?.children?.find(t=>t.name===e)??null,!r)return[];let i=n.length?`/${n.join(`/`)}`:``,a=(r.children??[]).filter(e=>e.type!==`canvas`).map(e=>({name:e.name,path:`${i}/${e.name}`,label:e.label,color:e.color,childCount:e.children?.length??0})).sort((e,t)=>(e.label||e.name).localeCompare(t.label||t.name,void 0,{numeric:!0,sensitivity:`base`}));return n.length>0&&a.unshift({name:`..`,path:n.length>1?`/${n.slice(0,-1).join(`/`)}`:`/`,isParent:!0}),a}var gt=new Map;function _t(e,t,n){return`${e}\0${t}\0${n}`}function vt(e,t,n,r,i,a,o=``,s=``,c=`path`){return`${_t(e,t,n)}\0${r}\0${i}\0${a}\0${o}\0${s}\0${c}`}function j(e,t,n){let r=_t(e,t,n);for(let e of gt.keys())e.startsWith(r)&>.delete(e)}function yt(e,t){let n=`${e}\0`;for(let[e,r]of gt){if(!e.startsWith(n))continue;let[,i,a,,,,,,o=`path`]=e.split(`\0`);ot(t,{tree:i,kind:S(i),path:a,wholeWorkspace:o.startsWith(`workspace`)},r.documents.map(e=>Number(e.id)))&>.delete(e)}}function bt(e,t){yt(t?.workspaceName??e,at(t))}function xt(){let{workspaceName:e}=r();return e?(0,D.jsx)(Ie,{workspaceName:e,children:(0,D.jsx)(M,{})}):null}function M(){let{workspaceName:e,treeName:t}=r(),n=a(),o=i(),{showToast:s,showProgress:c}=h(),l=new URLSearchParams(n.search),Ie=(()=>{let e=l.getAll(`q`).map(e=>e.trim()).filter(Boolean);if(e.length>0)return e;let t=(l.get(`search`)||``).trim();return t?[t]:[]})(),[w,Je]=(0,E.useState)(null),[Ye,Xe]=(0,E.useState)(!0),[Ze,T]=(0,E.useState)([]),[$e,et]=(0,E.useState)(!1),[tt,O]=(0,E.useState)(0),k=qe(),[it,st]=(0,E.useState)(null),[ct,lt]=(0,E.useState)(k);ct!==k&&(lt(k),k||st(null));let[A,ut]=(0,E.useState)(`path`),[dt,ft]=(0,E.useState)(!1),[_t,xt]=(0,E.useState)(null),[M,St]=(0,E.useState)(null),[wt,Tt]=(0,E.useState)(``),[Et,Dt]=(0,E.useState)(!1),[Ot,kt]=(0,E.useState)(!1),[At,jt]=(0,E.useState)(!1),[N,Mt]=(0,E.useState)(null),[P,F]=(0,E.useState)(1),[I,Nt]=(0,E.useState)(50),[L,Pt]=(0,E.useState)(Ie),[Ft,It]=(0,E.useState)(null),{state:R,saveFilters:Lt,setSort:Rt,setAccentColor:zt,setMapDocuments:Bt}=Se(),Vt=R.filters.features.allOf,z=R.filters.features.anyOf,Ht=R.filters.features.noneOf,Ut=De(R.filters.timeline),Wt=Ee(R.filters.geo),Gt=ke(R.filters.lens,R.filters.geo.includeUnlocated),B=R.filters.lens.ids,Kt=[...Ut,...Wt,...Gt],qt=R.filters.sort??Oe,Jt=JSON.stringify({a:Vt,b:z,c:Ht,d:Kt,i:B,s:qt}),Yt=JSON.stringify({a:Vt,b:z,c:Ht,d:Kt,s:qt}),V=Ae(n.pathname).path,H=t??`context`,U=H===`backends`,[Xt,Zt]=(0,E.useState)([]);(0,E.useEffect)(()=>{!U||!e||ce(e).then(Zt).catch(()=>Zt([]))},[U,e]);let Qt=U?me(V,Xt):null,[$t,en]=(0,E.useState)(!1),tn=`${H}\0${V}`,[nn,rn]=(0,E.useState)(tn);nn!==tn&&(rn(tn),en(!1));let W=l.get(`layer`)===`1`,G=l.get(`layerId`)||null,[K,an]=(0,E.useState)(null),[q,on]=(0,E.useState)(null),sn=(0,E.useRef)(null);(0,E.useEffect)(()=>{sn.current=q},[q]);let[cn,ln]=(0,E.useState)(`left`),[un,dn]=(0,E.useState)([]),{openM1Drawer:fn,openM2Drawer:pn,goBack:mn}=Ne(),[hn,gn]=(0,E.useState)([]),J=(0,E.useMemo)(()=>{if(!K||V===`/`||W)return null;let e=V.split(`/`).filter(Boolean),t=K;for(let n of e)if(t=t?.children?.find(e=>e.name===n)??null,!t)return null;return t},[K,V,W]),Y=J?.type===`canvas`?`canvas`:null,_n=(0,E.useRef)(null);(0,E.useEffect)(()=>{!e||!K||W||_n.current===`${e}/${H}`&&(V!==`/`&&!J||Pe(e,H,V))},[e,K,W,V,J,H]);let vn=(0,E.useMemo)(()=>W||A===`workspace`||L.length>0||S(H)!==`directory`?[]:ht(K,V),[K,V,H,W,A,L]),yn=W?null:V===`/`?K:J,X=be(),bn=`${H}\0${V}`,[xn,Sn]=(0,E.useState)(null),Cn=xn?.key===bn?xn.views:Ve(yn?.metadata),wn=X?.pinned&&X.view?[X.view,...Cn.filter(e=>e.id!==X.view.id)]:Cn,Tn=X?.pinned&&X.view?X.view.id:xn?.key===bn?xn.activeId:wn[0]?.id??ze.id,Z=wn.find(e=>e.id===Tn)??wn[0]??ze;(0,E.useEffect)(()=>{X?.selectView(Z)},[Z,X]);let En=U?void 0:X?.schema??Re(Z),Dn=En?[...Vt,En]:Vt,On=e=>{let t=wn.find(t=>t.id===e);t&&X?.selectView(t),F(1),dn([]),Sn({key:bn,views:wn,activeId:e})},kn=(t,n)=>{n&&n!==Tn&&(F(1),dn([]));let r=t.find(e=>e.id===(n??Tn));r&&X?.selectView(r),Sn({key:bn,views:t,activeId:n??Tn}),_(e,V,{metadata:{...yn?.metadata??{},views:t}},H).catch(()=>{s({title:`View not saved`,description:`Could not persist views to the layer`,variant:`destructive`})})},An=Y===`canvas`&&typeof J?.querySpec?.query==`string`?J.querySpec.query:``,jn=Y===`canvas`?{label:J?.label,description:J?.description,color:J?.color}:null,{isPinned:Mn,pin:Nn,unpin:Pn,pins:Fn}=_e(),In=w?.name,Q=(0,E.useMemo)(()=>In&&Y===`canvas`&&!W?{workspaceName:In,treeName:H,path:V}:null,[In,Y,W,H,V]),Ln=Q?Mn(Q):!1,Rn=J?.id,zn=J?.label,Bn=(0,E.useCallback)(async()=>{if(Q)try{let e=Fn.find(e=>e.workspaceName===Q.workspaceName&&e.treeName===Q.treeName&&e.path===Q.path);e?await Pn(e.id):await Nn({...Q,layerId:Rn,label:zn})}catch(e){console.error(`Failed to update home pins:`,e)}},[Q,Fn,Nn,Pn,Rn,zn]),Vn=e?`${e}://${V===`/`?``:V.replace(/^\//,``)}`:``,Hn=Ce(w?.color)||null;(0,E.useEffect)(()=>(zt(Hn),()=>zt(null)),[Hn,zt]);let Un=(0,E.useCallback)(async t=>{let n=B;if(t?.anyOf?.length&&z.length&&(n=((await x(e,V,H,{limit:0,anyOf:z,ids:B,applyCanvasSpec:!1})).payload||[]).map(e=>e.id),!n.length))return{payload:[],count:0,totalCount:0};let r=await x(e,V,H,{limit:t?.limit,offset:t?.offset,page:t?.page,sortBy:t?.sortBy,order:t?.order,allOf:[...Vt,...t?.allOf??[]],anyOf:t?.anyOf?.length?t.anyOf:z,noneOf:Ht,filters:Kt,ids:n,queries:[...L,...t?.queries??[],...t?.q?[t.q]:[]],applyCanvasSpec:!1});return{payload:r.payload||[],count:r.count??void 0,totalCount:r.totalCount??void 0}},[e,V,H,Jt,L]);(0,E.useEffect)(()=>{e&&(async()=>{Xe(!0);try{let t=await p.get(`${f.workspaces}/${e}`),n;n=t&&`workspace`in t?t.workspace:t,Je(n)}catch(t){let n=t instanceof Error?t.message:`Failed to fetch workspace ${e}`;s({title:`Error`,description:n,variant:`destructive`}),Je(null)}finally{Xe(!1)}})()},[e,s]),(0,E.useEffect)(()=>{let e=e=>{let t=e.detail?.workspace;t&&Je(e=>e&&(t===e.name||t===e.id)&&e.status!==`active`?{...e,status:`active`}:e)};return window.addEventListener(`workspace:autostarted`,e),()=>window.removeEventListener(`workspace:autostarted`,e)},[]);let Wn=(B?.length??0)>0&&!W&&!($t&&Qt)&&L.length<=1,{documents:Gn,count:Kn,ready:qn,setCue:Jn,resync:Yn,rank:Xn}=pt({workspaceRef:e,specs:(0,E.useMemo)(()=>{let e={features:{allOf:Dn,anyOf:z,noneOf:Ht},filters:Kt};return A!==`workspace`&&(S(H)===`directory`?e.directory={tree:H,path:V}:e.context=V),[{label:`scope`,spec:e}]},[Yt,V,H,A,En]),opts:(0,E.useMemo)(()=>({mode:`live`,debounceMs:150}),[]),enabled:Wn}),Zn=Wn&&qn,Qn=(0,E.useRef)(!1);(0,E.useEffect)(()=>{Qn.current=Zn},[Zn]);let $n=L.length===1?L[0].trim():``;(0,E.useEffect)(()=>{qn&&Xn($n?{text:$n}:null,{limit:I,offset:(P-1)*I}).catch(()=>{})},[qn,$n,I,P,Xn]);let er=(B??[]).join(`,`);(0,E.useEffect)(()=>{qn&&Jn(`lens`,{ids:B??[]}).catch(()=>{})},[qn,er,Jn,B]);let tr=Zn?Gn:Ze,nr=Zn?Kn:tt,rr=(0,E.useRef)(new Set);(0,E.useEffect)(()=>{rr.current=new Set(tr.map(e=>Number(e.id)))},[tr]);let ir=R.geoSelection;(0,E.useEffect)(()=>{Bt(tr,w?.name??null)},[tr,w?.name,Bt]),(0,E.useEffect)(()=>()=>Bt([]),[Bt]);let ar=(0,E.useMemo)(()=>ir?tr.filter(e=>we(e,ir,R.filters.geo.includeUnlocated)):tr,[tr,ir,R.filters.geo.includeUnlocated]),or=le(V,Dn,{treeName:H,treeType:S(H),scope:A,queries:L,anyOf:z,noneOf:Ht,filters:Kt,ids:B,layerId:W&&G?G:void 0}),sr=JSON.stringify([e,or]),[cr,lr]=(0,E.useState)(``),[ur,dr]=(0,E.useState)(!1),fr=(0,E.useRef)(!1),pr=$e||ur||cr!==sr||Zn||!!ir,mr=(0,E.useRef)(0),hr=(0,E.useRef)(null);(0,E.useEffect)(()=>()=>{mr.current++,hr.current=null},[]);let gr=(0,E.useRef)(``),$=(0,E.useCallback)(async t=>{if(!e)return;if(Te(H,V)){mr.current++,hr.current=null,gr.current=``,T([]),O(0),et(!1);return}if(Qn.current)return;let n=`${$t&&Qt?`${A}:unfiled`:A}:${En??``}`,r=(B?.length??0)>0,i=vt(e,H,V,P,I,L.join(`␟`),Yt,W&&G?G:``,n),a=r&&i===gr.current;gr.current=i;let o=vt(e,H,V,P,I,L.join(`␟`),Jt,W&&G?G:``,n),c=`${o}\0${k}`;if(t?.silent&&hr.current?.key===c){hr.current.refreshPending=!0;return}let l=++mr.current,u=t?.silent||r||k?void 0:gt.get(o);u&&(T(u.documents),O(u.totalCount),lr(sr),et(!1)),(t?.silent??(a||!!u))||et(!0);let d={key:c,refreshPending:!1};hr.current=d;try{let t;t=$t&&Qt?await ge(e,Qt.driver,Qt.address,{linked:!1,limit:I,offset:(P-1)*I}):W&&G&&A!==`workspace`?await oe(e,H,G,{limit:I,page:P,queries:L,allOf:Dn,anyOf:z,noneOf:Ht,filters:Kt,ids:B,sortBy:qt.sortBy||void 0,order:qt.order}):await pe(e,V,Dn,{limit:I,page:P,treeName:H,treeType:H===`directory`||H===`backends`?`directory`:`context`,queries:L,anyOf:z,noneOf:Ht,filters:Kt,ids:B,sortBy:qt.sortBy||void 0,order:qt.order,scope:A,debug:k&&L.length>0,debugLimit:200});let n=t.payload||[],i=t.totalCount||t.count||0;if(!r&&!d.refreshPending&>.set(o,{documents:n,totalCount:i}),l!==mr.current)return;let s=t.debug,c=s?.imageDistances??s?.distances??null;st(c?{query:L[L.length-1]??``,distances:c}:null),T(a?e=>e.length===n.length&&e.every((e,t)=>e.id===n[t].id)?e:n:n),O(i),lr(sr)}catch(e){if(l!==mr.current)return;let t=e instanceof Error?e.message:`Failed to fetch documents`;s({title:`Error`,description:t,variant:`destructive`}),T([]),O(0)}finally{hr.current===d&&(hr.current=null),l===mr.current&&et(!1),l===mr.current&&d.refreshPending&&$({silent:!0})}},[e,V,H,G,W,P,I,w?.status,L,Jt,A,$t,k,En]);(0,E.useEffect)(()=>{$()},[$]),(0,E.useEffect)(()=>{let t=t=>{let n=t.detail;!n||n.workspaceName!==e||(on({treeName:n.treeName||`context`,path:je(n.path||`/`)}),ln(`left`))};return window.addEventListener(`workspace:open-to-side`,t),()=>window.removeEventListener(`workspace:open-to-side`,t)},[e,H,V]),(0,E.useEffect)(()=>{let t=t=>{let n=t.detail;if(!(n?.workspaceName&&n.workspaceName!==e)&&(e&&bt(e,n),ot(at(n),{tree:H,kind:S(H),path:V,wholeWorkspace:A===`workspace`}))){if(e&&j(e,H,V),Qn.current){Yn();return}$({silent:!0})}};return window.addEventListener(`workspace:documents:refresh`,t),()=>window.removeEventListener(`workspace:documents:refresh`,t)},[$,e,V,H,A,Yn]);let _r=w?.name,vr=w?.id;(0,E.useEffect)(()=>{if(!e||!_r&&!vr)return;let t=[_r,vr].filter(Boolean).map(e=>`workspace:${e}`),n=()=>t.forEach(e=>m.emit(`subscribe`,{channel:e}));n();let r=m.on(`connect`,n),i=new Map,a=!1,o=()=>{te(e).then(e=>{a||(i=nt(e))}).catch(()=>{})};o();let s=null,c=0,l=!1,u=null,d=()=>{if(s=null,c=Date.now(),u){let{treeName:t,path:n}=u;u=null,window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,treeName:t,path:n}}))}if(l){if(l=!1,Qn.current){Yn();return}$({silent:!0})}},f=t=>n=>{(t.startsWith(`tree.created`)||t.startsWith(`tree.renamed`))&&o();let r=rt(t,n,i);yt(e,r);let a={tree:H,kind:S(H),path:V,wholeWorkspace:A===`workspace`},f=sn.current;f&&ot(r,{tree:f.treeName,kind:S(f.treeName),path:f.path})&&(u=f),ot(r,a,rr.current)&&(l=!0),!(!l&&!u)&&(s||=setTimeout(d,Math.max(200,c+1500-Date.now())))},p=[`document.inserted`,`document.inserted.batch`,`document.updated`,`document.removed`,`document.deleted`,`document.removed.batch`,`document.deleted.batch`,`document.linked`,`document.unlinked`,`document.linked.batch`,`document.unlinked.batch`,`tree.document.inserted`,`tree.document.inserted.batch`,`tree.document.removed`,`tree.document.removed.batch`,`tree.document.deleted`,`tree.document.deleted.batch`,`tree.layer.merged`,`tree.layer.subtracted`,`tree.created`,`tree.renamed`].map(e=>[e,f(e)]);return p.forEach(([e,t])=>m.on(e,t)),()=>{a=!0,s&&clearTimeout(s),r?.(),p.forEach(([e,t])=>m.off(e,t))}},[e,vr,_r,H,V,A,$,Yn]);let yr=`${V}\0${H}\0${G??``}\0${A}`,[br,xr]=(0,E.useState)(yr);br!==yr&&(xr(yr),F(1),It(null));let Sr=`${V}\0${H}\0${G??``}`,[Cr,wr]=(0,E.useState)(Sr);Cr!==Sr&&(wr(Sr),ut(`path`));let Tr=(e,t)=>{let n=e===`/`?`canvas`:e.split(`/`).pop()||`canvas`;Tt(n),St({parentPath:e,captureView:t})},Er=l.get(`createCanvas`)===`1`,[Dr,Or]=(0,E.useState)(!1);Dr!==Er&&(Or(Er),Er&&Tr(V,!1)),(0,E.useEffect)(()=>{if(!Er)return;let e=new URLSearchParams(n.search);e.delete(`createCanvas`);let t=e.toString();o(`${n.pathname}${t?`?${t}`:``}${n.hash}`,{replace:!0})},[Er,V]);let kr=(0,E.useCallback)(e=>{let t=new URLSearchParams(n.search);t.delete(`q`),t.delete(`search`);for(let n of e)t.append(`q`,n);let r=t.toString();o(`${n.pathname}${r?`?${r}`:``}${n.hash}`)},[n.pathname,n.search,n.hash,o]),Ar=JSON.stringify([l.has(`q`),...Ie]),[jr,Mr]=(0,E.useState)(Ar);jr!==Ar&&(Mr(Ar),Pt(Ie),F(1));let Nr=`${Ar}\0${Y??``}\0${An}\0${V}\0${Ft??``}`,[Pr,Fr]=(0,E.useState)(Nr);Pr!==Nr&&(Fr(Nr),l.has(`q`)||Ie.length>0||Y!==`canvas`||Ft===V||(Pt(An?[An]:[]),F(1)));let Ir=(0,E.useCallback)(e=>{let t=e.trim();t&&(It(null),Pt(e=>{if(e.includes(t))return e;let n=[...e,t];return kr(n),F(1),n}))},[kr,It,Pt,F]),Lr=(0,E.useCallback)(e=>{Pt(t=>{let n=e<0?[]:t.filter((t,n)=>n!==e);return n.length===0&&It(V),kr(n),F(1),n})},[kr,V,It,Pt,F]),Rr=L.join(` `).trim(),zr=!!R.activeContextType&&(R.isDirty||Rr!==(Y===`canvas`?An:R.savedSearchQuery||``));!e&&K!==null&&an(null),(0,E.useEffect)(()=>{let t=!1;if(!e)return;let n=0,r=!1,i=(i=!1)=>{let a=++n;i&&fe(e,H),ee(e,H).then(i=>{!t&&a===n&&(r=!0,_n.current=`${e}/${H}`,an(i))}).catch(()=>{!t&&a===n&&!r&&an(null)})};i(!1);let a=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||n?.treeName&&n.treeName!==H||i(!n?.cacheInvalidated)};window.addEventListener(`workspace:tree:refresh`,a);let o=C(e,vr);return()=>{t=!0,o(),window.removeEventListener(`workspace:tree:refresh`,a)}},[e,H,vr]),!(e&&Y===`canvas`&&!W)&&N!==null&&Mt(null),(0,E.useEffect)(()=>{let t=!1;if(!(!e||Y!==`canvas`||W))return ae(e,V,H).then(e=>{t||Mt(e)}).catch(()=>{t||Mt(null)}),()=>{t=!0}},[e,V,H,Y,W]);let Br=async()=>{if(w){ft(!0);try{let t=await ue(e||w.id);Je(t),s({title:`Success`,description:`Workspace started successfully`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){let t=e instanceof Error?e.message:`Failed to start workspace`;s({title:`Error`,description:t,variant:`destructive`})}finally{ft(!1)}}},Vr=async t=>{if(!w)return;let n=c({title:`Removing…`,description:`Document from "${V}"`});try{await re(e||w.id,[t],V,[],H,Yr,{trashIfOrphaned:!0}),j(e||w.id,H,V),T(e=>e.filter(e=>e.id!==t)),O(e=>Math.max(0,e-1)),n.done({title:`Success`,description:`Document removed from workspace path.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to remove document`,variant:`destructive`})}},Hr=async t=>{if(!w)return;let n=c({title:`Deleting…`,description:`Document from "${V}"`});try{await ie(e||w.id,[t],V,[],H,Yr),j(e||w.id,H,V),T(e=>e.filter(e=>e.id!==t)),O(e=>Math.max(0,e-1)),n.done({title:`Success`,description:`Document deleted.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to delete document`,variant:`destructive`})}},Ur=async t=>{if(!w)return;let n=c({title:`Removing…`,description:`${t.length} document(s) from "${V}"`});try{await re(e||w.id,t,V,[],H,Yr,{trashIfOrphaned:!0}),j(e||w.id,H,V),T(e=>e.filter(e=>!t.includes(e.id))),O(e=>Math.max(0,e-t.length)),n.done({title:`Success`,description:`${t.length} document(s) removed.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},Wr=async t=>{if(!w)return;let n=c({title:`Deleting…`,description:`${t.length} document(s)`});try{await ie(e||w.id,t,V,[],H,Yr),j(e||w.id,H,V),T(e=>e.filter(e=>!t.includes(e.id))),O(e=>Math.max(0,e-t.length)),n.done({title:`Success`,description:`${t.length} document(s) deleted.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},Gr=async t=>{if(!w)return;let n=c({title:`Destroying…`,description:`Document and its backend copies`});try{let r=await ne(e||w.id,[t]);if(r.failed?.length){n.fail({title:`Error`,description:r.failed[0].reason,variant:`destructive`});return}T(e=>e.filter(e=>e.id!==t)),O(e=>Math.max(0,e-1)),n.done({title:`Destroyed`,description:`Document removed from all backends.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy document`,variant:`destructive`})}},Kr=async t=>{if(!w)return;let n=c({title:`Destroying…`,description:`${t.length} document(s) and their backend copies`});try{let r=await ne(e||w.id,t),i=new Set(r.successful?.filter(e=>e.docDeleted).map(e=>e.id)??[]);T(e=>e.filter(e=>!i.has(e.id))),O(e=>Math.max(0,e-i.size));let a=[r.successful?.length?`${r.successful.length} destroyed`:null,r.failed?.length?`${r.failed.length} failed`:null].filter(Boolean).join(`, `);r.failed?.length?n.fail({title:`Destroy incomplete`,description:a,variant:`destructive`}):n.done({title:`Destroyed`,description:a||`No documents destroyed`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},qr=e=>{xt({documentIds:e,operation:`copy`,sourcePath:V,sourceTreeName:H}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}})),s({title:`Copied`,description:`${e.length} document(s) copied to clipboard`})},Jr=e=>{xt({documentIds:e,operation:`cut`,sourcePath:V,sourceTreeName:H}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}})),s({title:`Cut`,description:`${e.length} document(s) cut to clipboard`})},Yr=S(H),Xr=async(t,n,r={})=>{if(!e)return!1;let i=r.targetTreeName??H,a=r.targetTreeType??Yr,o=r.move??_t?.operation===`cut`,s=c({title:o?`Moving…`:`Pasting…`,description:`${n.length} document(s) → "${t}"`});try{let c=await b(e,t,n,i,a);if(c){j(e,i,t);let a=r.sourceTreeName||_t?.sourceTreeName,c=r.sourcePath||_t?.sourcePath;if((r.move??_t?.operation===`cut`)&&c&&a){let t=S(a);await re(e,n,c,[],a,t),j(e,a,c),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:c,treeName:a}}))}s.done({title:`Success`,description:`${n.length} document(s) ${o?`moved`:`pasted`} to "${t}"`}),xt(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}));let l=performance.now();await $(),console.info(`[paste] list refresh ${Math.round(performance.now()-l)} ms`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:i}}))}else s.done();return c}catch(e){return s.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},Zr=async(t,n)=>{if(!e)return!1;try{let r=(await de(e,n,t,H,Yr)).length>0;return r&&(xe(e,H,n),s({title:`Success`,description:`Imported ${t.length} document(s) to "${n}"`})),r}catch(e){return s({title:`Error`,description:e instanceof Error?e.message:`Failed to import documents`,variant:`destructive`}),!1}},Qr=async()=>{if(!w||nr===0||pr||fr.current||window.prompt(`Type PURGE to permanently delete all ${nr} matching documents across all pages.`)!==`PURGE`)return;fr.current=!0,dr(!0);let t=c({title:`Purging…`,description:`${nr} matching document(s)`});try{let n=await y(e||w.id,or,nr);n.deleted===n.requested?t.done({title:`Success`,description:`${n.deleted} document(s) purged.`}):t.fail({title:`Purge incomplete`,description:`${n.deleted} of ${n.requested} document(s) purged. Refresh and review the remaining results before retrying.`})}catch(e){t.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to purge documents`,variant:`destructive`})}finally{j(e||w.id,H,V),await $({silent:!0}),fr.current=!1,dr(!1)}},$r=()=>Tr(V,!0),ei=async()=>{if(!(!e||!M||!wt.trim())){Dt(!0);try{let t=wt.trim(),n=M.parentPath,r=n===`/`?`/${t}`:`${n}/${t}`,i={...R.filters,features:{...R.filters.features,allOf:Dn}};await se(e,r,H,M.captureView?{metadata:{toolbox:i},querySpec:{features:i.features,filters:[...De(R.filters.timeline),...Ee(R.filters.geo)],query:Rr||void 0,sort:R.filters.sort?.sortBy?R.filters.sort:null}}:{}),St(null),fe(e,H);try{let t=await ee(e,H,{force:!0});an(t)}catch{}window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e}})),o(Me(e,r,H))}catch(e){s({title:`Error`,description:e instanceof Error?e.message:`Failed to create canvas`,variant:`destructive`})}finally{Dt(!1)}}},ti=async()=>{if(!(!e||Y!==`canvas`)){kt(!0);try{let t=N||await he(e,V,H);Mt(t);let n=`${window.location.origin}${t.url}`;await navigator.clipboard?.writeText(n),s({title:`Public canvas link copied`,description:n})}catch(e){s({title:`Error`,description:e instanceof Error?e.message:`Failed to share canvas`,variant:`destructive`})}finally{kt(!1)}}},ni=async()=>{if(N){kt(!0);try{await v(N.code),Mt(null),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:H}})),s({title:`Canvas unshared`,description:`The public link no longer works.`})}catch(e){s({title:`Error`,description:e instanceof Error?e.message:`Failed to unshare canvas`,variant:`destructive`})}finally{kt(!1)}}},ri=async()=>{if(!e||Y!==`canvas`||V===`/`)return;let t=jn?.label||V.split(`/`).pop()||`canvas`,n=N?` Its public link will stop working.`:``;if(window.confirm(`Delete canvas "${t}"? This cannot be undone.${n}`)){jt(!0);try{if(N)await v(N.code),Mt(null);else if(J?.locked){s({title:`Canvas is locked`,description:`Unlock it before deleting.`,variant:`destructive`});return}await g(e,V,!1,H);let n=V.split(`/`).filter(Boolean);n.pop();let r=n.length?`/${n.join(`/`)}`:`/`;window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:H}})),o(Me(e,r,H)),s({title:`Canvas deleted`,description:`"${t}" was removed.`})}catch(e){s({title:`Error`,description:e instanceof Error?e.message:`Failed to delete canvas`,variant:`destructive`})}finally{jt(!1)}}},ii=(0,E.useCallback)(async t=>{if(!e||!q)return;let n={treeName:H,path:V},r=cn===`left`?n:q,i=cn===`left`?q:n,a=cn===`left`?un:hn;if(a.length===0){s({title:`Nothing selected`,description:`Tick documents in the focused pane first.`});return}let o=S(i.treeName),l=c({title:t?`Moving…`:`Copying…`,description:`${a.length} document(s) → "${i.path}"`});try{if(!await b(e,i.path,a,i.treeName,o)){l.done();return}if(j(e,i.treeName,i.path),t){let t=S(r.treeName);await re(e,a,r.path,[],r.treeName,t),j(e,r.treeName,r.path)}[r,i].forEach(t=>window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t.path,treeName:t.treeName}}))),l.done({title:t?`Moved`:`Copied`,description:`${a.length} document(s) → "${i.path}"`})}catch(e){l.fail({title:`Error`,description:e instanceof Error?e.message:`Transfer failed`,variant:`destructive`})}},[e,q,cn,H,V,un,hn,s,c]);if((0,E.useEffect)(()=>{if(!q)return;let e=e=>{if(e.key!==`F5`&&e.key!==`F6`)return;let t=e.target;t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`&&(e.preventDefault(),ii(e.key===`F6`))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[q,ii]),Ye)return(0,D.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,D.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,D.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,D.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading workspace...`})]})});if(!w)return(0,D.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:`Workspace not found.`});let ai=Y===`canvas`&&!W&&!!J,oi=!ai&&!U&&yn?(0,D.jsx)(He,{views:wn,activeId:Tn,onSelect:On,onSave:kn,accentColor:Ce(w.color),onOpenToSide:e=>{on({treeName:H,path:V,viewId:e}),ln(`right`)}}):void 0,si=Qt||w.status!==`active`?(0,D.jsxs)(D.Fragment,{children:[Qt&&(0,D.jsx)(`button`,{type:`button`,onClick:()=>{en(!$t),F(1)},"aria-pressed":$t,className:u(`min-h-10 rounded-md border px-2 text-xs`,$t&&`bg-warning/15 text-warning`),children:`Unfiled only`}),w.status!==`active`&&(0,D.jsx)(`button`,{type:`button`,onClick:Br,disabled:dt,className:`min-h-10 rounded-md border px-2 text-xs`,children:dt?`Starting…`:`Start`})]}):void 0,ci=Te(H,V)?V===`/Trash`?(0,D.jsx)(`div`,{className:`h-full overflow-auto p-4`,children:(0,D.jsx)(Ge,{workspaceName:e||w.id})}):(0,D.jsx)(Ke,{workspace:e||w.id,path:V,onNavigate:t=>o(Me(e,t,`backends`))},e):(0,D.jsx)(Ue,{navigationTabs:oi,navigationActions:si,onBack:mn,accentColor:Ce(w.color),urlType:W?S(H)===`directory`?`${H}-layer`:`context-layer`:Y===`canvas`?`canvas`:S(H)===`directory`?H:`context`,urlDisplay:Vn,contextPath:V,treeName:H,workspaceId:e||w.id,workspaceLabel:w.label||w.name,workspaceIcon:w.icon,documentSchema:En,documents:ar,isLoading:$e,totalCount:nr,currentPage:P,pageSize:I,onPageChange:F,onPageSizeChange:e=>{Nt(e),F(1)},onRemoveDocument:V===`/`?void 0:Vr,onDeleteDocument:Hr,onDestroyDocument:Gr,onRemoveDocuments:V===`/`?void 0:Ur,onDeleteDocuments:Wr,onDestroyDocuments:Kr,onCopyDocuments:qr,onCutDocuments:Jr,onPasteDocuments:U?void 0:Xr,onImportDocuments:U?void 0:Zr,onSelectionChange:dn,onBrowseTree:()=>pn(`workspaces`,`detail`,e??null),onBrowseWorkspaces:()=>fn(`workspaces`),onNavigatePath:t=>o(Me(e,t,H)),folders:vn,onOpenFolder:t=>o(Me(e,je(t),H)),scope:A,onScopeChange:ut,pastedDocumentIds:_t?.documentIds,linkTree:K,onPurgeDocuments:U?void 0:Qr,disablePurgeDocuments:pr,canvasInfo:jn??void 0,isCanvasPinned:Ln,onTogglePinCanvas:Q?Bn:void 0,onSaveAsCanvas:K&&Y!==`canvas`&&!W&&!U?$r:void 0,onShareCanvas:Y===`canvas`&&!W?ti:void 0,onUnshareCanvas:N?ni:void 0,onDeleteCanvas:Y===`canvas`&&!W?ri:void 0,isSharingCanvas:Ot,isDeletingCanvas:At,isCanvasShared:!!N,isCanvasLocked:!!J?.locked,backendSearchQueries:L,onBackendSearch:Ir,serverSort:R.filters.sort,onServerSortChange:Rt,onRemoveBackendQuery:Lr,canSaveChanges:zr,isSavingChanges:R.isSaving,onSaveChanges:Lt,contentBanner:k&&it?(0,D.jsx)(mt,{data:it,className:`mb-3`}):null,children:ai&&J?(0,D.jsx)(ve,{workspaceId:e||w.id,treeName:H,path:V,layerId:J.id,querySpec:J.querySpec,metadata:J.metadata,isLocked:!!J.locked,fetchDocuments:R.isDirty?Un:void 0}):!U&&Z.kind===`columns`?(0,D.jsx)(Be,{documents:ar,workspaceId:e||w.id,columns:Z.columns??[],onColumnsChange:e=>kn(wn.map(t=>t.id===Z.id?{...t,columns:e}:t))}):!U&&Z.kind===`app`&&Z.app&&Z.app!==`notes`?(0,D.jsx)(We,{app:Z.app,workspaceId:e||w.id,treeName:H,path:V}):null});return(0,D.jsxs)(Fe,{workspaceId:e||w.id,treeName:H,path:V,headerOnly:!0,className:`relative flex flex-col h-full min-h-0`,children:[(0,D.jsx)(Qe,{workspaceId:w.id,workspaceName:w.label||w.name},w.id),Te(H,V)&&(0,D.jsx)(ye,{workspace:w.label||w.name,workspaceIcon:w.icon,tree:H,path:V,onBack:mn,onBrowseTree:()=>pn(`workspaces`,`detail`,e||w.id),onBrowseWorkspaces:()=>fn(`workspaces`),onNavigatePath:t=>o(Me(e,t,H)),accentColor:Ce(w.color)}),M&&(0,D.jsx)(`div`,{className:`shrink-0 px-2 pt-2`,children:(0,D.jsx)(Le,{title:`New canvas`,onClose:()=>St(null),children:(0,D.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),ei()},className:`space-y-4`,children:[(0,D.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,D.jsxs)(`div`,{children:[(0,D.jsx)(`label`,{htmlFor:`canvas-name`,className:`mb-1 block text-sm font-medium`,children:`Name`}),(0,D.jsx)(`input`,{id:`canvas-name`,className:`w-full rounded-md border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary`,placeholder:`Canvas name…`,value:wt,onChange:e=>Tt(e.target.value),onKeyDown:e=>{e.key===`Escape`&&St(null)},autoFocus:!0})]}),(0,D.jsxs)(`div`,{children:[(0,D.jsx)(`span`,{className:`mb-1 block text-sm font-medium`,children:`Parent path`}),(0,D.jsx)(`div`,{className:`flex h-10 items-center rounded-md bg-muted px-3 font-mono text-sm text-muted-foreground`,children:M.parentPath===`/`?`/`:M.parentPath})]})]}),(0,D.jsxs)(`label`,{className:`flex items-start gap-2 text-sm`,children:[(0,D.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:M.captureView,onChange:e=>St({...M,captureView:e.target.checked})}),(0,D.jsxs)(`span`,{children:[`Capture the current view`,(0,D.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:`Freezes the active filters, search and sort into the canvas.`})]})]}),(0,D.jsxs)(`div`,{className:`flex gap-2`,children:[(0,D.jsx)(d,{type:`submit`,disabled:!wt.trim()||Et,children:Et?`Creating…`:`Create canvas`}),(0,D.jsx)(d,{type:`button`,variant:`outline`,onClick:()=>St(null),children:`Cancel`})]})]})})}),(0,D.jsxs)(`div`,{"data-canvas-panes":!0,className:`flex-1 min-h-0 flex gap-2`,children:[(0,D.jsx)(`div`,{"data-canvas-pane":!0,className:u(`flex-1 min-w-0 bg-background overflow-hidden`,q&&(cn===`left`?`ring-2 ring-primary`:`ring-1 ring-primary/20`)),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||ln(`left`)},children:ci}),q&&e&&(0,D.jsx)(Ct,{workspaceName:e,workspaceLabel:w.label||w.name,workspaceIcon:w.icon,pane:q,isFocused:cn===`right`,clipboard:_t,setClipboard:xt,onFocus:()=>ln(`right`),onSelectionChange:gn,onNavigate:e=>on(t=>t&&{...t,path:e,viewId:void 0}),onClose:()=>{on(null),ln(`left`),gn([])}})]})]})}function St(e,t){if(!e||t===`/`)return e;let n=e;for(let e of t.split(`/`).filter(Boolean))if(n=n?.children?.find(t=>t.name===e)??null,!n)return null;return n}function Ct({workspaceName:e,workspaceLabel:t,workspaceIcon:n,pane:r,isFocused:i=!1,clipboard:a,setClipboard:o,onFocus:s,onSelectionChange:c,onNavigate:l,onClose:d}){let{openM1Drawer:f,openM2Drawer:p}=Ne(),{showToast:m,showProgress:g}=h(),[_,te]=(0,E.useState)(null),[v,y]=(0,E.useState)([]),[ae,oe]=(0,E.useState)(!1),[se,ce]=(0,E.useState)(0),[le,ue]=(0,E.useState)(1),[de,me]=(0,E.useState)(50),x=S(r.treeName),he=St(_,r.path),ge=he?.type===`canvas`,_e=(0,E.useMemo)(()=>x===`directory`?ht(_,r.path):[],[_,r.path,x]),ve=r.viewId?Ve(he?.metadata).find(e=>e.id===r.viewId)??null:null,ye=`${e}://${r.path===`/`?``:r.path.replace(/^\//,``)}`,be=Re(ve),C=(0,E.useCallback)(async()=>{if(Te(r.treeName,r.path)){y([]),ce(0),oe(!1);return}let t=vt(e,r.treeName,r.path,le,de,``,be??``),n=gt.get(t);if(n){y(n.documents),ce(n.totalCount);return}oe(!0);try{let n=await pe(e,r.path,be?[be]:[],{limit:de,page:le,treeName:r.treeName,treeType:x}),i=n.payload||[],a=n.totalCount||n.count||0;y(i),ce(a),gt.set(t,{documents:i,totalCount:a})}catch(e){m({title:`Error`,description:e instanceof Error?e.message:`Failed to fetch side pane documents`,variant:`destructive`}),y([]),ce(0)}finally{oe(!1)}},[e,r.path,r.treeName,x,de,le,m,be]);(0,E.useEffect)(()=>{let t=!1,n=0,i=!1,a=(a=!1)=>{let o=++n;a&&fe(e,r.treeName),ee(e,r.treeName).then(e=>{!t&&o===n&&(i=!0,te(e))}).catch(()=>{!t&&o===n&&!i&&te(null)})};a(!1);let o=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||n?.treeName&&n.treeName!==r.treeName||a(!n?.cacheInvalidated)};return window.addEventListener(`workspace:tree:refresh`,o),()=>{t=!0,window.removeEventListener(`workspace:tree:refresh`,o)}},[e,r.treeName]),(0,E.useEffect)(()=>{C()},[C]),(0,E.useEffect)(()=>{let t=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||(bt(e,n),ot(at(n),{tree:r.treeName,kind:S(r.treeName),path:r.path})&&(j(e,r.treeName,r.path),C()))};return window.addEventListener(`workspace:documents:refresh`,t),()=>window.removeEventListener(`workspace:documents:refresh`,t)},[C,e,r.treeName,r.path]);let xe=(0,E.useCallback)(async(t,n,i={})=>{let s=i.targetTreeName??r.treeName,c=i.targetTreeType??x,l=i.move??a?.operation===`cut`,u=g({title:l?`Moving…`:`Pasting…`,description:`${n.length} document(s) → "${t}"`});try{let r=await b(e,t,n,s,c);if(r){j(e,s,t);let r=i.sourcePath||a?.sourcePath,c=i.sourceTreeName||a?.sourceTreeName;if((i.move??a?.operation===`cut`)&&r&&c){let t=S(c);await re(e,n,r,[],c,t),j(e,c,r),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:r,treeName:c}}))}u.done({title:`Success`,description:`${n.length} document(s) ${l?`moved`:`pasted`} to "${t}"`}),o(null),await C(),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:s}}))}else u.done();return r}catch(e){return u.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},[e,r.treeName,x,C,g,a,o]),Se=(0,E.useCallback)(()=>{j(e,r.treeName,r.path),C()},[e,r.treeName,r.path,C]),Ce=(0,E.useCallback)(async t=>{let n=g({title:`Removing…`,description:`${t.length} document(s) from "${r.path}"`});try{await re(e,t,r.path,[],r.treeName,x),Se(),n.done({title:`Removed`,description:`${t.length} document(s) removed from "${r.path}"`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},[e,r.path,r.treeName,x,Se,g]),we=(0,E.useCallback)(async t=>{let n=g({title:`Deleting…`,description:`${t.length} document(s)`});try{await ie(e,t,r.path,[],r.treeName,x),Se(),n.done({title:`Deleted`,description:`${t.length} document(s) deleted.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},[e,r.path,r.treeName,x,Se,g]),Ee=(0,E.useCallback)(async t=>{let n=g({title:`Destroying…`,description:`${t.length} document(s) and their backend copies`});try{let r=await ne(e,t);if(r.failed?.length&&!r.successful?.length){n.fail({title:`Error`,description:r.failed[0].reason,variant:`destructive`});return}Se();let i=`${r.successful?.length??0} document(s) destroyed${r.failed?.length?` · ${r.failed.length} failed`:``}.`;r.failed?.length?n.fail({title:`Destroy incomplete`,description:i,variant:`destructive`}):n.done({title:`Destroyed`,description:i})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},[e,Se,g]);return(0,D.jsxs)(`div`,{className:u(`relative flex-1 min-w-0 rounded-(--sheet-radius) border bg-background overflow-hidden`,i?`ring-2 ring-primary`:`ring-1 ring-primary/20`),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||s()},children:[d&&(0,D.jsx)(`button`,{type:`button`,onClick:d,className:`absolute right-2 top-2 z-10 px-2 py-1 text-xs rounded-md border bg-background/90 hover:bg-accent`,children:`Close`}),Te(r.treeName,r.path)?r.path===`/Trash`?(0,D.jsx)(`div`,{className:`h-full overflow-auto p-4`,children:(0,D.jsx)(Ge,{workspaceName:e})}):(0,D.jsx)(Ke,{workspace:e,path:r.path,onNavigate:l||(()=>{})}):(0,D.jsx)(Ue,{frameContent:!1,onBrowseWorkspaces:()=>f(`workspaces`),onBrowseTree:()=>p(`workspaces`,`detail`,e),urlType:ge?`canvas`:x===`directory`?r.treeName:`context`,urlDisplay:ye,contextPath:r.path,treeName:r.treeName,workspaceId:e,workspaceLabel:t,workspaceIcon:n,documentSchema:be,documents:v,isLoading:ae,totalCount:se,currentPage:le,pageSize:de,onPageChange:ue,onPageSizeChange:e=>{me(e),ue(1)},onRemoveDocument:r.path===`/`?void 0:e=>Ce([e]),onRemoveDocuments:r.path===`/`?void 0:Ce,onDeleteDocument:e=>we([e]),onDeleteDocuments:we,onDestroyDocument:e=>Ee([e]),onDestroyDocuments:Ee,onCopyDocuments:e=>{o({documentIds:e,operation:`copy`,sourcePath:r.path,sourceTreeName:r.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}}))},onCutDocuments:e=>{o({documentIds:e,operation:`cut`,sourcePath:r.path,sourceTreeName:r.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}}))},onPasteDocuments:r.treeName===`backends`?void 0:xe,onSelectionChange:c,pastedDocumentIds:a?.documentIds,linkTree:_,folders:_e,onOpenFolder:l,onNavigatePath:l,canvasInfo:ge?{label:he?.label,description:he?.description,color:he?.color}:void 0,children:ve?.kind===`columns`?(0,D.jsx)(Be,{documents:v,workspaceId:e,columns:ve.columns??[],onColumnsChange:()=>{},readOnly:!0}):ve?.kind===`app`&&ve.app&&ve.app!==`notes`?(0,D.jsx)(We,{app:ve.app,workspaceId:e,treeName:r.treeName,path:r.path}):null})]})}export{xt as default};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{$r as r,Ct as i,Hr as a,Jn as o,Kn as s,L as c,Nr as l,Nt as u,Q as d,X as f,Y as p,Z as m,Zr as h,_r as g,fn as ee,jn as _,li as v,ri as y,sn as b,st as x,zn as S,zt as te}from"./ui-Byg1cZDr.js";import{t as C}from"./utils-2pl1SbIp.js";import{t as w}from"./button-SgR3GVvV.js";import{t as T}from"./input-BOtCd4HP.js";import{c as ne,t as E}from"./api-CA6WiiYM.js";import{t as D}from"./socket-CtH3EU9m.js";import{n as re}from"./use-toast-BlLDqSUO.js";import{t as ie}from"./LinkToCard-nR7Lal_o.js";import{W as ae,bt as oe,gn as se,gt as ce,hn as O}from"./workspace-DvxC7pw1.js";import{i as le}from"./MessageComposerDialog-gbD0Gu_b.js";import{n as ue}from"./LinkToSidePanel-eCy3nW4R.js";import{t as de}from"./PathPickerField-DBe7jykL.js";var k=e(n(),1);function A(e){return`/workspaces/${e}/hooks`}async function fe(e){return await E.get(A(e))||[]}async function j(e,t){return(await E.get(`${A(e)}/${t}`))?.content??``}async function M(e,t,n){await E.put(`${A(e)}/${t}`,{content:n})}async function N(e,t){await E.delete(`${A(e)}/${t}`)}var pe=[`example-`,`disabled-`,`_`];function P(e){let t=e.lastIndexOf(`/`);return{dir:t===-1?``:e.slice(0,t+1),base:t===-1?e:e.slice(t+1)}}function F(e){return pe.find(t=>e.startsWith(t))??null}function me(e){return F(P(e).base)===null}function he(e){return P(e).base.startsWith(`example-`)}function ge(e){let{dir:t,base:n}=P(e),r=F(n);return t+(r?n.slice(r.length):`disabled-${n}`)}async function _e(e,t,n){if(me(t)===n)return t;let r=ge(t);return await M(e,r,await j(e,t)),await N(e,t),r}function ve(e){let t={};for(let n of e){let e;e=n.path.includes(`/`)?n.path.split(`/`)[0]:/^(?:example-|disabled-|_)?rules\.json$/.test(n.path)?`rules`:n.path.replace(/\.js$/,``),(t[e]||=[]).push(n)}return t}function ye(e){let t=e.when?.event;return Array.isArray(t)?t.map(String):t?[String(t)]:[]}function be(e){let t=e.when?.eventPathExact??e.when?.pathExact??e.when?.path;return Array.isArray(t)?t.map(String):typeof t==`string`?[t]:[]}function xe(e){let t=String(e||``).split(`/`).filter(Boolean);return t[0]===`workspace`&&t.length>=2?{backend:`workspace:${t[1]}`,rel:t.slice(2).join(`/`)}:t[0]===`device`?t.length>=3?{backend:t[2],rel:t.slice(3).join(`/`)}:null:t.length>=2?{backend:t[1],rel:t.slice(2).join(`/`)}:null}function Se(e){let t=new URLSearchParams;return e.kind&&e.kind!==`mirror`&&t.set(`addRuleKind`,e.kind),e.path&&t.set(`addRulePath`,e.path),e.target&&t.set(`addRuleTarget`,e.target),e.storeTo&&t.set(`addRuleStoreTo`,e.storeTo),e.storeFolder&&t.set(`addRuleStoreFolder`,e.storeFolder),t}function Ce(e){return String(e||``).replace(/^[a-z]+:/i,``).split(`/`).filter(Boolean).join(`/`)}var we=`rules.json`;async function Te(e){try{let t=await j(e,we),n=JSON.parse(t||`{}`);return Array.isArray(n.rules)?n.rules:[]}catch{return[]}}async function Ee(e,t){await M(e,we,JSON.stringify({$schema:`canvas.hook-rules/v1`,rules:t},null,2)+`
|
|
2
|
-
`)}async function De(e,t={}){let n=new URLSearchParams;t.status&&n.set(`status`,t.status),t.handler&&n.set(`handler`,t.handler),t.limit&&n.set(`limit`,String(t.limit));let r=n.toString();return await E.get(`${A(e)}/pending${r?`?${r}`:``}`)||[]}async function Oe(e,t){return await E.post(`${A(e)}/pending/decisions`,t)}async function ke(e,t){return await E.get(`${A(e)}/runs/${encodeURIComponent(t)}`)}async function Ae(e,t={}){let n=new URLSearchParams;t.limit&&n.set(`limit`,String(t.limit)),t.handler&&n.set(`handler`,t.handler),t.event&&n.set(`event`,t.event),t.failed&&n.set(`failed`,`true`);let r=n.toString();return await E.get(`${A(e)}/runs${r?`?${r}`:``}`)||[]}var I=1e4,je=`canvas.hooks.backfillLimit`;function Me(e){let t=Math.floor(Number(e));return!Number.isFinite(t)||t<1?500:Math.min(t,I)}function Ne(){try{let e=localStorage.getItem(je);return e?Me(e):500}catch{return 500}}function Pe(e){let t=Me(e);try{localStorage.setItem(je,String(t))}catch{}return t}function Fe(e){if(e.includes(`/`)){let t=e.split(`/`)[0];return t===`lib`||t===`rules`?null:t}return e.endsWith(`.js`)?e.replace(/\.js$/,``).replace(/^(?:example-|disabled-|_)/,``):null}async function Ie(e,t){return await E.post(`${A(e)}/backfill`,t)}function Le(e,t){return E.post(`${A(e)}/backfill/jobs`,t)}function L(e,t){return E.get(`${A(e)}/backfill/jobs/${t}`)}function Re(e,t){return E.delete(`${A(e)}/backfill/jobs/${t}`)}function ze(e){return E.get(`${A(e)}/backfill/jobs`)}async function R(e,t){return await E.post(`${A(e)}/run`,t)}async function z(e,t){return await E.post(`${A(e)}/runs/${t}/replay`,{})}async function Be(e){return await E.get(`${A(e)}/meta`)}async function Ve(e,t){return await E.post(`${A(e)}/generate`,t)}async function He(e,t){let n=await j(e,we),r=JSON.parse(n),i=Array.isArray(r)?r:r?.rules;if(!Array.isArray(i))throw Error(`The workspace rules file is invalid. Fix it in Rules before adding a rule.`);let a=(Array.isArray(t)?t:[t]).filter(e=>!i.some(t=>t.id===e.id));if(!a.length)return;let o=Array.isArray(r)?[...i,...a]:{...r,rules:[...i,...a]};await M(e,we,JSON.stringify(o,null,2)+`
|
|
3
|
-
`)}var Ue=He;function We(e,t,n,r=new Date){let i=e=>String(e).padStart(2,`0`),a={YYYY:String(r.getFullYear()),YY:i(r.getFullYear()%100),MM:i(r.getMonth()+1),DD:i(r.getDate()),HH:i(r.getHours()),mm:i(r.getMinutes()),ss:i(r.getSeconds())},o=e=>e.replace(/\{\{\s*([A-Za-z]+)\s*\}\}/g,(e,t)=>a[t]??e),s=e=>e.split(/[\\/]+/).filter(e=>e&&e!==`.`&&e!==`..`).join(`/`),c=[e,s(o(t.trim()))].filter(Boolean).join(`/`),l=s(o(n.trim()));return{root:c,added:l,result:[c,l,`<attachment filename>`].filter(Boolean).join(`/`),date:`${a.YYYY}-${a.MM}-${a.DD}`}}var B=`Applying rules to existing documents…`,Ge=new Map;function V(e){return`${e.ruleIds.length>1?`Rule ${e.ruleIndex+1}/${e.ruleIds.length}: `:``}${e.processed}${e.total===null?``:` / ${e.total}`} documents · ${e.applied} applied`}function Ke(e,t){let n=`${t.checked} checked, ${t.applied} applied${t.skipped?`, ${t.skipped} already there`:``}`;t.status===`cancelled`?e.done({title:`Cancelled`,description:n}):t.status===`failed`?e.fail({title:`Stopped before finishing`,description:`${n}: ${t.error}. The rule stays enabled; rerun it from Rules to finish.`,variant:`destructive`}):t.failed?e.done({title:`Finished with errors`,description:`${n}, ${t.failed} failed. Details in the rule’s run log.`,variant:`destructive`}):e.done({title:`Rule applied`,description:n})}function H(e,t,n){let r=Ge.get(n.id);if(r)return r;let i=new Promise(r=>{let i={channel:`workspace:${t}`},a=e({title:B,description:V(n),action:{label:`Cancel`,onClick:()=>{a.update({title:`Cancelling…`,description:V(n)}),Re(t,n.id).catch(()=>a.update({title:B,description:`Could not cancel. Try again.`}))}}}),o=()=>{u?.(),D.off(`job.progress`,c),D.off(`job.finished`,c),r()},s=e=>{if(e.status===`running`)return a.update({title:B,description:V(e)});Ke(a,e),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`)),o()},c=e=>{let t=e?.job;t?.id===n.id&&s(t)},l=()=>{D.emit(`subscribe`,i),L(t,n.id).then(s,()=>{})},u=D.on(`connect`,l);D.on(`job.progress`,c),D.on(`job.finished`,c),l()});return Ge.set(n.id,i),i.finally(()=>Ge.delete(n.id)),i}async function qe(e,t,n){let r;try{r=await Le(t,{ruleIds:n,limit:Ne()})}catch(t){e({title:B}).fail({title:`Could not start`,description:`${t instanceof Error?t.message:String(t)}. The rule stays enabled; rerun it from Rules.`,variant:`destructive`});return}return H(e,t,r)}async function Je(e,t){let n=await ze(t).catch(()=>[]);for(let r of n)r.status===`running`&&H(e,t,r)}function U(e){return`/workspaces/${e}/scripts`}async function Ye(e){return await E.get(U(e))||[]}async function Xe(e,t){return(await E.get(`${U(e)}/${t}`))?.content??``}async function Ze(e,t,n){await E.put(`${U(e)}/${t}`,{content:n})}async function Qe(e,t){await E.delete(`${U(e)}/${t}`)}var W=t(),$e=[{value:``,label:`any item`},{value:`email`,label:`an email`},{value:`message`,label:`a message`},{value:`tab`,label:`a browser tab / link`},{value:`note`,label:`a note`},{value:`file`,label:`a file`},{value:`todo`,label:`a todo / task`}],et=[{value:`document.inserted`,label:`is added`,hint:`Fires when the item is created or uploaded.`},{value:`document.updated`,label:`is updated`,hint:`Fires on every edit of the item.`},{value:`document.linked`,label:`is filed into a folder`,hint:`Fires when the item is (re)filed into a tree path — the usual pair with "is added" for folder rules.`},{value:`document.unlinked`,label:`is removed from a folder`,hint:`Fires when the item leaves a tree path.`}],tt=[{key:`toExact`,label:`recipient (To/Cc) is`,hint:`accounting@example.com`},{key:`fromExact`,label:`email sender is`,hint:`person@example.com`},{key:`senderExact`,label:`message sender is`,hint:`Sender ID`},{key:`sender`,label:`message sender contains`,hint:`Sender ID or name`},{key:`senderRegex`,label:`message sender matches regex`,hint:`Sender ID or name pattern`},{key:`body`,label:`body / text contains`,hint:`Words in the email preview or message text`},{key:`bodyRegex`,label:`body / text matches regex`,hint:`invoice\\s+\\d+`},{key:`threadExact`,label:`thread is`,hint:`Thread ID`},{key:`channelExact`,label:`channel / conversation is`,hint:`Channel or conversation ID`},{key:`platformExact`,label:`platform is`,hint:`slack, whatsapp, teams`},{key:`pathExact`,label:`is directly in the folder`,hint:`Current folder membership`},{key:`eventPathExact`,label:`is inserted / linked directly into`,hint:`Exact event destination, e.g. ctx:/foo/bar/baz. Descendant inserts do not match.`},{key:`path`,label:`is under the folder`,hint:`/projects/canvas/UI or backends:/workspace/home/foo`},{key:`mime`,label:`file type is`,hint:`image/*, application/pdf`},{key:`from`,label:`sender contains`,hint:`boss@company.tld`},{key:`to`,label:`recipient (To/Cc) contains`,hint:`invoice@my-company.tld`},{key:`subject`,label:`subject contains`,hint:`invoice`},{key:`fromRegex`,label:`sender matches regex`,hint:`@(acme|example)\\.com$`},{key:`toRegex`,label:`recipient (To/Cc) matches regex`,hint:`^(billing|accounts)@`},{key:`subjectRegex`,label:`subject matches regex`,hint:`^invoice\\s+\\d+`},{key:`urlRegex`,label:`URL matches regex`,hint:`/(invoice|receipt)/`},{key:`urlHost`,label:`website is`,hint:`youtube.com`},{key:`urlContains`,label:`URL contains`,hint:`/watch?v=`},{key:`attachment`,label:`has an attachment of type`,hint:`application/pdf, or * for any`}],nt=new Set([`toExact`,`fromExact`,`senderExact`,`threadExact`,`channelExact`,`platformExact`]),rt=e=>nt.has(e)?e.replace(/Exact$/,``):e.replace(/Regex$/,``),it=[{key:`sendFile`,label:`Send file(s) via a channel`,icon:b,tone:`text-blue-600 dark:text-blue-400 bg-blue-500/10`},{key:`extractAttachments`,label:`Extract email attachments to a folder`,icon:b,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`moveMessage`,label:`Move the email to a mail folder`,icon:b,tone:`text-teal-600 dark:text-teal-400 bg-teal-500/10`},{key:`store`,label:`Copy/Move file(s) to a storage backend`,icon:S,tone:`text-sky-600 dark:text-sky-400 bg-sky-500/10`},{key:`download`,label:`download what the link points at`,icon:g,tone:`text-rose-600 dark:text-rose-400 bg-rose-500/10`},{key:`link`,label:`file it into a folder`,icon:o,tone:`text-emerald-600 dark:text-emerald-400 bg-emerald-500/10`},{key:`unlink`,label:`remove it from a folder`,icon:o,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`tag`,label:`add tags`,icon:d,tone:`text-violet-600 dark:text-violet-400 bg-violet-500/10`},{key:`unstore`,label:`delete the file from a storage backend`,icon:p,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`notify`,label:`Send me a notification`,icon:y,tone:`text-pink-600 dark:text-pink-400 bg-pink-500/10`},{key:`agent`,label:`ask an agent`,icon:r,tone:`text-indigo-600 dark:text-indigo-400 bg-indigo-500/10`},{key:`script`,label:`run a script`,icon:m,tone:`text-slate-600 dark:text-slate-300 bg-slate-500/10`},{key:`delete`,label:`delete it from Canvas`,icon:f,tone:`text-destructive bg-destructive/10`},{key:`destroy`,label:`delete it everywhere`,icon:f,tone:`text-destructive bg-destructive/10`}],at=e=>it.find(t=>t.key===e)||it[1],ot=`{{title}}{{ext}}`,G=`{{YYYY}}/{{MM}}/{{YYYY}}{{MM}}{{DD}}_{{HH}}{{mm}}{{ss}}{{ext}}`,st=[{value:`auto`,label:`whatever it is (auto)`,hint:`arXiv → the PDF · YouTube, Vimeo, TikTok… → the video · image / video / PDF links → the file · anything else → the page.`},{value:`image`,label:`the file itself (image, PDF, …)`,hint:`Fetches the bytes the URL serves.`},{value:`video`,label:`the video (yt-dlp)`,hint:`Best video + audio, merged. Needs yt-dlp on the server.`},{value:`arxiv`,label:`the arXiv paper (PDF)`,hint:`Works for abs/ and pdf/ links.`},{value:`page`,label:`the page with its images & styles`,hint:`One page, offline-readable (wget --page-requisites).`},{value:`website`,label:`the whole website (mirror)`,hint:`Follows links on the same site up to the chosen depth.`}],ct=[{value:`keep`,label:`keep the original file name`},{value:`title`,label:`use the item title as file name`},{value:`dated`,label:`photo style: 2024/07/20240714_183012.jpg`},{value:`custom`,label:`custom template…`}],K=e=>({sendDriver:`imap`,sendSource:`document`,sendSubject:`{{file.name}}`,sendMessage:``,kind:e,a:``,b:``,recursive:!1,storeFrom:``,storeFolder:``,storeName:`keep`,storeMode:`copy`,storeConflict:`rename`,attachmentMime:`application/pdf`,attachmentName:``,attachmentPath:`{{YYYY}}/{{MM}}`,includeInline:!1,dlKind:`auto`,dlDepth:`2`,dlTags:``,keepLast:!0,notePath:``,noteTitle:``,filePath:``,fileBackend:`home`,fileInsert:``,notifyReply:!1}),q={id:null,description:``,events:[`document.inserted`],schema:``,cascade:!1,approval:!1,conditions:[],actions:[K(`link`)]},lt=e=>e.split(`|`).map(e=>e.trim()).filter(Boolean);function ut(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`rule-${Math.random().toString(36).slice(2,7)}`}var J=e=>e.split(`,`).map(e=>e.trim()).filter(Boolean),dt=[{id:`send-invoices`,title:`Send invoice PDFs to accounting`,icon:b,tone:`text-blue-600 dark:text-blue-400 bg-blue-500/10`,blurb:`Send matching PDF attachments to your accounting firm’s ingestion email, or to a Slack / WhatsApp conversation. Keep the original email and files.`,build:()=>({...q,description:`Send invoice PDFs to accounting`,schema:`email`,conditions:[{field:`toExact`,value:``}],actions:[{...K(`sendFile`),sendSource:`attachments`,sendSubject:`Invoice: {{file.name}}`}]})},{id:`attachments`,title:`File PDF email attachments by month`,icon:b,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`,blurb:`Choose a recipient and extract PDF attachments into Accounting / year / month, using the email date. Add a subject or filename filter to narrow it to invoices.`,build:()=>({...q,description:`File accounting PDF attachments by month`,schema:`email`,conditions:[{field:`toExact`,value:``}],actions:[{...K(`extractAttachments`),a:`workspace:home`,storeFolder:`Accounting`}]})},{id:`store`,title:`Copy/Move file(s) to a storage backend`,icon:S,tone:`text-sky-600 dark:text-sky-400 bg-sky-500/10`,blurb:`Uploads land in the managed blob store. Pick a folder in Canvas and a folder on a storage backend — copy or move matching files and optionally recreate their sub-folder paths.`,build:({backend:e})=>({...q,description:`Copy/Move file(s) to a storage backend`,schema:`file`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:``}],actions:[{...K(`store`),a:e,recursive:!0}]})},{id:`photos`,title:`Sort photos by date`,icon:_,tone:`text-emerald-600 dark:text-emerald-400 bg-emerald-500/10`,blurb:`Images filed into a folder are stored as Photos / 2024 / 07 / 20240714_183012.jpg — by the time the photo was taken (EXIF), not uploaded.`,build:({backend:e})=>({...q,description:`Sort photos by date`,schema:`file`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:``},{field:`mime`,value:`image/*`}],actions:[{...K(`store`),a:e,storeFolder:`Photos`,storeName:`dated`}]})},{id:`mirror`,title:`Mirror a storage folder`,icon:o,tone:`text-violet-600 dark:text-violet-400 bg-violet-500/10`,blurb:`Everything that appears under a folder of a storage backend shows up 1:1 in the Directory tree.`,build:()=>({...q,description:`Mirror a storage folder`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:`backends:/workspace/home/`}],actions:[{...K(`link`),a:`dir:/`,recursive:!0}]})},{id:`mail`,title:`File mail from a sender`,icon:b,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`,blurb:`Emails from a person or domain are filed into a folder and you get a notification.`,build:()=>({...q,description:`Mail from …`,schema:`email`,conditions:[{field:`from`,value:``}],actions:[{...K(`link`),a:`/work/urgent`},{...K(`notify`),a:`New mail from {{doc.data.from}}: {{doc.data.subject}}`}]})},{id:`download`,title:`Download what links point at`,icon:g,tone:`text-rose-600 dark:text-rose-400 bg-rose-500/10`,blurb:`Bookmarks filed into a folder are fetched for real — images, videos (yt-dlp), arXiv papers, a page or a whole website — saved to a folder and filed next to the link.`,build:({backend:e})=>({...q,description:`Download what links point at`,schema:`tab`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:``}],actions:[{...K(`download`),a:e,storeFolder:`Downloads`,recursive:!0}]})},{id:`agent`,title:`Ask an agent`,icon:r,tone:`text-indigo-600 dark:text-indigo-400 bg-indigo-500/10`,blurb:`Hand new items to an agent with a prompt; save its reply as a note or get it as a notification.`,build:()=>({...q,description:`Summarize new items`,actions:[{...K(`agent`),b:`Read document #{{doc.id}} in full with canvas_get, then summarize it in three bullet points.`,notifyReply:!0}]})},{id:`blank`,title:`Start from scratch`,icon:x,tone:`text-muted-foreground bg-muted`,blurb:`An empty rule: choose what it reacts to, add conditions and actions.`,build:()=>({...q})}];function Y(e){let t=e.filter(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field));if(t.length!==1||t[0].field!==`eventPathExact`)return null;let n=lt(t[0].value);return n.length===1&&/^(ctx|context):\//.test(n[0])?n[0].replace(/^(ctx|context):/,``).replace(/\/+$/,``)||`/`:null}function ft(e){if(Y(e)!==null)return!0;let t=e.filter(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field)).flatMap(e=>lt(e.value));return t.length>0&&t.every(e=>/^(dir|directory|backends):\//.test(e))}function pt(e,t,n){let r=e=>e.replace(/\\/g,`/`).split(`/`).filter(e=>e&&e!==`.`&&e!==`..`).join(`/`),i=`${n?.treePath?`backends:${n.treePath}`:e.a}/${r(e.storeFolder.trim())}`.replace(/\/+$/,``),a=Y(t),o=e.recursive?a===null?`<sub-folders>`:r(a):``;return{root:i,recreated:o,result:[i,o,e.storeName===`keep`?`<original filename>`:e.storeName===`title`?`<title>.<ext>`:e.storeName===`dated`?G:e.b||`<filename>`].filter(Boolean).join(`/`)}}function mt(e,t=[]){let n={event:e.events.length===1?e.events[0]:e.events};e.schema&&(n.schema=e.schema);let r={},i={};for(let t of e.conditions){let e=t.field.endsWith(`Regex`),n=nt.has(t.field),a=e||n?t.value.trim()?[t.value]:[]:lt(t.value);if(e&&a.length)try{new RegExp(t.value,`i`)}catch{throw Error(`Invalid regular expression for ${tt.find(e=>e.key===t.field)?.label}: ${t.value}`)}if(!a.length)throw Error(`Enter a value for ${tt.find(e=>e.key===t.field)?.label||t.field}, or remove that condition.`);if(t.field===`urlHost`||t.field===`urlContains`||t.field===`urlRegex`){let e=t.field===`urlHost`?`host`:t.field===`urlRegex`?`regex`:`contains`,n=i[e],r=[...Array.isArray(n)?n:n==null?[]:[n],...a];i[e]=r.length===1?r[0]:r}else(r[rt(t.field)]||=[]).push(...e?a.map(e=>({regex:e})):n?a.map(e=>({equals:e})):a)}for(let[e,t]of Object.entries(r))t?.length&&(n[e]=t.length===1?t[0]:t);Object.keys(i).length&&(n.url=i);let a=e=>{let t={};return e.notePath.trim()&&(t.note={path:e.notePath.trim(),...e.noteTitle.trim()?{title:e.noteTitle.trim()}:{}}),e.filePath.trim()&&(t.file={path:e.filePath.trim(),...e.fileBackend===`data`?{backend:`data`}:{},...e.fileInsert.trim()?{insert:e.fileInsert.trim()}:{}}),e.notifyReply&&(t.notify=!0),Object.keys(t).length?t:null},o=[];for(let n of e.actions){let r=n.a.trim(),i=n.b.trim(),s=n.recursive?{recursive:!0}:{};if(n.kind===`sendFile`){if(!r)throw Error(`Choose a sending account for the file.`);if(!i)throw Error(n.sendDriver===`imap`?`Enter the destination email address.`:`Enter a configured destination conversation.`);if(![`imap`,`slack`,`whatsapp`].includes(n.sendDriver))throw Error(`Choose email, Slack or WhatsApp.`);if(![`document`,`attachments`,`download`].includes(n.sendSource))throw Error(`Choose which files to send.`);if(n.sendSource===`download`&&!o.some(e=>e.action===`download`))throw Error(`Add a Download action before sending its files.`);let e=J(n.attachmentMime);if(n.sendSource===`attachments`&&(!e.length||e.some(e=>!/^(\*|[a-z0-9!#$&^_.+-]+\/(\*|[a-z0-9!#$&^_.+-]+)|\*\/\*)$/i.test(e))))throw Error(`Enter attachment MIME types, such as application/pdf.`);if(n.sendDriver===`whatsapp`&&n.sendMessage.length>1024)throw Error(`WhatsApp file captions must be at most 1,024 characters.`);o.push({action:`sendFile`,source:n.sendSource,driver:n.sendDriver,address:r,...n.sendDriver===`imap`?{to:J(i),subject:n.sendSubject}:{target:i},...n.sendMessage?{message:n.sendMessage}:{},...n.sendSource===`attachments`?{mime:e.length===1?e[0]:e,...n.attachmentName.trim()?{filename:n.attachmentName.trim()}:{},...n.includeInline?{includeInline:!0}:{}}:{}})}if(n.kind===`link`&&r&&o.push({action:`link`,paths:J(r),...s,...i?{tags:J(i)}:{}}),n.kind===`unlink`&&r&&o.push({action:`unlink`,paths:J(r),...s}),n.kind===`tag`&&r&&o.push({action:`tag`,tags:J(r)}),n.kind===`moveMessage`){if(!r)throw Error(`Enter the mail folder to move the email to, such as INBOX/Accounting/{{YYYY}}/Expenses.`);o.push({action:`moveMessage`,folder:r})}if(n.kind===`store`&&r){if(n.storeMode===`move`&&!n.storeFrom.trim())throw Error(`Choose the source backend whose copy should be moved.`);if(n.recursive&&!ft(e.conditions))throw Error(`Choose a Directory/Backends source path, or one exact Context insertion path, to recreate the path.`);if(n.recursive&&t.find(e=>e.address===r)?.capabilities?.paths!==!0)throw Error(`This destination has not reported support for folder paths. Choose a supported backend or turn off path recreation.`);let a=n.storeFolder.trim().replace(/^\/+|\/+$/g,``),c=n.storeName===`title`?ot:n.storeName===`dated`?G:n.storeName===`custom`?i:``;o.push({action:`store`,to:r,...n.storeFrom.trim()?{from:n.storeFrom.trim()}:{},mode:n.storeMode,...a?{folder:a}:{},...s,...n.recursive&&Y(e.conditions)!==null?{pathMode:`full`}:{},...c?{key:c}:{},onConflict:n.storeConflict})}if(n.kind===`extractAttachments`){if(!r)throw Error(`Choose a destination backend for the attachments.`);if(t.find(e=>e.address===r)?.capabilities?.paths!==!0)throw Error(`Choose an attachment destination with support for folder paths.`);let e=J(n.attachmentMime);if(!e.length||e.some(e=>!/^(\*|[a-z0-9!#$&^_.+-]+\/(\*|[a-z0-9!#$&^_.+-]+)|\*\/\*)$/i.test(e)))throw Error(`Enter attachment MIME types, such as application/pdf or image/*. Use * for all attachments.`);if(![`rename`,`error`].includes(n.storeConflict))throw Error(`Choose rename or skip for attachment filename conflicts.`);o.push({action:`extractAttachments`,to:r,mime:e.length===1?e[0]:e,...n.storeFolder.trim()?{folder:n.storeFolder.trim()}:{},...n.attachmentPath.trim()?{subfolder:n.attachmentPath.trim()}:{},...n.attachmentName.trim()?{filename:n.attachmentName.trim()}:{},...n.includeInline?{includeInline:!0}:{},onConflict:n.storeConflict})}if(n.kind===`download`){let e=n.storeFolder.trim().replace(/^\/+|\/+$/g,``),t=Number(n.dlDepth);o.push({action:`download`,to:r||`workspace:home`,...e?{folder:e}:{},...s,...n.dlKind===`auto`?{}:{kind:n.dlKind},...i?{insert:J(i)}:{},...n.dlTags.trim()?{tags:J(n.dlTags)}:{},...n.dlKind===`website`&&Number.isFinite(t)&&t>0&&t!==2?{depth:t}:{}})}if(n.kind===`unstore`&&r&&o.push({action:`unstore`,from:r,...i?{ifOn:i}:{},...n.keepLast?{}:{keepLast:!1}}),n.kind===`notify`&&r&&o.push({action:`notify`,message:r}),n.kind===`delete`&&o.push({action:`delete`}),n.kind===`destroy`&&o.push({action:`destroy`}),n.kind===`agent`&&r&&i){let e=a(n);o.push({action:`agent`,slug:r,prompt:i,...e?{output:e}:{}})}if(n.kind===`script`&&r){let e=a(n);o.push({action:`script`,path:r,...e?{output:e}:{}})}}return{id:e.id||ut(e.description),enabled:!0,...e.description?{description:e.description}:{},...e.cascade?{cascade:!0}:{},...e.approval?{approval:!0}:{},...e.editable?.length?{editable:e.editable}:{},...e.ttl===void 0?{}:{ttl:e.ttl},when:n,then:o}}function ht(e){let{event:t,schema:n,from:r,to:i,subject:a,body:o,sender:s,thread:c,channel:l,platform:u,path:d,pathExact:f,eventPathExact:p,mime:m,url:h,attachment:g,...ee}=e.when;if(Object.keys(ee).length>0)return null;let _=Array.isArray(t)?t:[t];if(!_.length||!_.every(e=>typeof e==`string`&&et.some(t=>t.value===e))||n!==void 0&&typeof n!=`string`)return null;let v=[],y=(e,t)=>{let n=Array.isArray(t)?t:[t];if(e.endsWith(`Regex`)){if(!n.every(e=>typeof e==`string`))return!1;for(let t of n)v.push({field:e,value:t})}else if(nt.has(e))for(let t of n){if(!t||typeof t!=`object`||Object.keys(t).length!==1||typeof t.equals!=`string`)return!1;v.push({field:e,value:t.equals})}else if([`from`,`to`,`subject`,`body`,`sender`].includes(e))for(let t of n)if(typeof t==`string`)v.push({field:e,value:t});else if([`from`,`to`,`sender`].includes(e)&&t&&typeof t==`object`&&Object.keys(t).length===1&&typeof t.equals==`string`)v.push({field:`${e}Exact`,value:t.equals});else if(t&&typeof t==`object`&&Object.keys(t).length===1&&typeof t.regex==`string`)v.push({field:`${e}Regex`,value:t.regex});else return!1;else{if(!n.every(e=>typeof e==`string`))return!1;v.push({field:e,value:n.join(` | `)})}return!0};if(d!==void 0&&!y(`path`,d)||f!==void 0&&!y(`pathExact`,f)||p!==void 0&&!y(`eventPathExact`,p)||m!==void 0&&!y(`mime`,m)||r!==void 0&&!y(`from`,r)||i!==void 0&&!y(`to`,i)||a!==void 0&&!y(`subject`,a)||o!==void 0&&!y(`body`,o)||s!==void 0&&!y(`sender`,s)||c!==void 0&&!y(`threadExact`,c)||l!==void 0&&!y(`channelExact`,l)||u!==void 0&&!y(`platformExact`,u)||g!==void 0&&!y(`attachment`,g))return null;if(h!==void 0){if(typeof h==`string`)v.push({field:`urlContains`,value:h});else if(h&&typeof h==`object`){let e=h;if(Object.keys(e).filter(e=>e!==`host`&&e!==`contains`&&e!==`regex`).length||e.host!==void 0&&!y(`urlHost`,e.host)||e.contains!==void 0&&!y(`urlContains`,e.contains)||e.regex!==void 0&&!y(`urlRegex`,e.regex))return null}else return null}let b=e=>{let t=e.output&&typeof e.output==`object`?e.output:{};if(Object.keys(t).filter(e=>e!==`note`&&e!==`file`&&e!==`notify`).length)return null;let n=t.note&&typeof t.note==`object`?t.note:{},r=t.file&&typeof t.file==`object`?t.file:{};return Object.keys(r).filter(e=>e!==`path`&&e!==`backend`&&e!==`insert`).length?null:{notePath:typeof n.path==`string`?n.path:``,noteTitle:typeof n.title==`string`?n.title:``,filePath:typeof r.path==`string`?r.path:``,fileBackend:r.backend===`data`?`data`:`home`,fileInsert:typeof r.insert==`string`?r.insert:``,notifyReply:t.notify===!0}},x=[];for(let t of e.then||[]){if(t.approval!==void 0)return null;if(t.action===`link`&&Array.isArray(t.paths))x.push({...K(`link`),a:t.paths.join(`, `),b:Array.isArray(t.tags)?t.tags.join(`, `):``,recursive:t.recursive===!0});else if(t.action===`unlink`&&Array.isArray(t.paths))x.push({...K(`unlink`),a:t.paths.join(`, `),recursive:t.recursive===!0});else if(t.action===`tag`&&Array.isArray(t.tags))x.push({...K(`tag`),a:t.tags.join(`, `)});else if(t.action===`moveMessage`){if(Object.keys(t).some(e=>e!==`action`&&e!==`folder`)||typeof t.folder!=`string`)return null;x.push({...K(`moveMessage`),a:t.folder})}else if(t.action===`notify`&&typeof t.message==`string`)x.push({...K(`notify`),a:t.message});else if(t.action===`store`&&typeof t.to==`string`){if(t.pathMode!==void 0&&(t.pathMode!==`full`||t.recursive!==!0||Y(v)===null)||t.recursive===!0&&Y(v)!==null&&t.pathMode!==`full`||t.folder!==void 0&&typeof t.folder!=`string`||t.key!==void 0&&typeof t.key!=`string`)return null;let e=typeof t.key==`string`?t.key:``;x.push({...K(`store`),a:t.to,b:e===ot||e===G?``:e,storeFolder:typeof t.folder==`string`?t.folder:``,recursive:t.recursive===!0,storeName:e?e===ot?`title`:e===G?`dated`:`custom`:`keep`,storeFrom:typeof t.from==`string`?t.from:Array.isArray(t.from)?String(t.from[0]??``):``,storeMode:t.mode===`move`?`move`:`copy`,storeConflict:t.onConflict===`error`||t.onConflict===`overwrite`?t.onConflict:`rename`})}else if(t.action===`sendFile`){let e=new Set([`action`,`source`,`driver`,`address`,`to`,`target`,`subject`,`message`,`mime`,`filename`,`includeInline`]);if(Object.keys(t).some(t=>!e.has(t))||![`imap`,`slack`,`whatsapp`].includes(String(t.driver))||typeof t.address!=`string`||t.source!==void 0&&![`document`,`attachments`,`download`].includes(String(t.source))||[`target`,`subject`,`message`,`filename`].some(e=>t[e]!==void 0&&typeof t[e]!=`string`)||t.includeInline!==void 0&&typeof t.includeInline!=`boolean`)return null;let n=Array.isArray(t.to)?t.to:t.to===void 0?[]:[t.to],r=Array.isArray(t.mime)?t.mime:[t.mime??`*`];if(!n.every(e=>typeof e==`string`)||!r.every(e=>typeof e==`string`)||(t.driver===`imap`?t.target!==void 0:t.to!==void 0||t.subject!==void 0))return null;x.push({...K(`sendFile`),a:t.address,b:t.driver===`imap`?n.join(`, `):String(t.target||``),sendDriver:t.driver,sendSource:t.source||`document`,sendSubject:String(t.subject??`{{file.name}}`),sendMessage:String(t.message||``),attachmentMime:r.join(`, `),attachmentName:String(t.filename||``),includeInline:t.includeInline===!0})}else if(t.action===`extractAttachments`){let e=new Set([`action`,`to`,`folder`,`subfolder`,`mime`,`filename`,`includeInline`,`onConflict`]);if(Object.keys(t).some(t=>!e.has(t))||typeof t.to!=`string`||[`folder`,`subfolder`,`filename`].some(e=>t[e]!==void 0&&typeof t[e]!=`string`)||t.includeInline!==void 0&&typeof t.includeInline!=`boolean`||t.onConflict!==void 0&&t.onConflict!==`rename`&&t.onConflict!==`error`)return null;let n=Array.isArray(t.mime)?t.mime:[t.mime??`*`];if(!n.every(e=>typeof e==`string`))return null;x.push({...K(`extractAttachments`),a:t.to,storeFolder:typeof t.folder==`string`?t.folder:``,attachmentPath:typeof t.subfolder==`string`?t.subfolder:``,attachmentMime:n.join(`, `),attachmentName:typeof t.filename==`string`?t.filename:``,includeInline:t.includeInline===!0,storeConflict:t.onConflict===`error`?`error`:`rename`})}else if(t.action===`download`){let e=new Set([`action`,`to`,`folder`,`recursive`,`kind`,`insert`,`tags`,`depth`]);if(Object.keys(t).some(t=>!e.has(t)))return null;let n=typeof t.kind==`string`?t.kind:`auto`;if(!st.some(e=>e.value===n))return null;let r=Array.isArray(t.insert)?t.insert:typeof t.insert==`string`?[t.insert]:[];if(!r.every(e=>typeof e==`string`))return null;x.push({...K(`download`),a:typeof t.to==`string`?t.to:`workspace:home`,b:r.join(`, `),storeFolder:typeof t.folder==`string`?t.folder:``,recursive:t.recursive===!0,dlKind:n,dlDepth:typeof t.depth==`number`?String(t.depth):`2`,dlTags:Array.isArray(t.tags)?t.tags.join(`, `):``})}else if(t.action===`unstore`&&(typeof t.from==`string`||Array.isArray(t.from))){let e=e=>Array.isArray(e)?String(e[0]??``):typeof e==`string`?e:``;x.push({...K(`unstore`),a:e(t.from),b:e(t.ifOn),keepLast:t.keepLast!==!1})}else if(t.action===`delete`)x.push(K(`delete`));else if(t.action===`destroy`)x.push(K(`destroy`));else if(t.action===`agent`&&typeof t.slug==`string`&&typeof t.prompt==`string`){let e=b(t);if(!e)return null;x.push({...K(`agent`),a:t.slug,b:t.prompt,...e})}else if(t.action===`script`&&typeof t.path==`string`){let e=b(t);if(!e)return null;x.push({...K(`script`),a:t.path,...e})}else return null}return{id:e.id,description:e.description||``,events:_,schema:typeof n==`string`?n:``,cascade:e.cascade===!0,approval:e.approval===!0,...e.editable?.length?{editable:e.editable}:{},...e.ttl===void 0?{}:{ttl:e.ttl},conditions:v,actions:x.length?x:[K(`link`)]}}var gt=(e,t)=>t.find(t=>t.value===e)?.label?.replace(/\s\(\d+\)$/,``)||(e?String(e).replace(/^data\/schema\//,``):`any item`);function _t(e,t=$e){let n=e.when,r=ye(e).map(e=>et.find(t=>t.value===e)?.label||e).join(` or `),i=[`When ${gt(n.schema,t)} ${r}`],a=e=>Array.isArray(e)?e.join(` or `):typeof e==`object`&&e?JSON.stringify(e):String(e),o={path:`under`,pathExact:`directly in`,eventPathExact:`inserted / linked directly into`,mime:`type`,from:`from`,to:`to`,subject:`subject`,body:`body / text`,sender:`sender`,thread:`thread`,channel:`conversation`,platform:`platform`,url:`url`,attachment:`attachment`};for(let e of Object.keys(o))n[e]!==void 0&&i.push(`${o[e]} ${a(n[e])}`);return i.join(` · `)}function vt(e){let t=e.output||{},n=t.note||{},r=t.file||{};return[n.path?`reply → note ${n.path}`:``,r.path?`reply → file ${r.backend===`data`?`data:`:`home/`}${r.path}${r.insert?` (indexed at ${r.insert})`:``}`:``,t.notify?`reply → notify`:``].filter(Boolean).join(`, `)}function yt(e){if(e.action===`link`)return`file into ${e.paths?.join(`, `)}${e.recursive===!0?` (sub-folders kept)`:``}`;if(e.action===`unlink`)return`remove from ${e.paths?.join(`, `)}${e.recursive===!0?` (sub-folders kept)`:``}`;if(e.action===`tag`)return`tag ${e.tags?.join(`, `)}`;if(e.action===`store`){let t=typeof e.folder==`string`&&e.folder?`/${e.folder}`:``,n=e.key===ot?`, named by title`:e.key===G?`, by date`:typeof e.key==`string`&&e.key?`, as ${e.key}`:``;return`${e.mode===`move`?`move`:`copy`} the file to ${e.to}${t}${e.recursive===!0?e.pathMode===`full`?` (full directory path recreated)`:` (sub-folder path recreated)`:``}${n}`}if(e.action===`extractAttachments`){let t=[e.to,e.folder,e.subfolder].filter(Boolean).join(`/`);return`extract ${Array.isArray(e.mime)?e.mime.join(`, `):e.mime||`all`} attachments to ${t}${e.filename?` (filename contains ${e.filename})`:``}`}if(e.action===`moveMessage`)return`move the email to mail folder ${e.folder}`;if(e.action===`download`){let t=st.find(t=>t.value===(e.kind||`auto`)),n=typeof e.folder==`string`&&e.folder?`/${e.folder}`:``,r=Array.isArray(e.insert)&&e.insert.length?`, filed at ${e.insert.join(`, `)}`:`, filed next to the link`;return`download ${t?.value===`auto`?`the link (auto-detected)`:t?.label||e.kind} to ${e.to||`workspace:home`}${n}${e.recursive===!0?` (sub-folders kept)`:``}${r}`}if(e.action===`unstore`)return`delete the file from ${Array.isArray(e.from)?e.from.join(`, `):e.from}${e.ifOn?` once it is on ${Array.isArray(e.ifOn)?e.ifOn.join(`, `):e.ifOn}`:``}`;if(e.action===`sendFile`)return`send ${e.source===`attachments`?`matching attachments`:e.source===`download`?`downloaded files`:`the file`} via ${e.driver===`imap`?`email`:e.driver} to ${Array.isArray(e.to)?e.to.join(`, `):e.to||e.target||`…`}`;if(e.action===`notify`)return`send me a notification`;if(e.action===`delete`)return`delete from Canvas (keeps stored files/mail)`;if(e.action===`destroy`)return`⚠ delete everywhere (index + storage)`;if(e.action===`agent`){let t=vt(e);return`ask agent "${e.slug}"${t?` (${t})`:``}`}if(e.action===`script`){let t=vt(e);return`run ${e.path}${t?` (${t})`:``}`}return e.action}function bt(e){return(e.then||[]).map(yt).join(` · `)||`(no actions)`}function xt(e){return be(e).length>0&&(e.then||[]).length>0&&(e.then||[]).every(e=>e.action===`link`||e.action===`unlink`||e.action===`store`||e.action===`unstore`)}function St(e){let t={};for(let n of e){if(n.handlerType!==`rule`)continue;let e=t[n.handler]||={count:0,errors:0,last:n};e.count++,n.status===`error`&&e.errors++,n.ts>e.last.ts&&(e.last=n)}return t}function Ct(e){let t=Date.now()-new Date(e).getTime();if(!Number.isFinite(t)||t<0)return``;let n=Math.floor(t/6e4);if(n<1)return`just now`;if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<48?`${r}h ago`:`${Math.floor(r/24)}d ago`}function wt(e){return e.some(e=>e.address===`workspace:home`)?`workspace:home`:e.find(e=>e.address!==`workspace:data`)?.address||e[0]?.address||``}function Tt(e){if(e.kind===`document`&&e.rule)return{...ht(e.rule)||q,id:null};if(e.kind===`download`){let t=e.path?` filed under ${e.path.replace(/^(ctx|dir):/,``)}`:``;return{...q,description:`Download links${t}`,schema:`tab`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:e.path||``}],actions:[{...K(`download`),a:e.storeTo||``,storeFolder:e.storeFolder||`Downloads`,recursive:!0}]}}if(e.kind===`store`){let t=e.path||``,n=/^(?:(?:ctx|context):)?\//.test(t),r=[{field:n?`eventPathExact`:`path`,value:n&&t.startsWith(`/`)?`ctx:${t}`:t}],i=e.path?`${n?` inserted / linked directly into`:` filed under`} ${e.path.replace(/^(ctx|context|dir|directory):/,``)}`:``;return{...q,description:e.storeTo?`Copy files${i} to ${e.storeTo}${e.storeFolder?`/${e.storeFolder}`:``}`:`Copy files${i} to a storage backend`,schema:`file`,events:[`document.inserted`,`document.linked`],conditions:r,actions:[{...K(`store`),a:e.storeTo||``,storeFolder:e.storeFolder||``,recursive:ft(r)}]}}return{...q,description:`Mirror ${e.path} into ${e.target}`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:e.path||``}],actions:[{...K(`link`),a:e.target||`dir:/`,recursive:!0}]}}var X=`h-10 w-full rounded-md border bg-background px-3 text-sm outline-none focus:ring-2 focus:ring-ring disabled:opacity-50`,Z=`h-10 text-sm`;function Q({label:e,hint:t,children:n,className:r}){return(0,W.jsxs)(`label`,{className:C(`flex min-w-0 flex-col gap-1.5`,r),children:[(0,W.jsx)(`span`,{className:`text-sm font-medium`,children:e}),n,t&&(0,W.jsx)(`span`,{className:`text-xs leading-relaxed text-muted-foreground`,children:t})]})}function $({checked:e,onChange:t,label:n,hint:r,disabled:i}){return(0,W.jsxs)(`button`,{type:`button`,role:`switch`,"aria-checked":e,disabled:i,onClick:()=>t(!e),className:C(`flex w-full items-start gap-3 rounded-lg border p-3 text-left transition-colors hover:bg-accent/40 disabled:cursor-not-allowed disabled:opacity-50`,e&&`border-primary/40 bg-primary/5`),children:[(0,W.jsx)(`span`,{className:C(`mt-0.5 inline-flex h-5 w-9 shrink-0 items-center rounded-full p-0.5 transition-colors`,e?`bg-primary`:`bg-muted-foreground/30`),children:(0,W.jsx)(`span`,{className:C(`h-4 w-4 rounded-full bg-background shadow transition-transform`,e&&`translate-x-4`)})}),(0,W.jsxs)(`span`,{className:`min-w-0`,children:[(0,W.jsx)(`span`,{className:`block text-sm font-medium`,children:n}),r&&(0,W.jsx)(`span`,{className:`block text-xs leading-relaxed text-muted-foreground`,children:r})]})]})}function Et({value:e,options:t,onChange:n}){return(0,W.jsx)(`div`,{className:`inline-flex h-10 rounded-md border bg-background p-1`,children:t.map(t=>(0,W.jsx)(`button`,{type:`button`,onClick:()=>n(t.value),className:C(`rounded px-3 text-sm transition-colors`,e===t.value?`bg-primary text-primary-foreground shadow-sm`:`text-muted-foreground hover:text-foreground`),children:t.label},t.value))})}function Dt({active:e,onClick:t,children:n,title:r}){return(0,W.jsx)(`button`,{type:`button`,title:r,onClick:t,"aria-pressed":e,className:C(`h-9 rounded-full border px-3.5 text-sm transition-colors`,e?`border-primary bg-primary/10 font-medium text-foreground`:`text-muted-foreground hover:bg-accent hover:text-foreground`),children:n})}function Ot({step:e,title:t,hint:n}){return(0,W.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,W.jsx)(`span`,{className:`mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-primary/10 text-sm font-semibold text-primary`,children:e}),(0,W.jsxs)(`div`,{children:[(0,W.jsx)(`h3`,{className:`text-base font-semibold leading-7`,children:t}),n&&(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:n})]})]})}function kt({icon:e,tone:t,size:n=`md`}){return(0,W.jsx)(`span`,{className:C(`inline-flex shrink-0 items-center justify-center rounded-xl`,n===`lg`?`h-12 w-12`:`h-10 w-10`,t),children:(0,W.jsx)(e,{className:n===`lg`?`h-6 w-6`:`h-5 w-5`})})}function At({workspaceId:e,onOpenJson:t,onShowRuns:n,backfillLimit:r,prefill:d,onPrefillConsumed:p,createOnly:m=!1,onCreated:g,onCancel:_}){let{showToast:y,showProgress:b}=re(),[S,ne]=(0,k.useState)([]),[E,D]=(0,k.useState)({}),ae=e=>{Ae(e,{limit:500}).then(e=>D(St(e))).catch(()=>D({}))},[se,ce]=(0,k.useState)(!0),[O,A]=(0,k.useState)(null),[fe,j]=(0,k.useState)(!1),[M,N]=(0,k.useState)(!1),[pe,P]=(0,k.useState)([]),[F,me]=(0,k.useState)([]),[he,ge]=(0,k.useState)([]),[_e,ve]=(0,k.useState)(``),ye=(0,k.useRef)(null),[Se,Ce]=(0,k.useState)(e);e!==Se&&(Ce(e),ce(!0)),(0,k.useEffect)(()=>{Te(e).then(e=>ne(e)).finally(()=>ce(!1)),ae(e)},[e]);let[we,De]=(0,k.useState)(null);d!==we&&(De(d),d&&(A(Tt(d)),j(!1))),(0,k.useEffect)(()=>{d&&p?.()},[d,p]),(0,k.useEffect)(()=>{Ye(e).then(e=>P(e.map(e=>e.path))).catch(()=>P([]))},[e]),(0,k.useEffect)(()=>{let t=!1;return le(e).then(e=>{t||(ge([...new Map(e.map(e=>[`${e.driver}:${e.address}`,e])).values()]),ve(``))}).catch(()=>{t||(ge([]),ve(`Sending accounts could not be loaded.`))}),()=>{t=!0}},[e]),(0,k.useEffect)(()=>{oe(e).then(e=>{let t=e.filter(e=>e.kind===`storage`&&e.enabled!==!1&&e.config?.supported!==!1&&e.config?.readOnly!==!0&&e.capabilities?.write!==!1);me(t);let n=wt(t);n&&A(e=>e&&e.actions.some(e=>(e.kind===`store`||e.kind===`download`)&&!e.a)?{...e,actions:e.actions.map(e=>(e.kind===`store`||e.kind===`download`)&&!e.a?{...e,a:n}:e)}:e)}).catch(()=>me([]))},[e]);let[Oe,ke]=(0,k.useState)($e);(0,k.useEffect)(()=>{Be(e).then(e=>{e.schemas?.length&&ke([{value:``,label:`any item`},...e.schemas.map(e=>({value:e.id,label:`${e.name} (${e.count})`}))])}).catch(()=>{})},[e]);let I=async(t,n)=>{N(!0);try{return await Ee(e,t),ne(t),y({title:n,description:`rules.json updated (committed to workspace git)`}),!0}catch(e){return y({title:`Error`,description:e instanceof Error?e.message:`Failed to save rules`,variant:`destructive`}),!1}finally{N(!1)}},je=async()=>{if(!O||se||M)return;let t;try{t=mt(O,F)}catch(e){y({title:`Invalid rule`,description:e instanceof Error?e.message:`Check the rule conditions and actions`,variant:`destructive`});return}if(!t.then.length){y({title:`Add an action`,description:`Pick at least one "then" action and fill in its fields.`,variant:`destructive`});return}if(m){t.id=`${t.id}-${Math.random().toString(36).slice(2,10)}`,N(!0);try{await He(e,t),y({title:`Rule created`,description:`The rule will run for matching new items.`}),g?.()}catch(e){y({title:`Could not create rule`,description:e instanceof Error?e.message:`Failed to save rule`,variant:`destructive`})}finally{N(!1)}return}!O.id&&S.some(e=>e.id===t.id)&&(t.id=`${t.id}-${Math.random().toString(36).slice(2,10)}`);let n=O.id?S.map(e=>e.id===O.id?{...t,enabled:e.enabled!==!1}:e):[...S,t];await I(n,O.id?`Rule updated`:`Rule created`)&&(A(null),g?.())},Me=e=>I(S.map(t=>t.id===e?{...t,enabled:t.enabled===!1}:t),`Rule toggled`),Ne=e=>{confirm(`Delete rule "${e}"?`)&&I(S.filter(t=>t.id!==e),`Rule deleted`)},[Pe,Fe]=(0,k.useState)(null),Le=async t=>{Fe(t);try{let n=await Ie(e,{ruleId:t,dryRun:!0,limit:r}),i=n.results.filter(e=>e.matched).length;if(!i){y({title:`Apply to existing items`,description:`No matches among ${n.processed} existing documents (conditions evaluate against each document's current tree placements). Raise the batch size in the toolbar to cover more.`});return}if(!confirm(`Rule "${t}" matches ${i} of the first ${n.processed} of ${n.total??n.processed} existing documents. Run its actions on all of them now?`))return;await qe(b,e,[t])}catch(e){y({title:`Backfill failed`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{Fe(null),ae(e)}},L=(e,t)=>A(n=>n&&{...n,[e]:t}),Re=e=>{A(e.build({backend:wt(F)})),j(!1),requestAnimationFrame(()=>ye.current?.scrollIntoView({behavior:`smooth`,block:`start`}))},ze=e=>{let n=ht(e);n?(A(n),j(!1),requestAnimationFrame(()=>ye.current?.scrollIntoView({behavior:`smooth`,block:`start`}))):t?.()},[R,z]=(0,k.useState)(null),Ve=(e,t)=>t.treeType===`context`?e:t.treeName===`directory`?`dir:${e}`:`${t.treeName}:${e}`,Ue=(e,t)=>{if(!R||!O||!e.length){z(null);return}if(R.target===`storeFolder`){let t=xe(e[0]);L(`actions`,O.actions.map((e,n)=>n===R.index?{...e,storeFolder:t?.rel||``,...t?.backend&&F.some(e=>e.address===t.backend)?{a:t.backend}:{}}:e))}else if(R.target===`condition`){let n=e.map(e=>Ve(e,t)),r=t.treeType===`context`&&O.actions.some(e=>e.kind===`store`);L(`conditions`,O.conditions.map((e,t)=>t===R.index?{...e,...r?{field:`eventPathExact`}:{},value:n.join(` | `)}:e))}else{let n=e.map(e=>Ve(e,t));L(`actions`,O.actions.map((e,t)=>t===R.index?e.kind===`download`?{...e,b:n.join(`, `)}:{...e,a:n.join(`, `)}:e))}z(null)},B=(e,t,n=`Browse…`)=>(0,W.jsxs)(w,{type:`button`,size:`sm`,variant:`outline`,className:`h-10 shrink-0 px-3`,title:n,onClick:()=>z({target:e,index:t}),children:[(0,W.jsx)(s,{className:`h-4 w-4 sm:mr-1.5`}),(0,W.jsx)(`span`,{className:`hidden sm:inline`,children:`Browse`})]}),Ge=ft(O?.conditions||[]),V=!!O?.conditions.some(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field)&&e.value.trim()),Ke=e=>`${e.address}${e.address===`workspace:data`?` — managed blob store (default)`:e.address===`workspace:home`?` — workspace home folder`:e.driver?` — ${e.driver}`:``}`,H=(e,t,n,r=`workspace:home`)=>F.length?(0,W.jsxs)(`select`,{className:X,value:e,onChange:e=>t(e.target.value),children:[(0,W.jsx)(`option`,{value:``,children:n}),F.map(e=>(0,W.jsx)(`option`,{value:e.address,children:Ke(e)},e.address)),e&&!F.some(t=>t.address===e)&&(0,W.jsx)(`option`,{value:e,children:e})]}):(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:r,value:e,onChange:e=>t(e.target.value)}),Je=S.filter(xt),U=S.filter(e=>!xt(e)),Xe=({rule:e})=>{let t=e.enabled!==!1,r=ht(e)!==null,i=E[e.id],a=at(e.then?.[0]?.action||`link`),o=be(e);return(0,W.jsxs)(`div`,{className:C(`rule-card rounded-xl border bg-card p-4 transition-opacity`,!t&&`opacity-60`),children:[(0,W.jsx)(kt,{icon:a.icon,tone:a.tone}),(0,W.jsxs)(`div`,{className:`rule-card-content min-w-0 space-y-1.5`,children:[(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,W.jsx)(`h3`,{className:`text-base font-semibold leading-6`,children:e.description||e.id}),e.approval===!0&&(0,W.jsx)(`span`,{className:`rounded-full bg-warning/15 px-2 py-0.5 text-xs font-medium text-warning`,children:`needs approval`}),e.cascade===!0&&(0,W.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,children:`incl. automation-created`}),!r&&(0,W.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,title:`This rule uses matchers the builder cannot show; edit it as JSON.`,children:`JSON only`})]}),(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:_t(e,Oe)}),(0,W.jsxs)(`p`,{className:`flex items-start gap-1.5 text-sm`,children:[(0,W.jsx)(v,{className:`mt-1 h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,W.jsx)(`span`,{children:bt(e)})]}),o.length>0&&(0,W.jsx)(`p`,{className:`truncate font-mono text-xs text-muted-foreground`,title:o.join(` | `),children:o.join(` | `)}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:i?(0,W.jsxs)(`button`,{type:`button`,className:C(`text-left underline-offset-2 hover:underline`,i.last.status===`error`&&`text-destructive`,!n&&`cursor-default hover:no-underline`),title:n?`Show this rule's run log`:i.last.error||i.last.skipReason||``,onClick:()=>n?.(e.id),children:[`ran `,i.count,`×`,i.errors?` (${i.errors} failed)`:``,` · last `,i.last.status,` `,Ct(i.last.ts)]}):`not run yet`})]}),(0,W.jsxs)(`div`,{className:`rule-card-actions`,children:[(0,W.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":t,disabled:M,title:t?`Enabled — click to pause`:`Paused — click to enable`,onClick:()=>Me(e.id),className:C(`mr-1 inline-flex h-6 w-11 items-center rounded-full p-0.5 transition-colors`,t?`bg-primary`:`bg-muted-foreground/30`),children:(0,W.jsx)(`span`,{className:C(`h-5 w-5 rounded-full bg-background shadow transition-transform`,t&&`translate-x-5`)})}),(0,W.jsxs)(w,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5`,title:e.when.eventPathExact===void 0?`Apply this rule to existing items (dry-run first)`:`Requires an original insert/link event. Current folder membership cannot reconstruct its destination.`,disabled:Pe!==null||e.when.eventPathExact!==void 0,onClick:()=>Le(e.id),children:[Pe===e.id?(0,W.jsx)(ee,{className:`h-4 w-4 animate-spin`}):(0,W.jsx)(l,{className:`h-4 w-4`}),(0,W.jsx)(`span`,{className:`rule-card-action-label ml-1.5`,children:`Apply`})]}),(0,W.jsxs)(w,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5`,title:r?`Edit rule`:`Edit as JSON`,onClick:()=>ze(e),children:[r?(0,W.jsx)(te,{className:`h-4 w-4`}):(0,W.jsx)(h,{className:`h-4 w-4`}),(0,W.jsx)(`span`,{className:`rule-card-action-label ml-1.5`,children:`Edit`})]}),(0,W.jsx)(w,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5 text-destructive hover:text-destructive`,title:`Delete rule`,onClick:()=>Ne(e.id),children:(0,W.jsx)(f,{className:`h-4 w-4`})})]})]})},Ze=(0,W.jsxs)(`div`,{className:`space-y-3`,children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,W.jsx)(`h3`,{className:`text-base font-semibold`,children:`What should happen automatically?`}),fe&&(0,W.jsxs)(w,{size:`sm`,variant:`ghost`,onClick:()=>j(!1),children:[(0,W.jsx)(c,{className:`mr-1 h-4 w-4`}),` Close`]})]}),(0,W.jsx)(`div`,{className:`grid min-w-0 grid-cols-[repeat(auto-fill,minmax(min(100%,17rem),1fr))] gap-3`,children:dt.map(e=>(0,W.jsxs)(`button`,{type:`button`,onClick:()=>Re(e),className:`flex min-w-0 items-start gap-3 rounded-xl border bg-card p-4 text-left transition-colors hover:border-primary/50 hover:bg-accent/40`,children:[(0,W.jsx)(kt,{icon:e.icon,tone:e.tone,size:`lg`}),(0,W.jsxs)(`span`,{className:`min-w-0`,children:[(0,W.jsx)(`span`,{className:`block text-base font-semibold leading-6`,children:e.title}),(0,W.jsx)(`span`,{className:`mt-1 block break-words text-sm leading-relaxed text-muted-foreground`,children:e.blurb})]})]},e.id))})]});return(0,W.jsxs)(`div`,{className:`rule-builder min-w-0 space-y-5`,children:[!m&&(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,W.jsxs)(`div`,{className:`min-w-0 flex-[1_1_20rem]`,children:[(0,W.jsx)(`h2`,{className:`text-lg font-semibold`,children:`Rules`}),(0,W.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Rules run automatically as items arrive or get filed — no code needed. Stored in`,` `,(0,W.jsx)(`span`,{className:`font-mono`,children:`rules.json`}),` in the workspace git.`]})]}),(0,W.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[t&&(0,W.jsxs)(w,{variant:`ghost`,onClick:t,title:`Edit rules.json directly`,children:[(0,W.jsx)(h,{className:`mr-1.5 h-4 w-4`}),` JSON`]}),(0,W.jsxs)(w,{onClick:()=>{A(null),j(!0)},disabled:fe,children:[(0,W.jsx)(u,{className:`mr-1.5 h-4 w-4`}),` New rule`]})]})]}),fe&&!O&&Ze,O&&(0,W.jsxs)(`div`,{ref:ye,className:`scroll-mt-4 space-y-6 rounded-xl border bg-card p-4 sm:p-6`,children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,W.jsx)(`h3`,{className:`text-lg font-semibold`,children:O.id?`Edit rule`:`New rule`}),(0,W.jsxs)(w,{variant:`ghost`,size:`sm`,onClick:()=>A(null),children:[(0,W.jsx)(c,{className:`mr-1 h-4 w-4`}),` Cancel`]})]}),(0,W.jsx)(Q,{label:`Name`,hint:`Shown in the list and the run log.`,children:(0,W.jsx)(T,{className:`h-11 text-base`,placeholder:`Keep UI designs in Projects/Canvas/UI`,value:O.description,onChange:e=>L(`description`,e.target.value)})}),(0,W.jsxs)(`section`,{className:`space-y-4`,children:[(0,W.jsx)(Ot,{step:1,title:`When…`,hint:`What the rule reacts to. All conditions must match; repeat a condition for either/or.`}),(0,W.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-[minmax(0,220px)_1fr]`,children:[(0,W.jsx)(Q,{label:`Item`,children:(0,W.jsxs)(`select`,{className:X,value:O.schema,onChange:e=>L(`schema`,e.target.value),children:[Oe.map(e=>(0,W.jsx)(`option`,{value:e.value,children:e.label},e.value)),O.schema&&!Oe.some(e=>e.value===O.schema)&&(0,W.jsx)(`option`,{value:O.schema,children:O.schema.replace(/^data\/schema\//,``)})]})}),(0,W.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,W.jsxs)(`span`,{className:`text-sm font-medium`,children:[`Event `,(0,W.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(any of)`})]}),(0,W.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:et.map(e=>{let t=O.events.includes(e.value);return(0,W.jsx)(Dt,{active:t,title:e.hint,onClick:()=>{let n=t?O.events.filter(t=>t!==e.value):[...O.events,e.value];n.length&&L(`events`,n)},children:e.label},e.value)})})]})]}),O.conditions.length>0&&(0,W.jsx)(`div`,{className:`space-y-2`,children:O.conditions.map((e,t)=>{let n=tt.find(t=>t.key===e.field);return(0,W.jsxs)(`div`,{className:`grid grid-cols-[2.25rem_1fr_auto] items-center gap-2 sm:grid-cols-[2.25rem_minmax(0,240px)_1fr_auto]`,children:[(0,W.jsx)(`span`,{className:`text-xs font-medium uppercase tracking-wide text-muted-foreground`,title:`Same condition again = either may match (OR); different conditions must all match (AND)`,children:O.conditions.slice(0,t).some(t=>rt(t.field)===rt(e.field))?`or`:`and`}),(0,W.jsx)(`select`,{className:X,value:e.field,onChange:e=>L(`conditions`,O.conditions.map((n,r)=>r===t?{...n,field:e.target.value}:n)),children:tt.map(e=>(0,W.jsx)(`option`,{value:e.key,children:e.label},e.key))}),(0,W.jsxs)(`div`,{className:`order-4 col-span-3 flex gap-2 sm:order-3 sm:col-span-1`,children:[(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:n?.hint,value:e.value,onChange:e=>L(`conditions`,O.conditions.map((n,r)=>r===t?{...n,value:e.target.value}:n))}),[`path`,`pathExact`,`eventPathExact`].includes(e.field)&&B(`condition`,t,`Browse the workspace trees`)]}),(0,W.jsx)(w,{size:`sm`,variant:`ghost`,className:`order-3 h-10 w-10 p-0 text-muted-foreground sm:order-4`,title:`Remove condition`,onClick:()=>L(`conditions`,O.conditions.filter((e,n)=>n!==t)),children:(0,W.jsx)(c,{className:`h-4 w-4`})})]},t)})}),(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,W.jsxs)(w,{size:`sm`,variant:`outline`,onClick:()=>L(`conditions`,[...O.conditions,{field:O.schema===`email`?`from`:`path`,value:``}]),children:[(0,W.jsx)(u,{className:`mr-1 h-4 w-4`}),` Add condition`]}),(0,W.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[`Contains matches literal text. Regex is case-insensitive: enter the pattern without /…/ delimiters; | stays part of the expression. For other filters, separate alternatives with `,(0,W.jsx)(`span`,{className:`font-mono`,children:`|`}),`, e.g. `,(0,W.jsx)(`span`,{className:`font-mono`,children:`image/* | video/*`}),`.`]})]})]}),(0,W.jsxs)(`section`,{className:`space-y-4`,children:[(0,W.jsx)(Ot,{step:2,title:`Then…`,hint:`Actions run in order. The item keeps its id, tags and folders unless an action says otherwise.`}),O.actions.map((t,n)=>{let r=e=>L(`actions`,O.actions.map((t,r)=>r===n?{...t,...e}:t)),i=F.find(e=>e.address===t.a),o=i?.capabilities?.paths===!0,s=Ge&&o,l=at(t.kind),u=n=>(0,W.jsxs)(`div`,{className:`space-y-3 rounded-lg border border-dashed p-3`,children:[(0,W.jsxs)(`p`,{className:`text-sm font-medium`,children:[`What to do with the `,n]}),(0,W.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,W.jsx)(Q,{label:`Save as a note at`,hint:`Context path by default, dir:/path for the directory tree.`,children:(0,W.jsx)(de,{inputClassName:Z,placeholder:`/notes/summaries (optional)`,value:t.notePath,onChange:e=>r({notePath:e}),fixedWorkspaceName:e,pickerTitle:`Save note under…`,onPickTarget:(e,t)=>r({notePath:t.treeType===`directory`?`dir:${e}`:e})})}),t.notePath.trim()&&(0,W.jsx)(Q,{label:`Note title`,children:(0,W.jsx)(T,{className:Z,placeholder:`Summary: {{doc.data.subject}}`,value:t.noteTitle,onChange:e=>r({noteTitle:e.target.value})})}),(0,W.jsx)(Q,{label:`Save as a file at`,hint:`Relative path under the workspace home folder or in the data blob store.`,children:(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`logs/agent.log (optional)`,value:t.filePath,onChange:e=>r({filePath:e.target.value})})}),t.filePath.trim()&&(0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(Q,{label:`File lives in`,children:(0,W.jsxs)(`select`,{className:X,value:t.fileBackend,onChange:e=>r({fileBackend:e.target.value}),children:[(0,W.jsx)(`option`,{value:`home`,children:`the workspace home folder`}),(0,W.jsx)(`option`,{value:`data`,children:`the data blob store`})]})}),(0,W.jsx)(Q,{label:`Also file the saved file under`,hint:`Index it as a document at this tree path.`,children:(0,W.jsx)(de,{inputClassName:Z,placeholder:`/path (optional)`,value:t.fileInsert,onChange:e=>r({fileInsert:e}),fixedWorkspaceName:e,tabs:[`context`],pickerTitle:`File under…`,onPickTarget:e=>r({fileInsert:e})})})]})]}),(0,W.jsx)($,{checked:t.notifyReply,onChange:e=>r({notifyReply:e}),label:`Send me a notification with the result`})]}),d=Y(O.conditions),f=t.kind===`store`&&t.a&&(!t.recursive||s)?pt(t,O.conditions,i):null,p=t.kind===`extractAttachments`&&t.a?We(t.a,t.storeFolder,t.attachmentPath):null;return(0,W.jsxs)(`div`,{className:`space-y-4 rounded-xl border bg-background p-4`,children:[(0,W.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,W.jsx)(kt,{icon:l.icon,tone:l.tone}),(0,W.jsx)(`select`,{className:C(X,`flex-1 font-medium`),value:t.kind,onChange:e=>r(K(e.target.value)),children:it.map(e=>(0,W.jsx)(`option`,{value:e.key,children:e.label},e.key))}),(0,W.jsx)(w,{size:`sm`,variant:`ghost`,className:`h-10 w-10 shrink-0 p-0 text-muted-foreground`,title:`Remove action`,disabled:O.actions.length===1,onClick:()=>L(`actions`,O.actions.filter((e,t)=>t!==n)),children:(0,W.jsx)(c,{className:`h-4 w-4`})})]}),(t.kind===`link`||t.kind===`unlink`)&&(0,W.jsxs)(`div`,{className:`space-y-3`,children:[(0,W.jsx)(Q,{label:t.kind===`link`?`Folder(s)`:`Remove from folder(s)`,hint:`Context-tree path by default; dir:/path for the directory tree. Comma-separate several.`,children:(0,W.jsxs)(`div`,{className:`flex gap-2`,children:[(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:t.kind===`link`?`/work/urgent or dir:/projects/x`:`/inbox or dir:/staging`,value:t.a,onChange:e=>r({a:e.target.value})}),B(`action`,n)]})}),t.kind===`link`&&(0,W.jsx)(Q,{label:`Tags`,hint:`Optional, comma-separated.`,children:(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`custom/design, ui`,value:t.b,onChange:e=>r({b:e.target.value})})}),(0,W.jsx)($,{checked:t.recursive,onChange:e=>r({recursive:e}),label:`Recreate sub-folder path in destination`,hint:V?`The part of the item's path below the "is under the folder" prefix is appended to the target: …/foo/a/b → target/a/b.`:`Needs an "is under the folder" condition to know where sub-folders start.`,disabled:!V})]}),t.kind===`moveMessage`&&(0,W.jsxs)(`div`,{className:`space-y-2`,children:[(0,W.jsx)(Q,{label:`Mail folder`,hint:`The folder on the email's own IMAP account, with / between levels (works for servers that use . too). {{YYYY}}, {{MM}}, {{DD}} = the email's date.`,children:(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`INBOX/Accounting/{{YYYY}}/Expenses`,value:t.a,onChange:e=>r({a:e.target.value})})}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Moves the message on the mail server, like dragging it in a mail client. Put this after Extract attachments so the files are copied first. The folder must already exist on the server; subscribe to it in the mailbox settings to see the moved mail in Canvas.`})]}),t.kind===`tag`&&(0,W.jsx)(Q,{label:`Tags`,hint:`Comma-separated.`,children:(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`urgent, follow-up`,value:t.a,onChange:e=>r({a:e.target.value})})}),t.kind===`store`&&(0,W.jsxs)(`div`,{className:`space-y-4`,children:[(0,W.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,W.jsx)(Q,{label:`Storage backend`,hint:`Where the file's bytes should live. Only writable backends are listed.`,children:H(t.a,e=>r({a:e}),`pick a backend…`)}),(0,W.jsx)(Q,{label:`Destination root folder`,hint:`Choose the folder beneath which the path will be recreated. Leave empty to use the backend root.`,children:(0,W.jsxs)(`div`,{className:`flex gap-2`,children:[(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`Projects/Canvas/UI`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),B(`storeFolder`,n,`Browse storage backends`)]})}),(0,W.jsx)(Q,{label:`File name`,children:(0,W.jsx)(`select`,{className:X,value:t.storeName,onChange:e=>r({storeName:e.target.value}),children:ct.map(e=>(0,W.jsx)(`option`,{value:e.value,children:e.label},e.value))})}),(0,W.jsx)(Q,{label:`Move or copy`,hint:t.storeMode===`move`?`Remove only the selected source copy after the destination is safely stored.`:`Preserve every existing copy.`,children:(0,W.jsx)(Et,{value:t.storeMode,onChange:e=>r({storeMode:e}),options:[{value:`copy`,label:`Copy`},{value:`move`,label:`Move`}]})}),t.storeMode===`move`&&(0,W.jsx)(Q,{className:`sm:col-span-2`,label:`Move bytes from (required)`,hint:`Context membership does not identify a source copy. If the file is absent here, nothing is moved. Multiple locations on this backend make the move ambiguous; use copy.`,children:H(t.storeFrom,e=>r({storeFrom:e}),`choose a source backend…`,`workspace:data`)}),t.storeName===`custom`&&(0,W.jsx)(Q,{className:`sm:col-span-2`,label:`Name template`,hint:`Tokens: {{YYYY}} {{MM}} {{DD}} {{HH}} {{mm}} {{ss}} (photo capture time when present), {{ext}} {{basename}} {{filename}} {{title}} {{id}}, plus {{doc.…}} fields. Slashes create sub-folders.`,children:(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`{{YYYY}}-{{MM}}-{{DD}} {{title}}{{ext}}`,value:t.b,onChange:e=>r({b:e.target.value})})})]}),(0,W.jsx)($,{checked:t.recursive,onChange:e=>r({recursive:e}),label:d===null?`Recreate sub-folder path in destination`:`Recreate directory path in destination`,hint:o?Ge?d===null?`The path below the source folder is appended beneath the destination root: …/UI/mobile → Root/mobile. Missing destination folders are created.`:`Only inserts or links directly into ctx:${d} trigger this rule. Its full path is appended beneath the destination root; descendant inserts do not match.`:`For Context, choose one folder with “is inserted / linked directly into”. Directory and Backends sources can include sub-folders.`:`Choose a destination that reports support for folder paths. Content-addressed blob stores cannot recreate sub-folder paths.`,disabled:!s&&!t.recursive}),f&&(0,W.jsxs)(`div`,{className:`space-y-1.5 rounded-lg bg-muted/60 px-3 py-3 text-sm`,"aria-live":`polite`,children:[(0,W.jsx)(`p`,{className:`font-medium`,children:`Destination preview`}),(0,W.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Root folder: `,(0,W.jsxs)(`span`,{className:`break-all font-mono`,children:[f.root,`/`]})]}),t.recursive&&(0,W.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Path added beneath it: `,(0,W.jsxs)(`span`,{className:`break-all font-mono`,children:[f.recreated||`(root)`,`/`]})]}),(0,W.jsx)(`p`,{className:`break-all font-mono`,children:f.result})]}),(0,W.jsxs)(`details`,{className:`group rounded-lg border`,children:[(0,W.jsxs)(`summary`,{className:`flex cursor-pointer select-none items-center gap-2 px-3 py-2 text-sm font-medium`,children:[(0,W.jsx)(a,{className:`h-4 w-4 transition-transform group-open:rotate-180`}),` More options`]}),(0,W.jsxs)(`div`,{className:`grid gap-4 border-t p-3 sm:grid-cols-2`,children:[t.storeMode===`copy`&&(0,W.jsx)(Q,{label:`Copy bytes from`,hint:`Optional source restriction. Default: any readable copy outside the destination backend.`,children:H(t.storeFrom,e=>r({storeFrom:e}),`any readable source`,`workspace:data (optional)`)}),(0,W.jsx)(Q,{label:`If the name is already taken`,children:(0,W.jsxs)(`select`,{className:X,value:t.storeConflict,onChange:e=>r({storeConflict:e.target.value}),children:[(0,W.jsx)(`option`,{value:`rename`,children:`add -1, -2, … to the name`}),(0,W.jsx)(`option`,{value:`error`,children:`skip the file`}),(0,W.jsx)(`option`,{value:`overwrite`,children:`overwrite the existing file`})]})})]})]}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The item keeps its id and virtual tree memberships. A move removes the chosen physical source location from the backend tree.`})]}),t.kind===`extractAttachments`&&(0,W.jsxs)(`div`,{className:`space-y-4`,children:[(0,W.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,W.jsx)(Q,{label:`Attachment types`,hint:`MIME types, comma-separated. application/pdf for PDFs, image/* for images, or * for all.`,children:(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`application/pdf`,value:t.attachmentMime,onChange:e=>r({attachmentMime:e.target.value})})}),(0,W.jsx)(Q,{label:`Attachment filename contains`,hint:`Optional: invoice, faktura, or another literal filename fragment. Every selected attachment must also match its type.`,children:(0,W.jsx)(T,{className:Z,placeholder:`Any matching filename`,value:t.attachmentName,onChange:e=>r({attachmentName:e.target.value})})}),(0,W.jsx)(Q,{label:`Storage backend`,hint:`Choose a writable backend that supports folder paths.`,children:H(t.a,e=>r({a:e}),`pick a backend…`)}),(0,W.jsx)(Q,{label:`Destination root folder`,hint:`Choose the folder beneath which date subfolders will be created. Leave empty to use the backend root.`,children:(0,W.jsxs)(`div`,{className:`flex gap-2`,children:[(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`Accounting`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),B(`storeFolder`,n,`Browse storage backends`)]})}),(0,W.jsx)(Q,{label:`Sub-folder path template`,hint:`Appended beneath the root folder. {{YYYY}} = year, {{MM}} = month, {{DD}} = day of the email. Leave empty to file directly in the root folder.`,children:(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`No subfolders`,value:t.attachmentPath,onChange:e=>r({attachmentPath:e.target.value})})}),(0,W.jsx)(Q,{label:`If the attachment name is already taken`,children:(0,W.jsxs)(`select`,{className:X,value:t.storeConflict,onChange:e=>r({storeConflict:e.target.value}),children:[(0,W.jsx)(`option`,{value:`rename`,children:`add -1, -2, … to the name`}),(0,W.jsx)(`option`,{value:`error`,children:`skip the file and report the conflict`})]})})]}),!o&&(0,W.jsx)(`p`,{className:`text-sm text-amber-700 dark:text-amber-400`,children:`This destination has not reported support for folder paths. Select a supported backend before saving.`}),p&&(0,W.jsxs)(`div`,{className:`space-y-1.5 rounded-lg bg-muted/60 px-3 py-3 text-sm`,"aria-live":`polite`,children:[(0,W.jsx)(`p`,{className:`font-medium`,children:`Destination preview`}),(0,W.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Example email dated `,p.date,`. Each email supplies its own date.`]}),(0,W.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Root folder: `,(0,W.jsxs)(`span`,{className:`break-all font-mono`,children:[p.root,`/`]})]}),(0,W.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Path added beneath it: `,(0,W.jsx)(`span`,{className:`break-all font-mono`,children:p.added?`${p.added}/`:`(none)`})]}),(0,W.jsx)(`p`,{className:`break-all font-mono`,children:p.result})]}),(0,W.jsx)($,{checked:t.includeInline,onChange:e=>r({includeInline:e}),label:`Include inline attachments`,hint:`Off by default, so signature images and embedded resources are excluded.`}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Copies matching attachments and keeps the email and its original files. Missing folders are created on the backend. Dates use the email's sent date (received/content date, then creation date if absent), in the server's timezone. This does not read the invoice date from the PDF.`}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Use Apply on the saved rule to process existing mail within the selected batch size. Add a subject or attachment filename condition if you need to distinguish invoices from other PDFs.`})]}),t.kind===`download`&&(0,W.jsxs)(`div`,{className:`space-y-4`,children:[(0,W.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,W.jsx)(Q,{label:`Download`,hint:st.find(e=>e.value===t.dlKind)?.hint,children:(0,W.jsx)(`select`,{className:X,value:t.dlKind,onChange:e=>r({dlKind:e.target.value}),children:st.map(e=>(0,W.jsx)(`option`,{value:e.value,children:e.label},e.value))})}),t.dlKind===`website`?(0,W.jsx)(Q,{label:`Mirror depth`,hint:`How many link hops to follow on the same site (1–5).`,children:(0,W.jsx)(T,{type:`number`,min:1,max:5,className:C(Z,`sm:max-w-32`),value:t.dlDepth,onChange:e=>r({dlDepth:e.target.value})})}):(0,W.jsx)(`div`,{className:`hidden sm:block`}),(0,W.jsx)(Q,{label:`Storage backend`,hint:`Where the downloaded file's bytes should live.`,children:H(t.a,e=>r({a:e}),`workspace:home (default)`)}),(0,W.jsx)(Q,{label:`Folder on that backend`,hint:`Relative to the backend root.`,children:(0,W.jsxs)(`div`,{className:`flex gap-2`,children:[(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`Downloads`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),B(`storeFolder`,n,`Browse storage backends`)]})}),(0,W.jsx)(Q,{label:`File the download under`,hint:`Leave empty to file it in the same folder(s) as the link. Comma-separate several.`,children:(0,W.jsxs)(`div`,{className:`flex gap-2`,children:[(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`same folders as the link`,value:t.b,onChange:e=>r({b:e.target.value})}),B(`action`,n)]})}),(0,W.jsx)(Q,{label:`Tags for the download`,hint:`Optional, comma-separated.`,children:(0,W.jsx)(T,{className:C(Z,`font-mono`),placeholder:`downloaded, custom/paper`,value:t.dlTags,onChange:e=>r({dlTags:e.target.value})})})]}),(0,W.jsx)($,{checked:t.recursive,onChange:e=>r({recursive:e}),label:`Recreate sub-folder path in destination`,hint:V?`A link filed under …/folder/a/b is downloaded into Folder/a/b.`:`Add an "is under the folder" condition to mirror sub-folders.`,disabled:!V}),(0,W.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`The link stays as it is; the download becomes a new file item next to it. Each link is downloaded once per rule. Videos need `,(0,W.jsx)(`span`,{className:`font-mono`,children:`yt-dlp`}),`, pages and websites `,(0,W.jsx)(`span`,{className:`font-mono`,children:`wget`}),` on the server.`]})]}),t.kind===`unstore`&&(0,W.jsxs)(`div`,{className:`space-y-4`,children:[(0,W.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,W.jsx)(Q,{label:`Delete the file from`,children:H(t.a,e=>r({a:e}),`pick a backend…`,`workspace:data`)}),(0,W.jsx)(Q,{label:`…but only once it is also on`,hint:`Safety: the copy is dropped only after another backend holds the file.`,children:H(t.b,e=>r({b:e}),`anywhere else`,`workspace:home (optional)`)})]}),(0,W.jsx)($,{checked:t.keepLast,onChange:e=>r({keepLast:e}),label:`Never delete the last copy`,hint:`Off means the rule may delete the only remaining copy of a file. Leave it on unless you mean exactly that.`}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Deletes the stored bytes on that backend only — copies elsewhere and the item itself are kept.`})]}),t.kind===`sendFile`&&(0,W.jsxs)(`div`,{className:`space-y-4`,children:[(0,W.jsx)(Q,{label:`Files to send`,children:(0,W.jsxs)(`select`,{className:X,value:t.sendSource,onChange:e=>r({sendSource:e.target.value}),children:[(0,W.jsx)(`option`,{value:`document`,children:`The file that triggered this rule`}),(0,W.jsx)(`option`,{value:`attachments`,children:`Matching attachments from the email`}),(0,W.jsx)(`option`,{value:`download`,children:`Files from an earlier Download action`})]})}),t.sendSource===`attachments`&&(0,W.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,W.jsx)(Q,{label:`Attachment types`,hint:`application/pdf for invoices; * for all files.`,children:(0,W.jsx)(T,{className:Z,value:t.attachmentMime,onChange:e=>r({attachmentMime:e.target.value})})}),(0,W.jsx)(Q,{label:`Attachment filename contains`,hint:`Optional literal filename fragment.`,children:(0,W.jsx)(T,{className:Z,placeholder:`invoice`,value:t.attachmentName,onChange:e=>r({attachmentName:e.target.value})})})]}),t.sendSource===`attachments`&&(0,W.jsx)($,{checked:t.includeInline,onChange:e=>r({includeInline:e}),label:`Include inline attachments`,hint:`Signature images are excluded by default.`}),(0,W.jsx)(Q,{label:`Sending account`,hint:`Enable sending for the account in Connected services.`,children:(0,W.jsxs)(`select`,{className:X,value:t.a?`${t.sendDriver}:${t.a}`:``,onChange:e=>{let t=he.find(t=>`${t.driver}:${t.address}`===e.target.value);t&&r({a:t.address,sendDriver:t.driver,b:``})},children:[(0,W.jsx)(`option`,{value:``,disabled:!0,children:`Choose email, WhatsApp or Slack…`}),t.a&&!he.some(e=>e.driver===t.sendDriver&&e.address===t.a)&&(0,W.jsxs)(`option`,{value:`${t.sendDriver}:${t.a}`,disabled:!0,children:[t.sendDriver,`: `,t.a,` (unavailable)`]}),he.map(e=>(0,W.jsxs)(`option`,{value:`${e.driver}:${e.address}`,disabled:!e.canSend,children:[e.driver===`imap`?`Email (SMTP)`:e.driver===`whatsapp`?`WhatsApp`:`Slack`,` · `,e.from||e.address,e.canSend?``:` — sending disabled`]},`${e.driver}:${e.address}`))]})}),_e&&(0,W.jsx)(`p`,{className:`text-xs text-destructive`,role:`status`,children:_e}),(0,W.jsx)(Q,{label:t.sendDriver===`imap`?`Destination email address`:`Destination conversation`,hint:t.sendDriver===`imap`?`The accounting ingestion address; separate multiple recipients with commas.`:t.sendDriver===`slack`?`A configured Slack channel ID or name. The account needs files:write permission.`:`A configured WhatsApp chat ID, e.g. 421…@s.whatsapp.net or …@g.us.`,children:(0,W.jsx)(T,{className:Z,value:t.b,placeholder:t.sendDriver===`imap`?`invoices@accounting-firm.example`:t.sendDriver===`slack`?`C0123456789`:`421…@s.whatsapp.net`,onChange:e=>r({b:e.target.value})})}),t.sendDriver===`imap`&&(0,W.jsx)(Q,{label:`Email subject`,hint:`{{file.name}} inserts the attachment filename.`,children:(0,W.jsx)(T,{className:Z,value:t.sendSubject,onChange:e=>r({sendSubject:e.target.value})})}),(0,W.jsx)(Q,{label:t.sendDriver===`imap`?`Email body (optional)`:`Message / caption (optional)`,hint:`Templates: {{file.name}}, {{doc.data.subject}}, {{doc.data.title}}.`,children:(0,W.jsx)(`textarea`,{className:`min-h-20 w-full rounded-md border bg-background p-3 text-sm`,value:t.sendMessage,onChange:e=>r({sendMessage:e.target.value})})}),(0,W.jsxs)(`div`,{className:`rounded-lg border bg-muted/30 p-3 text-sm`,"aria-label":`File delivery preview`,children:[t.sendSource===`attachments`?`Each matching email attachment`:t.sendSource===`download`?`Each downloaded file`:`The triggering file`,` → `,t.sendDriver===`imap`?`email attachment`:t.sendDriver===`slack`?`Slack file upload`:`WhatsApp document`,` → `,t.b||`choose a destination`]}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Sends each file in a separate message and keeps the original. Maximum 18 MB per file. Replaying this rule does not resend the same file version to the same destination. Unconfirmed deliveries are recorded for review, not retried automatically.`}),t.sendSource===`document`&&(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`For files created by another automation, enable this rule’s option to also run on automation events.`})]}),t.kind===`notify`&&(0,W.jsx)(Q,{label:`Notification`,hint:`Notifies you through your bound channel, or in Canvas. Templates: {{doc.data.subject}}, {{doc.data.from}}, {{doc.data.title}}…`,children:(0,W.jsx)(T,{className:Z,placeholder:`New mail from {{doc.data.from}}: {{doc.data.subject}}`,value:t.a,onChange:e=>r({a:e.target.value})})}),t.kind===`delete`&&(0,W.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Removes the item from the Canvas index. Files, blobs and mail on storage backends stay untouched.`}),t.kind===`destroy`&&(0,W.jsx)(`p`,{className:`rounded-lg border border-destructive/40 bg-destructive/5 p-3 text-sm text-destructive`,children:`⚠ Irreversible: deletes the stored bytes too (blobs, workspace files, mail on the server), then removes the item from the index.`}),t.kind===`agent`&&(0,W.jsxs)(`div`,{className:`space-y-3`,children:[(0,W.jsx)(Q,{label:`Agent`,hint:`The agent's slug.`,children:(0,W.jsx)(T,{className:C(Z,`font-mono sm:max-w-xs`),placeholder:`assistant`,value:t.a,onChange:e=>r({a:e.target.value})})}),(0,W.jsx)(Q,{label:`Prompt`,hint:`Templates use indexed fields: {{doc.id}}, {{doc.data.subject}}, {{doc.data.bodyPreview}} (emails), {{doc.data.url}}… Ask the agent to use canvas_get for full email content. Objects are inserted as JSON.`,children:(0,W.jsx)(`textarea`,{className:`min-h-28 w-full rounded-md border bg-background p-3 text-sm outline-none focus:ring-2 focus:ring-ring`,placeholder:`Read email #{{doc.id}} in full with canvas_get and summarize it in plain markdown.
|
|
4
|
-
|
|
5
|
-
Subject: {{doc.data.subject}}
|
|
6
|
-
Preview: {{doc.data.bodyPreview}}`,value:t.b,onChange:e=>r({b:e.target.value})})}),u(`reply`)]}),t.kind===`script`&&(0,W.jsxs)(`div`,{className:`space-y-3`,children:[(0,W.jsx)(Q,{label:`Script`,hint:`From the Scripts section of this workspace.`,children:pe.length?(0,W.jsxs)(`select`,{className:C(X,`font-mono sm:max-w-md`),value:t.a,onChange:e=>r({a:e.target.value}),children:[(0,W.jsx)(`option`,{value:``,children:`pick a script…`}),pe.map(e=>(0,W.jsx)(`option`,{value:`scripts/${e}`,children:e},e))]}):(0,W.jsx)(T,{className:C(Z,`font-mono sm:max-w-md`),placeholder:`scripts/my-script.sh`,value:t.a,onChange:e=>r({a:e.target.value})})}),u(`output`)]})]},n)}),(0,W.jsxs)(w,{size:`sm`,variant:`outline`,onClick:()=>L(`actions`,[...O.actions,K(`tag`)]),children:[(0,W.jsx)(u,{className:`mr-1 h-4 w-4`}),` Add another action`]})]}),(0,W.jsxs)(`section`,{className:`space-y-3`,children:[(0,W.jsx)(Ot,{step:3,title:`Options`}),(0,W.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,W.jsx)($,{checked:O.approval,onChange:e=>L(`approval`,e),label:`Ask me before running`,hint:`Actions are held in the Pending queue for review — approve (optionally amended) or decline — instead of running automatically.`}),(0,W.jsx)($,{checked:O.cascade,onChange:e=>L(`cascade`,e),label:`Also react to items created by automation`,hint:`Off by default so rules, hooks and agents cannot trigger each other in a loop. A server-side depth limit still stops runaway chains.`})]})]}),(0,W.jsxs)(`div`,{className:`flex flex-wrap gap-2 border-t pt-4`,children:[(0,W.jsxs)(w,{className:`h-10 px-5`,onClick:je,disabled:M||se,children:[M?(0,W.jsx)(ee,{className:`mr-1.5 h-4 w-4 animate-spin`}):(0,W.jsx)(i,{className:`mr-1.5 h-4 w-4`}),` `,O.id?`Save changes`:`Create rule`]}),(0,W.jsx)(w,{className:`h-10`,variant:`outline`,onClick:()=>{A(null),_?.()},children:`Cancel`})]})]}),R&&(0,W.jsx)(ue,{onClose:()=>z(null),children:(0,W.jsx)(ie,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,fixedWorkspaceName:e,multiple:R.target!==`storeFolder`&&!(R.target===`condition`&&O?.actions.some(e=>e.kind===`store`)),tabs:R.target===`condition`?[`context`,`directory`,`backends`]:R.target===`storeFolder`?[`backends`]:[`context`,`directory`],title:R.target===`condition`?`Choose source folder…`:R.target===`storeFolder`?`Store files under…`:`File into…`,confirmLabel:R.target===`storeFolder`?`Use folder`:`Use path`,onConfirm:Ue,onClose:()=>z(null)})}),!m&&(se?(0,W.jsx)(`p`,{className:`rounded-xl border p-6 text-center text-sm text-muted-foreground`,children:`Loading…`}):S.length===0?!fe&&!O&&(0,W.jsxs)(`div`,{className:`space-y-4`,children:[(0,W.jsxs)(`div`,{className:`rounded-xl border border-dashed p-6 text-center`,children:[(0,W.jsx)(`p`,{className:`text-base font-medium`,children:`No rules yet`}),(0,W.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:`Pick a starting point below, or right-click a folder in the tree and choose “Create rule…”.`})]}),Ze]}):(0,W.jsxs)(`div`,{className:`space-y-6`,children:[Je.length>0&&(0,W.jsxs)(`section`,{className:`space-y-3`,children:[(0,W.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1 text-sm text-muted-foreground`,children:[(0,W.jsxs)(`h3`,{className:`flex items-center gap-2 font-semibold uppercase tracking-wide`,children:[(0,W.jsx)(o,{className:`h-4 w-4 shrink-0`}),` Folder & storage rules`]}),(0,W.jsx)(`p`,{children:`Right-click a folder in the tree to add one`})]}),(0,W.jsx)(`div`,{className:`space-y-3`,children:Je.map(e=>(0,W.jsx)(Xe,{rule:e},e.id))})]}),U.length>0&&(0,W.jsxs)(`section`,{className:`space-y-3`,children:[Je.length>0&&(0,W.jsxs)(`h3`,{className:`flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-muted-foreground`,children:[(0,W.jsx)(x,{className:`h-4 w-4`}),` Other rules`]}),(0,W.jsx)(`div`,{className:`space-y-3`,children:U.map(e=>(0,W.jsx)(Xe,{rule:e},e.id))})]})]}))]})}function jt(e,t){let n=t.split(`/`).filter(Boolean);if(e!==`backends`||n[0]!==`Trash`)return null;try{return{backend:n[1]?decodeURIComponent(n[1]):null,prefix:n.slice(2).join(`/`)}}catch{return null}}function Mt(e,t=``){return`/Trash${e?`/${encodeURIComponent(e)}`:``}${t?`/${t}`:``}`}function Nt(e,t=``){let n=new Map,r=[],i=t?`${t}/`:``;for(let t of e){if(!t.key.startsWith(i))continue;let e=t.key.slice(i.length);if(!e)continue;let a=e.indexOf(`/`);if(a>=0){let r=e.slice(0,a),o=i+r,s=n.get(o)??{id:`folder:${o}`,name:r,key:o,directory:!0,navigable:!0,items:[]};s.items.push(t),n.set(o,s)}else r.push({id:t.id,name:e,key:t.key,directory:t.type===`directory`,navigable:!1,items:[t]})}return[...n.values(),...r].sort((e,t)=>Number(t.directory)-Number(e.directory)||e.name.localeCompare(t.name)||t.items[0].deletedAt-e.items[0].deletedAt||e.id.localeCompare(t.id))}var Pt=(e,t)=>`${ne.workspaces}/${encodeURIComponent(e)}/backends/file/${encodeURIComponent(t)}/trash`;async function Ft(e,t){let n=[],r=new Set,i=null,a=null;do{let o=new URLSearchParams({limit:`1000`,...i?{cursor:i}:{}}),s=await E.get(`${Pt(e,t)}?${o}`);if(n.push(...s.items),a=s.retention?.days??null,i=s.cursor,i&&r.has(i))throw Error(`Trash listing returned a repeated cursor`);i&&r.add(i)}while(i);return{items:n,days:a}}function It(e,t,n){return Rt(e,t,n,`restore`)}function Lt(e,t,n){return Rt(e,t,n,`discard`)}async function Rt(e,t,n,r){let i=[...new Set(n)],a=[];try{for(let n=0;n<i.length;n+=100){let o=await E.post(`${Pt(e,t)}/${r}`,{ids:i.slice(n,n+100)});a.push(...o.results)}return a}finally{ce(e,`backends`),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:`backends`}})),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e}})),window.dispatchEvent(new CustomEvent(`workspace:trash:refresh`,{detail:{workspaceName:e,backend:t}}))}}async function zt(e,t){let n=jt(`backends`,t);if(!n?.backend)return;let{items:r}=await Ft(e,n.backend),i=r.filter(e=>!n.prefix||e.key===n.prefix||e.key.startsWith(`${n.prefix}/`)).sort((e,t)=>t.deletedAt-e.deletedAt),a=await It(e,n.backend,i.map(e=>e.id)),o=a.filter(e=>!e.ok);if(o.length)throw Error(`${a.length-o.length} restored; ${o.length} remain in Trash. Existing paths were kept.`)}function Bt(e,t){if(!t.length)return!1;let n=[...new Set(t.map(e=>e.key))],r=n.slice(0,5).join(`
|
|
7
|
-
`)+(n.length>5?`\n…and ${n.length-5} more paths`:``);return window.confirm(`Permanently delete ${t.length} Trash item(s) from ${e}?\n\n${r}\n\nDeleted folders include all their contents. This cannot be undone. Files currently at the original paths are kept.`)}async function Vt(e,t){let n=jt(`backends`,t);if(!n?.backend)return;let{items:r}=await Ft(e,n.backend),i=r.filter(e=>!n.prefix||e.key===n.prefix||e.key.startsWith(`${n.prefix}/`));if(!Bt(n.backend,i))return;let a=await Lt(e,n.backend,i.map(e=>e.id)),o=a.filter(e=>!e.ok);if(o.length)throw Error(`${a.length-o.length} deleted; ${o.length} remain in Trash. ${o[0].message||o[0].reason||`Please retry.`}`)}var Ht=new Map;function Ut(e,t,n,r,i,a){let o=JSON.stringify([t,n,r,a]),s=Ht.get(o);if(s)return s;let c=(async()=>{let o=e({title:`Resyncing…`,description:r});try{for(a?await se(t,n,r,a):await O(t,n,r);;){let e=await ae(t,n,r);i?.(e);let s=a?e.containers?.find(e=>e.name===a):void 0;if(a?s?.status!==`syncing`:!e.resyncing&&e.status!==`syncing`){let i=s?s.lastError:e.lastError;if(i)throw Error(i);o.done({title:e.resyncCancelledAt?`Resync stopped`:`Resync complete`,description:`${r}${n!==`imap`&&e.progress?` · ${e.progress.scanned} files scanned`:``}`}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:t,treeName:`backends`}}));return}let c=n===`imap`?void 0:e.progress;o.update({title:`Resyncing…`,description:`${r}${c?` · ${c.scanned}${c.total==null?``:` / ${c.total}`} files scanned`:``}`}),await new Promise(e=>setTimeout(e,2e3))}}catch(e){throw o.fail({title:`Resync needs attention`,description:`${r}: ${e instanceof Error?e.message:String(e)}`,variant:`destructive`}),e}})();return Ht.set(o,c),c.finally(()=>{Ht.get(o)===c&&Ht.delete(o)}).catch(()=>{}),c}export{ke as A,R as B,Ce as C,j as D,Ne as E,fe as F,Pe as H,De as I,Ae as L,Fe as M,he as N,Be as O,me as P,z as R,Oe as S,Ve as T,_e as U,M as V,xe as W,qe as _,Ft as a,Ie as b,jt as c,At as d,Qe as f,Je as g,Ze as h,Vt as i,ve as j,Te as k,Mt as l,Ye as m,Bt as n,It as o,Xe as p,Lt as r,zt as s,Ut as t,Nt as u,I as v,N as w,Me as x,Ue as y,Se as z};
|