@promptowl/contextnest-community 1.25.0 → 1.26.0
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/API.md +68 -8
- package/CONFIGURATION.md +572 -116
- package/README.md +3 -2
- package/dist/{chunk-32SZCH36.js → chunk-2QOJE7A5.js} +4 -4
- package/dist/{chunk-2KHM5C7V.js → chunk-DGPTJXIV.js} +13 -15
- package/dist/chunk-I5EDEZBQ.js +523 -0
- package/dist/{chunk-TI7HMP64.js → chunk-IEAWRHMV.js} +2 -2
- package/dist/{chunk-DTLMBF4W.js → chunk-M6PGYMBD.js} +15 -8
- package/dist/{chunk-F66VCBLA.js → chunk-PICUHQEM.js} +51 -2
- package/dist/{chunk-KPGNZLZL.js → chunk-RPGFHESR.js} +1 -1
- package/dist/{chunk-7FROMOZM.js → chunk-SWA5M5XX.js} +68 -544
- package/dist/{chunk-JDAOA5KP.js → chunk-TRSGPS27.js} +39 -14
- package/dist/{engine-TER6FDBP.js → engine-QNMFDIBV.js} +3 -2
- package/dist/{external-edit-service-CAGENHDJ.js → external-edit-service-4MEGPT4D.js} +4 -3
- package/dist/{grants-service-2OTFS7EH.js → grants-service-24GLUBY4.js} +2 -2
- package/dist/index.js +911 -263
- package/dist/invited-user-AM6A3WGO.js +12 -0
- package/dist/{migrations.postgres-23VJJJJX.js → migrations.postgres-HGSQ7IA5.js} +4 -0
- package/dist/{review-service-4G2XUFS6.js → review-service-2EWN7WWO.js} +7 -6
- package/dist/{stewardship-service-S22V2JKG.js → stewardship-service-TDZUC2Q6.js} +4 -3
- package/dist/{version-service-X4FAG2OZ.js → version-service-C3JTZLJH.js} +4 -3
- package/dist/web3/assets/ActivityTracePage-DzwWIjjx.js +1 -0
- package/dist/web3/assets/{AgentDocsPage-Dkhgb1hk.js → AgentDocsPage-ixP2UdAE.js} +1 -1
- package/dist/web3/assets/CollaboratorManager-C9VAXZ0h.js +1 -0
- package/dist/web3/assets/CollaboratorsTab-tq4ZTexH.js +1 -0
- package/dist/web3/assets/DocumentEditor-C2CP2fiE.js +36 -0
- package/dist/web3/assets/DocumentsTab-Mh7KxUoB.js +6 -0
- package/dist/web3/assets/ExternalEditsTab-B_CWKXZ_.js +1 -0
- package/dist/web3/assets/{MarkdownEditor-Dfk5uIE5.js → MarkdownEditor-CKh4WSn-.js} +136 -131
- package/dist/web3/assets/MarkdownEditor-ndtIx5x0.css +1 -0
- package/dist/web3/assets/NestPageHeader-Cizo8nUi.js +1 -0
- package/dist/web3/assets/NestView-EW-sraEb.js +73 -0
- package/dist/web3/assets/OverviewTab-CjidsMX_.js +6 -0
- package/dist/web3/assets/PersonCombobox-BKI7dff4.js +1 -0
- package/dist/web3/assets/{ReviewActions-BXDTDPp1.js → ReviewActions-CS8JXgXF.js} +2 -2
- package/dist/web3/assets/ReviewTab-CwVrXzw5.js +1 -0
- package/dist/web3/assets/StewardsTab-C-iP6gnh.js +1 -0
- package/dist/web3/assets/SubmitForReviewModal-Biq3m79i.js +1 -0
- package/dist/web3/assets/{alert-dialog-4SiLKlz8.js → alert-dialog-BvF3NFr7.js} +2 -2
- package/dist/web3/assets/{arrow-left-BAgIocLn.js → arrow-left-CWIsv-sG.js} +1 -1
- package/dist/web3/assets/backlinks-Cqcn7n1J.js +19 -0
- package/dist/web3/assets/boxes-ClbgQqG2.js +6 -0
- package/dist/web3/assets/{chevron-left-XR4ReJ9Z.js → chevron-left-CK_ZPFm9.js} +1 -1
- package/dist/web3/assets/{circle-check-CSkZUEFK.js → circle-check-Bw_aTXiH.js} +1 -1
- package/dist/web3/assets/{circle-x-in2o3aHU.js → circle-x-DkIG68H7.js} +1 -1
- package/dist/web3/assets/{code-xml-pPQgdctI.js → code-xml-BlR7EN6l.js} +1 -1
- package/dist/web3/assets/{corner-down-right-CuxZWscX.js → corner-down-right-DSVxK3tf.js} +1 -1
- package/dist/web3/assets/count-skeleton-DToLM74B.js +1 -0
- package/dist/web3/assets/{earth-CXOcThqn.js → earth-BXhVPvCR.js} +1 -1
- package/dist/web3/assets/{file-exclamation-point-CSphs1VD.js → file-exclamation-point-BevGZgtj.js} +1 -1
- package/dist/web3/assets/{folder-input-BAwK9tFL.js → folder-input-m8UBV4fA.js} +1 -1
- package/dist/web3/assets/{index-A0_ymcqL.js → index-BOVYgMvj.js} +1 -1
- package/dist/web3/assets/index-DVnaYqj9.css +1 -0
- package/dist/web3/assets/index-WYDmEOfO.js +404 -0
- package/dist/web3/assets/page-B6pkc9cd.js +2 -0
- package/dist/web3/assets/page-BJrFCKXB.js +1 -0
- package/dist/web3/assets/page-Bgy9Ng9p.js +1 -0
- package/dist/web3/assets/page-C2zoxumw.js +1 -0
- package/dist/web3/assets/page-CJWO06dN.js +1 -0
- package/dist/web3/assets/page-CptuAPJc.js +6 -0
- package/dist/web3/assets/page-DPY01SOj.js +1 -0
- package/dist/web3/assets/page-Dea2SblF.js +9 -0
- package/dist/web3/assets/page-Deq6IKiN.js +6 -0
- package/dist/web3/assets/page-Dfjg8p7Z.js +1 -0
- package/dist/web3/assets/{page-xzYqkBUP.js → page-Dh57L0RG.js} +5 -5
- package/dist/web3/assets/page-Dwbp4Seu.js +6 -0
- package/dist/web3/assets/{page-CUjuSs5Q.js → page-DzKwP5Ds.js} +3 -3
- package/dist/web3/assets/page-YxjrE5b5.js +45 -0
- package/dist/web3/assets/{page-title-BkqlUA0j.js → page-title-DVq4qvMR.js} +1 -1
- package/dist/web3/assets/{play-B8xE9j5f.js → play-CXhS6Pgq.js} +1 -1
- package/dist/web3/assets/{send-CvAgOUPG.js → send-DdfwnIrj.js} +1 -1
- package/dist/web3/assets/{settings-EY4A_DYv.js → settings-DKX0Q4gO.js} +1 -1
- package/dist/web3/assets/{share-2-vGmZUl90.js → share-2-CxmXRt58.js} +1 -1
- package/dist/web3/assets/{tag-Br_y1f00.js → tag-DeYC_mRv.js} +1 -1
- package/dist/web3/assets/{trash-2-B4hRXo-p.js → trash-2-B0HyPTnI.js} +1 -1
- package/dist/web3/assets/{user-plus-4CTYEkd3.js → user-plus-Ckm_Isyc.js} +1 -1
- package/dist/web3/assets/{x-qxt1WrUi.js → x-mNtADYHc.js} +1 -1
- package/dist/web3/assets/{zap-BcsKR0ef.js → zap-D2ifcnYb.js} +1 -1
- package/dist/web3/index.html +2 -2
- package/package.json +3 -2
- package/dist/client-D44ZHDTJ.js +0 -11
- package/dist/keys-CTOGAG3W.js +0 -20
- package/dist/web3/assets/ActivityTracePage-D2iIbEph.js +0 -1
- package/dist/web3/assets/CollaboratorManager-Bo81D--Q.js +0 -1
- package/dist/web3/assets/CollaboratorsTab-DRCitQuX.js +0 -1
- package/dist/web3/assets/DocumentEditor-DV2WHYbj.js +0 -36
- package/dist/web3/assets/DocumentsTab-BUxBCN8o.js +0 -6
- package/dist/web3/assets/ExternalEditsTab-kIBimZyE.js +0 -1
- package/dist/web3/assets/MarkdownEditor-CsVusP2d.css +0 -1
- package/dist/web3/assets/NestPageHeader-yOK-OIYZ.js +0 -1
- package/dist/web3/assets/NestView-DwIagxwJ.js +0 -68
- package/dist/web3/assets/OverviewTab-DFOFMVyE.js +0 -1
- package/dist/web3/assets/PersonCombobox-D350WlrJ.js +0 -1
- package/dist/web3/assets/ReasonDialog-CN3ECAnQ.js +0 -1
- package/dist/web3/assets/ReviewTab-CZewAYiz.js +0 -1
- package/dist/web3/assets/StewardsTab-AagNWcWS.js +0 -1
- package/dist/web3/assets/SubmitForReviewModal-BOZJxwRN.js +0 -1
- package/dist/web3/assets/backlinks-Cb8Uf8mw.js +0 -24
- package/dist/web3/assets/card-UDyMRcps.js +0 -1
- package/dist/web3/assets/count-skeleton-DBWCDhRy.js +0 -1
- package/dist/web3/assets/dates-BCxbm4_q.js +0 -1
- package/dist/web3/assets/index-B5hLclEq.js +0 -389
- package/dist/web3/assets/index-DrUAtoQM.css +0 -1
- package/dist/web3/assets/page-BHD4beun.js +0 -1
- package/dist/web3/assets/page-BSYUXYmO.js +0 -11
- package/dist/web3/assets/page-BYc2DIux.js +0 -45
- package/dist/web3/assets/page-BfibLg8e.js +0 -1
- package/dist/web3/assets/page-CGe8MtUu.js +0 -9
- package/dist/web3/assets/page-CIgPJmG6.js +0 -2
- package/dist/web3/assets/page-Ck31nx9b.js +0 -1
- package/dist/web3/assets/page-Cpdj_11Y.js +0 -1
- package/dist/web3/assets/page-D0sN3GO6.js +0 -1
- package/dist/web3/assets/page-DEpH91X2.js +0 -1
- package/dist/web3/assets/page-l8-B7CGt.js +0 -1
- package/dist/web3/assets/page-mnSHmk6A.js +0 -6
- package/dist/web3/assets/refresh-cw-CsCtmWwX.js +0 -6
- package/dist/web3/assets/scroll-area-CbcH6yrZ.js +0 -1
- package/dist/web3/assets/scroll-area-dRWncRqa.css +0 -1
- package/dist/web3/assets/select-DrL0mpRN.js +0 -6
- package/dist/web3/assets/triangle-alert-CsYGyfGZ.js +0 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j as e,
|
|
1
|
+
import{j as e,w as l}from"./index-WYDmEOfO.js";function x({icon:s,title:r,description:t,actions:a,className:i}){return e.jsxs("div",{className:l("mb-4",i),"data-testid":"page-title",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("h1",{className:"flex items-center gap-2 text-2xl font-semibold tracking-tight",children:[s&&e.jsx(s,{className:"h-6 w-6 shrink-0 text-muted-foreground"}),r]}),a&&e.jsx("div",{className:"ml-auto flex shrink-0 items-center gap-2",children:a})]}),t&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:t})]})}export{x as P};
|
package/dist/web3/index.html
CHANGED
|
@@ -5,8 +5,8 @@
|
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
6
|
<title>ContextNest</title>
|
|
7
7
|
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🪺</text></svg>" />
|
|
8
|
-
<script type="module" crossorigin src="/assets/index-
|
|
9
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
8
|
+
<script type="module" crossorigin src="/assets/index-WYDmEOfO.js"></script>
|
|
9
|
+
<link rel="stylesheet" crossorigin href="/assets/index-DVnaYqj9.css">
|
|
10
10
|
</head>
|
|
11
11
|
<body class="bg-background text-foreground antialiased">
|
|
12
12
|
<div id="root"></div>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@promptowl/contextnest-community",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.26.0",
|
|
4
4
|
"description": "ContextNest Community Edition — self-hosted context governance server for AI workflows. Commercial software by Promptowl LLC.",
|
|
5
5
|
"private": false,
|
|
6
6
|
"type": "module",
|
|
@@ -69,9 +69,10 @@
|
|
|
69
69
|
]
|
|
70
70
|
},
|
|
71
71
|
"dependencies": {
|
|
72
|
+
"@aws-sdk/client-sesv2": "3.1139.0",
|
|
72
73
|
"@hono/node-server": "^1.13.8",
|
|
73
74
|
"@modelcontextprotocol/sdk": "^1.12.1",
|
|
74
|
-
"@promptowl/contextnest-engine": "^2.
|
|
75
|
+
"@promptowl/contextnest-engine": "^2.8.0",
|
|
75
76
|
"@tanstack/react-query": "^5.101.4",
|
|
76
77
|
"bcryptjs": "^3.0.3",
|
|
77
78
|
"better-sqlite3": "^11.8.2",
|
package/dist/client-D44ZHDTJ.js
DELETED
package/dist/keys-CTOGAG3W.js
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
MAX_API_KEYS_PER_USER,
|
|
3
|
-
generateApiKey,
|
|
4
|
-
getKeyPrefix,
|
|
5
|
-
hashApiKey,
|
|
6
|
-
hashPassword,
|
|
7
|
-
parseBearerToken,
|
|
8
|
-
verifyKeyRequest,
|
|
9
|
-
verifyPassword
|
|
10
|
-
} from "./chunk-F66VCBLA.js";
|
|
11
|
-
export {
|
|
12
|
-
MAX_API_KEYS_PER_USER,
|
|
13
|
-
generateApiKey,
|
|
14
|
-
getKeyPrefix,
|
|
15
|
-
hashApiKey,
|
|
16
|
-
hashPassword,
|
|
17
|
-
parseBearerToken,
|
|
18
|
-
verifyKeyRequest,
|
|
19
|
-
verifyPassword
|
|
20
|
-
};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r as s,dD as z,dE as D,j as e,B as m,dF as F,bw as _,I as q,L as K,bx as M}from"./index-B5hLclEq.js";import{P as U}from"./page-title-BkqlUA0j.js";import{S as B,a as V,b as $,c as G,d as p}from"./select-DrL0mpRN.js";import{f as Z}from"./dates-BCxbm4_q.js";import{f as y}from"./client-attribution-BraarYaP.js";import{A as H}from"./arrow-left-BAgIocLn.js";import{R as I}from"./refresh-cw-CsCtmWwX.js";import{C as J}from"./chevron-left-XR4ReJ9Z.js";const i=25;function ae({onBack:f,nestId:a}){const[g,C]=s.useState([]),[o,k]=s.useState(0),[l,h]=s.useState(0),[n,N]=s.useState(!0),[v,w]=s.useState(null),[c,E]=s.useState("all"),[d,T]=s.useState(""),[u,b]=s.useState(""),x=s.useRef(0);s.useEffect(()=>{const t=setTimeout(()=>b(d),300);return()=>clearTimeout(t)},[d]),s.useEffect(()=>{h(0)},[c,u]);const j=s.useCallback(async()=>{const t=++x.current;N(!0),w(null);try{const r={kind:c==="all"?void 0:c,user:u.trim()||void 0,limit:i,offset:l*i},S=a?await z(a,r):await D(r);if(t!==x.current)return;C(S.events),k(S.total)}catch(r){if(t!==x.current)return;w((r==null?void 0:r.message)||"Failed to load trace")}finally{t===x.current&&N(!1)}},[c,u,l,a]);s.useEffect(()=>{j()},[j]);const A=o===0?0:l*i+1,P=Math.min((l+1)*i,o),R=l>0,L=(l+1)*i<o;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[f&&e.jsxs(m,{variant:"ghost",size:"sm",onClick:f,className:"mt-1",children:[e.jsx(H,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsx(U,{icon:F,title:"Activity trace",className:"mb-0 flex-1",actions:e.jsxs(e.Fragment,{children:[e.jsxs(B,{value:c,onValueChange:t=>E(t),children:[e.jsx(V,{className:"h-8 w-28",children:e.jsx($,{})}),e.jsxs(G,{children:[e.jsx(p,{value:"all",children:"All"}),e.jsx(p,{value:"api",children:"API"}),e.jsx(p,{value:"mcp",children:"MCP"})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(_,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground pointer-events-none"}),e.jsx(q,{value:d,onChange:t=>T(t.target.value),onKeyDown:t=>t.key==="Enter"&&b(d),placeholder:"Filter by user…",className:"h-8 pl-8 w-48"})]}),e.jsx(m,{variant:"outline",size:"sm",onClick:j,disabled:n,children:n?e.jsx(K,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(I,{className:"h-3.5 w-3.5"})})]})})]}),v&&e.jsx("p",{className:"text-sm text-red-500",children:v}),e.jsx("div",{className:"border border-border rounded-lg overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"bg-muted/50 text-muted-foreground",children:e.jsxs("tr",{className:"[&>th]:px-3 [&>th]:py-2 [&>th]:text-left [&>th]:font-medium",children:[e.jsx("th",{children:"Time"}),e.jsx("th",{children:"Kind"}),e.jsx("th",{children:"Call"}),!a&&e.jsx("th",{children:"Nest"}),e.jsx("th",{children:"Caller"}),e.jsx("th",{children:"Status"}),e.jsx("th",{className:"text-right",children:"ms"})]})}),e.jsxs("tbody",{children:[g.length===0&&!n&&e.jsx("tr",{children:e.jsx("td",{colSpan:a?6:7,className:"px-3 py-8 text-center text-muted-foreground",children:"No activity recorded yet."})}),g.map(t=>e.jsxs("tr",{className:"border-t border-border [&>td]:px-3 [&>td]:py-1.5",children:[e.jsx("td",{className:"whitespace-nowrap text-muted-foreground",children:Z(t.ts)}),e.jsx("td",{children:e.jsx("span",{className:t.kind==="mcp"?"rounded bg-violet-50 text-violet-700 px-1.5 py-0.5":"rounded bg-blue-50 text-blue-700 px-1.5 py-0.5",children:t.kind})}),e.jsx("td",{className:"font-mono max-w-[340px] truncate",title:t.path||t.tool||"",children:t.kind==="mcp"?t.tool:`${t.method} ${t.path}`}),!a&&e.jsx("td",{className:"font-mono max-w-[120px] truncate",title:t.nest_id||"",children:t.nest_id||"—"}),e.jsxs("td",{className:"max-w-[180px] truncate",title:t.caller||"",children:[t.caller||"—",t.client&&e.jsx("div",{className:"text-[11px] text-muted-foreground truncate font-mono",title:y(t.client),children:y(t.client)})]}),e.jsx("td",{children:t.status==null?"—":e.jsx("span",{className:t.status>=400?"text-red-600":"text-green-700",children:t.status})}),e.jsx("td",{className:"text-right text-muted-foreground",children:t.duration_ms??"—"})]},t.id))]})]})}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Rolling retention window (server setting), newest first."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{children:[A,"–",P," of ",o]}),e.jsx(m,{variant:"outline",size:"sm",className:"h-7 px-2",disabled:!R||n,onClick:()=>h(t=>Math.max(t-1,0)),children:e.jsx(J,{className:"h-3.5 w-3.5"})}),e.jsx(m,{variant:"outline",size:"sm",className:"h-7 px-2",disabled:!L||n,onClick:()=>h(t=>t+1),children:e.jsx(M,{className:"h-3.5 w-3.5"})})]})]})]})}export{ae as ActivityTracePage};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r as n,O as ve,u as de,W as ge,j as e,J as M,ah as fe,ai as be,L as z,a9 as te,aa as ie,ab as le,aj as je,ak as ye,am as we,C as Ne,bC as Ce,a8 as Se,bQ as Ae,A as Te,K as De,a as ke,U as ne,B as A,e as _,i as E,N as Pe,f as re,bB as Fe,dM as Re,M as Le,dN as Me,dO as ze}from"./index-B5hLclEq.js";import{S as X,a as Z,b as ee,c as se,d as O}from"./select-DrL0mpRN.js";import{A as Oe,a as Be,b as Ue,c as Ve,d as $e,e as qe,f as Qe,g as We}from"./alert-dialog-4SiLKlz8.js";import{T as He}from"./scroll-area-CbcH6yrZ.js";import{x as Ie,w as ce,y as Ke,S as Ye}from"./MarkdownEditor-Dfk5uIE5.js";import{P as _e}from"./PersonCombobox-D350WlrJ.js";import{U as Ee}from"./user-plus-4CTYEkd3.js";import{S as Ge}from"./share-2-vGmZUl90.js";import{T as oe}from"./trash-2-B4hRXo-p.js";const G=[{value:"private",label:"Private"},{value:"org",label:"Organization"},{value:"public",label:"Public"}];function ns({nestId:d,onChanged:B,onError:l,variant:W="card"}){var S,V,$,q;const[x,p]=n.useState("private"),v=x==="public",f=x==="org",[N,U]=n.useState(!1),[g,b]=n.useState(null),{sharedDeployment:T}=ve(),j={sharedDeployment:T},D=de(),[C,k]=n.useState(""),P=ge(d),y=(V=(S=P.data)==null?void 0:S.nest)==null?void 0:V.visibility,w=((q=($=P.data)==null?void 0:$.nest)==null?void 0:q.description)??"";n.useEffect(()=>{y&&p(y)},[y]);const F=async(a,h)=>{const u=x;p(a),U(!0),l==null||l(null);try{const i=await Ae(d,a,h);if(p(i.visibility||a),i.visibility!==a){l==null||l("Server did not accept the change. You may not have admin access to this nest.");return}B()}catch(i){p(u),l==null||l((i==null?void 0:i.message)||"Failed to change visibility")}finally{U(!1)}},R=async a=>{if(a!==x){if(a!=="private"&&Ke(a,j)){k(w),b(a);return}await F(a)}},c=async()=>{const a=g;if(!a)return;b(null);const h=C.trim();if(h&&h!==w.trim())try{await Ce(d,{description:h}),D.invalidateQueries({queryKey:Se.nest(d)})}catch(u){l==null||l((u==null?void 0:u.message)||"Failed to save the description")}await F(a,!0)},o=g?Ie(g,j):null,L=e.jsx(Oe,{open:g!==null,onOpenChange:a=>{a||b(null)},children:e.jsxs(Be,{children:[e.jsxs(Ue,{children:[e.jsx(Ve,{children:o==null?void 0:o.title}),e.jsx($e,{children:o==null?void 0:o.body})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(M,{htmlFor:"visibility-description",className:"text-xs",children:w.trim()?"Description readers will see":"This nest has no description — readers will only see its name. Add one? (optional)"}),e.jsx(He,{id:"visibility-description",value:C,onChange:a=>k(a.target.value),placeholder:"What this nest is for, and who it's meant for",rows:2,"data-testid":"visibility-description"})]}),e.jsxs(qe,{children:[e.jsx(Qe,{children:"Cancel"}),e.jsx(We,{onClick:()=>void c(),"data-testid":"visibility-confirm",children:o==null?void 0:o.confirm})]})]})});if(W==="compact"){if(!y)return null;const a=v?te:f?ie:le,h=G.find(i=>i.value===x)??G[0],u=ce(x,j);return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(be,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:N,className:"inline-flex h-8 items-center gap-1 rounded-md px-2 text-xs text-muted-foreground hover:bg-accent hover:text-accent-foreground disabled:opacity-60",title:`${h.label} — ${u}. Click to change.`,"aria-label":`Nest visibility: ${h.label}`,"data-testid":"nest-visibility-compact",children:[N?e.jsx(z,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(a,{className:`h-3.5 w-3.5 ${v?"text-green-600":f?"text-blue-600":""}`}),e.jsx("span",{className:"hidden sm:inline",children:h.label}),e.jsx(je,{className:"h-3 w-3 opacity-60"})]})}),e.jsx(ye,{align:"end",className:"w-64",children:G.map(i=>e.jsxs(we,{onClick:()=>void R(i.value),className:"flex items-start gap-2",children:[i.value===x?e.jsx(Ne,{className:"mt-0.5 h-4 w-4 shrink-0"}):e.jsx("span",{className:"w-4 shrink-0"}),e.jsxs("span",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm",children:i.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:ce(i.value,j)})]})]},i.value))})]}),L]})}return e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(M,{className:"flex items-center gap-2 text-sm font-medium",children:[v?e.jsx(te,{className:"h-4 w-4 text-green-600"}):f?e.jsx(ie,{className:"h-4 w-4 text-blue-600"}):e.jsx(le,{className:"h-4 w-4"}),v?"Public":f?"Organization":"Private"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v?T?"Anyone on the internet with the URL can read this nest — including every account on this server, other organizations too. Editing still requires being added below.":"Anyone on the internet with the URL can read this nest. Editing still requires being added below.":f?T?"Every account on this server can read this nest — other organizations included, not just yours. Editing still requires being added below.":"Everyone signed in to this deployment can read this nest. Editing still requires being added below.":"Only people added below (and the owner) can see this nest."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[N&&e.jsx(z,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground"}),e.jsxs(X,{value:x,onValueChange:a=>void R(a),disabled:N,children:[e.jsx(Z,{className:"h-8 w-[150px]","aria-label":"Nest visibility",children:e.jsx(ee,{})}),e.jsxs(se,{children:[e.jsx(O,{value:"private",children:"Private"}),e.jsx(O,{value:"org",children:"Organization"}),e.jsx(O,{value:"public",children:"Public"})]})]})]})]}),L]})}const J=[{value:"read",label:"Viewer",hint:"Read only"},{value:"write",label:"Editor",hint:"Read and edit documents"},{value:"admin",label:"Admin",hint:"Full access except deleting the nest"}],Q={read:1,write:2,admin:3,owner:4};function rs({nestId:d,nestName:B,onChanged:l,currentUserEmail:W,callerPermission:x="admin",showTeams:p=!1}){const v=(W||"").toLowerCase(),f=Q[x]??Q.read,N=f>=Q.admin,U=J.filter(s=>Q[s.value]<=f),[g,b]=n.useState([]),[T,j]=n.useState(!0),D=de(),[C,k]=n.useState(""),[P,y]=n.useState("read"),[w,F]=n.useState(!1),[R,c]=n.useState(null),[o,L]=n.useState("person"),[S,V]=n.useState([]),[$,q]=n.useState([]),[a,h]=n.useState(""),[u,i]=n.useState(!1),H=async()=>{j(!0);try{const{collaborators:s}=await D.fetchQuery(E.collaborators(d));b(s)}catch(s){c((s==null?void 0:s.message)||"Failed to load collaborators")}finally{j(!1)}},I=async()=>{try{const[s,r]=await Promise.all([D.fetchQuery(E.nestTeams(d)),D.fetchQuery(E.teamList()).catch(()=>({teams:[]}))]);V(s.teams),q(r.teams)}catch(s){c((s==null?void 0:s.message)||"Failed to load teams")}};n.useEffect(()=>{H(),p&&I()},[d]);const ae=async()=>{const s=C.trim();if(s){if(!Fe(s)){c("Enter a valid email address.");return}F(!0),c(null);try{await Re(d,{email:s,permission:P}),k(""),y("read"),await H(),l()}catch(r){c((r==null?void 0:r.message)||"Failed to add collaborator")}finally{F(!1)}}},me=s=>{s.preventDefault(),ae()},K=$.filter(s=>!S.some(r=>r.teamId===s.id)),he=async()=>{if(a){i(!0),c(null);try{await Pe(d,a),h(""),re.success("Team shared"),await I(),l()}catch(s){c((s==null?void 0:s.message)||"Failed to share team")}finally{i(!1)}}},ue=async(s,r)=>{if(window.confirm(`Unshare "${r}" from "${B}"? Its members lose the access this share granted.`)){i(!0),c(null);try{await Le(d,s),await I(),l()}catch(m){c((m==null?void 0:m.message)||"Failed to unshare team")}finally{i(!1)}}},xe=async(s,r)=>{const t=g.find(m=>m.id===s);if(t&&(t.email||"").toLowerCase()===v){re.error("You can't change your own access level.");return}c(null),b(m=>m.map(Y=>Y.id===s?{...Y,permission:r}:Y));try{await Me(d,s,r),l()}catch(m){c((m==null?void 0:m.message)||"Failed to update permission"),await H()}},pe=async s=>{if(window.confirm(`Remove ${s.email||"this collaborator"}'s access to "${B}"? They keep their account; only their access to this nest is revoked.`)){c(null);try{await ze(d,s.id),b(t=>t.filter(m=>m.id!==s.id)),l()}catch(t){c((t==null?void 0:t.message)||"Failed to remove collaborator")}}};return e.jsxs("div",{className:"space-y-4",children:[R&&e.jsxs(Te,{variant:"destructive",children:[e.jsx(De,{className:"h-4 w-4"}),e.jsx(ke,{children:R})]}),e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(M,{className:"flex items-center gap-2 text-sm font-medium",children:p&&o==="team"?e.jsxs(e.Fragment,{children:[e.jsx(ne,{className:"h-4 w-4"}),"Add a team"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ee,{className:"h-4 w-4"}),"Add a person"]})}),p&&e.jsxs("div",{className:"flex gap-1",children:[e.jsx(A,{type:"button",size:"sm",variant:o==="person"?"secondary":"ghost",className:"h-7 px-2 text-xs",onClick:()=>L("person"),children:"Person"}),e.jsx(A,{type:"button",size:"sm",variant:o==="team"?"secondary":"ghost",className:"h-7 px-2 text-xs",onClick:()=>L("team"),children:"Team"})]})]}),p&&o==="team"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx("div",{className:"flex-1",children:e.jsx(Ye,{value:a,onChange:h,options:K.map(s=>({value:s.id,label:s.name})),disabled:K.length===0,placeholder:K.length===0?"No teams available to share":"Select a team…",searchPlaceholder:"Search teams…",emptyText:"No teams match.",testId:"collab-team-select"})}),e.jsx(A,{onClick:he,disabled:u||!a,children:u?e.jsx(z,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ge,{className:"h-4 w-4 mr-1"}),"Share"]})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Every member gets the role you gave them on the Teams page. Manage members there."})]}):e.jsxs("form",{onSubmit:me,className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(_e,{value:C,onChange:k,onSubmit:ae,placeholder:"teammate@example.com",disabled:w,className:"flex-1",exclude:g.map(s=>s.email||"").filter(Boolean),testId:"collab-person-input"}),e.jsxs(X,{value:P,onValueChange:s=>y(s),children:[e.jsx(Z,{className:"w-full sm:w-[130px]",children:e.jsx(ee,{})}),e.jsx(se,{children:U.map(s=>e.jsx(O,{value:s.value,children:s.label},s.value))})]}),e.jsx(A,{type:"submit",disabled:w||!C.trim(),children:w?e.jsx(z,{className:"h-4 w-4 animate-spin"}):"Add"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"If they don't have an account yet, they'll get access when they register with this email."})]})]}),p&&S.length>0&&e.jsxs("div",{className:"rounded-lg border p-4 space-y-2",children:[e.jsxs(M,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(ne,{className:"h-4 w-4"}),"Teams with access"]}),e.jsx("div",{className:"space-y-1",children:S.map(s=>e.jsxs("div",{className:"flex items-center gap-2 py-1.5",children:[e.jsx("span",{className:"flex-1 min-w-0 truncate text-sm",children:s.teamName}),e.jsxs(_,{variant:"secondary",className:"text-[11px]",children:[s.members.length," member",s.members.length===1?"":"s"]}),e.jsx(A,{variant:"ghost",size:"sm",disabled:u,onClick:()=>ue(s.teamId,s.teamName),title:"Unshare team",className:"text-destructive hover:text-destructive hover:bg-destructive/10",children:e.jsx(oe,{className:"h-3.5 w-3.5"})})]},s.teamId))})]}),e.jsxs("div",{className:"rounded-lg border p-4 space-y-2",children:[e.jsx(M,{className:"text-sm font-medium",children:"People with access"}),T?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(z,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):g.length===0?e.jsx("p",{className:"text-xs text-muted-foreground py-2",children:"Nobody's been added yet. The owner always has full access."}):e.jsx("div",{className:"space-y-1",children:g.map(s=>{var r;return e.jsxs("div",{className:"flex items-center gap-2 py-1.5","data-testid":`collaborator-row-${s.id}`,children:[e.jsx("span",{className:"flex-1 min-w-0 truncate text-sm",children:s.email||s.user_id}),(s.stewardRoles??[]).map(t=>e.jsx(_,{variant:"outline",className:"text-[10px] px-1.5 py-0 capitalize",title:"Steward role — manage in the Stewards tab",children:t},t)),N?e.jsxs(e.Fragment,{children:[e.jsxs(X,{value:s.permission,disabled:(s.email||"").toLowerCase()===v,onValueChange:t=>xe(s.id,t),children:[e.jsx(Z,{className:"w-[120px] h-8",title:(s.email||"").toLowerCase()===v?"You can't change your own access level":void 0,children:e.jsx(ee,{})}),e.jsx(se,{children:J.map(t=>e.jsx(O,{value:t.value,children:t.label},t.value))})]}),(s.email||"").toLowerCase()!==v&&e.jsx(A,{variant:"ghost",size:"sm",onClick:()=>pe(s),title:"Remove access",className:"text-destructive hover:text-destructive hover:bg-destructive/10",children:e.jsx(oe,{className:"h-3.5 w-3.5"})})]}):e.jsx(_,{variant:"secondary",className:"text-[11px] capitalize",children:((r=J.find(t=>t.value===s.permission))==null?void 0:r.label)??s.permission})]},s.id)})})]})]})}export{rs as C,ns as N};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{j as s,f as c}from"./index-B5hLclEq.js";import{N as p,C as h}from"./CollaboratorManager-Bo81D--Q.js";import{C as x,a as f,c as u,b as j,d as b}from"./card-UDyMRcps.js";import"./select-DrL0mpRN.js";import"./alert-dialog-4SiLKlz8.js";import"./scroll-area-CbcH6yrZ.js";import"./MarkdownEditor-Dfk5uIE5.js";import"./zap-BcsKR0ef.js";import"./triangle-alert-CsYGyfGZ.js";import"./index-A0_ymcqL.js";import"./arrow-left-BAgIocLn.js";import"./trash-2-B4hRXo-p.js";import"./x-qxt1WrUi.js";import"./PersonCombobox-D350WlrJ.js";import"./user-plus-4CTYEkd3.js";import"./share-2-vGmZUl90.js";function R({nestId:r,nestName:t,canManage:a,canManageGovernance:i,stewardshipEnabled:n,currentUserEmail:l,callerPermission:m,onOpenSettings:d,onChanged:e}){return s.jsxs(x,{children:[s.jsxs(f,{className:"pb-3",children:[s.jsx(u,{className:"text-lg",children:"Collaborators"}),s.jsxs(j,{className:"space-y-1",children:[s.jsxs("span",{className:"block",children:[s.jsx("strong",{className:"font-medium text-foreground",children:"Who can access this nest"})," ","— visibility and access for people and teams. Sharing grants viewer, editor or admin access."]}),s.jsxs("span",{className:"block",children:[s.jsx("strong",{className:"font-medium text-foreground",children:"Stewardship"})," — sharing does not make anyone a steward.",n?" Stewards are assigned on the Stewards tab.":i?s.jsxs(s.Fragment,{children:[" ","Turn on Stewardship & Approval Workflow in"," ",s.jsx("button",{type:"button",onClick:d,className:"font-medium text-foreground underline underline-offset-2 hover:no-underline",children:"Nest settings"})," ","to use stewards."]}):" Stewardship & Approval Workflow is off for this nest — an owner or admin can turn it on in Nest settings."]})]})]}),s.jsxs(b,{className:"space-y-4",children:[a&&s.jsx(p,{nestId:r,onChanged:e,onError:o=>o&&c.error(o)}),s.jsx(h,{nestId:r,nestName:t,onChanged:e,currentUserEmail:l,callerPermission:m,showTeams:!0})]})]})}export{R as CollaboratorsTab};
|
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
import{c as Ts,r as a,j as e,A as De,a as $e,B as y,L as ee,b as fi,g as pi,d as gi,I as Ia,e as Nt,t as bi,f as k,u as Ds,h as wi,i as ye,k as er,l as Ss,m as vi,n as tr,o as sr,p as nr,q as ar,E as ji,s as mn,F as Js,U as $s,v as yi,C as Pt,w as Is,D as bt,x as wt,y as vt,z as jt,G as en,H as yt,J as Ni,K as Fe,M as ki,N as Si,O as hn,T as Ci,P as Ri,Q as ga,R as ba,S as Ti,V as rr,W as Di,X as $i,Y as Ei,Z as Ai,_ as Li,$ as Mi,a0 as Fi,a1 as tn,a2 as wa,a3 as Pi,a4 as Ks,a5 as va,a6 as ja,a7 as Vi,a8 as Oi,a9 as qi,aa as zi,ab as _i,ac as Hi,ad as Bi,ae as Xs,af as Wi,ag as ya,ah as ir,ai as lr,aj as or,ak as cr,al as dr,am as It,an as ur,ao as Ui,ap as Qi,aq as Gi,ar as Ki,as as Xi,at as Na,au as Yi,av as Zi,aw as Ji,ax as Ii,ay as ka,az as el,aA as tl,aB as Sa,aC as sl,aD as nl}from"./index-B5hLclEq.js";import{f as Cs,r as Ca}from"./dates-BCxbm4_q.js";import{T as sn,p as al,t as rl,U as il,a as ll,r as ol,u as cl,b as Ys,l as dl,c as ul,H as ml,O as mr,D as nn,d as hl,g as xl,S as fl,i as pl,e as hr,m as gl,Q as Ra,f as bl,h as wl,W as Ta,j as vl,k as jl,n as yl,P as Nl,o as kl,M as Sl,q as Cl,L as Rl,F as Tl,s as Dl}from"./MarkdownEditor-Dfk5uIE5.js";import{N as xr,C as $l}from"./CollaboratorManager-Bo81D--Q.js";import{S as El,a as Al,b as Ll,c as Ml,d as Da}from"./select-DrL0mpRN.js";import{D as fr,H as pr,R as xn,V as gr,e as an,f as Fl,s as Pl,S as Vl,P as Ol,r as ql,A as zl,u as _l}from"./backlinks-Cb8Uf8mw.js";import{P as Hl}from"./play-B8xE9j5f.js";import{T as Bl}from"./triangle-alert-CsYGyfGZ.js";import{T as Wl}from"./scroll-area-CbcH6yrZ.js";import"./card-UDyMRcps.js";import{A as rn}from"./arrow-left-BAgIocLn.js";import{C as es}from"./code-xml-pPQgdctI.js";import{R as ln}from"./refresh-cw-CsCtmWwX.js";import{M as Rs,R as Ul}from"./ReviewActions-BXDTDPp1.js";import{X as st}from"./x-qxt1WrUi.js";import{S as on}from"./send-CvAgOUPG.js";import{T as cn}from"./trash-2-B4hRXo-p.js";import{S as dn}from"./share-2-vGmZUl90.js";import{C as Ql}from"./circle-check-CSkZUEFK.js";import{C as Gl}from"./corner-down-right-CuxZWscX.js";import{A as Kl,a as Xl,b as Yl,c as Zl,d as Jl,e as Il,f as eo,g as to}from"./alert-dialog-4SiLKlz8.js";import{S as so}from"./SubmitForReviewModal-BOZJxwRN.js";import{R as no}from"./ReasonDialog-CN3ECAnQ.js";import{F as br}from"./file-exclamation-point-CSphs1VD.js";import{Z as $a}from"./zap-BcsKR0ef.js";import{F as Ea}from"./folder-input-BAwK9tFL.js";import"./index-A0_ymcqL.js";import"./PersonCombobox-D350WlrJ.js";import"./user-plus-4CTYEkd3.js";import"./client-attribution-BraarYaP.js";import"./circle-x-in2o3aHU.js";/**
|
|
2
|
-
* @license lucide-react v0.577.0 - ISC
|
|
3
|
-
*
|
|
4
|
-
* This source code is licensed under the ISC license.
|
|
5
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
-
*/const ao=[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["path",{d:"M11 18H8a2 2 0 0 1-2-2V9",key:"19pyzm"}]],Aa=Ts("git-compare",ao);/**
|
|
7
|
-
* @license lucide-react v0.577.0 - ISC
|
|
8
|
-
*
|
|
9
|
-
* This source code is licensed under the ISC license.
|
|
10
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
-
*/const ro=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M12 8v6",key:"1ib9pf"}],["path",{d:"M9 11h6",key:"1fldmi"}]],wr=Ts("message-square-plus",ro);/**
|
|
12
|
-
* @license lucide-react v0.577.0 - ISC
|
|
13
|
-
*
|
|
14
|
-
* This source code is licensed under the ISC license.
|
|
15
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
16
|
-
*/const io=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],La=Ts("save",io);/**
|
|
17
|
-
* @license lucide-react v0.577.0 - ISC
|
|
18
|
-
*
|
|
19
|
-
* This source code is licensed under the ISC license.
|
|
20
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
21
|
-
*/const lo=[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]],Ma=Ts("undo-2",lo);function oo({nestId:s,nodeId:r,pending:n,onResolved:o}){const[l,m]=a.useState(null),[x,u]=a.useState(!1),[h,f]=a.useState(""),[j,N]=a.useState(null),[v,g]=a.useState(null),w=async()=>{m("approve"),g(null);try{await fi(s,r,n.suggestion_id),o()}catch(A){g(A.message||"Approval failed")}finally{m(null)}},z=async()=>{if(!h.trim()){g("Rejection reason is required");return}m("reject"),g(null);try{await gi(s,r,n.suggestion_id,h.trim()),o()}catch(A){g(A.message||"Rejection failed")}finally{m(null)}},V=async()=>{if(j){N(null);return}m("view"),g(null);try{const{entry:A}=await pi(s,r,n.suggestion_id);N(A)}catch(A){g(A.message||"Failed to load diff")}finally{m(null)}};return e.jsxs(De,{className:"border-orange-300 bg-orange-50 dark:bg-orange-950/30",children:[e.jsx(br,{className:"h-4 w-4 text-orange-700 dark:text-orange-400"}),e.jsxs($e,{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("strong",{className:"text-orange-900 dark:text-orange-200",children:"This file was edited outside the app."})," ",e.jsxs("span",{className:"text-sm text-orange-800/90 dark:text-orange-300/90",children:["Detected ",Cs(n.detected_at)," ·"," ",e.jsx("code",{className:"text-xs",children:n.source}),". The displayed content is the last approved version; the on-disk change is staged for review."]})]}),v&&e.jsx("div",{className:"text-sm text-red-700 dark:text-red-400",children:v}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(y,{size:"sm",onClick:w,disabled:l!==null,"data-testid":"external-edit-approve",children:[l==="approve"?e.jsx(ee,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Approve change"]}),e.jsx(y,{size:"sm",variant:"outline",onClick:()=>u(A=>!A),disabled:l!==null,"data-testid":"external-edit-reject-toggle",children:"Reject"}),e.jsxs(y,{size:"sm",variant:"ghost",onClick:V,disabled:l!==null,"data-testid":"external-edit-view-diff",children:[l==="view"?e.jsx(ee,{className:"h-4 w-4 mr-2 animate-spin"}):null,j?"Hide diff":"View diff"]})]}),x&&e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsx(Wl,{value:h,onChange:A=>f(A.target.value),placeholder:"Reason for rejecting this external edit (required, kept in audit log)",rows:2,"data-testid":"external-edit-reject-reason"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(y,{size:"sm",variant:"destructive",onClick:z,disabled:l!==null||!h.trim(),"data-testid":"external-edit-reject-confirm",children:[l==="reject"?e.jsx(ee,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Confirm reject"]}),e.jsx(y,{size:"sm",variant:"ghost",onClick:()=>{u(!1),f("")},disabled:l!==null,children:"Cancel"})]})]}),(j==null?void 0:j.patch)&&e.jsx("div",{className:"pt-2",children:e.jsx(fr,{patch:j.patch})})]})]})}const ks=40,co=120,uo=/[^a-zA-Z0-9_:-]+/g,mo=s=>s.normalize("NFD").replace(new RegExp("\\p{Diacritic}","gu"),"");function Fa(s,r){const n=new Set(s.map(un)),o=[];for(const l of r){const m=un(l);n.has(m)||(n.add(m),o.push(l))}return o}function un(s){return vr(s).tag??s.trim().toLowerCase()}function vr(s){const r=s.trim().replace(/^#+/,"");if(!r)return{tag:null,note:null};const n=mo(r).replace(uo,"").replace(/^[^a-zA-Z]+|[_:-]+$/g,"").toLowerCase();return n?n.length>ks?{tag:n.slice(0,ks),note:`Tags are capped at ${ks} characters — "${r}" was shortened.`}:n!==r.toLowerCase()?{tag:n,note:`"${r}" was adjusted to "${n}".`}:{tag:n,note:null}:{tag:null,note:`"${r}" has no usable characters — a tag starts with a letter and is built from letters a-z, digits, and _ : -`}}function ho(s){return s.replace(/[^\s,]+/g,r=>{const n=/^#*/.exec(r)[0];return n+r.slice(n.length,n.length+ks)})}function xo(s){const{isNew:r,isOwner:n,isAdmin:o,permission:l,nestStewards:m,nodeRoles:x,grant:u,isArchived:h}=s,f=n||o||l==="owner"||l==="admin"||l==="write"||m.some(w=>w.role==="editor"&&w.scope==="nest"),j=o||l==="admin"||x.includes("admin"),N=x.includes("editor")||x.includes("admin"),v=h?!0:r?!f:!(f||u==="write"||N),g=!n&&x.length>0&&!x.includes("editor")&&!j;return{canAuthorNew:f,hasAdminApprove:j,isViewOnly:v,isReviewerOnly:g,canEditContent:!v&&!g}}function fo(s){const{isNew:r,canShare:n,isArchived:o,canEditContent:l,isLocked:m,canRequestDeletion:x,canDeleteDirectly:u,deletionRequested:h,isOwnDeletionRequest:f,includeVersionHistory:j=!0}=s,N=[];!r&&j&&N.push({key:"history",label:"Version history",testId:"document-editor-history"}),r||N.push({key:"copy-link",label:"Copy link",testId:"document-editor-copy-link",separatorBefore:!0}),!r&&l&&!m&&N.push({key:"move",label:"Move to folder",testId:"document-editor-move"}),n&&!r&&!o&&N.push({key:"share-doc",label:"Share this document",testId:"document-editor-share-doc",separatorBefore:!0}),n&&!r&&!o&&N.push({key:"publish",label:"Publish",testId:"document-editor-publish"});const v=!r&&x&&(u||!h);return v&&N.push({key:u?"delete":"request-deletion",label:"Delete",testId:u?"document-editor-delete":"document-editor-request-deletion",separatorBefore:!0,destructive:u}),!r&&h&&f&&N.push({key:"withdraw-deletion",label:"Withdraw deletion request",testId:"document-editor-withdraw-deletion",separatorBefore:!v}),N}function Pa(s){const r=[];let n="",o=!1;for(let l=0;l<s.length;l++){const m=s[l];o?m==='"'?s[l+1]==='"'?(n+='"',l++):o=!1:n+=m:m==='"'?o=!0:m===","?(r.push(n),n=""):n+=m}return r.push(n),r.map(l=>l.trim())}function po({nestId:s,nodeId:r,csv:n}){const[o,l]=a.useState(""),[m,x]=a.useState(null),[u,h]=a.useState(null),[f,j]=a.useState(!1),N=a.useMemo(()=>{const w=n.split(/\r?\n/).filter(A=>A.trim()!==""&&!A.trim().startsWith("#"));if(!w.length)return{header:[],rows:[]};const z=Pa(w[0]),V=w.slice(1).map(Pa);return{header:z,rows:V}},[n]),v=async()=>{j(!0),h(null);try{x(await bi(s,r,o))}catch(w){x(null),h(w instanceof Error?w.message:"Query failed")}finally{j(!1)}},g=m??{columns:N.header.map(w=>w.split(":")[0]),rows:N.rows,matched:N.rows.length,returned:N.rows.length,total:N.rows.length};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sn,{className:"h-4 w-4 text-cyan-500 shrink-0"}),e.jsx(Ia,{value:o,onChange:w=>l(w.target.value),onKeyDown:w=>w.key==="Enter"&&void v(),placeholder:'where region = "EU" and price > 100 select sku, price limit 5 — empty = all rows',className:"h-8 text-xs font-mono flex-1","data-testid":"table-query-input"}),e.jsxs(y,{size:"sm",className:"h-8",disabled:f,onClick:()=>void v(),children:[e.jsx(Hl,{className:"h-3.5 w-3.5 mr-1"})," Query"]}),m&&e.jsx(y,{size:"sm",variant:"ghost",className:"h-8 text-muted-foreground",onClick:()=>{x(null),h(null)},children:"Show all"})]}),u&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:u}),e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsxs(Nt,{variant:"secondary",className:"text-[10px]",children:[g.returned," row",g.returned===1?"":"s",m?` of ${g.matched} matching`:""," · ",g.total," total"]}),N.header.filter(w=>w.includes(":")).map(w=>e.jsx(Nt,{variant:"outline",className:"text-[10px] font-mono",children:w},w))]}),e.jsx(fn,{columns:g.columns,rows:g.rows})]})}function fn({columns:s,rows:r,limit:n=500,rowClassName:o}){return e.jsxs("div",{className:"overflow-x-auto rounded-lg border",children:[e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsx("tr",{className:"bg-muted/50 text-left text-muted-foreground",children:s.map(l=>e.jsx("th",{className:"px-3 py-2 font-semibold whitespace-nowrap",children:l},l))})}),e.jsx("tbody",{children:r.slice(0,n).map((l,m)=>e.jsx("tr",{className:`border-t align-top hover:bg-muted/30 ${(o==null?void 0:o(m))??""}`,children:l.map((x,u)=>e.jsx("td",{className:"px-3 py-1.5 whitespace-nowrap font-mono",children:x},u))},m))})]}),r.length>n&&e.jsxs("p",{className:"px-3 py-2 text-[11px] text-muted-foreground border-t",children:["Showing first ",n.toLocaleString()," rows."]})]})}function go({value:s,onChange:r,onBlur:n,readOnly:o=!1}){const l=a.useRef(null),[m,x]=a.useState(!1),u=o||m,h=a.useMemo(()=>{const v=al(s,",").filter(g=>!(g[0]??"").trimStart().startsWith("#")&&g.some(w=>w.trim()!==""));return{columns:(v[0]??[]).map(g=>g.split(":")[0].trim()),rows:v.slice(1),issues:rl(v)}},[s]),f=(v,g)=>{const w=s;r(v),k(g,w.trim()?{action:{label:"Undo",onClick:()=>r(w)}}:void 0)},j=async v=>{var w;if(u)return;const g=(w=v.target.files)==null?void 0:w[0];if(v.target.value="",!!g){x(!0);try{const z=k.loading("Processing file…");await new Promise(H=>requestAnimationFrame(()=>requestAnimationFrame(()=>H(null))));const V=await ol(g);if(!V.ok){k.error(cl(V.error,g),{id:z});return}const A=V.delimiter===","?V.text:Ys(V.rows),d=Math.max(0,V.rows.filter(H=>!(H[0]??"").trimStart().startsWith("#")).length-1);k.dismiss(z),f(A,`Table replaced from ${g.name} — ${d.toLocaleString()} data row${d===1?"":"s"}.`)}finally{x(!1)}}},N=v=>{if(u)return;const g=v.clipboardData.getData("text/plain"),w=dl(g);if(w&&w.delimiter!==","){v.preventDefault(),f(Ys(w.rows),`Pasted grid converted to CSV — table body replaced (${w.rows.length.toLocaleString()} rows).`);return}if(w)return;const z=ul(g);if(!z)return;v.preventDefault();const V=v.currentTarget,A=V.selectionStart??s.length,d=V.selectionEnd??A,H=Ys(z.rows);r(s.slice(0,A)+H+s.slice(d));const C=A+H.length;requestAnimationFrame(()=>V.setSelectionRange(C,C))};return e.jsxs("div",{"data-testid":"table-source-editor",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground min-w-0",children:["CSV — header first; directives welcome (",e.jsx("code",{children:"sku:key, price:number"}),"). Pasting a spreadsheet/TSV grid converts it to CSV."]}),e.jsxs(y,{type:"button",variant:"outline",size:"sm",className:"h-7 shrink-0",disabled:u,onClick:()=>{var v;return(v=l.current)==null?void 0:v.click()},"data-testid":"table-source-upload",children:[e.jsx(il,{className:"h-3.5 w-3.5 mr-1.5"}),"Replace from CSV / TSV"]}),e.jsx("input",{ref:l,type:"file",accept:".csv,.tsv,text/csv,text/tab-separated-values",className:"hidden",onChange:j})]}),e.jsxs("div",{className:h.columns.length>0?"grid gap-3 lg:grid-cols-2":"",children:[e.jsx("textarea",{value:s,onChange:v=>{u||r(v.target.value)},onBlur:n,onPaste:N,readOnly:u,spellCheck:!1,placeholder:`sku:key, price:number, region
|
|
22
|
-
OWL-100, 149, EU`,className:"w-full min-h-[360px] border rounded-lg bg-background shadow-sm p-4 font-mono text-sm leading-relaxed resize-y focus:outline-none focus:ring-2 focus:ring-ring","data-testid":"table-source-textarea"}),h.columns.length>0&&e.jsxs("div",{className:"min-w-0","data-testid":"table-source-preview",children:[e.jsxs("p",{className:"mb-1 text-xs font-medium text-muted-foreground",children:["Preview — ",h.rows.length.toLocaleString()," data row",h.rows.length===1?"":"s"]}),h.issues.length>0&&e.jsx("div",{className:"mb-2 rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-xs text-amber-900 dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-200","data-testid":"table-source-issues",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Bl,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("b",{children:[h.issues.length," column",h.issues.length===1?"":"s"," disagree with the header"]})," ","— table-query trusts these types.",e.jsx("ul",{className:"mt-1 list-disc space-y-0.5 pl-4",children:h.issues.slice(0,5).map((v,g)=>e.jsx("li",{children:ll(v)},`${v.column}-${v.kind}-${g}`))})]})]})}),e.jsx(fn,{columns:h.columns,rows:h.rows,limit:50})]})]})]})}const Va=250,bo=new Set(["P","DIV","SECTION","ARTICLE","HEADER","FOOTER","LI","TR","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","PRE","TABLE","UL","OL","BR","HR"]);function wo(s){if(!s)return"";if(typeof DOMParser>"u")return s.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/gi," ").replace(/<[^>]*>/g," ").replace(/[<>]/g," ").replace(/[ \t]+/g," ").replace(/\n{3,}/g,`
|
|
23
|
-
|
|
24
|
-
`).trim();const r=new DOMParser().parseFromString(s,"text/html");if(r.querySelectorAll("script,style,noscript,template").forEach(l=>l.remove()),!r.body.querySelector("*"))return(r.body.textContent||"").replace(/[ \t]+/g," ").replace(/[ \t]+\n/g,`
|
|
25
|
-
`).replace(/\n{3,}/g,`
|
|
26
|
-
|
|
27
|
-
`).trim();let n="";const o=(l,m)=>{if(l.nodeType===Node.TEXT_NODE){const h=l.textContent||"";n+=m?h:h.replace(/\s+/g," ");return}if(l.nodeType!==Node.ELEMENT_NODE)return;const x=l.tagName,u=bo.has(x);u&&n&&!n.endsWith(`
|
|
28
|
-
`)&&(n+=`
|
|
29
|
-
`),l.childNodes.forEach(h=>o(h,m||x==="PRE")),u&&!n.endsWith(`
|
|
30
|
-
`)&&(n+=`
|
|
31
|
-
`)};return o(r.body,!1),n.replace(/[ \t]+\n/g,`
|
|
32
|
-
`).replace(/\n{3,}/g,`
|
|
33
|
-
|
|
34
|
-
`).trim()}function vo(s,r,n){if(r<0||n>s.length||r>=n)return null;const o=s.slice(r,n).trim();return o?{quote:o,before:s.slice(Math.max(0,r-Va),r),after:s.slice(n,n+Va),line:s.slice(0,r).split(`
|
|
35
|
-
`).length}:null}const jo="artifact";function yo(s){return(s==null?void 0:s.replace("T"," ").replace(/\.\d+Z?$/,"").slice(0,16))||s}function No({nestId:s,nodeId:r,title:n,snapshotVersion:o,currentEmail:l,viewOnly:m=!1,reviewerOnly:x=!1,initialThreadId:u,onBack:h,onTurnedInto:f,actions:j,visibilityControl:N,onShareNest:v}){var Ae;const[g,w]=a.useState("preview"),[z,V]=a.useState(!!u);a.useEffect(()=>{g==="annotate"&&V(!0)},[g]);const[A,d]=a.useState(!1),[H,C]=a.useState(!1),X=async()=>{C(!0);try{await Ss(s,r,{type:"document"}),k.success("Turned into a document"),d(!1),f==null||f()}catch(c){k.error(c instanceof Error?c.message:"Failed to convert")}finally{C(!1)}},se=Ds(),[ne,S]=a.useState([]),[F,Y]=a.useState(!0),[ce,Ne]=a.useState(""),[nt,ke]=a.useState(null),kt=nt==null||/^s*</.test(nt),[Ge,b]=a.useState(!1),[L,Z]=a.useState(o??null),[Ke,Pe]=a.useState(0),[ts,at]=a.useState(!1),[St,ss]=a.useState(null),[de,T]=a.useState(null),[Se,Ce]=a.useState(null),[Ve,$]=a.useState(!1),[_,B]=a.useState(null),[Oe,pe]=a.useState(!1),[Re,ae]=a.useState(""),[Xe,rt]=a.useState(!1),Vt=!m,ue=!m&&!x,it=(_==null?void 0:_.status)==="pending_review",ge=_!=null&&Re!==_.content,Ot=it||St!=null&&((Ae=St.versions.find(c=>c.version===St.currentVersion))==null?void 0:Ae.status)==="pending_review",[W,qe]=a.useState(null),[Ct,qt]=a.useState(""),[J,zt]=a.useState(!1),[Rt,lt]=a.useState(null),[Ee,ze]=a.useState(""),_e=a.useRef(null),_t=wi(s,r,de??L,Ke),re=a.useCallback(async()=>{try{ss(await se.fetchQuery(ye.nodeVersions(s,r)))}catch(c){ss(null),k.error((c==null?void 0:c.message)||"Failed to load version history")}},[s,r]),Te=a.useCallback(c=>{if(g==="edit"&&ge){if(!window.confirm("Discard unsaved source changes?"))return;_&&ae(_.content)}c()},[g,ge,_]),Ye=a.useCallback(()=>{Te(()=>{at(!0),re()})},[Te,re]);a.useEffect(()=>{if(!ge)return;const c=R=>{R.preventDefault(),R.returnValue=""};return window.addEventListener("beforeunload",c),()=>window.removeEventListener("beforeunload",c)},[ge]);const Es=a.useCallback(c=>{Te(()=>{at(!1),T(c),w("preview"),Ne(""),ke(null),Pe(R=>R+1)})},[Te]),Tt=a.useCallback(()=>{T(null),Ne(""),ke(null),Pe(c=>c+1)},[]),Dt=a.useCallback(async c=>{await er(s,r,c),k.success(`Restored from version ${c}`),T(null),at(!1),w("preview"),Z(null),Ne(""),ke(null),B(null),ae(""),Pe(R=>R+1),await re()},[s,r,re]),Ze=a.useCallback(async()=>{if(Se!=null){$(!0);try{await Dt(Se),Ce(null)}catch(c){k.error((c==null?void 0:c.message)||"Restore failed")}finally{$(!1)}}},[Se,Dt]),As=a.useCallback(async()=>{if(T(null),w("edit"),!(_||Oe)){pe(!0);try{const{node:c}=await se.fetchQuery(ye.node(s,r)),R=(c==null?void 0:c.content)==null?"":String(c.content);B({content:R,version:c==null?void 0:c.version,status:(c==null?void 0:c.status)??null}),ae(R)}catch(c){k.error((c==null?void 0:c.message)||"Failed to load artifact source"),w("preview")}finally{pe(!1)}}},[_,Oe,s,r]),ns=a.useCallback(async()=>{var c,R;if(!(!_||!ge||Xe)){rt(!0);try{const P=await Ss(s,r,{content:Re},_.version),le=(P==null?void 0:P.version)??((c=P==null?void 0:P.node)==null?void 0:c.version);B({content:Re,version:typeof le=="number"?le:_.version,status:((R=P==null?void 0:P.node)==null?void 0:R.status)??_.status}),Z(null),Ne(""),ke(null),Pe(He=>He+1),w("preview"),k.success(typeof le=="number"?`Saved as version ${le}`:"Artifact saved")}catch(P){k.error((P==null?void 0:P.message)||"Save failed")}finally{rt(!1)}}},[_,ge,Xe,s,r,Re]),as=a.useCallback(()=>{Te(()=>w("preview"))},[Te]),be=a.useCallback(async()=>{Y(!0);try{const{threads:c}=await se.fetchQuery(ye.nodeAnnotations(s,r));S(c)}catch(c){k.error((c==null?void 0:c.message)||"Failed to load annotations")}finally{Y(!1)}},[s,r]);a.useEffect(()=>{be()},[be]);const rs=a.useRef(!1);a.useEffect(()=>{!u||rs.current||F||ne.some(c=>c.id===u)&&(rs.current=!0,requestAnimationFrame(()=>{var c;(c=document.getElementById(`annotation-thread-${u}`))==null||c.scrollIntoView({behavior:"smooth",block:"center"})}))},[ne,F,u]);const ot=a.useCallback(async()=>{if(!(ce||Ge)){b(!0);try{const{html:c,snapshot:R}=await vi(s,r,de??L,Ke);Ne(wo(c)),ke(c),R!=null&&de==null&&Z(R)}catch(c){k.error((c==null?void 0:c.message)||"Failed to load artifact text")}finally{b(!1)}}},[ce,Ge,s,r,L,de,Ke]);a.useEffect(()=>{(g==="annotate"||g==="preview")&&ot()},[g,ot]);const Ht=a.useCallback(()=>{const c=window.getSelection(),R=_e.current;if(!c||c.isCollapsed||!R){qe(null);return}const P=c.getRangeAt(0);if(!R.contains(P.startContainer)||!R.contains(P.endContainer))return;const le=Math.min(P.startOffset,P.endOffset),He=Math.max(P.startOffset,P.endOffset),is=ce.slice(le,He).trim();if(!is){qe(null);return}qe({start:le,end:He,quote:is})},[ce]),$t=a.useCallback(async()=>{var R,P;const c=Ct.trim();if(c){zt(!0);try{const le=W!=null?vo(ce,W.start,W.end):null;await tr(s,r,{body:c,anchor:le,snapshotVersion:L}),qt(""),qe(null),(P=(R=window.getSelection)==null?void 0:R.call(window))==null||P.removeAllRanges(),await be(),k.success("Comment added")}catch(le){k.error((le==null?void 0:le.message)||"Failed to add comment")}finally{zt(!1)}}},[Ct,W,ce,s,r,L,be]),we=a.useCallback(async c=>{const R=Ee.trim();if(R)try{await sr(s,r,c,R),ze(""),lt(null),await be()}catch(P){k.error((P==null?void 0:P.message)||"Failed to reply")}},[Ee,s,r,be]),Bt=a.useCallback(async c=>{try{c.status==="open"?await nr(s,r,c.id):await ar(s,r,c.id),await be()}catch(R){k.error((R==null?void 0:R.message)||"Failed to update thread")}},[s,r,be]),{openThreads:I,resolvedThreads:U}=a.useMemo(()=>{const c=ne.filter(P=>P.status==="open"),R=ne.filter(P=>P.status==="resolved");return{openThreads:c,resolvedThreads:R}},[ne]);return e.jsxs("div",{className:"flex min-h-full flex-col",children:[e.jsxs("div",{className:"sticky top-16 z-30 flex h-12 items-center justify-between gap-3 border-b bg-background/95 px-2 backdrop-blur supports-[backdrop-filter]:bg-background/80 sm:px-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(y,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>Te(h),children:e.jsx(rn,{className:"h-4 w-4"})}),e.jsx("h1",{className:"text-sm font-medium truncate",children:n||r}),e.jsx(Nt,{variant:"secondary",className:"shrink-0 gap-1",children:"Artifact"}),de!=null?e.jsxs(Nt,{variant:"outline",className:"shrink-0 border-amber-300 bg-amber-50 text-amber-800",title:"Read-only view of a historical version.",children:["Viewing v",de]}):L!=null?e.jsxs(Nt,{variant:"outline",className:"shrink-0",title:"Annotations are anchored to this frozen snapshot.",children:["Snapshot v",L]}):null]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("div",{className:"flex items-center rounded-md border h-9",children:[e.jsxs("button",{type:"button",className:`px-3 h-full rounded-l-md inline-flex items-center gap-1.5 text-sm ${g==="preview"?"bg-muted":"hover:bg-muted/50"}`,onClick:()=>Te(()=>w("preview")),children:[e.jsx(ji,{className:"h-4 w-4"})," Preview"]}),e.jsxs("button",{type:"button",className:mn("px-3 h-full inline-flex items-center gap-1.5 text-sm disabled:opacity-50",!ue&&"rounded-r-md",g==="annotate"?"bg-muted":"hover:bg-muted/50"),disabled:de!=null,title:de!=null?"Return to the current version to annotate":void 0,onClick:()=>Te(()=>w("annotate")),children:[e.jsx(ml,{className:"h-4 w-4"})," Annotate"]}),ue&&e.jsxs("button",{type:"button",className:`px-3 h-full rounded-r-md inline-flex items-center gap-1.5 text-sm ${g==="edit"?"bg-muted":"hover:bg-muted/50"}`,title:"Edit the artifact's raw HTML source",onClick:()=>void As(),children:[e.jsx(es,{className:"h-4 w-4"})," Edit source"]})]}),e.jsx(y,{variant:"outline",size:"icon",title:"Version history",onClick:Ye,children:e.jsx(pr,{className:"h-4 w-4"})}),e.jsx(y,{variant:"outline",size:"icon",title:"Reload artifact",onClick:()=>Pe(c=>c+1),children:e.jsx(ln,{className:"h-4 w-4"})}),!m&&!x&&f&&e.jsx(y,{variant:"outline",size:"icon",title:ge?"Save or discard the source edits first":"Turn into a document",disabled:ge,onClick:()=>d(!0),"data-testid":"artifact-turn-into-document",children:e.jsx(Js,{className:"h-4 w-4"})}),N,v&&e.jsx(y,{variant:"outline",size:"icon",title:"Share this nest — people, teams, visibility",onClick:v,"data-testid":"artifact-share-nest",children:e.jsx($s,{className:"h-4 w-4"})}),e.jsxs(y,{variant:z?"secondary":"outline",size:"icon",title:z?"Hide annotations":"Show annotations","aria-pressed":z,onClick:()=>V(c=>!c),"data-testid":"artifact-comments-toggle",className:"relative",children:[e.jsx(Rs,{className:"h-4 w-4"}),I.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 rounded-full bg-primary px-1 text-[10px] font-semibold leading-4 text-primary-foreground",children:I.length})]}),e.jsx("a",{href:_t,target:"_blank",rel:"noopener noreferrer",children:e.jsx(y,{variant:"outline",size:"icon",title:"Open in new tab",children:e.jsx(yi,{className:"h-4 w-4"})})}),j&&j.length>0&&e.jsx(mr,{actions:j,variant:"outline",testId:"artifact-viewer-more"})]})]}),e.jsxs("div",{className:"flex flex-1 flex-col items-stretch lg:flex-row lg:items-start",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col px-5 py-6 sm:px-10 sm:py-8 min-h-[calc(100vh-7rem)]",children:[de!=null&&e.jsxs("div",{className:"px-3 py-2 border-b bg-amber-50 text-xs text-amber-900 flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("span",{children:[e.jsxs("span",{className:"font-medium",children:["Viewing version ",de]})," ","— read-only historical snapshot."]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[Vt&&e.jsxs(y,{size:"sm",variant:"outline",className:"h-6 px-2 text-xs border-amber-300 text-amber-900 hover:bg-amber-100",disabled:Ot,title:Ot?"Locked while awaiting steward review — resolve the review first":void 0,onClick:()=>Ce(de),children:[e.jsx(xn,{className:"h-3 w-3 mr-1"}),Ot?"Locked — review pending":"Restore this version"]}),e.jsxs(y,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-amber-900 hover:bg-amber-100",onClick:Tt,children:[e.jsx(st,{className:"h-3 w-3 mr-1"})," Back to current"]})]})]}),g==="edit"?e.jsxs("div",{className:"flex-1 flex flex-col",children:[e.jsx("div",{className:"mb-3 text-xs text-muted-foreground",children:it?"Locked while awaiting steward review — resolve the review before editing.":"Editing raw HTML source. Saving creates a new version, like any document edit."}),Oe?e.jsxs("div",{className:"flex items-center justify-center flex-1 text-muted-foreground",children:[e.jsx(ee,{className:"h-5 w-5 animate-spin mr-2"})," Loading source…"]}):e.jsxs(e.Fragment,{children:[e.jsx("textarea",{value:Re,onChange:c=>ae(c.target.value),readOnly:it,spellCheck:!1,placeholder:"Paste the artifact's HTML (a self-contained slide deck, dashboard, infographic)…",className:"flex-1 w-full min-h-[60vh] rounded-lg border bg-background p-4 font-mono text-sm leading-relaxed resize-y shadow-sm focus:outline-none focus:ring-2 focus:ring-ring"}),e.jsxs("div",{className:"sticky bottom-0 z-20 mt-auto -mx-5 flex items-center justify-between gap-2 border-t bg-background/95 px-4 py-2 backdrop-blur supports-[backdrop-filter]:bg-background/80 sm:-mx-10",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(_==null?void 0:_.version)!=null?`Editing v${_.version}`:"",ge?" · unsaved changes":""]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(y,{variant:"ghost",size:"sm",onClick:as,disabled:Xe,children:"Cancel"}),e.jsxs(y,{size:"sm",onClick:()=>void ns(),disabled:it||Xe||!ge||!Re.trim(),title:it?"Locked while awaiting steward review":void 0,children:[Xe?e.jsx(ee,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(Pt,{className:"h-4 w-4 mr-1.5"}),"Save"]})]})]})]})]}):g==="preview"&&!kt?e.jsx(nn,{content:nt??"",className:"flex-1 min-h-[70vh] max-h-none overflow-visible rounded-lg border bg-background"}):g==="preview"?e.jsx("iframe",{src:_t,title:n||r,sandbox:"allow-scripts allow-popups allow-modals",className:"w-full flex-1 min-h-[70vh] rounded-lg border bg-white"},Ke):e.jsxs("div",{className:"flex-1 flex flex-col min-h-[70vh] rounded-lg border bg-background",children:[e.jsx("div",{className:"px-3 py-2 border-b bg-muted/30 text-xs text-muted-foreground",children:"Select text below to anchor a comment to it. This is the artifact's extracted text — the same text the nest indexes."}),Ge?e.jsxs("div",{className:"flex items-center justify-center flex-1 text-muted-foreground",children:[e.jsx(ee,{className:"h-5 w-5 animate-spin mr-2"})," Loading text…"]}):e.jsx("pre",{ref:_e,onMouseUp:Ht,className:"flex-1 overflow-auto whitespace-pre-wrap break-words p-4 text-sm leading-relaxed font-sans selection:bg-amber-200",children:ce||"(no extractable text)"})]})]}),e.jsxs("aside",{className:`w-full shrink-0 border-t lg:w-80 lg:border-t-0 lg:border-l lg:sticky lg:top-28 lg:self-start lg:max-h-[calc(100vh-7rem)] flex flex-col min-h-0 max-h-[70vh]${z?"":" hidden"}`,"data-testid":"artifact-comments-rail","aria-hidden":!z,children:[e.jsxs("div",{className:"px-3 py-2 border-b flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm font-medium",children:["Annotations",e.jsxs("span",{className:"text-muted-foreground font-normal",children:[" ","· ",I.length," open"]})]}),e.jsx(y,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Refresh",onClick:be,children:e.jsx(ln,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"p-3 border-b space-y-2",children:[W?e.jsxs("div",{className:"text-xs rounded border-l-2 border-amber-400 bg-amber-50 px-2 py-1 text-amber-900",children:[e.jsx("span",{className:"font-medium",children:"Anchored to:"})," ",'"',W.quote.length>80?W.quote.slice(0,80)+"…":W.quote,'"',e.jsx("button",{type:"button",className:"ml-2 underline text-amber-700",onClick:()=>{var c,R;qe(null),(R=(c=window.getSelection)==null?void 0:c.call(window))==null||R.removeAllRanges()},children:"clear"})]}):e.jsx("div",{className:"text-xs text-muted-foreground",children:g==="annotate"?"No selection — this will be a whole-artifact comment.":"Switch to Annotate to highlight text, or comment on the whole artifact below."}),e.jsx("textarea",{value:Ct,onChange:c=>qt(c.target.value),placeholder:"Add a comment…",rows:3,className:"w-full text-sm rounded border px-2 py-1.5 resize-y focus:outline-none focus:ring-1 focus:ring-primary"}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(y,{size:"sm",onClick:$t,disabled:J||!Ct.trim(),children:[J?e.jsx(ee,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(wr,{className:"h-4 w-4 mr-1.5"}),"Comment"]})})]}),e.jsx("div",{className:"flex-1 overflow-auto p-3 space-y-3",children:F?e.jsxs("div",{className:"flex items-center justify-center py-8 text-muted-foreground",children:[e.jsx(ee,{className:"h-4 w-4 animate-spin mr-2"})," Loading…"]}):ne.length===0?e.jsx("div",{className:"text-sm text-muted-foreground text-center py-8",children:"No annotations yet. Highlight text and leave the first comment."}):e.jsxs(e.Fragment,{children:[I.map(c=>e.jsx(Oa,{thread:c,currentEmail:l,replyOpen:Rt===c.id,replyBody:Ee,onReplyOpen:()=>{lt(c.id),ze("")},onReplyChange:ze,onReplySubmit:()=>we(c.id),onToggleResolved:()=>Bt(c)},c.id)),U.length>0&&e.jsx("div",{className:"pt-2 text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Resolved"}),U.map(c=>e.jsx(Oa,{thread:c,currentEmail:l,replyOpen:Rt===c.id,replyBody:Ee,onReplyOpen:()=>{lt(c.id),ze("")},onReplyChange:ze,onReplySubmit:()=>we(c.id),onToggleResolved:()=>Bt(c)},c.id))]})})]})]}),ts&&e.jsx(gr,{open:!0,onClose:()=>at(!1),title:n||r,versionData:St,previewAs:"source",onView:Es,onLoadContent:async c=>(await Is(s,r,c)).content,onRestore:Vt?async c=>{try{await Dt(c)}catch(R){k.error((R==null?void 0:R.message)||"Restore failed")}}:void 0}),e.jsx(bt,{open:A,onOpenChange:c=>{H||d(c)},children:e.jsxs(wt,{className:"sm:max-w-[440px]",children:[e.jsxs(vt,{children:[e.jsx(jt,{children:"Turn into a document?"}),e.jsx(en,{children:"The HTML stays as the body, opened in the markdown editor's source view for you to rework. It stops being hosted as a page until it is turned back into an artifact."})]}),e.jsxs(yt,{children:[e.jsx(y,{variant:"outline",onClick:()=>d(!1),disabled:H,children:"Cancel"}),e.jsxs(y,{onClick:()=>void X(),disabled:H,"data-testid":"artifact-turn-into-confirm",children:[H?e.jsx(ee,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Turn into document"]})]})]})}),e.jsx(bt,{open:Se!=null,onOpenChange:c=>!c&&Ce(null),children:e.jsxs(wt,{children:[e.jsxs(vt,{children:[e.jsxs(jt,{children:["Restore version ",Se,"?"]}),e.jsxs(en,{children:["This writes version ",Se,"'s HTML as a new version through the normal save path — review rules still apply and the current content stays in history."]})]}),e.jsxs(yt,{children:[e.jsx(y,{variant:"outline",onClick:()=>Ce(null),disabled:Ve,children:"Cancel"}),e.jsx(y,{onClick:()=>void Ze(),disabled:Ve,children:Ve?"Restoring…":"Restore"})]})]})})]})}function Oa({thread:s,replyOpen:r,replyBody:n,onReplyOpen:o,onReplyChange:l,onReplySubmit:m,onToggleResolved:x}){const u=s.status==="resolved";return e.jsxs("div",{id:`annotation-thread-${s.id}`,className:`rounded-lg border p-2.5 text-sm ${u?"bg-muted/40 opacity-80":"bg-background"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx(Nt,{variant:"outline",className:u?"border-emerald-200 bg-emerald-50 text-emerald-700":"border-amber-200 bg-amber-50 text-amber-700",children:u?"Resolved":"Open"}),e.jsx("button",{type:"button",className:"text-xs inline-flex items-center gap-1 text-muted-foreground hover:text-foreground",onClick:x,title:u?"Reopen thread":"Mark resolved",children:u?e.jsxs(e.Fragment,{children:[e.jsx(xn,{className:"h-3 w-3"})," Reopen"]}):e.jsxs(e.Fragment,{children:[e.jsx(Pt,{className:"h-3 w-3"})," Resolve"]})})]}),s.anchor?e.jsxs("div",{className:"mb-1.5 text-xs rounded border-l-2 border-amber-300 bg-amber-50/60 px-2 py-1 text-amber-900",children:['"',s.anchor.quote.length>100?s.anchor.quote.slice(0,100)+"…":s.anchor.quote,'"']}):e.jsx("div",{className:"mb-1.5 text-xs text-muted-foreground italic",children:"Whole-artifact comment"}),e.jsx("ul",{className:"space-y-1.5",children:s.comments.map(h=>e.jsxs("li",{children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"font-medium text-xs",children:h.author}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:yo(h.createdAt)})]}),e.jsx("div",{className:"whitespace-pre-wrap break-words",children:h.body})]},h.id))}),r?e.jsxs("div",{className:"mt-2 space-y-1.5",children:[e.jsx("textarea",{value:n,onChange:h=>l(h.target.value),placeholder:"Reply…",rows:2,className:"w-full text-sm rounded border px-2 py-1 resize-y focus:outline-none focus:ring-1 focus:ring-primary",autoFocus:!0}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(y,{size:"sm",onClick:m,disabled:!n.trim(),children:[e.jsx(on,{className:"h-3.5 w-3.5 mr-1.5"})," Reply"]})})]}):e.jsx("button",{type:"button",className:"mt-1.5 text-xs text-primary hover:underline",onClick:o,children:"Reply"})]})}const ko=hl(xl);function jr(s){return s.map((r,n)=>{var l;if(r.type==="text")return r.value;const o=(((l=r.properties)==null?void 0:l.className)??[]).join(" ");return e.jsx("span",{className:o,children:jr(r.children??[])},n)})}function qa({code:s,className:r="",...n}){const o=a.useMemo(()=>{if(!s.trim())return null;try{return jr(ko.highlightAuto(s).children)}catch{return null}},[s]);return e.jsx("pre",{className:`overflow-x-auto p-4 font-mono text-xs leading-relaxed whitespace-pre ${r}`,...n,children:e.jsx("code",{children:o??s})})}function So({nestId:s,onChanged:r}){const[n,o]=a.useState([]),[l,m]=a.useState([]),[x,u]=a.useState(""),[h,f]=a.useState(!0),j=Ds(),[N,v]=a.useState(!1),[g,w]=a.useState(null),z=async()=>{f(!0),w(null);try{const[C,X]=await Promise.all([j.fetchQuery(ye.nestTeams(s)),j.fetchQuery(ye.teamList()).catch(()=>({teams:[]}))]);o(C.teams),m(X.teams)}catch(C){w((C==null?void 0:C.message)||"Failed to load teams")}finally{f(!1)}};a.useEffect(()=>{z()},[s]);const V=new Set(n.map(C=>C.teamId)),A=l.filter(C=>!V.has(C.id)),d=async()=>{if(x){v(!0);try{await Si(s,x),u(""),k.success("Team shared"),await z(),r()}catch(C){k.error((C==null?void 0:C.message)||"Failed to share team")}finally{v(!1)}}},H=async(C,X)=>{v(!0);try{await ki(s,C),k.success(`"${X}" unshared`),await z(),r()}catch(se){k.error((se==null?void 0:se.message)||"Failed to unshare team")}finally{v(!1)}};return e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsxs(Ni,{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx($s,{className:"h-4 w-4"}),"Teams"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Share a whole team at once. Each member gets the role you gave them on the Teams page. Manage members there."}),g&&e.jsxs(De,{variant:"destructive",children:[e.jsx(Fe,{className:"h-4 w-4"}),e.jsx($e,{children:g})]}),h?e.jsx("div",{className:"flex justify-center py-4",children:e.jsx(ee,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[n.length>0&&e.jsx("div",{className:"space-y-2",children:n.map(C=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm flex-1 truncate",children:C.teamName}),e.jsxs(Nt,{variant:"secondary",children:[C.members.length," member",C.members.length===1?"":"s"]}),e.jsx(y,{size:"icon",variant:"ghost",className:"h-8 w-8",disabled:N,onClick:()=>H(C.teamId,C.teamName),"aria-label":`Unshare ${C.teamName}`,children:e.jsx(cn,{className:"h-3.5 w-3.5"})})]},C.teamId))}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx("div",{className:"flex-1",children:e.jsx(fl,{value:x,onChange:u,options:A.map(C=>({value:C.id,label:C.name})),disabled:A.length===0,placeholder:A.length===0?"No more teams to share":"Select a team…",searchPlaceholder:"Search teams…",emptyText:"No teams match.",testId:"team-share-select"})}),e.jsxs(y,{size:"sm",onClick:d,disabled:N||!x,children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Share"]})]})]})]})}function Co({nestId:s,nestName:r,onClose:n,onChanged:o,stewardshipEnabled:l=!1}){var f,j;const{adminStatus:m}=hn(),x=((j=(f=m==null?void 0:m.me)==null?void 0:f.email)==null?void 0:j.toLowerCase())??"",[u,h]=a.useState(null);return e.jsx(bt,{open:!0,onOpenChange:n,children:e.jsxs(wt,{className:"sm:max-w-[560px]",children:[e.jsxs(vt,{children:[e.jsxs(jt,{className:"flex items-center gap-2",children:[e.jsx($s,{className:"h-4 w-4"}),"Share nest: ",r]}),e.jsxs(en,{children:["Sharing applies to the ",e.jsx("strong",{children:"whole nest"})," — every document in it. Sharing grants plain access; it does not make anyone a steward."," ",l?e.jsx(e.Fragment,{children:"To restrict who can touch an individual document, assign stewards on the nest's Stewards tab instead."}):e.jsx(e.Fragment,{children:"Per-document control comes from stewards, which need Stewardship & Approval Workflow turned on in Nest settings."})]})]}),e.jsxs("div",{className:"space-y-4 py-1",children:[u&&e.jsxs(De,{variant:"destructive",children:[e.jsx(Fe,{className:"h-4 w-4"}),e.jsx($e,{children:u})]}),e.jsx(xr,{nestId:s,onChanged:o,onError:h}),e.jsxs(Ci,{defaultValue:"people",children:[e.jsxs(Ri,{className:"grid grid-cols-2 w-full",children:[e.jsx(ga,{value:"people",children:"People"}),e.jsx(ga,{value:"teams",children:"Teams"})]}),e.jsx(ba,{value:"people",className:"mt-3 max-h-[52vh] overflow-y-auto pr-1",children:e.jsx($l,{nestId:s,nestName:r,onChanged:o,currentUserEmail:x})}),e.jsx(ba,{value:"teams",className:"mt-3 max-h-[52vh] overflow-y-auto pr-1",children:e.jsx(So,{nestId:s,onChanged:o})})]})]}),e.jsx(yt,{children:e.jsx(y,{variant:"outline",onClick:n,children:"Done"})})]})})}function Ro(s,r,n){const o=s.slice(0,r),l=hr(o);if(!l||l.kind!=="mention")return null;const m=r-l.length,x=`@${n} `,u=s.slice(r),h=u.startsWith(" ")?u.slice(1):u;return{value:s.slice(0,m)+x+h,caret:m+x.length}}const za=/((?:```[\s\S]*?```)|(?:`[^`\n]*`))|(?:(^|\s)@(?:\(([^)]+)\)|([a-zA-Z0-9._@-]+)))/g;function To(s,r){const n=[],o=s||"",l=r.length>0;let m=0;const x=h=>{if(!h)return;const f=n[n.length-1];(f==null?void 0:f.kind)==="text"?f.text+=h:n.push({kind:"text",text:h})};za.lastIndex=0;let u;for(;(u=za.exec(o))!==null;){const[h,f,j,N,v]=u;if(f){x(o.slice(m,u.index+h.length)),m=u.index+h.length;continue}const g=(N||v||"").trim(),w=u.index+(j?j.length:0);x(o.slice(m,w)),n.push({kind:"mention",text:o.slice(w,u.index+h.length),name:g,resolved:!l||pl(r,g)}),m=u.index+h.length}return x(o.slice(m)),n}const _a=a.forwardRef(function({value:r,onValueChange:n,members:o,className:l,onKeyDown:m,...x},u){var X,se,ne;const h=a.useRef(null),[f,j]=a.useState(0),[N,v]=a.useState(!1),[g,w]=a.useState(0),z=S=>{h.current=S,typeof u=="function"?u(S):u&&(u.current=S)},V=a.useMemo(()=>{if(!N)return null;const S=hr(r.slice(0,f));return(S==null?void 0:S.kind)==="mention"?S:null},[N,r,f]),A=(ne=(se=(X=hn().adminStatus)==null?void 0:X.me)==null?void 0:se.email)==null?void 0:ne.toLowerCase(),d=a.useMemo(()=>V?gl(o.filter(S=>S.email.toLowerCase()!==A),V.query):[],[V,o,A]);a.useEffect(()=>w(0),[V==null?void 0:V.query,d.length]);const H=S=>{const F=h.current,Y=Ro(r,f,S);Y&&(n(Y.value),v(!1),requestAnimationFrame(()=>{F&&(F.focus(),F.setSelectionRange(Y.caret,Y.caret),j(Y.caret))}))},C=!!V&&d.length>0;return e.jsxs("div",{className:"relative",children:[e.jsx("textarea",{...x,ref:z,value:r,className:l,onChange:S=>{n(S.target.value),j(S.target.selectionStart??S.target.value.length),v(!0)},onKeyUp:S=>j(S.target.selectionStart??0),onPaste:S=>{const F=S.currentTarget;requestAnimationFrame(()=>j(F.selectionStart??0))},onClick:S=>j(S.target.selectionStart??0),onBlur:()=>v(!1),onKeyDown:S=>{if(C){if(S.key==="ArrowDown"){S.preventDefault(),w(F=>(F+1)%d.length);return}if(S.key==="ArrowUp"){S.preventDefault(),w(F=>F<=0?d.length-1:F-1);return}if(S.key==="Enter"||S.key==="Tab"){S.preventDefault();const F=d[g]??d[0];F&&H(F.email);return}if(S.key==="Escape"){S.stopPropagation(),v(!1);return}}m==null||m(S)}}),C&&e.jsx("ul",{role:"listbox",className:"absolute left-0 right-0 top-full z-50 mt-1 max-h-48 overflow-auto rounded-md border bg-popover py-1 text-popover-foreground shadow-md","data-testid":"mention-picker",children:d.map((S,F)=>e.jsx("li",{children:e.jsxs("button",{type:"button",role:"option","aria-selected":F===g,onMouseDown:Y=>{Y.preventDefault(),H(S.email)},onMouseEnter:()=>w(F),className:mn("flex w-full flex-col items-start px-3 py-1.5 text-left text-sm",F===g?"bg-accent text-accent-foreground":""),children:[e.jsx("span",{className:"truncate font-medium",children:S.name||S.email.split("@")[0]}),e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:S.email})]})},S.email))})]})});function Ha({body:s,members:r,className:n}){const o=a.useMemo(()=>To(s,r),[s,r]);return e.jsx("div",{className:mn("whitespace-pre-wrap",n),children:o.map((l,m)=>l.kind==="text"?e.jsx("span",{children:l.text},m):e.jsx("span",{className:l.resolved?"rounded bg-primary/10 px-0.5 font-medium text-primary":"rounded bg-muted px-0.5 text-muted-foreground line-through decoration-dotted",title:l.resolved?l.name:`No member named "${l.name}" in this nest`,children:l.text},m))})}function Zs(s){return Cs(s)||s}function Ba(s,r=80){const n=s.replace(/\s+/g," ").trim();return n.length>r?n.slice(0,r)+"…":n}function Do({nestId:s,nodeId:r,readOnly:n,pendingAnchor:o,onClearAnchor:l,onFocusAnchor:m,onThreadsChange:x,activeThreadId:u,commentMode:h,onSetCommentMode:f}){const j=typeof f=="function",N=!j||!!h,[v,g]=a.useState(null),[w,z]=a.useState(""),[V,A]=a.useState(null),[d,H]=a.useState(""),[C,X]=a.useState(!1),se=Ds(),ne=a.useRef(null),{data:S}=Ti({...ye.mentionable(s),enabled:!!s&&!n}),F=a.useMemo(()=>((S==null?void 0:S.people)??[]).filter(b=>!!b.email),[S]),Y=a.useRef({}),ce=async()=>{try{const{threads:b}=await se.fetchQuery(ye.nodeAnnotations(s,r));g(b),x==null||x(b)}catch{g([]),x==null||x([])}};a.useEffect(()=>{g(null),ce()},[s,r]),a.useEffect(()=>{var b;o&&((b=ne.current)==null||b.focus())},[o]),a.useEffect(()=>{var b;u&&Y.current[u]&&((b=Y.current[u])==null||b.scrollIntoView({behavior:"smooth",block:"nearest"}))},[u]);const Ne=async()=>{const b=w.trim();if(b){X(!0);try{await tr(s,r,{body:b,anchor:o??null}),z(""),l==null||l(),await ce()}catch(L){k.error((L==null?void 0:L.message)||"Failed to add comment")}finally{X(!1)}}},nt=async b=>{const L=d.trim();if(L){X(!0);try{await sr(s,r,b,L),H(""),A(null),await ce()}catch(Z){k.error((Z==null?void 0:Z.message)||"Failed to reply")}finally{X(!1)}}},ke=async b=>{X(!0);try{b.status==="open"?await nr(s,r,b.id):await ar(s,r,b.id),await ce()}catch(L){k.error((L==null?void 0:L.message)||"Failed to update thread")}finally{X(!1)}},kt=(v==null?void 0:v.length)??0,Ge=v&&[...v].sort((b,L)=>L.createdAt.localeCompare(b.createdAt));return e.jsxs("section",{className:"flex flex-col flex-1 min-h-0 max-h-[calc(100vh-2rem)] rounded-lg border border-border bg-card p-5","data-testid":"annotations-panel",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4 border-b pb-3 shrink-0",children:[e.jsx(Rs,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("h3",{className:"text-sm font-semibold whitespace-nowrap",children:["Comments",v?` (${kt})`:""]}),!n&&j&&e.jsxs("label",{className:"ml-auto flex shrink-0 items-center gap-1.5 whitespace-nowrap text-xs text-muted-foreground cursor-pointer",children:["Comment mode",e.jsx(rr,{checked:!!h,onCheckedChange:b=>f==null?void 0:f(b),"data-testid":"annotations-comment-mode"})]})]}),!n&&e.jsxs("div",{className:"mb-4 shrink-0",children:[N&&(o?e.jsx("div",{className:"mb-2 rounded-md border border-amber-200 bg-amber-50/60 dark:bg-amber-950/20 px-2 py-1.5 text-xs","data-testid":"annotations-pending-anchor",children:e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(Ra,{className:"h-3 w-3 mt-0.5 shrink-0 text-amber-700"}),e.jsxs("span",{className:"flex-1 italic text-foreground/80",children:["“",Ba(o.quote),"”"]}),e.jsx("button",{type:"button",className:"shrink-0 text-muted-foreground hover:text-foreground",title:"Comment on the whole document instead",onClick:()=>l==null?void 0:l(),children:e.jsx(st,{className:"h-3 w-3"})})]})}):e.jsx("p",{className:"mb-2 text-[11px] text-muted-foreground",children:"Tip: select text in the document to pin a comment to it."})),e.jsx(_a,{ref:ne,members:F,value:N?w:"",onValueChange:z,readOnly:!N,onMouseDown:N?void 0:b=>{b.preventDefault(),f==null||f(!0)},onFocus:N?void 0:()=>f==null?void 0:f(!0),placeholder:N?o?"Comment on the highlighted text…":"Add a comment… use @ to tag someone":"Click here to start commenting…",title:N?void 0:"Click to turn on comment mode",rows:2,className:`w-full rounded-md border px-3 py-2 text-sm resize-y ${N?"border-input bg-background":"border-dashed border-input bg-muted/50 text-muted-foreground cursor-pointer"}`,"data-testid":"annotations-new"}),N&&e.jsx("div",{className:"flex justify-end mt-2",children:e.jsx(y,{size:"sm",onClick:Ne,disabled:C||!w.trim(),children:o?"Comment on selection":"Comment"})})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto -mr-2 pr-2",children:v===null?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-4",children:[e.jsx(ee,{className:"h-4 w-4 animate-spin"})," Loading comments…"]}):kt===0?e.jsx("p",{className:"text-sm text-muted-foreground py-2",children:"No comments yet."}):e.jsx("ul",{className:"space-y-3",children:Ge.map(b=>{var L;return e.jsxs("li",{ref:Z=>{Y.current[b.id]=Z},className:`rounded-md border p-3 transition-shadow ${u===b.id?"border-amber-400 ring-2 ring-amber-300/60":b.status==="resolved"?"border-emerald-200 bg-emerald-50/40 dark:bg-emerald-950/20":"border-border"}`,children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded ${b.status==="resolved"?"bg-emerald-100 text-emerald-800":"bg-amber-100 text-amber-800"}`,children:b.status})}),((L=b.anchor)==null?void 0:L.quote)&&e.jsxs("button",{type:"button",onClick:()=>m==null?void 0:m(b.anchor),className:"group mb-2 block w-full text-left rounded border-l-2 border-amber-400 bg-amber-50/50 dark:bg-amber-950/20 px-2 py-1 text-xs italic text-foreground/75 hover:bg-amber-100/70",title:"Jump to this text in the document",children:[e.jsx(Ra,{className:"inline h-3 w-3 mr-1 text-amber-600 align-[-1px]"}),Ba(b.anchor.quote)]}),b.comments.length>0&&e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:b.comments[0].author})," ","· ",Zs(b.comments[0].createdAt)]}),e.jsx(Ha,{body:b.comments[0].body,members:F})]}),b.comments.length>1&&e.jsx("ul",{className:"mt-2 ml-2 space-y-2 border-l-2 border-border pl-3",children:b.comments.slice(1).map(Z=>e.jsxs("li",{className:"text-sm",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:Z.author})," ","replied · ",Zs(Z.createdAt)]}),e.jsx(Ha,{body:Z.body,members:F})]},Z.id))}),b.status==="resolved"&&b.resolvedBy&&e.jsxs("div",{className:"mt-2 flex items-center gap-1 text-xs text-emerald-700 dark:text-emerald-400",children:[e.jsx(Ql,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{children:["Resolved by"," ",e.jsx("span",{className:"font-medium",children:b.resolvedBy}),b.resolvedAt&&e.jsxs(e.Fragment,{children:[" · ",Zs(b.resolvedAt)]})]})]}),!n&&(V===b.id?e.jsxs("div",{className:"mt-2",children:[e.jsx(_a,{members:F,value:d,onValueChange:H,placeholder:"Reply… use @ to tag someone",rows:2,className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm resize-y",autoFocus:!0}),e.jsxs("div",{className:"flex justify-end gap-2 mt-1",children:[e.jsx(y,{variant:"ghost",size:"sm",onClick:()=>{A(null),H("")},children:"Cancel"}),e.jsx(y,{size:"sm",onClick:()=>nt(b.id),disabled:C||!d.trim(),children:"Reply"})]})]}):e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 rounded-md border px-2.5 py-1 text-xs font-medium text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>{A(b.id),H("")},children:[e.jsx(Gl,{className:"h-3 w-3"})," Reply"]}),b.status==="open"?e.jsxs("button",{type:"button",disabled:C,className:"inline-flex items-center gap-1 rounded-md border border-emerald-600 bg-emerald-600 px-2.5 py-1 text-xs font-semibold text-white shadow-sm hover:bg-emerald-700 disabled:opacity-50",onClick:()=>ke(b),children:[e.jsx(Pt,{className:"h-3.5 w-3.5"})," Resolve"]}):e.jsxs("button",{type:"button",disabled:C,className:"inline-flex items-center gap-1 rounded-md border px-2.5 py-1 text-xs font-medium text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50",onClick:()=>ke(b),children:[e.jsx(xn,{className:"h-3 w-3"})," Reopen"]})]}))]},b.id)})})})]})}function $o(s){const r=document.createTreeWalker(s,NodeFilter.SHOW_TEXT),n=[];let o="",l;for(;l=r.nextNode();){const m=l;n.push({node:m,start:o.length}),o+=m.data}return{text:o,segs:n}}function Wa(s,r){if(!s.segs.length)return null;for(let n=s.segs.length-1;n>=0;n--){const o=s.segs[n];if(r>=o.start)return{node:o.node,offset:Math.min(r-o.start,o.node.data.length)}}return{node:s.segs[0].node,offset:0}}function Eo(s,r){const n=r.quote;if(!n)return null;const o=[];let l=s.text.indexOf(n);for(;l!==-1;)o.push(l),l=s.text.indexOf(n,l+1);if(!o.length)return null;let m=o[0];if(o.length>1&&r.before){const x=r.before.slice(-24),u=o.find(h=>s.text.slice(Math.max(0,h-x.length),h).endsWith(x));u!==void 0&&(m=u)}return{start:m,end:m+n.length}}function Ao(s,r,n){const o=Eo(r,n);if(!o)return null;const l=Wa(r,o.start),m=Wa(r,o.end);if(!l||!m)return null;try{const x=document.createRange();return x.setStart(l.node,l.offset),x.setEnd(m.node,m.offset),x}catch{return null}}function yr(){return typeof CSS<"u"&&"highlights"in CSS}function Ua(s,r){if(!yr())return;const n=window.Highlight;if(n){if(!r.length){CSS.highlights.delete(s);return}CSS.highlights.set(s,new n(...r))}}function Qa(s){yr()&&CSS.highlights.delete(s)}function Ga(s,r){const n=document;if(n.caretPositionFromPoint){const o=n.caretPositionFromPoint(s,r);return o?{node:o.offsetNode,offset:o.offset}:null}if(n.caretRangeFromPoint){const o=n.caretRangeFromPoint(s,r);return o?{node:o.startContainer,offset:o.startOffset}:null}return null}function Ka(s){return s.replace(/^#/,"").toLowerCase()}const Lo=2,Mo=1;function Fo(s,r,n=5){const o=s.id.toLowerCase(),l=new Set((s.tags??[]).map(Ka)),m=new Set(an(s.content??"").map(u=>u.toLowerCase())),x=[];for(const u of r){if(u.id.toLowerCase()===o)continue;const h=[];for(const N of u.tags??[])l.has(Ka(N))&&h.push(N);let f=0;for(const N of an(u.content??""))m.has(N.toLowerCase())&&f++;const j=h.length*Lo+f*Mo;j>0&&x.push({id:u.id,title:u.title,score:j,sharedTags:h})}return x.sort((u,h)=>h.score-u.score||u.title.localeCompare(h.title)).slice(0,n)}function Xa(s){const r=s.lastIndexOf("/");return r>=0?s.slice(r+1):s}function Po(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Vo(s){return(s??"").replace(/\[\[[^\]]*\]\]/g," ")}function Oo(s,r){const n=s.id.toLowerCase(),o=(s.title??"").trim();if(!o)return[];const l=o.toLowerCase(),m=Xa(s.id).toLowerCase(),x=new RegExp(`\\b${Po(l)}\\b`),u=f=>an(f).some(j=>{const N=j.toLowerCase();return N===n||N===l||Xa(j).toLowerCase()===m}),h=[];for(const f of r){if(f.id.toLowerCase()===n)continue;const j=f.content??"";u(j)||x.test(Vo(j).toLowerCase())&&h.push({id:f.id,title:f.title})}return h}const qo={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 * *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@midnight":"0 0 * * *","@hourly":"0 * * * *"},zo=[{label:"minute",min:0,max:59},{label:"hour",min:0,max:23},{label:"day of month",min:1,max:31},{label:"month",min:1,max:12},{label:"day of week",min:0,max:7}],_o=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Ho=["","January","February","March","April","May","June","July","August","September","October","November","December"],Ya=s=>s.padStart(2,"0"),tt=s=>/^\d+$/.test(s);function Bo(s,r){for(const n of s.split(",")){const o=/^(\*|\d+(?:-\d+)?)(?:\/(\d+))?$/.exec(n);if(!o)return`"${n}" isn't a valid ${r.label} (use a number, a range like 1-5, \`*\`, or \`*/n\`)`;const[,l,m]=o;if(m!==void 0&&Number(m)<=0)return`the step in "${n}" must be greater than zero`;if(l!=="*"){const x=l.split("-").map(Number);for(const u of x)if(u<r.min||u>r.max)return`${r.label} must be between ${r.min} and ${r.max} (got ${u} in "${n}")`;if(x.length===2&&x[0]>x[1])return`the range "${n}" is backwards — ${x[0]} is after ${x[1]}`}}return null}function Wo(s){const[r,n,o,l,m]=s,x=o==="*"&&l==="*"&&m==="*";if(r==="*"&&n==="*"&&x)return"Runs every minute";if(tt(r)&&tt(n)){const u=`${Ya(n)}:${Ya(r)}`;if(x)return`Runs daily at ${u}`;if(o==="*"&&l==="*"&&tt(m))return`Runs weekly on ${_o[Number(m)%7]} at ${u}`;if(tt(o)&&l==="*"&&m==="*")return`Runs monthly on day ${o} at ${u}`;if(tt(o)&&tt(l)&&m==="*")return`Runs yearly on ${Ho[Number(l)]} ${o} at ${u}`}return r.startsWith("*/")&&n==="*"&&x?`Runs every ${r.slice(2)} minutes`:tt(r)&&n==="*"&&x?r==="0"?"Runs hourly, on the hour":`Runs hourly at minute ${r}`:tt(r)&&n.startsWith("*/")&&x?`Runs at minute ${r} past every ${n.slice(2)} hours`:"Runs on a custom schedule (minute hour day-of-month month day-of-week)"}function Uo(s){const n=(qo[s.toLowerCase()]??s).trim().split(/\s+/);if(n.length!==5)return{kind:"invalid",error:`A cron schedule needs 5 space-separated fields (minute hour day month weekday) — got ${n.length}`};for(let o=0;o<5;o++){const l=Bo(n[o],zo[o]);if(l)return{kind:"invalid",error:l}}return{kind:"valid",description:Wo(n)}}const Qo={s:1,m:60,h:3600,d:86400};function Go(s){const r=s.slice(6).trim(),n=/(\d+)(s|m|h|d)/gi;let o,l=0,m=0;for(;o=n.exec(r);)l+=Number(o[1])*Qo[o[2].toLowerCase()],m+=o[0].length;if(m===0||m!==r.replace(/\s+/g,"").length)return{kind:"invalid",error:`"${r}" isn't a valid duration — use a number plus s/m/h/d, e.g. "15m" or "1h30m"`};if(l<=0)return{kind:"invalid",error:"the interval must be greater than zero"};const x=[],u=Math.floor(l/86400),h=Math.floor(l%86400/3600),f=Math.floor(l%3600/60),j=l%60;return u&&x.push(`${u} day${u===1?"":"s"}`),h&&x.push(`${h} hour${h===1?"":"s"}`),f&&x.push(`${f} minute${f===1?"":"s"}`),j&&x.push(`${j} second${j===1?"":"s"}`),{kind:"valid",description:`Runs every ${x.join(" ")}`}}function Ko(s){const r=s.trim();return r?r.toLowerCase().startsWith("@every")?Go(r):Uo(r):{kind:"empty"}}function Ns(s){return s?/^\s*</.test(s):!1}function Za(s){switch(s){case"html":return"raw HTML (served as a sandboxed page)";case"csv":return"CSV data";case"code":return"code (tool source)";default:return"formatted document prose"}}function Ja(s){if(!s)return"";if(typeof DOMParser>"u")return s.trim();try{return(new DOMParser().parseFromString(s,"text/html").body.innerHTML||"").replace(/\s+/g," ").trim()}catch{return s.trim()}}function $c({nestId:s,nestName:r,nodeId:n,initialFolder:o,initialThreadId:l,isOwner:m=!1,onBack:x,onSaved:u,onNavigateDocument:h,onTagClick:f,onOpenNest:j,onOpenFolder:N,onCreateDocument:v,initialTitle:g,breadcrumb:w,onJumpBreadcrumb:z,sidebarCollapsed:V=!1,onToggleSidebar:A}){var na,aa,ra,ia,la,oa,ca,da,ua,ma,ha,xa,fa;const d=n==="new",H=bl(),{adminStatus:C,isAdmin:X,workflowPlaneEnabled:se,typeArtifactEnabled:ne,typeTableEnabled:S}=hn(),F=((aa=(na=C==null?void 0:C.me)==null?void 0:na.email)==null?void 0:aa.toLowerCase())??"",Y=m||X,[ce,Ne]=a.useState(!1),[nt,ke]=a.useState(!1),[kt,Ge]=a.useState(!1),b=Ds(),L=Di(s),Z=$i(s),Ke=Ei(s,d?void 0:n),Pe=a.useMemo(()=>{var t;return(((t=Ke.data)==null?void 0:t.stewards)??[]).filter(i=>(i.email||"").toLowerCase()===F).map(i=>String(i.role))},[Ke.data,F]),ts=d||!Ke.isLoading,[at,St]=a.useState(null),ss=at==="write",de=((ra=L.data)==null?void 0:ra.myStewards)??[],[T,Se]=a.useState(d&&g?g:"");Ai([{label:d?"New document":T.trim()||"Untitled"}]);const[Ce,Ve]=a.useState(o??""),[$,_]=a.useState(""),[B,Oe]=a.useState([]),[pe,Re]=a.useState(""),[ae,Xe]=a.useState(null),rt=a.useRef(null),Vt=((ia=Z.data)==null?void 0:ia.prime_tags)??[],[ue,it]=a.useState(null),[ge,Ot]=a.useState(null),[W,qe]=a.useState(null),[Ct,qt]=a.useState(!1),[J,zt]=a.useState(null),[Rt,lt]=a.useState(!1),[Ee,ze]=a.useState(""),[_e,_t]=a.useState(void 0),[re,Te]=a.useState(null),[Ye,Es]=a.useState(null),[Tt,Dt]=a.useState(null),[Ze,As]=a.useState([]),[ns,as]=a.useState(null),[be,rs]=a.useState(null),ot=!!((la=Z.data)!=null&&la.stewardship_enabled),Ht=!!((oa=Z.data)!=null&&oa.allow_self_approve),$t=((ca=L.data)==null?void 0:ca.permission)??null,we=Li((da=L.data)==null?void 0:da.nest),{hasAdminApprove:Bt,isViewOnly:I,isReviewerOnly:U,canEditContent:Ae}=xo({isNew:d,isOwner:m,isAdmin:X,permission:$t,nestStewards:de,nodeRoles:Pe,grant:at,isArchived:we}),c=!!Ye&&!!((ua=C==null?void 0:C.me)!=null&&ua.email)&&Ye.toLowerCase()===C.me.email.toLowerCase(),R=!we&&(m||X||$t==="owner"||$t==="admin"||c),P=!we&&(R||$t==="write"||ss||Pe.includes("editor")||de.some(t=>t.role==="editor"&&t.scope==="nest")),[le,He]=a.useState(!1),[is,pn]=a.useState(!1),[me,Ls]=a.useState(null),Ms=(me==null?void 0:me.status)==="pending",[Nr,gn]=a.useState(!1),[Q,ct]=a.useState(d?"edit":"view"),[Fs,bn]=a.useState(!1),[ve,wn]=a.useState("document"),[ls,os]=a.useState(null),dt=d&&ve==="artifact",cs=t=>t==="artifact"?"html":t==="table"?"csv":t==="tool"?"code":"markdown",kr=(t,i)=>{if(t!==ve&&$.trim()&&cs(t)!==cs(ve)){os({value:t,label:i});return}wn(t)},Le=d?ve:ue??"document",Et=!d&&ue==="pdf",Ps=Le==="tool"||Le==="table",Wt=d?ve==="agent"||ve==="skill":ue==="agent"||ue==="skill",vn=`${typeof window<"u"?window.location.origin:""}/nests/${s}/runnables`,[Sr,jn]=a.useState(!1),Cr=async()=>{await Na(vn)&&(jn(!0),setTimeout(()=>jn(!1),1500))},[he,Ut]=a.useState(!1),[Vs,Os]=a.useState(null),[Qt,Be]=a.useState(null),yn=a.useRef(null),Gt=a.useRef(null),Nn=a.useRef(null),[ut,Rr]=a.useState([]),[Kt,At]=a.useState(null),[We,kn]=a.useState(()=>Mi(localStorage).commentsOpen),Tr=t=>{kn(t),Ji(localStorage,{commentsOpen:t})},Sn=a.useMemo(()=>Q==="view"&&!Ns($)?wl($):[],[Q,$]),qs=!d&&Sn.length>=3,ds=a.useRef(!1);a.useEffect(()=>{kn(t=>Fi(t,{initialThreadId:ds.current?null:l,commentMode:he,pendingAnchor:!!Vs,activeThreadId:Kt}))},[l,he,Vs,Kt]);const Cn=ut.filter(t=>t.status==="open").length,Je=a.useRef([]),Xt=a.useRef(null);a.useEffect(()=>{var i;if(!l||ds.current)return;const t=ut.find(p=>p.id===l);t&&(ds.current=!0,Ut(!0),ct("view"),At(t.id),(i=t.anchor)!=null&&i.quote&&(Xt.current=t.id))},[ut,l]);const Dr=a.useCallback(()=>{const t=window.getSelection();if(!t||t.isCollapsed||t.rangeCount===0){Be(null);return}const i=t.getRangeAt(0),p=Gt.current;if(!p||!p.contains(i.commonAncestorContainer)){Be(null);return}if(!t.toString().trim()){Be(null);return}const D=(hi,xi)=>{const Gs=document.createRange();return Gs.setStart(p,0),Gs.setEnd(hi,xi),Gs.toString().length},O=document.createRange();O.selectNodeContents(p);const M=O.toString();let q=D(i.startContainer,i.startOffset),E=D(i.endContainer,i.endOffset);for(q>E&&([q,E]=[E,q]);q<E&&/\s/.test(M[q]);)q++;for(;E>q&&/\s/.test(M[E-1]);)E--;const G=M.slice(q,E);if(!G){Be(null);return}const ys=M.slice(Math.max(0,q-250),q),ui=M.slice(E,E+250),pa=$.indexOf(G),mi=pa>=0?$.slice(0,pa).split(`
|
|
36
|
-
`).length:void 0;yn.current={quote:G,before:ys,after:ui,line:mi};const Qs=i.getBoundingClientRect();Be({x:Qs.left+Qs.width/2,y:Qs.top})},[$]),$r=a.useCallback(()=>{var i;const t=yn.current;t&&(Os(t),Be(null),(i=window.getSelection())==null||i.removeAllRanges())},[]);a.useEffect(()=>{const t=Gt.current,i=!d&&(he||Q==="view")&&!Fs&&J==null&&!Ns($);if(!t||!i){Je.current=[],Qa("comment-anchor"),Qa("comment-anchor-active");return}const p=requestAnimationFrame(()=>{var M,q;const D=$o(t),O=[];for(const E of ut){if(!((M=E.anchor)!=null&&M.quote))continue;const G=Ao(t,D,E.anchor);G&&O.push({id:E.id,range:G})}if(Je.current=O,Ua("comment-anchor",O.map(E=>E.range)),Xt.current){const E=O.find(G=>G.id===Xt.current);E&&((q=E.range.startContainer.parentElement)==null||q.scrollIntoView({behavior:"smooth",block:"center"}),At(E.id)),Xt.current=null}});return()=>cancelAnimationFrame(p)},[ut,$,Q,Fs,J,d,he]),a.useEffect(()=>{const t=Je.current.find(i=>i.id===Kt);Ua("comment-anchor-active",t?[t.range]:[])},[Kt]);const Er=a.useCallback(t=>{var O,M;const i=ut.find(q=>{var E,G;return((E=q.anchor)==null?void 0:E.quote)===t.quote&&((G=q.anchor)==null?void 0:G.before)===t.before});i&&At(i.id);const p=(O=Je.current.find(q=>q.id===(i==null?void 0:i.id)))==null?void 0:O.range;if(p){(M=p.startContainer.parentElement)==null||M.scrollIntoView({behavior:"smooth",block:"center"});return}if(!(he||Q==="view")&&!Ns($)){Xt.current=(i==null?void 0:i.id)??null,Ut(!0),ct("view");return}k.message("That highlighted text isn't in the current version.")},[ut,he,Q,$]),Ar=a.useCallback(t=>{if(!Je.current.length)return;const i=Ga(t.clientX,t.clientY);if(i)for(const{id:p,range:D}of Je.current)try{if(D.isPointInRange(i.node,i.offset)){At(p);return}}catch{}},[]),Lr=a.useCallback(t=>{const i=Gt.current;if(!i)return;if(!Je.current.length){i.style.cursor="";return}const p=Ga(t.clientX,t.clientY);let D=!1;if(p)for(const{range:O}of Je.current)try{if(O.isPointInRange(p.node,p.offset)){D=!0;break}}catch{}i.style.cursor=D?"pointer":""},[]);a.useEffect(()=>{if(!Qt)return;const t=i=>{var D;const p=i.target;p.closest('[data-testid="selection-comment-button"]')||(D=Gt.current)!=null&&D.contains(p)||Be(null)};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[Qt]);const us=a.useRef(null),Rn=a.useRef(null);a.useEffect(()=>{var t;d&&((t=Rn.current)==null||t.focus())},[]);const ms=a.useRef({title:d&&g?g:"",content:"",tags:[],schedule:""}),zs=a.useRef(""),[je,Tn]=a.useState(!d),[xe,Mr]=a.useState([]),[Dn,Fr]=a.useState([]);a.useEffect(()=>{if(je)return;let t=!1;return(async()=>{try{const{census:i}=await b.fetchQuery(ye.census(s));t||Fr(i.folders.map(p=>p.path))}catch{}})(),()=>{t=!0}},[je,s,b]),a.useEffect(()=>{if(je)return;let t=!1;return(async()=>{try{const{nodes:i}=await b.fetchQuery(ye.nodes(s));t||Mr(i)}catch{}})(),()=>{t=!0}},[d,je,s]);const $n=a.useMemo(()=>{const t=new Set(Dn);for(const i of xe){const D=(i.id.startsWith("nodes/")?i.id.slice(6):i.id).split("/").slice(0,-1);for(let O=1;O<=D.length;O++)t.add(D.slice(0,O).join("/"))}return[...t].sort()},[xe,Dn]),Pr=a.useMemo(()=>{if(d||!n)return[];const i=(n.startsWith("nodes/")?n.slice(6):n).split("/").slice(0,-1);return i.map((p,D)=>({path:i.slice(0,D+1).join("/"),label:tn(p)}))},[d,n]),[Ue,Yt]=a.useState(null),[Ie,hs]=a.useState(null),[xs,En]=a.useState(!1),fs=a.useMemo(()=>[{value:"document",label:"Document",Icon:Js,expects:"Markdown prose."},...ne?[{value:"artifact",label:"Artifact",Icon:es,expects:"An HTML page — the body is hosted and rendered as-is."}]:[],...S?[{value:"table",label:"Table",Icon:sn,expects:"CSV — one header row, then data rows."}]:[],...se?[{value:"agent",label:"Agent",Icon:wa,expects:"Markdown instructions an orchestrator runs; can carry a schedule."},{value:"skill",label:"Skill",Icon:$a,expects:"Markdown instructions with a trigger (defaulted from the title)."},{value:"tool",label:"Tool",Icon:Ta,expects:"Source code, shown and edited as code."}]:[]].filter(i=>i.value!==(ue??"document")),[ne,S,se,ue]),Vr=async()=>{var t;if(!(!Ie||d)){En(!0);try{await Ss(s,n,{type:Ie}),Xs(b,`/nests/${s}/nodes/${n}`),k.success(`Turned into ${((t=fs.find(i=>i.value===Ie))==null?void 0:t.label)??Ie}`),hs(null),await oe()}catch(i){k.error(i instanceof Error?i.message:"Failed to convert")}finally{En(!1)}}},[ps,An]=a.useState(!1),Ln=a.useMemo(()=>d||!n?"":(n.startsWith("nodes/")?n.slice(6):n).split("/").slice(0,-1).join("/"),[d,n]),gs=a.useMemo(()=>d?[]:Fl(xe,{id:n,title:T}),[d,xe,n,T]),Mn=a.useMemo(()=>d?[]:Fo({id:n,tags:B,content:$},xe),[d,xe,n,T,B,$]),bs=a.useMemo(()=>d?[]:Oo({id:n,title:T},xe),[d,xe,n,T]),Lt=a.useMemo(()=>d?[]:Pl($,xe),[d,$,xe]),Or=a.useCallback(t=>{const i=vl(xe,t);return i?{title:i.title,snippet:jl(i.content??"")}:null},[xe]),[Qe,Fn]=a.useState(!1),[Zt,Jt]=a.useState(null),[qr,Pn]=a.useState(!1),[Mt,K]=a.useState(!1),[_s,Vn]=a.useState(!1),[zr,_r]=a.useState(!1),[On,ws]=a.useState(null),oe=a.useCallback(async()=>{if(!d){Tn(!0),Pn(!1);try{const{node:t}=await b.fetchQuery(ye.node(s,n)),i=(t==null?void 0:t.title)==null?"":String(t.title),p=(t==null?void 0:t.content)==null?"":String(t.content),D=Array.isArray(t==null?void 0:t.tags)?Fa([],t.tags.map(E=>un(String(E)))):[];Se(i),_(p),Oe(D),it((t==null?void 0:t.type)??null),Ot((t==null?void 0:t.type)==="pdf"&&(t!=null&&t.pdf)?t.pdf:null);const O=(t==null?void 0:t.schedule)==null?"":String(t.schedule);Re(O);const M=typeof(t==null?void 0:t.prime)=="boolean"?t.prime:null;Xe(M),rt.current=M,_t(t==null?void 0:t.version),Te((t==null?void 0:t.status)??null),Es((t==null?void 0:t.author)??null),Dt((t==null?void 0:t.updated_at)??null),As(Array.isArray(t==null?void 0:t.collaborators)?t.collaborators.map(E=>String(E)):[]),as((t==null?void 0:t.pendingChange)??null),rs((t==null?void 0:t.pendingReviewBy)??null),Ls((t==null?void 0:t.deletionRequest)??null),St((t==null?void 0:t.myGrant)??null),ms.current={title:i,content:p,tags:D,schedule:O},zs.current=i,K(!1);const q=Pi(s,n);ws(null),q&&(q.baseVersion!==(t==null?void 0:t.version)?Ks(s,n):(Se(q.title),_(q.content),Oe(q.tags),Re(q.schedule),K(!0),ws(q.savedAt??Date.now())))}catch(t){Jt(t.message),Pn(!0)}finally{Tn(!1)}}},[d,s,n]),et=a.useCallback(async()=>{if(d){qe(null);return}try{qe(await b.fetchQuery(ye.nodeVersions(s,n)))}catch(t){console.error("[DocumentEditor] getNodeVersions failed",s,n,t),qe(null),k.error((t==null?void 0:t.message)||"Failed to load version history")}},[d,s,n]);a.useEffect(()=>{d||oe()},[d,oe]);const Hr=a.useCallback(async()=>{qt(!0),await et()},[et]),[qn,zn]=a.useState(!1),[Br,Hs]=a.useState(!1),Wr=a.useCallback(async()=>{Hs(!1),zn(!0);try{const t=await va(s,n);if(t.deleted){k.success("Never approved — document deleted"),x();return}k.success(`Draft discarded — back to version ${t.version}`),await Promise.all([oe(),et()])}catch(t){k.error((t==null?void 0:t.message)||"Discard failed")}finally{zn(!1)}},[s,n,T,x,oe,et]),Ur=a.useCallback(async()=>{W||await et()},[W,et]),[Bs,_n]=a.useState(null),Ws=a.useCallback(async t=>{if(zt(t),lt(!1),_n(null),t!=null)try{const{content:i}=await Is(s,n,t);_n({version:t,content:i??""})}catch(i){k.error((i==null?void 0:i.message)||`Failed to load version ${t}`),zt(null)}},[s,n]),Us=re==="pending_review"&&!!be&&!!F&&be.toLowerCase()===F,fe=re==="pending_review"&&!Us,Hn=!d&&!fe&&!Et&&fs.length>0,mt=d?ve:ue??"document",ie=fe||Q!=="edit",Qr=a.useMemo(()=>T.trim().length>0&&$.trim().length>0&&!Qe,[T,$,Qe]),te=a.useMemo(()=>{if(!Mt)return!1;const t=ms.current;if(T.trim()!==t.title.trim()||Ja($)!==Ja(t.content)||B.length!==t.tags.length)return!0;for(let i=0;i<B.length;i++)if(B[i]!==t.tags[i])return!0;return pe.trim()!==t.schedule.trim()||ae!==rt.current},[Mt,T,$,B,pe,ae]),Bn=Qr&&(d||te),vs=a.useRef(!1),ht=a.useRef(0);a.useEffect(()=>{if(!te||U)return;const t=i=>{vs.current||i.preventDefault()};return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[te,U]),a.useEffect(()=>(ja(t=>!te||U?!1:(pt({label:"leave this document",run:t}),!0)),()=>ja(null)),[te,U]),a.useEffect(()=>{if(!te||U)return;vs.current=!1,ht.current=0;const t=()=>{window.history.pushState({cnLeaveGuard:!0},""),ht.current++};t();const i=()=>{ht.current=Math.max(0,ht.current-1),t(),pt(p=>p??{label:"leave this page",run:()=>{vs.current=!0,window.history.go(-(ht.current+1))}})};return window.addEventListener("popstate",i),()=>{var p;window.removeEventListener("popstate",i),!vs.current&&ht.current>0&&((p=window.history.state)!=null&&p.cnLeaveGuard)&&window.history.go(-ht.current)}},[te,U]);const xt=a.useMemo(()=>Ko(pe),[pe]),[Wn,Gr]=a.useState("");a.useEffect(()=>{if(!dt)return;const t=setTimeout(()=>Gr($),400);return()=>clearTimeout(t)},[$,dt]);const Kr=a.useDeferredValue($),Ft=a.useMemo(()=>{const t=Ee.split(/[\s,]+/).map(vr),i=t.map(p=>p.tag).filter(p=>!!p);return{tags:Fa(B,i),notes:t.map(p=>p.note).filter(Boolean)}},[Ee,B]),Un=a.useCallback(()=>{const{tags:t,notes:i}=Ft;if(i.length===1?k.warning(i[0]):i.length>1&&k.warning(`${i.length} tags normalized`,{description:i.join(" "),duration:8e3}),t.length===0){ze("");return}Oe([...B,...t]),ze(""),K(!0),k.success(t.length===1?`Tag "${t[0]}" added`:`${t.length} tags added`,{id:"tag-added",description:"Save the document to keep it."})},[Ft,B]),Xr=t=>{Oe(B.filter(i=>i!==t)),K(!0)},Yr=async()=>{var D,O,M,q;if(!d&&!te)return K(!1),k.message("Not saved — no changes were made. Edit the document, then save again."),{ok:!0,savedId:n,noop:!0};const t={title:T.trim(),content:$,tags:B};let i,p;if(d){const E=await nl(s,{...t,type:ve,...Ce.trim()?{folder:Ce.trim()}:{},...Wt?{schedule:pe.trim()}:{},...ae===null?{}:{prime:ae}});i=(D=E==null?void 0:E.node)==null?void 0:D.id,p=(O=E==null?void 0:E.node)==null?void 0:O.status}else{const E=ae===rt.current?{}:{prime:ae},G=await Ss(s,n,Wt?{...t,...E,schedule:pe.trim()}:{...t,...E},_e);rt.current=ae;const ys=(G==null?void 0:G.version)??((M=G==null?void 0:G.node)==null?void 0:M.version);typeof ys=="number"&&_t(ys),Dt(((q=G==null?void 0:G.node)==null?void 0:q.updated_at)??new Date().toISOString()),i=n}return ms.current={title:t.title,content:$,tags:[...B],schedule:pe.trim()},d||Ks(s,n),K(!1),ws(null),{ok:!0,savedId:i,...d?{createdStatus:p}:{}}},[ft,pt]=a.useState(null),Qn=async t=>{if(!Bn){Jt(d?"Add a title and content before saving.":"Current document can't be saved — fix errors before leaving.");return}Fn(!0),Jt(null);try{const{savedId:i,noop:p,createdStatus:D}=await Yr();p||Vn(!0),d&&i&&k.success(D==="published"?`"${T.trim()||"Untitled"}" published — it's now live and available for use.`:`"${T.trim()||"Untitled"}" saved as a draft.`),Sa(()=>t(i??""))}catch(i){Jt(i.message)}finally{Fn(!1)}},Gn=()=>Qn(t=>u==null?void 0:u(t));a.useEffect(()=>{te&&Vn(!1)},[te]);const Kn=a.useRef(()=>{});Kn.current=()=>{if(d||fe||U||I||!te)return;const t=Vi(s,n,{title:T,content:$,tags:[...B],schedule:pe.trim(),baseVersion:_e});_r(!t)};const gt=a.useCallback(()=>{Kn.current()},[]),Me=(t,i)=>{if(!te||U){i();return}pt({label:t,run:i})},Zr=()=>Qn(()=>{const t=ft==null?void 0:ft.run;pt(null),t==null||t()}),Xn=()=>{d||Ks(s,n);const t=ms.current;Se(t.title),_(t.content),Oe([...t.tags]),Re(t.schedule),K(!1),ws(null)},Jr=()=>{if(!ft)return;const t=ft.run;Xn(),pt(null),Sa(t)},Ir=async(t,i)=>{d||(await tl(s,n,t,i),He(!1),await oe())},ei=async t=>{d||(await Zi(s,n,t),await oe())},ti=async t=>{d||(await Yi(s,n,t),await oe())},si=async()=>{if(!d)try{await Ii(s,n),k.success("Submission withdrawn — back to Draft"),await oe()}catch(t){console.error("[DocumentEditor] cancelReview failed",s,n,t),k.error((t==null?void 0:t.message)||"Failed to withdraw submission")}},ni=async t=>{if(d)return;const{request:i}=await Ki(s,n,t);Ls(i),k.success("Deletion requested — a nest admin will review it")},ai=async()=>{d||(await Gi(s,n),k.success(`Deleted "${T||n}"`),x())},ri=Pe.includes("reviewer"),ii=Us,js=Vt.length>0&&B.some(t=>Vt.includes(t.trim().replace(/^#+/,"").toLowerCase())),Yn=ae===null?js:ae,li=m||Bt,oi=!d&&re==="pending_review"&&(Bt||ri||m&&Ht)&&(!ii||m&&Ht),Zn=a.useRef(!1);a.useEffect(()=>{Zn.current||je||!ts||(Zn.current=!0,re==="pending_review"&&U&&Ut(!0))},[je,ts,re,U]),a.useEffect(()=>{je||Q==="edit"||he||Et||!I&&!fe&&!U&&ct("edit")},[je,I,fe,U,Q,he,Et]),a.useEffect(()=>{fe&&Q==="edit"&&ct("view")},[fe,Q]);const Jn=!d&&ot&&re==="draft"&&!U,ci=t=>{var i;(i=us.current)==null||i.insertWikiLink(t.id,t.title)},In=async(t,i)=>{try{const{nodes:p}=await b.fetchQuery(ye.nodes(s)),M=Dl(p,t,!U&&!I);M.kind==="navigate"?Me(`open "${M.node.title}"`,()=>h==null?void 0:h(s,M.node.id,T)):M.kind==="create"?Me(`create "${M.title}"`,()=>v==null?void 0:v(s,M.title)):Jt(`"${M.title}" doesn't exist in this nest. You only have view access — ask someone with edit rights to add it.`)}catch{}},di=Ms&&((ma=me==null?void 0:me.requestedBy)==null?void 0:ma.toLowerCase())===F,ea=t=>fo({isNew:d,canShare:Y,isArchived:we,canEditContent:Ae,isLocked:fe,canRequestDeletion:P,canDeleteDirectly:R,deletionRequested:Ms,isOwnDeletionRequest:di,includeVersionHistory:t.includeVersionHistory}).map(i=>{const p={label:i.label,testId:i.testId,separatorBefore:i.separatorBefore,destructive:i.destructive};switch(i.key){case"history":return{...p,icon:pr,onSelect:Hr};case"copy-link":return{...p,icon:Rl,onSelect:()=>{const D=`${window.location.origin}${sl(s)}?doc=${encodeURIComponent(n)}`;Na(D,"Link copied — recipient needs access to this nest")}};case"move":return{...p,icon:Ea,onSelect:()=>Yt(Ln)};case"share-doc":return{...p,icon:dn,onSelect:()=>Ge(!0)};case"publish":return{...p,icon:dn,onSelect:()=>ke(!0)};case"delete":case"request-deletion":return{...p,icon:cn,onSelect:()=>pn(!0)};case"withdraw-deletion":return{...p,icon:st,onSelect:async()=>{try{await Xi(s,me.id),Ls(null),k.success("Deletion request withdrawn")}catch(D){k.error(D instanceof Error?D.message:"Failed to withdraw request")}}}}}),ta=e.jsx(e.Fragment,{children:!d&&(Y&&!we?e.jsx(xr,{nestId:s,variant:"compact",onChanged:()=>void b.invalidateQueries({queryKey:Oi.nest(s)}),onError:t=>{t&&k.error(t)}}):((xa=(ha=L.data)==null?void 0:ha.nest)==null?void 0:xa.visibility)&&e.jsxs("span",{className:"hidden sm:inline-flex items-center gap-1 px-1.5 text-xs text-muted-foreground",title:L.data.nest.visibility==="public"?"Public — anyone with the URL can read":L.data.nest.visibility==="org"?"Organization — everyone signed in here can read":"Private","data-testid":"document-editor-visibility",children:[L.data.nest.visibility==="public"?e.jsx(qi,{className:"h-3.5 w-3.5"}):L.data.nest.visibility==="org"?e.jsx(zi,{className:"h-3.5 w-3.5"}):e.jsx(_i,{className:"h-3.5 w-3.5"}),L.data.nest.visibility==="public"?"Public":L.data.nest.visibility==="org"?"Organization":"Private"]}))}),sa=e.jsxs(e.Fragment,{children:[!d&&e.jsx(no,{open:is,onOpenChange:pn,title:R?`Delete "${T||n}"?`:`Request deletion of "${T||n}"`,description:R?"This removes the document, its version history, comments and annotations. It cannot be undone.":"A nest admin reviews this and either deletes the document or rejects with a note. Nothing is removed yet.",label:R?void 0:"Why should it be deleted?",placeholder:"e.g. superseded by the new runbook",confirmLabel:R?"Delete document":"Request deletion",destructive:R,priorDecline:!R&&(me==null?void 0:me.status)==="declined"?me:null,onConfirm:R?ai:ni}),e.jsx(bt,{open:Ue!==null,onOpenChange:t=>{!t&&!ps&&Yt(null)},children:e.jsxs(wt,{className:"sm:max-w-[440px]",children:[e.jsx(vt,{children:e.jsx(jt,{children:"Move to folder"})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Move ",e.jsx("strong",{children:T||n})," to another folder. Version history, review state, and [[wiki links]] follow the document."]}),e.jsxs(El,{value:Ue===""?"__root__":Ue??"__root__",onValueChange:t=>Yt(t==="__root__"?"":t),children:[e.jsx(Al,{"data-testid":"document-editor-move-select",children:e.jsx(Ll,{placeholder:"Choose a folder"})}),e.jsxs(Ml,{children:[e.jsx(Da,{value:"__root__",children:"Nest root"}),$n.map(t=>e.jsx(Da,{value:t,children:Hi(t)},t))]})]}),e.jsxs(yt,{children:[e.jsx(y,{variant:"ghost",disabled:ps,onClick:()=>Yt(null),children:"Cancel"}),e.jsxs(y,{disabled:ps||Ue===null||Ue===Ln,"data-testid":"document-editor-move-confirm",onClick:async()=>{if(Ue!==null){An(!0);try{const{node:t}=await Bi(s,n,Ue);k.success(Ue?`Moved to ${Ue}`:"Moved to nest root"),Yt(null),u==null||u(t.id)}catch(t){k.error((t==null?void 0:t.message)||"Move failed")}finally{An(!1)}}},children:[ps?e.jsx(ee,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ea,{className:"h-4 w-4 mr-2"}),"Move"]})]})]})}),kt&&e.jsx(Vl,{nestId:s,targetType:"document",target:n,label:T||n,archived:we,onClose:()=>Ge(!1)}),ce&&e.jsx(Co,{nestId:s,nestName:r,stewardshipEnabled:ot,onClose:()=>Ne(!1),onChanged:()=>{}}),nt&&e.jsx(Ol,{nestId:s,nodeId:n,nodeTitle:T||n,onClose:()=>ke(!1)})]});return!d&&!je&&qr?e.jsx("div",{className:"mt-14 md:mt-0","data-testid":"document-not-found",children:e.jsxs("div",{className:"max-w-xl mx-auto py-16 text-center space-y-4",children:[e.jsx(br,{className:"h-10 w-10 mx-auto text-muted-foreground"}),e.jsx("h2",{className:"text-xl font-semibold",children:"Document not found"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:Zt??`Nothing lives at ${n} in this nest — the link may be stale or the document may have been moved or deleted.`}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsxs(y,{variant:"outline",onClick:()=>void oe(),children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Try again"]}),e.jsxs(y,{onClick:x,children:[e.jsx(rn,{className:"h-4 w-4 mr-2"}),"Back to documents"]})]})]})}):!d&&!je&&ue===jo?e.jsxs(e.Fragment,{children:[e.jsx(No,{nestId:s,nodeId:n,title:T,snapshotVersion:null,currentEmail:F,viewOnly:I,reviewerOnly:U,initialThreadId:l,onBack:x,onTurnedInto:()=>{Xs(b,`/nests/${s}/nodes/${n}`),oe()},onShareNest:Y&&!we?()=>Ne(!0):void 0,visibilityControl:ta,actions:ea({includeVersionHistory:!1})}),sa]}):e.jsxs("div",{className:"flex min-h-full flex-col","data-testid":"document-page",children:[e.jsxs("div",{className:"sticky top-16 z-30 flex h-12 items-center gap-2 border-b bg-background/95 px-2 backdrop-blur supports-[backdrop-filter]:bg-background/80 sm:px-3","data-testid":"document-editor-topbar",children:[e.jsxs("div",{className:"flex items-center gap-1 min-w-0 flex-1",children:[V&&A&&e.jsx(y,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:A,title:"Show sidebar","aria-label":"Show sidebar","data-testid":"document-sidebar-expand",children:e.jsx(Wi,{className:"h-4 w-4"})}),e.jsx(y,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>Me("go back",x),title:"Back to documents","data-testid":"document-editor-back",children:e.jsx(rn,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-nowrap overflow-hidden",children:[e.jsx("button",{type:"button",onClick:()=>j&&Me("go to the nest",j),disabled:!j,className:"text-sm text-muted-foreground truncate hover:text-foreground hover:underline underline-offset-2 disabled:no-underline disabled:hover:text-muted-foreground disabled:cursor-default",title:j?`Open ${r}`:r,children:r}),w==null?void 0:w.map((t,i)=>e.jsxs(a.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground shrink-0",children:"›"}),e.jsx("button",{type:"button",onClick:()=>Me(`go to "${t.title}"`,()=>z==null?void 0:z(i)),className:"text-sm text-muted-foreground hover:text-foreground hover:underline underline-offset-2 truncate max-w-[160px]",title:t.title,"data-testid":`document-editor-breadcrumb-${i}`,children:t.title})]},`${t.nestId}/${t.nodeId}/${i}`)),Pr.map((t,i)=>e.jsxs(a.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground shrink-0",children:"›"}),e.jsx("button",{type:"button",onClick:()=>N&&Me(`open "${t.label}"`,()=>N(t.path)),disabled:!N,className:"text-sm text-muted-foreground truncate max-w-[160px] hover:text-foreground hover:underline underline-offset-2 disabled:no-underline disabled:hover:text-muted-foreground disabled:cursor-default",title:t.path,children:t.label})]},`folder-${i}`)),!d&&re&&e.jsx(Xo,{status:re}),!d&&Ms&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs border bg-red-50 text-red-700 border-red-200 whitespace-nowrap",title:`${me.requestedBy} asked for this to be deleted: "${me.reason}". A nest admin decides.`,"data-testid":"deletion-requested-badge",children:[e.jsx(cn,{className:"h-3 w-3"}),"Deletion requested"]}),!d&&!ot&&re==="published"&&e.jsx("span",{className:"hidden sm:inline px-1.5 py-0.5 rounded text-xs bg-green-50 text-green-700 border border-green-200 whitespace-nowrap",title:"Stewardship off — saving auto-publishes.",children:"Auto-published"})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0","data-testid":"document-editor-actions",children:[(()=>{if(te)return e.jsxs("span",{className:"hidden sm:inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs border bg-amber-50 text-amber-800 border-amber-200 dark:bg-amber-950/40 dark:text-amber-300 dark:border-amber-900",title:"These edits are parked locally and not yet saved to the nest.","data-testid":"document-editor-dirty-badge",children:[e.jsx(ya,{className:"h-3 w-3"}),"Unsaved changes"]});const t=Qe?"Saving…":_s?"Saved":Tt?`Edited ${Ca(Tt)}`:null;return t?e.jsx("span",{className:"hidden sm:inline px-1.5 text-xs text-muted-foreground",title:Tt?Cs(Tt):void 0,children:t}):null})(),oi&&e.jsx(Ul,{documentTitle:T,version:_e??1,onApprove:ei,onReject:ti}),ta,Y&&!we&&e.jsxs(y,{variant:"ghost",size:"sm",className:"h-8",onClick:()=>Ne(!0),title:"Share this nest — people, teams, visibility","data-testid":"document-editor-share",children:[e.jsx($s,{className:"h-4 w-4 sm:mr-1.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Share"})]}),!d&&e.jsxs(y,{variant:We?"secondary":"ghost",size:"sm",className:"h-8","aria-pressed":We,onClick:()=>{We&&(ds.current=!0,Ut(!1),At(null),Os(null),Be(null)),Tr(!We)},title:We?"Hide comments":"Show comments","data-testid":"document-editor-comments-toggle",children:[e.jsx(Rs,{className:"h-4 w-4"}),Cn>0&&e.jsx("span",{className:"ml-1 text-xs tabular-nums",children:Cn})]}),!d&&e.jsxs(ir,{onOpenChange:t=>{t&&Ur()},children:[e.jsx(lr,{asChild:!0,children:e.jsxs(y,{variant:J!=null?"secondary":"ghost",size:"sm",className:"h-8",title:"Compare with a past version","data-testid":"document-editor-compare",children:[e.jsx(Aa,{className:"h-4 w-4"}),e.jsx("span",{className:J!=null?"ml-1":"hidden xl:inline ml-1",children:J!=null?`Comparing v${J}`:"Compare"}),e.jsx(or,{className:"h-3.5 w-3.5 ml-0.5 opacity-60"})]})}),e.jsxs(cr,{align:"end",className:"w-56 max-h-80 overflow-y-auto",children:[e.jsx(dr,{children:"Diff current against…"}),J!=null&&e.jsxs(e.Fragment,{children:[e.jsxs(It,{onClick:()=>void Ws(null),children:[e.jsx(st,{className:"h-4 w-4 mr-2"})," Exit compare"]}),e.jsx(ur,{})]}),W?W.versions.filter(t=>t.version!==W.currentVersion).length===0?e.jsx(It,{disabled:!0,children:"No earlier versions"}):W.versions.filter(t=>t.version!==W.currentVersion).map(t=>{var i;return e.jsxs(It,{onClick:()=>void Ws(t.version),children:[J===t.version?e.jsx(Pt,{className:"h-4 w-4 mr-2"}):e.jsx("span",{className:"w-4 mr-2"}),"v",t.version,e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",title:t.editedAt?Cs(t.editedAt):void 0,children:[(i=t.editedBy)==null?void 0:i.split("@")[0],Ca(t.editedAt)].filter(Boolean).join(" · ")})]},t.version)}):e.jsxs(It,{disabled:!0,children:[e.jsx(ee,{className:"h-4 w-4 mr-2 animate-spin"})," Loading…"]})]})]}),(()=>{const t=ea({includeVersionHistory:!0});return t.length?e.jsx(mr,{actions:t,variant:"ghost",testId:"document-editor-more"}):null})(),Q!=="edit"&&e.jsxs(e.Fragment,{children:[!I&&Jn&&e.jsxs(y,{variant:"outline",size:"sm",className:"h-8",onClick:()=>He(!0),"data-testid":"document-editor-submit",title:"Requires steward approval — with stewardship on, publishing in this nest submits the document for steward review.",children:[e.jsx(on,{className:"h-4 w-4 sm:mr-1.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Submit for review"})]}),!I&&!U&&!fe&&!Et&&e.jsxs(y,{size:"sm",className:"h-8",onClick:()=>ct("edit"),"data-testid":"document-editor-start-edit",children:[e.jsx(ya,{className:"h-4 w-4 mr-1.5"}),"Edit"]})]})]})]}),e.jsxs("div",{className:"flex flex-1 flex-col items-stretch lg:flex-row lg:items-start",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col min-h-[calc(100vh-7rem)]",children:[e.jsxs("div",{className:"w-full px-5 py-6 sm:px-10 sm:py-8",children:[Zt&&e.jsxs(De,{variant:"destructive",className:"mb-4",children:[e.jsx(Fe,{className:"h-4 w-4"}),e.jsx($e,{children:Zt})]}),On!==null&&e.jsxs(De,{className:"mb-4 border-amber-300 bg-amber-50 text-amber-800",children:[e.jsx(Fe,{className:"h-4 w-4 text-amber-600"}),e.jsxs($e,{className:"flex flex-wrap items-center gap-x-2 gap-y-1 text-amber-800",children:[e.jsxs("span",{children:["Unsaved edits from this browser"," (",new Date(On).toLocaleString(),") ","were restored — the saved document still says something else."]}),e.jsx("button",{type:"button",onClick:Xn,className:"font-medium underline underline-offset-2 hover:no-underline","data-testid":"discard-restored-draft",children:"Discard them"})]})]}),zr&&te&&e.jsxs(De,{className:"mb-4 border-amber-300 bg-amber-50 text-amber-800",children:[e.jsx(Fe,{className:"h-4 w-4 text-amber-600"}),e.jsx($e,{className:"text-amber-800",children:"This browser couldn't store a local backup of your unsaved edits (storage is full or blocked). Save the document — a page reload would lose them."})]}),je?e.jsxs("div",{className:"flex items-center justify-center py-20 text-muted-foreground",children:[e.jsx(ee,{className:"h-5 w-5 animate-spin mr-2"}),"Loading document..."]}):e.jsxs("div",{className:"space-y-4",children:[!d&&ns&&e.jsx(oo,{nestId:s,nodeId:n,pending:ns,onResolved:()=>{as(null),oe()}}),fe&&e.jsxs(De,{children:[e.jsx(Fe,{className:"h-4 w-4"}),e.jsx($e,{children:"This document is locked while it awaits steward review. Editing is disabled until the review is approved or rejected."})]}),Us&&e.jsxs(De,{children:[e.jsx(Fe,{className:"h-4 w-4"}),e.jsxs($e,{className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:[e.jsx("span",{className:"flex-1 min-w-[16rem]",children:"This is still under review. Your edits update the same pending submission — no need to withdraw and resubmit — and the steward reviews your latest version."}),e.jsxs(y,{size:"sm",variant:"outline",className:"shrink-0",onClick:()=>void si(),"data-testid":"document-editor-withdraw",title:"Withdraw this submission and return the document to Draft",children:[e.jsx(Ma,{className:"h-3.5 w-3.5 mr-1.5"}),"Withdraw"]})]})]}),e.jsxs("div",{children:[Q==="view"&&!d?e.jsx("h1",{className:"text-4xl font-bold leading-tight tracking-tight text-foreground","data-testid":"document-editor-title",children:T||(je?"Loading…":"Untitled")}):e.jsxs(e.Fragment,{children:[e.jsx("input",{id:"document-editor-title",ref:Rn,value:T,onChange:t=>{Se(t.target.value),K(!0)},onBlur:gt,onKeyDown:t=>{var i,p;t.key==="Enter"&&(t.preventDefault(),us.current?us.current.focus():(p=(i=Nn.current)==null?void 0:i.querySelector('textarea, [contenteditable="true"], input'))==null||p.focus())},placeholder:"Untitled",maxLength:120,disabled:ie,required:!0,"aria-required":"true","aria-label":"Title","aria-invalid":Mt&&!T.trim()?!0:void 0,"data-testid":"document-editor-title",className:`block w-full bg-transparent text-4xl font-bold leading-tight tracking-tight text-foreground outline-none border-b border-border pb-1 focus:border-primary placeholder:text-muted-foreground/50 disabled:opacity-100${Mt&&!T.trim()?" placeholder:text-destructive/60":""}`}),(Mt&&!T.trim()||T.length>=90)&&e.jsxs("div",{className:"mt-1 flex items-start justify-between gap-2 text-xs",children:[e.jsx("span",{className:"text-destructive",children:Mt&&!T.trim()?"Title is required":""}),e.jsx("span",{className:"text-muted-foreground tabular-nums",children:T.length>=90?`${T.length}/120`:""})]})]}),!d&&Q==="edit"&&T.trim()!==zs.current.trim()&&(()=>{const t=ql(xe,{id:n,title:zs.current});return t.length===0?null:e.jsx(De,{className:"mt-2 border-amber-300 bg-amber-50 text-amber-800",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fe,{className:"h-4 w-4 shrink-0 text-amber-600"}),e.jsxs($e,{className:"text-amber-800",children:["Renaming affects ",t.length," wiki link",t.length!==1?"s":""," in other documents that reference this one by its old title (",t.slice(0,3).map(i=>i.title).join(", "),t.length>3?", …":"","). Links by slug still resolve, but their visible label keeps the old name; plain [[title]] links break."]})]})})})()]}),!d&&Lt.length>0&&e.jsx(De,{className:"border-amber-300 bg-amber-50 text-amber-800",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fe,{className:"h-4 w-4 shrink-0 text-amber-600"}),e.jsxs($e,{className:"text-amber-800",children:[Lt.length," link",Lt.length!==1?"s":""," in this document show an outdated name — the target document",Lt.length!==1?"s were":" was"," renamed (",Lt.slice(0,3).map(t=>`"${t.shownAs}" → "${t.currentTitle}"`).join(", "),Lt.length>3?", …":"","). The links still work; only the visible label is out of date."]})]})}),d&&e.jsxs("div",{children:[e.jsx("label",{className:"block mb-1 text-sm font-medium",children:"Folder"}),e.jsxs("div",{className:"flex items-center flex-wrap gap-1 rounded-md border px-2 py-1.5 min-h-9","data-testid":"document-editor-folder-input",children:[e.jsx("button",{type:"button",disabled:ie,onClick:()=>{Ve(""),K(!0)},className:`text-sm rounded px-1.5 py-0.5 ${Ce?"text-primary hover:bg-muted":"font-medium bg-muted"}`,title:"File directly under the nest root",children:"Root"}),Ce.split("/").filter(Boolean).map((t,i,p)=>{const D=p.slice(0,i+1).join("/"),O=p.slice(0,i).join("/"),M=i===p.length-1;return e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-muted-foreground/50 text-sm",children:"/"}),e.jsxs("span",{className:`flex items-center rounded ${M?"bg-muted":""}`,children:[e.jsx("button",{type:"button",disabled:ie,onClick:()=>{Ve(D),K(!0)},className:`text-sm rounded px-1.5 py-0.5 ${M?"font-medium":"text-primary hover:bg-muted"}`,title:`Scope to ${D}`,children:tn(t)}),M&&e.jsx("button",{type:"button",disabled:ie,onClick:()=>{Ve(O),K(!0)},className:"mr-0.5 rounded p-0.5 text-muted-foreground hover:text-foreground hover:bg-background",title:O?`Go up to ${O}`:"Go up to the nest root","data-testid":"folder-step-up",children:e.jsx(st,{className:"h-3 w-3"})})]})]},D)}),e.jsx(Yo,{folder:Ce,folderOptions:$n,disabled:ie,onPick:t=>{Ve(t),K(!0)}}),Ce&&e.jsx("button",{type:"button",disabled:ie,onClick:()=>{Ve(""),K(!0)},className:"ml-auto text-muted-foreground hover:text-foreground",title:"Clear folder (file under the nest root)",children:e.jsx(st,{className:"h-3.5 w-3.5"})})]})]}),(Ae||B.length>0)&&e.jsxs("div",{children:[e.jsxs("div",{className:"space-y-2",children:[Ae&&!ie&&e.jsx("input",{value:Ee,onChange:t=>ze(ho(t.target.value)),onKeyDown:t=>{(t.key==="Enter"||t.key===","||t.key===" ")&&(t.preventDefault(),Un())},onBlur:()=>{Ee.trim()&&Un()},placeholder:B.length?"Add a tag":"Add a tag…",maxLength:co,"aria-label":"Add a tag",className:"block h-8 w-full border-b border-border bg-transparent px-1 text-sm outline-none focus:border-primary placeholder:text-muted-foreground/70 focus:placeholder:text-muted-foreground","data-testid":"document-editor-tag-input"}),B.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:B.map(t=>{const i=Q==="view"&&!!f;return e.jsxs("span",{onClick:i?p=>{p.stopPropagation(),f(t)}:void 0,className:"inline-flex items-center gap-1 rounded bg-secondary px-2 py-0.5 text-xs"+(i?" cursor-pointer hover:bg-secondary/80":""),title:i?`Filter nest by ${t}`:t,children:[e.jsx("span",{className:"truncate max-w-[16rem]",children:t}),!ie&&e.jsx("button",{type:"button",onClick:p=>{p.stopPropagation(),Xr(t)},className:"hover:text-destructive","aria-label":`Remove ${t}`,children:e.jsx(st,{className:"h-3 w-3"})})]},t)})})]}),Ee.trim()&&e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground","data-testid":"document-editor-tag-preview",children:[Ft.tags.length>0?`Will add: ${Ft.tags.join(", ")}`:"Nothing new to add",Ft.notes.length>0&&` — ${Ft.notes.join(" ")}`]})]}),ot&&li&&e.jsxs("div",{className:"flex items-start justify-between gap-4 rounded-lg border p-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-sm font-medium",children:[e.jsx(yl,{className:"h-4 w-4"}),"Prime document"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:js&&ae===null?"Inherited from a prime tag on this document — it always needs steward approval.":"Always require steward approval for this document, even from an owner or admin with auto-publish on."}),js&&ae===!1&&e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:"Exempted from its prime tag."}),Yn&&Ht&&e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:"Overrides auto-publish — your edits here queue for review like everyone else’s."})]}),e.jsx(rr,{checked:Yn,disabled:ie,onCheckedChange:t=>{Xe(t===js?null:t),K(!0)},"aria-label":"Prime document","data-testid":"document-editor-prime"})]}),!d&&(Ye||Ze.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground",children:[Ye&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:["Created by ",e.jsx("span",{className:"font-medium text-foreground/80",children:Ye})]}),Ye&&Ze.length>0&&e.jsx("span",{"aria-hidden":!0,children:"·"}),Ze.length>0&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",title:Ze.join(", "),children:["Collaborators:",e.jsx(zl,{collaborators:Ze,max:5,size:"md"}),e.jsx("span",{className:"font-medium text-foreground/80",children:Ze.length})]})]}),Ae&&(d||Wt||Hn)&&e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 w-full",children:[(d||Hn)&&e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("label",{className:"block text-sm font-medium mb-1",children:"Type"}),e.jsx("div",{className:"inline-flex rounded-md border overflow-hidden",role:"radiogroup","aria-label":"Document type","data-testid":"document-editor-type",...H,children:[{value:"document",label:"Document",Icon:Js,on:"bg-slate-500/15 text-slate-700 dark:text-slate-300"},...ne?[{value:"artifact",label:"Artifact",Icon:es,on:"bg-amber-500/15 text-amber-700 dark:text-amber-300"}]:[],...S?[{value:"table",label:"Table",Icon:sn,on:"bg-cyan-500/15 text-cyan-700 dark:text-cyan-300"}]:[],...se?[{value:"agent",label:"Agent",Icon:wa,on:"bg-violet-500/15 text-violet-700 dark:text-violet-300"},{value:"skill",label:"Skill",Icon:$a,on:"bg-blue-500/15 text-blue-700 dark:text-blue-300"},{value:"tool",label:"Tool",Icon:Ta,on:"bg-teal-500/15 text-teal-700 dark:text-teal-300"}]:[]].map(({value:t,label:i,Icon:p,on:D},O)=>{const M=mt===t;return e.jsxs("button",{type:"button",role:"radio","aria-checked":M,title:t==="document"?"Markdown document":t==="artifact"?"Hosted HTML artifact":t==="table"?"Table — CSV fact store, queryable deterministically":t==="tool"?"Tool — the body is code an agent can call":`${i} (runnable)`,onClick:()=>{if(d){kr(t,i);return}t!==mt&&Me("turn it into another kind",()=>hs(t))},className:`flex items-center gap-1.5 px-3 py-1.5 text-sm transition-colors ${O>0?"border-l":""} ${M?`${D} font-medium`:"text-muted-foreground hover:bg-muted/60"}`,"data-testid":`document-editor-type-${t}`,children:[e.jsx(p,{className:"h-4 w-4"}),i]},t)})}),mt==="artifact"&&e.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:"Hosted HTML — the body is served as a sandboxed page."}),(mt==="agent"||mt==="skill")&&e.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:"The body is the instructions. Add flow edges from it in the Workflows tab, then trigger a run."}),mt==="table"&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted-foreground",children:["The body is CSV — header first, directives welcome (",e.jsx("code",{children:"sku:key, price:number, region"}),"). Agents fetch exact rows with table-query instead of reading it whole."]}),mt==="tool"&&e.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:"The body is code. Wire it to an agent on the canvas and the runner ships it (plus the nest's env vars) in the run bundle."})]}),Wt&&e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("label",{htmlFor:"document-editor-schedule",className:"block text-sm font-medium mb-1",children:["Schedule"," ",e.jsx("span",{className:"font-normal text-muted-foreground",children:"(cron / interval — optional)"})]}),e.jsx("input",{id:"document-editor-schedule","data-testid":"document-editor-schedule",type:"text",value:pe,placeholder:"e.g. 0 6 * * * or @daily or @every 15m","aria-invalid":xt.kind==="invalid",onChange:t=>{Re(t.target.value),K(!0)},onBlur:gt,className:`w-full rounded-md border bg-background px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-ring ${xt.kind==="invalid"?"border-destructive focus:ring-destructive":""}`}),e.jsx("p",{"data-testid":"document-editor-schedule-feedback",className:`mt-1 text-xs ${xt.kind==="invalid"?"text-destructive":"text-muted-foreground"}`,children:xt.kind==="invalid"?e.jsxs(e.Fragment,{children:["Doesn't look like a cron/interval schedule — ",xt.error,"."]}):xt.kind==="valid"?e.jsxs(e.Fragment,{children:[xt.description,". Opaque to this server — an external orchestrator parses it and runs the"," ",ve==="skill"||ue==="skill"?"skill":"agent","."]}):e.jsxs(e.Fragment,{children:["Opaque to this server — an external orchestrator parses it and runs the"," ",ve==="skill"||ue==="skill"?"skill":"agent",". Leave blank for none."]})})]})]}),Wt&&e.jsxs("div",{className:"w-full rounded-md border border-dashed bg-muted/40 px-3 py-2.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[e.jsxs("span",{className:"text-xs font-medium text-muted-foreground",children:["Orchestrator fetch — this ",ue==="skill"||ve==="skill"?"skill":"agent"," appears here"]}),e.jsx(y,{variant:"ghost",size:"sm",className:"h-6 px-2 shrink-0",onClick:Cr,title:"Copy URL",children:Sr?e.jsx(Pt,{className:"h-3 w-3 text-green-600"}):e.jsx(Ui,{className:"h-3 w-3"})})]}),e.jsxs("code",{className:"block text-[11px] font-mono break-all text-foreground/80",children:["GET ",vn]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:"Returns every runnable node (approved agent/skill) with its schedule + content, so an external scheduler can discover what to run and when."})]}),e.jsx("div",{className:"flex flex-col lg:flex-row gap-6 items-start",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[he&&J==null&&e.jsxs("div",{className:"mb-2 flex items-center gap-2 rounded-md border border-amber-300 bg-amber-50/70 dark:bg-amber-950/20 px-3 py-1.5 text-xs text-amber-900 dark:text-amber-200",children:[e.jsx(Rs,{className:"h-3.5 w-3.5 shrink-0"}),"Comment mode — select any text to pin a comment, or click a highlighted phrase to open its thread. Editing is paused."]}),e.jsxs("div",{ref:Nn,onClick:()=>{he||I||fe||dt||Le!=="table"&&(Et||Q==="view"&&!U&&ct("edit"))},children:[Et&&e.jsx(Nl,{nestId:s,nodeId:n,title:T,pdf:ge,canReplace:!I&&!U&&!fe&&!we,onReplaced:()=>{Xs(b,`/nests/${s}/nodes/${n}`),oe()}}),(dt||Le==="tool"||Le==="table")&&e.jsx("div",{className:"mb-1 text-xs font-medium text-muted-foreground",children:dt?"Artifact HTML":Le==="tool"?"Tool source (code)":"Table data (CSV)"}),J!=null?e.jsxs("div",{"data-testid":"document-editor-inline-diff",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Aa,{className:"h-4 w-4"}),"Diff: v",J," → current (v",(W==null?void 0:W.currentVersion)??_e??"?",")",te&&e.jsx("span",{className:"rounded bg-amber-100 text-amber-800 dark:bg-amber-950/40 dark:text-amber-300 px-1.5 py-px text-[10px] font-semibold uppercase",children:"incl. unsaved edits"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs("div",{className:"flex rounded-md border overflow-hidden text-xs",children:[e.jsx("button",{type:"button",className:`px-2 py-1 ${Rt?"text-muted-foreground hover:bg-muted/50":"bg-secondary font-medium"}`,onClick:()=>lt(!1),children:"Source"}),e.jsx("button",{type:"button",className:`px-2 py-1 ${Rt?"bg-secondary font-medium":"text-muted-foreground hover:bg-muted/50"}`,onClick:()=>lt(!0),children:"Rendered"})]}),e.jsxs(y,{variant:"ghost",size:"sm",className:"h-7",onClick:()=>void Ws(null),children:[e.jsx(st,{className:"h-4 w-4 mr-1"})," Exit diff"]})]})]}),(()=>{const t=Bs&&Bs.version===J?Bs:null;if(!t)return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground p-4 border rounded-lg",children:[e.jsx(ee,{className:"h-4 w-4 animate-spin"})," Loading version"," ",J,"…"]});if(Rt){const i=Le==="table"?kl(t.content||"",$):null,p=(D,O)=>i?e.jsx(fn,{columns:i[D].columns,rows:i[D].rows,rowClassName:M=>i[D].changed[M]?D==="past"?"bg-red-50 dark:bg-red-950/30":"bg-emerald-50 dark:bg-emerald-950/30":""}):e.jsx(nn,{content:O,className:"px-4 py-3"});return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"bg-muted px-3 py-1.5 text-xs font-medium text-muted-foreground border-b",children:["v",J]}),p("past",t.content||"")]}),e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"bg-muted px-3 py-1.5 text-xs font-medium text-muted-foreground border-b",children:["current (v",(W==null?void 0:W.currentVersion)??_e??"?",")"]}),p("current",$)]})]})}return e.jsx(fr,{patch:_l(t.content||"",$),className:"max-h-none border rounded-lg"})})()]}):Ps&&Q==="edit"&&!he?Le==="table"?e.jsx(go,{value:$,onChange:t=>{ie||(_(t),K(!0))},onBlur:gt,readOnly:ie}):e.jsxs("div",{className:$.trim()?"grid gap-3 lg:grid-cols-2":"",children:[e.jsx("textarea",{value:$,onChange:t=>{ie||(_(t.target.value),K(!0))},onBlur:gt,readOnly:ie,spellCheck:!1,placeholder:"The body is code — paste or write the tool's source.",className:"w-full min-h-[400px] border rounded-lg bg-background shadow-sm p-4 font-mono text-sm leading-relaxed resize-y focus:outline-none focus:ring-2 focus:ring-ring","data-testid":"tool-source-editor"}),$.trim()&&e.jsxs("div",{className:"min-w-0 flex flex-col min-h-[400px] rounded-lg border bg-background shadow-sm overflow-hidden",children:[e.jsx("div",{className:"bg-muted px-3 py-1.5 text-xs font-medium text-muted-foreground border-b",children:"Preview"}),e.jsx(qa,{code:Kr,className:"flex-1 text-sm","data-testid":"tool-source-preview"})]})]}):Fs?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(y,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>bn(!1),title:"Back to the rich editor","data-testid":"document-editor-rich-toggle",children:[e.jsx(es,{className:"h-3.5 w-3.5 mr-1.5"}),"Rich editor"]})}),e.jsx("textarea",{value:$,onChange:t=>{ie||(_(t.target.value),K(!0))},onBlur:gt,readOnly:ie,spellCheck:!1,placeholder:"# Raw markdown",className:"w-full min-h-[400px] border rounded-lg bg-background shadow-sm p-4 font-mono text-sm leading-relaxed resize-y focus:outline-none focus:ring-2 focus:ring-ring","data-testid":"document-editor-raw-markdown"})]}):dt?e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsx("textarea",{value:$,onChange:t=>{_(t.target.value),K(!0)},onBlur:gt,placeholder:"Paste the artifact's HTML (a self-contained slide deck, dashboard, infographic)…",spellCheck:!1,className:"w-full min-h-[360px] rounded-lg border bg-background p-3 font-mono text-xs leading-relaxed shadow-sm focus:outline-none focus:ring-1 focus:ring-primary"}),e.jsxs("div",{className:"rounded-lg border overflow-hidden flex flex-col min-h-[360px]",children:[e.jsx("div",{className:"bg-muted px-3 py-1.5 text-xs font-medium text-muted-foreground border-b",children:"Preview"}),Wn.trim()?e.jsx("iframe",{srcDoc:Wn,title:"Artifact preview",sandbox:"allow-scripts allow-popups allow-modals",className:"w-full flex-1 bg-white","data-testid":"artifact-draft-preview"}):e.jsx("p",{className:"flex-1 flex items-center justify-center text-xs text-muted-foreground",children:"Paste HTML to see it render here."})]})]}):(he||Q==="view")&&(Ps||!Ns($))?e.jsx("div",{ref:Gt,onMouseUp:d?void 0:Dr,onClick:d?void 0:Ar,onMouseMove:d?void 0:Lr,className:"min-h-[300px] cursor-text","data-testid":"document-view-surface",children:Le==="table"&&!d?e.jsx("div",{className:"p-4",children:e.jsx(po,{nestId:s,nodeId:n,csv:$})}):Le==="tool"?e.jsx(qa,{code:$,"data-testid":"tool-source-view"}):e.jsx(nn,{content:$,onWikiLinkClick:t=>In(t),previewFor:Or})}):e.jsx(Sl,{ref:us,content:$,onChange:t=>{_(t),K(!0)},onSave:Gn,onBlur:gt,nestId:s,currentNodeId:d?void 0:n,editable:!ie,onRequestDocLink:()=>gn(!0),onUploadImage:async t=>{const{url:i}=await Qi(s,t);return i},onWikiLinkClick:In,placeholder:"Start writing, or select text to format it…",autofocus:!1,variant:"page",toolbarEnd:e.jsx(e.Fragment,{children:!Ps&&J==null&&!dt&&e.jsxs(y,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>bn(!0),title:"Edit the raw markdown","data-testid":"document-editor-markdown-toggle",children:[e.jsx(es,{className:"h-3.5 w-3.5 sm:mr-1.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Markdown"})]})})})]})]})}),Qt&&!I&&e.jsxs("button",{type:"button","data-testid":"selection-comment-button",onMouseDown:t=>t.preventDefault(),onClick:$r,style:{position:"fixed",left:Qt.x,top:Qt.y-40,transform:"translateX(-50%)",zIndex:50},className:"flex items-center gap-1 rounded-md bg-foreground text-background px-2.5 py-1.5 text-xs font-medium shadow-lg hover:opacity-90",children:[e.jsx(wr,{className:"h-3.5 w-3.5"})," Comment"]}),Q==="view"&&gs.length>0&&e.jsxs("div",{className:"border rounded-lg bg-muted/20 p-3",children:[e.jsxs("div",{className:"text-xs font-medium text-muted-foreground mb-2",children:["Linked from ",gs.length," document",gs.length!==1?"s":""]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:gs.map(t=>e.jsx("button",{type:"button",className:"text-sm text-primary hover:underline text-left",onClick:()=>Me(`open "${t.title}"`,()=>h==null?void 0:h(s,t.id,T)),children:t.title},t.id))})]}),Q==="view"&&Mn.length>0&&e.jsxs("div",{className:"border rounded-lg bg-muted/20 p-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Related documents"}),e.jsx("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:Mn.map((t,i)=>e.jsxs(a.Fragment,{children:[i>0&&e.jsx("span",{"aria-hidden":!0,className:"text-muted-foreground/50",children:"·"}),e.jsx("button",{type:"button",className:"text-sm text-primary hover:underline text-left",title:t.sharedTags.length?`Shared tags: ${t.sharedTags.join(", ")}`:"Shared links",onClick:()=>Me(`open "${t.title}"`,()=>h==null?void 0:h(s,t.id,T)),children:t.title})]},t.id))})]}),Q==="view"&&bs.length>0&&e.jsxs("div",{className:"border rounded-lg bg-muted/20 p-3",children:[e.jsxs("div",{className:"text-xs font-medium text-muted-foreground mb-2",children:["Mentioned in ",bs.length," document",bs.length!==1?"s":""," without a link"]}),e.jsx("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:bs.map((t,i)=>e.jsxs(a.Fragment,{children:[i>0&&e.jsx("span",{"aria-hidden":!0,className:"text-muted-foreground/50",children:"·"}),e.jsx("button",{type:"button",className:"text-sm text-primary hover:underline text-left",onClick:()=>Me(`open "${t.title}"`,()=>h==null?void 0:h(s,t.id,T)),children:t.title})]},t.id))})]})]})]}),Q==="edit"&&e.jsx("div",{className:"sticky bottom-0 z-20 mt-auto flex items-center justify-center gap-2 border-t bg-background/95 px-4 py-2 backdrop-blur supports-[backdrop-filter]:bg-background/80","data-testid":"document-editor-actions-bottom",children:(()=>{const t=!I&&!U&&!fe,i=!I&&Jn;return e.jsxs(e.Fragment,{children:[t&&!d&&Ae&&(re==="draft"||re==="rejected")&&e.jsxs(y,{variant:"ghost",size:"sm",className:"h-8 text-muted-foreground",disabled:qn,onClick:()=>Hs(!0),"data-testid":"document-editor-discard",children:[e.jsx(Ma,{className:"h-4 w-4 sm:mr-1.5"}),e.jsx("span",{className:"hidden sm:inline",children:qn?"Discarding…":"Discard draft"})]}),i&&e.jsxs(y,{variant:"outline",size:"sm",className:"h-8",onClick:()=>He(!0),"data-testid":"document-editor-submit",title:"Requires steward approval — with stewardship on, publishing in this nest submits the document for steward review.",children:[e.jsx(on,{className:"h-4 w-4 sm:mr-1.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Submit for review"})]}),t&&e.jsxs(y,{size:"sm",className:"h-8",onMouseDown:p=>p.preventDefault(),onClick:Gn,disabled:!Bn,"data-testid":"document-editor-save",children:[Qe?e.jsx(ee,{className:"h-4 w-4 mr-1.5 animate-spin"}):_s&&!te?e.jsx(Pt,{className:"h-4 w-4 mr-1.5"}):e.jsx(La,{className:"h-4 w-4 mr-1.5"}),Qe?"Saving…":_s&&!te?"Saved":d?"Create":"Save"]})]})})()})]}),!d&&e.jsxs("aside",{className:`w-full shrink-0 border-t lg:w-80 lg:border-t-0 lg:border-l lg:sticky lg:top-28 lg:self-start lg:max-h-[calc(100vh-7rem)] flex flex-col min-h-0 max-h-[70vh] px-4 py-4${We||qs?"":" hidden"}`,"data-testid":"document-comments-rail","aria-hidden":!We&&!qs,children:[!We&&qs&&e.jsxs("nav",{className:"flex flex-col min-h-0 rounded-lg border border-border bg-card p-5","aria-label":"Outline",children:[e.jsx("div",{className:"mb-4 border-b pb-3 text-sm font-semibold",children:"Outline"}),e.jsx("div",{className:"space-y-0.5 overflow-y-auto min-h-0",children:Sn.map(t=>e.jsx("button",{type:"button",className:"block w-full text-left text-sm text-primary hover:underline truncate",style:{paddingLeft:`${(t.level-1)*12}px`},title:t.text,onClick:i=>{var p;i.stopPropagation(),(p=document.getElementById(t.id))==null||p.scrollIntoView({behavior:"smooth",block:"start"})},children:t.text},t.id))})]}),e.jsx("div",{className:We?"flex flex-col flex-1 min-h-0":"hidden",children:e.jsx(Do,{nestId:s,nodeId:n,readOnly:I,pendingAnchor:Vs,onClearAnchor:()=>Os(null),onFocusAnchor:Er,onThreadsChange:Rr,activeThreadId:Kt,commentMode:he,onSetCommentMode:t=>{Ut(t),t&&ct("view"),Be(null),t||At(null)}})})]})]}),Ct&&!d&&e.jsx(gr,{open:!0,onClose:()=>qt(!1),title:T||n,versionData:W,onLoadContent:async t=>(await Is(s,n,t)).content,onRestore:Ae?async t=>{try{await er(s,n,t),k.success(`Reverted to version ${t}`),await Promise.all([oe(),et()])}catch(i){k.error((i==null?void 0:i.message)||"Revert failed")}}:void 0,onDiscard:Ae?async()=>{try{const{version:t}=await va(s,n);k.success(`Draft discarded — back to version ${t}`),await Promise.all([oe(),et()])}catch(t){k.error((t==null?void 0:t.message)||"Discard failed")}}:void 0}),!d&&e.jsx(so,{isOpen:le,onClose:()=>He(!1),documentTitle:T,currentVersion:_e??1,onSubmit:Ir}),e.jsx(Cl,{isOpen:Nr,onClose:()=>gn(!1),nestId:s,excludeNodeId:d?void 0:n,onSelect:ci}),e.jsx(bt,{open:Ie!==null,onOpenChange:t=>{!t&&!xs&&hs(null)},children:e.jsxs(wt,{className:"sm:max-w-[480px]",children:[(()=>{const t=fs.find(p=>p.value===Ie),i=t==null?void 0:t.Icon;return e.jsxs(e.Fragment,{children:[e.jsx(vt,{children:e.jsxs(jt,{children:["Turn into ",(t==null?void 0:t.label)??"","?"]})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Changes what kind of node this is. The body is kept as it is — edit it afterwards if the new kind expects something else."}),t&&i&&e.jsxs("div",{className:"flex items-start gap-3 rounded-md border bg-muted/40 px-3 py-2 text-sm","data-testid":`document-editor-turn-into-${t.value}`,children:[e.jsx(i,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsxs("span",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium",children:t.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:t.expects})]})]})]})})(),e.jsxs(yt,{children:[e.jsx(y,{variant:"outline",onClick:()=>hs(null),disabled:xs,children:"Cancel"}),e.jsxs(y,{onClick:()=>void Vr(),disabled:xs||!Ie,"data-testid":"document-editor-turn-into-confirm",children:[xs?e.jsx(ee,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Turn into ",((fa=fs.find(t=>t.value===Ie))==null?void 0:fa.label)??""]})]})]})}),sa,ft&&e.jsx(bt,{open:!0,onOpenChange:()=>pt(null),children:e.jsxs(wt,{className:"sm:max-w-[460px]",children:[e.jsx(vt,{children:e.jsx(jt,{children:"Unsaved changes"})}),e.jsxs("p",{className:"text-sm text-muted-foreground py-2",children:["You have unsaved changes in this document. Save them before you ",ft.label,", or discard to leave without saving."]}),Zt&&e.jsxs(De,{variant:"destructive",children:[e.jsx(Fe,{className:"h-4 w-4"}),e.jsx($e,{children:Zt})]}),e.jsxs(yt,{children:[e.jsx(y,{variant:"outline",onClick:()=>pt(null),disabled:Qe,children:"Cancel"}),e.jsx(y,{variant:"outline",onClick:Jr,disabled:Qe,children:"Discard"}),e.jsxs(y,{onClick:Zr,disabled:Qe,children:[Qe?e.jsx(ee,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(La,{className:"h-4 w-4 mr-2"}),"Save & leave"]})]})]})}),ls&&e.jsx(bt,{open:!0,onOpenChange:()=>os(null),children:e.jsxs(wt,{className:"sm:max-w-[460px]",children:[e.jsx(vt,{children:e.jsxs(jt,{children:["Switch to ",ls.label,"?"]})}),e.jsxs("p",{className:"text-sm text-muted-foreground py-2",children:["Your existing content will stay as-is, but it will now be interpreted as ",Za(cs(ls.value))," ","instead of ",Za(cs(ve)),". Nothing is converted automatically — review the body after switching."]}),e.jsxs(yt,{children:[e.jsx(y,{variant:"outline",onClick:()=>os(null),children:"Cancel"}),e.jsx(y,{onClick:()=>{wn(ls.value),os(null)},children:"Switch anyway"})]})]})}),e.jsx(Kl,{open:Br,onOpenChange:Hs,children:e.jsxs(Xl,{children:[e.jsxs(Yl,{children:[e.jsxs(Zl,{children:['Discard the draft of "',T||n,'"?']}),e.jsx(Jl,{children:"The document goes back to its last approved version. If it was never approved, it is deleted instead. This can't be undone."})]}),e.jsxs(Il,{children:[e.jsx(eo,{children:"Cancel"}),e.jsx(to,{onClick:()=>void Wr(),"data-testid":"document-editor-discard-confirm",children:"Discard draft"})]})]})})]})}function Xo({status:s}){const n={draft:{label:"Draft",cls:"bg-muted text-muted-foreground"},pending_review:{label:"Pending review",cls:"bg-amber-100 text-amber-800 dark:bg-amber-950 dark:text-amber-300"},approved:{label:"Approved",cls:"bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-300"},published:{label:"Published",cls:"bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-300"},rejected:{label:"Rejected",cls:"bg-red-100 text-red-800 dark:bg-red-950 dark:text-red-300"},external_edit_pending:{label:"External edit",cls:"bg-orange-100 text-orange-800 dark:bg-orange-950 dark:text-orange-300"}}[s];return n?e.jsx("span",{className:`shrink-0 inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${n.cls}`,"data-testid":`document-status-${s}`,children:n.label}):null}function Yo({folder:s,folderOptions:r,disabled:n,onPick:o}){const[l,m]=a.useState(""),x=s.split("/").filter(Boolean).length>=ka,u=a.useMemo(()=>{const f=new Set;for(const j of r)if(s){if(j===s||!j.startsWith(`${s}/`))continue;f.add(j.slice(s.length+1).split("/")[0])}else f.add(j.split("/")[0]);return[...f].sort()},[s,r]),h=()=>{if(x)return;const f=l.trim().replace(/\/+/g,"-");f&&(o(s?`${s}/${f}`:f),m(""))};return e.jsxs(ir,{modal:!1,children:[e.jsx(lr,{asChild:!0,children:e.jsx(y,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-1.5 text-muted-foreground",disabled:n,title:"Open a subfolder or create a new one","data-testid":"folder-step-picker",children:e.jsx(or,{className:"h-3.5 w-3.5"})})}),e.jsxs(cr,{align:"start",className:"min-w-56",children:[u.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(dr,{children:s?"Subfolders":"Existing folders"}),u.map(f=>e.jsxs(It,{onSelect:()=>o(s?`${s}/${f}`:f),children:[e.jsx(el,{className:"h-3.5 w-3.5 mr-2 text-blue-500"}),tn(f)]},f)),e.jsx(ur,{})]}),x?e.jsxs("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:["Max folder depth (",ka,") reached — can't nest deeper."]}):e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1.5",onKeyDown:f=>f.stopPropagation(),children:[e.jsx(Tl,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsx(Ia,{value:l,onChange:f=>m(f.target.value),onKeyDown:f=>{f.key==="Enter"&&(f.preventDefault(),h())},placeholder:"New subfolder…",className:"h-7 text-sm"})]})]})]})}export{$c as DocumentEditor,$c as default};
|