@augmentd-labs/canvas-web 2.26.40 → 2.26.41
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/{CalendarApplet-Co0RKLQE.js → CalendarApplet-Bno3IDzO.js} +1 -1
- package/dist/assets/{FiltersApplet-DMoH8Y2S.js → FiltersApplet-PclPc7fz.js} +1 -1
- package/dist/assets/{HomeFab-CpgkP2jx.js → HomeFab-B3f-hO-p.js} +1 -1
- package/dist/assets/{LensApplet-BRvNa6QA.js → LensApplet-BnW7b0KX.js} +1 -1
- package/dist/assets/{NotesApplet-BUlo1AeT.js → NotesApplet-FjdHMWCV.js} +1 -1
- package/dist/assets/{_agentId_-DpUGhD0N.js → _agentId_-CW33ane1.js} +0 -0
- package/dist/assets/{_contextId_-BYACtvKh.js → _contextId_-wbu8w6OE.js} +1 -1
- package/dist/assets/_workspaceName_-Ck6op9kd.js +1 -0
- package/dist/assets/{about-he3_XqHw.js → about-DRzhyy-e.js} +1 -1
- package/dist/assets/{add-CPWQz9ZK.js → add-BeESP_fg.js} +1 -1
- package/dist/assets/{agents-e-nclilT.js → agents-BYNJHrPc.js} +1 -1
- package/dist/assets/{appearance-De5ieWdQ.js → appearance-DiQhAis2.js} +1 -1
- package/dist/assets/{apps-o8pk-feK.js → apps-C2mb0HML.js} +1 -1
- package/dist/assets/backend-sync-progress-CFe6JPuR.js +6 -0
- package/dist/assets/{document-list-J63eer10.js → document-list-CUmMhD6M.js} +1 -1
- package/dist/assets/{home-Cgt-SPAO.js → home-BRx1tOR-.js} +1 -1
- package/dist/assets/{index-B01BkfMJ.js → index-I9cslsRe.js} +2 -2
- package/dist/assets/{key-bindings-DbpenCz7.js → key-bindings-CvzGVYrr.js} +1 -1
- package/dist/assets/{registry-CPdMkdKq.js → registry-NAExJwr9.js} +2 -2
- package/dist/assets/{settings-D1g-5DNT.js → settings-CjKOuPew.js} +1 -1
- package/dist/assets/{settings-DX6t8wLi.js → settings-DMM8k_4o.js} +1 -1
- package/dist/assets/{settings-3y1P0NnU.js → settings-DrQdeEUS.js} +1 -1
- package/dist/assets/{settings-B25sRmAM.js → settings-HBpYbGPW.js} +1 -1
- package/dist/assets/{share-target-DAjpH4Qw.js → share-target-q77WkQhO.js} +1 -1
- package/dist/assets/{shared-BiquP0Yf.js → shared-DsgNtRuD.js} +1 -1
- package/dist/assets/{tree-folders-BMqMmyq7.js → tree-folders-CNu09uPg.js} +1 -1
- package/dist/assets/{use-canvas-pins-BV8AsYCE.js → use-canvas-pins-Bhd7_wde.js} +1 -1
- package/dist/assets/{useAgentModels-KcfEQ6u9.js → useAgentModels-B48KqDI7.js} +1 -1
- package/dist/assets/{workspace-area-menu-Y2-IWSxU.js → workspace-area-menu-B-bXURzn.js} +1 -1
- package/dist/assets/{workspaces-CWqg_P7W.js → workspaces-y3zARr9A.js} +1 -1
- package/dist/index.html +6 -6
- package/dist/sw.js +1 -1
- package/package.json +2 -2
- package/dist/assets/_workspaceName_-V027dHb_.js +0 -1
- package/dist/assets/backend-sync-progress-DqI8zbnK.js +0 -6
|
@@ -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{Kn as o,L as s,Tt as c,Ur as l,Vr as u,X as d,ar as f,gr as p,kt as m,pn as h}from"./ui-CDoK3F3U.js";import{t as g}from"./utils-2pl1SbIp.js";import{t as ee}from"./button-SeUZ_Pvi.js";import{c as _,t as te}from"./api-CA6WiiYM.js";import{t as v}from"./socket-CtH3EU9m.js";import{n as ne}from"./use-toast-BlLDqSUO.js";import{h as y,o as re,s as b}from"./LinkToCard-CKVi4Nrg.js";import{At as x,D as S,G as ie,Gt as C,Kt as w,Lt as ae,W as oe,Y as se,_ as T,_n as ce,a as le,bn as E,gt as D,lt as O,mt as ue,nt as de,rn as fe,rt as pe,u as me,vt as he,w as ge,x as _e,y as ve,zt as ye}from"./workspace-C5V-ZCOE.js";import{n as be,r as xe}from"./use-canvas-pins-BV8AsYCE.js";import{u as Se}from"./ObjectPropertiesCard-D2lrTQqT.js";import{a as Ce,c as k,d as we,f as A,i as Te,l as Ee,o as De,p as Oe,r as ke,w as Ae}from"./document-list-J63eer10.js";import{n as je}from"./use-toolbox-Ck_cLGgf.js";import{i as Me}from"./color-DFEH4BfK.js";import{t as Ne}from"./geo-CZfs0E-x.js";import{a as Pe,i as Fe,n as Ie,o as Le}from"./workspace-BydSRtST.js";import{n as Re,r as ze,t as Be}from"./url-params-n7kU_WZ-.js";import{i as Ve}from"./use-menu-DIP1zh7I.js";import{n as He}from"./last-path-BbXWC3b3.js";import{t as Ue}from"./workspace-area-menu-Y2-IWSxU.js";import{t as We}from"./workspace-content-gate-C54J9Man.js";import{t as Ge}from"./form-panel-3p-ncEVK.js";import{a as Ke,c as qe,i as Je,l as Ye,n as Xe,o as Ze,r as Qe,s as $e,t as et,u as tt}from"./tree-folders-BMqMmyq7.js";import{i as nt,r as rt}from"./query-debug-lD5vbJGi.js";var j=`session.open`,it=`session.set`,at=`session.ids`,ot=`session.materialize`,st=`session.close`,ct=`session.delta`,M=e(n(),1),N=t();function lt(e){let t=we(`backends`,e.path)?.backend;return(0,N.jsx)(ut,{...e},JSON.stringify([e.workspace,t]))}function ut({workspace:e,path:t,onNavigate:n}){let r=we(`backends`,t),i=r.backend,a=r.prefix,[s,l]=(0,M.useState)(null),[u,h]=(0,M.useState)(null),g=(0,M.useRef)(!1),[ee,_]=(0,M.useState)(null),[te,v]=(0,M.useState)(null),[ne,x]=(0,M.useState)(0),[S,ie]=(0,M.useState)(new Set),[C,w]=(0,M.useState)(null),ae=(0,M.useCallback)(()=>x(e=>e+1),[]),[oe,se]=(0,M.useState)(t);oe!==t&&(se(t),ie(new Set),w(null),v(null),_(null));let T=s?.revision!==ne,ce=T?[]:s.items,le=T?[]:s.backends,E=s?.days;(0,M.useEffect)(()=>{let t=!1;return(i?k(e,i).then(e=>({...e,backends:[]})):he(e).then(e=>({items:[],days:null,backends:e.filter(e=>e.driver===`file`&&e.enabled!==!1)}))).then(e=>{t||l({...e,revision:ne,error:null})}).catch(e=>{t||l({revision:ne,items:[],backends:[],days:null,error:e instanceof Error?e.message:String(e)})}),()=>{t=!0}},[e,i,ne]),(0,M.useEffect)(()=>{let t=null,n=n=>{let r=n.detail;r?.workspaceName&&r.workspaceName!==e||r?.treeName&&r.treeName!==`backends`||(t||=setTimeout(()=>{t=null,ae()},500))};return window.addEventListener(`workspace:trash:refresh`,n),window.addEventListener(`workspace:tree:refresh`,n),()=>{window.removeEventListener(`workspace:trash:refresh`,n),window.removeEventListener(`workspace:tree:refresh`,n),t&&clearTimeout(t)}},[e,ae]);let D=Oe(ce,a),O=async(t,n)=>{if(!(!i||g.current||T||!n.length)&&!(t===`discard`&&!Ce(i,n))){g.current=!0,h(t),_(null),v(null),w(null);try{let r=await(t===`restore`?Ee:De)(e,i,[...n].sort((e,t)=>t.deletedAt-e.deletedAt).map(e=>e.id)),a=r.filter(e=>!e.ok);v(`${r.length-a.length} item(s) ${t===`restore`?`restored to their original paths`:`permanently deleted`}.`),a.length&&_(`${a.length} item(s) remain in Trash. ${a.slice(0,3).map(e=>`${e.key||`Item`}: ${e.reason===`precondition-failed`||e.reason===`target-exists`?`original path is occupied`:e.message||e.reason}`).join(`; `)}`),ie(new Set)}catch(e){_(e instanceof Error?e.message:String(e))}finally{g.current=!1,h(null),ae()}}},ue=(e,t,n)=>w({x:e,y:t,row:n});return(0,N.jsxs)(`section`,{className:`flex h-full min-h-0 flex-col bg-background`,"aria-label":`Backend Trash`,children:[(0,N.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2 border-b px-4 py-3`,children:[(0,N.jsx)(d,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,N.jsx)(b,{items:re(t,e).map((e,t)=>t===2&&i?{...e,label:i}:e),onNavigate:n,className:`basis-48`}),(0,N.jsxs)(`div`,{className:`ml-auto flex max-w-full flex-wrap items-center gap-2`,children:[S.size>0&&(0,N.jsxs)(N.Fragment,{children:[(0,N.jsxs)(`button`,{className:`flex items-center gap-1 rounded border px-2 py-1 text-sm disabled:opacity-50`,disabled:!!u||T,onClick:()=>void O(`restore`,D.filter(e=>S.has(e.id)).flatMap(e=>e.items)),children:[(0,N.jsx)(c,{className:`h-3.5 w-3.5`}),`Restore selected`]}),(0,N.jsxs)(`button`,{className:`flex items-center gap-1 rounded border px-2 py-1 text-sm text-destructive disabled:opacity-50`,disabled:!!u||T,onClick:()=>void O(`discard`,D.filter(e=>S.has(e.id)).flatMap(e=>e.items)),children:[(0,N.jsx)(d,{className:`h-3.5 w-3.5`}),`Delete selected`]})]}),i&&D.length>0&&(0,N.jsxs)(`button`,{className:`flex items-center gap-1 rounded border px-2 py-1 text-sm text-destructive disabled:opacity-50`,disabled:!!u||T,onClick:()=>void O(`discard`,D.flatMap(e=>e.items)),children:[(0,N.jsx)(d,{className:`h-3.5 w-3.5`}),a?`Empty this folder`:`Empty Trash`]}),(0,N.jsx)(`button`,{title:`Refresh Trash`,"aria-label":`Refresh Trash`,className:`rounded p-2 hover:bg-accent`,disabled:!!u||T,onClick:ae,children:(0,N.jsx)(m,{className:`h-4 w-4 ${T?`animate-spin`:``}`})})]})]}),(0,N.jsxs)(`div`,{className:`border-b px-4 py-2 text-xs text-muted-foreground`,children:[`Restore files and folders to their original paths. Existing files are kept.`,E?` Deleted items are kept for ${E} days.`:``]}),te&&(0,N.jsx)(`p`,{role:`status`,className:`px-4 py-2 text-sm`,children:te}),(ee||s?.error)&&(0,N.jsx)(`p`,{role:`alert`,className:`px-4 py-2 text-sm text-destructive`,children:ee||s?.error}),u&&(0,N.jsx)(`p`,{role:`status`,className:`px-4 py-2 text-sm`,children:u===`restore`?`Restoring…`:`Deleting permanently…`}),(0,N.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto p-3`,children:T?(0,N.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`Loading Trash…`}):i?D.length===0?(0,N.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`This Trash folder is empty.`}):(0,N.jsxs)(`table`,{className:`w-full text-left text-sm`,children:[(0,N.jsx)(`thead`,{className:`border-b text-xs text-muted-foreground`,children:(0,N.jsxs)(`tr`,{children:[(0,N.jsx)(`th`,{className:`w-8 p-2`,children:(0,N.jsx)(`input`,{type:`checkbox`,"aria-label":`Select all visible items`,checked:D.length>0&&D.every(e=>S.has(e.id)),onChange:e=>ie(e.target.checked?new Set(D.map(e=>e.id)):new Set)})}),(0,N.jsx)(`th`,{className:`p-2`,children:`Name`}),(0,N.jsx)(`th`,{className:`p-2 max-sm:hidden`,children:`Original path`}),(0,N.jsx)(`th`,{className:`p-2 max-md:hidden`,children:`Deleted`}),(0,N.jsx)(`th`,{className:`p-2`,children:(0,N.jsx)(`span`,{className:`sr-only`,children:`Actions`})})]})}),(0,N.jsx)(`tbody`,{children:D.map(e=>(0,N.jsxs)(`tr`,{className:`border-b border-border/50 hover:bg-accent/50`,onContextMenu:t=>{t.preventDefault(),ue(t.clientX,t.clientY,e)},onDoubleClick:()=>e.navigable&&n(A(i,e.key)),children:[(0,N.jsx)(`td`,{className:`p-2`,children:(0,N.jsx)(`input`,{type:`checkbox`,"aria-label":`Select ${e.name}`,checked:S.has(e.id),disabled:!!u,onChange:t=>ie(n=>{let r=new Set(n);return t.target.checked?r.add(e.id):r.delete(e.id),r})})}),(0,N.jsx)(`td`,{className:`p-2`,children:(0,N.jsxs)(`button`,{className:`flex items-center gap-2 text-left`,onClick:()=>e.navigable&&n(A(i,e.key)),children:[e.directory?(0,N.jsx)(o,{className:`h-4 w-4 shrink-0`}):(0,N.jsx)(f,{className:`h-4 w-4 shrink-0`}),(0,N.jsxs)(`span`,{children:[e.name,e.navigable&&(0,N.jsxs)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:[e.items.length,` items`]})]})]})}),(0,N.jsx)(`td`,{className:`p-2 text-xs text-muted-foreground max-sm:hidden`,children:e.key}),(0,N.jsx)(`td`,{className:`p-2 text-xs text-muted-foreground max-md:hidden`,children:new Date(e.items.reduce((e,t)=>Math.max(e,t.deletedAt),0)).toLocaleString()}),(0,N.jsx)(`td`,{className:`p-2 text-right`,children:(0,N.jsx)(`button`,{title:`Actions for ${e.name}`,"aria-label":`Actions for ${e.name}`,disabled:!!u,className:`rounded p-2 hover:bg-accent`,onClick:t=>ue(t.clientX,t.clientY,e),children:(0,N.jsx)(p,{className:`h-4 w-4`})})})]},e.id))})]}):(0,N.jsxs)(`div`,{className:`grid gap-2 sm:grid-cols-2 lg:grid-cols-3`,children:[le.map(e=>(0,N.jsxs)(`button`,{onClick:()=>n(A(e.address)),className:`flex items-center gap-3 rounded-lg border p-4 text-left hover:bg-accent`,children:[(0,N.jsx)(d,{className:`h-6 w-6 text-muted-foreground`}),(0,N.jsxs)(`span`,{children:[(0,N.jsx)(`span`,{className:`block text-sm font-medium`,children:e.label||e.address}),(0,N.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.address})]})]},e.address)),!le.length&&(0,N.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`No file backends are available.`})]})}),C&&(0,N.jsxs)(y,{x:C.x,y:C.y,onClose:()=>w(null),className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[C.row.navigable&&(0,N.jsxs)(`button`,{className:`flex w-full items-center gap-2 rounded px-3 py-2 text-sm hover:bg-accent`,onClick:()=>{n(A(i,C.row.key)),w(null)},children:[(0,N.jsx)(o,{className:`h-4 w-4`}),`Open folder`]}),(0,N.jsxs)(`button`,{disabled:!!u,className:`flex w-full items-center gap-2 rounded px-3 py-2 text-sm hover:bg-accent disabled:opacity-50`,onClick:()=>void O(`restore`,C.row.items),children:[(0,N.jsx)(c,{className:`h-4 w-4`}),`Restore `,C.row.directory?`folder`:`file`]}),(0,N.jsxs)(`button`,{disabled:!!u||T,className:`flex w-full items-center gap-2 rounded px-3 py-2 text-sm text-destructive hover:bg-destructive/10 disabled:opacity-50`,onClick:()=>void O(`discard`,C.row.items),children:[(0,N.jsx)(d,{className:`h-4 w-4`}),`Delete permanently`]})]})]})}function dt({workspaceId:e,workspaceName:t}){let[n,r]=(0,M.useState)([]),[i,a]=(0,M.useState)(new Set),o=t=>`${e}:${t.address}:${t.resyncStartedAt||``}`;(0,M.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 he(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=v.on(`connect`,l);return v.on(`backend.resync.changed`,u),v.on(`backend.changed`,d),window.addEventListener(`focus`,l),()=>{t=!0,f?.(),v.off(`backend.resync.changed`,u),v.off(`backend.changed`,d),window.removeEventListener(`focus`,l)}},[e]);let c=n.filter(e=>!i.has(o(e)));return c.length?(0,N.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,N.jsxs)(`div`,{role:`status`,className:`mb-2 flex items-center gap-2 text-sm font-medium`,children:[(0,N.jsx)(h,{"aria-hidden":`true`,className:`h-4 w-4 animate-spin`}),(0,N.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,N.jsx)(`span`,{className:`block`,children:`Scanning storage`}),(0,N.jsx)(`span`,{className:`block truncate text-xs font-normal text-muted-foreground`,title:t,children:t})]}),(0,N.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,...c.map(o)])),children:(0,N.jsx)(s,{"aria-hidden":`true`,className:`h-4 w-4`})})]}),(0,N.jsx)(`div`,{className:`max-h-48 space-y-3 overflow-y-auto`,children:c.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,N.jsxs)(`div`,{children:[(0,N.jsxs)(`div`,{className:`flex items-center justify-between gap-3 text-xs`,children:[(0,N.jsx)(`span`,{className:`truncate`,children:i}),(0,N.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,children:n===null?`${t} files`:`${t} / ${n}`})]}),(0,N.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,N.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 ft=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:null;function pt(e){return`/${e}`.replace(/\/+/g,`/`).replace(/\/$/,``)||`/`}function mt(e,t,n){if(e==null)return[];if(Array.isArray(e))return e.flatMap(e=>mt(e,t,n));if(typeof e==`string`)return[{tree:null,kind:t,path:pt(e)}];let r=ft(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:pt(e)}))}function ht(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 gt(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 _t(e,t,n=new Map){let r=ft(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:pt(n)}],ids:ht(r),unknown:!1}:{targets:[],ids:[],unknown:!0}}let i=[...mt(r.context,`context`,n),...mt(r.directory,`directory`,n)],a=ft(r.changed);a&&i.push(...mt(a.context,`context`,n),...mt(a.directory,`directory`,n));let o=ht(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 vt(e,t){return e===t||e===`/`||t===`/`||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}function yt(e,t){if(e.kind&&e.kind!==t.kind||e.tree&&e.tree!==t.tree)return!1;if(t.kind===`context`){let n=e=>pt(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 vt(e.path,t.path)}function bt(e){return _t(`tree.refresh`,{treeName:e?.treeName,path:e?.path||`/`})}function xt(e,t,n){if(e.unknown||e.targets.length&&(t.wholeWorkspace||e.targets.some(e=>yt(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 v.request(j,{workspace:e,specs:t,opts:n})}function Ct(e,t,n){return v.request(it,{sessionId:e,label:t,spec:n})}function wt(e){return v.request(at,{sessionId:e})}function P(e,t={}){return v.request(ot,{sessionId:e,...t})}function Tt(e){return v.request(st,{sessionId:e})}function F(e){return v.on(ct,e)}var I=100;function Et({workspaceRef:e,specs:t,opts:n,enabled:r=!0}){let[i,a]=(0,M.useState)([]),[o,s]=(0,M.useState)(0),[c,l]=(0,M.useState)(null),[u,d]=(0,M.useState)(null),f=(0,M.useRef)([]),p=(0,M.useRef)(new Map),m=(0,M.useRef)(null),h=(0,M.useRef)(null),g=(0,M.useRef)(null),ee=(0,M.useRef)({}),_=(0,M.useRef)(null),te=(0,M.useMemo)(()=>JSON.stringify(t),[t]),ne=(0,M.useMemo)(()=>JSON.stringify(n??{}),[n]),y=(0,M.useCallback)(()=>{let e=p.current;a(f.current.map(t=>e.get(t)).filter(Boolean))},[]),re=(0,M.useCallback)(async e=>{let t=h.current;if(!t||e.length===0)return[];let n=[];for(let r=0;r<e.length;r+=I){let i=e.slice(r,r+I),a=await de(t,`/`,[],{ids:i,scope:`workspace`,limit:i.length});n.push(...a.payload||[])}return n},[]),b=(0,M.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),y(),r.length===0)return;let a=await re(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))}y()},[re,y]),x=(0,M.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 b(a,[],t)},[b]);(0,M.useEffect)(()=>{if(h.current=e??null,!r||!e)return;let t=!1,n=null,i=async()=>{try{let r=await St(e,JSON.parse(te),JSON.parse(ne));if(t){Tt(r.sessionId).catch(()=>{});return}n=r.sessionId,m.current=r.sessionId,l(r.sessionId),d(null),f.current=[],p.current=new Map,await x(r.ids,r.count)}catch(e){if(t)return;d(e instanceof Error?e.message:`Failed to open query session`),l(null),m.current=null}};i();let o=v.on(`connect`,()=>{i()});return()=>{t=!0,o?.();let e=n??m.current;e&&Tt(e).catch(()=>{}),m.current=null,f.current=[],p.current=new Map,l(null),a([]),s(0)}},[e,te,ne,r]),(0,M.useEffect)(()=>{if(!c)return;let e=F(e=>{if(e.sessionId===c){if(g.current!==null){_.current?.(g.current,ee.current);return}e.ids===void 0?b(e.added??[],e.removed??[],e.count):x(e.ids,e.count)}});return()=>{e?.()}},[c,b,x]);let S=(0,M.useCallback)(async()=>{let e=m.current;if(e)try{let t=await wt(e);await x(t.ids,t.count)}catch{}},[x]),ie=(0,M.useCallback)(async(e,t)=>{let n=m.current;if(!n)throw Error(`No open query session`);let r=await Ct(n,e,t);if(g.current!==null){await _.current?.(g.current,ee.current);return}await x(r.ids,r.count)},[x]),C=(0,M.useCallback)(async(e,t={})=>{let n=m.current;if(!n)throw Error(`No open query session`);if(g.current=e,ee.current=t,e===null){await S();return}let r=await P(n,{match:e,...t});for(let e of r.documents)p.current.set(e.id,e);f.current=r.ids,s(r.totalCount),y()},[y,S]);(0,M.useEffect)(()=>{_.current=C},[C]);let w=(0,M.useCallback)(async(e,t,n={})=>{let r=m.current;if(!r)throw Error(`No open query session`);let i=await P(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 x(a.ids,a.count),i.ids},[x]);return{documents:i,count:o,ready:c!==null,error:u,setCue:ie,resync:S,rank:C,rankAndPin:w}}function Dt({data:e,className:t}){let[n,r]=(0,M.useState)(!0),{rows:i,gapIndex:a,span:o}=(0,M.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,N.jsxs)(`div`,{className:g(`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 s=a>0?i[a].distance:null;return(0,N.jsxs)(`div`,{className:g(`rounded-md border border-border bg-muted/30 text-xs`,t),children:[(0,N.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,N.jsx)(l,{className:`h-3.5 w-3.5`}):(0,N.jsx)(u,{className:`h-3.5 w-3.5`}),`Query debug`,(0,N.jsxs)(`span`,{className:`font-normal text-muted-foreground`,children:[`: image distances for “`,e.query,`” (`,i.length,` nearest, unfloored)`]})]}),n&&(0,N.jsxs)(`div`,{className:`space-y-2 border-t border-border px-3 py-2`,children:[(0,N.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.`,s===null?(0,N.jsxs)(N.Fragment,{children:[` `,(0,N.jsx)(`span`,{className:`text-amber-600 dark:text-amber-500`,children:`No boundary in this window`}),`; the distances step evenly (typical Δ`,o.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,N.jsxs)(N.Fragment,{children:[` A jump at `,(0,N.jsx)(`span`,{className:`font-mono`,children:s.toFixed(4)}),` (Δ`,o.biggest.toFixed(4),`, vs typical Δ`,o.median.toFixed(4),`) stands out (a likely boundary).`]})]}),(0,N.jsx)(`div`,{className:`max-h-56 overflow-y-auto`,children:(0,N.jsx)(`table`,{className:`w-full font-mono text-[11px]`,children:(0,N.jsx)(`tbody`,{children:i.map((e,t)=>(0,N.jsxs)(`tr`,{className:g(`border-b border-border/40 last:border-0`,t===a&&`border-t-2 border-t-amber-500/70`),children:[(0,N.jsx)(`td`,{className:`py-0.5 pr-3 text-muted-foreground`,children:t+1}),(0,N.jsxs)(`td`,{className:`py-0.5 pr-3`,children:[`#`,e.id]}),(0,N.jsx)(`td`,{className:`py-0.5 tabular-nums`,children:e.distance.toFixed(4)}),t===a&&(0,N.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,N.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Range `,o.first.toFixed(4),` – `,o.last.toFixed(4),` (spread `,(o.last-o.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.`]})]})]})}var Ot=new Map;function L(e,t,n){return`${e}\0${t}\0${n}`}function kt(e,t,n,r,i,a,o=``,s=``,c=`path`){return`${L(e,t,n)}\0${r}\0${i}\0${a}\0${o}\0${s}\0${c}`}function R(e,t,n){let r=L(e,t,n);for(let e of Ot.keys())e.startsWith(r)&&Ot.delete(e)}function At(e,t){let n=`${e}\0`;for(let[e,r]of Ot){if(!e.startsWith(n))continue;let[,i,a,,,,,,o=`path`]=e.split(`\0`);xt(t,{tree:i,kind:E(i),path:a,wholeWorkspace:o.startsWith(`workspace`)},r.documents.map(e=>Number(e.id)))&&Ot.delete(e)}}function jt(e,t){At(t?.workspaceName??e,bt(t))}function Mt(){let{workspaceName:e}=r();return e?(0,N.jsx)(We,{workspaceName:e,children:(0,N.jsx)(z,{})}):null}function z(){let{workspaceName:e,treeName:t}=r(),n=a(),o=i(),{showToast:s,showProgress:c}=ne(),l=new URLSearchParams(n.search),u=(()=>{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]:[]})(),[d,f]=(0,M.useState)(null),[p,m]=(0,M.useState)(!0),[h,y]=(0,M.useState)([]),[re,b]=(0,M.useState)(!1),[Ce,k]=(0,M.useState)(0),A=rt(),[Ee,De]=(0,M.useState)(null),[Oe,We]=(0,M.useState)(A);Oe!==A&&(We(A),A||De(null));let[j,it]=(0,M.useState)(`path`),[at,ot]=(0,M.useState)(!1),[st,ct]=(0,M.useState)(null),[ut,ft]=(0,M.useState)(null),[pt,mt]=(0,M.useState)(``),[ht,vt]=(0,M.useState)(!1),[yt,St]=(0,M.useState)(!1),[Ct,wt]=(0,M.useState)(!1),[P,Tt]=(0,M.useState)(null),[F,I]=(0,M.useState)(1),[L,Mt]=(0,M.useState)(50),[z,Nt]=(0,M.useState)(u),[Ft,It]=(0,M.useState)(null),{state:B,saveFilters:Lt,setSort:Rt,setAccentColor:zt,setMapDocuments:Bt}=je(),Vt=B.filters.features.allOf,Ht=B.filters.features.anyOf,Ut=B.filters.features.noneOf,Wt=Fe(B.filters.timeline),Gt=Pe(B.filters.geo),Kt=Le(B.filters.lens,B.filters.geo.includeUnlocated),V=B.filters.lens.ids,qt=[...Wt,...Gt,...Kt],Jt=B.filters.sort??Ie,Yt=JSON.stringify({a:Vt,b:Ht,c:Ut,d:qt,i:V,s:Jt}),Xt=JSON.stringify({a:Vt,b:Ht,c:Ut,d:qt,s:Jt}),H=Re(n.pathname).path,U=t??`context`,W=U===`backends`,[Zt,Qt]=(0,M.useState)([]);(0,M.useEffect)(()=>{!W||!e||he(e).then(Qt).catch(()=>Qt([]))},[W,e]);let $t=W?le(H,Zt):null,[en,tn]=(0,M.useState)(!1),nn=`${U}\0${H}`,[rn,an]=(0,M.useState)(nn);rn!==nn&&(an(nn),tn(!1));let G=l.get(`layer`)===`1`,K=l.get(`layerId`)||null,[q,on]=(0,M.useState)(null),[J,sn]=(0,M.useState)(null),cn=(0,M.useRef)(null);(0,M.useEffect)(()=>{cn.current=J},[J]);let[ln,un]=(0,M.useState)(`left`),[dn,fn]=(0,M.useState)([]),{openM1Drawer:pn,openM2Drawer:mn,goBack:hn}=Ve(),[gn,_n]=(0,M.useState)([]),Y=(0,M.useMemo)(()=>{if(!q||H===`/`||G)return null;let e=H.split(`/`).filter(Boolean),t=q;for(let n of e)if(t=t?.children?.find(e=>e.name===n)??null,!t)return null;return t},[q,H,G]),X=Y?.type===`canvas`?`canvas`:null,vn=(0,M.useRef)(null);(0,M.useEffect)(()=>{!e||!q||G||vn.current===`${e}/${U}`&&(H!==`/`&&!Y||He(e,U,H))},[e,q,G,H,Y,U]);let yn=(0,M.useMemo)(()=>G||j===`workspace`||z.length>0?[]:et(q,H),[q,H,G,j,z]),bn=G?null:H===`/`?q:Y,Z=Ae(),xn=`${U}\0${H}`,[Sn,Cn]=(0,M.useState)(null),wn=Sn?.key===xn?Sn.views:$e(bn?.metadata),Tn=Z?.pinned&&Z.view?[Z.view,...wn.filter(e=>e.id!==Z.view.id)]:wn,En=Z?.pinned&&Z.view?Z.view.id:Sn?.key===xn?Sn.activeId:Tn[0]?.id??Ke.id,Q=Tn.find(e=>e.id===En)??Tn[0]??Ke;(0,M.useEffect)(()=>{Z?.selectView(Q)},[Q,Z]);let Dn=W?void 0:Z?.schema??Ze(Q),On=Dn?[...Vt,Dn]:Vt;tt(Ye({workspace:e??null,treeNameOrId:U,treeType:E(U),path:H,scope:j===`workspace`?`workspace`:G?`layer`:`path`,layerId:G?K:void 0,unfiledOnly:en},{...B.filters,features:{...B.filters.features,allOf:On}},B.geoSelection,z));let kn=e=>{let t=Tn.find(t=>t.id===e);t&&Z?.selectView(t),I(1),fn([]),Cn({key:xn,views:Tn,activeId:e})},An=(t,n)=>{n&&n!==En&&(I(1),fn([]));let r=t.find(e=>e.id===(n??En));r&&Z?.selectView(r),Cn({key:xn,views:t,activeId:n??En}),ce(e,H,{metadata:{...bn?.metadata??{},views:t}},U).catch(()=>{s({title:`View not saved`,description:`Could not persist views to the layer`,variant:`destructive`})})},jn=X===`canvas`&&typeof Y?.querySpec?.query==`string`?Y.querySpec.query:``,Mn=X===`canvas`?{label:Y?.label,description:Y?.description,color:Y?.color}:null,{isPinned:Nn,pin:Pn,unpin:Fn,pins:In}=be(),Ln=d?.name,$=(0,M.useMemo)(()=>Ln&&X===`canvas`&&!G?{workspaceName:Ln,treeName:U,path:H}:null,[Ln,X,G,U,H]),Rn=$?Nn($):!1,zn=Y?.id,Bn=Y?.label,Vn=(0,M.useCallback)(async()=>{if($)try{let e=In.find(e=>e.workspaceName===$.workspaceName&&e.treeName===$.treeName&&e.path===$.path);e?await Fn(e.id):await Pn({...$,layerId:zn,label:Bn})}catch(e){console.error(`Failed to update home pins:`,e)}},[$,In,Pn,Fn,zn,Bn]),Hn=e?`${e}://${H===`/`?``:H.replace(/^\//,``)}`:``,Un=Me(d?.color)||null;(0,M.useEffect)(()=>(zt(Un),()=>zt(null)),[Un,zt]);let Wn=(0,M.useCallback)(async t=>{let n=V;if(t?.anyOf?.length&&Ht.length&&(n=((await ie(e,H,U,{limit:0,anyOf:Ht,ids:V,applyCanvasSpec:!1})).payload||[]).map(e=>e.id),!n.length))return{payload:[],count:0,totalCount:0};let r=await ie(e,H,U,{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:Ht,noneOf:Ut,filters:qt,ids:n,queries:[...z,...t?.queries??[],...t?.q?[t.q]:[]],applyCanvasSpec:!1});return{payload:r.payload||[],count:r.count??void 0,totalCount:r.totalCount??void 0}},[e,H,U,Yt,z]);(0,M.useEffect)(()=>{e&&(async()=>{m(!0);try{let t=await te.get(`${_.workspaces}/${e}`),n;n=t&&`workspace`in t?t.workspace:t,f(n)}catch(t){let n=t instanceof Error?t.message:`Failed to fetch workspace ${e}`;s({title:`Error`,description:n,variant:`destructive`}),f(null)}finally{m(!1)}})()},[e,s]),(0,M.useEffect)(()=>{let e=e=>{let t=e.detail?.workspace;t&&f(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 Gn=(V?.length??0)>0&&!G&&!(en&&$t)&&z.length<=1,{documents:Kn,count:qn,ready:Jn,setCue:Yn,resync:Xn,rank:Zn}=Et({workspaceRef:e,specs:(0,M.useMemo)(()=>{let e={features:{allOf:On,anyOf:Ht,noneOf:Ut},filters:qt};return j!==`workspace`&&(E(U)===`directory`?e.directory={tree:U,path:H}:e.context=H),[{label:`scope`,spec:e}]},[Xt,H,U,j,Dn]),opts:(0,M.useMemo)(()=>({mode:`live`,debounceMs:150}),[]),enabled:Gn}),Qn=Gn&&Jn,$n=(0,M.useRef)(!1);(0,M.useEffect)(()=>{$n.current=Qn},[Qn]);let er=z.length===1?z[0].trim():``;(0,M.useEffect)(()=>{Jn&&Zn(er?{text:er}:null,{limit:L,offset:(F-1)*L}).catch(()=>{})},[Jn,er,L,F,Zn]);let tr=(V??[]).join(`,`);(0,M.useEffect)(()=>{Jn&&Yn(`lens`,{ids:V??[]}).catch(()=>{})},[Jn,tr,Yn,V]);let nr=Qn?Kn:h,rr=Qn?qn:Ce,ir=(0,M.useRef)(new Set);(0,M.useEffect)(()=>{ir.current=new Set(nr.map(e=>Number(e.id)))},[nr]);let ar=B.geoSelection;(0,M.useEffect)(()=>{Bt(nr,d?.name??null)},[nr,d?.name,Bt]),(0,M.useEffect)(()=>()=>Bt([]),[Bt]);let or=(0,M.useMemo)(()=>ar?nr.filter(e=>Ne(e,ar,B.filters.geo.includeUnlocated)):nr,[nr,ar,B.filters.geo.includeUnlocated]),sr=me(H,On,{treeName:U,treeType:E(U),scope:j,queries:z,anyOf:Ht,noneOf:Ut,filters:qt,ids:V,layerId:G&&K?K:void 0}),cr=JSON.stringify([e,sr]),[lr,ur]=(0,M.useState)(``),[dr,fr]=(0,M.useState)(!1),pr=(0,M.useRef)(!1),mr=re||dr||lr!==cr||Qn||!!ar,hr=(0,M.useRef)(0),gr=(0,M.useRef)(null);(0,M.useEffect)(()=>()=>{hr.current++,gr.current=null},[]);let _r=(0,M.useRef)(``),vr=(0,M.useCallback)(async t=>{if(!e)return;if(we(U,H)){hr.current++,gr.current=null,_r.current=``,y([]),k(0),b(!1);return}if($n.current)return;let n=`${en&&$t?`${j}:unfiled`:j}:${Dn??``}`,r=(V?.length??0)>0,i=kt(e,U,H,F,L,z.join(`␟`),Xt,G&&K?K:``,n),a=r&&i===_r.current;_r.current=i;let o=kt(e,U,H,F,L,z.join(`␟`),Yt,G&&K?K:``,n),c=`${o}\0${A}`;if(t?.silent&&gr.current?.key===c){gr.current.refreshPending=!0;return}let l=++hr.current,u=t?.silent||r||A?void 0:Ot.get(o);u&&(y(u.documents),k(u.totalCount),ur(cr),b(!1)),(t?.silent??(a||!!u))||b(!0);let d={key:c,refreshPending:!1};gr.current=d;try{let t;if(en&&$t)t=await D(e,$t.driver,$t.address,{linked:!1,limit:L,offset:(F-1)*L});else if(G&&K&&j!==`workspace`)t=await pe(e,U,K,{limit:L,page:F,queries:z,allOf:On,anyOf:Ht,noneOf:Ut,filters:qt,ids:V,sortBy:Jt.sortBy||void 0,order:Jt.order});else{let n=E(U);t=await de(e,H,On,{limit:L,page:F,treeName:U,treeType:n,queries:z,anyOf:Ht,noneOf:Ut,filters:qt,ids:V,sortBy:Jt.sortBy||void 0,order:Jt.order,scope:j,debug:A&&z.length>0,debugLimit:200})}let n=t.payload||[],i=t.totalCount||t.count||0;if(!r&&!d.refreshPending&&Ot.set(o,{documents:n,totalCount:i}),l!==hr.current)return;let s=t.debug,c=s?.imageDistances??s?.distances??null;De(c?{query:z[z.length-1]??``,distances:c}:null),y(a?e=>e.length===n.length&&e.every((e,t)=>e.id===n[t].id)?e:n:n),k(i),ur(cr)}catch(e){if(l!==hr.current)return;let t=e instanceof Error?e.message:`Failed to fetch documents`;s({title:`Error`,description:t,variant:`destructive`}),y([]),k(0)}finally{gr.current===d&&(gr.current=null),l===hr.current&&b(!1),l===hr.current&&d.refreshPending&&vr({silent:!0})}},[e,H,U,K,G,F,L,d?.status,z,Yt,j,en,A,Dn]);(0,M.useEffect)(()=>{vr()},[vr]),(0,M.useEffect)(()=>{let t=t=>{let n=t.detail;!n||n.workspaceName!==e||(sn({treeName:n.treeName||`context`,path:ze(n.path||`/`)}),un(`left`))};return window.addEventListener(`workspace:open-to-side`,t),()=>window.removeEventListener(`workspace:open-to-side`,t)},[e,U,H]),(0,M.useEffect)(()=>{let t=t=>{let n=t.detail;if(!(n?.workspaceName&&n.workspaceName!==e)&&(e&&jt(e,n),xt(bt(n),{tree:U,kind:E(U),path:H,wholeWorkspace:j===`workspace`}))){if(e&&R(e,U,H),$n.current){Xn();return}vr({silent:!0})}};return window.addEventListener(`workspace:documents:refresh`,t),()=>window.removeEventListener(`workspace:documents:refresh`,t)},[vr,e,H,U,j,Xn]);let yr=d?.name,br=d?.id;(0,M.useEffect)(()=>{if(!e||!yr&&!br)return;let t=[yr,br].filter(Boolean).map(e=>`workspace:${e}`),n=()=>t.forEach(e=>v.emit(`subscribe`,{channel:e}));n();let r=v.on(`connect`,n),i=new Map,a=!1,o=()=>{x(e).then(e=>{a||(i=gt(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,$n.current){Xn();return}vr({silent:!0})}},f=t=>n=>{(t.startsWith(`tree.created`)||t.startsWith(`tree.renamed`))&&o();let r=_t(t,n,i);At(e,r);let a={tree:U,kind:E(U),path:H,wholeWorkspace:j===`workspace`},f=cn.current;f&&xt(r,{tree:f.treeName,kind:E(f.treeName),path:f.path})&&(u=f),xt(r,a,ir.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])=>v.on(e,t)),()=>{a=!0,s&&clearTimeout(s),r?.(),p.forEach(([e,t])=>v.off(e,t))}},[e,br,yr,U,H,j,vr,Xn]);let xr=`${H}\0${U}\0${K??``}\0${j}`,[Sr,Cr]=(0,M.useState)(xr);Sr!==xr&&(Cr(xr),I(1),It(null));let wr=`${H}\0${U}\0${K??``}`,[Tr,Er]=(0,M.useState)(wr);Tr!==wr&&(Er(wr),it(`path`));let Dr=(e,t)=>{let n=e===`/`?`canvas`:e.split(`/`).pop()||`canvas`;mt(n),ft({parentPath:e,captureView:t})},Or=l.get(`createCanvas`)===`1`,[kr,Ar]=(0,M.useState)(!1);kr!==Or&&(Ar(Or),Or&&Dr(H,!1)),(0,M.useEffect)(()=>{if(!Or)return;let e=new URLSearchParams(n.search);e.delete(`createCanvas`);let t=e.toString();o(`${n.pathname}${t?`?${t}`:``}${n.hash}`,{replace:!0})},[Or,H]);let jr=(0,M.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]),Mr=JSON.stringify([l.has(`q`),...u]),[Nr,Pr]=(0,M.useState)(Mr);Nr!==Mr&&(Pr(Mr),Nt(u),I(1));let Fr=`${Mr}\0${X??``}\0${jn}\0${H}\0${Ft??``}`,[Ir,Lr]=(0,M.useState)(Fr);Ir!==Fr&&(Lr(Fr),l.has(`q`)||u.length>0||X!==`canvas`||Ft===H||(Nt(jn?[jn]:[]),I(1)));let Rr=(0,M.useCallback)(e=>{let t=e.trim();t&&(It(null),Nt(e=>{if(e.includes(t))return e;let n=[...e,t];return jr(n),I(1),n}))},[jr,It,Nt,I]),zr=(0,M.useCallback)(e=>{Nt(t=>{let n=e<0?[]:t.filter((t,n)=>n!==e);return n.length===0&&It(H),jr(n),I(1),n})},[jr,H,It,Nt,I]),Br=z.join(` `).trim(),Vr=!!B.activeContextType&&(B.isDirty||Br!==(X===`canvas`?jn:B.savedSearchQuery||``));!e&&q!==null&&on(null),(0,M.useEffect)(()=>{let t=!1;if(!e)return;let n=0,r=!1,i=(i=!1)=>{let a=++n;i&&ue(e,U),oe(e,U).then(i=>{!t&&a===n&&(r=!0,vn.current=`${e}/${U}`,on(i))}).catch(()=>{!t&&a===n&&!r&&on(null)})};i(!1);let a=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||n?.treeName&&n.treeName!==U||i(!n?.cacheInvalidated)};window.addEventListener(`workspace:tree:refresh`,a);let o=Te(e,br);return()=>{t=!0,o(),window.removeEventListener(`workspace:tree:refresh`,a)}},[e,U,br]),!(e&&X===`canvas`&&!G)&&P!==null&&Tt(null),(0,M.useEffect)(()=>{let t=!1;if(!(!e||X!==`canvas`||G))return se(e,H,U).then(e=>{t||Tt(e)}).catch(()=>{t||Tt(null)}),()=>{t=!0}},[e,H,U,X,G]);let Hr=async()=>{if(d){ot(!0);try{let t=await fe(e||d.id);f(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{ot(!1)}}},Ur=async t=>{if(!d)return;let n=c({title:`Removing…`,description:`Document from "${H}"`});try{await C(e||d.id,[t],H,[],U,Zr,{trashIfOrphaned:!0}),R(e||d.id,U,H),y(e=>e.filter(e=>e.id!==t)),k(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`})}},Wr=async t=>{if(!d)return;let n=c({title:`Deleting…`,description:`Document from "${H}"`});try{await ge(e||d.id,[t],H,[],U,Zr),R(e||d.id,U,H),y(e=>e.filter(e=>e.id!==t)),k(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`})}},Gr=async t=>{if(!d)return;let n=c({title:`Removing…`,description:`${t.length} document(s) from "${H}"`});try{await C(e||d.id,t,H,[],U,Zr,{trashIfOrphaned:!0}),R(e||d.id,U,H),y(e=>e.filter(e=>!t.includes(e.id))),k(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`})}},Kr=async t=>{if(!d)return;let n=c({title:`Deleting…`,description:`${t.length} document(s)`});try{await ge(e||d.id,t,H,[],U,Zr),R(e||d.id,U,H),y(e=>e.filter(e=>!t.includes(e.id))),k(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`})}},qr=async t=>{if(!d)return;let n=c({title:`Destroying…`,description:`Document and its backend copies`});try{let r=await S(e||d.id,[t]);if(r.failed?.length){n.fail({title:`Error`,description:r.failed[0].reason,variant:`destructive`});return}y(e=>e.filter(e=>e.id!==t)),k(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`})}},Jr=async t=>{if(!d)return;let n=c({title:`Destroying…`,description:`${t.length} document(s) and their backend copies`});try{let r=await S(e||d.id,t),i=new Set(r.successful?.filter(e=>e.docDeleted).map(e=>e.id)??[]);y(e=>e.filter(e=>!i.has(e.id))),k(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`})}},Yr=e=>{ct({documentIds:e,operation:`copy`,sourcePath:H,sourceTreeName:U}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}})),s({title:`Copied`,description:`${e.length} document(s) copied to clipboard`})},Xr=e=>{ct({documentIds:e,operation:`cut`,sourcePath:H,sourceTreeName:U}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}})),s({title:`Cut`,description:`${e.length} document(s) cut to clipboard`})},Zr=E(U),Qr=async(t,n,r={})=>{if(!e)return!1;let i=r.targetTreeName??U,a=r.targetTreeType??Zr,o=r.move??st?.operation===`cut`,s=c({title:o?`Moving…`:`Pasting…`,description:`${n.length} document(s) → "${t}"`});try{let c=await ae(e,t,n,i,a);if(c){R(e,i,t);let a=r.sourceTreeName||st?.sourceTreeName,c=r.sourcePath||st?.sourcePath;if((r.move??st?.operation===`cut`)&&c&&a){let t=E(a);await C(e,n,c,[],a,t),R(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}"`}),ct(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}));let l=performance.now();await vr(),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}},$r=async(t,n)=>{if(!e)return!1;try{let r=(await O(e,n,t,U,Zr)).length>0;return r&&(ke(e,U,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}},ei=async()=>{if(!d||rr===0||mr||pr.current||window.prompt(`Type PURGE to permanently delete all ${rr} matching documents across all pages.`)!==`PURGE`)return;pr.current=!0,fr(!0);let t=c({title:`Purging…`,description:`${rr} matching document(s)`});try{let n=await ye(e||d.id,sr,rr);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{R(e||d.id,U,H),await vr({silent:!0}),pr.current=!1,fr(!1)}},ti=()=>Dr(H,!0),ni=async()=>{if(!(!e||!ut||!pt.trim())){vt(!0);try{let t=pt.trim(),n=ut.parentPath,r=n===`/`?`/${t}`:`${n}/${t}`,i={...B.filters,features:{...B.filters.features,allOf:On}};await ve(e,r,U,ut.captureView?{metadata:{toolbox:i},querySpec:{features:i.features,filters:[...Fe(B.filters.timeline),...Pe(B.filters.geo)],query:Br||void 0,sort:B.filters.sort?.sortBy?B.filters.sort:null}}:{}),ft(null),ue(e,U);try{let t=await oe(e,U,{force:!0});on(t)}catch{}window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e}})),o(Be(e,r,U))}catch(e){s({title:`Error`,description:e instanceof Error?e.message:`Failed to create canvas`,variant:`destructive`})}finally{vt(!1)}}},ri=async()=>{if(!(!e||X!==`canvas`)){St(!0);try{let t=P||await T(e,H,U);Tt(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{St(!1)}}},ii=async()=>{if(P){St(!0);try{await _e(P.code),Tt(null),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:U}})),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{St(!1)}}},ai=async()=>{if(!e||X!==`canvas`||H===`/`)return;let t=Mn?.label||H.split(`/`).pop()||`canvas`,n=P?` Its public link will stop working.`:``;if(window.confirm(`Delete canvas "${t}"? This cannot be undone.${n}`)){wt(!0);try{if(P)await _e(P.code),Tt(null);else if(Y?.locked){s({title:`Canvas is locked`,description:`Unlock it before deleting.`,variant:`destructive`});return}await w(e,H,!1,U);let n=H.split(`/`).filter(Boolean);n.pop();let r=n.length?`/${n.join(`/`)}`:`/`;window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:U}})),o(Be(e,r,U)),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{wt(!1)}}},oi=(0,M.useCallback)(async t=>{if(!e||!J)return;let n={treeName:U,path:H},r=ln===`left`?n:J,i=ln===`left`?J:n,a=ln===`left`?dn:gn;if(a.length===0){s({title:`Nothing selected`,description:`Tick documents in the focused pane first.`});return}let o=E(i.treeName),l=c({title:t?`Moving…`:`Copying…`,description:`${a.length} document(s) → "${i.path}"`});try{if(!await ae(e,i.path,a,i.treeName,o)){l.done();return}if(R(e,i.treeName,i.path),t){let t=E(r.treeName);await C(e,a,r.path,[],r.treeName,t),R(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,J,ln,U,H,dn,gn,s,c]);if((0,M.useEffect)(()=>{if(!J)return;let e=e=>{if(e.key!==`F5`&&e.key!==`F6`)return;let t=e.target;t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`&&(e.preventDefault(),oi(e.key===`F6`))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[J,oi]),p)return(0,N.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,N.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,N.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,N.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading workspace...`})]})});if(!d)return(0,N.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:`Workspace not found.`});let si=X===`canvas`&&!G&&!!Y,ci=!si&&!W&&bn?(0,N.jsx)(Je,{views:Tn,activeId:En,onSelect:kn,onSave:An,accentColor:Me(d.color),onOpenToSide:e=>{sn({treeName:U,path:H,viewId:e}),un(`right`)}}):void 0,li=$t||d.status!==`active`?(0,N.jsxs)(N.Fragment,{children:[$t&&(0,N.jsx)(`button`,{type:`button`,onClick:()=>{tn(!en),I(1)},"aria-pressed":en,className:g(`min-h-10 rounded-md border px-2 text-xs`,en&&`bg-warning/15 text-warning`),children:`Unfiled only`}),d.status!==`active`&&(0,N.jsx)(`button`,{type:`button`,onClick:Hr,disabled:at,className:`min-h-10 rounded-md border px-2 text-xs`,children:at?`Starting…`:`Start`})]}):void 0,ui=we(U,H)?H===`/Trash`?(0,N.jsx)(`div`,{className:`h-full overflow-auto p-4`,children:(0,N.jsx)(nt,{workspaceName:e||d.id})}):(0,N.jsx)(lt,{workspace:e||d.id,path:H,onNavigate:t=>o(Be(e,t,`backends`))},e):(0,N.jsx)(qe,{navigationTabs:ci,navigationActions:li,onBack:hn,accentColor:Me(d.color),urlType:G?E(U)===`directory`?`${U}-layer`:`context-layer`:X===`canvas`?`canvas`:E(U)===`directory`?U:`context`,urlDisplay:Hn,contextPath:H,treeName:U,workspaceId:e||d.id,workspaceLabel:d.label||d.name,workspaceIcon:d.icon,documentSchema:Dn,documents:or,isLoading:re,totalCount:rr,currentPage:F,pageSize:L,onPageChange:I,onPageSizeChange:e=>{Mt(e),I(1)},onRemoveDocument:H===`/`?void 0:Ur,onDeleteDocument:Wr,onDestroyDocument:qr,onRemoveDocuments:H===`/`?void 0:Gr,onDeleteDocuments:Kr,onDestroyDocuments:Jr,onCopyDocuments:Yr,onCutDocuments:Xr,onPasteDocuments:W?void 0:Qr,onImportDocuments:W?void 0:$r,onSelectionChange:fn,onBrowseTree:()=>mn(`workspaces`,`detail`,e??null),onBrowseWorkspaces:()=>pn(`workspaces`),onNavigatePath:t=>o(Be(e,t,U)),folders:yn,onOpenFolder:t=>o(Be(e,ze(t),U)),scope:j,onScopeChange:it,pastedDocumentIds:st?.documentIds,linkTree:q,onPurgeDocuments:W?void 0:ei,disablePurgeDocuments:mr,canvasInfo:Mn??void 0,isCanvasPinned:Rn,onTogglePinCanvas:$?Vn:void 0,onSaveAsCanvas:q&&X!==`canvas`&&!G&&!W?ti:void 0,onShareCanvas:X===`canvas`&&!G?ri:void 0,onUnshareCanvas:P?ii:void 0,onDeleteCanvas:X===`canvas`&&!G?ai:void 0,isSharingCanvas:yt,isDeletingCanvas:Ct,isCanvasShared:!!P,isCanvasLocked:!!Y?.locked,backendSearchQueries:z,onBackendSearch:Rr,serverSort:B.filters.sort,onServerSortChange:Rt,onRemoveBackendQuery:zr,canSaveChanges:Vr,isSavingChanges:B.isSaving,onSaveChanges:Lt,contentBanner:A&&Ee?(0,N.jsx)(Dt,{data:Ee,className:`mb-3`}):null,children:si&&Y?(0,N.jsx)(xe,{workspaceId:e||d.id,treeName:U,path:H,layerId:Y.id,querySpec:Y.querySpec,metadata:Y.metadata,isLocked:!!Y.locked,fetchDocuments:B.isDirty?Wn:void 0}):!W&&Q.kind===`columns`?(0,N.jsx)(Qe,{documents:or,workspaceId:e||d.id,columns:Q.columns??[],onColumnsChange:e=>An(Tn.map(t=>t.id===Q.id?{...t,columns:e}:t))}):!W&&Q.kind===`app`&&Q.app&&Q.app!==`notes`?(0,N.jsx)(Xe,{app:Q.app,workspaceId:e||d.id,treeName:U,path:H}):null});return(0,N.jsxs)(Ue,{workspaceId:e||d.id,treeName:U,path:H,headerOnly:!0,className:`relative flex flex-col h-full min-h-0`,children:[(0,N.jsx)(dt,{workspaceId:d.id,workspaceName:d.label||d.name},d.id),we(U,H)&&(0,N.jsx)(Se,{workspace:d.label||d.name,workspaceIcon:d.icon,tree:U,path:H,onBack:hn,onBrowseTree:()=>mn(`workspaces`,`detail`,e||d.id),onBrowseWorkspaces:()=>pn(`workspaces`),onNavigatePath:t=>o(Be(e,t,U)),accentColor:Me(d.color)}),ut&&(0,N.jsx)(`div`,{className:`shrink-0 px-2 pt-2`,children:(0,N.jsx)(Ge,{title:`New canvas`,onClose:()=>ft(null),children:(0,N.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),ni()},className:`space-y-4`,children:[(0,N.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,N.jsxs)(`div`,{children:[(0,N.jsx)(`label`,{htmlFor:`canvas-name`,className:`mb-1 block text-sm font-medium`,children:`Name`}),(0,N.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:pt,onChange:e=>mt(e.target.value),onKeyDown:e=>{e.key===`Escape`&&ft(null)},autoFocus:!0})]}),(0,N.jsxs)(`div`,{children:[(0,N.jsx)(`span`,{className:`mb-1 block text-sm font-medium`,children:`Parent path`}),(0,N.jsx)(`div`,{className:`flex h-10 items-center rounded-md bg-muted px-3 font-mono text-sm text-muted-foreground`,children:ut.parentPath===`/`?`/`:ut.parentPath})]})]}),(0,N.jsxs)(`label`,{className:`flex items-start gap-2 text-sm`,children:[(0,N.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:ut.captureView,onChange:e=>ft({...ut,captureView:e.target.checked})}),(0,N.jsxs)(`span`,{children:[`Capture the current view`,(0,N.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:`Freezes the active filters, search and sort into the canvas.`})]})]}),(0,N.jsxs)(`div`,{className:`flex gap-2`,children:[(0,N.jsx)(ee,{type:`submit`,disabled:!pt.trim()||ht,children:ht?`Creating…`:`Create canvas`}),(0,N.jsx)(ee,{type:`button`,variant:`outline`,onClick:()=>ft(null),children:`Cancel`})]})]})})}),(0,N.jsxs)(`div`,{"data-canvas-panes":!0,className:`flex-1 min-h-0 flex gap-2`,children:[(0,N.jsx)(`div`,{"data-canvas-pane":!0,className:g(`flex-1 min-w-0 bg-background overflow-hidden`,J&&(ln===`left`?`ring-2 ring-primary`:`ring-1 ring-primary/20`)),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||un(`left`)},children:ui}),J&&e&&(0,N.jsx)(Pt,{workspaceName:e,workspaceLabel:d.label||d.name,workspaceIcon:d.icon,pane:J,isFocused:ln===`right`,clipboard:st,setClipboard:ct,onFocus:()=>un(`right`),onSelectionChange:_n,onNavigate:e=>sn(t=>t&&{...t,path:e,viewId:void 0}),onClose:()=>{sn(null),un(`left`),_n([])}})]})]})}function Nt(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 Pt({workspaceName:e,workspaceLabel:t,workspaceIcon:n,pane:r,isFocused:i=!1,clipboard:a,setClipboard:o,onFocus:s,onSelectionChange:c,onNavigate:l,onClose:u}){let{openM1Drawer:d,openM2Drawer:f}=Ve(),{showToast:p,showProgress:m}=ne(),[h,ee]=(0,M.useState)(null),[_,te]=(0,M.useState)([]),[v,y]=(0,M.useState)(!1),[re,b]=(0,M.useState)(0),[x,ie]=(0,M.useState)(1),[w,se]=(0,M.useState)(50),T=E(r.treeName),ce=Nt(h,r.path),le=ce?.type===`canvas`,D=(0,M.useMemo)(()=>et(h,r.path),[h,r.path]),O=r.viewId?$e(ce?.metadata).find(e=>e.id===r.viewId)??null:null,fe=`${e}://${r.path===`/`?``:r.path.replace(/^\//,``)}`,pe=Ze(O),me=(0,M.useCallback)(async()=>{if(we(r.treeName,r.path)){te([]),b(0),y(!1);return}let t=kt(e,r.treeName,r.path,x,w,``,pe??``),n=Ot.get(t);if(n){te(n.documents),b(n.totalCount);return}y(!0);try{let n=await de(e,r.path,pe?[pe]:[],{limit:w,page:x,treeName:r.treeName,treeType:T}),i=n.payload||[],a=n.totalCount||n.count||0;te(i),b(a),Ot.set(t,{documents:i,totalCount:a})}catch(e){p({title:`Error`,description:e instanceof Error?e.message:`Failed to fetch side pane documents`,variant:`destructive`}),te([]),b(0)}finally{y(!1)}},[e,r.path,r.treeName,T,w,x,p,pe]);(0,M.useEffect)(()=>{let t=!1,n=0,i=!1,a=(a=!1)=>{let o=++n;a&&ue(e,r.treeName),oe(e,r.treeName).then(e=>{!t&&o===n&&(i=!0,ee(e))}).catch(()=>{!t&&o===n&&!i&&ee(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,M.useEffect)(()=>{me()},[me]),(0,M.useEffect)(()=>{let t=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||(jt(e,n),xt(bt(n),{tree:r.treeName,kind:E(r.treeName),path:r.path})&&(R(e,r.treeName,r.path),me()))};return window.addEventListener(`workspace:documents:refresh`,t),()=>window.removeEventListener(`workspace:documents:refresh`,t)},[me,e,r.treeName,r.path]);let he=(0,M.useCallback)(async(t,n,i={})=>{let s=i.targetTreeName??r.treeName,c=i.targetTreeType??T,l=i.move??a?.operation===`cut`,u=m({title:l?`Moving…`:`Pasting…`,description:`${n.length} document(s) → "${t}"`});try{let r=await ae(e,t,n,s,c);if(r){R(e,s,t);let r=i.sourcePath||a?.sourcePath,c=i.sourceTreeName||a?.sourceTreeName;if((i.move??a?.operation===`cut`)&&r&&c){let t=E(c);await C(e,n,r,[],c,t),R(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 me(),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,T,me,m,a,o]),_e=(0,M.useCallback)(()=>{R(e,r.treeName,r.path),me()},[e,r.treeName,r.path,me]),ve=(0,M.useCallback)(async t=>{let n=m({title:`Removing…`,description:`${t.length} document(s) from "${r.path}"`});try{await C(e,t,r.path,[],r.treeName,T),_e(),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,T,_e,m]),ye=(0,M.useCallback)(async t=>{let n=m({title:`Deleting…`,description:`${t.length} document(s)`});try{await ge(e,t,r.path,[],r.treeName,T),_e(),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,T,_e,m]),be=(0,M.useCallback)(async t=>{let n=m({title:`Destroying…`,description:`${t.length} document(s) and their backend copies`});try{let r=await S(e,t);if(r.failed?.length&&!r.successful?.length){n.fail({title:`Error`,description:r.failed[0].reason,variant:`destructive`});return}_e();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,_e,m]);return(0,N.jsxs)(`div`,{className:g(`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:[u&&(0,N.jsx)(`button`,{type:`button`,onClick:u,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`}),we(r.treeName,r.path)?r.path===`/Trash`?(0,N.jsx)(`div`,{className:`h-full overflow-auto p-4`,children:(0,N.jsx)(nt,{workspaceName:e})}):(0,N.jsx)(lt,{workspace:e,path:r.path,onNavigate:l||(()=>{})}):(0,N.jsx)(qe,{frameContent:!1,onBrowseWorkspaces:()=>d(`workspaces`),onBrowseTree:()=>f(`workspaces`,`detail`,e),urlType:le?`canvas`:T===`directory`?r.treeName:`context`,urlDisplay:fe,contextPath:r.path,treeName:r.treeName,workspaceId:e,workspaceLabel:t,workspaceIcon:n,documentSchema:pe,documents:_,isLoading:v,totalCount:re,currentPage:x,pageSize:w,onPageChange:ie,onPageSizeChange:e=>{se(e),ie(1)},onRemoveDocument:r.path===`/`?void 0:e=>ve([e]),onRemoveDocuments:r.path===`/`?void 0:ve,onDeleteDocument:e=>ye([e]),onDeleteDocuments:ye,onDestroyDocument:e=>be([e]),onDestroyDocuments:be,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:he,onSelectionChange:c,pastedDocumentIds:a?.documentIds,linkTree:h,folders:D,onOpenFolder:l,onNavigatePath:l,canvasInfo:le?{label:ce?.label,description:ce?.description,color:ce?.color}:void 0,children:O?.kind===`columns`?(0,N.jsx)(Qe,{documents:_,workspaceId:e,columns:O.columns??[],onColumnsChange:()=>{},readOnly:!0}):O?.kind===`app`&&O.app&&O.app!==`notes`?(0,N.jsx)(Xe,{app:O.app,workspaceId:e,treeName:r.treeName,path:r.path}):null})]})}export{Mt as default};
|
|
@@ -1,6 +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,Bn as i,Bt as a,Ct as o,L as s,Mn as c,Pr as l,Pt as u,Q as d,Ur as ee,X as f,Y as p,Yn as m,Z as te,ai as ne,cn as h,di as g,pn as _,qn as re,st as v,ti as ie,vr as y}from"./ui-CDoK3F3U.js";import{t as b}from"./utils-2pl1SbIp.js";import{t as x}from"./button-SeUZ_Pvi.js";import{t as S}from"./input-BOtCd4HP.js";import{t as C}from"./api-CA6WiiYM.js";import{t as w}from"./socket-CtH3EU9m.js";import{n as ae}from"./use-toast-BlLDqSUO.js";import{t as oe}from"./LinkToCard-CKVi4Nrg.js";import{H as se,cn as ce,sn as le,vt as ue}from"./workspace-C5V-ZCOE.js";import{i as de}from"./MessageComposerDialog-CdPp-3GR.js";import{n as fe}from"./LinkToSidePanel-eCy3nW4R.js";import{t as pe}from"./PathPickerField-CW2yG2Yg.js";var T=e(n(),1);function E(e){return`/workspaces/${e}/hooks`}async function D(e){return await C.get(E(e))||[]}async function O(e,t){return(await C.get(`${E(e)}/${t}`))?.content??``}async function k(e,t,n){await C.put(`${E(e)}/${t}`,{content:n})}async function A(e,t){await C.delete(`${E(e)}/${t}`)}var j=[`example-`,`disabled-`,`_`];function M(e){let t=e.lastIndexOf(`/`);return{dir:t===-1?``:e.slice(0,t+1),base:t===-1?e:e.slice(t+1)}}function me(e){return j.find(t=>e.startsWith(t))??null}function he(e){return me(M(e).base)===null}function N(e){return M(e).base.startsWith(`example-`)}function ge(e){let{dir:t,base:n}=M(e),r=me(n);return t+(r?n.slice(r.length):`disabled-${n}`)}async function _e(e,t,n){if(he(t)===n)return t;let r=ge(t);return await k(e,r,await O(e,t)),await A(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 P=`rules.json`;async function we(e){try{let t=await O(e,P),n=JSON.parse(t||`{}`);return Array.isArray(n.rules)?n.rules:[]}catch{return[]}}async function Te(e,t){await k(e,P,JSON.stringify({$schema:`canvas.hook-rules/v1`,rules:t},null,2)+`
|
|
2
|
-
`)}async function Ee(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 C.get(`${E(e)}/pending${r?`?${r}`:``}`)||[]}async function De(e,t){return await C.post(`${E(e)}/pending/decisions`,t)}async function Oe(e,t){return await C.get(`${E(e)}/runs/${encodeURIComponent(t)}`)}async function ke(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 C.get(`${E(e)}/runs${r?`?${r}`:``}`)||[]}var F=1e4,Ae=`canvas.hooks.backfillLimit`;function I(e){let t=Math.floor(Number(e));return!Number.isFinite(t)||t<1?500:Math.min(t,F)}function je(){try{let e=localStorage.getItem(Ae);return e?I(e):500}catch{return 500}}function Me(e){let t=I(e);try{localStorage.setItem(Ae,String(t))}catch{}return t}function Ne(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 Pe(e,t){return await C.post(`${E(e)}/backfill`,t)}function Fe(e,t){return C.post(`${E(e)}/backfill/jobs`,t)}function Ie(e,t){return C.get(`${E(e)}/backfill/jobs/${t}`)}function Le(e,t){return C.delete(`${E(e)}/backfill/jobs/${t}`)}function L(e){return C.get(`${E(e)}/backfill/jobs`)}async function Re(e,t){return await C.post(`${E(e)}/run`,t)}async function ze(e,t){return await C.post(`${E(e)}/runs/${t}/replay`,{})}async function Be(e){return await C.get(`${E(e)}/meta`)}async function R(e,t){return await C.post(`${E(e)}/generate`,t)}async function Ve(e,t){let n=await O(e,P),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 k(e,P,JSON.stringify(o,null,2)+`
|
|
3
|
-
`)}var z=Ve;function He(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…`,Ue=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 We(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=Ue.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)}),Le(t,n.id).catch(()=>a.update({title:B,description:`Could not cancel. Try again.`}))}}}),o=()=>{u?.(),w.off(`job.progress`,c),w.off(`job.finished`,c),r()},s=e=>{if(e.status===`running`)return a.update({title:B,description:V(e)});We(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=()=>{w.emit(`subscribe`,i),Ie(t,n.id).then(s,()=>{})},u=w.on(`connect`,l);w.on(`job.progress`,c),w.on(`job.finished`,c),l()});return Ue.set(n.id,i),i.finally(()=>Ue.delete(n.id)),i}async function Ge(e,t,n){let r;try{r=await Fe(t,{ruleIds:n,limit:je()})}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 Ke(e,t){let n=await L(t).catch(()=>[]);for(let r of n)r.status===`running`&&H(e,t,r)}function U(e){return`/workspaces/${e}/scripts`}async function qe(e){return await C.get(U(e))||[]}async function Je(e,t){return(await C.get(`${U(e)}/${t}`))?.content??``}async function Ye(e,t,n){await C.put(`${U(e)}/${t}`,{content:n})}async function Xe(e,t){await C.delete(`${U(e)}/${t}`)}var W=t(),Ze=[{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`}],Qe=[{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.`}],$e=[{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`}],G=new Set([`toExact`,`fromExact`,`senderExact`,`threadExact`,`channelExact`,`platformExact`]),et=e=>G.has(e)?e.replace(/Exact$/,``):e.replace(/Regex$/,``),tt=[{key:`sendFile`,label:`Send file(s) via a channel`,icon:h,tone:`text-blue-600 dark:text-blue-400 bg-blue-500/10`},{key:`extractAttachments`,label:`Extract email attachments to a folder`,icon:h,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`moveMessage`,label:`Move the email to a mail folder`,icon:h,tone:`text-teal-600 dark:text-teal-400 bg-teal-500/10`},{key:`store`,label:`Copy/Move file(s) to a storage backend`,icon:i,tone:`text-sky-600 dark:text-sky-400 bg-sky-500/10`},{key:`download`,label:`download what the link points at`,icon:y,tone:`text-rose-600 dark:text-rose-400 bg-rose-500/10`},{key:`link`,label:`file it into a folder`,icon:m,tone:`text-emerald-600 dark:text-emerald-400 bg-emerald-500/10`},{key:`unlink`,label:`remove it from a folder`,icon:m,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:ne,tone:`text-pink-600 dark:text-pink-400 bg-pink-500/10`},{key:`agent`,label:`ask an agent`,icon:ie,tone:`text-indigo-600 dark:text-indigo-400 bg-indigo-500/10`},{key:`script`,label:`run a script`,icon:te,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`}],nt=e=>tt.find(t=>t.key===e)||tt[1],rt=`{{title}}{{ext}}`,it=`{{YYYY}}/{{MM}}/{{YYYY}}{{MM}}{{DD}}_{{HH}}{{mm}}{{ss}}{{ext}}`,at=[{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.`}],ot=[{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,deleteSource:!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`)]},st=e=>e.split(`|`).map(e=>e.trim()).filter(Boolean);function ct(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),lt=[{id:`send-invoices`,title:`Send invoice PDFs to accounting`,icon:h,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:h,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:i,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:c,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:m,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:h,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:y,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:ie,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_doc_get_by_id, then summarize it in three bullet points.`,notifyReply:!0}]})},{id:`blank`,title:`Start from scratch`,icon:v,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=st(t[0].value);return n.length===1&&/^(ctx|context):\//.test(n[0])?n[0].replace(/^(ctx|context):/,``).replace(/\/+$/,``)||`/`:null}function ut(e){if(Y(e)!==null)return!0;let t=e.filter(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field)).flatMap(e=>st(e.value));return t.length>0&&t.every(e=>/^(ctx|context|dir|directory|backends):\//.test(e))}function dt(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`?it:e.b||`<filename>`].filter(Boolean).join(`/`)}}function ft(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=G.has(t.field),a=e||n?t.value.trim()?[t.value]:[]:st(t.value);if(e&&a.length)try{new RegExp(t.value,`i`)}catch{throw Error(`Invalid regular expression for ${$e.find(e=>e.key===t.field)?.label}: ${t.value}`)}if(!a.length)throw Error(`Enter a value for ${$e.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[et(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&&!ut(e.conditions))throw Error(`Choose a Context, Directory or Backends source 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`?rt:n.storeName===`dated`?it: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.deleteSource?{deleteSource:!0}:{},...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.deleteSource?{deleteSource:!0}:{},...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||ct(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 pt(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:ee,eventPathExact:f,mime:p,url:m,attachment:te,...ne}=e.when;if(Object.keys(ne).length>0)return null;let h=Array.isArray(t)?t:[t];if(!h.length||!h.every(e=>typeof e==`string`&&Qe.some(t=>t.value===e))||n!==void 0&&typeof n!=`string`)return null;let g=[],_=(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)g.push({field:e,value:t})}else if(G.has(e))for(let t of n){if(!t||typeof t!=`object`||Object.keys(t).length!==1||typeof t.equals!=`string`)return!1;g.push({field:e,value:t.equals})}else if([`from`,`to`,`subject`,`body`,`sender`].includes(e))for(let t of n)if(typeof t==`string`)g.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`)g.push({field:`${e}Exact`,value:t.equals});else if(t&&typeof t==`object`&&Object.keys(t).length===1&&typeof t.regex==`string`)g.push({field:`${e}Regex`,value:t.regex});else return!1;else{if(!n.every(e=>typeof e==`string`))return!1;g.push({field:e,value:n.join(` | `)})}return!0};if(d!==void 0&&!_(`path`,d)||ee!==void 0&&!_(`pathExact`,ee)||f!==void 0&&!_(`eventPathExact`,f)||p!==void 0&&!_(`mime`,p)||r!==void 0&&!_(`from`,r)||i!==void 0&&!_(`to`,i)||a!==void 0&&!_(`subject`,a)||o!==void 0&&!_(`body`,o)||s!==void 0&&!_(`sender`,s)||c!==void 0&&!_(`threadExact`,c)||l!==void 0&&!_(`channelExact`,l)||u!==void 0&&!_(`platformExact`,u)||te!==void 0&&!_(`attachment`,te))return null;if(m!==void 0){if(typeof m==`string`)g.push({field:`urlContains`,value:m});else if(m&&typeof m==`object`){let e=m;if(Object.keys(e).filter(e=>e!==`host`&&e!==`contains`&&e!==`regex`).length||e.host!==void 0&&!_(`urlHost`,e.host)||e.contains!==void 0&&!_(`urlContains`,e.contains)||e.regex!==void 0&&!_(`urlRegex`,e.regex))return null}else return null}let re=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}},v=[];for(let t of e.then||[]){if(t.approval!==void 0)return null;if(t.action===`link`&&Array.isArray(t.paths))v.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))v.push({...K(`unlink`),a:t.paths.join(`, `),recursive:t.recursive===!0});else if(t.action===`tag`&&Array.isArray(t.tags))v.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;v.push({...K(`moveMessage`),a:t.folder})}else if(t.action===`notify`&&typeof t.message==`string`)v.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(g)===null)||t.recursive===!0&&Y(g)!==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:``;v.push({...K(`store`),a:t.to,b:e===rt||e===it?``:e,storeFolder:typeof t.folder==`string`?t.folder:``,recursive:t.recursive===!0,deleteSource:t.deleteSource===!0,storeName:e?e===rt?`title`:e===it?`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;v.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;v.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`,`deleteSource`]);if(Object.keys(t).some(t=>!e.has(t)))return null;let n=typeof t.kind==`string`?t.kind:`auto`;if(!at.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;v.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,deleteSource:t.deleteSource===!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:``;v.push({...K(`unstore`),a:e(t.from),b:e(t.ifOn),keepLast:t.keepLast!==!1})}else if(t.action===`delete`)v.push(K(`delete`));else if(t.action===`destroy`)v.push(K(`destroy`));else if(t.action===`agent`&&typeof t.slug==`string`&&typeof t.prompt==`string`){let e=re(t);if(!e)return null;v.push({...K(`agent`),a:t.slug,b:t.prompt,...e})}else if(t.action===`script`&&typeof t.path==`string`){let e=re(t);if(!e)return null;v.push({...K(`script`),a:t.path,...e})}else return null}return{id:e.id,description:e.description||``,events:h,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:g,actions:v.length?v:[K(`link`)]}}var mt=(e,t)=>t.find(t=>t.value===e)?.label?.replace(/\s\(\d+\)$/,``)||(e?String(e).replace(/^data\/schema\//,``):`any item`);function ht(e,t=Ze){let n=e.when,r=ye(e).map(e=>Qe.find(t=>t.value===e)?.label||e).join(` or `),i=[`When ${mt(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 gt(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 _t(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===rt?`, named by title`:e.key===it?`, 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=at.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=gt(e);return`ask agent "${e.slug}"${t?` (${t})`:``}`}if(e.action===`script`){let t=gt(e);return`run ${e.path}${t?` (${t})`:``}`}return e.action}function vt(e){return(e.then||[]).map(_t).join(` · `)||`(no actions)`}function yt(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 bt(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 xt(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 St(e){return e.some(e=>e.address===`workspace:home`)?`workspace:home`:e.find(e=>e.address!==`workspace:data`)?.address||e[0]?.address||``}function Ct(e){if(e.kind===`document`&&e.rule)return{...pt(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:ut(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:b(`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:b(`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:b(`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:b(`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 wt({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:b(`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 Tt({active:e,onClick:t,children:n,title:r}){return(0,W.jsx)(`button`,{type:`button`,title:r,onClick:t,"aria-pressed":e,className:b(`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 Et({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 Dt({icon:e,tone:t,size:n=`md`}){return(0,W.jsx)(`span`,{className:b(`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 Ot({workspaceId:e,onOpenJson:t,onShowRuns:n,backfillLimit:i,prefill:c,onPrefillConsumed:d,createOnly:p=!1,onCreated:te,onCancel:ne}){let{showToast:h,showProgress:ie}=ae(),[y,C]=(0,T.useState)([]),[w,se]=(0,T.useState)({}),ce=e=>{ke(e,{limit:500}).then(e=>se(bt(e))).catch(()=>se({}))},[le,E]=(0,T.useState)(!0),[D,O]=(0,T.useState)(null),[k,A]=(0,T.useState)(!1),[j,M]=(0,T.useState)(!1),[me,he]=(0,T.useState)([]),[N,ge]=(0,T.useState)([]),[_e,ve]=(0,T.useState)([]),[ye,Se]=(0,T.useState)(``),Ce=(0,T.useRef)(null),[P,Ee]=(0,T.useState)(e);e!==P&&(Ee(e),E(!0)),(0,T.useEffect)(()=>{we(e).then(e=>C(e)).finally(()=>E(!1)),ce(e)},[e]);let[De,Oe]=(0,T.useState)(null);c!==De&&(Oe(c),c&&(O(Ct(c)),A(!1))),(0,T.useEffect)(()=>{c&&d?.()},[c,d]),(0,T.useEffect)(()=>{qe(e).then(e=>he(e.map(e=>e.path))).catch(()=>he([]))},[e]),(0,T.useEffect)(()=>{let t=!1;return de(e).then(e=>{t||(ve([...new Map(e.map(e=>[`${e.driver}:${e.address}`,e])).values()]),Se(``))}).catch(()=>{t||(ve([]),Se(`Sending accounts could not be loaded.`))}),()=>{t=!0}},[e]),(0,T.useEffect)(()=>{ue(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);ge(t);let n=St(t);n&&O(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(()=>ge([]))},[e]);let[F,Ae]=(0,T.useState)(Ze);(0,T.useEffect)(()=>{Be(e).then(e=>{e.schemas?.length&&Ae([{value:``,label:`any item`},...e.schemas.map(e=>({value:e.id,label:`${e.name} (${e.count})`}))])}).catch(()=>{})},[e]);let I=async(t,n)=>{M(!0);try{return await Te(e,t),C(t),h({title:n,description:`rules.json updated (committed to workspace git)`}),!0}catch(e){return h({title:`Error`,description:e instanceof Error?e.message:`Failed to save rules`,variant:`destructive`}),!1}finally{M(!1)}},je=async()=>{if(!D||le||j)return;let t;try{t=ft(D,N)}catch(e){h({title:`Invalid rule`,description:e instanceof Error?e.message:`Check the rule conditions and actions`,variant:`destructive`});return}if(!t.then.length){h({title:`Add an action`,description:`Pick at least one "then" action and fill in its fields.`,variant:`destructive`});return}if(p){t.id=`${t.id}-${Math.random().toString(36).slice(2,10)}`,M(!0);try{await Ve(e,t),h({title:`Rule created`,description:`The rule will run for matching new items.`}),te?.()}catch(e){h({title:`Could not create rule`,description:e instanceof Error?e.message:`Failed to save rule`,variant:`destructive`})}finally{M(!1)}return}!D.id&&y.some(e=>e.id===t.id)&&(t.id=`${t.id}-${Math.random().toString(36).slice(2,10)}`);let n=D.id?y.map(e=>e.id===D.id?{...t,enabled:e.enabled!==!1}:e):[...y,t];await I(n,D.id?`Rule updated`:`Rule created`)&&(O(null),te?.())},Me=e=>I(y.map(t=>t.id===e?{...t,enabled:t.enabled===!1}:t),`Rule toggled`),Ne=e=>{confirm(`Delete rule "${e}"?`)&&I(y.filter(t=>t.id!==e),`Rule deleted`)},[Fe,Ie]=(0,T.useState)(null),Le=async t=>{Ie(t);try{let n=await Pe(e,{ruleId:t,dryRun:!0,limit:i}),r=n.results.filter(e=>e.matched).length;if(!r){h({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 ${r} of the first ${n.processed} of ${n.total??n.processed} existing documents. Run its actions on all of them now?`))return;await Ge(ie,e,[t])}catch(e){h({title:`Backfill failed`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{Ie(null),ce(e)}},L=(e,t)=>O(n=>n&&{...n,[e]:t}),Re=e=>{O(e.build({backend:St(N)})),A(!1),requestAnimationFrame(()=>Ce.current?.scrollIntoView({behavior:`smooth`,block:`start`}))},ze=e=>{let n=pt(e);n?(O(n),A(!1),requestAnimationFrame(()=>Ce.current?.scrollIntoView({behavior:`smooth`,block:`start`}))):t?.()},[R,z]=(0,T.useState)(null),B=(e,t)=>t.treeType===`context`?e:t.treeName===`directory`?`dir:${e}`:`${t.treeName}:${e}`,Ue=(e,t)=>{if(!R||!D||!e.length){z(null);return}if(R.target===`storeFolder`){let t=xe(e[0]);L(`actions`,D.actions.map((e,n)=>n===R.index?{...e,storeFolder:t?.rel||``,...t?.backend&&N.some(e=>e.address===t.backend)?{a:t.backend}:{}}:e))}else if(R.target===`condition`){let n=e.map(e=>B(e,t)),r=t.treeType===`context`&&D.actions.some(e=>e.kind===`store`);L(`conditions`,D.conditions.map((e,t)=>t===R.index?{...e,...r?{field:`eventPathExact`}:{},value:n.join(` | `)}:e))}else{let n=e.map(e=>B(e,t));L(`actions`,D.actions.map((e,t)=>t===R.index?e.kind===`download`?{...e,b:n.join(`, `)}:{...e,a:n.join(`, `)}:e))}z(null)},V=(e,t,n=`Browse…`)=>(0,W.jsxs)(x,{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)(re,{className:`h-4 w-4 sm:mr-1.5`}),(0,W.jsx)(`span`,{className:`hidden sm:inline`,children:`Browse`})]}),We=ut(D?.conditions||[]),H=!!D?.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}`:``}`,U=(e,t,n,r=`workspace:home`)=>N.length?(0,W.jsxs)(`select`,{className:X,value:e,onChange:e=>t(e.target.value),children:[(0,W.jsx)(`option`,{value:``,children:n}),N.map(e=>(0,W.jsx)(`option`,{value:e.address,children:Ke(e)},e.address)),e&&!N.some(t=>t.address===e)&&(0,W.jsx)(`option`,{value:e,children:e})]}):(0,W.jsx)(S,{className:b(Z,`font-mono`),placeholder:r,value:e,onChange:e=>t(e.target.value)}),Je=y.filter(yt),Ye=y.filter(e=>!yt(e)),Xe=({rule:e})=>{let t=e.enabled!==!1,i=pt(e)!==null,o=w[e.id],s=nt(e.then?.[0]?.action||`link`),c=be(e);return(0,W.jsxs)(`div`,{className:b(`rule-card rounded-xl border bg-card p-4 transition-opacity`,!t&&`opacity-60`),children:[(0,W.jsx)(Dt,{icon:s.icon,tone:s.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`}),!i&&(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:ht(e,F)}),(0,W.jsxs)(`p`,{className:`flex items-start gap-1.5 text-sm`,children:[(0,W.jsx)(g,{className:`mt-1 h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,W.jsx)(`span`,{children:vt(e)})]}),c.length>0&&(0,W.jsx)(`p`,{className:`truncate font-mono text-xs text-muted-foreground`,title:c.join(` | `),children:c.join(` | `)}),(0,W.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:o?(0,W.jsxs)(`button`,{type:`button`,className:b(`text-left underline-offset-2 hover:underline`,o.last.status===`error`&&`text-destructive`,!n&&`cursor-default hover:no-underline`),title:n?`Show this rule's run log`:o.last.error||o.last.skipReason||``,onClick:()=>n?.(e.id),children:[`ran `,o.count,`×`,o.errors?` (${o.errors} failed)`:``,` · last `,o.last.status,` `,xt(o.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:j,title:t?`Enabled — click to pause`:`Paused — click to enable`,onClick:()=>Me(e.id),className:b(`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:b(`h-5 w-5 rounded-full bg-background shadow transition-transform`,t&&`translate-x-5`)})}),(0,W.jsxs)(x,{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:Fe!==null||e.when.eventPathExact!==void 0,onClick:()=>Le(e.id),children:[Fe===e.id?(0,W.jsx)(_,{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)(x,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5`,title:i?`Edit rule`:`Edit as JSON`,onClick:()=>ze(e),children:[i?(0,W.jsx)(a,{className:`h-4 w-4`}):(0,W.jsx)(r,{className:`h-4 w-4`}),(0,W.jsx)(`span`,{className:`rule-card-action-label ml-1.5`,children:`Edit`})]}),(0,W.jsx)(x,{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`})})]})]})},G=(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?`}),k&&(0,W.jsxs)(x,{size:`sm`,variant:`ghost`,onClick:()=>A(!1),children:[(0,W.jsx)(s,{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:lt.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)(Dt,{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:[!p&&(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)(x,{variant:`ghost`,onClick:t,title:`Edit rules.json directly`,children:[(0,W.jsx)(r,{className:`mr-1.5 h-4 w-4`}),` JSON`]}),(0,W.jsxs)(x,{onClick:()=>{O(null),A(!0)},disabled:k,children:[(0,W.jsx)(u,{className:`mr-1.5 h-4 w-4`}),` New rule`]})]})]}),k&&!D&&G,D&&(0,W.jsxs)(`div`,{ref:Ce,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:D.id?`Edit rule`:`New rule`}),(0,W.jsxs)(x,{variant:`ghost`,size:`sm`,onClick:()=>O(null),children:[(0,W.jsx)(s,{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)(S,{className:`h-11 text-base`,placeholder:`Keep UI designs in Projects/Canvas/UI`,value:D.description,onChange:e=>L(`description`,e.target.value)})}),(0,W.jsxs)(`section`,{className:`space-y-4`,children:[(0,W.jsx)(Et,{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:D.schema,onChange:e=>L(`schema`,e.target.value),children:[F.map(e=>(0,W.jsx)(`option`,{value:e.value,children:e.label},e.value)),D.schema&&!F.some(e=>e.value===D.schema)&&(0,W.jsx)(`option`,{value:D.schema,children:D.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:Qe.map(e=>{let t=D.events.includes(e.value);return(0,W.jsx)(Tt,{active:t,title:e.hint,onClick:()=>{let n=t?D.events.filter(t=>t!==e.value):[...D.events,e.value];n.length&&L(`events`,n)},children:e.label},e.value)})})]})]}),D.conditions.length>0&&(0,W.jsx)(`div`,{className:`space-y-2`,children:D.conditions.map((e,t)=>{let n=$e.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:D.conditions.slice(0,t).some(t=>et(t.field)===et(e.field))?`or`:`and`}),(0,W.jsx)(`select`,{className:X,value:e.field,onChange:e=>L(`conditions`,D.conditions.map((n,r)=>r===t?{...n,field:e.target.value}:n)),children:$e.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)(S,{className:b(Z,`font-mono`),placeholder:n?.hint,value:e.value,onChange:e=>L(`conditions`,D.conditions.map((n,r)=>r===t?{...n,value:e.target.value}:n))}),[`path`,`pathExact`,`eventPathExact`].includes(e.field)&&V(`condition`,t,`Browse the workspace trees`)]}),(0,W.jsx)(x,{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`,D.conditions.filter((e,n)=>n!==t)),children:(0,W.jsx)(s,{className:`h-4 w-4`})})]},t)})}),(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,W.jsxs)(x,{size:`sm`,variant:`outline`,onClick:()=>L(`conditions`,[...D.conditions,{field:D.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)(Et,{step:2,title:`Then…`,hint:`Actions run in order. The item keeps its id, tags and folders unless an action says otherwise.`}),D.actions.map((t,n)=>{let r=e=>L(`actions`,D.actions.map((t,r)=>r===n?{...t,...e}:t)),i=N.find(e=>e.address===t.a),a=i?.capabilities?.paths===!0,o=We&&a,c=nt(t.kind),l=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)(pe,{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)(S,{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)(S,{className:b(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)(pe,{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`})]}),u=Y(D.conditions),d=t.kind===`store`&&t.a&&(!t.recursive||o)?dt(t,D.conditions,i):null,f=t.kind===`extractAttachments`&&t.a?He(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)(Dt,{icon:c.icon,tone:c.tone}),(0,W.jsx)(`select`,{className:b(X,`flex-1 font-medium`),value:t.kind,onChange:e=>r(K(e.target.value)),children:tt.map(e=>(0,W.jsx)(`option`,{value:e.key,children:e.label},e.key))}),(0,W.jsx)(x,{size:`sm`,variant:`ghost`,className:`h-10 w-10 shrink-0 p-0 text-muted-foreground`,title:`Remove action`,disabled:D.actions.length===1,onClick:()=>L(`actions`,D.actions.filter((e,t)=>t!==n)),children:(0,W.jsx)(s,{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)(S,{className:b(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})}),V(`action`,n)]})}),t.kind===`link`&&(0,W.jsx)(Q,{label:`Tags`,hint:`Optional, comma-separated.`,children:(0,W.jsx)(S,{className:b(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:H?`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:!H})]}),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)(S,{className:b(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)(S,{className:b(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:U(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)(S,{className:b(Z,`font-mono`),placeholder:`Projects/Canvas/UI`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),V(`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:ot.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)(wt,{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:U(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)(S,{className:b(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:u===null?`Recreate sub-folder path in destination`:`Recreate directory path in destination`,hint:a?We?u===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:${u} trigger this rule. Its full path is appended beneath the destination root; descendant inserts do not match.`:`Choose a source folder. Context paths use the destination of the insertion or link event.`:`Choose a destination that reports support for folder paths. Content-addressed blob stores cannot recreate sub-folder paths.`,disabled:!o&&!t.recursive}),d&&(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:[d.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:[d.recreated||`(root)`,`/`]})]}),(0,W.jsx)(`p`,{className:`break-all font-mono`,children:d.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)(ee,{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:U(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`})]})})]})]}),t.storeMode===`copy`&&(0,W.jsx)($,{checked:t.deleteSource,onChange:e=>r({deleteSource:e}),label:`Delete source link from Canvas`,hint:`For links without stored bytes, download the target and remove the link only after success. Files are copied normally.`}),(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)(S,{className:b(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)(S,{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:U(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)(S,{className:b(Z,`font-mono`),placeholder:`Accounting`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),V(`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)(S,{className:b(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`})]})})]}),!a&&(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.`}),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:[`Example email dated `,f.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:[f.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:f.added?`${f.added}/`:`(none)`})]}),(0,W.jsx)(`p`,{className:`break-all font-mono`,children:f.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:at.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:at.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)(S,{type:`number`,min:1,max:5,className:b(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:U(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)(S,{className:b(Z,`font-mono`),placeholder:`Downloads`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),V(`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)(S,{className:b(Z,`font-mono`),placeholder:`same folders as the link`,value:t.b,onChange:e=>r({b:e.target.value})}),V(`action`,n)]})}),(0,W.jsx)(Q,{label:`Tags for the download`,hint:`Optional, comma-separated.`,children:(0,W.jsx)(S,{className:b(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:H?`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:!H}),(0,W.jsx)($,{checked:t.deleteSource,onChange:e=>r({deleteSource:e}),label:`Delete source link from Canvas`,hint:`Remove the source item only after the download is saved successfully. Kept links are related to their downloads.`}),(0,W.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`The download becomes a file item at the filing destination. Repeated events reuse the saved download. 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:U(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:U(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)(S,{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)(S,{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=_e.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&&!_e.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)`]}),_e.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}`))]})}),ye&&(0,W.jsx)(`p`,{className:`text-xs text-destructive`,role:`status`,children:ye}),(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)(S,{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)(S,{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)(S,{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)(S,{className:b(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_doc_get_by_id 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_doc_get_by_id 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})})}),l(`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:me.length?(0,W.jsxs)(`select`,{className:b(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…`}),me.map(e=>(0,W.jsx)(`option`,{value:`scripts/${e}`,children:e},e))]}):(0,W.jsx)(S,{className:b(Z,`font-mono sm:max-w-md`),placeholder:`scripts/my-script.sh`,value:t.a,onChange:e=>r({a:e.target.value})})}),l(`output`)]})]},n)}),(0,W.jsxs)(x,{size:`sm`,variant:`outline`,onClick:()=>L(`actions`,[...D.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)(Et,{step:3,title:`Options`}),(0,W.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,W.jsx)($,{checked:D.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:D.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)(x,{className:`h-10 px-5`,onClick:je,disabled:j||le,children:[j?(0,W.jsx)(_,{className:`mr-1.5 h-4 w-4 animate-spin`}):(0,W.jsx)(o,{className:`mr-1.5 h-4 w-4`}),` `,D.id?`Save changes`:`Create rule`]}),(0,W.jsx)(x,{className:`h-10`,variant:`outline`,onClick:()=>{O(null),ne?.()},children:`Cancel`})]})]}),R&&(0,W.jsx)(fe,{onClose:()=>z(null),children:(0,W.jsx)(oe,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,fixedWorkspaceName:e,multiple:R.target!==`storeFolder`&&!(R.target===`condition`&&D?.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)})}),!p&&(le?(0,W.jsx)(`p`,{className:`rounded-xl border p-6 text-center text-sm text-muted-foreground`,children:`Loading…`}):y.length===0?!k&&!D&&(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…”.`})]}),G]}):(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)(m,{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))})]}),Ye.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)(v,{className:`h-4 w-4`}),` Other rules`]}),(0,W.jsx)(`div`,{className:`space-y-3`,children:Ye.map(e=>(0,W.jsx)(Xe,{rule:e},e.id))})]})]}))]})}var kt=new Map;function At(e,t,n,r,i,a){let o=JSON.stringify([t,n,r,a]),s=kt.get(o);if(s)return s;let c=(async()=>{let o=e({title:`Resyncing…`,description:r});try{for(a?await ce(t,n,r,a):await le(t,n,r);;){let e=await se(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 kt.set(o,c),c.finally(()=>{kt.get(o)===c&&kt.delete(o)}).catch(()=>{}),c}export{Se as A,Ne as C,Ee as D,D as E,xe as F,k as M,Me as N,ke as O,_e as P,ve as S,he as T,je as _,qe as a,we as b,Ge as c,Pe as d,I as f,R as g,A as h,Je as i,Re as j,ze as k,F as l,Ce as m,Ot as n,Ye as o,De as p,Xe as r,Ke as s,At as t,z as u,O as v,N as w,Oe as x,Be as y};
|