@promptowl/contextnest-community 1.23.0 → 1.24.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.
Files changed (89) hide show
  1. package/API.md +2092 -0
  2. package/CONFIGURATION.md +1 -0
  3. package/README.md +61 -9
  4. package/STEWARDSHIP.md +229 -0
  5. package/dist/{chunk-2YPY2HGZ.js → chunk-2TPQTN4Y.js} +5 -4
  6. package/dist/{chunk-MLQU4I5J.js → chunk-5EZOPA47.js} +5 -5
  7. package/dist/{chunk-UOMW7TT6.js → chunk-I3CSD6CK.js} +1 -1
  8. package/dist/{chunk-QLXC6542.js → chunk-KIAAEHWL.js} +49 -25
  9. package/dist/{chunk-QWNXWRWO.js → chunk-LA3VTQ22.js} +25 -1
  10. package/dist/{chunk-XYD6V2LH.js → chunk-XUIWAWDO.js} +28 -33
  11. package/dist/{chunk-5CVZMHHB.js → chunk-ZTT4U4NE.js} +2 -2
  12. package/dist/{client-LWDMNKX3.js → client-KEY4PYJH.js} +1 -1
  13. package/dist/{engine-QFF2IA3G.js → engine-S3QBQ7LH.js} +2 -2
  14. package/dist/{external-edit-service-F7D3VSA2.js → external-edit-service-6FNFPOJJ.js} +3 -3
  15. package/dist/{grants-service-TBGTCO5K.js → grants-service-UT3EQ3R7.js} +2 -2
  16. package/dist/index.js +371 -90
  17. package/dist/{migrations.postgres-APCVSYUE.js → migrations.postgres-AIQ7WSU7.js} +45 -4
  18. package/dist/{review-service-A7PNLWG5.js → review-service-HHGOTO6P.js} +6 -6
  19. package/dist/{stewardship-service-32UHIRQ5.js → stewardship-service-4DHNRULG.js} +3 -3
  20. package/dist/{version-service-RJ6CWZ3O.js → version-service-KIOQME6U.js} +3 -3
  21. package/dist/web3/assets/ActivityTracePage-BOZHgJ8S.js +1 -0
  22. package/dist/web3/assets/AgentDocsPage-CIiaBqMy.js +1 -0
  23. package/dist/web3/assets/CollaboratorManager-By91wrIr.js +1 -0
  24. package/dist/web3/assets/CollaboratorsTab-D1EE64Fs.js +1 -0
  25. package/dist/web3/assets/DocumentEditor-DrQfrW3d.js +36 -0
  26. package/dist/web3/assets/DocumentsTab-Vba-AzBv.js +6 -0
  27. package/dist/web3/assets/ExternalEditsTab-BSzAQIGM.js +1 -0
  28. package/dist/web3/assets/MarkdownEditor-74N_naNQ.css +1 -0
  29. package/dist/web3/assets/MarkdownEditor-C9zqZjC5.js +643 -0
  30. package/dist/web3/assets/NestPageHeader-CoLUV1Oz.js +1 -0
  31. package/dist/web3/assets/NestView-CTZ55tXD.js +63 -0
  32. package/dist/web3/assets/OverviewTab-Dxi-Hu-N.js +1 -0
  33. package/dist/web3/assets/PersonCombobox-CPOlNs6G.js +1 -0
  34. package/dist/web3/assets/ReasonDialog-DgLxfRWv.js +1 -0
  35. package/dist/web3/assets/ReviewActions-OfOdqzCn.js +6 -0
  36. package/dist/web3/assets/ReviewTab-CyX8yxd3.js +1 -0
  37. package/dist/web3/assets/StewardsTab-DBEEfAQI.js +1 -0
  38. package/dist/web3/assets/SubmitForReviewModal-Ci2DdWs0.js +1 -0
  39. package/dist/web3/assets/alert-dialog-DTozKlmV.js +7 -0
  40. package/dist/web3/assets/arrow-left-BCKt4CwQ.js +6 -0
  41. package/dist/web3/assets/backlinks-CYd4xENL.js +24 -0
  42. package/dist/web3/assets/card-XG2dP5Xf.js +1 -0
  43. package/dist/web3/assets/chevron-left-BPwUT9DS.js +6 -0
  44. package/dist/web3/assets/circle-check-DI8IBGeo.js +6 -0
  45. package/dist/web3/assets/circle-x-VKVhC88W.js +6 -0
  46. package/dist/web3/assets/code-xml-CMabYZvH.js +6 -0
  47. package/dist/web3/assets/corner-down-right-BGxwK6wH.js +6 -0
  48. package/dist/web3/assets/count-skeleton-DMbdpscX.js +1 -0
  49. package/dist/web3/assets/dates-BCxbm4_q.js +1 -0
  50. package/dist/web3/assets/earth-BEp1EKTo.js +6 -0
  51. package/dist/web3/assets/file-exclamation-point-r8qZGIjP.js +6 -0
  52. package/dist/web3/assets/folder-input-Cmtx1Jhk.js +11 -0
  53. package/dist/web3/assets/folder-target-CUSWqImF.js +1 -0
  54. package/dist/web3/assets/index-BM-h3DwI.css +1 -0
  55. package/dist/web3/assets/index-C1wTSjfP.js +29 -0
  56. package/dist/web3/assets/index-EaX2yql0.js +389 -0
  57. package/dist/web3/assets/page-B3yvQvHy.js +1 -0
  58. package/dist/web3/assets/page-BExMvttJ.js +1 -0
  59. package/dist/web3/assets/page-BUOADv2X.js +1 -0
  60. package/dist/web3/assets/page-BYUFhYWZ.js +1 -0
  61. package/dist/web3/assets/page-Bicf02Cz.js +1 -0
  62. package/dist/web3/assets/page-BsPMDm5d.js +45 -0
  63. package/dist/web3/assets/page-ByyVLDVo.js +16 -0
  64. package/dist/web3/assets/page-CC0NJi8v.js +1 -0
  65. package/dist/web3/assets/page-CHb0F5hV.js +24 -0
  66. package/dist/web3/assets/page-CPjWQNKx.js +11 -0
  67. package/dist/web3/assets/page-CQt3ZGbf.js +2 -0
  68. package/dist/web3/assets/page-Cj1NetQ-.js +1 -0
  69. package/dist/web3/assets/page-CtaW65El.js +1 -0
  70. package/dist/web3/assets/page-DGOL9l8i.js +6 -0
  71. package/dist/web3/assets/page-title-ClvvBsIo.js +1 -0
  72. package/dist/web3/assets/play-C5YNKpAH.js +6 -0
  73. package/dist/web3/assets/refresh-cw-BhHzSH9m.js +6 -0
  74. package/dist/web3/assets/scroll-area-dRWncRqa.css +1 -0
  75. package/dist/web3/assets/scroll-area-hz-xtayP.js +1 -0
  76. package/dist/web3/assets/select-DBFTrUmI.js +6 -0
  77. package/dist/web3/assets/send-0CHvmluT.js +6 -0
  78. package/dist/web3/assets/settings-CeeF4LEb.js +6 -0
  79. package/dist/web3/assets/share-2-CMnOlOt-.js +6 -0
  80. package/dist/web3/assets/tag-DQ_6J5Gv.js +11 -0
  81. package/dist/web3/assets/trash-2-HBi-Pslz.js +6 -0
  82. package/dist/web3/assets/triangle-alert-CDy8-7sv.js +6 -0
  83. package/dist/web3/assets/user-plus-CvBNcpn4.js +6 -0
  84. package/dist/web3/assets/x-By7piikG.js +6 -0
  85. package/dist/web3/assets/zap-C2T8riBp.js +11 -0
  86. package/dist/web3/index.html +2 -2
  87. package/package.json +4 -2
  88. package/dist/web3/assets/index-BJ-LRNis.js +0 -1382
  89. package/dist/web3/assets/index-DPMEt-A_.css +0 -1
@@ -49,7 +49,8 @@ var HISTORICAL_MIGRATIONS = [
49
49
  "038_nest_archive",
50
50
  "039_nest_pins",
51
51
  "041_nest_visibility_org",
52
- "042_community_sites"
52
+ "042_community_sites",
53
+ "043_node_suggestion_details"
53
54
  ];
54
55
  async function runPostgresMigrations(db) {
55
56
  await db.exec(`
@@ -274,13 +275,26 @@ async function runPostgresMigrations(db) {
274
275
  CREATE INDEX IF NOT EXISTS idx_node_index_folder
275
276
  ON node_index(nest_id, folder);
276
277
 
277
- -- node_suggestions (migration 036). Which documents have an external edit
278
- -- staged \u2014 so the listing's pending badge is a SELECT, not a vault walk.
278
+ -- node_suggestions (migrations 036 + 043). One row per staged external
279
+ -- edit with the suggestion itself \u2014 so the External Edits list and its
280
+ -- badge are a SELECT, not a vault walk, and old vs new is detected_at.
279
281
  CREATE TABLE IF NOT EXISTS node_suggestions (
280
282
  nest_id TEXT NOT NULL REFERENCES nests(id) ON DELETE CASCADE,
281
283
  node_id TEXT NOT NULL,
282
- PRIMARY KEY (nest_id, node_id)
284
+ suggestion_id TEXT NOT NULL,
285
+ source TEXT NOT NULL,
286
+ actor TEXT NOT NULL,
287
+ detected_at TEXT NOT NULL,
288
+ target_hash TEXT NOT NULL,
289
+ proposed_hash TEXT NOT NULL,
290
+ note TEXT,
291
+ created_at TEXT NOT NULL DEFAULT ${NOW},
292
+ PRIMARY KEY (nest_id, node_id, suggestion_id)
283
293
  );
294
+ -- idx_node_suggestions_nest_detected is created after the 043 parity
295
+ -- check below: a pre-043 database already has node_suggestions without
296
+ -- detected_at, so CREATE TABLE IF NOT EXISTS is a no-op and indexing the
297
+ -- column here aborts the whole bootstrap before the rebuild can run.
284
298
 
285
299
  -- sessions (migration 003).
286
300
  CREATE TABLE IF NOT EXISTS sessions (
@@ -725,6 +739,33 @@ async function runPostgresMigrations(db) {
725
739
  "ALTER TABLE nests ADD CONSTRAINT nests_visibility_check CHECK (visibility IN ('private', 'org', 'public'))"
726
740
  );
727
741
  }
742
+ const suggestionIdCol = await db.get(
743
+ `SELECT 1 AS ok FROM information_schema.columns
744
+ WHERE table_name = 'node_suggestions' AND column_name = 'suggestion_id'`
745
+ );
746
+ if (!suggestionIdCol?.ok) {
747
+ await db.exec(`
748
+ DROP TABLE IF EXISTS node_suggestions;
749
+ CREATE TABLE node_suggestions (
750
+ nest_id TEXT NOT NULL REFERENCES nests(id) ON DELETE CASCADE,
751
+ node_id TEXT NOT NULL,
752
+ suggestion_id TEXT NOT NULL,
753
+ source TEXT NOT NULL,
754
+ actor TEXT NOT NULL,
755
+ detected_at TEXT NOT NULL,
756
+ target_hash TEXT NOT NULL,
757
+ proposed_hash TEXT NOT NULL,
758
+ note TEXT,
759
+ created_at TEXT NOT NULL DEFAULT ${NOW},
760
+ PRIMARY KEY (nest_id, node_id, suggestion_id)
761
+ );
762
+ UPDATE nests SET index_synced_at = NULL;
763
+ `);
764
+ }
765
+ await db.exec(`
766
+ CREATE INDEX IF NOT EXISTS idx_node_suggestions_nest_detected
767
+ ON node_suggestions(nest_id, detected_at DESC);
768
+ `);
728
769
  await db.run(
729
770
  "UPDATE nests SET visibility = 'public' WHERE user_id = ? AND visibility = 'private'",
730
771
  [ANON_USER_ID]
@@ -17,15 +17,15 @@ import {
17
17
  requestDeletion,
18
18
  submitForReview,
19
19
  withdrawDeletionRequest
20
- } from "./chunk-MLQU4I5J.js";
20
+ } from "./chunk-5EZOPA47.js";
21
21
  import {
22
22
  canUserApprove
23
- } from "./chunk-2YPY2HGZ.js";
24
- import "./chunk-UOMW7TT6.js";
25
- import "./chunk-5CVZMHHB.js";
26
- import "./chunk-QLXC6542.js";
23
+ } from "./chunk-2TPQTN4Y.js";
24
+ import "./chunk-I3CSD6CK.js";
25
+ import "./chunk-ZTT4U4NE.js";
26
+ import "./chunk-KIAAEHWL.js";
27
27
  import "./chunk-YVMSM7LS.js";
28
- import "./chunk-QWNXWRWO.js";
28
+ import "./chunk-LA3VTQ22.js";
29
29
  import "./chunk-YB3LKF7U.js";
30
30
  import "./chunk-FRQJWGN3.js";
31
31
  export {
@@ -23,10 +23,10 @@ import {
23
23
  syncFromConfig,
24
24
  updateSteward,
25
25
  updateStewardRole
26
- } from "./chunk-2YPY2HGZ.js";
27
- import "./chunk-QLXC6542.js";
26
+ } from "./chunk-2TPQTN4Y.js";
27
+ import "./chunk-KIAAEHWL.js";
28
28
  import "./chunk-YVMSM7LS.js";
29
- import "./chunk-QWNXWRWO.js";
29
+ import "./chunk-LA3VTQ22.js";
30
30
  import "./chunk-YB3LKF7U.js";
31
31
  import "./chunk-FRQJWGN3.js";
32
32
  export {
@@ -20,10 +20,10 @@ import {
20
20
  setApprovedVersion,
21
21
  systemAuthor,
22
22
  upsertVersion
23
- } from "./chunk-5CVZMHHB.js";
24
- import "./chunk-QLXC6542.js";
23
+ } from "./chunk-ZTT4U4NE.js";
24
+ import "./chunk-KIAAEHWL.js";
25
25
  import "./chunk-YVMSM7LS.js";
26
- import "./chunk-QWNXWRWO.js";
26
+ import "./chunk-LA3VTQ22.js";
27
27
  import "./chunk-YB3LKF7U.js";
28
28
  import "./chunk-FRQJWGN3.js";
29
29
  export {
@@ -0,0 +1 @@
1
+ import{r as s,dB as L,dC as z,j as e,B as m,dD as D,bw as _,I as q,L as B,bx as F}from"./index-EaX2yql0.js";import{P as K}from"./page-title-ClvvBsIo.js";import{S as M,a as U,b as V,c as $,d as p}from"./select-DBFTrUmI.js";import{f as G}from"./dates-BCxbm4_q.js";import{A as Z}from"./arrow-left-BCKt4CwQ.js";import{R as H}from"./refresh-cw-BhHzSH9m.js";import{C as I}from"./chevron-left-BPwUT9DS.js";const i=25;function te({onBack:f,nestId:a}){const[g,y]=s.useState([]),[o,C]=s.useState(0),[l,h]=s.useState(0),[n,N]=s.useState(!0),[v,w]=s.useState(null),[c,k]=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 L(a,r):await z(r);if(t!==x.current)return;y(S.events),C(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 E=o===0?0:l*i+1,A=Math.min((l+1)*i,o),P=l>0,R=(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(Z,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsx(K,{icon:D,title:"Activity trace",className:"mb-0 flex-1",actions:e.jsxs(e.Fragment,{children:[e.jsxs(M,{value:c,onValueChange:t=>k(t),children:[e.jsx(U,{className:"h-8 w-28",children:e.jsx(V,{})}),e.jsxs($,{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(B,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(H,{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:G(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.jsx("td",{className:"max-w-[180px] truncate",title:t.caller||"",children:t.caller||"—"}),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:[E,"–",A," of ",o]}),e.jsx(m,{variant:"outline",size:"sm",className:"h-7 px-2",disabled:!P||n,onClick:()=>h(t=>Math.max(t-1,0)),children:e.jsx(I,{className:"h-3.5 w-3.5"})}),e.jsx(m,{variant:"outline",size:"sm",className:"h-7 px-2",disabled:!R||n,onClick:()=>h(t=>t+1),children:e.jsx(F,{className:"h-3.5 w-3.5"})})]})]})]})}export{te as ActivityTracePage};
@@ -0,0 +1 @@
1
+ import{r as o,j as e,aE as m,v as c,aF as x,aG as u,L as h}from"./index-EaX2yql0.js";import{P as p}from"./page-title-ClvvBsIo.js";import{C as f}from"./code-xml-CMabYZvH.js";import{M as g,r as j}from"./index-C1wTSjfP.js";const w=[[x,"Connect an MCP client","Claude Code, Cursor, VS Code or Claude Desktop talk to a nest directly. See “MCP” below."],[f,"Call the REST API","Every read is deterministic: same selector, same context. See “Deterministic retrieval API” below."],[u,"Use the ctx CLI","Query a hosted nest from a terminal or a script. See “From the ctx CLI” below."]];function v({onOpenGuide:n}){const[r,l]=o.useState(null),[a,i]=o.useState(null);return o.useEffect(()=>{let s=!1;return fetch("/llms.txt").then(t=>{if(!t.ok)throw new Error(`Failed to load manual (${t.status})`);return t.text()}).then(t=>!s&&l(t)).catch(t=>!s&&i((t==null?void 0:t.message)||"Failed to load")),()=>{s=!0}},[]),e.jsxs("div",{className:"w-full space-y-6",children:[e.jsx(p,{icon:m,title:"Docs",description:"How agents talk to this server: keys, endpoints, MCP tools and the CLI.",className:"mb-0",actions:e.jsxs("a",{href:"/llms.txt",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:["Raw llms.txt (for agents)",e.jsx(c,{className:"h-3 w-3"})]})}),e.jsxs("div",{className:"rounded-lg border-l-2 border-primary bg-muted/40 p-4 text-sm text-muted-foreground",children:["This is the manual an agent reads when you point it at"," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:"/llms.txt"}),". It documents shapes, never data. Looking for how to use the app yourself?"," ",e.jsx("button",{type:"button",onClick:n,className:"font-medium text-foreground underline underline-offset-2",children:"Start with How it works"}),"."]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:w.map(([s,t,d])=>e.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-2 text-sm font-semibold",children:[e.jsx(s,{className:"h-4 w-4 text-primary"}),t]}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:d})]},t))}),a&&e.jsx("p",{className:"text-sm text-red-500",children:a}),!r&&!a&&e.jsxs("div",{className:"flex items-center justify-center py-16 text-muted-foreground",children:[e.jsx(h,{className:"h-5 w-5 animate-spin mr-2"})," Loading docs…"]}),r&&e.jsx("article",{className:"prose prose-sm dark:prose-invert max-w-none",children:e.jsx(g,{remarkPlugins:[j],children:r})})]})}export{v as AgentDocsPage};
@@ -0,0 +1 @@
1
+ import{r as n,W as ue,j as e,af as pe,ag as ve,L as A,ac as ee,ad as ae,ae as se,ah as be,ai as ge,ak as fe,C as je,J as F,bK as ye,u as Ne,A as we,K as Se,a as Ce,U as te,B as N,e as E,i as K,N as Ae,f as le,bB as Te,dK as ke,M as Pe,dL as De,dM as Le}from"./index-EaX2yql0.js";import{S as Y,a as _,b as W,c as G,d as T}from"./select-DBFTrUmI.js";import{A as Me,a as Re,b as Fe,c as ze,d as Ue,e as Be,f as Oe,g as Ve}from"./alert-dialog-DTozKlmV.js";import{P as $e}from"./PersonCombobox-CPOlNs6G.js";import{S as Ie}from"./MarkdownEditor-C9zqZjC5.js";import{U as Ee}from"./user-plus-CvBNcpn4.js";import{S as Ke}from"./share-2-CMnOlOt-.js";import{T as ie}from"./trash-2-HBi-Pslz.js";const Q=[{value:"private",label:"Private",hint:"Only people added to the nest"},{value:"org",label:"Organization",hint:"Everyone signed in here can read"},{value:"public",label:"Public",hint:"Anyone with the URL can read"}];function Xe({nestId:d,onChanged:k,onError:r,variant:z="card"}){var S,C;const[x,m]=n.useState("private"),h=x==="public",p=x==="org",[g,P]=n.useState(!1),[f,v]=n.useState(!1),b=(C=(S=ue(d).data)==null?void 0:S.nest)==null?void 0:C.visibility;n.useEffect(()=>{b&&m(b)},[b]);const j=async(l,u)=>{const o=x;m(l),P(!0),r==null||r(null);try{const s=await ye(d,l,u);if(m(s.visibility||l),s.visibility!==l){r==null||r("Server did not accept the change. You may not have admin access to this nest.");return}k()}catch(s){m(o),r==null||r((s==null?void 0:s.message)||"Failed to change visibility")}finally{P(!1)}},y=async l=>{if(l!==x){if(l==="public"){v(!0);return}await j(l)}},w=e.jsx(Me,{open:f,onOpenChange:v,children:e.jsxs(Re,{children:[e.jsxs(Fe,{children:[e.jsx(ze,{children:"Make this nest public?"}),e.jsx(Ue,{children:"This makes the nest readable by anyone on the internet, outside your organization. Anyone with the URL will be able to read it."})]}),e.jsxs(Be,{children:[e.jsx(Oe,{children:"Cancel"}),e.jsx(Ve,{onClick:()=>{v(!1),j("public",!0)},children:"Make public"})]})]})});if(z==="compact"){if(!b)return null;const l=h?ee:p?ae:se,u=Q.find(o=>o.value===x)??Q[0];return e.jsxs(e.Fragment,{children:[e.jsxs(pe,{children:[e.jsx(ve,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:g,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:`${u.label} — ${u.hint}. Click to change.`,"aria-label":`Nest visibility: ${u.label}`,"data-testid":"nest-visibility-compact",children:[g?e.jsx(A,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(l,{className:`h-3.5 w-3.5 ${h?"text-green-600":p?"text-blue-600":""}`}),e.jsx("span",{className:"hidden sm:inline",children:u.label}),e.jsx(be,{className:"h-3 w-3 opacity-60"})]})}),e.jsx(ge,{align:"end",className:"w-64",children:Q.map(o=>e.jsxs(fe,{onClick:()=>void y(o.value),className:"flex items-start gap-2",children:[o.value===x?e.jsx(je,{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:o.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:o.hint})]})]},o.value))})]}),w]})}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(F,{className:"flex items-center gap-2 text-sm font-medium",children:[h?e.jsx(ee,{className:"h-4 w-4 text-green-600"}):p?e.jsx(ae,{className:"h-4 w-4 text-blue-600"}):e.jsx(se,{className:"h-4 w-4"}),h?"Public":p?"Organization":"Private"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:h?"Anyone on the internet with the URL can read this nest. Editing still requires being added below.":p?"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:[g&&e.jsx(A,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground"}),e.jsxs(Y,{value:x,onValueChange:l=>void y(l),disabled:g,children:[e.jsx(_,{className:"h-8 w-[150px]","aria-label":"Nest visibility",children:e.jsx(W,{})}),e.jsxs(G,{children:[e.jsx(T,{value:"private",children:"Private"}),e.jsx(T,{value:"org",children:"Organization"}),e.jsx(T,{value:"public",children:"Public"})]})]})]})]}),w]})}const q=[{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"}],R={read:1,write:2,admin:3,owner:4};function Ze({nestId:d,nestName:k,onChanged:r,currentUserEmail:z,callerPermission:x="admin",showTeams:m=!1}){const h=(z||"").toLowerCase(),p=R[x]??R.read,g=p>=R.admin,P=q.filter(a=>R[a.value]<=p),[f,v]=n.useState([]),[H,b]=n.useState(!0),j=Ne(),[y,w]=n.useState(""),[S,C]=n.useState("read"),[l,u]=n.useState(!1),[o,s]=n.useState(null),[D,J]=n.useState("person"),[U,ne]=n.useState([]),[re,ce]=n.useState([]),[L,X]=n.useState(""),[B,M]=n.useState(!1),O=async()=>{b(!0);try{const{collaborators:a}=await j.fetchQuery(K.collaborators(d));v(a)}catch(a){s((a==null?void 0:a.message)||"Failed to load collaborators")}finally{b(!1)}},V=async()=>{try{const[a,i]=await Promise.all([j.fetchQuery(K.nestTeams(d)),j.fetchQuery(K.teamList()).catch(()=>({teams:[]}))]);ne(a.teams),ce(i.teams)}catch(a){s((a==null?void 0:a.message)||"Failed to load teams")}};n.useEffect(()=>{O(),m&&V()},[d]);const Z=async()=>{const a=y.trim();if(a){if(!Te(a)){s("Enter a valid email address.");return}u(!0),s(null);try{await ke(d,{email:a,permission:S}),w(""),C("read"),await O(),r()}catch(i){s((i==null?void 0:i.message)||"Failed to add collaborator")}finally{u(!1)}}},oe=a=>{a.preventDefault(),Z()},$=re.filter(a=>!U.some(i=>i.teamId===a.id)),de=async()=>{if(L){M(!0),s(null);try{await Ae(d,L),X(""),le.success("Team shared"),await V(),r()}catch(a){s((a==null?void 0:a.message)||"Failed to share team")}finally{M(!1)}}},me=async(a,i)=>{if(window.confirm(`Unshare "${i}" from "${k}"? Its members lose the access this share granted.`)){M(!0),s(null);try{await Pe(d,a),await V(),r()}catch(c){s((c==null?void 0:c.message)||"Failed to unshare team")}finally{M(!1)}}},he=async(a,i)=>{const t=f.find(c=>c.id===a);if(t&&(t.email||"").toLowerCase()===h){le.error("You can't change your own access level.");return}s(null),v(c=>c.map(I=>I.id===a?{...I,permission:i}:I));try{await De(d,a,i),r()}catch(c){s((c==null?void 0:c.message)||"Failed to update permission"),await O()}},xe=async a=>{if(window.confirm(`Remove ${a.email||"this collaborator"}'s access to "${k}"? They keep their account; only their access to this nest is revoked.`)){s(null);try{await Le(d,a.id),v(t=>t.filter(c=>c.id!==a.id)),r()}catch(t){s((t==null?void 0:t.message)||"Failed to remove collaborator")}}};return e.jsxs("div",{className:"space-y-4",children:[o&&e.jsxs(we,{variant:"destructive",children:[e.jsx(Se,{className:"h-4 w-4"}),e.jsx(Ce,{children:o})]}),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(F,{className:"flex items-center gap-2 text-sm font-medium",children:m&&D==="team"?e.jsxs(e.Fragment,{children:[e.jsx(te,{className:"h-4 w-4"}),"Add a team"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ee,{className:"h-4 w-4"}),"Add a person"]})}),m&&e.jsxs("div",{className:"flex gap-1",children:[e.jsx(N,{type:"button",size:"sm",variant:D==="person"?"secondary":"ghost",className:"h-7 px-2 text-xs",onClick:()=>J("person"),children:"Person"}),e.jsx(N,{type:"button",size:"sm",variant:D==="team"?"secondary":"ghost",className:"h-7 px-2 text-xs",onClick:()=>J("team"),children:"Team"})]})]}),m&&D==="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(Ie,{value:L,onChange:X,options:$.map(a=>({value:a.id,label:a.name})),disabled:$.length===0,placeholder:$.length===0?"No teams available to share":"Select a team…",searchPlaceholder:"Search teams…",emptyText:"No teams match.",testId:"collab-team-select"})}),e.jsx(N,{onClick:de,disabled:B||!L,children:B?e.jsx(A,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ke,{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:oe,className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx($e,{value:y,onChange:w,onSubmit:Z,placeholder:"teammate@example.com",disabled:l,className:"flex-1",exclude:f.map(a=>a.email||"").filter(Boolean),testId:"collab-person-input"}),e.jsxs(Y,{value:S,onValueChange:a=>C(a),children:[e.jsx(_,{className:"w-full sm:w-[130px]",children:e.jsx(W,{})}),e.jsx(G,{children:P.map(a=>e.jsx(T,{value:a.value,children:a.label},a.value))})]}),e.jsx(N,{type:"submit",disabled:l||!y.trim(),children:l?e.jsx(A,{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."})]})]}),m&&U.length>0&&e.jsxs("div",{className:"rounded-lg border p-4 space-y-2",children:[e.jsxs(F,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(te,{className:"h-4 w-4"}),"Teams with access"]}),e.jsx("div",{className:"space-y-1",children:U.map(a=>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:a.teamName}),e.jsxs(E,{variant:"secondary",className:"text-[11px]",children:[a.members.length," member",a.members.length===1?"":"s"]}),e.jsx(N,{variant:"ghost",size:"sm",disabled:B,onClick:()=>me(a.teamId,a.teamName),title:"Unshare team",className:"text-destructive hover:text-destructive hover:bg-destructive/10",children:e.jsx(ie,{className:"h-3.5 w-3.5"})})]},a.teamId))})]}),e.jsxs("div",{className:"rounded-lg border p-4 space-y-2",children:[e.jsx(F,{className:"text-sm font-medium",children:"People with access"}),H?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(A,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):f.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:f.map(a=>{var i;return e.jsxs("div",{className:"flex items-center gap-2 py-1.5","data-testid":`collaborator-row-${a.id}`,children:[e.jsx("span",{className:"flex-1 min-w-0 truncate text-sm",children:a.email||a.user_id}),(a.stewardRoles??[]).map(t=>e.jsx(E,{variant:"outline",className:"text-[10px] px-1.5 py-0 capitalize",title:"Steward role — manage in the Stewards tab",children:t},t)),g?e.jsxs(e.Fragment,{children:[e.jsxs(Y,{value:a.permission,disabled:(a.email||"").toLowerCase()===h,onValueChange:t=>he(a.id,t),children:[e.jsx(_,{className:"w-[120px] h-8",title:(a.email||"").toLowerCase()===h?"You can't change your own access level":void 0,children:e.jsx(W,{})}),e.jsx(G,{children:q.map(t=>e.jsx(T,{value:t.value,children:t.label},t.value))})]}),(a.email||"").toLowerCase()!==h&&e.jsx(N,{variant:"ghost",size:"sm",onClick:()=>xe(a),title:"Remove access",className:"text-destructive hover:text-destructive hover:bg-destructive/10",children:e.jsx(ie,{className:"h-3.5 w-3.5"})})]}):e.jsx(E,{variant:"secondary",className:"text-[11px] capitalize",children:((i=q.find(t=>t.value===a.permission))==null?void 0:i.label)??a.permission})]},a.id)})})]})]})}export{Ze as C,Xe as N};
@@ -0,0 +1 @@
1
+ import{j as s,f as c}from"./index-EaX2yql0.js";import{N as p,C as h}from"./CollaboratorManager-By91wrIr.js";import{C as x,a as f,c as u,b as j,d as b}from"./card-XG2dP5Xf.js";import"./select-DBFTrUmI.js";import"./alert-dialog-DTozKlmV.js";import"./PersonCombobox-CPOlNs6G.js";import"./MarkdownEditor-C9zqZjC5.js";import"./scroll-area-hz-xtayP.js";import"./index-C1wTSjfP.js";import"./arrow-left-BCKt4CwQ.js";import"./trash-2-HBi-Pslz.js";import"./x-By7piikG.js";import"./zap-C2T8riBp.js";import"./user-plus-CvBNcpn4.js";import"./share-2-CMnOlOt-.js";function M({nestId:r,nestName:t,canManage:a,canManageGovernance:n,stewardshipEnabled:i,currentUserEmail:l,callerPermission:d,onOpenSettings:m,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.",i?" Stewards are assigned on the Stewards tab.":n?s.jsxs(s.Fragment,{children:[" ","Turn on Stewardship & Approval Workflow in"," ",s.jsx("button",{type:"button",onClick:m,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:d,showTeams:!0})]})]})}export{M as CollaboratorsTab};
@@ -0,0 +1,36 @@
1
+ import{c as Ns,r as n,j as e,A as Re,a as Te,B as v,L as I,b as li,g as oi,d as ci,I as Qn,e as kt,t as di,f as C,u as ks,h as ui,i as ye,k as Gn,l as vs,m as mi,n as Kn,o as Xn,p as Yn,q as Zn,E as hi,s as ra,F as Qs,v as xi,C as Mt,w as Gs,D as wt,x as vt,y as jt,z as yt,G as Ks,H as Nt,J as fi,U as ia,K as Ae,M as pi,N as gi,O as la,T as bi,P as wi,Q as on,R as cn,S as vi,V as Jn,W as ji,X as yi,Y as Ni,Z as ki,_ as Si,$ as Ci,a0 as Ri,a1 as Xs,a2 as dn,a3 as Ti,a4 as Bs,a5 as un,a6 as mn,a7 as $i,a8 as hn,a9 as Ei,aa as xn,ab as Li,ac as Di,ad as Ai,ae as Mi,af as In,ag as er,ah as tr,ai as sr,aj as ar,ak as Yt,al as nr,am as Fi,an as Pi,ao as Oi,ap as Vi,aq as qi,ar as zi,as as _i,at as Hi,au as fn,av as Bi,aw as pn,ax as Wi,ay as Ui,az as Qi,aA as gn,aB as Gi,aC as Ki,aD as Xi}from"./index-EaX2yql0.js";import{f as js,r as bn}from"./dates-BCxbm4_q.js";import{T as Ys,p as Yi,t as Zi,U as Ji,a as Ii,r as el,u as tl,b as Ws,l as sl,c as al,H as nl,D as Zs,d as rl,g as il,S as ll,i as ol,e as rr,m as cl,Q as wn,f as dl,h as ul,W as vn,j as jn,k as ml,O as hl,n as xl,o as fl,M as pl,q as gl,F as bl,L as wl}from"./MarkdownEditor-C9zqZjC5.js";import{N as ir,C as vl}from"./CollaboratorManager-By91wrIr.js";import{S as jl,a as yl,b as Nl,c as kl,d as yn}from"./select-DBFTrUmI.js";import{D as lr,H as or,R as oa,V as cr,e as Js,f as Sl,s as Cl,r as Rl,A as Tl,u as $l,S as El,P as Ll}from"./backlinks-CYd4xENL.js";import{P as Dl}from"./play-C5YNKpAH.js";import{T as Al}from"./triangle-alert-CDy8-7sv.js";import{T as Ml}from"./scroll-area-hz-xtayP.js";import"./card-XG2dP5Xf.js";import{A as Is}from"./arrow-left-BCKt4CwQ.js";import{C as Zt}from"./code-xml-CMabYZvH.js";import{R as ea}from"./refresh-cw-BhHzSH9m.js";import{M as ys,R as Fl}from"./ReviewActions-OfOdqzCn.js";import{X as et}from"./x-By7piikG.js";import{S as ta}from"./send-0CHvmluT.js";import{T as sa}from"./trash-2-HBi-Pslz.js";import{S as aa}from"./share-2-CMnOlOt-.js";import{C as Pl}from"./circle-check-DI8IBGeo.js";import{C as Ol}from"./corner-down-right-BGxwK6wH.js";import{A as Vl,a as ql,b as zl,c as _l,d as Hl,e as Bl,f as Wl,g as Ul}from"./alert-dialog-DTozKlmV.js";import{S as Ql}from"./SubmitForReviewModal-Ci2DdWs0.js";import{R as Gl}from"./ReasonDialog-DgLxfRWv.js";import{F as dr}from"./file-exclamation-point-r8qZGIjP.js";import{Z as Nn}from"./zap-C2T8riBp.js";import{F as kn}from"./folder-input-Cmtx1Jhk.js";import"./index-C1wTSjfP.js";import"./PersonCombobox-CPOlNs6G.js";import"./user-plus-CvBNcpn4.js";import"./circle-x-VKVhC88W.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 Kl=[["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"}]],Sn=Ns("git-compare",Kl);/**
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 Xl=[["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"}]],ur=Ns("message-square-plus",Xl);/**
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 Yl=[["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"}]],Cn=Ns("save",Yl);/**
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 Zl=[["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"}]],Rn=Ns("undo-2",Zl);function Jl({nestId:s,nodeId:r,pending:a,onResolved:o}){const[l,u]=n.useState(null),[x,m]=n.useState(!1),[h,f]=n.useState(""),[g,k]=n.useState(null),[w,y]=n.useState(null),j=async()=>{u("approve"),y(null);try{await li(s,r,a.suggestion_id),o()}catch(A){y(A.message||"Approval failed")}finally{u(null)}},q=async()=>{if(!h.trim()){y("Rejection reason is required");return}u("reject"),y(null);try{await ci(s,r,a.suggestion_id,h.trim()),o()}catch(A){y(A.message||"Rejection failed")}finally{u(null)}},P=async()=>{if(g){k(null);return}u("view"),y(null);try{const{entry:A}=await oi(s,r,a.suggestion_id);k(A)}catch(A){y(A.message||"Failed to load diff")}finally{u(null)}};return e.jsxs(Re,{className:"border-orange-300 bg-orange-50 dark:bg-orange-950/30",children:[e.jsx(dr,{className:"h-4 w-4 text-orange-700 dark:text-orange-400"}),e.jsxs(Te,{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 ",js(a.detected_at)," ·"," ",e.jsx("code",{className:"text-xs",children:a.source}),". The displayed content is the last approved version; the on-disk change is staged for review."]})]}),w&&e.jsx("div",{className:"text-sm text-red-700 dark:text-red-400",children:w}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(v,{size:"sm",onClick:j,disabled:l!==null,"data-testid":"external-edit-approve",children:[l==="approve"?e.jsx(I,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Approve change"]}),e.jsx(v,{size:"sm",variant:"outline",onClick:()=>m(A=>!A),disabled:l!==null,"data-testid":"external-edit-reject-toggle",children:"Reject"}),e.jsxs(v,{size:"sm",variant:"ghost",onClick:P,disabled:l!==null,"data-testid":"external-edit-view-diff",children:[l==="view"?e.jsx(I,{className:"h-4 w-4 mr-2 animate-spin"}):null,g?"Hide diff":"View diff"]})]}),x&&e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsx(Ml,{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(v,{size:"sm",variant:"destructive",onClick:q,disabled:l!==null||!h.trim(),"data-testid":"external-edit-reject-confirm",children:[l==="reject"?e.jsx(I,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Confirm reject"]}),e.jsx(v,{size:"sm",variant:"ghost",onClick:()=>{m(!1),f("")},disabled:l!==null,children:"Cancel"})]})]}),(g==null?void 0:g.patch)&&e.jsx("div",{className:"pt-2",children:e.jsx(lr,{patch:g.patch})})]})]})}const ws=40,Il=120,eo=/[^a-zA-Z0-9_:-]+/g,to=s=>s.normalize("NFD").replace(new RegExp("\\p{Diacritic}","gu"),"");function Tn(s,r){const a=new Set(s.map(na)),o=[];for(const l of r){const u=na(l);a.has(u)||(a.add(u),o.push(l))}return o}function na(s){return mr(s).tag??s.trim().toLowerCase()}function mr(s){const r=s.trim().replace(/^#+/,"");if(!r)return{tag:null,note:null};const a=to(r).replace(eo,"").replace(/^[^a-zA-Z]+|[_:-]+$/g,"").toLowerCase();return a?a.length>ws?{tag:a.slice(0,ws),note:`Tags are capped at ${ws} characters — "${r}" was shortened.`}:a!==r.toLowerCase()?{tag:a,note:`"${r}" was adjusted to "${a}".`}:{tag:a,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 so(s){return s.replace(/[^\s,]+/g,r=>{const a=/^#*/.exec(r)[0];return a+r.slice(a.length,a.length+ws)})}function ao(s){const{isNew:r,isOwner:a,isAdmin:o,permission:l,nestStewards:u,nodeRoles:x,grant:m,isArchived:h}=s,f=a||o||l==="owner"||l==="admin"||l==="write"||u.some(j=>j.role==="editor"&&j.scope==="nest"),g=o||l==="admin"||x.includes("admin"),k=x.includes("editor")||x.includes("admin"),w=h?!0:r?!f:!(f||m==="write"||k),y=!a&&x.length>0&&!x.includes("editor")&&!g;return{canAuthorNew:f,hasAdminApprove:g,isViewOnly:w,isReviewerOnly:y,canEditContent:!w&&!y}}function $n(s){const r=[];let a="",o=!1;for(let l=0;l<s.length;l++){const u=s[l];o?u==='"'?s[l+1]==='"'?(a+='"',l++):o=!1:a+=u:u==='"'?o=!0:u===","?(r.push(a),a=""):a+=u}return r.push(a),r.map(l=>l.trim())}function no({nestId:s,nodeId:r,csv:a}){const[o,l]=n.useState(""),[u,x]=n.useState(null),[m,h]=n.useState(null),[f,g]=n.useState(!1),k=n.useMemo(()=>{const j=a.split(/\r?\n/).filter(A=>A.trim()!==""&&!A.trim().startsWith("#"));if(!j.length)return{header:[],rows:[]};const q=$n(j[0]),P=j.slice(1).map($n);return{header:q,rows:P}},[a]),w=async()=>{g(!0),h(null);try{x(await di(s,r,o))}catch(j){x(null),h(j instanceof Error?j.message:"Query failed")}finally{g(!1)}},y=u??{columns:k.header.map(j=>j.split(":")[0]),rows:k.rows,matched:k.rows.length,returned:k.rows.length,total:k.rows.length};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"h-4 w-4 text-cyan-500 shrink-0"}),e.jsx(Qn,{value:o,onChange:j=>l(j.target.value),onKeyDown:j=>j.key==="Enter"&&void w(),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(v,{size:"sm",className:"h-8",disabled:f,onClick:()=>void w(),children:[e.jsx(Dl,{className:"h-3.5 w-3.5 mr-1"})," Query"]}),u&&e.jsx(v,{size:"sm",variant:"ghost",className:"h-8 text-muted-foreground",onClick:()=>{x(null),h(null)},children:"Show all"})]}),m&&e.jsx("div",{className:"rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:m}),e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsxs(kt,{variant:"secondary",className:"text-[10px]",children:[y.returned," row",y.returned===1?"":"s",u?` of ${y.matched} matching`:""," · ",y.total," total"]}),k.header.filter(j=>j.includes(":")).map(j=>e.jsx(kt,{variant:"outline",className:"text-[10px] font-mono",children:j},j))]}),e.jsx(ca,{columns:y.columns,rows:y.rows})]})}function ca({columns:s,rows:r,limit:a=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,a).map((l,u)=>e.jsx("tr",{className:`border-t align-top hover:bg-muted/30 ${(o==null?void 0:o(u))??""}`,children:l.map((x,m)=>e.jsx("td",{className:"px-3 py-1.5 whitespace-nowrap font-mono",children:x},m))},u))})]}),r.length>a&&e.jsxs("p",{className:"px-3 py-2 text-[11px] text-muted-foreground border-t",children:["Showing first ",a.toLocaleString()," rows."]})]})}function ro({value:s,onChange:r,onBlur:a,readOnly:o=!1}){const l=n.useRef(null),[u,x]=n.useState(!1),m=o||u,h=n.useMemo(()=>{const w=Yi(s,",").filter(y=>!(y[0]??"").trimStart().startsWith("#")&&y.some(j=>j.trim()!==""));return{columns:(w[0]??[]).map(y=>y.split(":")[0].trim()),rows:w.slice(1),issues:Zi(w)}},[s]),f=(w,y)=>{const j=s;r(w),C(y,j.trim()?{action:{label:"Undo",onClick:()=>r(j)}}:void 0)},g=async w=>{var j;if(m)return;const y=(j=w.target.files)==null?void 0:j[0];if(w.target.value="",!!y){x(!0);try{const q=C.loading("Processing file…");await new Promise(B=>requestAnimationFrame(()=>requestAnimationFrame(()=>B(null))));const P=await el(y);if(!P.ok){C.error(tl(P.error,y),{id:q});return}const A=P.delimiter===","?P.text:Ws(P.rows),d=Math.max(0,P.rows.filter(B=>!(B[0]??"").trimStart().startsWith("#")).length-1);C.dismiss(q),f(A,`Table replaced from ${y.name} — ${d.toLocaleString()} data row${d===1?"":"s"}.`)}finally{x(!1)}}},k=w=>{if(m)return;const y=w.clipboardData.getData("text/plain"),j=sl(y);if(j&&j.delimiter!==","){w.preventDefault(),f(Ws(j.rows),`Pasted grid converted to CSV — table body replaced (${j.rows.length.toLocaleString()} rows).`);return}if(j)return;const q=al(y);if(!q)return;w.preventDefault();const P=w.currentTarget,A=P.selectionStart??s.length,d=P.selectionEnd??A,B=Ws(q.rows);r(s.slice(0,A)+B+s.slice(d));const S=A+B.length;requestAnimationFrame(()=>P.setSelectionRange(S,S))};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(v,{type:"button",variant:"outline",size:"sm",className:"h-7 shrink-0",disabled:m,onClick:()=>{var w;return(w=l.current)==null?void 0:w.click()},"data-testid":"table-source-upload",children:[e.jsx(Ji,{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:g})]}),e.jsxs("div",{className:h.columns.length>0?"grid gap-3 lg:grid-cols-2":"",children:[e.jsx("textarea",{value:s,onChange:w=>{m||r(w.target.value)},onBlur:a,onPaste:k,readOnly:m,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(Al,{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((w,y)=>e.jsx("li",{children:Ii(w)},`${w.column}-${w.kind}-${y}`))})]})]})}),e.jsx(ca,{columns:h.columns,rows:h.rows,limit:50})]})]})]})}const En=250,io=new Set(["P","DIV","SECTION","ARTICLE","HEADER","FOOTER","LI","TR","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","PRE","TABLE","UL","OL","BR","HR"]);function lo(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 a="";const o=(l,u)=>{if(l.nodeType===Node.TEXT_NODE){const h=l.textContent||"";a+=u?h:h.replace(/\s+/g," ");return}if(l.nodeType!==Node.ELEMENT_NODE)return;const x=l.tagName,m=io.has(x);m&&a&&!a.endsWith(`
28
+ `)&&(a+=`
29
+ `),l.childNodes.forEach(h=>o(h,u||x==="PRE")),m&&!a.endsWith(`
30
+ `)&&(a+=`
31
+ `)};return o(r.body,!1),a.replace(/[ \t]+\n/g,`
32
+ `).replace(/\n{3,}/g,`
33
+
34
+ `).trim()}function oo(s,r,a){if(r<0||a>s.length||r>=a)return null;const o=s.slice(r,a).trim();return o?{quote:o,before:s.slice(Math.max(0,r-En),r),after:s.slice(a,a+En),line:s.slice(0,r).split(`
35
+ `).length}:null}const co="artifact";function uo(s){return(s==null?void 0:s.replace("T"," ").replace(/\.\d+Z?$/,"").slice(0,16))||s}function mo({nestId:s,nodeId:r,title:a,snapshotVersion:o,currentEmail:l,viewOnly:u=!1,reviewerOnly:x=!1,initialThreadId:m,onBack:h,onTurnedInto:f}){var Q;const[g,k]=n.useState("preview"),[w,y]=n.useState(!!m);n.useEffect(()=>{g==="annotate"&&y(!0)},[g]);const[j,q]=n.useState(!1),[P,A]=n.useState(!1),d=async()=>{A(!0);try{await vs(s,r,{type:"document"}),C.success("Turned into a document"),q(!1),f==null||f()}catch(c){C.error(c instanceof Error?c.message:"Failed to convert")}finally{A(!1)}},B=ks(),[S,Z]=n.useState([]),[te,fe]=n.useState(!0),[N,F]=n.useState(""),[K,pe]=n.useState(null),St=K==null||/^s*</.test(K),[tt,ze]=n.useState(!1),[ge,_e]=n.useState(o??null),[b,O]=n.useState(0),[se,He]=n.useState(!1),[Be,Ft]=n.useState(null),[le,Ct]=n.useState(null),[We,st]=n.useState(null),[R,at]=n.useState(!1),[z,Me]=n.useState(null),[T,Ne]=n.useState(!1),[_,$e]=n.useState(""),[ne,nt]=n.useState(!1),oe=!u,Pt=!u&&!x,Ee=(z==null?void 0:z.status)==="pending_review",ue=z!=null&&_!==z.content,ce=Ee||Be!=null&&((Q=Be.versions.find(c=>c.version===Be.currentVersion))==null?void 0:Q.status)==="pending_review",[Le,X]=n.useState(null),[Ue,Jt]=n.useState(""),[Ot,J]=n.useState(!1),[Vt,rt]=n.useState(null),[Qe,ke]=n.useState(""),Rt=n.useRef(null),Fe=ui(s,r,le??ge,b),it=n.useCallback(async()=>{try{Ft(await B.fetchQuery(ye.nodeVersions(s,r)))}catch(c){Ft(null),C.error((c==null?void 0:c.message)||"Failed to load version history")}},[s,r]),U=n.useCallback(c=>{if(g==="edit"&&ue){if(!window.confirm("Discard unsaved source changes?"))return;z&&$e(z.content)}c()},[g,ue,z]),Ss=n.useCallback(()=>{U(()=>{He(!0),it()})},[U,it]);n.useEffect(()=>{if(!ue)return;const c=L=>{L.preventDefault(),L.returnValue=""};return window.addEventListener("beforeunload",c),()=>window.removeEventListener("beforeunload",c)},[ue]);const Ge=n.useCallback(c=>{U(()=>{He(!1),Ct(c),k("preview"),F(""),pe(null),O(L=>L+1)})},[U]),Cs=n.useCallback(()=>{Ct(null),F(""),pe(null),O(c=>c+1)},[]),Ke=n.useCallback(async c=>{await Gn(s,r,c),C.success(`Restored from version ${c}`),Ct(null),He(!1),k("preview"),_e(null),F(""),pe(null),Me(null),$e(""),O(L=>L+1),await it()},[s,r,it]),It=n.useCallback(async()=>{if(We!=null){at(!0);try{await Ke(We),st(null)}catch(c){C.error((c==null?void 0:c.message)||"Restore failed")}finally{at(!1)}}},[We,Ke]),Xe=n.useCallback(async()=>{if(Ct(null),k("edit"),!(z||T)){Ne(!0);try{const{node:c}=await B.fetchQuery(ye.node(s,r)),L=(c==null?void 0:c.content)==null?"":String(c.content);Me({content:L,version:c==null?void 0:c.version,status:(c==null?void 0:c.status)??null}),$e(L)}catch(c){C.error((c==null?void 0:c.message)||"Failed to load artifact source"),k("preview")}finally{Ne(!1)}}},[z,T,s,r]),Rs=n.useCallback(async()=>{var c,L;if(!(!z||!ue||ne)){nt(!0);try{const $=await vs(s,r,{content:_},z.version),ie=($==null?void 0:$.version)??((c=$==null?void 0:$.node)==null?void 0:c.version);Me({content:_,version:typeof ie=="number"?ie:z.version,status:((L=$==null?void 0:$.node)==null?void 0:L.status)??z.status}),_e(null),F(""),pe(null),O($t=>$t+1),k("preview"),C.success(typeof ie=="number"?`Saved as version ${ie}`:"Artifact saved")}catch($){C.error(($==null?void 0:$.message)||"Save failed")}finally{nt(!1)}}},[z,ue,ne,s,r,_]),es=n.useCallback(()=>{U(()=>k("preview"))},[U]),be=n.useCallback(async()=>{fe(!0);try{const{threads:c}=await B.fetchQuery(ye.nodeAnnotations(s,r));Z(c)}catch(c){C.error((c==null?void 0:c.message)||"Failed to load annotations")}finally{fe(!1)}},[s,r]);n.useEffect(()=>{be()},[be]);const qt=n.useRef(!1);n.useEffect(()=>{!m||qt.current||te||S.some(c=>c.id===m)&&(qt.current=!0,requestAnimationFrame(()=>{var c;(c=document.getElementById(`annotation-thread-${m}`))==null||c.scrollIntoView({behavior:"smooth",block:"center"})}))},[S,te,m]);const ts=n.useCallback(async()=>{if(!(N||tt)){ze(!0);try{const{html:c,snapshot:L}=await mi(s,r,le??ge,b);F(lo(c)),pe(c),L!=null&&le==null&&_e(L)}catch(c){C.error((c==null?void 0:c.message)||"Failed to load artifact text")}finally{ze(!1)}}},[N,tt,s,r,ge,le,b]);n.useEffect(()=>{(g==="annotate"||g==="preview")&&ts()},[g,ts]);const Tt=n.useCallback(()=>{const c=window.getSelection(),L=Rt.current;if(!c||c.isCollapsed||!L){X(null);return}const $=c.getRangeAt(0);if(!L.contains($.startContainer)||!L.contains($.endContainer))return;const ie=Math.min($.startOffset,$.endOffset),$t=Math.max($.startOffset,$.endOffset),ct=N.slice(ie,$t).trim();if(!ct){X(null);return}X({start:ie,end:$t,quote:ct})},[N]),zt=n.useCallback(async()=>{var L,$;const c=Ue.trim();if(c){J(!0);try{const ie=Le!=null?oo(N,Le.start,Le.end):null;await Kn(s,r,{body:c,anchor:ie,snapshotVersion:ge}),Jt(""),X(null),($=(L=window.getSelection)==null?void 0:L.call(window))==null||$.removeAllRanges(),await be(),C.success("Comment added")}catch(ie){C.error((ie==null?void 0:ie.message)||"Failed to add comment")}finally{J(!1)}}},[Ue,Le,N,s,r,ge,be]),lt=n.useCallback(async c=>{const L=Qe.trim();if(L)try{await Xn(s,r,c,L),ke(""),rt(null),await be()}catch($){C.error(($==null?void 0:$.message)||"Failed to reply")}},[Qe,s,r,be]),Se=n.useCallback(async c=>{try{c.status==="open"?await Yn(s,r,c.id):await Zn(s,r,c.id),await be()}catch(L){C.error((L==null?void 0:L.message)||"Failed to update thread")}},[s,r,be]),{openThreads:ot,resolvedThreads:re}=n.useMemo(()=>{const c=S.filter($=>$.status==="open"),L=S.filter($=>$.status==="resolved");return{openThreads:c,resolvedThreads:L}},[S]);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(v,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>U(h),children:e.jsx(Is,{className:"h-4 w-4"})}),e.jsx("h1",{className:"text-sm font-medium truncate",children:a||r}),e.jsx(kt,{variant:"secondary",className:"shrink-0 gap-1",children:"Artifact"}),le!=null?e.jsxs(kt,{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",le]}):ge!=null?e.jsxs(kt,{variant:"outline",className:"shrink-0",title:"Annotations are anchored to this frozen snapshot.",children:["Snapshot v",ge]}):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:()=>U(()=>k("preview")),children:[e.jsx(hi,{className:"h-4 w-4"})," Preview"]}),e.jsxs("button",{type:"button",className:ra("px-3 h-full inline-flex items-center gap-1.5 text-sm disabled:opacity-50",!Pt&&"rounded-r-md",g==="annotate"?"bg-muted":"hover:bg-muted/50"),disabled:le!=null,title:le!=null?"Return to the current version to annotate":void 0,onClick:()=>U(()=>k("annotate")),children:[e.jsx(nl,{className:"h-4 w-4"})," Annotate"]}),Pt&&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 Xe(),children:[e.jsx(Zt,{className:"h-4 w-4"})," Edit source"]})]}),e.jsx(v,{variant:"outline",size:"icon",title:"Version history",onClick:Ss,children:e.jsx(or,{className:"h-4 w-4"})}),e.jsx(v,{variant:"outline",size:"icon",title:"Reload artifact",onClick:()=>O(c=>c+1),children:e.jsx(ea,{className:"h-4 w-4"})}),!u&&!x&&f&&e.jsx(v,{variant:"outline",size:"icon",title:ue?"Save or discard the source edits first":"Turn into a document",disabled:ue,onClick:()=>q(!0),"data-testid":"artifact-turn-into-document",children:e.jsx(Qs,{className:"h-4 w-4"})}),e.jsxs(v,{variant:w?"secondary":"outline",size:"icon",title:w?"Hide annotations":"Show annotations","aria-pressed":w,onClick:()=>y(c=>!c),"data-testid":"artifact-comments-toggle",className:"relative",children:[e.jsx(ys,{className:"h-4 w-4"}),ot.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:ot.length})]}),e.jsx("a",{href:Fe,target:"_blank",rel:"noopener noreferrer",children:e.jsx(v,{variant:"outline",size:"icon",title:"Open in new tab",children:e.jsx(xi,{className:"h-4 w-4"})})})]})]}),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:[le!=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 ",le]})," ","— read-only historical snapshot."]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[oe&&e.jsxs(v,{size:"sm",variant:"outline",className:"h-6 px-2 text-xs border-amber-300 text-amber-900 hover:bg-amber-100",disabled:ce,title:ce?"Locked while awaiting steward review — resolve the review first":void 0,onClick:()=>st(le),children:[e.jsx(oa,{className:"h-3 w-3 mr-1"}),ce?"Locked — review pending":"Restore this version"]}),e.jsxs(v,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-amber-900 hover:bg-amber-100",onClick:Cs,children:[e.jsx(et,{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:Ee?"Locked while awaiting steward review — resolve the review before editing.":"Editing raw HTML source. Saving creates a new version, like any document edit."}),T?e.jsxs("div",{className:"flex items-center justify-center flex-1 text-muted-foreground",children:[e.jsx(I,{className:"h-5 w-5 animate-spin mr-2"})," Loading source…"]}):e.jsxs(e.Fragment,{children:[e.jsx("textarea",{value:_,onChange:c=>$e(c.target.value),readOnly:Ee,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:[(z==null?void 0:z.version)!=null?`Editing v${z.version}`:"",ue?" · unsaved changes":""]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(v,{variant:"ghost",size:"sm",onClick:es,disabled:ne,children:"Cancel"}),e.jsxs(v,{size:"sm",onClick:()=>void Rs(),disabled:Ee||ne||!ue||!_.trim(),title:Ee?"Locked while awaiting steward review":void 0,children:[ne?e.jsx(I,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(Mt,{className:"h-4 w-4 mr-1.5"}),"Save"]})]})]})]})]}):g==="preview"&&!St?e.jsx(Zs,{content:K??"",className:"flex-1 min-h-[70vh] max-h-none overflow-visible rounded-lg border bg-background"}):g==="preview"?e.jsx("iframe",{src:Fe,title:a||r,sandbox:"allow-scripts allow-popups allow-modals",className:"w-full flex-1 min-h-[70vh] rounded-lg border bg-white"},b):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."}),tt?e.jsxs("div",{className:"flex items-center justify-center flex-1 text-muted-foreground",children:[e.jsx(I,{className:"h-5 w-5 animate-spin mr-2"})," Loading text…"]}):e.jsx("pre",{ref:Rt,onMouseUp:Tt,className:"flex-1 overflow-auto whitespace-pre-wrap break-words p-4 text-sm leading-relaxed font-sans selection:bg-amber-200",children:N||"(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]${w?"":" hidden"}`,"data-testid":"artifact-comments-rail","aria-hidden":!w,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:[" ","· ",ot.length," open"]})]}),e.jsx(v,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Refresh",onClick:be,children:e.jsx(ea,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"p-3 border-b space-y-2",children:[Le?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:"})," ",'"',Le.quote.length>80?Le.quote.slice(0,80)+"…":Le.quote,'"',e.jsx("button",{type:"button",className:"ml-2 underline text-amber-700",onClick:()=>{var c,L;X(null),(L=(c=window.getSelection)==null?void 0:c.call(window))==null||L.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:Ue,onChange:c=>Jt(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(v,{size:"sm",onClick:zt,disabled:Ot||!Ue.trim(),children:[Ot?e.jsx(I,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(ur,{className:"h-4 w-4 mr-1.5"}),"Comment"]})})]}),e.jsx("div",{className:"flex-1 overflow-auto p-3 space-y-3",children:te?e.jsxs("div",{className:"flex items-center justify-center py-8 text-muted-foreground",children:[e.jsx(I,{className:"h-4 w-4 animate-spin mr-2"})," Loading…"]}):S.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:[ot.map(c=>e.jsx(Ln,{thread:c,currentEmail:l,replyOpen:Vt===c.id,replyBody:Qe,onReplyOpen:()=>{rt(c.id),ke("")},onReplyChange:ke,onReplySubmit:()=>lt(c.id),onToggleResolved:()=>Se(c)},c.id)),re.length>0&&e.jsx("div",{className:"pt-2 text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Resolved"}),re.map(c=>e.jsx(Ln,{thread:c,currentEmail:l,replyOpen:Vt===c.id,replyBody:Qe,onReplyOpen:()=>{rt(c.id),ke("")},onReplyChange:ke,onReplySubmit:()=>lt(c.id),onToggleResolved:()=>Se(c)},c.id))]})})]})]}),se&&e.jsx(cr,{open:!0,onClose:()=>He(!1),title:a||r,versionData:Be,previewAs:"source",onView:Ge,onLoadContent:async c=>(await Gs(s,r,c)).content,onRestore:oe?async c=>{try{await Ke(c)}catch(L){C.error((L==null?void 0:L.message)||"Restore failed")}}:void 0}),e.jsx(wt,{open:j,onOpenChange:c=>{P||q(c)},children:e.jsxs(vt,{className:"sm:max-w-[440px]",children:[e.jsxs(jt,{children:[e.jsx(yt,{children:"Turn into a document?"}),e.jsx(Ks,{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(Nt,{children:[e.jsx(v,{variant:"outline",onClick:()=>q(!1),disabled:P,children:"Cancel"}),e.jsxs(v,{onClick:()=>void d(),disabled:P,"data-testid":"artifact-turn-into-confirm",children:[P?e.jsx(I,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Turn into document"]})]})]})}),e.jsx(wt,{open:We!=null,onOpenChange:c=>!c&&st(null),children:e.jsxs(vt,{children:[e.jsxs(jt,{children:[e.jsxs(yt,{children:["Restore version ",We,"?"]}),e.jsxs(Ks,{children:["This writes version ",We,"'s HTML as a new version through the normal save path — review rules still apply and the current content stays in history."]})]}),e.jsxs(Nt,{children:[e.jsx(v,{variant:"outline",onClick:()=>st(null),disabled:R,children:"Cancel"}),e.jsx(v,{onClick:()=>void It(),disabled:R,children:R?"Restoring…":"Restore"})]})]})})]})}function Ln({thread:s,replyOpen:r,replyBody:a,onReplyOpen:o,onReplyChange:l,onReplySubmit:u,onToggleResolved:x}){const m=s.status==="resolved";return e.jsxs("div",{id:`annotation-thread-${s.id}`,className:`rounded-lg border p-2.5 text-sm ${m?"bg-muted/40 opacity-80":"bg-background"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx(kt,{variant:"outline",className:m?"border-emerald-200 bg-emerald-50 text-emerald-700":"border-amber-200 bg-amber-50 text-amber-700",children:m?"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:m?"Reopen thread":"Mark resolved",children:m?e.jsxs(e.Fragment,{children:[e.jsx(oa,{className:"h-3 w-3"})," Reopen"]}):e.jsxs(e.Fragment,{children:[e.jsx(Mt,{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:uo(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:a,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(v,{size:"sm",onClick:u,disabled:!a.trim(),children:[e.jsx(ta,{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 ho=rl(il);function hr(s){return s.map((r,a)=>{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:hr(r.children??[])},a)})}function Dn({code:s,className:r="",...a}){const o=n.useMemo(()=>{if(!s.trim())return null;try{return hr(ho.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}`,...a,children:e.jsx("code",{children:o??s})})}function xo({nestId:s,onChanged:r}){const[a,o]=n.useState([]),[l,u]=n.useState([]),[x,m]=n.useState(""),[h,f]=n.useState(!0),g=ks(),[k,w]=n.useState(!1),[y,j]=n.useState(null),q=async()=>{f(!0),j(null);try{const[S,Z]=await Promise.all([g.fetchQuery(ye.nestTeams(s)),g.fetchQuery(ye.teamList()).catch(()=>({teams:[]}))]);o(S.teams),u(Z.teams)}catch(S){j((S==null?void 0:S.message)||"Failed to load teams")}finally{f(!1)}};n.useEffect(()=>{q()},[s]);const P=new Set(a.map(S=>S.teamId)),A=l.filter(S=>!P.has(S.id)),d=async()=>{if(x){w(!0);try{await gi(s,x),m(""),C.success("Team shared"),await q(),r()}catch(S){C.error((S==null?void 0:S.message)||"Failed to share team")}finally{w(!1)}}},B=async(S,Z)=>{w(!0);try{await pi(s,S),C.success(`"${Z}" unshared`),await q(),r()}catch(te){C.error((te==null?void 0:te.message)||"Failed to unshare team")}finally{w(!1)}};return e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsxs(fi,{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(ia,{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."}),y&&e.jsxs(Re,{variant:"destructive",children:[e.jsx(Ae,{className:"h-4 w-4"}),e.jsx(Te,{children:y})]}),h?e.jsx("div",{className:"flex justify-center py-4",children:e.jsx(I,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[a.length>0&&e.jsx("div",{className:"space-y-2",children:a.map(S=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm flex-1 truncate",children:S.teamName}),e.jsxs(kt,{variant:"secondary",children:[S.members.length," member",S.members.length===1?"":"s"]}),e.jsx(v,{size:"icon",variant:"ghost",className:"h-8 w-8",disabled:k,onClick:()=>B(S.teamId,S.teamName),"aria-label":`Unshare ${S.teamName}`,children:e.jsx(sa,{className:"h-3.5 w-3.5"})})]},S.teamId))}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx("div",{className:"flex-1",children:e.jsx(ll,{value:x,onChange:m,options:A.map(S=>({value:S.id,label:S.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(v,{size:"sm",onClick:d,disabled:k||!x,children:[e.jsx(aa,{className:"h-4 w-4 mr-1"}),"Share"]})]})]})]})}function fo({nestId:s,nestName:r,onClose:a,onChanged:o,stewardshipEnabled:l=!1}){var f,g;const{adminStatus:u}=la(),x=((g=(f=u==null?void 0:u.me)==null?void 0:f.email)==null?void 0:g.toLowerCase())??"",[m,h]=n.useState(null);return e.jsx(wt,{open:!0,onOpenChange:a,children:e.jsxs(vt,{className:"sm:max-w-[560px]",children:[e.jsxs(jt,{children:[e.jsxs(yt,{className:"flex items-center gap-2",children:[e.jsx(ia,{className:"h-4 w-4"}),"Share nest: ",r]}),e.jsxs(Ks,{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:[m&&e.jsxs(Re,{variant:"destructive",children:[e.jsx(Ae,{className:"h-4 w-4"}),e.jsx(Te,{children:m})]}),e.jsx(ir,{nestId:s,onChanged:o,onError:h}),e.jsxs(bi,{defaultValue:"people",children:[e.jsxs(wi,{className:"grid grid-cols-2 w-full",children:[e.jsx(on,{value:"people",children:"People"}),e.jsx(on,{value:"teams",children:"Teams"})]}),e.jsx(cn,{value:"people",className:"mt-3 max-h-[52vh] overflow-y-auto pr-1",children:e.jsx(vl,{nestId:s,nestName:r,onChanged:o,currentUserEmail:x})}),e.jsx(cn,{value:"teams",className:"mt-3 max-h-[52vh] overflow-y-auto pr-1",children:e.jsx(xo,{nestId:s,onChanged:o})})]})]}),e.jsx(Nt,{children:e.jsx(v,{variant:"outline",onClick:a,children:"Done"})})]})})}function po(s,r,a){const o=s.slice(0,r),l=rr(o);if(!l||l.kind!=="mention")return null;const u=r-l.length,x=`@${a} `,m=s.slice(r),h=m.startsWith(" ")?m.slice(1):m;return{value:s.slice(0,u)+x+h,caret:u+x.length}}const An=/((?:```[\s\S]*?```)|(?:`[^`\n]*`))|(?:(^|\s)@(?:\(([^)]+)\)|([a-zA-Z0-9._@-]+)))/g;function go(s,r){const a=[],o=s||"",l=r.length>0;let u=0;const x=h=>{if(!h)return;const f=a[a.length-1];(f==null?void 0:f.kind)==="text"?f.text+=h:a.push({kind:"text",text:h})};An.lastIndex=0;let m;for(;(m=An.exec(o))!==null;){const[h,f,g,k,w]=m;if(f){x(o.slice(u,m.index+h.length)),u=m.index+h.length;continue}const y=(k||w||"").trim(),j=m.index+(g?g.length:0);x(o.slice(u,j)),a.push({kind:"mention",text:o.slice(j,m.index+h.length),name:y,resolved:!l||ol(r,y)}),u=m.index+h.length}return x(o.slice(u)),a}const Mn=n.forwardRef(function({value:r,onValueChange:a,members:o,className:l,onKeyDown:u,...x},m){var Z,te,fe;const h=n.useRef(null),[f,g]=n.useState(0),[k,w]=n.useState(!1),[y,j]=n.useState(0),q=N=>{h.current=N,typeof m=="function"?m(N):m&&(m.current=N)},P=n.useMemo(()=>{if(!k)return null;const N=rr(r.slice(0,f));return(N==null?void 0:N.kind)==="mention"?N:null},[k,r,f]),A=(fe=(te=(Z=la().adminStatus)==null?void 0:Z.me)==null?void 0:te.email)==null?void 0:fe.toLowerCase(),d=n.useMemo(()=>P?cl(o.filter(N=>N.email.toLowerCase()!==A),P.query):[],[P,o,A]);n.useEffect(()=>j(0),[P==null?void 0:P.query,d.length]);const B=N=>{const F=h.current,K=po(r,f,N);K&&(a(K.value),w(!1),requestAnimationFrame(()=>{F&&(F.focus(),F.setSelectionRange(K.caret,K.caret),g(K.caret))}))},S=!!P&&d.length>0;return e.jsxs("div",{className:"relative",children:[e.jsx("textarea",{...x,ref:q,value:r,className:l,onChange:N=>{a(N.target.value),g(N.target.selectionStart??N.target.value.length),w(!0)},onKeyUp:N=>g(N.target.selectionStart??0),onPaste:N=>{const F=N.currentTarget;requestAnimationFrame(()=>g(F.selectionStart??0))},onClick:N=>g(N.target.selectionStart??0),onBlur:()=>w(!1),onKeyDown:N=>{if(S){if(N.key==="ArrowDown"){N.preventDefault(),j(F=>(F+1)%d.length);return}if(N.key==="ArrowUp"){N.preventDefault(),j(F=>F<=0?d.length-1:F-1);return}if(N.key==="Enter"||N.key==="Tab"){N.preventDefault();const F=d[y]??d[0];F&&B(F.email);return}if(N.key==="Escape"){N.stopPropagation(),w(!1);return}}u==null||u(N)}}),S&&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((N,F)=>e.jsx("li",{children:e.jsxs("button",{type:"button",role:"option","aria-selected":F===y,onMouseDown:K=>{K.preventDefault(),B(N.email)},onMouseEnter:()=>j(F),className:ra("flex w-full flex-col items-start px-3 py-1.5 text-left text-sm",F===y?"bg-accent text-accent-foreground":""),children:[e.jsx("span",{className:"truncate font-medium",children:N.name||N.email.split("@")[0]}),e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:N.email})]})},N.email))})]})});function Fn({body:s,members:r,className:a}){const o=n.useMemo(()=>go(s,r),[s,r]);return e.jsx("div",{className:ra("whitespace-pre-wrap",a),children:o.map((l,u)=>l.kind==="text"?e.jsx("span",{children:l.text},u):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},u))})}function Us(s){return js(s)||s}function Pn(s,r=80){const a=s.replace(/\s+/g," ").trim();return a.length>r?a.slice(0,r)+"…":a}function bo({nestId:s,nodeId:r,readOnly:a,pendingAnchor:o,onClearAnchor:l,onFocusAnchor:u,onThreadsChange:x,activeThreadId:m,commentMode:h,onSetCommentMode:f}){const g=typeof f=="function",k=!g||!!h,[w,y]=n.useState(null),[j,q]=n.useState(""),[P,A]=n.useState(null),[d,B]=n.useState(""),[S,Z]=n.useState(!1),te=ks(),fe=n.useRef(null),{data:N}=vi({...ye.mentionable(s),enabled:!!s&&!a}),F=n.useMemo(()=>((N==null?void 0:N.people)??[]).filter(b=>!!b.email),[N]),K=n.useRef({}),pe=async()=>{try{const{threads:b}=await te.fetchQuery(ye.nodeAnnotations(s,r));y(b),x==null||x(b)}catch{y([]),x==null||x([])}};n.useEffect(()=>{y(null),pe()},[s,r]),n.useEffect(()=>{var b;o&&((b=fe.current)==null||b.focus())},[o]),n.useEffect(()=>{var b;m&&K.current[m]&&((b=K.current[m])==null||b.scrollIntoView({behavior:"smooth",block:"nearest"}))},[m]);const St=async()=>{const b=j.trim();if(b){Z(!0);try{await Kn(s,r,{body:b,anchor:o??null}),q(""),l==null||l(),await pe()}catch(O){C.error((O==null?void 0:O.message)||"Failed to add comment")}finally{Z(!1)}}},tt=async b=>{const O=d.trim();if(O){Z(!0);try{await Xn(s,r,b,O),B(""),A(null),await pe()}catch(se){C.error((se==null?void 0:se.message)||"Failed to reply")}finally{Z(!1)}}},ze=async b=>{Z(!0);try{b.status==="open"?await Yn(s,r,b.id):await Zn(s,r,b.id),await pe()}catch(O){C.error((O==null?void 0:O.message)||"Failed to update thread")}finally{Z(!1)}},ge=(w==null?void 0:w.length)??0,_e=w&&[...w].sort((b,O)=>O.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(ys,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("h3",{className:"text-sm font-semibold whitespace-nowrap",children:["Comments",w?` (${ge})`:""]}),!a&&g&&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(Jn,{checked:!!h,onCheckedChange:b=>f==null?void 0:f(b),"data-testid":"annotations-comment-mode"})]})]}),!a&&e.jsxs("div",{className:"mb-4 shrink-0",children:[k&&(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(wn,{className:"h-3 w-3 mt-0.5 shrink-0 text-amber-700"}),e.jsxs("span",{className:"flex-1 italic text-foreground/80",children:["“",Pn(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(et,{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(Mn,{ref:fe,members:F,value:k?j:"",onValueChange:q,readOnly:!k,onMouseDown:k?void 0:b=>{b.preventDefault(),f==null||f(!0)},onFocus:k?void 0:()=>f==null?void 0:f(!0),placeholder:k?o?"Comment on the highlighted text…":"Add a comment… use @ to tag someone":"Click here to start commenting…",title:k?void 0:"Click to turn on comment mode",rows:2,className:`w-full rounded-md border px-3 py-2 text-sm resize-y ${k?"border-input bg-background":"border-dashed border-input bg-muted/50 text-muted-foreground cursor-pointer"}`,"data-testid":"annotations-new"}),k&&e.jsx("div",{className:"flex justify-end mt-2",children:e.jsx(v,{size:"sm",onClick:St,disabled:S||!j.trim(),children:o?"Comment on selection":"Comment"})})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto -mr-2 pr-2",children:w===null?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-4",children:[e.jsx(I,{className:"h-4 w-4 animate-spin"})," Loading comments…"]}):ge===0?e.jsx("p",{className:"text-sm text-muted-foreground py-2",children:"No comments yet."}):e.jsx("ul",{className:"space-y-3",children:_e.map(b=>{var O;return e.jsxs("li",{ref:se=>{K.current[b.id]=se},className:`rounded-md border p-3 transition-shadow ${m===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})}),((O=b.anchor)==null?void 0:O.quote)&&e.jsxs("button",{type:"button",onClick:()=>u==null?void 0:u(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(wn,{className:"inline h-3 w-3 mr-1 text-amber-600 align-[-1px]"}),Pn(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})," ","· ",Us(b.comments[0].createdAt)]}),e.jsx(Fn,{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(se=>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:se.author})," ","replied · ",Us(se.createdAt)]}),e.jsx(Fn,{body:se.body,members:F})]},se.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(Pl,{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:[" · ",Us(b.resolvedAt)]})]})]}),!a&&(P===b.id?e.jsxs("div",{className:"mt-2",children:[e.jsx(Mn,{members:F,value:d,onValueChange:B,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(v,{variant:"ghost",size:"sm",onClick:()=>{A(null),B("")},children:"Cancel"}),e.jsx(v,{size:"sm",onClick:()=>tt(b.id),disabled:S||!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),B("")},children:[e.jsx(Ol,{className:"h-3 w-3"})," Reply"]}),b.status==="open"?e.jsxs("button",{type:"button",disabled:S,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:()=>ze(b),children:[e.jsx(Mt,{className:"h-3.5 w-3.5"})," Resolve"]}):e.jsxs("button",{type:"button",disabled:S,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:()=>ze(b),children:[e.jsx(oa,{className:"h-3 w-3"})," Reopen"]})]}))]},b.id)})})})]})}function wo(s){const r=document.createTreeWalker(s,NodeFilter.SHOW_TEXT),a=[];let o="",l;for(;l=r.nextNode();){const u=l;a.push({node:u,start:o.length}),o+=u.data}return{text:o,segs:a}}function On(s,r){if(!s.segs.length)return null;for(let a=s.segs.length-1;a>=0;a--){const o=s.segs[a];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 vo(s,r){const a=r.quote;if(!a)return null;const o=[];let l=s.text.indexOf(a);for(;l!==-1;)o.push(l),l=s.text.indexOf(a,l+1);if(!o.length)return null;let u=o[0];if(o.length>1&&r.before){const x=r.before.slice(-24),m=o.find(h=>s.text.slice(Math.max(0,h-x.length),h).endsWith(x));m!==void 0&&(u=m)}return{start:u,end:u+a.length}}function jo(s,r,a){const o=vo(r,a);if(!o)return null;const l=On(r,o.start),u=On(r,o.end);if(!l||!u)return null;try{const x=document.createRange();return x.setStart(l.node,l.offset),x.setEnd(u.node,u.offset),x}catch{return null}}function xr(){return typeof CSS<"u"&&"highlights"in CSS}function Vn(s,r){if(!xr())return;const a=window.Highlight;if(a){if(!r.length){CSS.highlights.delete(s);return}CSS.highlights.set(s,new a(...r))}}function qn(s){xr()&&CSS.highlights.delete(s)}function zn(s,r){const a=document;if(a.caretPositionFromPoint){const o=a.caretPositionFromPoint(s,r);return o?{node:o.offsetNode,offset:o.offset}:null}if(a.caretRangeFromPoint){const o=a.caretRangeFromPoint(s,r);return o?{node:o.startContainer,offset:o.startOffset}:null}return null}function _n(s){return s.replace(/^#/,"").toLowerCase()}const yo=2,No=1;function ko(s,r,a=5){const o=s.id.toLowerCase(),l=new Set((s.tags??[]).map(_n)),u=new Set(Js(s.content??"").map(m=>m.toLowerCase())),x=[];for(const m of r){if(m.id.toLowerCase()===o)continue;const h=[];for(const k of m.tags??[])l.has(_n(k))&&h.push(k);let f=0;for(const k of Js(m.content??""))u.has(k.toLowerCase())&&f++;const g=h.length*yo+f*No;g>0&&x.push({id:m.id,title:m.title,score:g,sharedTags:h})}return x.sort((m,h)=>h.score-m.score||m.title.localeCompare(h.title)).slice(0,a)}function Hn(s){const r=s.lastIndexOf("/");return r>=0?s.slice(r+1):s}function So(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Co(s){return(s??"").replace(/\[\[[^\]]*\]\]/g," ")}function Ro(s,r){const a=s.id.toLowerCase(),o=(s.title??"").trim();if(!o)return[];const l=o.toLowerCase(),u=Hn(s.id).toLowerCase(),x=new RegExp(`\\b${So(l)}\\b`),m=f=>Js(f).some(g=>{const k=g.toLowerCase();return k===a||k===l||Hn(g).toLowerCase()===u}),h=[];for(const f of r){if(f.id.toLowerCase()===a)continue;const g=f.content??"";m(g)||x.test(Co(g).toLowerCase())&&h.push({id:f.id,title:f.title})}return h}const To={"@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 * * * *"},$o=[{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}],Eo=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Lo=["","January","February","March","April","May","June","July","August","September","October","November","December"],Bn=s=>s.padStart(2,"0"),Ie=s=>/^\d+$/.test(s);function Do(s,r){for(const a of s.split(",")){const o=/^(\*|\d+(?:-\d+)?)(?:\/(\d+))?$/.exec(a);if(!o)return`"${a}" isn't a valid ${r.label} (use a number, a range like 1-5, \`*\`, or \`*/n\`)`;const[,l,u]=o;if(u!==void 0&&Number(u)<=0)return`the step in "${a}" must be greater than zero`;if(l!=="*"){const x=l.split("-").map(Number);for(const m of x)if(m<r.min||m>r.max)return`${r.label} must be between ${r.min} and ${r.max} (got ${m} in "${a}")`;if(x.length===2&&x[0]>x[1])return`the range "${a}" is backwards — ${x[0]} is after ${x[1]}`}}return null}function Ao(s){const[r,a,o,l,u]=s,x=o==="*"&&l==="*"&&u==="*";if(r==="*"&&a==="*"&&x)return"Runs every minute";if(Ie(r)&&Ie(a)){const m=`${Bn(a)}:${Bn(r)}`;if(x)return`Runs daily at ${m}`;if(o==="*"&&l==="*"&&Ie(u))return`Runs weekly on ${Eo[Number(u)%7]} at ${m}`;if(Ie(o)&&l==="*"&&u==="*")return`Runs monthly on day ${o} at ${m}`;if(Ie(o)&&Ie(l)&&u==="*")return`Runs yearly on ${Lo[Number(l)]} ${o} at ${m}`}return r.startsWith("*/")&&a==="*"&&x?`Runs every ${r.slice(2)} minutes`:Ie(r)&&a==="*"&&x?r==="0"?"Runs hourly, on the hour":`Runs hourly at minute ${r}`:Ie(r)&&a.startsWith("*/")&&x?`Runs at minute ${r} past every ${a.slice(2)} hours`:"Runs on a custom schedule (minute hour day-of-month month day-of-week)"}function Mo(s){const a=(To[s.toLowerCase()]??s).trim().split(/\s+/);if(a.length!==5)return{kind:"invalid",error:`A cron schedule needs 5 space-separated fields (minute hour day month weekday) — got ${a.length}`};for(let o=0;o<5;o++){const l=Do(a[o],$o[o]);if(l)return{kind:"invalid",error:l}}return{kind:"valid",description:Ao(a)}}const Fo={s:1,m:60,h:3600,d:86400};function Po(s){const r=s.slice(6).trim(),a=/(\d+)(s|m|h|d)/gi;let o,l=0,u=0;for(;o=a.exec(r);)l+=Number(o[1])*Fo[o[2].toLowerCase()],u+=o[0].length;if(u===0||u!==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=[],m=Math.floor(l/86400),h=Math.floor(l%86400/3600),f=Math.floor(l%3600/60),g=l%60;return m&&x.push(`${m} day${m===1?"":"s"}`),h&&x.push(`${h} hour${h===1?"":"s"}`),f&&x.push(`${f} minute${f===1?"":"s"}`),g&&x.push(`${g} second${g===1?"":"s"}`),{kind:"valid",description:`Runs every ${x.join(" ")}`}}function Oo(s){const r=s.trim();return r?r.toLowerCase().startsWith("@every")?Po(r):Mo(r):{kind:"empty"}}function bs(s){return s?/^\s*</.test(s):!1}function Wn(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 Un(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 bc({nestId:s,nestName:r,nodeId:a,initialFolder:o,initialThreadId:l,isOwner:u=!1,onBack:x,onSaved:m,onNavigateDocument:h,onTagClick:f,onOpenNest:g,onOpenFolder:k,onCreateDocument:w,initialTitle:y,breadcrumb:j,onJumpBreadcrumb:q,sidebarCollapsed:P=!1,onToggleSidebar:A}){var Ka,Xa,Ya,Za,Ja,Ia,en,tn,sn,an,nn,rn;const d=a==="new",B=dl(),{adminStatus:S,isAdmin:Z,workflowPlaneEnabled:te,typeArtifactEnabled:fe,typeTableEnabled:N}=la(),F=((Xa=(Ka=S==null?void 0:S.me)==null?void 0:Ka.email)==null?void 0:Xa.toLowerCase())??"",K=u||Z,[pe,St]=n.useState(!1),[tt,ze]=n.useState(!1),[ge,_e]=n.useState(!1),b=ks(),O=ji(s),se=yi(s),He=Ni(s,d?void 0:a),Be=n.useMemo(()=>{var t;return(((t=He.data)==null?void 0:t.stewards)??[]).filter(i=>(i.email||"").toLowerCase()===F).map(i=>String(i.role))},[He.data,F]),Ft=d||!He.isLoading,[le,Ct]=n.useState(null),We=le==="write",st=((Ya=O.data)==null?void 0:Ya.myStewards)??[],[R,at]=n.useState(d&&y?y:"");ki([{label:d?"New document":R.trim()||"Untitled"}]);const[z,Me]=n.useState(o??""),[T,Ne]=n.useState(""),[_,$e]=n.useState([]),[ne,nt]=n.useState(""),[oe,Pt]=n.useState(null),Ee=n.useRef(null),ue=((Za=se.data)==null?void 0:Za.prime_tags)??[],[ce,Le]=n.useState(null),[X,Ue]=n.useState(null),[Jt,Ot]=n.useState(!1),[J,Vt]=n.useState(null),[rt,Qe]=n.useState(!1),[ke,Rt]=n.useState(""),[Fe,it]=n.useState(void 0),[U,Ss]=n.useState(null),[Ge,Cs]=n.useState(null),[Ke,It]=n.useState(null),[Xe,Rs]=n.useState([]),[es,be]=n.useState(null),[qt,ts]=n.useState(null),Tt=!!((Ja=se.data)!=null&&Ja.stewardship_enabled),zt=!!((Ia=se.data)!=null&&Ia.allow_self_approve),lt=((en=O.data)==null?void 0:en.permission)??null,Se=Si((tn=O.data)==null?void 0:tn.nest),{hasAdminApprove:ot,isViewOnly:re,isReviewerOnly:Q,canEditContent:c}=ao({isNew:d,isOwner:u,isAdmin:Z,permission:lt,nestStewards:st,nodeRoles:Be,grant:le,isArchived:Se}),L=!!Ge&&!!((sn=S==null?void 0:S.me)!=null&&sn.email)&&Ge.toLowerCase()===S.me.email.toLowerCase(),$=!Se&&(u||Z||lt==="owner"||lt==="admin"||L),ie=!Se&&($||lt==="write"||We||Be.includes("editor")||st.some(t=>t.role==="editor"&&t.scope==="nest")),[$t,ct]=n.useState(!1),[fr,da]=n.useState(!1),[me,Ts]=n.useState(null),$s=(me==null?void 0:me.status)==="pending",[pr,ua]=n.useState(!1),[W,dt]=n.useState(d?"edit":"view"),[Es,ma]=n.useState(!1),[we,ha]=n.useState("document"),[ss,as]=n.useState(null),ut=d&&we==="artifact",ns=t=>t==="artifact"?"html":t==="table"?"csv":t==="tool"?"code":"markdown",gr=(t,i)=>{if(t!==we&&T.trim()&&ns(t)!==ns(we)){as({value:t,label:i});return}ha(t)},De=d?we:ce??"document",Ls=De==="tool"||De==="table",_t=d?we==="agent"||we==="skill":ce==="agent"||ce==="skill",xa=`${typeof window<"u"?window.location.origin:""}/nests/${s}/runnables`,[br,fa]=n.useState(!1),wr=async()=>{await pn(xa)&&(fa(!0),setTimeout(()=>fa(!1),1500))},[he,Ht]=n.useState(!1),[Ds,As]=n.useState(null),[Bt,Pe]=n.useState(null),pa=n.useRef(null),Wt=n.useRef(null),ga=n.useRef(null),[mt,vr]=n.useState([]),[Ut,Et]=n.useState(null),[Oe,ba]=n.useState(()=>Ci(localStorage).commentsOpen),jr=t=>{ba(t),_i(localStorage,{commentsOpen:t})},wa=n.useMemo(()=>W==="view"&&!bs(T)?ul(T):[],[W,T]),Ms=!d&&wa.length>=3,rs=n.useRef(!1);n.useEffect(()=>{ba(t=>Ri(t,{initialThreadId:rs.current?null:l,commentMode:he,pendingAnchor:!!Ds,activeThreadId:Ut}))},[l,he,Ds,Ut]);const va=mt.filter(t=>t.status==="open").length,Ye=n.useRef([]),Qt=n.useRef(null);n.useEffect(()=>{var i;if(!l||rs.current)return;const t=mt.find(p=>p.id===l);t&&(rs.current=!0,Ht(!0),dt("view"),Et(t.id),(i=t.anchor)!=null&&i.quote&&(Qt.current=t.id))},[mt,l]);const yr=n.useCallback(()=>{const t=window.getSelection();if(!t||t.isCollapsed||t.rangeCount===0){Pe(null);return}const i=t.getRangeAt(0),p=Wt.current;if(!p||!p.contains(i.commonAncestorContainer)){Pe(null);return}if(!t.toString().trim()){Pe(null);return}const E=(ri,ii)=>{const Hs=document.createRange();return Hs.setStart(p,0),Hs.setEnd(ri,ii),Hs.toString().length},D=document.createRange();D.selectNodeContents(p);const H=D.toString();let V=E(i.startContainer,i.startOffset),M=E(i.endContainer,i.endOffset);for(V>M&&([V,M]=[M,V]);V<M&&/\s/.test(H[V]);)V++;for(;M>V&&/\s/.test(H[M-1]);)M--;const G=H.slice(V,M);if(!G){Pe(null);return}const gs=H.slice(Math.max(0,V-250),V),ai=H.slice(M,M+250),ln=T.indexOf(G),ni=ln>=0?T.slice(0,ln).split(`
36
+ `).length:void 0;pa.current={quote:G,before:gs,after:ai,line:ni};const _s=i.getBoundingClientRect();Pe({x:_s.left+_s.width/2,y:_s.top})},[T]),Nr=n.useCallback(()=>{var i;const t=pa.current;t&&(As(t),Pe(null),(i=window.getSelection())==null||i.removeAllRanges())},[]);n.useEffect(()=>{const t=Wt.current,i=!d&&(he||W==="view")&&!Es&&J==null&&!bs(T);if(!t||!i){Ye.current=[],qn("comment-anchor"),qn("comment-anchor-active");return}const p=requestAnimationFrame(()=>{var H,V;const E=wo(t),D=[];for(const M of mt){if(!((H=M.anchor)!=null&&H.quote))continue;const G=jo(t,E,M.anchor);G&&D.push({id:M.id,range:G})}if(Ye.current=D,Vn("comment-anchor",D.map(M=>M.range)),Qt.current){const M=D.find(G=>G.id===Qt.current);M&&((V=M.range.startContainer.parentElement)==null||V.scrollIntoView({behavior:"smooth",block:"center"}),Et(M.id)),Qt.current=null}});return()=>cancelAnimationFrame(p)},[mt,T,W,Es,J,d,he]),n.useEffect(()=>{const t=Ye.current.find(i=>i.id===Ut);Vn("comment-anchor-active",t?[t.range]:[])},[Ut]);const kr=n.useCallback(t=>{var D,H;const i=mt.find(V=>{var M,G;return((M=V.anchor)==null?void 0:M.quote)===t.quote&&((G=V.anchor)==null?void 0:G.before)===t.before});i&&Et(i.id);const p=(D=Ye.current.find(V=>V.id===(i==null?void 0:i.id)))==null?void 0:D.range;if(p){(H=p.startContainer.parentElement)==null||H.scrollIntoView({behavior:"smooth",block:"center"});return}if(!(he||W==="view")&&!bs(T)){Qt.current=(i==null?void 0:i.id)??null,Ht(!0),dt("view");return}C.message("That highlighted text isn't in the current version.")},[mt,he,W,T]),Sr=n.useCallback(t=>{if(!Ye.current.length)return;const i=zn(t.clientX,t.clientY);if(i)for(const{id:p,range:E}of Ye.current)try{if(E.isPointInRange(i.node,i.offset)){Et(p);return}}catch{}},[]),Cr=n.useCallback(t=>{const i=Wt.current;if(!i)return;if(!Ye.current.length){i.style.cursor="";return}const p=zn(t.clientX,t.clientY);let E=!1;if(p)for(const{range:D}of Ye.current)try{if(D.isPointInRange(p.node,p.offset)){E=!0;break}}catch{}i.style.cursor=E?"pointer":""},[]);n.useEffect(()=>{if(!Bt)return;const t=i=>{var E;const p=i.target;p.closest('[data-testid="selection-comment-button"]')||(E=Wt.current)!=null&&E.contains(p)||Pe(null)};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[Bt]);const is=n.useRef(null),ja=n.useRef(null);n.useEffect(()=>{var t;d&&((t=ja.current)==null||t.focus())},[]);const ls=n.useRef({title:d&&y?y:"",content:"",tags:[],schedule:""}),Fs=n.useRef(""),[ve,ya]=n.useState(!d),[xe,Rr]=n.useState([]),[Na,Tr]=n.useState([]);n.useEffect(()=>{if(ve)return;let t=!1;return(async()=>{try{const{census:i}=await b.fetchQuery(ye.census(s));t||Tr(i.folders.map(p=>p.path))}catch{}})(),()=>{t=!0}},[ve,s,b]),n.useEffect(()=>{if(ve)return;let t=!1;return(async()=>{try{const{nodes:i}=await b.fetchQuery(ye.nodes(s));t||Rr(i)}catch{}})(),()=>{t=!0}},[d,ve,s]);const ka=n.useMemo(()=>{const t=new Set(Na);for(const i of xe){const E=(i.id.startsWith("nodes/")?i.id.slice(6):i.id).split("/").slice(0,-1);for(let D=1;D<=E.length;D++)t.add(E.slice(0,D).join("/"))}return[...t].sort()},[xe,Na]),$r=n.useMemo(()=>{if(d||!a)return[];const i=(a.startsWith("nodes/")?a.slice(6):a).split("/").slice(0,-1);return i.map((p,E)=>({path:i.slice(0,E+1).join("/"),label:Xs(p)}))},[d,a]),[Ve,Gt]=n.useState(null),[Ze,os]=n.useState(null),[cs,Sa]=n.useState(!1),ds=n.useMemo(()=>[{value:"document",label:"Document",Icon:Qs,expects:"Markdown prose."},...fe?[{value:"artifact",label:"Artifact",Icon:Zt,expects:"An HTML page — the body is hosted and rendered as-is."}]:[],...N?[{value:"table",label:"Table",Icon:Ys,expects:"CSV — one header row, then data rows."}]:[],...te?[{value:"agent",label:"Agent",Icon:dn,expects:"Markdown instructions an orchestrator runs; can carry a schedule."},{value:"skill",label:"Skill",Icon:Nn,expects:"Markdown instructions with a trigger (defaulted from the title)."},{value:"tool",label:"Tool",Icon:vn,expects:"Source code, shown and edited as code."}]:[]].filter(i=>i.value!==(ce??"document")),[fe,N,te,ce]),Er=async()=>{var t;if(!(!Ze||d)){Sa(!0);try{await vs(s,a,{type:Ze}),hn(b,`/nests/${s}/nodes/${a}`),C.success(`Turned into ${((t=ds.find(i=>i.value===Ze))==null?void 0:t.label)??Ze}`),os(null),await de()}catch(i){C.error(i instanceof Error?i.message:"Failed to convert")}finally{Sa(!1)}}},[us,Ca]=n.useState(!1),Ra=n.useMemo(()=>d||!a?"":(a.startsWith("nodes/")?a.slice(6):a).split("/").slice(0,-1).join("/"),[d,a]),ms=n.useMemo(()=>d?[]:Sl(xe,{id:a,title:R}),[d,xe,a,R]),Ta=n.useMemo(()=>d?[]:ko({id:a,tags:_,content:T},xe),[d,xe,a,R,_,T]),hs=n.useMemo(()=>d?[]:Ro({id:a,title:R},xe),[d,xe,a,R]),Lt=n.useMemo(()=>d?[]:Cl(T,xe),[d,T,xe]),Lr=n.useCallback(t=>{const i=jn(xe,t);return i?{title:i.title,snippet:ml(i.content??"")}:null},[xe]),[qe,$a]=n.useState(!1),[Kt,Xt]=n.useState(null),[Dr,Ea]=n.useState(!1),[Dt,Y]=n.useState(!1),[Ps,La]=n.useState(!1),[Ar,Mr]=n.useState(!1),[Da,xs]=n.useState(null),de=n.useCallback(async()=>{if(!d){ya(!0),Ea(!1);try{const{node:t}=await b.fetchQuery(ye.node(s,a)),i=(t==null?void 0:t.title)==null?"":String(t.title),p=(t==null?void 0:t.content)==null?"":String(t.content),E=Array.isArray(t==null?void 0:t.tags)?Tn([],t.tags.map(M=>na(String(M)))):[];at(i),Ne(p),$e(E),Le((t==null?void 0:t.type)??null);const D=(t==null?void 0:t.schedule)==null?"":String(t.schedule);nt(D);const H=typeof(t==null?void 0:t.prime)=="boolean"?t.prime:null;Pt(H),Ee.current=H,it(t==null?void 0:t.version),Ss((t==null?void 0:t.status)??null),Cs((t==null?void 0:t.author)??null),It((t==null?void 0:t.updated_at)??null),Rs(Array.isArray(t==null?void 0:t.collaborators)?t.collaborators.map(M=>String(M)):[]),be((t==null?void 0:t.pendingChange)??null),ts((t==null?void 0:t.pendingReviewBy)??null),Ts((t==null?void 0:t.deletionRequest)??null),Ct((t==null?void 0:t.myGrant)??null),ls.current={title:i,content:p,tags:E,schedule:D},Fs.current=i,Y(!1);const V=Ti(s,a);xs(null),V&&(V.baseVersion!==(t==null?void 0:t.version)?Bs(s,a):(at(V.title),Ne(V.content),$e(V.tags),nt(V.schedule),Y(!0),xs(V.savedAt??Date.now())))}catch(t){Xt(t.message),Ea(!0)}finally{ya(!1)}}},[d,s,a]),Je=n.useCallback(async()=>{if(d){Ue(null);return}try{Ue(await b.fetchQuery(ye.nodeVersions(s,a)))}catch(t){console.error("[DocumentEditor] getNodeVersions failed",s,a,t),Ue(null),C.error((t==null?void 0:t.message)||"Failed to load version history")}},[d,s,a]);n.useEffect(()=>{d||de()},[d,de]);const Fr=n.useCallback(async()=>{Ot(!0),await Je()},[Je]),[Aa,Ma]=n.useState(!1),[Pr,Os]=n.useState(!1),Or=n.useCallback(async()=>{Os(!1),Ma(!0);try{const t=await un(s,a);if(t.deleted){C.success("Never approved — document deleted"),x();return}C.success(`Draft discarded — back to version ${t.version}`),await Promise.all([de(),Je()])}catch(t){C.error((t==null?void 0:t.message)||"Discard failed")}finally{Ma(!1)}},[s,a,R,x,de,Je]),Vr=n.useCallback(async()=>{X||await Je()},[X,Je]),[Vs,Fa]=n.useState(null),qs=n.useCallback(async t=>{if(Vt(t),Qe(!1),Fa(null),t!=null)try{const{content:i}=await Gs(s,a,t);Fa({version:t,content:i??""})}catch(i){C.error((i==null?void 0:i.message)||`Failed to load version ${t}`),Vt(null)}},[s,a]),zs=U==="pending_review"&&!!qt&&!!F&&qt.toLowerCase()===F,je=U==="pending_review"&&!zs,Pa=!d&&!je&&ds.length>0,ht=d?we:ce??"document",ae=je||W!=="edit",qr=n.useMemo(()=>R.trim().length>0&&T.trim().length>0&&!qe,[R,T,qe]),ee=n.useMemo(()=>{if(!Dt)return!1;const t=ls.current;if(R.trim()!==t.title.trim()||Un(T)!==Un(t.content)||_.length!==t.tags.length)return!0;for(let i=0;i<_.length;i++)if(_[i]!==t.tags[i])return!0;return ne.trim()!==t.schedule.trim()||oe!==Ee.current},[Dt,R,T,_,ne,oe]),Oa=qr&&(d||ee),fs=n.useRef(!1),xt=n.useRef(0);n.useEffect(()=>{if(!ee||Q)return;const t=i=>{fs.current||i.preventDefault()};return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[ee,Q]),n.useEffect(()=>(mn(t=>!ee||Q?!1:(gt({label:"leave this document",run:t}),!0)),()=>mn(null)),[ee,Q]),n.useEffect(()=>{if(!ee||Q)return;fs.current=!1,xt.current=0;const t=()=>{window.history.pushState({cnLeaveGuard:!0},""),xt.current++};t();const i=()=>{xt.current=Math.max(0,xt.current-1),t(),gt(p=>p??{label:"leave this page",run:()=>{fs.current=!0,window.history.go(-(xt.current+1))}})};return window.addEventListener("popstate",i),()=>{var p;window.removeEventListener("popstate",i),!fs.current&&xt.current>0&&((p=window.history.state)!=null&&p.cnLeaveGuard)&&window.history.go(-xt.current)}},[ee,Q]);const ft=n.useMemo(()=>Oo(ne),[ne]),[Va,zr]=n.useState("");n.useEffect(()=>{if(!ut)return;const t=setTimeout(()=>zr(T),400);return()=>clearTimeout(t)},[T,ut]);const _r=n.useDeferredValue(T),At=n.useMemo(()=>{const t=ke.split(/[\s,]+/).map(mr),i=t.map(p=>p.tag).filter(p=>!!p);return{tags:Tn(_,i),notes:t.map(p=>p.note).filter(Boolean)}},[ke,_]),qa=n.useCallback(()=>{const{tags:t,notes:i}=At;if(i.length===1?C.warning(i[0]):i.length>1&&C.warning(`${i.length} tags normalized`,{description:i.join(" "),duration:8e3}),t.length===0){Rt("");return}$e([..._,...t]),Rt(""),Y(!0),C.success(t.length===1?`Tag "${t[0]}" added`:`${t.length} tags added`,{id:"tag-added",description:"Save the document to keep it."})},[At,_]),Hr=t=>{$e(_.filter(i=>i!==t)),Y(!0)},Br=async()=>{var E,D,H,V;if(!d&&!ee)return Y(!1),C.message("Not saved — no changes were made. Edit the document, then save again."),{ok:!0,savedId:a,noop:!0};const t={title:R.trim(),content:T,tags:_};let i,p;if(d){const M=await Gi(s,{...t,type:we,...z.trim()?{folder:z.trim()}:{},..._t?{schedule:ne.trim()}:{},...oe===null?{}:{prime:oe}});i=(E=M==null?void 0:M.node)==null?void 0:E.id,p=(D=M==null?void 0:M.node)==null?void 0:D.status}else{const M=oe===Ee.current?{}:{prime:oe},G=await vs(s,a,_t?{...t,...M,schedule:ne.trim()}:{...t,...M},Fe);Ee.current=oe;const gs=(G==null?void 0:G.version)??((H=G==null?void 0:G.node)==null?void 0:H.version);typeof gs=="number"&&it(gs),It(((V=G==null?void 0:G.node)==null?void 0:V.updated_at)??new Date().toISOString()),i=a}return ls.current={title:t.title,content:T,tags:[..._],schedule:ne.trim()},d||Bs(s,a),Y(!1),xs(null),{ok:!0,savedId:i,...d?{createdStatus:p}:{}}},[pt,gt]=n.useState(null),za=async t=>{if(!Oa){Xt(d?"Add a title and content before saving.":"Current document can't be saved — fix errors before leaving.");return}$a(!0),Xt(null);try{const{savedId:i,noop:p,createdStatus:E}=await Br();p||La(!0),d&&i&&C.success(E==="published"?`"${R.trim()||"Untitled"}" published — it's now live and available for use.`:`"${R.trim()||"Untitled"}" saved as a draft.`),gn(()=>t(i??""))}catch(i){Xt(i.message)}finally{$a(!1)}},_a=()=>za(t=>m==null?void 0:m(t));n.useEffect(()=>{ee&&La(!1)},[ee]);const Ha=n.useRef(()=>{});Ha.current=()=>{if(d||je||Q||re||!ee)return;const t=$i(s,a,{title:R,content:T,tags:[..._],schedule:ne.trim(),baseVersion:Fe});Mr(!t)};const bt=n.useCallback(()=>{Ha.current()},[]),Ce=(t,i)=>{if(!ee||Q){i();return}gt({label:t,run:i})},Wr=()=>za(()=>{const t=pt==null?void 0:pt.run;gt(null),t==null||t()}),Ba=()=>{d||Bs(s,a);const t=ls.current;at(t.title),Ne(t.content),$e([...t.tags]),nt(t.schedule),Y(!1),xs(null)},Ur=()=>{if(!pt)return;const t=pt.run;Ba(),gt(null),gn(t)},Qr=async(t,i)=>{d||(await Wi(s,a,t,i),ct(!1),await de())},Gr=async t=>{d||(await zi(s,a,t),await de())},Kr=async t=>{d||(await qi(s,a,t),await de())},Xr=async()=>{if(!d)try{await Hi(s,a),C.success("Submission withdrawn — back to Draft"),await de()}catch(t){console.error("[DocumentEditor] cancelReview failed",s,a,t),C.error((t==null?void 0:t.message)||"Failed to withdraw submission")}},Yr=async t=>{if(d)return;const{request:i}=await Qi(s,a,t);Ts(i),C.success("Deletion requested — a nest admin will review it")},Zr=async()=>{d||(await Ui(s,a),C.success(`Deleted "${R||a}"`),x())},Jr=Be.includes("reviewer"),Ir=zs,ps=ue.length>0&&_.some(t=>ue.includes(t.trim().replace(/^#+/,"").toLowerCase())),Wa=oe===null?ps:oe,ei=u||ot,ti=!d&&U==="pending_review"&&(ot||Jr||u&&zt)&&(!Ir||u&&zt),Ua=n.useRef(!1);n.useEffect(()=>{Ua.current||ve||!Ft||(Ua.current=!0,U==="pending_review"&&Q&&Ht(!0))},[ve,Ft,U,Q]),n.useEffect(()=>{ve||W==="edit"||he||!re&&!je&&!Q&&dt("edit")},[ve,re,je,Q,W,he]),n.useEffect(()=>{je&&W==="edit"&&dt("view")},[je,W]);const Qa=!d&&Tt&&U==="draft"&&!Q,si=t=>{var i;(i=is.current)==null||i.insertWikiLink(t.id,t.title)},Ga=async(t,i)=>{if(i){Ce(`open "${t}"`,()=>h==null?void 0:h(s,i,R));return}try{const{nodes:p}=await b.fetchQuery(ye.nodes(s)),D=jn(p,t);if(D){Ce(`open "${D.title}"`,()=>h==null?void 0:h(s,D.id,R));return}if(Q||re){Xt(`"${t}" doesn't exist in this nest. You only have view access — ask someone with edit rights to add it.`);return}Ce(`create "${t}"`,()=>w==null?void 0:w(s,t))}catch{}};return!d&&!ve&&Dr?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(dr,{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:Kt??`Nothing lives at ${a} 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(v,{variant:"outline",onClick:()=>void de(),children:[e.jsx(ea,{className:"h-4 w-4 mr-2"}),"Try again"]}),e.jsxs(v,{onClick:x,children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Back to documents"]})]})]})}):!d&&!ve&&ce===co?e.jsx(mo,{nestId:s,nodeId:a,title:R,snapshotVersion:null,currentEmail:F,viewOnly:re,reviewerOnly:Q,initialThreadId:l,onBack:x,onTurnedInto:()=>{hn(b,`/nests/${s}/nodes/${a}`),de()}}):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:[P&&A&&e.jsx(v,{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(Ei,{className:"h-4 w-4"})}),e.jsx(v,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>Ce("go back",x),title:"Back to documents","data-testid":"document-editor-back",children:e.jsx(Is,{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:()=>g&&Ce("go to the nest",g),disabled:!g,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:g?`Open ${r}`:r,children:r}),j==null?void 0:j.map((t,i)=>e.jsxs(n.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground shrink-0",children:"›"}),e.jsx("button",{type:"button",onClick:()=>Ce(`go to "${t.title}"`,()=>q==null?void 0:q(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}`)),$r.map((t,i)=>e.jsxs(n.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground shrink-0",children:"›"}),e.jsx("button",{type:"button",onClick:()=>k&&Ce(`open "${t.label}"`,()=>k(t.path)),disabled:!k,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&&U&&e.jsx(Vo,{status:U}),!d&&$s&&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(sa,{className:"h-3 w-3"}),"Deletion requested"]}),!d&&!Tt&&U==="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(ee)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(xn,{className:"h-3 w-3"}),"Unsaved changes"]});const t=qe?"Saving…":Ps?"Saved":Ke?`Edited ${bn(Ke)}`:null;return t?e.jsx("span",{className:"hidden sm:inline px-1.5 text-xs text-muted-foreground",title:Ke?js(Ke):void 0,children:t}):null})(),ti&&e.jsx(Fl,{documentTitle:R,version:Fe??1,onApprove:Gr,onReject:Kr}),!d&&(K&&!Se?e.jsx(ir,{nestId:s,variant:"compact",onChanged:()=>void b.invalidateQueries({queryKey:Li.nest(s)}),onError:t=>{t&&C.error(t)}}):((nn=(an=O.data)==null?void 0:an.nest)==null?void 0:nn.visibility)&&e.jsxs("span",{className:"hidden sm:inline-flex items-center gap-1 px-1.5 text-xs text-muted-foreground",title:O.data.nest.visibility==="public"?"Public — anyone with the URL can read":O.data.nest.visibility==="org"?"Organization — everyone signed in here can read":"Private","data-testid":"document-editor-visibility",children:[O.data.nest.visibility==="public"?e.jsx(Di,{className:"h-3.5 w-3.5"}):O.data.nest.visibility==="org"?e.jsx(Ai,{className:"h-3.5 w-3.5"}):e.jsx(Mi,{className:"h-3.5 w-3.5"}),O.data.nest.visibility==="public"?"Public":O.data.nest.visibility==="org"?"Organization":"Private"]})),K&&!Se&&e.jsxs(v,{variant:"ghost",size:"sm",className:"h-8",onClick:()=>St(!0),title:"Share this nest — people, teams, visibility","data-testid":"document-editor-share",children:[e.jsx(ia,{className:"h-4 w-4 sm:mr-1.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Share"})]}),!d&&e.jsxs(v,{variant:Oe?"secondary":"ghost",size:"sm",className:"h-8","aria-pressed":Oe,onClick:()=>{Oe&&(rs.current=!0,Ht(!1),Et(null),As(null),Pe(null)),jr(!Oe)},title:Oe?"Hide comments":"Show comments","data-testid":"document-editor-comments-toggle",children:[e.jsx(ys,{className:"h-4 w-4"}),va>0&&e.jsx("span",{className:"ml-1 text-xs tabular-nums",children:va})]}),!d&&e.jsxs(In,{onOpenChange:t=>{t&&Vr()},children:[e.jsx(er,{asChild:!0,children:e.jsxs(v,{variant:J!=null?"secondary":"ghost",size:"sm",className:"h-8",title:"Compare with a past version","data-testid":"document-editor-compare",children:[e.jsx(Sn,{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(tr,{className:"h-3.5 w-3.5 ml-0.5 opacity-60"})]})}),e.jsxs(sr,{align:"end",className:"w-56 max-h-80 overflow-y-auto",children:[e.jsx(ar,{children:"Diff current against…"}),J!=null&&e.jsxs(e.Fragment,{children:[e.jsxs(Yt,{onClick:()=>void qs(null),children:[e.jsx(et,{className:"h-4 w-4 mr-2"})," Exit compare"]}),e.jsx(nr,{})]}),X?X.versions.filter(t=>t.version!==X.currentVersion).length===0?e.jsx(Yt,{disabled:!0,children:"No earlier versions"}):X.versions.filter(t=>t.version!==X.currentVersion).map(t=>{var i;return e.jsxs(Yt,{onClick:()=>void qs(t.version),children:[J===t.version?e.jsx(Mt,{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?js(t.editedAt):void 0,children:[(i=t.editedBy)==null?void 0:i.split("@")[0],bn(t.editedAt)].filter(Boolean).join(" · ")})]},t.version)}):e.jsxs(Yt,{disabled:!0,children:[e.jsx(I,{className:"h-4 w-4 mr-2 animate-spin"})," Loading…"]})]})]}),(()=>{var E;const t=[];d||t.push({label:"Version history",icon:or,testId:"document-editor-history",onSelect:Fr}),d||t.push({label:"Copy link",icon:wl,separatorBefore:!0,testId:"document-editor-copy-link",onSelect:()=>{const D=`${window.location.origin}${Xi(s)}?doc=${encodeURIComponent(a)}`;pn(D,"Link copied — recipient needs access to this nest")}}),!d&&c&&!je&&t.push({label:"Move to folder",icon:kn,testId:"document-editor-move",onSelect:()=>Gt(Ra)}),K&&!d&&!Se&&t.push({label:"Share this document",icon:aa,separatorBefore:!0,testId:"document-editor-share-doc",onSelect:()=>_e(!0)}),K&&!d&&!Se&&t.push({label:"Publish",icon:aa,testId:"document-editor-publish",onSelect:()=>ze(!0)});const i=!d&&ie&&($||!$s);i&&t.push({label:"Delete",icon:sa,separatorBefore:!0,destructive:$,testId:$?"document-editor-delete":"document-editor-request-deletion",onSelect:()=>da(!0)});const p=$s&&((E=me==null?void 0:me.requestedBy)==null?void 0:E.toLowerCase())===F;return!d&&p&&t.push({label:"Withdraw deletion request",icon:et,separatorBefore:!i,testId:"document-editor-withdraw-deletion",onSelect:async()=>{try{await Ki(s,me.id),Ts(null),C.success("Deletion request withdrawn")}catch(D){C.error(D instanceof Error?D.message:"Failed to withdraw request")}}}),t.length?e.jsx(hl,{actions:t,variant:"ghost",testId:"document-editor-more"}):null})(),W!=="edit"&&e.jsxs(e.Fragment,{children:[!re&&Qa&&e.jsxs(v,{variant:"outline",size:"sm",className:"h-8",onClick:()=>ct(!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(ta,{className:"h-4 w-4 sm:mr-1.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Submit for review"})]}),!re&&!Q&&!je&&e.jsxs(v,{size:"sm",className:"h-8",onClick:()=>dt("edit"),"data-testid":"document-editor-start-edit",children:[e.jsx(xn,{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:[Kt&&e.jsxs(Re,{variant:"destructive",className:"mb-4",children:[e.jsx(Ae,{className:"h-4 w-4"}),e.jsx(Te,{children:Kt})]}),Da!==null&&e.jsxs(Re,{className:"mb-4 border-amber-300 bg-amber-50 text-amber-800",children:[e.jsx(Ae,{className:"h-4 w-4 text-amber-600"}),e.jsxs(Te,{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(Da).toLocaleString(),") ","were restored — the saved document still says something else."]}),e.jsx("button",{type:"button",onClick:Ba,className:"font-medium underline underline-offset-2 hover:no-underline","data-testid":"discard-restored-draft",children:"Discard them"})]})]}),Ar&&ee&&e.jsxs(Re,{className:"mb-4 border-amber-300 bg-amber-50 text-amber-800",children:[e.jsx(Ae,{className:"h-4 w-4 text-amber-600"}),e.jsx(Te,{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."})]}),ve?e.jsxs("div",{className:"flex items-center justify-center py-20 text-muted-foreground",children:[e.jsx(I,{className:"h-5 w-5 animate-spin mr-2"}),"Loading document..."]}):e.jsxs("div",{className:"space-y-4",children:[!d&&es&&e.jsx(Jl,{nestId:s,nodeId:a,pending:es,onResolved:()=>{be(null),de()}}),je&&e.jsxs(Re,{children:[e.jsx(Ae,{className:"h-4 w-4"}),e.jsx(Te,{children:"This document is locked while it awaits steward review. Editing is disabled until the review is approved or rejected."})]}),zs&&e.jsxs(Re,{children:[e.jsx(Ae,{className:"h-4 w-4"}),e.jsxs(Te,{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(v,{size:"sm",variant:"outline",className:"shrink-0",onClick:()=>void Xr(),"data-testid":"document-editor-withdraw",title:"Withdraw this submission and return the document to Draft",children:[e.jsx(Rn,{className:"h-3.5 w-3.5 mr-1.5"}),"Withdraw"]})]})]}),e.jsxs("div",{children:[W==="view"&&!d?e.jsx("h1",{className:"text-4xl font-bold leading-tight tracking-tight text-foreground","data-testid":"document-editor-title",children:R||(ve?"Loading…":"Untitled")}):e.jsxs(e.Fragment,{children:[e.jsx("input",{id:"document-editor-title",ref:ja,value:R,onChange:t=>{at(t.target.value),Y(!0)},onBlur:bt,onKeyDown:t=>{var i,p;t.key==="Enter"&&(t.preventDefault(),is.current?is.current.focus():(p=(i=ga.current)==null?void 0:i.querySelector('textarea, [contenteditable="true"], input'))==null||p.focus())},placeholder:"Untitled",maxLength:120,disabled:ae,required:!0,"aria-required":"true","aria-label":"Title","aria-invalid":Dt&&!R.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${Dt&&!R.trim()?" placeholder:text-destructive/60":""}`}),(Dt&&!R.trim()||R.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:Dt&&!R.trim()?"Title is required":""}),e.jsx("span",{className:"text-muted-foreground tabular-nums",children:R.length>=90?`${R.length}/120`:""})]})]}),!d&&W==="edit"&&R.trim()!==Fs.current.trim()&&(()=>{const t=Rl(xe,{id:a,title:Fs.current});return t.length===0?null:e.jsx(Re,{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(Ae,{className:"h-4 w-4 shrink-0 text-amber-600"}),e.jsxs(Te,{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(Re,{className:"border-amber-300 bg-amber-50 text-amber-800",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ae,{className:"h-4 w-4 shrink-0 text-amber-600"}),e.jsxs(Te,{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:ae,onClick:()=>{Me(""),Y(!0)},className:`text-sm rounded px-1.5 py-0.5 ${z?"text-primary hover:bg-muted":"font-medium bg-muted"}`,title:"File directly under the nest root",children:"Root"}),z.split("/").filter(Boolean).map((t,i,p)=>{const E=p.slice(0,i+1).join("/"),D=p.slice(0,i).join("/"),H=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 ${H?"bg-muted":""}`,children:[e.jsx("button",{type:"button",disabled:ae,onClick:()=>{Me(E),Y(!0)},className:`text-sm rounded px-1.5 py-0.5 ${H?"font-medium":"text-primary hover:bg-muted"}`,title:`Scope to ${E}`,children:Xs(t)}),H&&e.jsx("button",{type:"button",disabled:ae,onClick:()=>{Me(D),Y(!0)},className:"mr-0.5 rounded p-0.5 text-muted-foreground hover:text-foreground hover:bg-background",title:D?`Go up to ${D}`:"Go up to the nest root","data-testid":"folder-step-up",children:e.jsx(et,{className:"h-3 w-3"})})]})]},E)}),e.jsx(qo,{folder:z,folderOptions:ka,disabled:ae,onPick:t=>{Me(t),Y(!0)}}),z&&e.jsx("button",{type:"button",disabled:ae,onClick:()=>{Me(""),Y(!0)},className:"ml-auto text-muted-foreground hover:text-foreground",title:"Clear folder (file under the nest root)",children:e.jsx(et,{className:"h-3.5 w-3.5"})})]})]}),(c||_.length>0)&&e.jsxs("div",{children:[e.jsxs("div",{className:"space-y-2",children:[c&&!ae&&e.jsx("input",{value:ke,onChange:t=>Rt(so(t.target.value)),onKeyDown:t=>{(t.key==="Enter"||t.key===","||t.key===" ")&&(t.preventDefault(),qa())},onBlur:()=>{ke.trim()&&qa()},placeholder:_.length?"Add a tag":"Add a tag…",maxLength:Il,"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"}),_.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:_.map(t=>{const i=W==="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}),!ae&&e.jsx("button",{type:"button",onClick:p=>{p.stopPropagation(),Hr(t)},className:"hover:text-destructive","aria-label":`Remove ${t}`,children:e.jsx(et,{className:"h-3 w-3"})})]},t)})})]}),ke.trim()&&e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground","data-testid":"document-editor-tag-preview",children:[At.tags.length>0?`Will add: ${At.tags.join(", ")}`:"Nothing new to add",At.notes.length>0&&` — ${At.notes.join(" ")}`]})]}),Tt&&ei&&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(xl,{className:"h-4 w-4"}),"Prime document"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:ps&&oe===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."}),ps&&oe===!1&&e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:"Exempted from its prime tag."}),Wa&&zt&&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(Jn,{checked:Wa,disabled:ae,onCheckedChange:t=>{Pt(t===ps?null:t),Y(!0)},"aria-label":"Prime document","data-testid":"document-editor-prime"})]}),!d&&(Ge||Xe.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground",children:[Ge&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:["Created by ",e.jsx("span",{className:"font-medium text-foreground/80",children:Ge})]}),Ge&&Xe.length>0&&e.jsx("span",{"aria-hidden":!0,children:"·"}),Xe.length>0&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",title:Xe.join(", "),children:["Collaborators:",e.jsx(Tl,{collaborators:Xe,max:5,size:"md"}),e.jsx("span",{className:"font-medium text-foreground/80",children:Xe.length})]})]}),c&&(d||_t||Pa)&&e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 w-full",children:[(d||Pa)&&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",...B,children:[{value:"document",label:"Document",Icon:Qs,on:"bg-slate-500/15 text-slate-700 dark:text-slate-300"},...fe?[{value:"artifact",label:"Artifact",Icon:Zt,on:"bg-amber-500/15 text-amber-700 dark:text-amber-300"}]:[],...N?[{value:"table",label:"Table",Icon:Ys,on:"bg-cyan-500/15 text-cyan-700 dark:text-cyan-300"}]:[],...te?[{value:"agent",label:"Agent",Icon:dn,on:"bg-violet-500/15 text-violet-700 dark:text-violet-300"},{value:"skill",label:"Skill",Icon:Nn,on:"bg-blue-500/15 text-blue-700 dark:text-blue-300"},{value:"tool",label:"Tool",Icon:vn,on:"bg-teal-500/15 text-teal-700 dark:text-teal-300"}]:[]].map(({value:t,label:i,Icon:p,on:E},D)=>{const H=ht===t;return e.jsxs("button",{type:"button",role:"radio","aria-checked":H,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){gr(t,i);return}t!==ht&&Ce("turn it into another kind",()=>os(t))},className:`flex items-center gap-1.5 px-3 py-1.5 text-sm transition-colors ${D>0?"border-l":""} ${H?`${E} 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)})}),ht==="artifact"&&e.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:"Hosted HTML — the body is served as a sandboxed page."}),(ht==="agent"||ht==="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."}),ht==="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."]}),ht==="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."})]}),_t&&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:ne,placeholder:"e.g. 0 6 * * * or @daily or @every 15m","aria-invalid":ft.kind==="invalid",onChange:t=>{nt(t.target.value),Y(!0)},onBlur:bt,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 ${ft.kind==="invalid"?"border-destructive focus:ring-destructive":""}`}),e.jsx("p",{"data-testid":"document-editor-schedule-feedback",className:`mt-1 text-xs ${ft.kind==="invalid"?"text-destructive":"text-muted-foreground"}`,children:ft.kind==="invalid"?e.jsxs(e.Fragment,{children:["Doesn't look like a cron/interval schedule — ",ft.error,"."]}):ft.kind==="valid"?e.jsxs(e.Fragment,{children:[ft.description,". Opaque to this server — an external orchestrator parses it and runs the"," ",we==="skill"||ce==="skill"?"skill":"agent","."]}):e.jsxs(e.Fragment,{children:["Opaque to this server — an external orchestrator parses it and runs the"," ",we==="skill"||ce==="skill"?"skill":"agent",". Leave blank for none."]})})]})]}),_t&&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 ",ce==="skill"||we==="skill"?"skill":"agent"," appears here"]}),e.jsx(v,{variant:"ghost",size:"sm",className:"h-6 px-2 shrink-0",onClick:wr,title:"Copy URL",children:br?e.jsx(Mt,{className:"h-3 w-3 text-green-600"}):e.jsx(Fi,{className:"h-3 w-3"})})]}),e.jsxs("code",{className:"block text-[11px] font-mono break-all text-foreground/80",children:["GET ",xa]}),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(ys,{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:ga,onClick:()=>{he||re||je||ut||De!=="table"&&W==="view"&&!Q&&dt("edit")},children:[(ut||De==="tool"||De==="table")&&e.jsx("div",{className:"mb-1 text-xs font-medium text-muted-foreground",children:ut?"Artifact HTML":De==="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(Sn,{className:"h-4 w-4"}),"Diff: v",J," → current (v",(X==null?void 0:X.currentVersion)??Fe??"?",")",ee&&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:()=>Qe(!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:()=>Qe(!0),children:"Rendered"})]}),e.jsxs(v,{variant:"ghost",size:"sm",className:"h-7",onClick:()=>void qs(null),children:[e.jsx(et,{className:"h-4 w-4 mr-1"})," Exit diff"]})]})]}),(()=>{const t=Vs&&Vs.version===J?Vs: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(I,{className:"h-4 w-4 animate-spin"})," Loading version"," ",J,"…"]});if(rt){const i=De==="table"?fl(t.content||"",T):null,p=(E,D)=>i?e.jsx(ca,{columns:i[E].columns,rows:i[E].rows,rowClassName:H=>i[E].changed[H]?E==="past"?"bg-red-50 dark:bg-red-950/30":"bg-emerald-50 dark:bg-emerald-950/30":""}):e.jsx(Zs,{content:D,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",(X==null?void 0:X.currentVersion)??Fe??"?",")"]}),p("current",T)]})]})}return e.jsx(lr,{patch:$l(t.content||"",T),className:"max-h-none border rounded-lg"})})()]}):Ls&&W==="edit"&&!he?De==="table"?e.jsx(ro,{value:T,onChange:t=>{ae||(Ne(t),Y(!0))},onBlur:bt,readOnly:ae}):e.jsxs("div",{className:T.trim()?"grid gap-3 lg:grid-cols-2":"",children:[e.jsx("textarea",{value:T,onChange:t=>{ae||(Ne(t.target.value),Y(!0))},onBlur:bt,readOnly:ae,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"}),T.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(Dn,{code:_r,className:"flex-1 text-sm","data-testid":"tool-source-preview"})]})]}):Es?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(v,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>ma(!1),title:"Back to the rich editor","data-testid":"document-editor-rich-toggle",children:[e.jsx(Zt,{className:"h-3.5 w-3.5 mr-1.5"}),"Rich editor"]})}),e.jsx("textarea",{value:T,onChange:t=>{ae||(Ne(t.target.value),Y(!0))},onBlur:bt,readOnly:ae,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"})]}):ut?e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsx("textarea",{value:T,onChange:t=>{Ne(t.target.value),Y(!0)},onBlur:bt,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"}),Va.trim()?e.jsx("iframe",{srcDoc:Va,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||W==="view")&&(Ls||!bs(T))?e.jsx("div",{ref:Wt,onMouseUp:d?void 0:yr,onClick:d?void 0:Sr,onMouseMove:d?void 0:Cr,className:"min-h-[300px] cursor-text","data-testid":"document-view-surface",children:De==="table"&&!d?e.jsx("div",{className:"p-4",children:e.jsx(no,{nestId:s,nodeId:a,csv:T})}):De==="tool"?e.jsx(Dn,{code:T,"data-testid":"tool-source-view"}):e.jsx(Zs,{content:T,onWikiLinkClick:t=>Ga(t,null),previewFor:Lr})}):e.jsx(pl,{ref:is,content:T,onChange:t=>{Ne(t),Y(!0)},onSave:_a,onBlur:bt,nestId:s,currentNodeId:d?void 0:a,editable:!ae,onRequestDocLink:()=>ua(!0),onUploadImage:async t=>{const{url:i}=await Pi(s,t);return i},onWikiLinkClick:Ga,placeholder:"Start writing, or select text to format it…",autofocus:!1,variant:"page",toolbarEnd:e.jsx(e.Fragment,{children:!Ls&&J==null&&!ut&&e.jsxs(v,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>ma(!0),title:"Edit the raw markdown","data-testid":"document-editor-markdown-toggle",children:[e.jsx(Zt,{className:"h-3.5 w-3.5 sm:mr-1.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Markdown"})]})})})]})]})}),Bt&&!re&&e.jsxs("button",{type:"button","data-testid":"selection-comment-button",onMouseDown:t=>t.preventDefault(),onClick:Nr,style:{position:"fixed",left:Bt.x,top:Bt.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(ur,{className:"h-3.5 w-3.5"})," Comment"]}),W==="view"&&ms.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 ",ms.length," document",ms.length!==1?"s":""]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:ms.map(t=>e.jsx("button",{type:"button",className:"text-sm text-primary hover:underline text-left",onClick:()=>Ce(`open "${t.title}"`,()=>h==null?void 0:h(s,t.id,R)),children:t.title},t.id))})]}),W==="view"&&Ta.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:Ta.map((t,i)=>e.jsxs(n.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:()=>Ce(`open "${t.title}"`,()=>h==null?void 0:h(s,t.id,R)),children:t.title})]},t.id))})]}),W==="view"&&hs.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 ",hs.length," document",hs.length!==1?"s":""," without a link"]}),e.jsx("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:hs.map((t,i)=>e.jsxs(n.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:()=>Ce(`open "${t.title}"`,()=>h==null?void 0:h(s,t.id,R)),children:t.title})]},t.id))})]})]})]}),W==="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=!re&&!Q&&!je,i=!re&&Qa;return e.jsxs(e.Fragment,{children:[t&&!d&&c&&(U==="draft"||U==="rejected")&&e.jsxs(v,{variant:"ghost",size:"sm",className:"h-8 text-muted-foreground",disabled:Aa,onClick:()=>Os(!0),"data-testid":"document-editor-discard",children:[e.jsx(Rn,{className:"h-4 w-4 sm:mr-1.5"}),e.jsx("span",{className:"hidden sm:inline",children:Aa?"Discarding…":"Discard draft"})]}),i&&e.jsxs(v,{variant:"outline",size:"sm",className:"h-8",onClick:()=>ct(!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(ta,{className:"h-4 w-4 sm:mr-1.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Submit for review"})]}),t&&e.jsxs(v,{size:"sm",className:"h-8",onMouseDown:p=>p.preventDefault(),onClick:_a,disabled:!Oa,"data-testid":"document-editor-save",children:[qe?e.jsx(I,{className:"h-4 w-4 mr-1.5 animate-spin"}):Ps&&!ee?e.jsx(Mt,{className:"h-4 w-4 mr-1.5"}):e.jsx(Cn,{className:"h-4 w-4 mr-1.5"}),qe?"Saving…":Ps&&!ee?"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${Oe||Ms?"":" hidden"}`,"data-testid":"document-comments-rail","aria-hidden":!Oe&&!Ms,children:[!Oe&&Ms&&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:wa.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:Oe?"flex flex-col flex-1 min-h-0":"hidden",children:e.jsx(bo,{nestId:s,nodeId:a,readOnly:re,pendingAnchor:Ds,onClearAnchor:()=>As(null),onFocusAnchor:kr,onThreadsChange:vr,activeThreadId:Ut,commentMode:he,onSetCommentMode:t=>{Ht(t),t&&dt("view"),Pe(null),t||Et(null)}})})]})]}),Jt&&!d&&e.jsx(cr,{open:!0,onClose:()=>Ot(!1),title:R||a,versionData:X,onLoadContent:async t=>(await Gs(s,a,t)).content,onRestore:c?async t=>{try{await Gn(s,a,t),C.success(`Reverted to version ${t}`),await Promise.all([de(),Je()])}catch(i){C.error((i==null?void 0:i.message)||"Revert failed")}}:void 0,onDiscard:c?async()=>{try{const{version:t}=await un(s,a);C.success(`Draft discarded — back to version ${t}`),await Promise.all([de(),Je()])}catch(t){C.error((t==null?void 0:t.message)||"Discard failed")}}:void 0}),!d&&e.jsx(Ql,{isOpen:$t,onClose:()=>ct(!1),documentTitle:R,currentVersion:Fe??1,onSubmit:Qr}),!d&&e.jsx(Gl,{open:fr,onOpenChange:da,title:$?`Delete "${R||a}"?`:`Request deletion of "${R||a}"`,description:$?"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:$?void 0:"Why should it be deleted?",placeholder:"e.g. superseded by the new runbook",confirmLabel:$?"Delete document":"Request deletion",destructive:$,priorDecline:!$&&(me==null?void 0:me.status)==="declined"?me:null,onConfirm:$?Zr:Yr}),e.jsx(gl,{isOpen:pr,onClose:()=>ua(!1),nestId:s,excludeNodeId:d?void 0:a,onSelect:si}),e.jsx(wt,{open:Ze!==null,onOpenChange:t=>{!t&&!cs&&os(null)},children:e.jsxs(vt,{className:"sm:max-w-[480px]",children:[(()=>{const t=ds.find(p=>p.value===Ze),i=t==null?void 0:t.Icon;return e.jsxs(e.Fragment,{children:[e.jsx(jt,{children:e.jsxs(yt,{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(Nt,{children:[e.jsx(v,{variant:"outline",onClick:()=>os(null),disabled:cs,children:"Cancel"}),e.jsxs(v,{onClick:()=>void Er(),disabled:cs||!Ze,"data-testid":"document-editor-turn-into-confirm",children:[cs?e.jsx(I,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Turn into ",((rn=ds.find(t=>t.value===Ze))==null?void 0:rn.label)??""]})]})]})}),e.jsx(wt,{open:Ve!==null,onOpenChange:t=>{!t&&!us&&Gt(null)},children:e.jsxs(vt,{className:"sm:max-w-[440px]",children:[e.jsx(jt,{children:e.jsx(yt,{children:"Move to folder"})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Move ",e.jsx("strong",{children:R||a})," to another folder. Version history, review state, and [[wiki links]] follow the document."]}),e.jsxs(jl,{value:Ve===""?"__root__":Ve??"__root__",onValueChange:t=>Gt(t==="__root__"?"":t),children:[e.jsx(yl,{"data-testid":"document-editor-move-select",children:e.jsx(Nl,{placeholder:"Choose a folder"})}),e.jsxs(kl,{children:[e.jsx(yn,{value:"__root__",children:"Nest root"}),ka.map(t=>e.jsx(yn,{value:t,children:Oi(t)},t))]})]}),e.jsxs(Nt,{children:[e.jsx(v,{variant:"ghost",disabled:us,onClick:()=>Gt(null),children:"Cancel"}),e.jsxs(v,{disabled:us||Ve===null||Ve===Ra,"data-testid":"document-editor-move-confirm",onClick:async()=>{if(Ve!==null){Ca(!0);try{const{node:t}=await Vi(s,a,Ve);C.success(Ve?`Moved to ${Ve}`:"Moved to nest root"),Gt(null),m==null||m(t.id)}catch(t){C.error((t==null?void 0:t.message)||"Move failed")}finally{Ca(!1)}}},children:[us?e.jsx(I,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(kn,{className:"h-4 w-4 mr-2"}),"Move"]})]})]})}),ge&&e.jsx(El,{nestId:s,targetType:"document",target:a,label:R||a,archived:Se,onClose:()=>_e(!1)}),pe&&e.jsx(fo,{nestId:s,nestName:r,stewardshipEnabled:Tt,onClose:()=>St(!1),onChanged:()=>{}}),tt&&e.jsx(Ll,{nestId:s,nodeId:a,nodeTitle:R||a,onClose:()=>ze(!1)}),pt&&e.jsx(wt,{open:!0,onOpenChange:()=>gt(null),children:e.jsxs(vt,{className:"sm:max-w-[460px]",children:[e.jsx(jt,{children:e.jsx(yt,{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 ",pt.label,", or discard to leave without saving."]}),Kt&&e.jsxs(Re,{variant:"destructive",children:[e.jsx(Ae,{className:"h-4 w-4"}),e.jsx(Te,{children:Kt})]}),e.jsxs(Nt,{children:[e.jsx(v,{variant:"outline",onClick:()=>gt(null),disabled:qe,children:"Cancel"}),e.jsx(v,{variant:"outline",onClick:Ur,disabled:qe,children:"Discard"}),e.jsxs(v,{onClick:Wr,disabled:qe,children:[qe?e.jsx(I,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Cn,{className:"h-4 w-4 mr-2"}),"Save & leave"]})]})]})}),ss&&e.jsx(wt,{open:!0,onOpenChange:()=>as(null),children:e.jsxs(vt,{className:"sm:max-w-[460px]",children:[e.jsx(jt,{children:e.jsxs(yt,{children:["Switch to ",ss.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 ",Wn(ns(ss.value))," ","instead of ",Wn(ns(we)),". Nothing is converted automatically — review the body after switching."]}),e.jsxs(Nt,{children:[e.jsx(v,{variant:"outline",onClick:()=>as(null),children:"Cancel"}),e.jsx(v,{onClick:()=>{ha(ss.value),as(null)},children:"Switch anyway"})]})]})}),e.jsx(Vl,{open:Pr,onOpenChange:Os,children:e.jsxs(ql,{children:[e.jsxs(zl,{children:[e.jsxs(_l,{children:['Discard the draft of "',R||a,'"?']}),e.jsx(Hl,{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(Bl,{children:[e.jsx(Wl,{children:"Cancel"}),e.jsx(Ul,{onClick:()=>void Or(),"data-testid":"document-editor-discard-confirm",children:"Discard draft"})]})]})})]})}function Vo({status:s}){const a={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 a?e.jsx("span",{className:`shrink-0 inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${a.cls}`,"data-testid":`document-status-${s}`,children:a.label}):null}function qo({folder:s,folderOptions:r,disabled:a,onPick:o}){const[l,u]=n.useState(""),x=s.split("/").filter(Boolean).length>=fn,m=n.useMemo(()=>{const f=new Set;for(const g of r)if(s){if(g===s||!g.startsWith(`${s}/`))continue;f.add(g.slice(s.length+1).split("/")[0])}else f.add(g.split("/")[0]);return[...f].sort()},[s,r]),h=()=>{if(x)return;const f=l.trim().replace(/\/+/g,"-");f&&(o(s?`${s}/${f}`:f),u(""))};return e.jsxs(In,{modal:!1,children:[e.jsx(er,{asChild:!0,children:e.jsx(v,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-1.5 text-muted-foreground",disabled:a,title:"Open a subfolder or create a new one","data-testid":"folder-step-picker",children:e.jsx(tr,{className:"h-3.5 w-3.5"})})}),e.jsxs(sr,{align:"start",className:"min-w-56",children:[m.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(ar,{children:s?"Subfolders":"Existing folders"}),m.map(f=>e.jsxs(Yt,{onSelect:()=>o(s?`${s}/${f}`:f),children:[e.jsx(Bi,{className:"h-3.5 w-3.5 mr-2 text-blue-500"}),Xs(f)]},f)),e.jsx(nr,{})]}),x?e.jsxs("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:["Max folder depth (",fn,") 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(bl,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsx(Qn,{value:l,onChange:f=>u(f.target.value),onKeyDown:f=>{f.key==="Enter"&&(f.preventDefault(),h())},placeholder:"New subfolder…",className:"h-7 text-sm"})]})]})]})}export{bc as DocumentEditor,bc as default};