@taskforcehq/taskforce 0.3.300 → 0.3.302

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 (153) hide show
  1. package/README.md +19 -0
  2. package/dist/Taskforce.module.css +26 -2
  3. package/dist/TaskforceCore.filter-persistence.test.js +1 -1
  4. package/dist/TaskforceCore.js +13 -24
  5. package/dist/TaskforceCore.test.js +167 -152
  6. package/dist/components/features/TaskSettings.js +14 -82
  7. package/dist/components/features/TaskSettings.test.js +33 -70
  8. package/dist/components/features/settings/TaxonomyLibraryManager.js +8 -2
  9. package/dist/components/features/settings/TaxonomyLibraryManager.test.js +1 -1
  10. package/dist/components/task/TaskActionHeader.js +6 -3
  11. package/dist/components/task/TaskCard.js +6 -3
  12. package/dist/components/task/TaskForm.js +2 -2
  13. package/dist/components/task/TaskForm.test.js +41 -2
  14. package/dist/components/ui/ReferenceBadgeButton.js +1 -1
  15. package/dist/components/views/PlansPage.js +9 -8
  16. package/dist/components/views/StandaloneLayout.js +490 -207
  17. package/dist/components/views/panels/FilterToolbar.d.ts +2 -0
  18. package/dist/components/views/panels/FilterToolbarControls.d.ts +1 -0
  19. package/dist/components/views/panels/FilterToolbarControls.js +1 -1
  20. package/dist/components/views/panels/PlanningDrawer.js +19 -2
  21. package/dist/components/views/standalone/modals/AccountHubModal.d.ts +43 -0
  22. package/dist/components/views/standalone/modals/AccountHubModal.js +22 -0
  23. package/dist/components/views/standalone/modals/CreateWorkspaceConfirmModal.d.ts +9 -0
  24. package/dist/components/views/standalone/modals/CreateWorkspaceConfirmModal.js +8 -0
  25. package/dist/components/views/standalone/modals/EditProfileModal.d.ts +26 -0
  26. package/dist/components/views/standalone/modals/EditProfileModal.js +10 -0
  27. package/dist/components/views/standalone/modals/HelpModal.d.ts +9 -0
  28. package/dist/components/views/standalone/modals/HelpModal.js +8 -0
  29. package/dist/components/views/standalone/modals/ScheduleWarningModal.d.ts +13 -0
  30. package/dist/components/views/standalone/modals/ScheduleWarningModal.js +6 -0
  31. package/dist/components/views/standalone/modals/SyncStatusModal.d.ts +61 -0
  32. package/dist/components/views/standalone/modals/SyncStatusModal.js +38 -0
  33. package/dist/components/views/standalone/modals/TeamManagementModal.d.ts +64 -0
  34. package/dist/components/views/standalone/modals/TeamManagementModal.js +10 -0
  35. package/dist/components/views/standalone/modals/types.d.ts +2 -0
  36. package/dist/components/views/standalone/modals/types.js +1 -0
  37. package/dist/components/views/teamManagementAccess.d.ts +1 -1
  38. package/dist/components/views/teamManagementAccess.js +2 -2
  39. package/dist/components/views/teamManagementAccess.test.js +3 -3
  40. package/dist/config/deployment.js +2 -2
  41. package/dist/config/deployment.test.js +5 -3
  42. package/dist/core/AiProfileService.js +7 -2
  43. package/dist/core/AiProfiles.test.js +19 -0
  44. package/dist/core/SyncReconciliationService.d.ts +2 -0
  45. package/dist/core/SyncReconciliationService.js +3 -0
  46. package/dist/core/TaskAuditTimeline.test.js +40 -0
  47. package/dist/core/Taskforce.d.ts +49 -0
  48. package/dist/core/Taskforce.ids.test.js +133 -0
  49. package/dist/core/Taskforce.js +241 -78
  50. package/dist/core/UserProfileAvatarDrafts.test.d.ts +1 -0
  51. package/dist/core/UserProfileAvatarDrafts.test.js +102 -0
  52. package/dist/core/taskReferencePolicy.d.ts +28 -0
  53. package/dist/core/taskReferencePolicy.js +189 -0
  54. package/dist/core/types.d.ts +2 -0
  55. package/dist/hooks/tasks/useTaskFormActions.js +3 -0
  56. package/dist/hooks/useTaskData.js +16 -11
  57. package/dist/hooks/useTaskData.test.js +127 -0
  58. package/dist/hooks/useTaskforce.d.ts +5 -0
  59. package/dist/hooks/useTaskforce.js +63 -15
  60. package/dist/hooks/useTaskforce.sync-behavior.test.js +185 -6
  61. package/dist/mcp/aiProfileBootstrap.d.ts +29 -0
  62. package/dist/mcp/aiProfileBootstrap.js +80 -0
  63. package/dist/mcp/aiProfileBootstrap.test.d.ts +1 -0
  64. package/dist/mcp/aiProfileBootstrap.test.js +68 -0
  65. package/dist/mcp/clientIntegrations.d.ts +2 -8
  66. package/dist/mcp/clientIntegrations.js +21 -40
  67. package/dist/mcp/clientIntegrations.test.js +28 -2
  68. package/dist/mcp/clientProfileDefaults.d.ts +12 -0
  69. package/dist/mcp/clientProfileDefaults.js +37 -0
  70. package/dist/mcp/runtime.d.ts +10 -7
  71. package/dist/mcp/runtime.js +45 -23
  72. package/dist/mcp/runtime.test.js +56 -3
  73. package/dist/migrations/taskSchemaMigrations.js +53 -1
  74. package/dist/qaOpen.test.d.ts +1 -0
  75. package/dist/qaOpen.test.js +56 -0
  76. package/dist/server/index.cookieProxy.test.js +1 -0
  77. package/dist/server/index.d.ts +1 -0
  78. package/dist/server/index.js +15 -1
  79. package/dist/server/index.test.js +14 -1
  80. package/dist/server/routes/admin.js +25 -22
  81. package/dist/server/routes/auth.d.ts +5 -0
  82. package/dist/server/routes/auth.js +350 -16
  83. package/dist/server/routes/billing.js +11 -1
  84. package/dist/server/routes/billing.test.js +32 -2
  85. package/dist/server/routes/documents.js +6 -1
  86. package/dist/server/routes/shared.d.ts +1 -1
  87. package/dist/server/routes/shared.js +11 -3
  88. package/dist/server/routes/sync.integration.test.js +130 -0
  89. package/dist/server/routes/sync.js +226 -1924
  90. package/dist/server/routes/tasks.js +18 -4
  91. package/dist/server/routes.js +26 -19
  92. package/dist/server/routes.test.js +352 -6
  93. package/dist/shared/runtimeContract.d.ts +1 -1
  94. package/dist/sync/collaborationSyncPayload.d.ts +17 -0
  95. package/dist/sync/collaborationSyncPayload.js +131 -0
  96. package/dist/sync/collaborationSyncPayload.test.d.ts +1 -0
  97. package/dist/sync/collaborationSyncPayload.test.js +104 -0
  98. package/dist/sync/collaborationSyncState.d.ts +15 -0
  99. package/dist/sync/collaborationSyncState.js +60 -0
  100. package/dist/sync/contentSyncPayload.d.ts +45 -0
  101. package/dist/sync/contentSyncPayload.js +104 -0
  102. package/dist/sync/contentSyncPayload.test.d.ts +1 -0
  103. package/dist/sync/contentSyncPayload.test.js +104 -0
  104. package/dist/sync/contentSyncState.d.ts +88 -0
  105. package/dist/sync/contentSyncState.js +743 -0
  106. package/dist/sync/planningSyncPayload.d.ts +9 -0
  107. package/dist/sync/planningSyncPayload.js +82 -0
  108. package/dist/sync/planningSyncPayload.test.d.ts +1 -0
  109. package/dist/sync/planningSyncPayload.test.js +68 -0
  110. package/dist/sync/syncApplyHandlers.d.ts +83 -0
  111. package/dist/sync/syncApplyHandlers.js +445 -0
  112. package/dist/sync/taskSyncPayload.d.ts +33 -0
  113. package/dist/sync/taskSyncPayload.js +126 -0
  114. package/dist/sync/taskSyncPayload.test.d.ts +1 -0
  115. package/dist/sync/taskSyncPayload.test.js +54 -0
  116. package/dist/sync/workspacePullFeed.d.ts +28 -0
  117. package/dist/sync/workspacePullFeed.js +301 -0
  118. package/dist/sync/workspacePullFeed.test.d.ts +1 -0
  119. package/dist/sync/workspacePullFeed.test.js +166 -0
  120. package/dist/sync/workspaceSyncModel.d.ts +4 -1
  121. package/dist/sync/workspaceSyncModel.js +9 -2
  122. package/dist/sync/workspaceSyncModel.test.js +29 -0
  123. package/dist/test/setup.js +1 -1
  124. package/dist/types.d.ts +1 -0
  125. package/dist/ui/assets/{AgentsModule-TVmCgizS.js → AgentsModule-JG5jc3he.js} +1 -1
  126. package/dist/ui/assets/{AnnotatedAttachmentWorkspace-CAyhnPeR.js → AnnotatedAttachmentWorkspace-Dvi02Y7q.js} +1 -1
  127. package/dist/ui/assets/{DocumentWorkspace-BOCw5e4D.js → DocumentWorkspace-iys3zfca.js} +2 -2
  128. package/dist/ui/assets/{InitiativesModule-CN0r02Oi.js → InitiativesModule-DJvLJI3A.js} +1 -1
  129. package/dist/ui/assets/PlansPage-BMPlpFpw.js +1 -0
  130. package/dist/ui/assets/TaskSettings-Bqd4cCzW.js +8 -0
  131. package/dist/ui/assets/{TaskSettings-BwB9NtmJ.css → TaskSettings-CnIBL_Eb.css} +1 -1
  132. package/dist/ui/assets/{WorkflowsModule-CY9R2zPB.js → WorkflowsModule-BguHeQaV.js} +1 -1
  133. package/dist/ui/assets/index-MXeWoebC.css +1 -0
  134. package/dist/ui/assets/index-YJ4k5QNa.js +6 -0
  135. package/dist/ui/assets/{vendor-icons-QZyhEwgT.js → vendor-icons-C8EED3Oh.js} +1 -1
  136. package/dist/ui/index.html +3 -3
  137. package/dist/utils/billingStatusCache.d.ts +21 -0
  138. package/dist/utils/billingStatusCache.js +70 -0
  139. package/dist/utils/taskActivity.js +17 -4
  140. package/dist/utils/taskActivity.test.js +27 -0
  141. package/dist/utils/taskNormalization.js +10 -2
  142. package/dist/utils/taskReferences.d.ts +11 -1
  143. package/dist/utils/taskReferences.js +33 -1
  144. package/package.json +4 -1
  145. package/scripts/deploy-prod.sh +41 -0
  146. package/scripts/deploy-staging.sh +23 -0
  147. package/scripts/qa-open-lib.mjs +175 -0
  148. package/scripts/qa-open-lib.mjs.d.ts +49 -0
  149. package/scripts/qa-open.mjs +352 -0
  150. package/dist/ui/assets/PlansPage-FcQSNLZd.js +0 -1
  151. package/dist/ui/assets/TaskSettings-Cw5zYD1L.js +0 -8
  152. package/dist/ui/assets/index-Bzqy5QGm.js +0 -6
  153. package/dist/ui/assets/index-DxRiI3tY.css +0 -1
@@ -1 +1 @@
1
- import{r as n,j as e}from"./vendor-react-CKJs5o3c.js";import{s as T,u as C,v as w,w as S,t as s,x as M}from"./index-Bzqy5QGm.js";import{h as L,B as A,k as I,a8 as H,aG as B,aH as D,b as R}from"./vendor-icons-QZyhEwgT.js";import"./vendor-markdown-BUxTU7dS.js";import"./vendor-dnd-DRzYolkg.js";import"./vendor-router-BbWMxlnO.js";function F({workspaceId:h}){const[x,k]=n.useState([]),[j,y]=n.useState(!1),[c,P]=n.useState(null),[p,m]=n.useState(null),[d,g]=n.useState(null),N=n.useCallback(async()=>{if(h){y(!0);try{const a=await(await fetch(`/api/taskforce/workspace/assignee-options?workspaceId=${encodeURIComponent(h)}`,{credentials:"include"})).json().catch(()=>({})),t=Array.isArray(a?.assignees)?a.assignees.filter(i=>i.kind==="agent").map(i=>({id:String(i.value||""),name:String(i.label||i.value||"Unknown Agent"),username:String(i.username||i.value||""),icon:String(i.icon||"Bot"),color:String(i.color||"#6B7280"),kind:String(i.kind||"agent"),description:typeof i.description=="string"?i.description:null,role:typeof i.role=="string"?i.role:null,provider:typeof i.provider=="string"?i.provider:null,model:typeof i.model=="string"?i.model:null,surfaceType:T(i.surfaceType),createdAt:String(i.createdAt||""),updatedAt:String(i.updatedAt||i.createdAt||""),lastActiveAt:typeof i.lastActiveAt=="string"?i.lastActiveAt:null})):[];k(t)}finally{y(!1)}}},[h]);n.useEffect(()=>{N()},[N]);const f=n.useMemo(()=>{const r=new Map;for(const a of x){const t=C(a.surfaceType);r.has(t)||r.set(t,new Map);const i=r.get(t),v=a.name.toLowerCase();i.has(v)||i.set(v,[]),i.get(v).push(a)}return w.map(a=>({section:a,label:S(a),groups:Array.from(r.get(a)?.entries()||[]).map(([t,i])=>({groupId:`${a}:${t}`,section:a,sectionLabel:S(a),profiles:i,primaryProfile:i[0]}))})).filter(a=>a.groups.length>0)},[x]),o=n.useMemo(()=>f.flatMap(r=>r.groups),[f]),l=n.useMemo(()=>o.find(r=>r.groupId===d)||o[0]||null,[o,d]);n.useEffect(()=>{if(!o.length){d!==null&&g(null);return}(!d||!o.some(r=>r.groupId===d))&&g(o[0].groupId)},[o,d]);const b=async(r,a)=>{m(null);try{const t=await fetch("/api/taskforce/workspace/ai-profiles/merge",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({keepId:r,mergeId:a})}),i=await t.json().catch(()=>({}));if(!t.ok){m({type:"error",message:String(i?.error||"Failed to merge AI profiles.")});return}P(null),m({type:"success",message:"AI profiles merged."}),await N()}catch{m({type:"error",message:"Failed to merge AI profiles."})}},u=r=>{const a=String(r||"").trim();if(!a)return"Unknown";const t=Date.parse(a);return Number.isFinite(t)?new Date(t).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"}):a};return e.jsx("div",{className:`${s.standalonePage} ${s.standaloneContent}`,style:{overflow:"auto"},children:e.jsx("div",{className:s.settingsContent,style:{maxWidth:960,margin:"0 auto",width:"100%"},children:e.jsx("div",{className:s.settingGroup,children:e.jsxs("div",{children:[e.jsx("h4",{className:s.settingSubTitle,children:"Registered AI Profiles"}),e.jsx("p",{className:`${s.settingsHint} ${s.marginBottom12}`,children:"AI agents register profiles when connecting via MCP. Merge duplicates created when a token was lost."}),j&&e.jsxs("div",{className:s.settingsHint,children:[e.jsx(L,{size:13,className:s.spinner})," Loading profiles…"]}),!j&&x.length===0&&e.jsx("div",{className:s.settingsHint,children:"No AI profiles registered yet."}),!j&&f.length>0&&e.jsxs("div",{className:s.aiProfilesExplorer,children:[e.jsx("div",{className:s.aiProfilesListPane,children:e.jsx("div",{className:s.aiProfilesList,children:f.map(r=>e.jsxs("div",{className:s.aiProfilesSection,children:[e.jsx("div",{className:s.aiProfilesSectionHeader,children:r.label}),r.groups.map(a=>{const t=l?.groupId===a.groupId,i=a.primaryProfile;return e.jsxs("button",{type:"button",className:`${s.aiProfileGroup} ${a.profiles.length>1?s.aiProfileGroupDuplicate:""} ${t?s.aiProfileGroupSelected:""}`,onClick:()=>g(a.groupId),"aria-pressed":t,children:[e.jsxs("div",{className:s.aiProfileGroupHeader,children:[e.jsx(A,{size:13,style:{color:i.color}}),e.jsx("span",{className:s.aiProfileName,children:i.name}),a.profiles.length>1&&e.jsxs("span",{className:s.aiProfileDuplicateBadge,children:[e.jsx(I,{size:11})," ",a.profiles.length," duplicates"]})]}),e.jsxs("div",{className:s.settingsHint,style:{marginTop:6},children:["@",i.username]}),(i.surfaceType||i.role||i.provider||i.model)&&e.jsxs("div",{className:s.aiProfileMetaRow,children:[i.surfaceType&&e.jsx("span",{className:s.aiProfileSurfaceBadge,children:M(i.surfaceType)}),i.role&&e.jsx("span",{children:i.role}),i.provider&&e.jsx("span",{children:i.provider}),i.model&&e.jsx("span",{children:i.model})]}),i.description&&e.jsx("div",{className:s.settingsHint,style:{marginTop:4},children:i.description})]},a.groupId)})]},r.section))})}),l&&e.jsx("div",{className:s.aiProfileDetailPane,children:e.jsxs("div",{className:s.aiProfileDetailCard,children:[e.jsxs("div",{className:s.aiProfileDetailHero,children:[e.jsx("div",{className:s.aiProfileDetailIcon,style:{color:l.primaryProfile.color},children:e.jsx(A,{size:18})}),e.jsxs("div",{className:s.aiProfileDetailHeading,children:[e.jsx("div",{className:s.aiProfileDetailTitleRow,children:e.jsx("h5",{className:s.aiProfileDetailTitle,children:l.primaryProfile.name})}),e.jsxs("div",{className:s.aiProfileDetailMetaRow,children:[e.jsxs("span",{className:s.aiProfileDetailHandle,children:["@",l.primaryProfile.username]}),e.jsx("span",{className:s.aiProfileDetailSectionBadge,children:l.sectionLabel}),l.profiles.length>1&&e.jsxs("span",{className:s.aiProfileDetailLinkedCount,children:[l.profiles.length," linked"]})]})]})]}),l.primaryProfile.description&&e.jsx("div",{className:s.aiProfileDetailDescription,children:l.primaryProfile.description}),e.jsxs("div",{className:s.aiProfileDetailGrid,children:[e.jsxs("div",{className:s.aiProfileDetailStat,children:[e.jsxs("span",{className:s.aiProfileDetailStatLabel,children:[e.jsx(H,{size:12})," Role"]}),e.jsx("span",{className:s.aiProfileDetailStatValue,children:l.primaryProfile.role||"Not set"})]}),e.jsxs("div",{className:s.aiProfileDetailStat,children:[e.jsxs("span",{className:s.aiProfileDetailStatLabel,children:[e.jsx(B,{size:12})," Provider"]}),e.jsx("span",{className:s.aiProfileDetailStatValue,children:[l.primaryProfile.provider,l.primaryProfile.model].filter(Boolean).join(" · ")||"Not set"})]}),e.jsxs("div",{className:s.aiProfileDetailStat,children:[e.jsxs("span",{className:s.aiProfileDetailStatLabel,children:[e.jsx(D,{size:12})," Last active"]}),e.jsx("span",{className:s.aiProfileDetailStatValue,children:u(l.primaryProfile.lastActiveAt)})]}),e.jsxs("div",{className:s.aiProfileDetailStat,children:[e.jsxs("span",{className:s.aiProfileDetailStatLabel,children:[e.jsx(D,{size:12})," Updated"]}),e.jsx("span",{className:s.aiProfileDetailStatValue,children:u(l.primaryProfile.updatedAt)})]})]}),e.jsxs("div",{className:s.aiProfileInstanceSection,children:[e.jsxs("div",{className:s.aiProfileInstanceSectionHeader,children:[e.jsx("span",{children:"Profile instances"}),e.jsx("span",{className:s.settingsHint,children:"Choose a keeper here if duplicates need to be merged."})]}),e.jsx("div",{className:s.aiProfileInstanceList,children:l.profiles.map(r=>e.jsxs("div",{className:s.aiProfileInstanceCard,children:[e.jsxs("div",{className:s.aiProfileInstanceTopRow,children:[e.jsxs("div",{children:[e.jsxs("div",{className:s.aiProfileInstanceName,children:["@",r.username]}),e.jsx("div",{className:s.aiProfileIdChip,children:r.id})]}),l.profiles.length>1&&c?.keepId===r.id&&e.jsx("span",{className:s.aiProfileKeepBadge,children:"Keeping"})]}),e.jsxs("div",{className:s.aiProfileInstanceMeta,children:[e.jsxs("span",{children:["Created ",u(r.createdAt)]}),e.jsxs("span",{children:["Updated ",u(r.updatedAt)]})]}),l.profiles.length>1&&c?.keepId!==r.id&&e.jsx("button",{className:s.secondaryHeaderBtn,title:"Keep this profile, merge others into it",onClick:()=>{const a=l.profiles.find(t=>t.id!==r.id)?.id;a&&P({keepId:r.id,mergeId:a})},children:"Keep this"})]},r.id))}),c&&l.profiles.some(r=>r.id===c.keepId)&&e.jsxs("div",{className:s.aiProfileMergeActions,children:[e.jsx("button",{className:s.dangerBtn,onClick:()=>{b(c.keepId,c.mergeId)},children:"Merge duplicates"}),e.jsx("button",{className:s.secondaryHeaderBtn,onClick:()=>P(null),children:"Cancel"})]})]})]})})]}),p&&e.jsxs("div",{className:`${p.type==="success"?s.successMessage:s.errorMessage} ${s.marginTop12}`,children:[p.type==="success"?e.jsx(R,{size:14}):e.jsx(I,{size:14}),p.message]})]})})})})}export{F as AgentsModule};
1
+ import{r as n,j as e}from"./vendor-react-CKJs5o3c.js";import{p as T,u as C,v as w,w as S,t as s,x as M}from"./index-YJ4k5QNa.js";import{h as L,B as A,k as I,a8 as H,aG as B,aH as D,b as R}from"./vendor-icons-C8EED3Oh.js";import"./vendor-markdown-BUxTU7dS.js";import"./vendor-dnd-DRzYolkg.js";import"./vendor-router-BbWMxlnO.js";function F({workspaceId:h}){const[x,k]=n.useState([]),[j,y]=n.useState(!1),[c,P]=n.useState(null),[p,m]=n.useState(null),[d,g]=n.useState(null),N=n.useCallback(async()=>{if(h){y(!0);try{const a=await(await fetch(`/api/taskforce/workspace/assignee-options?workspaceId=${encodeURIComponent(h)}`,{credentials:"include"})).json().catch(()=>({})),t=Array.isArray(a?.assignees)?a.assignees.filter(i=>i.kind==="agent").map(i=>({id:String(i.value||""),name:String(i.label||i.value||"Unknown Agent"),username:String(i.username||i.value||""),icon:String(i.icon||"Bot"),color:String(i.color||"#6B7280"),kind:String(i.kind||"agent"),description:typeof i.description=="string"?i.description:null,role:typeof i.role=="string"?i.role:null,provider:typeof i.provider=="string"?i.provider:null,model:typeof i.model=="string"?i.model:null,surfaceType:T(i.surfaceType),createdAt:String(i.createdAt||""),updatedAt:String(i.updatedAt||i.createdAt||""),lastActiveAt:typeof i.lastActiveAt=="string"?i.lastActiveAt:null})):[];k(t)}finally{y(!1)}}},[h]);n.useEffect(()=>{N()},[N]);const f=n.useMemo(()=>{const r=new Map;for(const a of x){const t=C(a.surfaceType);r.has(t)||r.set(t,new Map);const i=r.get(t),v=a.name.toLowerCase();i.has(v)||i.set(v,[]),i.get(v).push(a)}return w.map(a=>({section:a,label:S(a),groups:Array.from(r.get(a)?.entries()||[]).map(([t,i])=>({groupId:`${a}:${t}`,section:a,sectionLabel:S(a),profiles:i,primaryProfile:i[0]}))})).filter(a=>a.groups.length>0)},[x]),o=n.useMemo(()=>f.flatMap(r=>r.groups),[f]),l=n.useMemo(()=>o.find(r=>r.groupId===d)||o[0]||null,[o,d]);n.useEffect(()=>{if(!o.length){d!==null&&g(null);return}(!d||!o.some(r=>r.groupId===d))&&g(o[0].groupId)},[o,d]);const b=async(r,a)=>{m(null);try{const t=await fetch("/api/taskforce/workspace/ai-profiles/merge",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({keepId:r,mergeId:a})}),i=await t.json().catch(()=>({}));if(!t.ok){m({type:"error",message:String(i?.error||"Failed to merge AI profiles.")});return}P(null),m({type:"success",message:"AI profiles merged."}),await N()}catch{m({type:"error",message:"Failed to merge AI profiles."})}},u=r=>{const a=String(r||"").trim();if(!a)return"Unknown";const t=Date.parse(a);return Number.isFinite(t)?new Date(t).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"}):a};return e.jsx("div",{className:`${s.standalonePage} ${s.standaloneContent}`,style:{overflow:"auto"},children:e.jsx("div",{className:s.settingsContent,style:{maxWidth:960,margin:"0 auto",width:"100%"},children:e.jsx("div",{className:s.settingGroup,children:e.jsxs("div",{children:[e.jsx("h4",{className:s.settingSubTitle,children:"Registered AI Profiles"}),e.jsx("p",{className:`${s.settingsHint} ${s.marginBottom12}`,children:"AI agents register profiles when connecting via MCP. Merge duplicates created when a token was lost."}),j&&e.jsxs("div",{className:s.settingsHint,children:[e.jsx(L,{size:13,className:s.spinner})," Loading profiles…"]}),!j&&x.length===0&&e.jsx("div",{className:s.settingsHint,children:"No AI profiles registered yet."}),!j&&f.length>0&&e.jsxs("div",{className:s.aiProfilesExplorer,children:[e.jsx("div",{className:s.aiProfilesListPane,children:e.jsx("div",{className:s.aiProfilesList,children:f.map(r=>e.jsxs("div",{className:s.aiProfilesSection,children:[e.jsx("div",{className:s.aiProfilesSectionHeader,children:r.label}),r.groups.map(a=>{const t=l?.groupId===a.groupId,i=a.primaryProfile;return e.jsxs("button",{type:"button",className:`${s.aiProfileGroup} ${a.profiles.length>1?s.aiProfileGroupDuplicate:""} ${t?s.aiProfileGroupSelected:""}`,onClick:()=>g(a.groupId),"aria-pressed":t,children:[e.jsxs("div",{className:s.aiProfileGroupHeader,children:[e.jsx(A,{size:13,style:{color:i.color}}),e.jsx("span",{className:s.aiProfileName,children:i.name}),a.profiles.length>1&&e.jsxs("span",{className:s.aiProfileDuplicateBadge,children:[e.jsx(I,{size:11})," ",a.profiles.length," duplicates"]})]}),e.jsxs("div",{className:s.settingsHint,style:{marginTop:6},children:["@",i.username]}),(i.surfaceType||i.role||i.provider||i.model)&&e.jsxs("div",{className:s.aiProfileMetaRow,children:[i.surfaceType&&e.jsx("span",{className:s.aiProfileSurfaceBadge,children:M(i.surfaceType)}),i.role&&e.jsx("span",{children:i.role}),i.provider&&e.jsx("span",{children:i.provider}),i.model&&e.jsx("span",{children:i.model})]}),i.description&&e.jsx("div",{className:s.settingsHint,style:{marginTop:4},children:i.description})]},a.groupId)})]},r.section))})}),l&&e.jsx("div",{className:s.aiProfileDetailPane,children:e.jsxs("div",{className:s.aiProfileDetailCard,children:[e.jsxs("div",{className:s.aiProfileDetailHero,children:[e.jsx("div",{className:s.aiProfileDetailIcon,style:{color:l.primaryProfile.color},children:e.jsx(A,{size:18})}),e.jsxs("div",{className:s.aiProfileDetailHeading,children:[e.jsx("div",{className:s.aiProfileDetailTitleRow,children:e.jsx("h5",{className:s.aiProfileDetailTitle,children:l.primaryProfile.name})}),e.jsxs("div",{className:s.aiProfileDetailMetaRow,children:[e.jsxs("span",{className:s.aiProfileDetailHandle,children:["@",l.primaryProfile.username]}),e.jsx("span",{className:s.aiProfileDetailSectionBadge,children:l.sectionLabel}),l.profiles.length>1&&e.jsxs("span",{className:s.aiProfileDetailLinkedCount,children:[l.profiles.length," linked"]})]})]})]}),l.primaryProfile.description&&e.jsx("div",{className:s.aiProfileDetailDescription,children:l.primaryProfile.description}),e.jsxs("div",{className:s.aiProfileDetailGrid,children:[e.jsxs("div",{className:s.aiProfileDetailStat,children:[e.jsxs("span",{className:s.aiProfileDetailStatLabel,children:[e.jsx(H,{size:12})," Role"]}),e.jsx("span",{className:s.aiProfileDetailStatValue,children:l.primaryProfile.role||"Not set"})]}),e.jsxs("div",{className:s.aiProfileDetailStat,children:[e.jsxs("span",{className:s.aiProfileDetailStatLabel,children:[e.jsx(B,{size:12})," Provider"]}),e.jsx("span",{className:s.aiProfileDetailStatValue,children:[l.primaryProfile.provider,l.primaryProfile.model].filter(Boolean).join(" · ")||"Not set"})]}),e.jsxs("div",{className:s.aiProfileDetailStat,children:[e.jsxs("span",{className:s.aiProfileDetailStatLabel,children:[e.jsx(D,{size:12})," Last active"]}),e.jsx("span",{className:s.aiProfileDetailStatValue,children:u(l.primaryProfile.lastActiveAt)})]}),e.jsxs("div",{className:s.aiProfileDetailStat,children:[e.jsxs("span",{className:s.aiProfileDetailStatLabel,children:[e.jsx(D,{size:12})," Updated"]}),e.jsx("span",{className:s.aiProfileDetailStatValue,children:u(l.primaryProfile.updatedAt)})]})]}),e.jsxs("div",{className:s.aiProfileInstanceSection,children:[e.jsxs("div",{className:s.aiProfileInstanceSectionHeader,children:[e.jsx("span",{children:"Profile instances"}),e.jsx("span",{className:s.settingsHint,children:"Choose a keeper here if duplicates need to be merged."})]}),e.jsx("div",{className:s.aiProfileInstanceList,children:l.profiles.map(r=>e.jsxs("div",{className:s.aiProfileInstanceCard,children:[e.jsxs("div",{className:s.aiProfileInstanceTopRow,children:[e.jsxs("div",{children:[e.jsxs("div",{className:s.aiProfileInstanceName,children:["@",r.username]}),e.jsx("div",{className:s.aiProfileIdChip,children:r.id})]}),l.profiles.length>1&&c?.keepId===r.id&&e.jsx("span",{className:s.aiProfileKeepBadge,children:"Keeping"})]}),e.jsxs("div",{className:s.aiProfileInstanceMeta,children:[e.jsxs("span",{children:["Created ",u(r.createdAt)]}),e.jsxs("span",{children:["Updated ",u(r.updatedAt)]})]}),l.profiles.length>1&&c?.keepId!==r.id&&e.jsx("button",{className:s.secondaryHeaderBtn,title:"Keep this profile, merge others into it",onClick:()=>{const a=l.profiles.find(t=>t.id!==r.id)?.id;a&&P({keepId:r.id,mergeId:a})},children:"Keep this"})]},r.id))}),c&&l.profiles.some(r=>r.id===c.keepId)&&e.jsxs("div",{className:s.aiProfileMergeActions,children:[e.jsx("button",{className:s.dangerBtn,onClick:()=>{b(c.keepId,c.mergeId)},children:"Merge duplicates"}),e.jsx("button",{className:s.secondaryHeaderBtn,onClick:()=>P(null),children:"Cancel"})]})]})]})})]}),p&&e.jsxs("div",{className:`${p.type==="success"?s.successMessage:s.errorMessage} ${s.marginTop12}`,children:[p.type==="success"?e.jsx(R,{size:14}):e.jsx(I,{size:14}),p.message]})]})})})})}export{F as AgentsModule};
@@ -1,3 +1,3 @@
1
- import{j as t,r as a,R as qt}from"./vendor-react-CKJs5o3c.js";import{R as xs,f as Ce,e as Ct,g as vs,t as Bn,M as Jt}from"./index-Bzqy5QGm.js";import{q as _s,m as js,c as Zt,T as Tn,s as ks,a1 as ws,h as An,ai as Cs,R as Is,aj as Ss,ak as Ns,al as $s,am as tn,C as nn,an as Rs,ao as Dn,ap as zn,aq as Un,ar as Gn,g as Ps,f as Bs,b as sn}from"./vendor-icons-QZyhEwgT.js";import"./vendor-markdown-BUxTU7dS.js";import"./vendor-dnd-DRzYolkg.js";import"./vendor-router-BbWMxlnO.js";function Ts({copied:o,disabled:l=!1,label:m,onClick:g,title:w="Copy image reference",ariaLabel:y,className:M=""}){return t.jsx(xs,{copied:o,disabled:l,label:"",onClick:g,title:w,ariaLabel:y,className:M,children:m})}const As="_shell_sf7jc_1",Es="_panel_sf7jc_16",Ms="_sessionPanel_sf7jc_22",Ls="_detailPanel_sf7jc_23",Fs="_sessionContextBar_sf7jc_29",Hs="_sessionContextLeft_sf7jc_40",Os="_sessionContextRight_sf7jc_41",Ds="_sessionContextLabel_sf7jc_56",zs="_sessionContextSpacer_sf7jc_62",Us="_canvasPanel_sf7jc_67",Gs="_canvasWorkspace_sf7jc_74",Ys="_canvasMain_sf7jc_81",Ks="_panelHeader_sf7jc_88",Ws="_panelHeaderText_sf7jc_97",Xs="_panelTitle_sf7jc_101",Vs="_canvasHeading_sf7jc_105",qs="_sessionActions_sf7jc_109",Js="_sessionList_sf7jc_117",Zs="_annotationList_sf7jc_118",Qs="_markerHelpModalBody_sf7jc_133",ea="_openImageModalBody_sf7jc_139",ta="_openImageField_sf7jc_145",na="_openImageActions_sf7jc_149",sa="_markerHelpItem_sf7jc_155",aa="_markerHelpHeader_sf7jc_163",oa="_markerHelpExample_sf7jc_175",ra="_sessionCard_sf7jc_179",ia="_annotationCard_sf7jc_180",la="_sessionEmptyState_sf7jc_197",ca="_sessionCardButton_sf7jc_204",da="_annotationCardButton_sf7jc_214",ua="_sessionCardBody_sf7jc_224",fa="_sessionCardActive_sf7jc_230",ma="_annotationCardActive_sf7jc_231",pa="_annotationMeta_sf7jc_241",ha="_annotationInstructionPreview_sf7jc_248",ba="_annotationPreviewFooter_sf7jc_256",ga="_annotationInstructionEditor_sf7jc_263",ya="_annotationTypeField_sf7jc_269",xa="_annotationInstructionButton_sf7jc_275",va="_annotationInstructionField_sf7jc_284",_a="_sessionMeta_sf7jc_288",ja="_sessionTitle_sf7jc_295",ka="_annotationTitle_sf7jc_296",wa="_sessionTimestamp_sf7jc_302",Ca="_annotationKind_sf7jc_303",Ia="_annotationInstructionTypeIcon_sf7jc_307",Sa="_sessionInstructionPreview_sf7jc_313",Na="_sessionInstructionEditor_sf7jc_321",$a="_sessionCardFooter_sf7jc_327",Ra="_toolRail_sf7jc_334",Pa="_canvasToolRail_sf7jc_343",Ba="_toolbarCluster_sf7jc_364",Ta="_toolbarViewportCluster_sf7jc_371",Aa="_toolbarSeparator_sf7jc_375",Ea="_toolBtn_sf7jc_381",Ma="_toolRailButton_sf7jc_385",La="_toolbarButton_sf7jc_395",Fa="_toolBtnActive_sf7jc_400",Ha="_toolbarActions_sf7jc_407",Oa="_toolbarSelectionActions_sf7jc_416",Da="_toolbarColorPicker_sf7jc_424",za="_colorPickerButton_sf7jc_428",Ua="_colorPickerSwatch_sf7jc_433",Ga="_colorPickerPopover_sf7jc_441",Ya="_colorOption_sf7jc_456",Ka="_colorOptionActive_sf7jc_466",Wa="_toolbarUtilities_sf7jc_473",Xa="_toolbarGeometryFields_sf7jc_481",Va="_toolbarGeometryField_sf7jc_481",qa="_toolbarGeometryLabel_sf7jc_494",Ja="_toolbarGeometryInput_sf7jc_500",Za="_iconButton_sf7jc_505",Qa="_ghostBtn_sf7jc_510",eo="_payloadBtn_sf7jc_511",to="_backToTaskBtn_sf7jc_512",no="_canvasScroller_sf7jc_532",so="_canvasFrame_sf7jc_548",ao="_canvasMedia_sf7jc_555",oo="_canvasStatusOverlay_sf7jc_563",ro="_canvasStatusCard_sf7jc_575",io="_canvasImage_sf7jc_588",lo="_overlay_sf7jc_595",co="_overlaySelect_sf7jc_601",uo="_overlayPan_sf7jc_605",fo="_overlaySvg_sf7jc_609",mo="_overlayHitLayer_sf7jc_618",po="_arrowHitArea_sf7jc_627",ho="_canvasHandleHit_sf7jc_634",bo="_canvasResizeHandleHit_sf7jc_641",go="_canvasHandleVisible_sf7jc_645",yo="_pin_sf7jc_662",xo="_note_sf7jc_663",vo="_annotationNumberBadge_sf7jc_680",_o="_box_sf7jc_705",jo="_boxNumberBadge_sf7jc_714",ko="_arrowNumberBadge_sf7jc_720",wo="_boxSurface_sf7jc_724",Co="_selected_sf7jc_737",Io="_textInput_sf7jc_754",So="_textArea_sf7jc_755",No="_select_sf7jc_737",$o="_sessionTitleInput_sf7jc_762",Ro="_sessionInstructionField_sf7jc_767",Po="_detailEmpty_sf7jc_776",Bo="_emptyState_sf7jc_777",To="_payloadModalBody_sf7jc_789",Ao="_payloadModalToolbar_sf7jc_796",Eo="_payloadViewToggle_sf7jc_803",Mo="_payloadModalActions_sf7jc_804",Lo="_payloadModalPreview_sf7jc_811",Fo="_statusBar_sf7jc_826",Ho="_annotationSummary_sf7jc_838",s={shell:As,panel:Es,sessionPanel:Ms,detailPanel:Ls,sessionContextBar:Fs,sessionContextLeft:Hs,sessionContextRight:Os,sessionContextLabel:Ds,sessionContextSpacer:zs,canvasPanel:Us,canvasWorkspace:Gs,canvasMain:Ys,panelHeader:Ks,panelHeaderText:Ws,panelTitle:Xs,canvasHeading:Vs,sessionActions:qs,sessionList:Js,annotationList:Zs,markerHelpModalBody:Qs,openImageModalBody:ea,openImageField:ta,openImageActions:na,markerHelpItem:sa,markerHelpHeader:aa,markerHelpExample:oa,sessionCard:ra,annotationCard:ia,sessionEmptyState:la,sessionCardButton:ca,annotationCardButton:da,sessionCardBody:ua,sessionCardActive:fa,annotationCardActive:ma,annotationMeta:pa,annotationInstructionPreview:ha,annotationPreviewFooter:ba,annotationInstructionEditor:ga,annotationTypeField:ya,annotationInstructionButton:xa,annotationInstructionField:va,sessionMeta:_a,sessionTitle:ja,annotationTitle:ka,sessionTimestamp:wa,annotationKind:Ca,annotationInstructionTypeIcon:Ia,sessionInstructionPreview:Sa,sessionInstructionEditor:Na,sessionCardFooter:$a,toolRail:Ra,canvasToolRail:Pa,toolbarCluster:Ba,toolbarViewportCluster:Ta,toolbarSeparator:Aa,toolBtn:Ea,toolRailButton:Ma,toolbarButton:La,toolBtnActive:Fa,toolbarActions:Ha,toolbarSelectionActions:Oa,toolbarColorPicker:Da,colorPickerButton:za,colorPickerSwatch:Ua,colorPickerPopover:Ga,colorOption:Ya,colorOptionActive:Ka,toolbarUtilities:Wa,toolbarGeometryFields:Xa,toolbarGeometryField:Va,toolbarGeometryLabel:qa,toolbarGeometryInput:Ja,iconButton:Za,ghostBtn:Qa,payloadBtn:eo,backToTaskBtn:to,canvasScroller:no,canvasFrame:so,canvasMedia:ao,canvasStatusOverlay:oo,canvasStatusCard:ro,canvasImage:io,overlay:lo,overlaySelect:co,overlayPan:uo,overlaySvg:fo,overlayHitLayer:mo,arrowHitArea:po,canvasHandleHit:ho,canvasResizeHandleHit:bo,canvasHandleVisible:go,pin:yo,note:xo,annotationNumberBadge:vo,box:_o,boxNumberBadge:jo,arrowNumberBadge:ko,boxSurface:wo,selected:Co,textInput:Io,textArea:So,select:No,sessionTitleInput:$o,sessionInstructionField:Ro,detailEmpty:Po,emptyState:Bo,payloadModalBody:To,payloadModalToolbar:Ao,payloadViewToggle:Eo,payloadModalActions:Mo,payloadModalPreview:Lo,statusBar:Fo,annotationSummary:Ho},En=[{value:"review",label:"Review"},{value:"change",label:"Change"},{value:"question",label:"Question"}],Mn=[{value:"select",label:"Select",icon:Rs},{value:"pin",label:"Pin",icon:Dn},{value:"box",label:"Box",icon:zn},{value:"arrow",label:"Arrow",icon:Un},{value:"text-note",label:"Note",icon:Gn}],Oo={pin:Dn,box:zn,arrow:Un,"text-note":Gn},Do={pin:"Pin",box:"Box",arrow:"Arrow","text-note":"Note"},zo={review:tn,change:sn,question:nn,issue:nn,idea:tn},It={select:{short:"Select and edit existing markers.",detail:"Use Select to click, drag, reorder, resize, and update markers that are already on the image.",example:"Example: move an existing marker after the screenshot changes."},pin:{short:"Mark a precise spot.",detail:"Use Pin when feedback points to one exact location instead of a broader area.",example:'Example: "This icon is misaligned by 2px."'},box:{short:"Mark an area or component.",detail:"Use Box when the feedback applies to a whole region, card, panel, or bounded UI block.",example:'Example: "This whole card needs tighter padding and a stronger border."'},arrow:{short:"Show direction or relationship.",detail:"Use Arrow when you need to show movement, attachment, flow, or source-to-target intent.",example:'Example: "This tooltip should anchor to this button, not the panel."'},"text-note":{short:"Add a comment-style point marker.",detail:"Use Note when you want a point marker that reads more like a comment or open question.",example:'Example: "Ask design whether this badge should stay."'}},it={question:"#0f766e",change:"#2563eb",issue:"#dc2626",idea:"#d97706",review:"#7c3aed"},Uo=["#7c3aed","#2563eb","#0f766e","#dc2626","#d97706","#111827"],re="review";function ze(o){const l=String(o.displayName||"").trim();return l?`${l} review`:"Annotated session"}function Yn(){return`annotation-${Math.random().toString(36).slice(2,10)}`}function _(o){return!Number.isFinite(o)||o<=0?0:o>=1?1:o}function Se(o){return _(Math.max(.02,o))}function rt(o){return o?[String(o.taskId||"").trim(),String(o.assetId||"").trim(),String(o.path||"").trim()].join("::"):""}function Go(o){if(!(o instanceof HTMLElement))return!1;const l=o.tagName.toLowerCase();return o.isContentEditable?!0:l==="input"||l==="textarea"||l==="select"}function Ie(o){return o.map((l,m)=>({...l,order:m}))}function Qt(o){if(!o)return"Unsaved";const l=new Date(o);return Number.isNaN(l.getTime())?"Unsaved":l.toLocaleString()}function St(o){const l=String(o.createdByActor?.label||"").trim();return l||null}function Yo(o){const l=String(o||"").trim().replace(/\s+/g," ");return l?l.length>110?`${l.slice(0,107)}...`:l:""}function Ln(o,l,m,g=it[re]){const w={id:Yn(),order:0,instruction:"",markerType:re,color:g};if(o==="pin")return{...w,kind:o,x:l.x,y:l.y};if(o==="text-note")return{...w,kind:o,x:l.x,y:l.y};if(o==="box"){const M=m||l;return{...w,kind:o,x:_(Math.min(l.x,M.x)),y:_(Math.min(l.y,M.y)),width:Se(Math.abs(M.x-l.x)),height:Se(Math.abs(M.y-l.y))}}const y=m||l;return{...w,kind:"arrow",x:l.x,y:l.y,x2:y.x,y2:y.y}}function en(o){return o.color?o.color:it[o.markerType||re]}function Ko(o,l){const m=Math.max(l.width,1),g=Math.max(l.height,1),w=o.x*m,y=o.y*g,M=o.x2*m,ne=o.y2*g,Ue=M-w,Ge=ne-y,me=Math.hypot(Ue,Ge)||1,ie=Ue/me,Ye=Ge/me,Ne=Math.max(10,Math.min(16,me-2)),T=Ne*.62,Ke=M-ie*Ne,pe=ne-Ye*Ne,he=-Ye,se=ie;return{shaftX1:w,shaftY1:y,shaftX2:Ke,shaftY2:pe,headPoints:[`${M},${ne}`,`${Ke+he*T},${pe+se*T}`,`${Ke-he*T},${pe-se*T}`].join(" ")}}function Wo(o,l){return{...o,markerType:l,color:o.color||it[l]}}function Xo(o,l){return{...o,id:Yn(),order:l}}function Vo(o,l){const m=String(o||"").trim()||(l?ze(l):"Annotated session");return/\bcopy$/i.test(m)?`${m} 2`:`${m} copy`}function qo(o,l,m){if(l===m||l<0||m<0||l>=o.length||m>=o.length)return o;const g=[...o],[w]=g.splice(l,1);return w?(g.splice(m,0,w),Ie(g)):o}function te(o){return String(Math.round(_(o)*1e3)/10)}function Jo(o){const l=Number.parseFloat(o);return Number.isFinite(l)?_(l/100):null}function Zo(o,l,m){return o.kind==="pin"||o.kind==="text-note"?l==="x"||l==="y"?{...o,[l]:_(m)}:o:o.kind==="box"?l==="x"||l==="y"?{...o,[l]:_(m)}:l==="width"||l==="height"?{...o,[l]:Se(m)}:o:l==="x"||l==="y"||l==="x2"||l==="y2"?{...o,[l]:_(m)}:o}function Qo(o){return o.kind==="pin"||o.kind==="text-note"?[{key:"x",label:"X",value:te(o.x)},{key:"y",label:"Y",value:te(o.y)}]:o.kind==="box"?[{key:"x",label:"X",value:te(o.x)},{key:"y",label:"Y",value:te(o.y)},{key:"width",label:"Width",value:te(o.width)},{key:"height",label:"Height",value:te(o.height)}]:[{key:"x",label:"Start X",value:te(o.x)},{key:"y",label:"Start Y",value:te(o.y)},{key:"x2",label:"End X",value:te(o.x2)},{key:"y2",label:"End Y",value:te(o.y2)}]}function er(o){if(!o)return null;const l=Math.round(o.x*100),m=Math.round(o.y*100),g=Math.round(o.width*100),w=Math.round(o.height*100);return`crop ${l}%, ${m}% size ${g}% x ${w}%`}function tr(o){return Number.isFinite(o)?Math.min(4,Math.max(.25,Number(o.toFixed(2)))):1}function Fn(o){const l=[`Annotated attachment: ${o.title||o.image.displayName}`,`Image: ${o.image.displayName}`,`Image Reference: ${o.image.referenceLabel||o.image.assetId}`,`Task ID: ${o.taskId}`,o.globalInstruction?`Global instruction: ${o.globalInstruction}`:"Global instruction: None provided.","Markers:"];return o.annotations.length===0?(l.push("0. No markers."),l.join(`
1
+ import{j as t,r as a,R as qt}from"./vendor-react-CKJs5o3c.js";import{R as xs,f as Ce,e as Ct,g as vs,t as Bn,M as Jt}from"./index-YJ4k5QNa.js";import{q as _s,m as js,c as Zt,T as Tn,s as ks,a1 as ws,h as An,ai as Cs,R as Is,aj as Ss,ak as Ns,al as $s,am as tn,C as nn,an as Rs,ao as Dn,ap as zn,aq as Un,ar as Gn,g as Ps,f as Bs,b as sn}from"./vendor-icons-C8EED3Oh.js";import"./vendor-markdown-BUxTU7dS.js";import"./vendor-dnd-DRzYolkg.js";import"./vendor-router-BbWMxlnO.js";function Ts({copied:o,disabled:l=!1,label:m,onClick:g,title:w="Copy image reference",ariaLabel:y,className:M=""}){return t.jsx(xs,{copied:o,disabled:l,label:"",onClick:g,title:w,ariaLabel:y,className:M,children:m})}const As="_shell_sf7jc_1",Es="_panel_sf7jc_16",Ms="_sessionPanel_sf7jc_22",Ls="_detailPanel_sf7jc_23",Fs="_sessionContextBar_sf7jc_29",Hs="_sessionContextLeft_sf7jc_40",Os="_sessionContextRight_sf7jc_41",Ds="_sessionContextLabel_sf7jc_56",zs="_sessionContextSpacer_sf7jc_62",Us="_canvasPanel_sf7jc_67",Gs="_canvasWorkspace_sf7jc_74",Ys="_canvasMain_sf7jc_81",Ks="_panelHeader_sf7jc_88",Ws="_panelHeaderText_sf7jc_97",Xs="_panelTitle_sf7jc_101",Vs="_canvasHeading_sf7jc_105",qs="_sessionActions_sf7jc_109",Js="_sessionList_sf7jc_117",Zs="_annotationList_sf7jc_118",Qs="_markerHelpModalBody_sf7jc_133",ea="_openImageModalBody_sf7jc_139",ta="_openImageField_sf7jc_145",na="_openImageActions_sf7jc_149",sa="_markerHelpItem_sf7jc_155",aa="_markerHelpHeader_sf7jc_163",oa="_markerHelpExample_sf7jc_175",ra="_sessionCard_sf7jc_179",ia="_annotationCard_sf7jc_180",la="_sessionEmptyState_sf7jc_197",ca="_sessionCardButton_sf7jc_204",da="_annotationCardButton_sf7jc_214",ua="_sessionCardBody_sf7jc_224",fa="_sessionCardActive_sf7jc_230",ma="_annotationCardActive_sf7jc_231",pa="_annotationMeta_sf7jc_241",ha="_annotationInstructionPreview_sf7jc_248",ba="_annotationPreviewFooter_sf7jc_256",ga="_annotationInstructionEditor_sf7jc_263",ya="_annotationTypeField_sf7jc_269",xa="_annotationInstructionButton_sf7jc_275",va="_annotationInstructionField_sf7jc_284",_a="_sessionMeta_sf7jc_288",ja="_sessionTitle_sf7jc_295",ka="_annotationTitle_sf7jc_296",wa="_sessionTimestamp_sf7jc_302",Ca="_annotationKind_sf7jc_303",Ia="_annotationInstructionTypeIcon_sf7jc_307",Sa="_sessionInstructionPreview_sf7jc_313",Na="_sessionInstructionEditor_sf7jc_321",$a="_sessionCardFooter_sf7jc_327",Ra="_toolRail_sf7jc_334",Pa="_canvasToolRail_sf7jc_343",Ba="_toolbarCluster_sf7jc_364",Ta="_toolbarViewportCluster_sf7jc_371",Aa="_toolbarSeparator_sf7jc_375",Ea="_toolBtn_sf7jc_381",Ma="_toolRailButton_sf7jc_385",La="_toolbarButton_sf7jc_395",Fa="_toolBtnActive_sf7jc_400",Ha="_toolbarActions_sf7jc_407",Oa="_toolbarSelectionActions_sf7jc_416",Da="_toolbarColorPicker_sf7jc_424",za="_colorPickerButton_sf7jc_428",Ua="_colorPickerSwatch_sf7jc_433",Ga="_colorPickerPopover_sf7jc_441",Ya="_colorOption_sf7jc_456",Ka="_colorOptionActive_sf7jc_466",Wa="_toolbarUtilities_sf7jc_473",Xa="_toolbarGeometryFields_sf7jc_481",Va="_toolbarGeometryField_sf7jc_481",qa="_toolbarGeometryLabel_sf7jc_494",Ja="_toolbarGeometryInput_sf7jc_500",Za="_iconButton_sf7jc_505",Qa="_ghostBtn_sf7jc_510",eo="_payloadBtn_sf7jc_511",to="_backToTaskBtn_sf7jc_512",no="_canvasScroller_sf7jc_532",so="_canvasFrame_sf7jc_548",ao="_canvasMedia_sf7jc_555",oo="_canvasStatusOverlay_sf7jc_563",ro="_canvasStatusCard_sf7jc_575",io="_canvasImage_sf7jc_588",lo="_overlay_sf7jc_595",co="_overlaySelect_sf7jc_601",uo="_overlayPan_sf7jc_605",fo="_overlaySvg_sf7jc_609",mo="_overlayHitLayer_sf7jc_618",po="_arrowHitArea_sf7jc_627",ho="_canvasHandleHit_sf7jc_634",bo="_canvasResizeHandleHit_sf7jc_641",go="_canvasHandleVisible_sf7jc_645",yo="_pin_sf7jc_662",xo="_note_sf7jc_663",vo="_annotationNumberBadge_sf7jc_680",_o="_box_sf7jc_705",jo="_boxNumberBadge_sf7jc_714",ko="_arrowNumberBadge_sf7jc_720",wo="_boxSurface_sf7jc_724",Co="_selected_sf7jc_737",Io="_textInput_sf7jc_754",So="_textArea_sf7jc_755",No="_select_sf7jc_737",$o="_sessionTitleInput_sf7jc_762",Ro="_sessionInstructionField_sf7jc_767",Po="_detailEmpty_sf7jc_776",Bo="_emptyState_sf7jc_777",To="_payloadModalBody_sf7jc_789",Ao="_payloadModalToolbar_sf7jc_796",Eo="_payloadViewToggle_sf7jc_803",Mo="_payloadModalActions_sf7jc_804",Lo="_payloadModalPreview_sf7jc_811",Fo="_statusBar_sf7jc_826",Ho="_annotationSummary_sf7jc_838",s={shell:As,panel:Es,sessionPanel:Ms,detailPanel:Ls,sessionContextBar:Fs,sessionContextLeft:Hs,sessionContextRight:Os,sessionContextLabel:Ds,sessionContextSpacer:zs,canvasPanel:Us,canvasWorkspace:Gs,canvasMain:Ys,panelHeader:Ks,panelHeaderText:Ws,panelTitle:Xs,canvasHeading:Vs,sessionActions:qs,sessionList:Js,annotationList:Zs,markerHelpModalBody:Qs,openImageModalBody:ea,openImageField:ta,openImageActions:na,markerHelpItem:sa,markerHelpHeader:aa,markerHelpExample:oa,sessionCard:ra,annotationCard:ia,sessionEmptyState:la,sessionCardButton:ca,annotationCardButton:da,sessionCardBody:ua,sessionCardActive:fa,annotationCardActive:ma,annotationMeta:pa,annotationInstructionPreview:ha,annotationPreviewFooter:ba,annotationInstructionEditor:ga,annotationTypeField:ya,annotationInstructionButton:xa,annotationInstructionField:va,sessionMeta:_a,sessionTitle:ja,annotationTitle:ka,sessionTimestamp:wa,annotationKind:Ca,annotationInstructionTypeIcon:Ia,sessionInstructionPreview:Sa,sessionInstructionEditor:Na,sessionCardFooter:$a,toolRail:Ra,canvasToolRail:Pa,toolbarCluster:Ba,toolbarViewportCluster:Ta,toolbarSeparator:Aa,toolBtn:Ea,toolRailButton:Ma,toolbarButton:La,toolBtnActive:Fa,toolbarActions:Ha,toolbarSelectionActions:Oa,toolbarColorPicker:Da,colorPickerButton:za,colorPickerSwatch:Ua,colorPickerPopover:Ga,colorOption:Ya,colorOptionActive:Ka,toolbarUtilities:Wa,toolbarGeometryFields:Xa,toolbarGeometryField:Va,toolbarGeometryLabel:qa,toolbarGeometryInput:Ja,iconButton:Za,ghostBtn:Qa,payloadBtn:eo,backToTaskBtn:to,canvasScroller:no,canvasFrame:so,canvasMedia:ao,canvasStatusOverlay:oo,canvasStatusCard:ro,canvasImage:io,overlay:lo,overlaySelect:co,overlayPan:uo,overlaySvg:fo,overlayHitLayer:mo,arrowHitArea:po,canvasHandleHit:ho,canvasResizeHandleHit:bo,canvasHandleVisible:go,pin:yo,note:xo,annotationNumberBadge:vo,box:_o,boxNumberBadge:jo,arrowNumberBadge:ko,boxSurface:wo,selected:Co,textInput:Io,textArea:So,select:No,sessionTitleInput:$o,sessionInstructionField:Ro,detailEmpty:Po,emptyState:Bo,payloadModalBody:To,payloadModalToolbar:Ao,payloadViewToggle:Eo,payloadModalActions:Mo,payloadModalPreview:Lo,statusBar:Fo,annotationSummary:Ho},En=[{value:"review",label:"Review"},{value:"change",label:"Change"},{value:"question",label:"Question"}],Mn=[{value:"select",label:"Select",icon:Rs},{value:"pin",label:"Pin",icon:Dn},{value:"box",label:"Box",icon:zn},{value:"arrow",label:"Arrow",icon:Un},{value:"text-note",label:"Note",icon:Gn}],Oo={pin:Dn,box:zn,arrow:Un,"text-note":Gn},Do={pin:"Pin",box:"Box",arrow:"Arrow","text-note":"Note"},zo={review:tn,change:sn,question:nn,issue:nn,idea:tn},It={select:{short:"Select and edit existing markers.",detail:"Use Select to click, drag, reorder, resize, and update markers that are already on the image.",example:"Example: move an existing marker after the screenshot changes."},pin:{short:"Mark a precise spot.",detail:"Use Pin when feedback points to one exact location instead of a broader area.",example:'Example: "This icon is misaligned by 2px."'},box:{short:"Mark an area or component.",detail:"Use Box when the feedback applies to a whole region, card, panel, or bounded UI block.",example:'Example: "This whole card needs tighter padding and a stronger border."'},arrow:{short:"Show direction or relationship.",detail:"Use Arrow when you need to show movement, attachment, flow, or source-to-target intent.",example:'Example: "This tooltip should anchor to this button, not the panel."'},"text-note":{short:"Add a comment-style point marker.",detail:"Use Note when you want a point marker that reads more like a comment or open question.",example:'Example: "Ask design whether this badge should stay."'}},it={question:"#0f766e",change:"#2563eb",issue:"#dc2626",idea:"#d97706",review:"#7c3aed"},Uo=["#7c3aed","#2563eb","#0f766e","#dc2626","#d97706","#111827"],re="review";function ze(o){const l=String(o.displayName||"").trim();return l?`${l} review`:"Annotated session"}function Yn(){return`annotation-${Math.random().toString(36).slice(2,10)}`}function _(o){return!Number.isFinite(o)||o<=0?0:o>=1?1:o}function Se(o){return _(Math.max(.02,o))}function rt(o){return o?[String(o.taskId||"").trim(),String(o.assetId||"").trim(),String(o.path||"").trim()].join("::"):""}function Go(o){if(!(o instanceof HTMLElement))return!1;const l=o.tagName.toLowerCase();return o.isContentEditable?!0:l==="input"||l==="textarea"||l==="select"}function Ie(o){return o.map((l,m)=>({...l,order:m}))}function Qt(o){if(!o)return"Unsaved";const l=new Date(o);return Number.isNaN(l.getTime())?"Unsaved":l.toLocaleString()}function St(o){const l=String(o.createdByActor?.label||"").trim();return l||null}function Yo(o){const l=String(o||"").trim().replace(/\s+/g," ");return l?l.length>110?`${l.slice(0,107)}...`:l:""}function Ln(o,l,m,g=it[re]){const w={id:Yn(),order:0,instruction:"",markerType:re,color:g};if(o==="pin")return{...w,kind:o,x:l.x,y:l.y};if(o==="text-note")return{...w,kind:o,x:l.x,y:l.y};if(o==="box"){const M=m||l;return{...w,kind:o,x:_(Math.min(l.x,M.x)),y:_(Math.min(l.y,M.y)),width:Se(Math.abs(M.x-l.x)),height:Se(Math.abs(M.y-l.y))}}const y=m||l;return{...w,kind:"arrow",x:l.x,y:l.y,x2:y.x,y2:y.y}}function en(o){return o.color?o.color:it[o.markerType||re]}function Ko(o,l){const m=Math.max(l.width,1),g=Math.max(l.height,1),w=o.x*m,y=o.y*g,M=o.x2*m,ne=o.y2*g,Ue=M-w,Ge=ne-y,me=Math.hypot(Ue,Ge)||1,ie=Ue/me,Ye=Ge/me,Ne=Math.max(10,Math.min(16,me-2)),T=Ne*.62,Ke=M-ie*Ne,pe=ne-Ye*Ne,he=-Ye,se=ie;return{shaftX1:w,shaftY1:y,shaftX2:Ke,shaftY2:pe,headPoints:[`${M},${ne}`,`${Ke+he*T},${pe+se*T}`,`${Ke-he*T},${pe-se*T}`].join(" ")}}function Wo(o,l){return{...o,markerType:l,color:o.color||it[l]}}function Xo(o,l){return{...o,id:Yn(),order:l}}function Vo(o,l){const m=String(o||"").trim()||(l?ze(l):"Annotated session");return/\bcopy$/i.test(m)?`${m} 2`:`${m} copy`}function qo(o,l,m){if(l===m||l<0||m<0||l>=o.length||m>=o.length)return o;const g=[...o],[w]=g.splice(l,1);return w?(g.splice(m,0,w),Ie(g)):o}function te(o){return String(Math.round(_(o)*1e3)/10)}function Jo(o){const l=Number.parseFloat(o);return Number.isFinite(l)?_(l/100):null}function Zo(o,l,m){return o.kind==="pin"||o.kind==="text-note"?l==="x"||l==="y"?{...o,[l]:_(m)}:o:o.kind==="box"?l==="x"||l==="y"?{...o,[l]:_(m)}:l==="width"||l==="height"?{...o,[l]:Se(m)}:o:l==="x"||l==="y"||l==="x2"||l==="y2"?{...o,[l]:_(m)}:o}function Qo(o){return o.kind==="pin"||o.kind==="text-note"?[{key:"x",label:"X",value:te(o.x)},{key:"y",label:"Y",value:te(o.y)}]:o.kind==="box"?[{key:"x",label:"X",value:te(o.x)},{key:"y",label:"Y",value:te(o.y)},{key:"width",label:"Width",value:te(o.width)},{key:"height",label:"Height",value:te(o.height)}]:[{key:"x",label:"Start X",value:te(o.x)},{key:"y",label:"Start Y",value:te(o.y)},{key:"x2",label:"End X",value:te(o.x2)},{key:"y2",label:"End Y",value:te(o.y2)}]}function er(o){if(!o)return null;const l=Math.round(o.x*100),m=Math.round(o.y*100),g=Math.round(o.width*100),w=Math.round(o.height*100);return`crop ${l}%, ${m}% size ${g}% x ${w}%`}function tr(o){return Number.isFinite(o)?Math.min(4,Math.max(.25,Number(o.toFixed(2)))):1}function Fn(o){const l=[`Annotated attachment: ${o.title||o.image.displayName}`,`Image: ${o.image.displayName}`,`Image Reference: ${o.image.referenceLabel||o.image.assetId}`,`Task ID: ${o.taskId}`,o.globalInstruction?`Global instruction: ${o.globalInstruction}`:"Global instruction: None provided.","Markers:"];return o.annotations.length===0?(l.push("0. No markers."),l.join(`
2
2
  `)):(o.annotations.forEach((m,g)=>{const w=m.markerType||re,y=er(m.cropHint);l.push(`${g+1}. ${m.kind} (${w})`),l.push(`Instruction: ${m.instruction||"No marker instruction."}`),y&&l.push(`Region: ${y}`)}),l.join(`
3
3
  `))}function Nt(o){return{title:o.title,globalInstruction:o.globalInstruction,annotations:Ie(o.annotations)}}function Hn(o){return JSON.stringify(Nt(o))}function On(o){const l=JSON.parse(o);return Nt({title:String(l?.title||""),globalInstruction:String(l?.globalInstruction||""),annotations:Array.isArray(l?.annotations)?l.annotations:[]})}function nr(o,l){return Nt({title:o?.title||l,globalInstruction:o?.globalInstruction||"",annotations:o?.annotations||[]})}function dr({runtimeMode:o="local",apiBaseUrl:l="",cloudAuthBaseUrl:m="",workspaceId:g="default",sessionLoadReady:w=!0,requestedTarget:y=null,requestedSessionId:M=null,requestedOpenVersion:ne=0,resolveTaskReferenceLabel:Ue,resolveImageReferenceLabel:Ge,onRequestedTargetHandled:me,onOpenTarget:ie,onContextChange:Ye,onBackToTask:Ne}){const T=o==="cloud"&&(m||l)||"",[Ke,pe]=a.useState(y),[he,se]=a.useState([]),[x,$e]=a.useState(null),[$t,We]=a.useState(!1),[Re,Xe]=a.useState(""),[Pe,Ve]=a.useState(""),[N,ae]=a.useState([]),[C,L]=a.useState(null),[lt,an]=a.useState(it[re]),[ct,dt]=a.useState(!1),[$,Be]=a.useState("select"),[Kn,be]=a.useState(!1),[ut,on]=a.useState(!1),[W,X]=a.useState(!1),[rn,h]=a.useState(null),[U,R]=a.useState("saved"),[sr,D]=a.useState(null),[ft,ln]=a.useState(!1),[oe,Rt]=a.useState(null),[le,Pt]=a.useState(!1),[Wn,Bt]=a.useState(!1),[Tt,cn]=a.useState("json"),[mt,At]=a.useState(!1),[pt,Et]=a.useState(!1),[Xn,dn]=a.useState(!1),[Vn,ht]=a.useState(!1),[Mt,bt]=a.useState(""),[qe,un]=a.useState(!1),[ce,Je]=a.useState(!1),[Lt,Ze]=a.useState(!1),[P,Ft]=a.useState(1),[G,Qe]=a.useState(!1),[gt,fn]=a.useState(!1),[yt,et]=a.useState({width:0,height:0}),mn=a.useRef(null),Te=a.useRef(null),Ht=a.useRef(null),pn=a.useRef(null),ge=a.useRef(M),ye=a.useRef(""),xt=a.useRef(0),Ot=a.useRef(""),xe=a.useRef(0),vt=a.useRef(null),hn=a.useRef(0),de=a.useRef(!1),tt=a.useRef(null),Dt=a.useRef(null),ve=a.useRef(null),F=a.useRef(""),A=a.useRef(""),_t=a.useRef(null),V=a.useRef(null),Ae=a.useRef(!1),jt=a.useRef(null),nt=a.useRef(null),st=a.useRef(null),_e=a.useRef(null),Ee=a.useRef(null),Me=a.useRef(null),Le=a.useRef(null),ue=a.useRef(null),q=a.useRef(null),bn=a.useRef(null),gn=a.useRef(null),B=a.useMemo(()=>he.find(e=>e.id===x)||null,[x,he]),J=a.useMemo(()=>`workspaceId=${encodeURIComponent(String(g||"default").trim()||"default")}`,[g]),E=a.useMemo(()=>({"x-taskforce-workspace-id":String(g||"default").trim()||"default"}),[g]),z=a.useMemo(()=>N.find(e=>e.id===C)||null,[N,C]),Z=a.useMemo(()=>rt(y),[y]),je=typeof ie=="function",d=je?y:Ke,kt=a.useMemo(()=>{const e=String(d?.taskId||"").trim();if(!e)return"";const n=Ue?.(e).trim()||"";if(n)return n;const r=String(d?.taskReferenceLabel||"").trim();return r&&r!==e?r:n||e},[d?.taskId,d?.taskReferenceLabel,Ue]),at=a.useMemo(()=>{const e=String(d?.assetId||"").trim();if(!e)return"";const n=Ge?.(e).trim()||"";return n||String(d?.imageReferenceLabel||"").trim()},[d?.assetId,d?.imageReferenceLabel,Ge]),zt=a.useMemo(()=>N.findIndex(e=>e.id===C),[N,C]),Ut=z?.color||lt,yn=a.useMemo(()=>Nt({title:Re,globalInstruction:Pe,annotations:N}),[N,Pe,Re]),Fe=a.useMemo(()=>Hn(yn),[yn]),xn=Fe!==A.current,b=a.useMemo(()=>({width:Math.max(yt.width*P,0),height:Math.max(yt.height*P,0)}),[yt.height,yt.width,P]),He=a.useMemo(()=>({visibleRadius:7,hitRadius:11}),[]),Gt=a.useMemo(()=>`0 0 ${Math.max(b.width,1)} ${Math.max(b.height,1)}`,[b.height,b.width]),ke=a.useMemo(()=>{const e=Te.current;return e?P>1||b.width>e.clientWidth+1||b.height>e.clientHeight+1:P>1},[b.height,b.width,P]),Yt=`${Math.round(P*100)}%`,Kt=a.useMemo(()=>{const e=new Map;return N.forEach((n,r)=>{e.set(n.id,r+1)}),e},[N]);a.useEffect(()=>{ge.current=M},[M]),a.useEffect(()=>{const e=pn.current;if(!e||!C)return;e.focus();const n=e.value.length;e.setSelectionRange(n,n)},[C]),a.useEffect(()=>{ve.current=x},[x]),a.useEffect(()=>{We(!1)},[x]),a.useEffect(()=>{if(!z){dt(!1);return}an(z.color||it[z.markerType||re])},[z]);const wt=a.useCallback(async e=>{const n=typeof performance<"u"?performance.now():Date.now(),r=await Ce(`/api/taskforce/annotated-attachments/sessions?${J}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...E},body:JSON.stringify({taskId:e.taskId,baseImageAssetId:e.assetId,title:ze(e),globalInstruction:"",annotations:[]})},T),i=await r.json().catch(()=>({}));if(!r.ok)throw new Error(String(i?.error||"Failed to create session."));const c=i?.session;if(!c?.id)throw new Error("Failed to create session.");return Ct("annotated_session_create_completed",{assetId:e.assetId,taskId:e.taskId||null,sessionId:c.id,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-n),debugTimings:i?.debugTimings||null,serverTiming:typeof r.headers?.get=="function"&&r.headers.get("server-timing")||null}),c},[E,T,J]),vn=a.useCallback(e=>new Promise((n,r)=>{const i=new FileReader;i.onload=()=>n(typeof i.result=="string"?i.result:""),i.onerror=()=>r(i.error||new Error("Failed to read clipboard image.")),i.readAsDataURL(e)}),[]),I=a.useCallback(()=>{tt.current!==null&&(window.clearTimeout(tt.current),tt.current=null),st.current!==null&&(window.clearTimeout(st.current),st.current=null)},[]),Oe=a.useCallback(e=>{Xe(e.title),Ve(e.globalInstruction),ae(e.annotations),L(n=>n&&e.annotations.some(r=>r.id===n)?n:e.annotations[0]?.id||null)},[]),fe=a.useCallback((e,n)=>{const r=ze(n||d||{assetId:e.baseImageAssetId,displayName:"Annotated session"}),i=nr(e,r),c=Hn(i);de.current=!0,I(),Oe(i),A.current=c,F.current=c,_t.current=null,Ae.current=!1,jt.current=null,nt.current=null,D(null),R("saved"),X(!1)},[d,Oe,I]),Wt=a.useCallback(e=>{de.current=!0,I(),se([]),$e(null),be(!1),We(!1),Xe(ze(e)),Ve(""),ae([]),L(null),A.current="",F.current="",_t.current=null,Ae.current=!1,jt.current=null,nt.current=null,Rt(null),Bt(!1),D(null),R("saved"),X(!1)},[I]),we=a.useCallback(async(e,n,r)=>{const i=ve.current;if(!i)return!0;if(e===A.current)return V.current||(D(null),R("saved")),!0;if(V.current){if(Ae.current=!0,!r?.waitForInFlight||!await V.current)return!1;const f=F.current;return f===A.current?!0:we(f,n,r)}I();const c=On(e);jt.current=i,_t.current=e,X(!0),h(null),D(null),R("saving");const p=(async()=>{try{const u=await Ce(`/api/taskforce/annotated-attachments/sessions/${encodeURIComponent(i)}?${J}`,{method:"PATCH",credentials:"include",headers:{"Content-Type":"application/json",...E},body:JSON.stringify(c)},T),f=await u.json().catch(()=>({}));if(!u.ok)throw new Error(String(f?.error||"Failed to save session."));const v=f?.session;if(!v?.id)throw new Error("Failed to save session.");se(Vt=>{const Rn=Vt.findIndex(ys=>ys.id===v.id);if(Rn===-1)return[v,...Vt];const Pn=[...Vt];return Pn[Rn]=v,Pn}),A.current=e,nt.current=null,D(null);const k=ve.current===v.id,S=F.current,K=S!==e,ot=Ae.current||K;return Ae.current=!1,k&&!ot?(de.current=!0,Oe(c),R("saved")):!ot&&S===A.current?R("saved"):R("pending"),!0}catch(u){const f=u instanceof Error?u.message:"Failed to save session.";return h(f),D(f),R("error"),nt.current!==e&&ve.current===i&&F.current===e&&(nt.current=e,st.current=window.setTimeout(()=>{st.current=null,!(ve.current!==i||F.current!==e)&&we(e,n,{waitForInFlight:!0})},1500)),!1}finally{_t.current=null,V.current=null,jt.current=null,X(!1)}})();V.current=p;const j=await p;if(j){const u=F.current;if(u!==A.current)return we(u,n,r)}return j},[Oe,I,E,T,J]),_n=a.useCallback(e=>{if(ve.current){if(F.current===A.current){D(null),V.current||R("saved");return}U!=="saving"&&R("pending"),I(),tt.current=window.setTimeout(()=>{tt.current=null,we(F.current,"structure")},e)}},[I,we,U]),Y=a.useCallback(e=>{Dt.current=e},[]),H=a.useCallback(async e=>{I();const n=F.current;return!ve.current||n===A.current?(D(null),V.current||R("saved"),!0):we(n,e,{waitForInFlight:!0})},[I,we]),qn=a.useCallback(()=>{const e=A.current;e&&(I(),de.current=!0,Oe(On(e)),D(null),R("saved"),h(null))},[Oe,I]),Q=a.useCallback(async(e,n)=>{const r=typeof performance<"u"?performance.now():Date.now(),i=JSON.stringify({targetKey:rt(e),requestedSessionId:n?.requestedSessionId??null,autoCreateIfEmpty:n?.autoCreateIfEmpty===!0});if(vt.current===i)return;const c=xe.current+1;xe.current=c,vt.current=i,on(!0),h(null);try{const p=new URLSearchParams;g&&p.set("workspaceId",g),e.taskId&&p.set("taskId",e.taskId),p.set("imageAssetId",e.assetId);const j=await Ce(`/api/taskforce/annotated-attachments/sessions?${p.toString()}`,{credentials:"include",headers:E,cache:"no-store"},T),u=await j.json().catch(()=>({}));if(!j.ok)throw new Error(String(u?.error||"Failed to load annotated attachment sessions."));const f=Array.isArray(u?.sessions)?u.sessions:[];if(Ct("annotated_sessions_loaded",{assetId:e.assetId,taskId:e.taskId||null,requestedSessionId:n?.requestedSessionId??null,autoCreateIfEmpty:n?.autoCreateIfEmpty===!0,sessionCount:f.length,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-r),serverTiming:typeof j.headers?.get=="function"&&j.headers.get("server-timing")||null}),f.length===0&&n?.autoCreateIfEmpty&&String(e.assetId||"").trim()){const S=n?.requestedSessionId??ge.current;if(ge.current=null,S&&h("The previously selected annotation session could not be restored."),xe.current!==c)return;const K=await wt(e);if(Ct("annotated_sessions_auto_created_after_empty_load",{assetId:e.assetId,taskId:e.taskId||null,sessionId:K.id,totalDurationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-r)}),xe.current!==c)return;se([K]),$e(K.id),be(!1),fe(K,e);return}if(xe.current!==c)return;se(f),be(f.length===0);const v=n?.requestedSessionId??ge.current;ge.current=null;const k=f.find(S=>S.id===v)||f[0]||null;v&&!k&&h("The previously selected annotation session could not be restored."),$e(k?.id||null),k?fe(k,e):(de.current=!0,I(),Xe(ze(e)),Ve(""),ae([]),L(null),A.current="",F.current="",D(null),R("saved"))}catch(p){if(xe.current!==c)return;h(p instanceof Error?p.message:"Failed to load sessions.")}finally{vt.current===i&&(vt.current=null),xe.current===c&&on(!1)}},[I,wt,E,T,fe,g]),Jn=a.useCallback(async()=>{if(typeof navigator>"u"||!navigator.clipboard||typeof navigator.clipboard.read!="function"){h("Clipboard image paste is not supported in this environment.");return}fn(!0),h(null),hn.current=Date.now()+2e3;try{const n=(await navigator.clipboard.read()).find(v=>v.types.some(k=>k.startsWith("image/"))),r=n?.types.find(v=>v.startsWith("image/"))||"";if(!n||!r)throw new Error("No image found on the clipboard.");const i=await n.getType(r),c=await vn(i);if(!c)throw new Error("Failed to read clipboard image.");const p=r==="image/jpeg"?"jpg":r==="image/webp"?"webp":r==="image/gif"?"gif":"png",j=await fetch("/api/taskforce/context-upload",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...E},body:JSON.stringify({file:c,originalName:`pasted-image.${p}`,workspaceId:String(g||"default").trim()||"default"})}),u=await j.json().catch(()=>({}));if(!j.ok||!u?.success||typeof u?.assetId!="string"||typeof u?.path!="string")throw new Error(String(u?.error||"Failed to paste image into Image Notes."));const f={assetId:u.assetId,imageReferenceLabel:typeof u?.referenceLabel=="string"?u.referenceLabel:void 0,path:u.path,displayName:typeof u?.displayName=="string"&&u.displayName.trim().length>0?u.displayName.trim():"Pasted image"};ge.current=null,je?(ye.current="",ie?.(f,{sessionId:null})):(pe(f),ye.current=rt(f),Q(f,{autoCreateIfEmpty:!0}))}catch(e){h(e instanceof Error?e.message:"Failed to paste image.")}finally{fn(!1)}},[je,Q,ie,vn,E,g]),Zn=a.useCallback(async()=>{const e=Mt.trim();if(!e){h("Enter an image reference to open.");return}un(!0),h(null);try{const n=new URLSearchParams({workspaceId:String(g||"default").trim()||"default"}),r=await Ce(`/api/taskforce/annotated-attachments/images/${encodeURIComponent(e)}?${n.toString()}`,{method:"GET",credentials:"include",headers:E}),i=await r.json().catch(()=>({}));if(!r.ok||!i?.target||typeof i.target.assetId!="string"||typeof i.target.path!="string")throw new Error(String(i?.error||"Failed to open image reference."));const c={assetId:i.target.assetId,path:i.target.path,displayName:typeof i.target.displayName=="string"&&i.target.displayName.trim().length>0?i.target.displayName.trim():"Image attachment",taskId:typeof i.target.taskId=="string"&&i.target.taskId.trim().length>0?i.target.taskId.trim():void 0,taskReferenceLabel:typeof i.target.taskReferenceLabel=="string"&&i.target.taskReferenceLabel.trim().length>0?i.target.taskReferenceLabel.trim():void 0,imageReferenceLabel:typeof i.target.imageReferenceLabel=="string"&&i.target.imageReferenceLabel.trim().length>0?i.target.imageReferenceLabel.trim():void 0};ge.current=null,ht(!1),bt(""),je?(ye.current="",ie?.(c,{sessionId:null})):(pe(c),ye.current=rt(c),Q(c,{autoCreateIfEmpty:!0}))}catch(n){h(n instanceof Error?n.message:"Failed to open image reference.")}finally{un(!1)}},[je,Q,ie,Mt,E,g]),jn=a.useCallback(e=>{se(n=>{const r=n.findIndex(c=>c.id===e.id);if(r===-1)return[e,...n];const i=[...n];return i[r]=e,i}),$e(e.id),fe(e,d)},[d,fe]),kn=a.useCallback(e=>{se(n=>{const r=n.filter(c=>c.id!==e),i=r[0]||null;return $e(i?.id||null),i?fe(i,d):(de.current=!0,I(),Xe(ze(d||{displayName:"Annotated session"})),Ve(""),ae([]),L(null),A.current="",F.current="",D(null),R("saved")),r})},[d,I,fe]);a.useEffect(()=>{if(!y)return;if(je||pe(n=>n&&rt(n)===Z&&n.taskReferenceLabel===y.taskReferenceLabel&&n.imageReferenceLabel===y.imageReferenceLabel&&n.displayName===y.displayName?n:y),!w){Z&&(Z!==ye.current||ne!==xt.current)&&Z!==Ot.current&&(Wt(y),Ot.current=Z,xt.current=ne,Ct("annotated_sessions_load_deferred",{assetId:y.assetId,taskId:y.taskId||null,requestedTargetKey:Z})),me?.();return}Z&&(Z!==ye.current||ne!==xt.current)&&(Wt(y),ye.current=Z,xt.current=ne,Ot.current="",Q(y,{autoCreateIfEmpty:!0})),me?.()},[je,Q,me,ne,y,Z,Wt,M,w]),a.useEffect(()=>{d&&Ye?.({target:d,sessionId:x})},[d,Ye,x]),a.useEffect(()=>{if(!d||typeof document>"u"||!w)return;const e=()=>{Date.now()<hn.current||F.current!==A.current||W||ut||Q(d,{requestedSessionId:x})},n=()=>{document.visibilityState==="visible"&&e()};return document.addEventListener("visibilitychange",n),()=>{document.removeEventListener("visibilitychange",n)}},[d,Q,ut,W,x,w]),a.useEffect(()=>{if(!d?.path){Je(!1),Ze(!1),et({width:0,height:0});return}Je(!0),Ze(!1),et({width:0,height:0}),Ft(1),Qe(!1)},[d?.path]),a.useEffect(()=>{if(!ce)return;const e=Ht.current;!e||!e.complete||e.naturalWidth<=0||e.naturalHeight<=0||(et({width:e.naturalWidth,height:e.naturalHeight}),Je(!1),Ze(!1))},[d?.path,ce]),a.useEffect(()=>{ke||Qe(!1)},[ke]),a.useEffect(()=>{Rt(null)},[x]),a.useEffect(()=>{if(F.current=Fe,de.current){de.current=!1;return}if(!x){I(),D(null),R("saved");return}if(Fe===A.current){I(),V.current||(D(null),R("saved"));return}const e=Dt.current;if(Dt.current=null,U==="error"&&e===null)return;const n=e??600;if(V.current){Ae.current=!0,R("pending");return}_n(n)},[I,Fe,U,_n,x]),a.useEffect(()=>{x&&(V.current||Fe===A.current&&U!=="error"&&U!=="saved"&&(D(null),R("saved")))},[Fe,U,x]),a.useEffect(()=>{if(typeof window>"u")return;const e=n=>{F.current!==A.current&&(n.preventDefault(),n.returnValue="")};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[]),a.useEffect(()=>{if(typeof document>"u")return;const e=()=>{document.visibilityState==="hidden"&&H("visibility-hidden")};return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[H]),a.useEffect(()=>{if(!ct||typeof document>"u")return;const e=n=>{const r=n.target;r instanceof Node&&(bn.current?.contains(r)||dt(!1))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[ct]),a.useEffect(()=>{if(!$t||typeof document>"u")return;const e=n=>{const r=n.target;r instanceof Node&&(gn.current?.contains(r)||We(!1))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[$t]),a.useEffect(()=>()=>{I()},[I]),a.useEffect(()=>{if(!le)return;const e=window.setTimeout(()=>Pt(!1),2e3);return()=>window.clearTimeout(e)},[le]),a.useEffect(()=>{if(!mt)return;const e=window.setTimeout(()=>At(!1),2e3);return()=>window.clearTimeout(e)},[mt]),a.useEffect(()=>{if(!pt)return;const e=window.setTimeout(()=>Et(!1),2e3);return()=>window.clearTimeout(e)},[pt]);const ee=a.useCallback((e,n,r=300)=>{ae(i=>Ie(i.map(c=>c.id===e?n(c):c))),Y(r)},[Y]),Qn=a.useCallback(e=>{z&&(ee(z.id,n=>({...n,color:e})),an(e),dt(!1))},[z,ee]),wn=a.useCallback(async()=>{if(!(!d||!await H("session-switch"))){X(!0),h(null);try{const n=await wt(d);be(!1),await Q(d,{requestedSessionId:n.id,autoCreateIfEmpty:!1}),Be("select")}catch(n){h(n instanceof Error?n.message:"Failed to create session."),be(!0)}finally{X(!1)}}},[d,wt,H,Q]),es=a.useCallback(e=>{if(e!=="select"&&!B){Qe(!1),h("No session exists for this image yet."),be(!0);return}h(null),be(!1),Qe(!1),Be(e)},[B]),ts=a.useCallback(async()=>{if(!(!d||!B||!await H("duplicate"))){X(!0),h(null);try{const n=Ie(N.map((p,j)=>Xo(p,j))),r=await Ce(`/api/taskforce/annotated-attachments/sessions?${J}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...E},body:JSON.stringify({taskId:d.taskId,baseImageAssetId:d.assetId,title:Vo(Re||B.title,d),globalInstruction:Pe,annotations:n})},T),i=await r.json().catch(()=>({}));if(!r.ok)throw new Error(String(i?.error||"Failed to duplicate session."));const c=i?.session;if(!c?.id)throw new Error("Failed to duplicate session.");jn(c),Be("select")}catch(n){h(n instanceof Error?n.message:"Failed to duplicate session.")}finally{X(!1)}}},[d,N,Pe,Re,jn,H,E,T,B,J]),ns=a.useCallback(async()=>H("manual"),[H]),Cn=a.useCallback(async()=>{if(x){ln(!0),h(null);try{const e=await Ce(`/api/taskforce/annotated-attachments/sessions/${encodeURIComponent(x)}/payload?${J}`,{credentials:"include",headers:E},T),n=await e.json().catch(()=>({}));if(!e.ok)throw new Error(String(n?.error||"Failed to load payload preview."));Rt(n?.payload||null)}catch(e){h(e instanceof Error?e.message:"Failed to load payload preview.")}finally{ln(!1)}}},[E,T,x,J]),ss=a.useCallback(()=>{x&&H("payload-preview").then(e=>{e&&(Bt(!0),Cn())})},[H,Cn,x]),In=a.useCallback(async e=>{if(!oe||!navigator.clipboard||typeof navigator.clipboard.writeText!="function"){h("Clipboard copy is not available in this browser.");return}try{const n=e==="json"?JSON.stringify(oe,null,2):Fn(oe);await navigator.clipboard.writeText(n),Pt(e)}catch(n){h(n instanceof Error?n.message:"Failed to copy payload content."),Pt(!1)}},[oe]),as=a.useCallback(async()=>{if(!kt||!navigator.clipboard||typeof navigator.clipboard.writeText!="function"){h("Clipboard copy is not available in this browser.");return}try{await navigator.clipboard.writeText(kt),At(!0)}catch(e){h(e instanceof Error?e.message:"Failed to copy task id."),At(!1)}},[kt]),os=a.useCallback(async()=>{if(!at||!navigator.clipboard||typeof navigator.clipboard.writeText!="function"){h("Clipboard copy is not available in this browser.");return}try{await navigator.clipboard.writeText(at),Et(!0)}catch(e){h(e instanceof Error?e.message:"Failed to copy image reference."),Et(!1)}},[at]),rs=a.useCallback(async()=>{if(!x||!await H("delete-session"))return;const n=(B?.title||"Untitled session").trim()||"Untitled session";if(window.confirm(`Delete the annotated attachment session "${n}"?`)){X(!0),h(null);try{const r=await Ce(`/api/taskforce/annotated-attachments/sessions/${encodeURIComponent(x)}?${J}`,{method:"DELETE",credentials:"include",headers:E},T),i=await r.json().catch(()=>({}));if(!r.ok)throw new Error(String(i?.error||"Failed to delete session."));kn(x),Be("select")}catch(r){h(r instanceof Error?r.message:"Failed to delete session.")}finally{X(!1)}}},[H,kn,E,T,B,x,J]),Xt=a.useCallback(()=>{C&&(ae(e=>Ie(e.filter(n=>n.id!==C))),L(null),Y(300))},[Y,C]),De=a.useCallback(e=>{const n=tr(e),r=Te.current;if(!r||n===P){Ft(n);return}const i=(r.scrollLeft+r.clientWidth/2)*(n/P)-r.clientWidth/2,c=(r.scrollTop+r.clientHeight/2)*(n/P)-r.clientHeight/2;Ft(n),window.requestAnimationFrame(()=>{r.scrollLeft=Math.max(0,i),r.scrollTop=Math.max(0,c)})},[P]),is=a.useCallback(()=>{De(P+.25)},[De,P]),ls=a.useCallback(()=>{De(P-.25)},[De,P]),cs=a.useCallback(()=>{De(1);const e=Te.current;e&&window.requestAnimationFrame(()=>{e.scrollLeft=0,e.scrollTop=0})},[De]),Sn=a.useCallback(e=>{C&&ae(n=>{const r=n.findIndex(c=>c.id===C);if(r===-1)return n;const i=e==="up"?r-1:r+1;return i<0||i>=n.length?n:(Y(300),qo(n,r,i))})},[Y,C]);a.useEffect(()=>{if(!C)return;const e=n=>{n.key==="Delete"&&(Go(n.target)||(n.preventDefault(),Xt()))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[Xt,C]);const O=a.useCallback(e=>{const n=mn.current?.getBoundingClientRect();return!n||n.width<=0||n.height<=0?null:{x:_((e.clientX-n.left)/n.width),y:_((e.clientY-n.top)/n.height)}},[]),ds=a.useCallback(e=>{if(G&&ke){const i=Te.current;if(!i)return;q.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,scrollLeft:i.scrollLeft,scrollTop:i.scrollTop},e.currentTarget.setPointerCapture(e.pointerId),e.preventDefault();return}if(!x)return;if($==="select"){L(null);return}const n=O(e);if(!n)return;if($==="pin"||$==="text-note"){const i=Ln($,n,n,lt);ae(c=>Ie([...c,i])),L(i.id),Y(300),Be("select");return}_e.current=n;const r=Ln($,n,n,lt);ue.current={annotationId:r.id,kind:$},e.currentTarget.setPointerCapture?.(e.pointerId),ae(i=>Ie([...i,r])),L(r.id),Y(300)},[ke,lt,Y,G,O,x,$]),us=a.useCallback(e=>{if(q.current?.pointerId===e.pointerId){e.currentTarget.releasePointerCapture?.(e.pointerId);return}if(!_e.current||!ue.current||$!=="box"&&$!=="arrow")return;const n=O(e);_e.current=null,ue.current=null,e.currentTarget.releasePointerCapture?.(e.pointerId),n&&Be("select")},[O,$]),Nn=a.useCallback((e,n)=>{if($!=="select"||G)return;const r=O(e);r&&(Ee.current={annotationId:n.id,originPointer:r,originAnnotation:n},L(n.id),e.stopPropagation())},[G,O,$]),fs=a.useCallback(e=>{if(q.current?.pointerId===e.pointerId){const u=Te.current;if(!u)return;const f=e.clientX-q.current.startX,v=e.clientY-q.current.startY;u.scrollLeft=q.current.scrollLeft-f,u.scrollTop=q.current.scrollTop-v;return}if(ue.current&&_e.current){const u=O(e);if(!u)return;const{annotationId:f,kind:v}=ue.current,k=_e.current;ee(f,S=>v==="box"&&S.kind==="box"?{...S,x:_(Math.min(k.x,u.x)),y:_(Math.min(k.y,u.y)),width:Se(Math.abs(u.x-k.x)),height:Se(Math.abs(u.y-k.y))}:v==="arrow"&&S.kind==="arrow"?{...S,x:k.x,y:k.y,x2:u.x,y2:u.y}:S);return}if(Me.current){const u=O(e);if(!u)return;const{annotationId:f,originPointer:v,originAnnotation:k}=Me.current,S=u.x-v.x,K=u.y-v.y;ee(f,()=>({...k,width:Se(k.width+S),height:Se(k.height+K)}));return}if(Le.current){const u=O(e);if(!u)return;const{annotationId:f,endpoint:v,originPointer:k,originAnnotation:S}=Le.current,K=u.x-k.x,ot=u.y-k.y;ee(f,()=>v==="tail"?{...S,x:_(S.x+K),y:_(S.y+ot)}:{...S,x2:_(S.x2+K),y2:_(S.y2+ot)});return}if(!Ee.current)return;const n=O(e);if(!n)return;const{annotationId:r,originPointer:i,originAnnotation:c}=Ee.current,p=n.x-i.x,j=n.y-i.y;ee(r,()=>c.kind==="pin"||c.kind==="text-note"?{...c,x:_(c.x+p),y:_(c.y+j)}:c.kind==="box"?{...c,x:_(c.x+p),y:_(c.y+j)}:{...c,x:_(c.x+p),y:_(c.y+j),x2:_(c.x2+p),y2:_(c.y2+j)})},[O,ee]),ms=a.useCallback(()=>{_e.current=null,Ee.current=null,Me.current=null,Le.current=null,ue.current=null,q.current=null},[]),ps=a.useCallback(()=>{_e.current=null,Ee.current=null,Me.current=null,Le.current=null,ue.current=null,q.current=null},[]),hs=a.useCallback(()=>{Ee.current=null,Me.current=null,Le.current=null,ue.current=null,q.current=null},[]),bs=a.useCallback((e,n)=>{if($!=="select"||G)return;const r=O(e);r&&(Me.current={annotationId:n.id,originPointer:r,originAnnotation:n},L(n.id),e.stopPropagation())},[G,O,$]),$n=a.useCallback((e,n,r)=>{if($!=="select"||G)return;const i=O(e);i&&(Le.current={annotationId:n.id,originPointer:i,originAnnotation:n,endpoint:r},L(n.id),e.stopPropagation())},[G,O,$]),gs=B?.updatedAt?Qt(B.updatedAt):"Not saved yet";return t.jsxs("div",{className:s.shell,children:[t.jsxs("section",{className:`tf-surface-panel ${s.panel} ${s.sessionPanel}`,children:[t.jsx("div",{className:s.sessionContextBar,children:d?.taskId?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:s.sessionContextLeft,children:Ne?t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${s.ghostBtn} ${s.backToTaskBtn}`,onClick:()=>{H("back-to-task").then(e=>{e&&d.taskId&&Ne(d.taskId)})},"aria-label":"Back to task",title:"Back to task",children:t.jsx(_s,{size:16})}):t.jsx("div",{className:s.sessionContextSpacer,"aria-hidden":"true"})}),t.jsx("div",{className:s.sessionContextRight,children:t.jsx(vs,{copied:mt,onClick:()=>{as()},title:"Copy task id",ariaLabel:mt?"Copied task id":"Copy task id",label:kt})})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:s.sessionContextLeft,children:t.jsx("span",{className:`tf-label-micro ${s.sessionContextLabel}`,children:"Unattached Image"})}),t.jsx("div",{className:s.sessionContextRight,children:t.jsx("div",{className:s.sessionContextSpacer,"aria-hidden":"true"})})]})}),t.jsxs("div",{className:s.panelHeader,children:[t.jsxs("div",{className:s.panelHeaderText,children:[t.jsx("div",{className:`tf-heading-card ${s.panelTitle}`,children:"Sessions"}),d?null:t.jsx("div",{className:"tf-text-secondary",children:"Open an image attachment to begin"})]}),t.jsx("div",{className:s.sessionActions,children:t.jsx("button",{type:"button",className:`tf-control-icon ${s.iconButton}`,onClick:()=>{wn()},disabled:!d||W,"aria-label":"Create session",title:"Create session",children:t.jsx(js,{size:16})})})]}),d?ut?t.jsx("div",{className:s.emptyState,children:t.jsx("p",{className:"tf-empty-copy",children:"Loading sessions…"})}):t.jsx("div",{className:`tf-scrollbar ${s.sessionList}`,children:he.length===0?t.jsxs("div",{className:s.sessionEmptyState,children:[t.jsx("div",{className:`tf-heading-card ${s.sessionTitle}`,children:"No sessions yet"}),t.jsx("div",{className:`tf-text-secondary ${s.annotationSummary}`,children:"Create the first annotation session for this image."})]}):he.map(e=>{const n=x===e.id,r=n&&$t,i=Yo(n?Pe:e.globalInstruction),c=(n?Re:e.title)||"Untitled session";return t.jsxs("div",{className:`tf-surface-elevated ${s.sessionCard} ${n?s.sessionCardActive:""}`,ref:n?gn:void 0,onBlur:r?p=>{const j=p.relatedTarget;j instanceof Node&&p.currentTarget.contains(j)||We(!1)}:void 0,children:[r?t.jsxs("div",{className:s.sessionCardBody,children:[t.jsxs("div",{className:s.sessionMeta,children:[t.jsx("label",{className:"tf-field-label",htmlFor:"annotated-session-title",children:"Session title"}),t.jsx("input",{id:"annotated-session-title",className:`tf-field-shell ${s.textInput} ${s.sessionTitleInput}`,value:Re,onChange:p=>{Xe(p.target.value),Y(600)},placeholder:"Session title"}),t.jsx("span",{className:`tf-text-meta ${s.sessionTimestamp}`,children:Qt(e.updatedAt)})]}),St(e)?t.jsxs("div",{className:`tf-text-secondary ${s.sessionCreator}`,children:["Created by ",St(e)]}):null,t.jsxs("div",{className:s.sessionInstructionEditor,children:[t.jsx("label",{className:"tf-field-label",htmlFor:"annotated-session-instruction",children:"Session instruction"}),t.jsx("textarea",{id:"annotated-session-instruction",className:`tf-field-shell ${s.textArea} ${s.sessionInstructionField}`,value:Pe,onChange:p=>{Ve(p.target.value),Y(600)},placeholder:"Add overall instructions, context, or framing for this session."})]}),t.jsxs("div",{className:`tf-text-secondary ${s.annotationSummary}`,children:[e.annotations.length," annotation",e.annotations.length===1?"":"s"]})]}):t.jsxs("button",{type:"button",className:s.sessionCardButton,onClick:()=>{if(n){We(!0);return}H("session-switch").then(p=>{p&&($e(e.id),fe(e,d))})},"aria-pressed":n,children:[t.jsxs("div",{className:s.sessionMeta,children:[t.jsx("span",{className:`tf-heading-card ${s.sessionTitle}`,children:c}),t.jsx("span",{className:`tf-text-meta ${s.sessionTimestamp}`,children:Qt(e.updatedAt)})]}),St(e)?t.jsxs("div",{className:`tf-text-secondary ${s.sessionCreator}`,children:["Created by ",St(e)]}):null,i?t.jsx("div",{className:`tf-text-secondary ${s.sessionInstructionPreview}`,children:i}):null,t.jsxs("div",{className:`tf-text-secondary ${s.annotationSummary}`,children:[e.annotations.length," annotation",e.annotations.length===1?"":"s"]})]}),n?t.jsx("div",{className:s.sessionCardFooter,children:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:`tf-button-ghost ${s.toolRailButton} ${s.iconButton}`,onClick:()=>{ts()},disabled:W,"aria-label":"Duplicate session",title:`Duplicate session "${c}"`,children:t.jsx(Zt,{size:16})}),t.jsx("button",{type:"button",className:`tf-button-ghost ${s.toolRailButton} ${s.iconButton}`,onClick:()=>{rs()},disabled:W,"aria-label":"Delete session",title:`Delete session "${c}"`,children:t.jsx(Tn,{size:16})})]})}):null]},e.id)})}):t.jsxs("div",{className:s.emptyState,children:[t.jsx("strong",{className:"tf-empty-title",children:"No image selected"}),t.jsx("p",{className:"tf-empty-copy",children:"Open an image attachment from a task to start an annotated session."})]})]}),t.jsxs("section",{className:`tf-surface-panel ${s.panel} ${s.canvasPanel}`,children:[t.jsxs("div",{className:s.panelHeader,children:[t.jsxs("div",{className:s.canvasHeading,children:[t.jsx("div",{className:"tf-heading-card",children:d?.displayName||"Annotated attachment"}),t.jsx("div",{className:"tf-text-secondary",children:B?`${N.length} markers · ${gs}`:"Pick or create a session"})]}),at?t.jsx(Ts,{copied:pt,onClick:()=>{os()},title:"Copy image reference",ariaLabel:pt?"Copied image reference":"Copy image reference",label:at}):null]}),t.jsxs("div",{className:s.toolRail,children:[t.jsxs("div",{className:`${s.toolbarCluster} ${s.toolbarViewportCluster}`,children:[t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${s.ghostBtn} ${s.toolbarButton}`,onClick:()=>{ns()},disabled:!B||W||!xn&&U!=="error","aria-label":W?"Saving session":"Save session",title:W?"Saving session":"Save session",children:t.jsx(ks,{size:18})}),t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${s.ghostBtn} ${s.toolbarButton}`,onClick:()=>ht(!0),disabled:qe,"aria-label":"Open image",title:"Open image",children:t.jsx(ws,{size:18})}),t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${s.ghostBtn} ${s.toolbarButton}`,onClick:()=>{Jn()},disabled:gt,"aria-label":gt?"Pasting image":"Paste image",title:gt?"Pasting image":"Paste image",children:gt?t.jsx(An,{size:18,className:Bn.spin}):t.jsx(Cs,{size:18})}),t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${s.ghostBtn} ${s.toolbarButton}`,onClick:()=>{B&&qn()},disabled:!B||!xn,"aria-label":"Reset unsaved changes",title:"Reset unsaved changes",children:t.jsx(Is,{size:18})}),t.jsx("button",{type:"button",className:`tf-button-ghost ${s.toolRailButton} ${s.iconButton}`,onClick:ls,disabled:!d||ce||P<=.25,"aria-label":"Zoom out",children:t.jsx(Ss,{size:18})}),t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${s.ghostBtn} ${s.toolbarButton}`,onClick:cs,disabled:!d||ce||P===1,"aria-label":`Reset zoom to 100 percent (currently ${Yt})`,title:`Reset zoom to 100% (currently ${Yt})`,children:t.jsx("span",{children:Yt})}),t.jsx("button",{type:"button",className:`tf-button-ghost ${s.toolRailButton} ${s.iconButton}`,onClick:is,disabled:!d||ce||P>=4,"aria-label":"Zoom in",children:t.jsx(Ns,{size:18})}),t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${s.toolBtn} ${s.toolbarButton} ${G?s.toolBtnActive:""}`,onClick:()=>Qe(e=>!e),disabled:!d||ce||!ke,"aria-label":"Pan canvas",title:"Pan canvas",children:t.jsx($s,{size:18})})]}),t.jsx("span",{className:s.toolbarSeparator,"aria-hidden":"true"}),t.jsxs("div",{className:s.toolbarActions,children:[t.jsx("div",{className:s.toolbarSelectionActions,children:z?t.jsxs(t.Fragment,{children:[t.jsxs("div",{ref:bn,className:s.toolbarColorPicker,children:[t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${s.ghostBtn} ${s.toolbarButton} ${s.colorPickerButton}`,onClick:()=>dt(e=>!e),"aria-label":"Marker color","aria-expanded":ct,title:"Marker color",children:t.jsx("span",{className:s.colorPickerSwatch,style:{backgroundColor:Ut},"aria-hidden":"true"})}),ct?t.jsx("div",{className:s.colorPickerPopover,role:"menu","aria-label":"Marker color options",children:Uo.map(e=>t.jsx("button",{type:"button",className:`${s.colorOption} ${Ut===e?s.colorOptionActive:""}`,style:{backgroundColor:e},onClick:()=>Qn(e),"aria-label":`Use marker color ${e}`,"aria-pressed":Ut===e},e))}):null]}),t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${s.ghostBtn} ${s.toolbarButton}`,onClick:Xt,"aria-label":"Delete marker",title:"Delete selected marker",children:t.jsx(Tn,{size:18})}),t.jsx("div",{className:s.toolbarGeometryFields,"aria-label":"Marker geometry percent controls",children:Qo(z).map(e=>t.jsxs("label",{className:s.toolbarGeometryField,children:[t.jsx("span",{className:`tf-text-meta ${s.toolbarGeometryLabel}`,children:e.label}),t.jsx("input",{className:`tf-field-shell ${s.toolbarGeometryInput}`,type:"number",min:0,max:100,step:.1,value:e.value,onChange:n=>{const r=Jo(n.target.value);r!==null&&ee(z.id,i=>Zo(i,e.key,r))},"aria-label":`${e.label} percent`})]},e.key))})]}):null}),t.jsxs("div",{className:s.toolbarUtilities,children:[t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${s.ghostBtn} ${s.payloadBtn} ${s.toolbarButton}`,onClick:ss,disabled:!B||ft,"aria-label":ft?"Loading payload preview":"Preview payload",title:ft?"Loading payload preview":"Preview payload",children:t.jsx(tn,{size:18})}),t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${s.ghostBtn} ${s.toolbarButton}`,onClick:()=>dn(!0),"aria-label":"How to use marker tools",title:"How to use marker tools",children:t.jsx(nn,{size:18})})]})]})]}),t.jsxs("div",{className:s.canvasWorkspace,children:[t.jsx("div",{className:s.canvasToolRail,"aria-label":"Annotation tools",children:Mn.map(e=>{const n=e.icon;return t.jsx("button",{type:"button",className:`tf-button-ghost ${s.toolRailButton} ${$===e.value?s.toolBtnActive:""}`,onClick:()=>es(e.value),disabled:!d,title:e.label,"aria-label":`${e.label} tool. ${It[e.value].short}`,children:t.jsx(n,{size:18})},e.value)})}),t.jsx("div",{className:s.canvasMain,children:t.jsx("div",{ref:Te,className:`tf-scrollbar ${s.canvasScroller}`,children:d?t.jsxs(t.Fragment,{children:[ce&&!Lt?t.jsx("div",{className:s.canvasStatusOverlay,"aria-live":"polite",children:t.jsxs("div",{className:s.canvasStatusCard,children:[t.jsx(An,{size:20,className:Bn.spinner}),t.jsx("span",{children:"Loading image…"})]})}):null,Lt?t.jsx("div",{className:s.canvasStatusOverlay,"aria-live":"polite",children:t.jsx("div",{className:s.canvasStatusCard,children:t.jsx("span",{children:"Image failed to load."})})}):null,t.jsx("div",{className:s.canvasFrame,children:t.jsxs("div",{className:s.canvasMedia,style:{width:b.width?`${b.width}px`:void 0,height:b.height?`${b.height}px`:void 0},children:[t.jsx("img",{ref:Ht,src:d.path,alt:d.displayName,className:s.canvasImage,onLoad:()=>{const e=Ht.current;et({width:e?.naturalWidth||0,height:e?.naturalHeight||0}),Je(!1),Ze(!1)},onError:()=>{et({width:0,height:0}),Je(!1),Ze(!0)}}),!ce&&!Lt&&B?t.jsxs("div",{ref:mn,className:`${s.overlay} ${$==="select"?s.overlaySelect:""} ${G&&ke?s.overlayPan:""}`,onPointerDown:ds,onPointerMove:fs,onPointerUp:e=>{us(e),hs()},"data-testid":"annotated-attachment-overlay",onPointerLeave:ms,onPointerCancel:ps,children:[t.jsx("svg",{className:s.overlaySvg,viewBox:Gt,preserveAspectRatio:"none","aria-hidden":"true",children:N.filter(e=>e.kind==="arrow").map(e=>{const n=Ko(e,b),r=en(e),i=C===e.id;return t.jsxs(qt.Fragment,{children:[i?t.jsxs(t.Fragment,{children:[t.jsx("line",{x1:n.shaftX1,y1:n.shaftY1,x2:n.shaftX2,y2:n.shaftY2,stroke:"color-mix(in srgb, var(--surface-elevated) 92%, transparent)",strokeWidth:14,strokeLinecap:"round"}),t.jsx("polygon",{points:n.headPoints,fill:r,stroke:"color-mix(in srgb, var(--surface-elevated) 92%, transparent)",strokeWidth:4,strokeLinejoin:"round"})]}):null,t.jsx("line",{x1:n.shaftX1,y1:n.shaftY1,x2:n.shaftX2,y2:n.shaftY2,stroke:r,strokeWidth:i?10:6,strokeLinecap:"round"}),t.jsx("polygon",{points:n.headPoints,fill:r})]},e.id)})}),t.jsx("svg",{className:s.overlayHitLayer,viewBox:Gt,preserveAspectRatio:"none",children:N.filter(e=>e.kind==="arrow").map(e=>t.jsxs(qt.Fragment,{children:[t.jsx("line",{x1:e.x*b.width,y1:e.y*b.height,x2:e.x2*b.width,y2:e.y2*b.height,className:s.arrowHitArea,"data-testid":`annotated-arrow-hit-${e.id}`,"aria-label":`Arrow marker ${Kt.get(e.id)||0}`,onPointerDown:n=>Nn(n,e),onClick:n=>{n.stopPropagation(),L(e.id)}}),C===e.id?t.jsxs(t.Fragment,{children:[t.jsx("circle",{cx:e.x*b.width,cy:e.y*b.height,r:He.hitRadius,className:s.canvasHandleHit,role:"button",tabIndex:0,"aria-label":"Move arrow tail",onPointerDown:n=>$n(n,e,"tail")}),t.jsx("circle",{cx:e.x*b.width,cy:e.y*b.height,r:He.visibleRadius,className:s.canvasHandleVisible,"aria-hidden":"true"}),t.jsx("circle",{cx:e.x2*b.width,cy:e.y2*b.height,r:He.hitRadius,className:s.canvasHandleHit,role:"button",tabIndex:0,"aria-label":"Move arrow tip",onPointerDown:n=>$n(n,e,"tip")}),t.jsx("circle",{cx:e.x2*b.width,cy:e.y2*b.height,r:He.visibleRadius,className:s.canvasHandleVisible,"aria-hidden":"true"})]}):null]},`hit-${e.id}`))}),N.filter(e=>e.kind==="arrow").map(e=>t.jsx("div",{className:`${s.annotationNumberBadge} ${s.arrowNumberBadge}`,style:{left:`${(e.x+e.x2)/2*100}%`,top:`${(e.y+e.y2)/2*100}%`,backgroundColor:en(e)},"aria-hidden":"true",children:Kt.get(e.id)||0},`arrow-number-${e.id}`)),N.filter(e=>e.kind!=="arrow").map(e=>{const n=en(e),r=Kt.get(e.id)||0,i={onPointerDown:c=>Nn(c,e),onClick:c=>{c.stopPropagation(),L(e.id)}};return e.kind==="pin"?t.jsx("button",{type:"button",...i,className:`${s.pin} ${C===e.id?s.selected:""}`,style:{left:`${e.x*100}%`,top:`${e.y*100}%`,backgroundColor:n},children:r},e.id):e.kind==="text-note"?t.jsx("button",{type:"button",...i,className:`${s.note} ${C===e.id?s.selected:""}`,style:{left:`${e.x*100}%`,top:`${e.y*100}%`,backgroundColor:n},children:r},e.id):t.jsxs("div",{className:`${s.box} ${C===e.id?s.selected:""}`,style:{left:`${e.x*100}%`,top:`${e.y*100}%`,width:`${e.width*100}%`,height:`${e.height*100}%`,borderColor:n},children:[t.jsx("span",{className:`${s.annotationNumberBadge} ${s.boxNumberBadge}`,style:{backgroundColor:n},"aria-hidden":"true",children:r}),t.jsx("button",{type:"button",...i,className:s.boxSurface,"aria-label":`Box marker ${r}`})]},e.id)}),t.jsx("svg",{className:s.overlaySvg,viewBox:Gt,preserveAspectRatio:"none",children:N.filter(e=>e.kind==="box"&&C===e.id).map(e=>t.jsxs(qt.Fragment,{children:[t.jsx("circle",{cx:(e.x+e.width)*b.width,cy:(e.y+e.height)*b.height,r:He.hitRadius,className:`${s.canvasHandleHit} ${s.canvasResizeHandleHit}`,role:"button",tabIndex:0,"aria-label":"Resize box marker",onPointerDown:n=>bs(n,e)}),t.jsx("circle",{cx:(e.x+e.width)*b.width,cy:(e.y+e.height)*b.height,r:He.visibleRadius,className:s.canvasHandleVisible,"aria-hidden":"true"})]},`box-handle-${e.id}`))})]}):null]})})]}):t.jsx("div",{className:s.emptyState,children:t.jsx("p",{className:"tf-empty-copy",children:"Select an image attachment to annotate."})})})})]}),t.jsxs("div",{className:s.statusBar,children:[t.jsx("span",{children:U==="error"?"Save failed. Retry now.":U==="saving"||U==="pending"?"Saving…":"Saved"}),rn?t.jsx("span",{children:rn}):t.jsx("span",{children:B?G&&ke?"Drag on the image to pan.":$==="select"?"Select a marker to edit it.":`Click on the image to place a ${$}.`:"Create a session to begin placing markers on this image."}),d&&!B&&Kn?t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${s.ghostBtn} ${s.toolbarButton}`,onClick:()=>{wn()},disabled:W||ut,children:W?"Creating…":"Create one now"}):null]})]}),t.jsx("section",{className:`tf-surface-panel ${s.panel} ${s.detailPanel}`,children:B?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:s.panelHeader,children:[t.jsxs("div",{className:s.panelHeaderText,children:[t.jsx("div",{className:`tf-heading-card ${s.panelTitle}`,children:"Markers"}),t.jsxs("div",{className:"tf-text-secondary",children:[N.length," in this session"]})]}),t.jsxs("div",{className:s.sessionActions,children:[t.jsx("button",{type:"button",className:`tf-control-icon ${s.iconButton}`,onClick:()=>Sn("up"),disabled:!z||zt<=0,"aria-label":"Move marker up",children:t.jsx(Ps,{size:16})}),t.jsx("button",{type:"button",className:`tf-control-icon ${s.iconButton}`,onClick:()=>Sn("down"),disabled:!z||zt===-1||zt>=N.length-1,"aria-label":"Move marker down",children:t.jsx(Bs,{size:16})})]})]}),t.jsx("div",{className:`tf-scrollbar ${s.annotationList}`,children:N.length===0?t.jsx("div",{className:s.detailEmpty,children:t.jsx("p",{className:"tf-empty-copy",children:"Add a marker on the image to begin."})}):N.map((e,n)=>{const r=Oo[e.kind],i=Do[e.kind],c=`${i} ${n+1}`,p=zo[e.markerType||re],j=En.find(f=>f.value===(e.markerType||re))?.label||"Review",u=C===e.id;return t.jsxs("div",{className:`tf-surface-elevated ${s.annotationCard} ${u?s.annotationCardActive:""}`,children:[t.jsx("button",{type:"button",className:s.annotationCardButton,onClick:()=>L(e.id),"aria-label":i,children:t.jsxs("div",{className:s.annotationMeta,children:[t.jsx("span",{className:`tf-heading-card ${s.annotationTitle}`,children:c}),t.jsx("span",{className:`tf-text-meta ${s.annotationKind}`,"aria-hidden":"true",children:t.jsx(r,{size:16})})]})}),u?t.jsxs("div",{className:s.annotationInstructionEditor,children:[t.jsx("label",{className:"tf-field-label",htmlFor:"annotated-marker-instruction",children:"Marker instruction"}),t.jsx("textarea",{id:"annotated-marker-instruction",ref:u?pn:null,className:`tf-field-shell ${s.textArea} ${s.annotationInstructionField}`,value:e.instruction,onChange:f=>{ee(e.id,v=>({...v,instruction:f.target.value}),600)},onBlur:()=>{H("text")},placeholder:"What should the AI focus on for this marker?"}),t.jsxs("div",{className:s.annotationTypeField,children:[t.jsx("label",{className:"tf-field-label",htmlFor:"annotated-marker-type",children:"Instruction type"}),t.jsx("select",{id:"annotated-marker-type",className:`tf-field-shell ${s.select}`,value:e.markerType||re,onChange:f=>{ee(e.id,v=>Wo(v,f.target.value))},children:En.map(f=>t.jsx("option",{value:f.value,children:f.label},f.value))})]})]}):t.jsx("button",{type:"button",className:s.annotationInstructionButton,onClick:()=>L(e.id),"aria-label":`Edit ${i} instruction`,children:t.jsxs("div",{className:s.annotationInstructionEditor,children:[t.jsx("div",{className:`tf-text-secondary ${s.annotationInstructionPreview}`,children:e.instruction.trim()||"No marker instruction yet."}),t.jsx("div",{className:s.annotationPreviewFooter,children:t.jsx("span",{className:`tf-text-meta ${s.annotationInstructionTypeIcon}`,"aria-label":`Instruction type: ${j}`,title:j,children:t.jsx(p,{size:16})})})]})})]},e.id)})})]}):t.jsxs("div",{className:s.emptyState,children:[t.jsx("strong",{className:"tf-empty-title",children:"No active session"}),t.jsx("p",{className:"tf-empty-copy",children:"Create or select a session to edit annotations."})]})}),t.jsx(Jt,{isOpen:Vn,onClose:()=>{qe||(ht(!1),bt(""))},title:"Open Image",size:"sm",children:t.jsxs("form",{className:s.openImageModalBody,onSubmit:e=>{e.preventDefault(),Zn()},children:[t.jsx("label",{className:"tf-field-label",htmlFor:"annotated-open-image-reference",children:"Image reference number"}),t.jsx("input",{id:"annotated-open-image-reference",className:`tf-field-shell ${s.textInput} ${s.openImageField}`,value:Mt,onChange:e=>bt(e.target.value),placeholder:"I-24",autoFocus:!0}),t.jsxs("div",{className:s.openImageActions,children:[t.jsx("button",{type:"button",className:"tf-button-ghost tf-button-compact",onClick:()=>{ht(!1),bt("")},disabled:qe,children:"Cancel"}),t.jsx("button",{type:"submit",className:"tf-button-primary tf-button-compact",disabled:qe,children:qe?"Opening…":"Open"})]})]})}),t.jsx(Jt,{isOpen:Xn,onClose:()=>dn(!1),title:"How To Use Markers",size:"md",children:t.jsx("div",{className:s.markerHelpModalBody,children:Mn.filter(e=>e.value!=="select").map(e=>t.jsxs("div",{className:`tf-surface-inset ${s.markerHelpItem}`,children:[t.jsxs("div",{className:s.markerHelpHeader,children:[t.jsx("strong",{className:"tf-heading-card",children:e.label}),t.jsx("span",{className:"tf-text-meta",children:It[e.value].short})]}),t.jsx("p",{className:"tf-text-secondary",children:It[e.value].detail}),t.jsx("p",{className:`tf-text-body ${s.markerHelpExample}`,children:It[e.value].example})]},e.value))})}),t.jsx(Jt,{isOpen:Wn,onClose:()=>Bt(!1),title:"AI Payload",size:"lg",children:t.jsxs("div",{className:s.payloadModalBody,children:[t.jsxs("div",{className:s.payloadModalToolbar,children:[t.jsxs("div",{className:s.payloadViewToggle,children:[t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${s.toolBtn} ${Tt==="json"?s.toolBtnActive:""}`,onClick:()=>cn("json"),children:"JSON"}),t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${s.toolBtn} ${Tt==="brief"?s.toolBtnActive:""}`,onClick:()=>cn("brief"),children:"AI Brief"})]}),t.jsxs("div",{className:s.payloadModalActions,children:[t.jsxs("button",{type:"button",className:`tf-button-ghost tf-button-compact ${s.ghostBtn}`,onClick:()=>{In("json")},disabled:!oe,"aria-label":le==="json"?"Copied JSON":"Copy JSON",title:le==="json"?"Copied JSON":"Copy JSON",children:[le==="json"?t.jsx(sn,{size:16}):t.jsx(Zt,{size:16}),t.jsx("span",{children:"JSON"})]}),t.jsxs("button",{type:"button",className:`tf-button-ghost tf-button-compact ${s.ghostBtn}`,onClick:()=>{In("brief")},disabled:!oe,"aria-label":le==="brief"?"Copied AI Brief":"Copy AI Brief",title:le==="brief"?"Copied AI Brief":"Copy AI Brief",children:[le==="brief"?t.jsx(sn,{size:16}):t.jsx(Zt,{size:16}),t.jsx("span",{children:"AI Brief"})]})]})]}),ft?t.jsx("div",{className:s.detailEmpty,children:t.jsx("p",{className:"tf-empty-copy",children:"Loading payload…"})}):oe?t.jsx("pre",{className:`tf-surface-inset tf-scrollbar ${s.payloadModalPreview}`,children:Tt==="json"?JSON.stringify(oe,null,2):Fn(oe)}):t.jsx("div",{className:s.detailEmpty,children:t.jsx("p",{className:"tf-empty-copy",children:"Load a payload preview to inspect the current session contract."})})]})})]})}export{dr as AnnotatedAttachmentWorkspaceShell};
@@ -1,4 +1,4 @@
1
- import{j as e,r as i,s as Ft,R as Fe}from"./vendor-react-CKJs5o3c.js";import{t as M,h as fe,f as B,i as rt,j as ot,k as Ot,m as Ht,R as Wt,n as I,o as ct,p as Gt,q as Kt}from"./index-Bzqy5QGm.js";import{r as Ut,W as Jt,t as Vt,l as Yt,as as Xt,at as Oe,n as qt,Z as He,X as wt,au as lt,e as gt,av as yt,aw as Qt,ax as Zt,a as en,i as tn,ay as nn,az as sn,aA as an,aB as _e,aC as rn,s as on,aD as cn,D as ln,aE as dn,T as un,ar as dt,R as mn,aF as fn,B as hn,U as pn,S as vn}from"./vendor-icons-QZyhEwgT.js";import{s as wn,M as ke,r as Se}from"./vendor-markdown-BUxTU7dS.js";import"./vendor-dnd-DRzYolkg.js";import"./vendor-router-BbWMxlnO.js";const gn="_index_18mna_1",yn="_header_18mna_8",xn="_title_18mna_17",bn="_refreshBtn_18mna_26",_n="_search_18mna_48",kn="_searchIcon_18mna_54",Sn="_searchInput_18mna_63",jn="_list_18mna_80",Cn="_state_18mna_89",Nn="_stateError_18mna_97",Tn="_item_18mna_104",En="_itemActive_18mna_124",Rn="_itemIcon_18mna_132",An="_itemBody_18mna_142",$n="_itemTitle_18mna_150",Ln="_itemTask_18mna_162",In="_itemBadge_18mna_172",Bn="_itemMeta_18mna_185",Dn="_itemMetaDetails_18mna_195",Pn="_itemMetaReference_18mna_202",R={index:gn,header:yn,title:xn,refreshBtn:bn,search:_n,searchIcon:kn,searchInput:Sn,list:jn,state:Cn,stateError:Nn,item:Tn,itemActive:En,itemIcon:Rn,itemBody:An,itemTitle:$n,itemTask:Ln,itemBadge:In,itemMeta:Bn,itemMetaDetails:Dn,itemMetaReference:Pn};function Mn({docType:t}){switch(t){case"implementation-plan":return e.jsx(qt,{size:13});case"review":return e.jsx(Oe,{size:13});case"walkthrough":return e.jsx(Xt,{size:13});default:return e.jsx(Yt,{size:13})}}function zn(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function Fn(t){if(!t)return"";const l=new Date(t),r=new Date().getTime()-l.getTime(),u=Math.floor(r/(1e3*60*60*24));return u===0?"Today":u===1?"Yesterday":u<7?`${u}d ago`:u<30?`${Math.floor(u/7)}w ago`:l.toLocaleDateString()}function On(t,l){t.key!=="Enter"&&t.key!==" "||(t.preventDefault(),l())}function Hn({documents:t,selectedDocId:l,loading:c,error:r,searchQuery:u,taskById:m,onSearchChange:v,onSelect:S,onRefresh:g,hasActiveFilters:w}){return e.jsxs("div",{className:R.index,children:[e.jsxs("div",{className:R.header,children:[e.jsxs("span",{className:R.title,children:[e.jsx(Ut,{size:14}),"Documents"]}),e.jsx("button",{className:R.refreshBtn,onClick:g,title:"Refresh document list",disabled:c,children:e.jsx(Jt,{size:13,className:c?M.docSpinning:void 0})})]}),e.jsxs("div",{className:R.search,children:[e.jsx(Vt,{size:12,className:R.searchIcon}),e.jsx("input",{type:"text",placeholder:"Search documents…",value:u,onChange:p=>v(p.target.value),className:R.searchInput})]}),e.jsxs("div",{className:`${R.list} tf-scrollbar`,children:[c&&e.jsx("div",{className:R.state,children:"Loading documents…"}),!c&&r&&e.jsx("div",{className:R.stateError,children:r}),!c&&!r&&t.length===0&&e.jsx("div",{className:R.state,children:w?"No documents match your filters.":"No documents found. Documents added as task attachments will appear here."}),!c&&t.map(p=>{const _=p.taskId?m.get(p.taskId):null,b=p.id===l,L=fe(p),z=Ce(p),D=typeof p.attachmentCount=="number"&&Number.isFinite(p.attachmentCount)?p.attachmentCount:p.taskId?1:0,N=D>1?`${D} tasks linked`:D===1?_?.title||"1 task linked":null;return e.jsxs("div",{role:"button",tabIndex:0,className:`${R.item} ${b?R.itemActive:""}`,onClick:()=>S(p),onKeyDown:J=>On(J,()=>S(p)),children:[e.jsx("div",{className:R.itemIcon,children:e.jsx(Mn,{docType:p.docType})}),e.jsxs("div",{className:R.itemBody,children:[e.jsx("span",{className:R.itemTitle,title:L,children:L}),z==="unattached"&&e.jsx("span",{className:R.itemBadge,children:"Unattached"}),N&&e.jsx("span",{className:R.itemTask,title:N,children:N}),e.jsxs("span",{className:R.itemMeta,children:[e.jsxs("span",{className:R.itemMetaDetails,children:[zn(p.sizeBytes),p.updatedAt&&e.jsxs(e.Fragment,{children:[" · ",Fn(p.updatedAt)]})]}),p.referenceLabel&&e.jsx("span",{className:R.itemMetaReference,children:p.referenceLabel})]})]})]},p.id)})]})]})}function je(t){return function(l){return wn(l,t)}}const Wn="_viewer_biumc_1",Gn="_viewerMonochrome_biumc_10",Kn="_metaDocumentName_biumc_10",Un="_viewerEditMode_biumc_14",Jn="_meta_biumc_10",Vn="_metaLeft_biumc_30",Yn="_metaRenameRow_biumc_49",Xn="_typeBadge_biumc_56",qn="_typeBadgeImplementationPlan_biumc_71",Qn="_typeBadgeReview_biumc_77",Zn="_typeBadgeWalkthrough_biumc_83",es="_metaTaskName_biumc_89",ts="_statusBadge_biumc_98",ns="_metaDate_biumc_113",ss="_metaSize_biumc_114",as="_actions_biumc_122",is="_actionBtn_biumc_129",rs="_dangerBtn_biumc_156",os="_generateBtn_biumc_167",cs="_editBtn_biumc_178",ls="_saveBtn_biumc_189",ds="_layoutToggle_biumc_205",us="_layoutBtn_biumc_213",ms="_layoutBtnActive_biumc_229",fs="_saveStatus_biumc_234",hs="_saveStatusSaved_biumc_241",ps="_saveStatusError_biumc_245",vs="_unsaved_biumc_250",ws="_viewerContent_biumc_256",gs="_viewerBody_biumc_265",ys="_viewerMain_biumc_273",xs="_reviewRail_biumc_277",bs="_printHint_biumc_283",_s="_reviewSection_biumc_290",ks="_reviewHeader_biumc_299",Ss="_reviewTitle_biumc_307",js="_reviewSubtitle_biumc_316",Cs="_reviewControls_biumc_323",Ns="_reviewSelect_biumc_330",Ts="_reviewSessionMeta_biumc_334",Es="_reviewStatusResolved_biumc_342",Rs="_reviewSessionLabel_biumc_348",As="_reviewTitleEditRow_biumc_353",$s="_reviewSessionTimestamp_biumc_360",Ls="_reviewAnchorLabel_biumc_364",Is="_reviewComposer_biumc_370",Bs="_reviewAnchorChip_biumc_377",Ds="_reviewAnchorSnippet_biumc_390",Ps="_reviewAnchorClear_biumc_395",Ms="_reviewCommentActions_biumc_408",zs="_reviewCommentAction_biumc_408",Fs="_reviewCommentEditor_biumc_429",Os="_viewerState_biumc_435",Hs="_viewerStateError_biumc_442",Ws="_editorArea_biumc_449",Gs="_editorPane_biumc_456",Ks="_editorLayoutSplit_biumc_464",Us="_previewPane_biumc_465",Js="_editorLayoutEditor_biumc_469",Vs="_editorLayoutPreview_biumc_470",Ys="_editorPaneLabel_biumc_474",Xs="_editorTextarea_biumc_486",qs="_markdownSurface_biumc_528",a={viewer:Wn,viewerMonochrome:Gn,metaDocumentName:Kn,viewerEditMode:Un,meta:Jn,metaLeft:Vn,metaRenameRow:Yn,typeBadge:Xn,typeBadgeImplementationPlan:qn,typeBadgeReview:Qn,typeBadgeWalkthrough:Zn,metaTaskName:es,statusBadge:ts,metaDate:ns,metaSize:ss,actions:as,actionBtn:is,dangerBtn:rs,generateBtn:os,editBtn:cs,saveBtn:ls,layoutToggle:ds,layoutBtn:us,layoutBtnActive:ms,saveStatus:fs,saveStatusSaved:hs,saveStatusError:ps,unsaved:vs,viewerContent:ws,viewerBody:gs,viewerMain:ys,reviewRail:xs,printHint:bs,reviewSection:_s,reviewHeader:ks,reviewTitle:Ss,reviewSubtitle:js,reviewControls:Cs,reviewSelect:Ns,reviewSessionMeta:Ts,reviewStatusResolved:Es,reviewSessionLabel:Rs,reviewTitleEditRow:As,reviewSessionTimestamp:$s,reviewAnchorLabel:Ls,reviewComposer:Is,reviewAnchorChip:Bs,reviewAnchorSnippet:Ds,reviewAnchorClear:Ps,reviewCommentActions:Ms,reviewCommentAction:zs,reviewCommentEditor:Fs,viewerState:Os,viewerStateError:Hs,editorArea:Ws,editorPane:Gs,editorLayoutSplit:Ks,previewPane:Us,editorLayoutEditor:Js,editorLayoutPreview:Vs,editorPaneLabel:Ys,editorTextarea:Xs,markdownSurface:qs},Qs="_overlay_1unik_1",Zs="_modal_1unik_12",ea="_header_1unik_16",ta="_title_1unik_20",na="_docName_1unik_24",sa="_body_1unik_34",aa="_state_1unik_41",ia="_stateError_1unik_52",ra="_stateDone_1unik_63",oa="_toolbar_1unik_84",ca="_toolbarCount_1unik_95",la="_toolbarActions_1unik_100",da="_tree_1unik_105",ua="_taskRow_1unik_113",ma="_taskRowDimmed_1unik_126",fa="_taskCheck_1unik_130",ha="_taskExpandBtn_1unik_139",pa="_taskExpandSpacer_1unik_155",va="_taskTitle_1unik_160",wa="_taskBadge_1unik_169",ga="_footer_1unik_179",C={overlay:Qs,modal:Zs,header:ea,title:ta,docName:na,body:sa,state:aa,stateError:ia,stateDone:ra,toolbar:oa,toolbarCount:ca,toolbarActions:la,tree:da,taskRow:ua,taskRowDimmed:ma,taskCheck:fa,taskExpandBtn:ha,taskExpandSpacer:pa,taskTitle:va,taskBadge:wa,footer:ga},ya={1:"Low",2:"Medium",3:"High"};function me(t,l){return t.map(c=>({...c,selected:l,children:me(c.children,l)}))}function xt(t,l,c){return t.map(r=>r.idempotencyKey===l?{...r,selected:c,children:me(r.children,c)}:{...r,children:xt(r.children,l,c)})}function We(t){let l=0;for(const c of t)c.selected&&l++,l+=We(c.children);return l}function bt({node:t,depth:l,onToggle:c}){const[r,u]=i.useState(!0),m=t.children.length>0,v=l*20;return e.jsxs("div",{children:[e.jsxs("div",{className:`${C.taskRow} ${t.selected?"":C.taskRowDimmed}`,style:{paddingLeft:`${12+v}px`},children:[e.jsx("button",{className:C.taskCheck,onClick:()=>c(t.idempotencyKey,!t.selected),title:t.selected?"Deselect":"Select",children:t.selected?e.jsx(Qt,{size:14,style:{color:"var(--brand-primary-strong)"}}):e.jsx(Zt,{size:14,style:{color:"var(--text-muted)"}})}),m?e.jsx("button",{className:C.taskExpandBtn,onClick:()=>u(S=>!S),children:r?e.jsx(en,{size:12}):e.jsx(tn,{size:12})}):e.jsx("span",{className:C.taskExpandSpacer}),e.jsx("span",{className:C.taskTitle,title:t.description||void 0,children:t.title}),e.jsx("span",{className:C.taskBadge,style:{color:rt(t.type),borderColor:rt(t.type)},children:t.type}),e.jsx("span",{className:C.taskBadge,style:{color:ot(t.priority),borderColor:ot(t.priority)},children:ya[t.priority]})]}),m&&r&&e.jsx("div",{children:t.children.map(S=>e.jsx(bt,{node:S,depth:l+1,onToggle:c},S.idempotencyKey))})]})}function xa({content:t,docTitle:l,apiBaseUrl:c="",onClose:r,onGenerated:u}){const[m,v]=i.useState("preview"),[S,g]=i.useState(null),[w,p]=i.useState([]),[_,b]=i.useState(!0),[L,z]=i.useState(0),[D,N]=i.useState(null);i.useEffect(()=>{let y=!1;return b(!0),g(null),B("/api/taskforce/documents/generate-tasks/preview",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:t})},c).then(j=>j.json()).then(j=>{if(!y){if(j.error)throw new Error(j.error);p(j.tasks||[]),v("preview")}}).catch(j=>{y||(g(j?.message||"Failed to parse plan"),v("error"))}).finally(()=>{y||b(!1)}),()=>{y=!0}},[t,c]);const J=i.useCallback((y,j)=>{p(q=>xt(q,y,j))},[]),F=()=>p(y=>me(y,!0)),W=()=>p(y=>me(y,!1)),O=We(w),Y=async()=>{v("generating"),N(null);try{const y=await B("/api/taskforce/documents/generate-tasks/commit",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({tasks:w})},c),j=await y.json().catch(()=>({}));if(!y.ok)throw new Error(j.error||`Generation failed (${y.status})`);z(j.created??0),v("done"),u(j.created??0)}catch(y){N(y?.message||"Generation failed"),v("error")}};return e.jsx("div",{className:C.overlay,onClick:y=>{y.target===y.currentTarget&&r()},children:e.jsxs("div",{className:`tf-surface-modal tf-modal-shell ${C.modal}`,children:[e.jsxs("div",{className:`tf-modal-header ${C.header}`,children:[e.jsxs("div",{className:`tf-modal-title ${C.title}`,children:[e.jsx(He,{size:16,style:{color:"var(--brand-primary-strong)"}}),"Generate Tasks from Plan"]}),e.jsx("span",{className:C.docName,children:l}),e.jsx("button",{className:"tf-control-icon",onClick:r,title:"Close",children:e.jsx(wt,{size:16})})]}),e.jsxs("div",{className:C.body,children:[_&&e.jsxs("div",{className:C.state,children:[e.jsx(lt,{size:20,className:M.docSpinning}),"Parsing plan…"]}),!_&&m==="error"&&e.jsxs("div",{className:C.stateError,children:[e.jsx(gt,{size:16}),S||D||"An error occurred"]}),!_&&m==="done"&&e.jsxs("div",{className:C.stateDone,children:[e.jsx(yt,{size:24,style:{color:"var(--status-success)"}}),e.jsxs("strong",{children:[L," task",L!==1?"s":""," created"]}),e.jsx("p",{children:"Tasks are now in your board. Switch to the Kanban or Hierarchy view to see them."})]}),!_&&(m==="preview"||m==="confirm"||m==="generating")&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:C.toolbar,children:[e.jsxs("span",{className:C.toolbarCount,children:[O," of ",We(me(w,!0))," tasks selected"]}),e.jsxs("div",{className:C.toolbarActions,children:[e.jsx("button",{className:"tf-control-icon",onClick:F,children:"Select all"}),e.jsx("button",{className:"tf-control-icon",onClick:W,children:"Deselect all"})]})]}),w.length===0?e.jsx("div",{className:C.state,children:"No tasks could be parsed from this document. Make sure the document uses ## H2 headings for phases and bullet points for tasks."}):e.jsx("div",{className:`${C.tree} tf-scrollbar`,children:w.map(y=>e.jsx(bt,{node:y,depth:0,onToggle:J},y.idempotencyKey))})]})]}),!_&&m!=="done"&&m!=="error"&&e.jsxs("div",{className:C.footer,children:[e.jsx("button",{className:"tf-button-secondary",onClick:r,children:"Cancel"}),e.jsx("button",{className:"tf-button-primary",onClick:Y,disabled:O===0||m==="generating",children:m==="generating"?e.jsxs(e.Fragment,{children:[e.jsx(lt,{size:13,className:M.docSpinning})," Generating…"]}):e.jsxs(e.Fragment,{children:[e.jsx(He,{size:13})," Generate ",O," task",O!==1?"s":""]})})]}),!_&&m==="done"&&e.jsx("div",{className:C.footer,children:e.jsx("button",{className:"tf-button-primary",onClick:r,children:"Done"})})]})})}const ba={"implementation-plan":"Implementation Plan",review:"Review",walkthrough:"Walkthrough",planning:"Planning",other:"Document"},_a={"implementation-plan":a.typeBadgeImplementationPlan,review:a.typeBadgeReview,walkthrough:a.typeBadgeWalkthrough,planning:void 0,other:void 0},ka={editor:a.editorLayoutEditor,split:a.editorLayoutSplit,preview:a.editorLayoutPreview},Sa=1500,ja=`
1
+ import{j as e,r as i,s as Ft,R as Fe}from"./vendor-react-CKJs5o3c.js";import{t as M,h as fe,f as B,i as rt,j as ot,k as Ot,m as Ht,R as Gt,n as I,o as ct,q as Wt,s as Kt}from"./index-YJ4k5QNa.js";import{r as Ut,t as Jt,u as Vt,l as Yt,as as Xt,at as Oe,n as qt,Z as He,X as wt,au as lt,e as gt,av as yt,aw as Qt,ax as Zt,a as en,i as tn,ay as nn,az as sn,aA as an,aB as _e,aC as rn,s as on,aD as cn,D as ln,aE as dn,T as un,ar as dt,R as mn,aF as fn,B as hn,U as pn,S as vn}from"./vendor-icons-C8EED3Oh.js";import{s as wn,M as ke,r as Se}from"./vendor-markdown-BUxTU7dS.js";import"./vendor-dnd-DRzYolkg.js";import"./vendor-router-BbWMxlnO.js";const gn="_index_18mna_1",yn="_header_18mna_8",xn="_title_18mna_17",bn="_refreshBtn_18mna_26",_n="_search_18mna_48",kn="_searchIcon_18mna_54",Sn="_searchInput_18mna_63",jn="_list_18mna_80",Cn="_state_18mna_89",Nn="_stateError_18mna_97",Tn="_item_18mna_104",En="_itemActive_18mna_124",Rn="_itemIcon_18mna_132",An="_itemBody_18mna_142",$n="_itemTitle_18mna_150",Ln="_itemTask_18mna_162",In="_itemBadge_18mna_172",Bn="_itemMeta_18mna_185",Dn="_itemMetaDetails_18mna_195",Pn="_itemMetaReference_18mna_202",R={index:gn,header:yn,title:xn,refreshBtn:bn,search:_n,searchIcon:kn,searchInput:Sn,list:jn,state:Cn,stateError:Nn,item:Tn,itemActive:En,itemIcon:Rn,itemBody:An,itemTitle:$n,itemTask:Ln,itemBadge:In,itemMeta:Bn,itemMetaDetails:Dn,itemMetaReference:Pn};function Mn({docType:t}){switch(t){case"implementation-plan":return e.jsx(qt,{size:13});case"review":return e.jsx(Oe,{size:13});case"walkthrough":return e.jsx(Xt,{size:13});default:return e.jsx(Yt,{size:13})}}function zn(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function Fn(t){if(!t)return"";const l=new Date(t),r=new Date().getTime()-l.getTime(),u=Math.floor(r/(1e3*60*60*24));return u===0?"Today":u===1?"Yesterday":u<7?`${u}d ago`:u<30?`${Math.floor(u/7)}w ago`:l.toLocaleDateString()}function On(t,l){t.key!=="Enter"&&t.key!==" "||(t.preventDefault(),l())}function Hn({documents:t,selectedDocId:l,loading:c,error:r,searchQuery:u,taskById:m,onSearchChange:v,onSelect:S,onRefresh:g,hasActiveFilters:w}){return e.jsxs("div",{className:R.index,children:[e.jsxs("div",{className:R.header,children:[e.jsxs("span",{className:R.title,children:[e.jsx(Ut,{size:14}),"Documents"]}),e.jsx("button",{className:R.refreshBtn,onClick:g,title:"Refresh document list",disabled:c,children:e.jsx(Jt,{size:13,className:c?M.docSpinning:void 0})})]}),e.jsxs("div",{className:R.search,children:[e.jsx(Vt,{size:12,className:R.searchIcon}),e.jsx("input",{type:"text",placeholder:"Search documents…",value:u,onChange:p=>v(p.target.value),className:R.searchInput})]}),e.jsxs("div",{className:`${R.list} tf-scrollbar`,children:[c&&e.jsx("div",{className:R.state,children:"Loading documents…"}),!c&&r&&e.jsx("div",{className:R.stateError,children:r}),!c&&!r&&t.length===0&&e.jsx("div",{className:R.state,children:w?"No documents match your filters.":"No documents found. Documents added as task attachments will appear here."}),!c&&t.map(p=>{const _=p.taskId?m.get(p.taskId):null,b=p.id===l,L=fe(p),z=Ce(p),D=typeof p.attachmentCount=="number"&&Number.isFinite(p.attachmentCount)?p.attachmentCount:p.taskId?1:0,N=D>1?`${D} tasks linked`:D===1?_?.title||"1 task linked":null;return e.jsxs("div",{role:"button",tabIndex:0,className:`${R.item} ${b?R.itemActive:""}`,onClick:()=>S(p),onKeyDown:J=>On(J,()=>S(p)),children:[e.jsx("div",{className:R.itemIcon,children:e.jsx(Mn,{docType:p.docType})}),e.jsxs("div",{className:R.itemBody,children:[e.jsx("span",{className:R.itemTitle,title:L,children:L}),z==="unattached"&&e.jsx("span",{className:R.itemBadge,children:"Unattached"}),N&&e.jsx("span",{className:R.itemTask,title:N,children:N}),e.jsxs("span",{className:R.itemMeta,children:[e.jsxs("span",{className:R.itemMetaDetails,children:[zn(p.sizeBytes),p.updatedAt&&e.jsxs(e.Fragment,{children:[" · ",Fn(p.updatedAt)]})]}),p.referenceLabel&&e.jsx("span",{className:R.itemMetaReference,children:p.referenceLabel})]})]})]},p.id)})]})]})}function je(t){return function(l){return wn(l,t)}}const Gn="_viewer_biumc_1",Wn="_viewerMonochrome_biumc_10",Kn="_metaDocumentName_biumc_10",Un="_viewerEditMode_biumc_14",Jn="_meta_biumc_10",Vn="_metaLeft_biumc_30",Yn="_metaRenameRow_biumc_49",Xn="_typeBadge_biumc_56",qn="_typeBadgeImplementationPlan_biumc_71",Qn="_typeBadgeReview_biumc_77",Zn="_typeBadgeWalkthrough_biumc_83",es="_metaTaskName_biumc_89",ts="_statusBadge_biumc_98",ns="_metaDate_biumc_113",ss="_metaSize_biumc_114",as="_actions_biumc_122",is="_actionBtn_biumc_129",rs="_dangerBtn_biumc_156",os="_generateBtn_biumc_167",cs="_editBtn_biumc_178",ls="_saveBtn_biumc_189",ds="_layoutToggle_biumc_205",us="_layoutBtn_biumc_213",ms="_layoutBtnActive_biumc_229",fs="_saveStatus_biumc_234",hs="_saveStatusSaved_biumc_241",ps="_saveStatusError_biumc_245",vs="_unsaved_biumc_250",ws="_viewerContent_biumc_256",gs="_viewerBody_biumc_265",ys="_viewerMain_biumc_273",xs="_reviewRail_biumc_277",bs="_printHint_biumc_283",_s="_reviewSection_biumc_290",ks="_reviewHeader_biumc_299",Ss="_reviewTitle_biumc_307",js="_reviewSubtitle_biumc_316",Cs="_reviewControls_biumc_323",Ns="_reviewSelect_biumc_330",Ts="_reviewSessionMeta_biumc_334",Es="_reviewStatusResolved_biumc_342",Rs="_reviewSessionLabel_biumc_348",As="_reviewTitleEditRow_biumc_353",$s="_reviewSessionTimestamp_biumc_360",Ls="_reviewAnchorLabel_biumc_364",Is="_reviewComposer_biumc_370",Bs="_reviewAnchorChip_biumc_377",Ds="_reviewAnchorSnippet_biumc_390",Ps="_reviewAnchorClear_biumc_395",Ms="_reviewCommentActions_biumc_408",zs="_reviewCommentAction_biumc_408",Fs="_reviewCommentEditor_biumc_429",Os="_viewerState_biumc_435",Hs="_viewerStateError_biumc_442",Gs="_editorArea_biumc_449",Ws="_editorPane_biumc_456",Ks="_editorLayoutSplit_biumc_464",Us="_previewPane_biumc_465",Js="_editorLayoutEditor_biumc_469",Vs="_editorLayoutPreview_biumc_470",Ys="_editorPaneLabel_biumc_474",Xs="_editorTextarea_biumc_486",qs="_markdownSurface_biumc_528",a={viewer:Gn,viewerMonochrome:Wn,metaDocumentName:Kn,viewerEditMode:Un,meta:Jn,metaLeft:Vn,metaRenameRow:Yn,typeBadge:Xn,typeBadgeImplementationPlan:qn,typeBadgeReview:Qn,typeBadgeWalkthrough:Zn,metaTaskName:es,statusBadge:ts,metaDate:ns,metaSize:ss,actions:as,actionBtn:is,dangerBtn:rs,generateBtn:os,editBtn:cs,saveBtn:ls,layoutToggle:ds,layoutBtn:us,layoutBtnActive:ms,saveStatus:fs,saveStatusSaved:hs,saveStatusError:ps,unsaved:vs,viewerContent:ws,viewerBody:gs,viewerMain:ys,reviewRail:xs,printHint:bs,reviewSection:_s,reviewHeader:ks,reviewTitle:Ss,reviewSubtitle:js,reviewControls:Cs,reviewSelect:Ns,reviewSessionMeta:Ts,reviewStatusResolved:Es,reviewSessionLabel:Rs,reviewTitleEditRow:As,reviewSessionTimestamp:$s,reviewAnchorLabel:Ls,reviewComposer:Is,reviewAnchorChip:Bs,reviewAnchorSnippet:Ds,reviewAnchorClear:Ps,reviewCommentActions:Ms,reviewCommentAction:zs,reviewCommentEditor:Fs,viewerState:Os,viewerStateError:Hs,editorArea:Gs,editorPane:Ws,editorLayoutSplit:Ks,previewPane:Us,editorLayoutEditor:Js,editorLayoutPreview:Vs,editorPaneLabel:Ys,editorTextarea:Xs,markdownSurface:qs},Qs="_overlay_1unik_1",Zs="_modal_1unik_12",ea="_header_1unik_16",ta="_title_1unik_20",na="_docName_1unik_24",sa="_body_1unik_34",aa="_state_1unik_41",ia="_stateError_1unik_52",ra="_stateDone_1unik_63",oa="_toolbar_1unik_84",ca="_toolbarCount_1unik_95",la="_toolbarActions_1unik_100",da="_tree_1unik_105",ua="_taskRow_1unik_113",ma="_taskRowDimmed_1unik_126",fa="_taskCheck_1unik_130",ha="_taskExpandBtn_1unik_139",pa="_taskExpandSpacer_1unik_155",va="_taskTitle_1unik_160",wa="_taskBadge_1unik_169",ga="_footer_1unik_179",C={overlay:Qs,modal:Zs,header:ea,title:ta,docName:na,body:sa,state:aa,stateError:ia,stateDone:ra,toolbar:oa,toolbarCount:ca,toolbarActions:la,tree:da,taskRow:ua,taskRowDimmed:ma,taskCheck:fa,taskExpandBtn:ha,taskExpandSpacer:pa,taskTitle:va,taskBadge:wa,footer:ga},ya={1:"Low",2:"Medium",3:"High"};function me(t,l){return t.map(c=>({...c,selected:l,children:me(c.children,l)}))}function xt(t,l,c){return t.map(r=>r.idempotencyKey===l?{...r,selected:c,children:me(r.children,c)}:{...r,children:xt(r.children,l,c)})}function Ge(t){let l=0;for(const c of t)c.selected&&l++,l+=Ge(c.children);return l}function bt({node:t,depth:l,onToggle:c}){const[r,u]=i.useState(!0),m=t.children.length>0,v=l*20;return e.jsxs("div",{children:[e.jsxs("div",{className:`${C.taskRow} ${t.selected?"":C.taskRowDimmed}`,style:{paddingLeft:`${12+v}px`},children:[e.jsx("button",{className:C.taskCheck,onClick:()=>c(t.idempotencyKey,!t.selected),title:t.selected?"Deselect":"Select",children:t.selected?e.jsx(Qt,{size:14,style:{color:"var(--brand-primary-strong)"}}):e.jsx(Zt,{size:14,style:{color:"var(--text-muted)"}})}),m?e.jsx("button",{className:C.taskExpandBtn,onClick:()=>u(S=>!S),children:r?e.jsx(en,{size:12}):e.jsx(tn,{size:12})}):e.jsx("span",{className:C.taskExpandSpacer}),e.jsx("span",{className:C.taskTitle,title:t.description||void 0,children:t.title}),e.jsx("span",{className:C.taskBadge,style:{color:rt(t.type),borderColor:rt(t.type)},children:t.type}),e.jsx("span",{className:C.taskBadge,style:{color:ot(t.priority),borderColor:ot(t.priority)},children:ya[t.priority]})]}),m&&r&&e.jsx("div",{children:t.children.map(S=>e.jsx(bt,{node:S,depth:l+1,onToggle:c},S.idempotencyKey))})]})}function xa({content:t,docTitle:l,apiBaseUrl:c="",onClose:r,onGenerated:u}){const[m,v]=i.useState("preview"),[S,g]=i.useState(null),[w,p]=i.useState([]),[_,b]=i.useState(!0),[L,z]=i.useState(0),[D,N]=i.useState(null);i.useEffect(()=>{let y=!1;return b(!0),g(null),B("/api/taskforce/documents/generate-tasks/preview",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:t})},c).then(j=>j.json()).then(j=>{if(!y){if(j.error)throw new Error(j.error);p(j.tasks||[]),v("preview")}}).catch(j=>{y||(g(j?.message||"Failed to parse plan"),v("error"))}).finally(()=>{y||b(!1)}),()=>{y=!0}},[t,c]);const J=i.useCallback((y,j)=>{p(q=>xt(q,y,j))},[]),F=()=>p(y=>me(y,!0)),G=()=>p(y=>me(y,!1)),O=Ge(w),Y=async()=>{v("generating"),N(null);try{const y=await B("/api/taskforce/documents/generate-tasks/commit",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({tasks:w})},c),j=await y.json().catch(()=>({}));if(!y.ok)throw new Error(j.error||`Generation failed (${y.status})`);z(j.created??0),v("done"),u(j.created??0)}catch(y){N(y?.message||"Generation failed"),v("error")}};return e.jsx("div",{className:C.overlay,onClick:y=>{y.target===y.currentTarget&&r()},children:e.jsxs("div",{className:`tf-surface-modal tf-modal-shell ${C.modal}`,children:[e.jsxs("div",{className:`tf-modal-header ${C.header}`,children:[e.jsxs("div",{className:`tf-modal-title ${C.title}`,children:[e.jsx(He,{size:16,style:{color:"var(--brand-primary-strong)"}}),"Generate Tasks from Plan"]}),e.jsx("span",{className:C.docName,children:l}),e.jsx("button",{className:"tf-control-icon",onClick:r,title:"Close",children:e.jsx(wt,{size:16})})]}),e.jsxs("div",{className:C.body,children:[_&&e.jsxs("div",{className:C.state,children:[e.jsx(lt,{size:20,className:M.docSpinning}),"Parsing plan…"]}),!_&&m==="error"&&e.jsxs("div",{className:C.stateError,children:[e.jsx(gt,{size:16}),S||D||"An error occurred"]}),!_&&m==="done"&&e.jsxs("div",{className:C.stateDone,children:[e.jsx(yt,{size:24,style:{color:"var(--status-success)"}}),e.jsxs("strong",{children:[L," task",L!==1?"s":""," created"]}),e.jsx("p",{children:"Tasks are now in your board. Switch to the Kanban or Hierarchy view to see them."})]}),!_&&(m==="preview"||m==="confirm"||m==="generating")&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:C.toolbar,children:[e.jsxs("span",{className:C.toolbarCount,children:[O," of ",Ge(me(w,!0))," tasks selected"]}),e.jsxs("div",{className:C.toolbarActions,children:[e.jsx("button",{className:"tf-control-icon",onClick:F,children:"Select all"}),e.jsx("button",{className:"tf-control-icon",onClick:G,children:"Deselect all"})]})]}),w.length===0?e.jsx("div",{className:C.state,children:"No tasks could be parsed from this document. Make sure the document uses ## H2 headings for phases and bullet points for tasks."}):e.jsx("div",{className:`${C.tree} tf-scrollbar`,children:w.map(y=>e.jsx(bt,{node:y,depth:0,onToggle:J},y.idempotencyKey))})]})]}),!_&&m!=="done"&&m!=="error"&&e.jsxs("div",{className:C.footer,children:[e.jsx("button",{className:"tf-button-secondary",onClick:r,children:"Cancel"}),e.jsx("button",{className:"tf-button-primary",onClick:Y,disabled:O===0||m==="generating",children:m==="generating"?e.jsxs(e.Fragment,{children:[e.jsx(lt,{size:13,className:M.docSpinning})," Generating…"]}):e.jsxs(e.Fragment,{children:[e.jsx(He,{size:13})," Generate ",O," task",O!==1?"s":""]})})]}),!_&&m==="done"&&e.jsx("div",{className:C.footer,children:e.jsx("button",{className:"tf-button-primary",onClick:r,children:"Done"})})]})})}const ba={"implementation-plan":"Implementation Plan",review:"Review",walkthrough:"Walkthrough",planning:"Planning",other:"Document"},_a={"implementation-plan":a.typeBadgeImplementationPlan,review:a.typeBadgeReview,walkthrough:a.typeBadgeWalkthrough,planning:void 0,other:void 0},ka={editor:a.editorLayoutEditor,split:a.editorLayoutSplit,preview:a.editorLayoutPreview},Sa=1500,ja=`
2
2
  @page {
3
3
  margin: 0.94in 1.02in 1in;
4
4
  }
@@ -247,4 +247,4 @@ body {
247
247
  <body>${l}</body>
248
248
  </html>`}async function Ea(t,l){try{await l.fonts?.ready}catch{}await new Promise(c=>{const r=t.requestAnimationFrame?.bind(t)??(u=>window.setTimeout(()=>u(0),0));r(()=>r(()=>c()))})}function Ra(t){return window.setTimeout(t,Sa)}function mt(t){try{return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return t}}function ft(t){return t?t.kind==="document"?"Entire document":t.kind==="quote"?t.quote?`Quote: "${t.quote}"`:"Quoted text":t.kind==="line-range"?t.startLine===t.endLine?`Line ${t.startLine}`:`Lines ${t.startLine}-${t.endLine}`:null:null}function Aa(t){return t.authorActor?.label?t.authorActor.label:t.authorActorId==="user"||t.authorActorId==="human"?"You":t.authorActorId?t.authorActorId:"Reviewer"}function ht(t){return t.replace(/\s+/g," ").trim()}function $a(t,l){if(!l)return 0;let c=0,r=0;for(;r>=0&&(r=t.indexOf(l,r),!(r<0));)c+=1,r+=l.length;return c}function La(t,l,c){const r=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);let u=r.nextNode(),m=0;for(;u;){const v=u.textContent||"";if(u===l)return m+Math.max(0,Math.min(c,v.length));m+=v.length,u=r.nextNode()}return null}function Ia(t,l,c){const r=c.replace(/\s+/g," ").trim();if(!r)return null;const u=t.textContent||"",m=ht(u),v=[];let S=m.indexOf(r);for(;S>=0;)v.push(S),S=m.indexOf(r,S+r.length);let g=null;const w=La(t,l.startContainer,l.startOffset);if(w!==null){const z=ht(u.slice(0,w));g=$a(z,r)}const p=g!==null&&g>=0&&g<v.length?g:v.length===1?0:null,_=p!==null?v[p]:v[0]??-1;if(_<0)return{kind:"quote",quote:r,occurrenceIndex:g};const b=m.slice(Math.max(0,_-40),_).trim()||null,L=m.slice(_+r.length,_+r.length+40).trim()||null;return{kind:"quote",quote:r,occurrenceIndex:p,prefix:b,suffix:L}}function Ba(t,l,c){if(l<0)return t;const r=t.split(`
249
249
  `);let u=-1;const m=/^(\s*(?:[-*+]|\d+\.)\s+)\[( |x|X)\](.*)$/,v=c?"x":" ";return r.map(g=>{const w=g.match(m);return!w||(u+=1,u!==l)?g:`${w[1]}[${v}]${w[3]}`}).join(`
250
- `)}function Da({doc:t,taskTitle:l,apiBaseUrl:c="",onSaved:r,onDeleted:u,enableTaskGeneration:m=!1}){const v=fe(t),[S,g]=i.useState(v),w=S,p=Ot({...t,displayName:S}),_=Ht(t),[b,L]=i.useState(null),[z,D]=i.useState(!1),[N,J]=i.useState(null),[F,W]=i.useState(!1),[O,Y]=i.useState(!1),[y,j]=i.useState([]),[q,Ne]=i.useState(!1),[ee,A]=i.useState(null),[se,V]=i.useState(null),[E,P]=i.useState(""),[x,$]=i.useState(!1),[H,Q]=i.useState(null),[he,ae]=i.useState(!1),[Te,Ee]=i.useState(""),[ie,ue]=i.useState(null),[pe,re]=i.useState(""),[T,ve]=i.useState(!1),[G,oe]=i.useState(""),[K,Re]=i.useState("split"),[X,U]=i.useState({type:"idle"}),[_t,Ae]=i.useState(!1),[Ke,kt]=i.useState(!1),[we,Ue]=i.useState(!1),[ge,te]=i.useState(!1),[$e,ce]=i.useState(w),le=t.editable!==!1,Je=Ce(t),St=Je==="unattached"&&!!t.assetId,Le=T&&G!==(b??""),Ie=i.useRef(null),Be=i.useRef(null),Ve=i.useRef(null),de=i.useRef(null),ye=i.useRef(null),Ye=i.useRef(null),Xe=i.useRef(null),h=y.find(n=>n.id===se)||y[0]||null,qe=i.useCallback(async()=>{D(!0),J(null),L(null);try{const n=await B(t.apiUrl,{credentials:"same-origin"},c);if(!n.ok)throw new Error(`Failed to load document (${n.status})`);const s=await n.text();L(s),oe(s)}catch(n){J(n?.message||"Failed to load document")}finally{D(!1)}},[c,t.apiUrl]),xe=i.useCallback(async n=>{if(!t.assetId){j([]),V(null),A(null);return}const s=n?.silent===!0;s||(Ne(!0),A(null));try{const o=await B(`/api/taskforce/document-reviews/sessions?assetId=${encodeURIComponent(t.assetId)}`,{credentials:"include"},c),d=await o.json().catch(()=>({}));if(!o.ok)throw new Error(d.error||`Failed to load reviews (${o.status})`);const f=Array.isArray(d.sessions)?d.sessions:[];j(f),V(k=>k&&f.some(Z=>Z.id===k)?k:f[0]?.id??null)}catch(o){s||(A(o?.message||"Failed to load reviews"),j([]),V(null))}finally{s||Ne(!1)}},[c,t.assetId]),De=i.useCallback(async()=>{if(!t.assetId||x)return null;$(!0),A(null);try{const n=await B("/api/taskforce/document-reviews/sessions",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({assetId:t.assetId,title:`Review ${y.length+1}`})},c),s=await n.json().catch(()=>({}));if(!n.ok)throw new Error(s.error||`Failed to create review (${n.status})`);const o=s.session||null;if(!o)throw new Error("Review session payload missing.");return j(d=>[o,...d.filter(f=>f.id!==o.id)]),V(o.id),o}catch(n){return A(n?.message||"Failed to create review"),null}finally{$(!1)}},[c,t.assetId,x,y.length]);i.useEffect(()=>{qe(),xe(),ve(!1),U({type:"idle"}),te(!1);const n=fe(t);g(n),ce(n),W(!1),Y(!1),P(""),Q(null),ae(!1),Ee(""),ue(null),re("")},[t,qe,xe]),i.useEffect(()=>{if(!h)return;const n=Ye.current;typeof n?.scrollIntoView=="function"&&n.scrollIntoView({block:"end"})},[h?.comments.length,h?.id]),i.useEffect(()=>{Ee(h?.title?.trim()||""),ae(!1)},[h?.id,h?.title]),i.useEffect(()=>{ge&&window.setTimeout(()=>{Be.current?.focus(),Be.current?.select()},0)},[ge]),i.useEffect(()=>{if(!t.assetId||T)return;const n=()=>{document.visibilityState==="visible"&&xe({silent:!0})},s=window.setInterval(n,15e3);return window.addEventListener("focus",n),document.addEventListener("visibilitychange",n),()=>{window.clearInterval(s),window.removeEventListener("focus",n),document.removeEventListener("visibilitychange",n)}},[t.assetId,T,xe]),i.useEffect(()=>{if(!T)return;const n=s=>{(s.metaKey||s.ctrlKey)&&s.key==="s"&&(s.preventDefault(),Qe())};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[T,G]);const ne=i.useCallback(()=>{ye.current!==null&&(window.clearTimeout(ye.current),ye.current=null),de.current&&(de.current.remove(),de.current=null)},[]);i.useEffect(()=>()=>{ne()},[ne]);const be=i.useCallback(n=>{if(!T||K!=="split")return;const s=Ie.current,o=Ve.current;if(!s||!o)return;const d=n==="editor"?s:o,f=n==="editor"?o:s,k=Math.max(d.scrollHeight-d.clientHeight,0),Z=Math.max(f.scrollHeight-f.clientHeight,0),ze=k<=0?0:d.scrollTop/k,it=Z*ze;Math.abs(f.scrollTop-it)<=1||(f.scrollTop=it)},[T,K]);i.useEffect(()=>{!T||K!=="split"||be("editor")},[G,T,K,be]);const jt=()=>{le&&(oe(b??""),U({type:"idle"}),ve(!0),setTimeout(()=>Ie.current?.focus(),50))},Ct=()=>{Le&&!window.confirm("Discard unsaved changes?")||(ve(!1),oe(b??""),U({type:"idle"}))},Qe=i.useCallback(async()=>{if(le&&X.type!=="saving"){U({type:"saving"});try{const n=await B("/api/taskforce/documents/save",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({fsPath:t.fsPath,content:G})},c),s=await n.json().catch(()=>({}));if(!n.ok)throw new Error(s.error||`Save failed (${n.status})`);const o=s.updatedAt||new Date().toISOString();L(G),U({type:"saved",savedAt:o}),r?.(o),ve(!1)}catch(n){U({type:"error",message:n?.message||"Save failed"})}}},[c,t.fsPath,G,X.type,r,le]),Nt=i.useCallback(()=>{const n=T?G:b??"";if(!n.trim())return;ne();const s=document.createElement("iframe");s.setAttribute("aria-hidden","true"),s.tabIndex=-1,s.style.position="fixed",s.style.right="0",s.style.bottom="0",s.style.width="0",s.style.height="0",s.style.border="0",s.style.opacity="0",s.style.pointerEvents="none",document.body.appendChild(s),de.current=s;const o=s.contentWindow,d=s.contentDocument;if(!o||!d){ne();return}d.open(),d.write(Ta(n)),d.close();let f=!1;const k=async()=>{f||de.current!==s||(f=!0,await Ea(o,d),de.current===s&&(o.focus(),o.print(),ye.current=Ra(ne)))};o.addEventListener("afterprint",ne,{once:!0}),k()},[ne,b,G,T]),Tt=async()=>{const n=t.apiUrl,s=new URL(ct(n,c),window.location.origin).toString();try{await navigator.clipboard.writeText(s)}catch{const o=document.createElement("textarea");o.value=s,document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o)}W(!0),setTimeout(()=>W(!1),2e3)},Et=i.useCallback(async()=>{if(_){try{await navigator.clipboard.writeText(_)}catch{const n=document.createElement("textarea");n.value=_,document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n)}Y(!0),setTimeout(()=>Y(!1),2e3)}},[_]),Rt=()=>{const n=t.apiUrl.includes("?")?"&":"?",s=ct(`${t.apiUrl}${n}download=1&filename=${encodeURIComponent(p)}`,c),o=document.createElement("a");o.href=s,o.click()},Pe=i.useCallback(async()=>{if(!t.assetId)return;const n=$e.trim();if(!n){ce(w),te(!1);return}if(n===w){te(!1);return}const s=await B(`/api/taskforce/documents/${encodeURIComponent(t.assetId)}`,{method:"PATCH",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({displayName:n})},c),o=await s.json().catch(()=>({}));if(!s.ok){window.alert(o.error||`Rename failed (${s.status})`);return}g(n),ce(n),te(!1),r?.(o.updatedAt||new Date().toISOString())},[c,t.assetId,r,w,$e]),At=i.useCallback(n=>{if(n.key==="Enter"){n.preventDefault(),Pe();return}n.key==="Escape"&&(n.preventDefault(),ce(w),te(!1))},[Pe,w]),$t=i.useCallback(async()=>{if(!(!t.assetId||we)&&window.confirm(`Permanently delete "${w}" from storage?`)){Ue(!0);try{const n=await B(`/api/taskforce/documents/${encodeURIComponent(t.assetId)}`,{method:"DELETE",credentials:"include"},c),s=await n.json().catch(()=>({}));if(!n.ok)throw new Error(s.error||`Delete failed (${n.status})`);u?.()}catch(n){window.alert(n?.message||"Delete failed")}finally{Ue(!1)}}},[c,we,t.assetId,u,w]),Lt=i.useCallback(async()=>{if(!(!h||x)){$(!0),A(null);try{const n=h.status==="resolved"?"open":"resolved",s=await B(`/api/taskforce/document-reviews/sessions/${encodeURIComponent(h.id)}`,{method:"PATCH",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:n})},c),o=await s.json().catch(()=>({}));if(!s.ok)throw new Error(o.error||`Failed to update review (${s.status})`);const d=o.session||null;if(!d)throw new Error("Review session payload missing.");j(f=>f.map(k=>k.id===d.id?d:k))}catch(n){A(n?.message||"Failed to update review")}finally{$(!1)}}},[h,c,x]),It=i.useCallback(async()=>{if(!h||x)return;const n=Te.trim();$(!0),A(null);try{const s=await B(`/api/taskforce/document-reviews/sessions/${encodeURIComponent(h.id)}`,{method:"PATCH",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:n||null})},c),o=await s.json().catch(()=>({}));if(!s.ok)throw new Error(o.error||`Failed to update review (${s.status})`);const d=o.session||null;if(!d)throw new Error("Review session payload missing.");j(f=>f.map(k=>k.id===d.id?d:k)),ae(!1)}catch(s){A(s?.message||"Failed to update review")}finally{$(!1)}},[h,c,x,Te]),Ze=T?G:b??"",Bt=i.useCallback(()=>{if(T)return;const n=typeof window.getSelection=="function"?window.getSelection():null,s=n?.toString().replace(/\s+/g," ").trim()||"";if(!n||!s)return;const o=n.rangeCount>0?n.getRangeAt(0):null,d=Xe.current;if(!o||!d)return;const f=o.commonAncestorContainer,k=f.nodeType===Node.TEXT_NODE?f.parentNode:f;if(!(k instanceof Node)||!d.contains(k))return;const Z=Ia(d,o,s);Z&&Q(Z)},[T]),et=i.useCallback(async()=>{const n=E.trim();if(!n||x)return;let s=h;if(s||(s=await De()),!!s){$(!0),A(null);try{const o=await B(`/api/taskforce/document-reviews/sessions/${encodeURIComponent(s.id)}/comments`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:n,anchor:H||{kind:"document"}})},c),d=await o.json().catch(()=>({}));if(!o.ok)throw new Error(d.error||`Failed to add comment (${o.status})`);const f=d.session||null;if(!f)throw new Error("Review session payload missing.");j(k=>{const Z=k.filter(ze=>ze.id!==f.id);return[f,...Z]}),V(f.id),P(""),Q(null)}catch(o){A(o?.message||"Failed to add comment")}finally{$(!1)}}},[h,c,De,H,x,E]),Dt=i.useCallback((n,s)=>{ue(n),re(s)},[]),Pt=i.useCallback(async()=>{if(!h||!ie||x)return;const n=pe.trim();if(n){$(!0),A(null);try{const s=await B(`/api/taskforce/document-reviews/sessions/${encodeURIComponent(h.id)}/comments/${encodeURIComponent(ie)}`,{method:"PATCH",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:n})},c),o=await s.json().catch(()=>({}));if(!s.ok)throw new Error(o.error||`Failed to update comment (${s.status})`);const d=o.session||null;if(!d)throw new Error("Review session payload missing.");j(f=>f.map(k=>k.id===d.id?d:k)),ue(null),re("")}catch(s){A(s?.message||"Failed to update comment")}finally{$(!1)}}},[h,c,pe,ie,x]),Mt=i.useCallback(async n=>{if(!(!h||x)&&window.confirm("Delete this review comment?")){$(!0),A(null);try{const s=await B(`/api/taskforce/document-reviews/sessions/${encodeURIComponent(h.id)}/comments/${encodeURIComponent(n)}`,{method:"DELETE",credentials:"include"},c),o=await s.json().catch(()=>({}));if(!s.ok)throw new Error(o.error||`Failed to delete comment (${s.status})`);const d=o.session||null;if(!d)throw new Error("Review session payload missing.");j(f=>f.map(k=>k.id===d.id?d:k)),ie===n&&(ue(null),re(""))}catch(s){A(s?.message||"Failed to delete comment")}finally{$(!1)}}},[h,c,ie,x]),tt=i.useCallback(async n=>{if(!le)return!1;U({type:"saving"});try{const s=await B("/api/taskforce/documents/save",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({fsPath:t.fsPath,content:n})},c),o=await s.json().catch(()=>({}));if(!s.ok)throw new Error(o.error||`Save failed (${s.status})`);const d=o.updatedAt||new Date().toISOString();return L(n),oe(n),U({type:"saved",savedAt:d}),r?.(d),!0}catch(s){return U({type:"error",message:s?.message||"Save failed"}),!1}},[c,t.fsPath,r,le]),zt=i.useCallback((n,s)=>{const o=T?G:b??"",d=Ba(o,n,s);if(d!==o){if(T){oe(d),U(f=>f.type==="saving"?f:{type:"idle"});return}tt(d)}},[b,G,T,tt]);let nt=-1;const Me=n=>!n||!Array.isArray(n.children)?!1:n.children.some(s=>s?s.type==="element"&&s.tagName==="input"&&s.properties?.type==="checkbox"?!0:Me(s):!1),st=n=>!n||!Array.isArray(n.children)?!1:n.children.some(s=>typeof s?.checked=="boolean"?!0:Me(s)),at={input({type:n,checked:s,...o}){if(n!=="checkbox")return e.jsx("input",{type:n,checked:s,...o});nt+=1;const d=nt;return e.jsx("input",{...o,type:"checkbox",checked:!!s,disabled:!1,onClick:f=>f.stopPropagation(),onChange:f=>zt(d,f.currentTarget.checked)})},ul({children:n,node:s,...o}){const d=st(s);return e.jsx("ul",{...o,style:d?{paddingLeft:"1.25em"}:void 0,"data-task-list":d?"true":void 0,children:n})},ol({children:n,node:s,...o}){const d=st(s);return e.jsx("ol",{...o,style:d?{paddingLeft:"1.25em"}:void 0,"data-task-list":d?"true":void 0,children:n})},li({children:n,node:s,...o}){const d=typeof s?.checked=="boolean"||Me(s);return e.jsx("li",{...o,style:d?{listStyleType:"none",listStyle:"none",marginLeft:0}:void 0,"data-task-item":d?"true":void 0,children:n})}};return e.jsxs("div",{className:`${a.viewer} ${T?a.viewerEditMode:""} ${Ke?a.viewerMonochrome:""}`,children:[e.jsxs("div",{className:a.meta,children:[e.jsxs("div",{className:a.metaLeft,children:[e.jsxs("span",{className:`${a.typeBadge} ${_a[t.docType]??""}`,children:[e.jsx(nn,{size:10}),ba[t.docType]]}),ge?e.jsx("div",{className:a.metaRenameRow,children:e.jsx("input",{ref:Be,type:"text",className:M.input,value:$e,onChange:n=>ce(n.target.value),onBlur:()=>{Pe()},onKeyDown:At})}):e.jsx("span",{className:a.metaDocumentName,title:w,onDoubleClick:()=>{t.assetId&&(ce(w),te(!0))},children:w}),l&&e.jsx("span",{className:a.metaTaskName,title:`From task: ${l}`,children:l}),Je==="unattached"&&e.jsx("span",{className:a.statusBadge,children:"Unattached"}),t.updatedAt&&e.jsxs("span",{className:a.metaDate,title:ut(t.updatedAt),children:[e.jsx(sn,{size:11}),ut(t.updatedAt)]}),e.jsxs("span",{className:a.metaSize,children:[e.jsx(an,{size:11}),Ca(t.sizeBytes)]}),_&&e.jsx(Wt,{label:_,copied:O,onClick:()=>{Et()},title:"Copy document reference"}),X.type==="saved"&&e.jsxs("span",{className:`${a.saveStatus} ${a.saveStatusSaved}`,children:[e.jsx(yt,{size:11}),"Saved"]}),X.type==="error"&&e.jsxs("span",{className:`${a.saveStatus} ${a.saveStatusError}`,title:X.message,children:[e.jsx(gt,{size:11}),X.message||"Save failed"]}),Le&&X.type!=="saving"&&e.jsx("span",{className:a.unsaved,children:"Unsaved changes"})]}),e.jsx("div",{className:a.actions,children:T?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:a.layoutToggle,children:[e.jsx("button",{className:`${a.layoutBtn} ${K==="editor"?a.layoutBtnActive:""}`,onClick:()=>Re("editor"),title:"Editor only",children:e.jsx(_e,{size:12})}),e.jsx("button",{className:`${a.layoutBtn} ${K==="split"?a.layoutBtnActive:""}`,onClick:()=>Re("split"),title:"Split view",children:e.jsx(rn,{size:12})}),e.jsx("button",{className:`${a.layoutBtn} ${K==="preview"?a.layoutBtnActive:""}`,onClick:()=>Re("preview"),title:"Preview only",children:e.jsx(Oe,{size:12})})]}),e.jsxs("button",{className:a.actionBtn,onClick:Ct,title:"Discard changes",children:[e.jsx(wt,{size:13}),"Cancel"]}),e.jsxs("button",{className:`${a.actionBtn} ${a.saveBtn}`,onClick:Qe,disabled:X.type==="saving"||!Le,title:"Save (Ctrl+S)",children:[e.jsx(on,{size:13}),X.type==="saving"?"Saving…":"Save"]})]}):e.jsxs(e.Fragment,{children:[t.assetId&&e.jsxs("button",{className:a.actionBtn,onClick:()=>te(n=>!n),title:"Rename document",children:[e.jsx(_e,{size:13}),ge?"Close Rename":"Rename"]}),le&&e.jsxs("button",{className:`${a.actionBtn} ${a.editBtn}`,onClick:jt,title:"Edit document",children:[e.jsx(_e,{size:13}),"Edit"]}),e.jsxs("button",{className:a.actionBtn,onClick:Tt,title:"Copy link",children:[e.jsx(cn,{size:13}),F?"Copied!":"Copy link"]}),e.jsxs("button",{className:a.actionBtn,onClick:Rt,title:"Download .md",children:[e.jsx(ln,{size:13}),"Download"]}),e.jsxs("button",{className:a.actionBtn,onClick:Nt,title:"Print",children:[e.jsx(dn,{size:13}),"Print"]}),e.jsxs("button",{className:a.actionBtn,onClick:()=>kt(n=>!n),title:"Toggle black and white style",children:[e.jsx(Oe,{size:13}),Ke?"Color":"B/W"]}),m&&t.docType==="implementation-plan"&&!T&&e.jsxs("button",{className:`${a.actionBtn} ${a.generateBtn}`,onClick:()=>Ae(!0),title:"Generate tasks from this plan",children:[e.jsx(He,{size:13}),"Generate Tasks"]}),St&&e.jsxs("button",{className:`${a.actionBtn} ${a.dangerBtn}`,onClick:()=>{$t()},disabled:we,title:"Permanently delete this unattached document",children:[e.jsx(un,{size:13}),we?"Deleting…":"Delete Permanently"]})]})})]}),z&&e.jsx("div",{className:a.viewerState,children:"Loading…"}),!z&&N&&e.jsx("div",{className:a.viewerStateError,children:N}),!z&&!N&&(T?e.jsxs("div",{className:`${a.editorArea} ${ka[K]}`,children:[(K==="editor"||K==="split")&&e.jsxs("div",{className:a.editorPane,children:[e.jsx("div",{className:a.editorPaneLabel,children:"Markdown"}),e.jsx("textarea",{ref:Ie,className:`${a.editorTextarea} tf-scrollbar`,value:G,onScroll:()=>be("editor"),onChange:n=>{oe(n.target.value),U(s=>s.type==="saving"?s:{type:"idle"})},spellCheck:!0,placeholder:"Write markdown here…"})]}),(K==="preview"||K==="split")&&e.jsxs("div",{className:a.previewPane,children:[e.jsx("div",{className:a.editorPaneLabel,children:"Preview"}),e.jsx("div",{ref:Ve,className:`${M.docMarkdown} ${a.markdownSurface}`,"data-testid":"doc-preview-scroll",onScroll:()=>be("preview"),children:e.jsx(ke,{remarkPlugins:[Se],rehypePlugins:[je],components:at,children:Ze})})]})]}):e.jsxs("div",{className:a.viewerBody,children:[e.jsx("div",{className:`${a.viewerContent} ${a.viewerMain} tf-scrollbar`,children:e.jsx("div",{ref:Xe,className:`${M.docMarkdown} ${a.markdownSurface}`,onMouseUp:Bt,children:e.jsx(ke,{remarkPlugins:[Se],rehypePlugins:[je],components:at,children:Ze})})}),e.jsx("aside",{className:a.reviewRail,children:e.jsxs("section",{className:a.reviewSection,"aria-label":"Review and comments",children:[e.jsxs("div",{className:a.reviewHeader,children:[e.jsxs("div",{children:[e.jsxs("div",{className:a.reviewTitle,children:[e.jsx(dt,{size:14}),"Review & Comments"]}),e.jsx("p",{className:a.reviewSubtitle,children:"Comments stay attached to this document review session."})]}),e.jsxs("div",{className:a.reviewControls,children:[y.length>1&&e.jsx("select",{className:`${M.select} ${a.reviewSelect}`,value:h?.id||"",onChange:n=>V(n.target.value||null),"aria-label":"Select review session",children:y.map(n=>e.jsx("option",{value:n.id,children:n.title?.trim()||"Untitled review"},n.id))}),e.jsxs("button",{type:"button",className:a.actionBtn,onClick:()=>{De()},disabled:x||!t.assetId,children:[e.jsx(dt,{size:13}),"Start Review"]}),h&&e.jsxs("button",{type:"button",className:a.actionBtn,onClick:()=>{Lt()},disabled:x,children:[h.status==="resolved"?e.jsx(mn,{size:13}):e.jsx(fn,{size:13}),h.status==="resolved"?"Reopen":"Resolve"]})]})]}),h&&e.jsxs("div",{className:a.reviewSessionMeta,children:[e.jsx("span",{className:`${a.statusBadge} ${h.status==="resolved"?a.reviewStatusResolved:""}`,children:h.status==="resolved"?"Resolved":"Open"}),he?e.jsxs("div",{className:a.reviewTitleEditRow,children:[e.jsx("input",{type:"text",className:M.input,value:Te,onChange:n=>Ee(n.target.value),placeholder:"Untitled review"}),e.jsx("button",{type:"button",className:M.secondaryHeaderBtn,onClick:()=>{It()},disabled:x,children:"Save Title"})]}):e.jsx("span",{className:a.reviewSessionLabel,children:h.title?.trim()||"Untitled review"}),e.jsxs("span",{className:a.reviewSessionTimestamp,children:["Updated ",mt(h.updatedAt)]}),!he&&e.jsxs("button",{type:"button",className:a.actionBtn,onClick:()=>ae(!0),disabled:x,children:[e.jsx(_e,{size:13}),"Rename Review"]})]}),ee&&e.jsx("div",{className:a.viewerStateError,children:ee}),e.jsxs("div",{className:I.commentPanel,children:[e.jsxs("div",{className:I.commentThread,children:[q&&e.jsx("div",{className:I.emptyComments,children:"Loading review comments…"}),!q&&!h&&e.jsx("div",{className:I.emptyComments,children:"Start a review to collect comments for this document."}),!q&&h&&h.comments.length===0&&e.jsx("div",{className:I.emptyComments,children:"No comments yet. Add the first review note for this document."}),!q&&h&&h.comments.map(n=>{const s=n.authorActor?.kind==="ai",o=ft(n.anchor),d=s?hn:pn,f=ie===n.id;return e.jsxs("div",{className:`${I.comment} ${s?I.commentAi:I.commentUser}`,children:[e.jsxs("div",{className:I.commentHeader,children:[e.jsxs("span",{className:I.commentAuthor,style:n.authorActor?.color?{color:n.authorActor.color}:void 0,children:[e.jsx(d,{size:12,strokeWidth:1.5}),Aa(n)]}),e.jsx("span",{className:I.commentTime,children:mt(n.updatedAt)}),e.jsxs("span",{className:a.reviewCommentActions,children:[!f&&e.jsx("button",{type:"button",className:a.reviewCommentAction,onClick:()=>Dt(n.id,n.body),disabled:x,children:"Edit"}),f&&e.jsx("button",{type:"button",className:a.reviewCommentAction,onClick:()=>{ue(null),re("")},disabled:x,children:"Cancel"}),e.jsx("button",{type:"button",className:a.reviewCommentAction,onClick:()=>{Mt(n.id)},disabled:x,children:"Delete"})]})]}),o&&e.jsx("span",{className:a.reviewAnchorLabel,children:o}),e.jsx("div",{className:I.commentText,children:f?e.jsxs("div",{className:a.reviewCommentEditor,children:[e.jsx("textarea",{className:I.commentInput,value:pe,onChange:k=>re(k.target.value),disabled:x}),e.jsx("button",{type:"button",className:M.secondaryHeaderBtn,onClick:()=>{Pt()},disabled:x||!pe.trim(),children:"Save Comment"})]}):e.jsx(ke,{remarkPlugins:[Se],rehypePlugins:[je],children:n.body})})]},n.id)}),e.jsx("div",{ref:Ye})]}),e.jsxs("div",{className:I.commentInputArea,children:[e.jsxs("div",{className:a.reviewComposer,children:[H&&e.jsxs("div",{className:a.reviewAnchorChip,children:[e.jsx("span",{children:ft(H)||"Selected text"}),"quote"in H&&H.quote&&e.jsxs("span",{className:a.reviewAnchorSnippet,children:['"',H.quote,'"']}),e.jsx("button",{type:"button",className:a.reviewAnchorClear,onClick:()=>Q(null),children:"Clear"})]}),e.jsx("textarea",{className:I.commentInput,placeholder:h?.status==="resolved"?"Reopen this review to add more comments…":H?"Add a comment for the selected text…":"Add a comment for this document review…",value:E,onChange:n=>P(n.target.value),disabled:x||h?.status==="resolved",onKeyDown:n=>{n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),et())}})]}),e.jsx("button",{type:"button",className:I.sendCommentBtn,onClick:()=>{et()},disabled:x||!E.trim()||h?.status==="resolved","aria-label":"Send review comment",title:"Send review comment",children:e.jsx(vn,{size:15})})]})]})]})})]})),m&&_t&&b!==null&&e.jsx(xa,{content:b,docTitle:t.title,apiBaseUrl:c,onClose:()=>Ae(!1),onGenerated:n=>Ae(!1)}),!T&&e.jsx("div",{className:a.printHint,children:"For the cleanest output, disable browser Headers and footers in the print dialog."})]})}function pt(t){return typeof t=="string"?t.trim().replace(/\/+$/,""):""}function Pa(t){return t.runtimeMode==="local"?"":pt(t.apiBaseUrl)||pt(t.cloudAuthBaseUrl)||""}function Ge(t){let l=t;try{l=decodeURIComponent(t)}catch{l=t}return l.trim().replace(/\\/g,"/").replace(/^\/+/,"").replace(/^\.\//,"").replace(/^\.taskforce\//,"")}function Ma(t,l){return!!(t===l||t.endsWith(`/${l}`)||l.endsWith(`/${t}`))}function vt(t){const l=Ge(String(t||""));if(!l)return null;const c=l.match(/(^|\/)(asset-[a-f0-9]{32})(?=[^/]*$)/i);return c?.[2]?c[2].toLowerCase():null}function Ce(t){return t.attachmentState==="attached"||t.attachmentState==="unattached"?t.attachmentState:(typeof t.attachmentCount=="number"&&Number.isFinite(t.attachmentCount)?t.attachmentCount:0)>0||t.taskId?"attached":"unattached"}function za({tasks:t,apiBaseUrl:l="",documents:c,loading:r,error:u,selectedDoc:m,searchQuery:v,typeFilters:S,attachmentFilters:g,onSearchChange:w,onSelectDoc:p,onRefresh:_,enableTaskGeneration:b=!1}){const L=c.filter(N=>{const F=`${fe(N)} ${N.originalFilename||""}`.toLowerCase(),W=!v||F.includes(v.toLowerCase()),O=S.length===0||S.includes(N.docType),Y=Ce(N),y=g.length===0||g.includes(Y);return W&&O&&y}),z=v.trim().length>0||S.length>0||g.length>0,D=new Map(t.map(N=>[N.id,N]));return e.jsxs("div",{className:M.docWorkspace,children:[e.jsx("div",{className:M.docIndexPanel,children:e.jsx(Hn,{documents:L,selectedDocId:m?.id??null,loading:r,error:u,searchQuery:v,onSearchChange:w,onSelect:N=>p(N),onRefresh:_,taskById:D,hasActiveFilters:z})}),e.jsx("div",{className:M.docViewerPanel,children:m?e.jsx(Da,{doc:m,taskTitle:m.taskId?D.get(m.taskId)?.title??null:null,apiBaseUrl:l,onSaved:N=>_(),onDeleted:()=>{p(null),_()},enableTaskGeneration:b}):!r&&e.jsx("div",{className:M.docViewerEmpty,children:e.jsx("p",{className:"tf-empty-copy",children:L.length===0?"No documents match your current filters.":"Select a document to view it."})})})]})}function Ua({tasks:t,runtimeMode:l="local",apiBaseUrl:c="",cloudAuthBaseUrl:r="",typeFilters:u,attachmentFilters:m,onTypeFiltersChange:v,onAttachmentFiltersChange:S,requestedDocPath:g=null,requestedDocAssetId:w=null,onRequestedDocHandled:p,enableTaskGeneration:_=!1}){const[b,L]=i.useState([]),[z,D]=i.useState(!0),[N,J]=i.useState(null),[F,W]=i.useState(null),[O,Y]=i.useState(""),[y,j]=i.useState(()=>Gt.map(E=>E.value)),[q,Ne]=i.useState(()=>Kt.map(E=>E.value)),ee=Pa({runtimeMode:l,apiBaseUrl:c,cloudAuthBaseUrl:r}),A=u??y,se=m??q,V=i.useCallback(async()=>{D(!0),J(null);try{const E=await B("/api/taskforce/documents",{credentials:"include"},ee);if(!E.ok)throw new Error(`Failed to load documents (${E.status})`);const x=(await E.json()).documents||[];Array.isArray(x)&&x.length,L(x)}catch(E){J(E?.message||"Failed to load documents"),E?.message}finally{D(!1)}},[ee,l]);return i.useEffect(()=>{V()},[V]),i.useEffect(()=>{g||w||!F&&b.length>0&&W(b[0])},[b,F,w,g]),i.useEffect(()=>{if(!g&&!w||b.length===0)return;const E=g?Ge(g):"",P=String(w||"").trim().toLowerCase()||vt(g),x=b.find($=>{const H=vt($.fsPath)||String($.assetId||"").trim().toLowerCase()||null;if(P&&H&&H===P)return!0;if(!E)return!1;const Q=Ge($.fsPath);return Ma(Q,E)});if(x){W(x),p?.();return}},[w,g,b,p]),i.useEffect(()=>{if((g||w)&&!F)return;const E=b.filter(P=>{const $=`${fe(P)} ${P.originalFilename||""}`.toLowerCase(),H=!O||$.includes(O.toLowerCase()),Q=A.length===0||A.includes(P.docType),he=Ce(P),ae=se.length===0||se.includes(he);return H&&Q&&ae});F&&E.some(P=>P.id===F.id)||W(E[0]??null)},[se,b,w,g,O,F,A]),e.jsx(za,{tasks:t,apiBaseUrl:ee,documents:b,loading:z,error:N,selectedDoc:F,searchQuery:O,typeFilters:A,attachmentFilters:se,onSearchChange:Y,onSelectDoc:W,onRefresh:V,enableTaskGeneration:_})}export{Kt as DOCUMENT_ATTACHMENT_FILTER_OPTIONS,Gt as DOCUMENT_TYPE_FILTER_OPTIONS,za as DocumentWorkspace,Ua as DocumentWorkspaceShell,Ce as getEffectiveAttachmentState};
250
+ `)}function Da({doc:t,taskTitle:l,apiBaseUrl:c="",onSaved:r,onDeleted:u,enableTaskGeneration:m=!1}){const v=fe(t),[S,g]=i.useState(v),w=S,p=Ot({...t,displayName:S}),_=Ht(t),[b,L]=i.useState(null),[z,D]=i.useState(!1),[N,J]=i.useState(null),[F,G]=i.useState(!1),[O,Y]=i.useState(!1),[y,j]=i.useState([]),[q,Ne]=i.useState(!1),[ee,A]=i.useState(null),[se,V]=i.useState(null),[E,P]=i.useState(""),[x,$]=i.useState(!1),[H,Q]=i.useState(null),[he,ae]=i.useState(!1),[Te,Ee]=i.useState(""),[ie,ue]=i.useState(null),[pe,re]=i.useState(""),[T,ve]=i.useState(!1),[W,oe]=i.useState(""),[K,Re]=i.useState("split"),[X,U]=i.useState({type:"idle"}),[_t,Ae]=i.useState(!1),[Ke,kt]=i.useState(!1),[we,Ue]=i.useState(!1),[ge,te]=i.useState(!1),[$e,ce]=i.useState(w),le=t.editable!==!1,Je=Ce(t),St=Je==="unattached"&&!!t.assetId,Le=T&&W!==(b??""),Ie=i.useRef(null),Be=i.useRef(null),Ve=i.useRef(null),de=i.useRef(null),ye=i.useRef(null),Ye=i.useRef(null),Xe=i.useRef(null),h=y.find(n=>n.id===se)||y[0]||null,qe=i.useCallback(async()=>{D(!0),J(null),L(null);try{const n=await B(t.apiUrl,{credentials:"same-origin"},c);if(!n.ok)throw new Error(`Failed to load document (${n.status})`);const s=await n.text();L(s),oe(s)}catch(n){J(n?.message||"Failed to load document")}finally{D(!1)}},[c,t.apiUrl]),xe=i.useCallback(async n=>{if(!t.assetId){j([]),V(null),A(null);return}const s=n?.silent===!0;s||(Ne(!0),A(null));try{const o=await B(`/api/taskforce/document-reviews/sessions?assetId=${encodeURIComponent(t.assetId)}`,{credentials:"include"},c),d=await o.json().catch(()=>({}));if(!o.ok)throw new Error(d.error||`Failed to load reviews (${o.status})`);const f=Array.isArray(d.sessions)?d.sessions:[];j(f),V(k=>k&&f.some(Z=>Z.id===k)?k:f[0]?.id??null)}catch(o){s||(A(o?.message||"Failed to load reviews"),j([]),V(null))}finally{s||Ne(!1)}},[c,t.assetId]),De=i.useCallback(async()=>{if(!t.assetId||x)return null;$(!0),A(null);try{const n=await B("/api/taskforce/document-reviews/sessions",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({assetId:t.assetId,title:`Review ${y.length+1}`})},c),s=await n.json().catch(()=>({}));if(!n.ok)throw new Error(s.error||`Failed to create review (${n.status})`);const o=s.session||null;if(!o)throw new Error("Review session payload missing.");return j(d=>[o,...d.filter(f=>f.id!==o.id)]),V(o.id),o}catch(n){return A(n?.message||"Failed to create review"),null}finally{$(!1)}},[c,t.assetId,x,y.length]);i.useEffect(()=>{qe(),xe(),ve(!1),U({type:"idle"}),te(!1);const n=fe(t);g(n),ce(n),G(!1),Y(!1),P(""),Q(null),ae(!1),Ee(""),ue(null),re("")},[t,qe,xe]),i.useEffect(()=>{if(!h)return;const n=Ye.current;typeof n?.scrollIntoView=="function"&&n.scrollIntoView({block:"end"})},[h?.comments.length,h?.id]),i.useEffect(()=>{Ee(h?.title?.trim()||""),ae(!1)},[h?.id,h?.title]),i.useEffect(()=>{ge&&window.setTimeout(()=>{Be.current?.focus(),Be.current?.select()},0)},[ge]),i.useEffect(()=>{if(!t.assetId||T)return;const n=()=>{document.visibilityState==="visible"&&xe({silent:!0})},s=window.setInterval(n,15e3);return window.addEventListener("focus",n),document.addEventListener("visibilitychange",n),()=>{window.clearInterval(s),window.removeEventListener("focus",n),document.removeEventListener("visibilitychange",n)}},[t.assetId,T,xe]),i.useEffect(()=>{if(!T)return;const n=s=>{(s.metaKey||s.ctrlKey)&&s.key==="s"&&(s.preventDefault(),Qe())};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[T,W]);const ne=i.useCallback(()=>{ye.current!==null&&(window.clearTimeout(ye.current),ye.current=null),de.current&&(de.current.remove(),de.current=null)},[]);i.useEffect(()=>()=>{ne()},[ne]);const be=i.useCallback(n=>{if(!T||K!=="split")return;const s=Ie.current,o=Ve.current;if(!s||!o)return;const d=n==="editor"?s:o,f=n==="editor"?o:s,k=Math.max(d.scrollHeight-d.clientHeight,0),Z=Math.max(f.scrollHeight-f.clientHeight,0),ze=k<=0?0:d.scrollTop/k,it=Z*ze;Math.abs(f.scrollTop-it)<=1||(f.scrollTop=it)},[T,K]);i.useEffect(()=>{!T||K!=="split"||be("editor")},[W,T,K,be]);const jt=()=>{le&&(oe(b??""),U({type:"idle"}),ve(!0),setTimeout(()=>Ie.current?.focus(),50))},Ct=()=>{Le&&!window.confirm("Discard unsaved changes?")||(ve(!1),oe(b??""),U({type:"idle"}))},Qe=i.useCallback(async()=>{if(le&&X.type!=="saving"){U({type:"saving"});try{const n=await B("/api/taskforce/documents/save",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({fsPath:t.fsPath,content:W})},c),s=await n.json().catch(()=>({}));if(!n.ok)throw new Error(s.error||`Save failed (${n.status})`);const o=s.updatedAt||new Date().toISOString();L(W),U({type:"saved",savedAt:o}),r?.(o),ve(!1)}catch(n){U({type:"error",message:n?.message||"Save failed"})}}},[c,t.fsPath,W,X.type,r,le]),Nt=i.useCallback(()=>{const n=T?W:b??"";if(!n.trim())return;ne();const s=document.createElement("iframe");s.setAttribute("aria-hidden","true"),s.tabIndex=-1,s.style.position="fixed",s.style.right="0",s.style.bottom="0",s.style.width="0",s.style.height="0",s.style.border="0",s.style.opacity="0",s.style.pointerEvents="none",document.body.appendChild(s),de.current=s;const o=s.contentWindow,d=s.contentDocument;if(!o||!d){ne();return}d.open(),d.write(Ta(n)),d.close();let f=!1;const k=async()=>{f||de.current!==s||(f=!0,await Ea(o,d),de.current===s&&(o.focus(),o.print(),ye.current=Ra(ne)))};o.addEventListener("afterprint",ne,{once:!0}),k()},[ne,b,W,T]),Tt=async()=>{const n=t.apiUrl,s=new URL(ct(n,c),window.location.origin).toString();try{await navigator.clipboard.writeText(s)}catch{const o=document.createElement("textarea");o.value=s,document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o)}G(!0),setTimeout(()=>G(!1),2e3)},Et=i.useCallback(async()=>{if(_){try{await navigator.clipboard.writeText(_)}catch{const n=document.createElement("textarea");n.value=_,document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n)}Y(!0),setTimeout(()=>Y(!1),2e3)}},[_]),Rt=()=>{const n=t.apiUrl.includes("?")?"&":"?",s=ct(`${t.apiUrl}${n}download=1&filename=${encodeURIComponent(p)}`,c),o=document.createElement("a");o.href=s,o.click()},Pe=i.useCallback(async()=>{if(!t.assetId)return;const n=$e.trim();if(!n){ce(w),te(!1);return}if(n===w){te(!1);return}const s=await B(`/api/taskforce/documents/${encodeURIComponent(t.assetId)}`,{method:"PATCH",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({displayName:n})},c),o=await s.json().catch(()=>({}));if(!s.ok){window.alert(o.error||`Rename failed (${s.status})`);return}g(n),ce(n),te(!1),r?.(o.updatedAt||new Date().toISOString())},[c,t.assetId,r,w,$e]),At=i.useCallback(n=>{if(n.key==="Enter"){n.preventDefault(),Pe();return}n.key==="Escape"&&(n.preventDefault(),ce(w),te(!1))},[Pe,w]),$t=i.useCallback(async()=>{if(!(!t.assetId||we)&&window.confirm(`Permanently delete "${w}" from storage?`)){Ue(!0);try{const n=await B(`/api/taskforce/documents/${encodeURIComponent(t.assetId)}`,{method:"DELETE",credentials:"include"},c),s=await n.json().catch(()=>({}));if(!n.ok)throw new Error(s.error||`Delete failed (${n.status})`);u?.()}catch(n){window.alert(n?.message||"Delete failed")}finally{Ue(!1)}}},[c,we,t.assetId,u,w]),Lt=i.useCallback(async()=>{if(!(!h||x)){$(!0),A(null);try{const n=h.status==="resolved"?"open":"resolved",s=await B(`/api/taskforce/document-reviews/sessions/${encodeURIComponent(h.id)}`,{method:"PATCH",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:n})},c),o=await s.json().catch(()=>({}));if(!s.ok)throw new Error(o.error||`Failed to update review (${s.status})`);const d=o.session||null;if(!d)throw new Error("Review session payload missing.");j(f=>f.map(k=>k.id===d.id?d:k))}catch(n){A(n?.message||"Failed to update review")}finally{$(!1)}}},[h,c,x]),It=i.useCallback(async()=>{if(!h||x)return;const n=Te.trim();$(!0),A(null);try{const s=await B(`/api/taskforce/document-reviews/sessions/${encodeURIComponent(h.id)}`,{method:"PATCH",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:n||null})},c),o=await s.json().catch(()=>({}));if(!s.ok)throw new Error(o.error||`Failed to update review (${s.status})`);const d=o.session||null;if(!d)throw new Error("Review session payload missing.");j(f=>f.map(k=>k.id===d.id?d:k)),ae(!1)}catch(s){A(s?.message||"Failed to update review")}finally{$(!1)}},[h,c,x,Te]),Ze=T?W:b??"",Bt=i.useCallback(()=>{if(T)return;const n=typeof window.getSelection=="function"?window.getSelection():null,s=n?.toString().replace(/\s+/g," ").trim()||"";if(!n||!s)return;const o=n.rangeCount>0?n.getRangeAt(0):null,d=Xe.current;if(!o||!d)return;const f=o.commonAncestorContainer,k=f.nodeType===Node.TEXT_NODE?f.parentNode:f;if(!(k instanceof Node)||!d.contains(k))return;const Z=Ia(d,o,s);Z&&Q(Z)},[T]),et=i.useCallback(async()=>{const n=E.trim();if(!n||x)return;let s=h;if(s||(s=await De()),!!s){$(!0),A(null);try{const o=await B(`/api/taskforce/document-reviews/sessions/${encodeURIComponent(s.id)}/comments`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:n,anchor:H||{kind:"document"}})},c),d=await o.json().catch(()=>({}));if(!o.ok)throw new Error(d.error||`Failed to add comment (${o.status})`);const f=d.session||null;if(!f)throw new Error("Review session payload missing.");j(k=>{const Z=k.filter(ze=>ze.id!==f.id);return[f,...Z]}),V(f.id),P(""),Q(null)}catch(o){A(o?.message||"Failed to add comment")}finally{$(!1)}}},[h,c,De,H,x,E]),Dt=i.useCallback((n,s)=>{ue(n),re(s)},[]),Pt=i.useCallback(async()=>{if(!h||!ie||x)return;const n=pe.trim();if(n){$(!0),A(null);try{const s=await B(`/api/taskforce/document-reviews/sessions/${encodeURIComponent(h.id)}/comments/${encodeURIComponent(ie)}`,{method:"PATCH",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:n})},c),o=await s.json().catch(()=>({}));if(!s.ok)throw new Error(o.error||`Failed to update comment (${s.status})`);const d=o.session||null;if(!d)throw new Error("Review session payload missing.");j(f=>f.map(k=>k.id===d.id?d:k)),ue(null),re("")}catch(s){A(s?.message||"Failed to update comment")}finally{$(!1)}}},[h,c,pe,ie,x]),Mt=i.useCallback(async n=>{if(!(!h||x)&&window.confirm("Delete this review comment?")){$(!0),A(null);try{const s=await B(`/api/taskforce/document-reviews/sessions/${encodeURIComponent(h.id)}/comments/${encodeURIComponent(n)}`,{method:"DELETE",credentials:"include"},c),o=await s.json().catch(()=>({}));if(!s.ok)throw new Error(o.error||`Failed to delete comment (${s.status})`);const d=o.session||null;if(!d)throw new Error("Review session payload missing.");j(f=>f.map(k=>k.id===d.id?d:k)),ie===n&&(ue(null),re(""))}catch(s){A(s?.message||"Failed to delete comment")}finally{$(!1)}}},[h,c,ie,x]),tt=i.useCallback(async n=>{if(!le)return!1;U({type:"saving"});try{const s=await B("/api/taskforce/documents/save",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({fsPath:t.fsPath,content:n})},c),o=await s.json().catch(()=>({}));if(!s.ok)throw new Error(o.error||`Save failed (${s.status})`);const d=o.updatedAt||new Date().toISOString();return L(n),oe(n),U({type:"saved",savedAt:d}),r?.(d),!0}catch(s){return U({type:"error",message:s?.message||"Save failed"}),!1}},[c,t.fsPath,r,le]),zt=i.useCallback((n,s)=>{const o=T?W:b??"",d=Ba(o,n,s);if(d!==o){if(T){oe(d),U(f=>f.type==="saving"?f:{type:"idle"});return}tt(d)}},[b,W,T,tt]);let nt=-1;const Me=n=>!n||!Array.isArray(n.children)?!1:n.children.some(s=>s?s.type==="element"&&s.tagName==="input"&&s.properties?.type==="checkbox"?!0:Me(s):!1),st=n=>!n||!Array.isArray(n.children)?!1:n.children.some(s=>typeof s?.checked=="boolean"?!0:Me(s)),at={input({type:n,checked:s,...o}){if(n!=="checkbox")return e.jsx("input",{type:n,checked:s,...o});nt+=1;const d=nt;return e.jsx("input",{...o,type:"checkbox",checked:!!s,disabled:!1,onClick:f=>f.stopPropagation(),onChange:f=>zt(d,f.currentTarget.checked)})},ul({children:n,node:s,...o}){const d=st(s);return e.jsx("ul",{...o,style:d?{paddingLeft:"1.25em"}:void 0,"data-task-list":d?"true":void 0,children:n})},ol({children:n,node:s,...o}){const d=st(s);return e.jsx("ol",{...o,style:d?{paddingLeft:"1.25em"}:void 0,"data-task-list":d?"true":void 0,children:n})},li({children:n,node:s,...o}){const d=typeof s?.checked=="boolean"||Me(s);return e.jsx("li",{...o,style:d?{listStyleType:"none",listStyle:"none",marginLeft:0}:void 0,"data-task-item":d?"true":void 0,children:n})}};return e.jsxs("div",{className:`${a.viewer} ${T?a.viewerEditMode:""} ${Ke?a.viewerMonochrome:""}`,children:[e.jsxs("div",{className:a.meta,children:[e.jsxs("div",{className:a.metaLeft,children:[e.jsxs("span",{className:`${a.typeBadge} ${_a[t.docType]??""}`,children:[e.jsx(nn,{size:10}),ba[t.docType]]}),ge?e.jsx("div",{className:a.metaRenameRow,children:e.jsx("input",{ref:Be,type:"text",className:M.input,value:$e,onChange:n=>ce(n.target.value),onBlur:()=>{Pe()},onKeyDown:At})}):e.jsx("span",{className:a.metaDocumentName,title:w,onDoubleClick:()=>{t.assetId&&(ce(w),te(!0))},children:w}),l&&e.jsx("span",{className:a.metaTaskName,title:`From task: ${l}`,children:l}),Je==="unattached"&&e.jsx("span",{className:a.statusBadge,children:"Unattached"}),t.updatedAt&&e.jsxs("span",{className:a.metaDate,title:ut(t.updatedAt),children:[e.jsx(sn,{size:11}),ut(t.updatedAt)]}),e.jsxs("span",{className:a.metaSize,children:[e.jsx(an,{size:11}),Ca(t.sizeBytes)]}),_&&e.jsx(Gt,{label:_,copied:O,onClick:()=>{Et()},title:"Copy document reference"}),X.type==="saved"&&e.jsxs("span",{className:`${a.saveStatus} ${a.saveStatusSaved}`,children:[e.jsx(yt,{size:11}),"Saved"]}),X.type==="error"&&e.jsxs("span",{className:`${a.saveStatus} ${a.saveStatusError}`,title:X.message,children:[e.jsx(gt,{size:11}),X.message||"Save failed"]}),Le&&X.type!=="saving"&&e.jsx("span",{className:a.unsaved,children:"Unsaved changes"})]}),e.jsx("div",{className:a.actions,children:T?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:a.layoutToggle,children:[e.jsx("button",{className:`${a.layoutBtn} ${K==="editor"?a.layoutBtnActive:""}`,onClick:()=>Re("editor"),title:"Editor only",children:e.jsx(_e,{size:12})}),e.jsx("button",{className:`${a.layoutBtn} ${K==="split"?a.layoutBtnActive:""}`,onClick:()=>Re("split"),title:"Split view",children:e.jsx(rn,{size:12})}),e.jsx("button",{className:`${a.layoutBtn} ${K==="preview"?a.layoutBtnActive:""}`,onClick:()=>Re("preview"),title:"Preview only",children:e.jsx(Oe,{size:12})})]}),e.jsxs("button",{className:a.actionBtn,onClick:Ct,title:"Discard changes",children:[e.jsx(wt,{size:13}),"Cancel"]}),e.jsxs("button",{className:`${a.actionBtn} ${a.saveBtn}`,onClick:Qe,disabled:X.type==="saving"||!Le,title:"Save (Ctrl+S)",children:[e.jsx(on,{size:13}),X.type==="saving"?"Saving…":"Save"]})]}):e.jsxs(e.Fragment,{children:[t.assetId&&e.jsxs("button",{className:a.actionBtn,onClick:()=>te(n=>!n),title:"Rename document",children:[e.jsx(_e,{size:13}),ge?"Close Rename":"Rename"]}),le&&e.jsxs("button",{className:`${a.actionBtn} ${a.editBtn}`,onClick:jt,title:"Edit document",children:[e.jsx(_e,{size:13}),"Edit"]}),e.jsxs("button",{className:a.actionBtn,onClick:Tt,title:"Copy link",children:[e.jsx(cn,{size:13}),F?"Copied!":"Copy link"]}),e.jsxs("button",{className:a.actionBtn,onClick:Rt,title:"Download .md",children:[e.jsx(ln,{size:13}),"Download"]}),e.jsxs("button",{className:a.actionBtn,onClick:Nt,title:"Print",children:[e.jsx(dn,{size:13}),"Print"]}),e.jsxs("button",{className:a.actionBtn,onClick:()=>kt(n=>!n),title:"Toggle black and white style",children:[e.jsx(Oe,{size:13}),Ke?"Color":"B/W"]}),m&&t.docType==="implementation-plan"&&!T&&e.jsxs("button",{className:`${a.actionBtn} ${a.generateBtn}`,onClick:()=>Ae(!0),title:"Generate tasks from this plan",children:[e.jsx(He,{size:13}),"Generate Tasks"]}),St&&e.jsxs("button",{className:`${a.actionBtn} ${a.dangerBtn}`,onClick:()=>{$t()},disabled:we,title:"Permanently delete this unattached document",children:[e.jsx(un,{size:13}),we?"Deleting…":"Delete Permanently"]})]})})]}),z&&e.jsx("div",{className:a.viewerState,children:"Loading…"}),!z&&N&&e.jsx("div",{className:a.viewerStateError,children:N}),!z&&!N&&(T?e.jsxs("div",{className:`${a.editorArea} ${ka[K]}`,children:[(K==="editor"||K==="split")&&e.jsxs("div",{className:a.editorPane,children:[e.jsx("div",{className:a.editorPaneLabel,children:"Markdown"}),e.jsx("textarea",{ref:Ie,className:`${a.editorTextarea} tf-scrollbar`,value:W,onScroll:()=>be("editor"),onChange:n=>{oe(n.target.value),U(s=>s.type==="saving"?s:{type:"idle"})},spellCheck:!0,placeholder:"Write markdown here…"})]}),(K==="preview"||K==="split")&&e.jsxs("div",{className:a.previewPane,children:[e.jsx("div",{className:a.editorPaneLabel,children:"Preview"}),e.jsx("div",{ref:Ve,className:`${M.docMarkdown} ${a.markdownSurface}`,"data-testid":"doc-preview-scroll",onScroll:()=>be("preview"),children:e.jsx(ke,{remarkPlugins:[Se],rehypePlugins:[je],components:at,children:Ze})})]})]}):e.jsxs("div",{className:a.viewerBody,children:[e.jsx("div",{className:`${a.viewerContent} ${a.viewerMain} tf-scrollbar`,children:e.jsx("div",{ref:Xe,className:`${M.docMarkdown} ${a.markdownSurface}`,onMouseUp:Bt,children:e.jsx(ke,{remarkPlugins:[Se],rehypePlugins:[je],components:at,children:Ze})})}),e.jsx("aside",{className:a.reviewRail,children:e.jsxs("section",{className:a.reviewSection,"aria-label":"Review and comments",children:[e.jsxs("div",{className:a.reviewHeader,children:[e.jsxs("div",{children:[e.jsxs("div",{className:a.reviewTitle,children:[e.jsx(dt,{size:14}),"Review & Comments"]}),e.jsx("p",{className:a.reviewSubtitle,children:"Comments stay attached to this document review session."})]}),e.jsxs("div",{className:a.reviewControls,children:[y.length>1&&e.jsx("select",{className:`${M.select} ${a.reviewSelect}`,value:h?.id||"",onChange:n=>V(n.target.value||null),"aria-label":"Select review session",children:y.map(n=>e.jsx("option",{value:n.id,children:n.title?.trim()||"Untitled review"},n.id))}),e.jsxs("button",{type:"button",className:a.actionBtn,onClick:()=>{De()},disabled:x||!t.assetId,children:[e.jsx(dt,{size:13}),"Start Review"]}),h&&e.jsxs("button",{type:"button",className:a.actionBtn,onClick:()=>{Lt()},disabled:x,children:[h.status==="resolved"?e.jsx(mn,{size:13}):e.jsx(fn,{size:13}),h.status==="resolved"?"Reopen":"Resolve"]})]})]}),h&&e.jsxs("div",{className:a.reviewSessionMeta,children:[e.jsx("span",{className:`${a.statusBadge} ${h.status==="resolved"?a.reviewStatusResolved:""}`,children:h.status==="resolved"?"Resolved":"Open"}),he?e.jsxs("div",{className:a.reviewTitleEditRow,children:[e.jsx("input",{type:"text",className:M.input,value:Te,onChange:n=>Ee(n.target.value),placeholder:"Untitled review"}),e.jsx("button",{type:"button",className:M.secondaryHeaderBtn,onClick:()=>{It()},disabled:x,children:"Save Title"})]}):e.jsx("span",{className:a.reviewSessionLabel,children:h.title?.trim()||"Untitled review"}),e.jsxs("span",{className:a.reviewSessionTimestamp,children:["Updated ",mt(h.updatedAt)]}),!he&&e.jsxs("button",{type:"button",className:a.actionBtn,onClick:()=>ae(!0),disabled:x,children:[e.jsx(_e,{size:13}),"Rename Review"]})]}),ee&&e.jsx("div",{className:a.viewerStateError,children:ee}),e.jsxs("div",{className:I.commentPanel,children:[e.jsxs("div",{className:I.commentThread,children:[q&&e.jsx("div",{className:I.emptyComments,children:"Loading review comments…"}),!q&&!h&&e.jsx("div",{className:I.emptyComments,children:"Start a review to collect comments for this document."}),!q&&h&&h.comments.length===0&&e.jsx("div",{className:I.emptyComments,children:"No comments yet. Add the first review note for this document."}),!q&&h&&h.comments.map(n=>{const s=n.authorActor?.kind==="ai",o=ft(n.anchor),d=s?hn:pn,f=ie===n.id;return e.jsxs("div",{className:`${I.comment} ${s?I.commentAi:I.commentUser}`,children:[e.jsxs("div",{className:I.commentHeader,children:[e.jsxs("span",{className:I.commentAuthor,style:n.authorActor?.color?{color:n.authorActor.color}:void 0,children:[e.jsx(d,{size:12,strokeWidth:1.5}),Aa(n)]}),e.jsx("span",{className:I.commentTime,children:mt(n.updatedAt)}),e.jsxs("span",{className:a.reviewCommentActions,children:[!f&&e.jsx("button",{type:"button",className:a.reviewCommentAction,onClick:()=>Dt(n.id,n.body),disabled:x,children:"Edit"}),f&&e.jsx("button",{type:"button",className:a.reviewCommentAction,onClick:()=>{ue(null),re("")},disabled:x,children:"Cancel"}),e.jsx("button",{type:"button",className:a.reviewCommentAction,onClick:()=>{Mt(n.id)},disabled:x,children:"Delete"})]})]}),o&&e.jsx("span",{className:a.reviewAnchorLabel,children:o}),e.jsx("div",{className:I.commentText,children:f?e.jsxs("div",{className:a.reviewCommentEditor,children:[e.jsx("textarea",{className:I.commentInput,value:pe,onChange:k=>re(k.target.value),disabled:x}),e.jsx("button",{type:"button",className:M.secondaryHeaderBtn,onClick:()=>{Pt()},disabled:x||!pe.trim(),children:"Save Comment"})]}):e.jsx(ke,{remarkPlugins:[Se],rehypePlugins:[je],children:n.body})})]},n.id)}),e.jsx("div",{ref:Ye})]}),e.jsxs("div",{className:I.commentInputArea,children:[e.jsxs("div",{className:a.reviewComposer,children:[H&&e.jsxs("div",{className:a.reviewAnchorChip,children:[e.jsx("span",{children:ft(H)||"Selected text"}),"quote"in H&&H.quote&&e.jsxs("span",{className:a.reviewAnchorSnippet,children:['"',H.quote,'"']}),e.jsx("button",{type:"button",className:a.reviewAnchorClear,onClick:()=>Q(null),children:"Clear"})]}),e.jsx("textarea",{className:I.commentInput,placeholder:h?.status==="resolved"?"Reopen this review to add more comments…":H?"Add a comment for the selected text…":"Add a comment for this document review…",value:E,onChange:n=>P(n.target.value),disabled:x||h?.status==="resolved",onKeyDown:n=>{n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),et())}})]}),e.jsx("button",{type:"button",className:I.sendCommentBtn,onClick:()=>{et()},disabled:x||!E.trim()||h?.status==="resolved","aria-label":"Send review comment",title:"Send review comment",children:e.jsx(vn,{size:15})})]})]})]})})]})),m&&_t&&b!==null&&e.jsx(xa,{content:b,docTitle:t.title,apiBaseUrl:c,onClose:()=>Ae(!1),onGenerated:n=>Ae(!1)}),!T&&e.jsx("div",{className:a.printHint,children:"For the cleanest output, disable browser Headers and footers in the print dialog."})]})}function pt(t){return typeof t=="string"?t.trim().replace(/\/+$/,""):""}function Pa(t){return t.runtimeMode==="local"?"":pt(t.apiBaseUrl)||pt(t.cloudAuthBaseUrl)||""}function We(t){let l=t;try{l=decodeURIComponent(t)}catch{l=t}return l.trim().replace(/\\/g,"/").replace(/^\/+/,"").replace(/^\.\//,"").replace(/^\.taskforce\//,"")}function Ma(t,l){return!!(t===l||t.endsWith(`/${l}`)||l.endsWith(`/${t}`))}function vt(t){const l=We(String(t||""));if(!l)return null;const c=l.match(/(^|\/)(asset-[a-f0-9]{32})(?=[^/]*$)/i);return c?.[2]?c[2].toLowerCase():null}function Ce(t){return t.attachmentState==="attached"||t.attachmentState==="unattached"?t.attachmentState:(typeof t.attachmentCount=="number"&&Number.isFinite(t.attachmentCount)?t.attachmentCount:0)>0||t.taskId?"attached":"unattached"}function za({tasks:t,apiBaseUrl:l="",documents:c,loading:r,error:u,selectedDoc:m,searchQuery:v,typeFilters:S,attachmentFilters:g,onSearchChange:w,onSelectDoc:p,onRefresh:_,enableTaskGeneration:b=!1}){const L=c.filter(N=>{const F=`${fe(N)} ${N.originalFilename||""}`.toLowerCase(),G=!v||F.includes(v.toLowerCase()),O=S.length===0||S.includes(N.docType),Y=Ce(N),y=g.length===0||g.includes(Y);return G&&O&&y}),z=v.trim().length>0||S.length>0||g.length>0,D=new Map(t.map(N=>[N.id,N]));return e.jsxs("div",{className:M.docWorkspace,children:[e.jsx("div",{className:M.docIndexPanel,children:e.jsx(Hn,{documents:L,selectedDocId:m?.id??null,loading:r,error:u,searchQuery:v,onSearchChange:w,onSelect:N=>p(N),onRefresh:_,taskById:D,hasActiveFilters:z})}),e.jsx("div",{className:M.docViewerPanel,children:m?e.jsx(Da,{doc:m,taskTitle:m.taskId?D.get(m.taskId)?.title??null:null,apiBaseUrl:l,onSaved:N=>_(),onDeleted:()=>{p(null),_()},enableTaskGeneration:b}):!r&&e.jsx("div",{className:M.docViewerEmpty,children:e.jsx("p",{className:"tf-empty-copy",children:L.length===0?"No documents match your current filters.":"Select a document to view it."})})})]})}function Ua({tasks:t,runtimeMode:l="local",apiBaseUrl:c="",cloudAuthBaseUrl:r="",typeFilters:u,attachmentFilters:m,onTypeFiltersChange:v,onAttachmentFiltersChange:S,requestedDocPath:g=null,requestedDocAssetId:w=null,onRequestedDocHandled:p,enableTaskGeneration:_=!1}){const[b,L]=i.useState([]),[z,D]=i.useState(!0),[N,J]=i.useState(null),[F,G]=i.useState(null),[O,Y]=i.useState(""),[y,j]=i.useState(()=>Wt.map(E=>E.value)),[q,Ne]=i.useState(()=>Kt.map(E=>E.value)),ee=Pa({runtimeMode:l,apiBaseUrl:c,cloudAuthBaseUrl:r}),A=u??y,se=m??q,V=i.useCallback(async()=>{D(!0),J(null);try{const E=await B("/api/taskforce/documents",{credentials:"include"},ee);if(!E.ok)throw new Error(`Failed to load documents (${E.status})`);const x=(await E.json()).documents||[];Array.isArray(x)&&x.length,L(x)}catch(E){J(E?.message||"Failed to load documents"),E?.message}finally{D(!1)}},[ee,l]);return i.useEffect(()=>{V()},[V]),i.useEffect(()=>{g||w||!F&&b.length>0&&G(b[0])},[b,F,w,g]),i.useEffect(()=>{if(!g&&!w||b.length===0)return;const E=g?We(g):"",P=String(w||"").trim().toLowerCase()||vt(g),x=b.find($=>{const H=vt($.fsPath)||String($.assetId||"").trim().toLowerCase()||null;if(P&&H&&H===P)return!0;if(!E)return!1;const Q=We($.fsPath);return Ma(Q,E)});if(x){G(x),p?.();return}},[w,g,b,p]),i.useEffect(()=>{if((g||w)&&!F)return;const E=b.filter(P=>{const $=`${fe(P)} ${P.originalFilename||""}`.toLowerCase(),H=!O||$.includes(O.toLowerCase()),Q=A.length===0||A.includes(P.docType),he=Ce(P),ae=se.length===0||se.includes(he);return H&&Q&&ae});F&&E.some(P=>P.id===F.id)||G(E[0]??null)},[se,b,w,g,O,F,A]),e.jsx(za,{tasks:t,apiBaseUrl:ee,documents:b,loading:z,error:N,selectedDoc:F,searchQuery:O,typeFilters:A,attachmentFilters:se,onSearchChange:Y,onSelectDoc:G,onRefresh:V,enableTaskGeneration:_})}export{Kt as DOCUMENT_ATTACHMENT_FILTER_OPTIONS,Wt as DOCUMENT_TYPE_FILTER_OPTIONS,za as DocumentWorkspace,Ua as DocumentWorkspaceShell,Ce as getEffectiveAttachmentState};
@@ -1 +1 @@
1
- import{r as i,j as s}from"./vendor-react-CKJs5o3c.js";import{t as e}from"./index-Bzqy5QGm.js";import{h as g,Z as v,b as j,k as f}from"./vendor-icons-QZyhEwgT.js";import"./vendor-markdown-BUxTU7dS.js";import"./vendor-dnd-DRzYolkg.js";import"./vendor-router-BbWMxlnO.js";function T({initiativeTemplates:n,onRefreshInitiativeTemplates:u,onCreateInitiativeFromTemplate:l}){const[a,o]=i.useState(""),[c,x]=i.useState(""),[d,m]=i.useState(!1),[r,p]=i.useState(null);return i.useEffect(()=>{if(!a&&n.length>0){const t=n[0];o(t.id)}},[n,a]),s.jsx("div",{className:`${e.standalonePage} ${e.standaloneContent}`,style:{overflow:"auto"},children:s.jsx("div",{className:e.settingsContent,style:{maxWidth:900,margin:"0 auto",width:"100%"},children:s.jsxs("div",{className:e.settingGroup,children:[s.jsxs("div",{className:e.settingTitleRow,children:[s.jsx("h2",{className:e.settingTitle,children:"Initiatives"}),s.jsx("button",{className:e.copyBtn,onClick:()=>{u?.()},children:"Refresh"})]}),s.jsx("p",{className:`${e.settingsHint} ${e.marginBottom12}`,children:"Create initiative-ready planning structures from reusable templates."}),s.jsxs("div",{className:e.exportItem,children:[s.jsx("label",{className:e.label,children:"Template"}),s.jsx("select",{className:e.input,value:a,onChange:t=>{const h=t.target.value;o(h)},children:n.map(t=>s.jsx("option",{value:t.id,children:t.name},t.id))})]}),s.jsxs("div",{className:`${e.exportItem} ${e.marginTop12}`,children:[s.jsx("label",{className:e.label,children:"Initiative Title"}),s.jsx("input",{className:e.input,placeholder:"e.g. Taskforce Private Beta Launch",value:c,onChange:t=>x(t.target.value)})]}),s.jsxs("button",{className:`${e.secondaryHeaderBtn} ${e.marginTop12}`,disabled:d||!a||!c.trim()||!l,onClick:async()=>{if(!l)return;m(!0);const t=await l({templateId:a,title:c.trim()});m(!1),p({type:t.success?"success":"error",message:t.success?"Initiative created from template.":t.error||"Failed to create initiative."})},children:[d?s.jsx(g,{size:14,className:e.spinner}):s.jsx(v,{size:14}),"Create Initiative"]}),r&&s.jsxs("div",{className:`${r.type==="success"?e.successMessage:e.errorMessage} ${e.marginTop12}`,children:[r.type==="success"?s.jsx(j,{size:14}):s.jsx(f,{size:14}),r.message]})]})})})}export{T as InitiativesModule};
1
+ import{r as i,j as s}from"./vendor-react-CKJs5o3c.js";import{t as e}from"./index-YJ4k5QNa.js";import{h as g,Z as v,b as j,k as f}from"./vendor-icons-C8EED3Oh.js";import"./vendor-markdown-BUxTU7dS.js";import"./vendor-dnd-DRzYolkg.js";import"./vendor-router-BbWMxlnO.js";function T({initiativeTemplates:n,onRefreshInitiativeTemplates:u,onCreateInitiativeFromTemplate:l}){const[a,o]=i.useState(""),[c,x]=i.useState(""),[d,m]=i.useState(!1),[r,p]=i.useState(null);return i.useEffect(()=>{if(!a&&n.length>0){const t=n[0];o(t.id)}},[n,a]),s.jsx("div",{className:`${e.standalonePage} ${e.standaloneContent}`,style:{overflow:"auto"},children:s.jsx("div",{className:e.settingsContent,style:{maxWidth:900,margin:"0 auto",width:"100%"},children:s.jsxs("div",{className:e.settingGroup,children:[s.jsxs("div",{className:e.settingTitleRow,children:[s.jsx("h2",{className:e.settingTitle,children:"Initiatives"}),s.jsx("button",{className:e.copyBtn,onClick:()=>{u?.()},children:"Refresh"})]}),s.jsx("p",{className:`${e.settingsHint} ${e.marginBottom12}`,children:"Create initiative-ready planning structures from reusable templates."}),s.jsxs("div",{className:e.exportItem,children:[s.jsx("label",{className:e.label,children:"Template"}),s.jsx("select",{className:e.input,value:a,onChange:t=>{const h=t.target.value;o(h)},children:n.map(t=>s.jsx("option",{value:t.id,children:t.name},t.id))})]}),s.jsxs("div",{className:`${e.exportItem} ${e.marginTop12}`,children:[s.jsx("label",{className:e.label,children:"Initiative Title"}),s.jsx("input",{className:e.input,placeholder:"e.g. Taskforce Private Beta Launch",value:c,onChange:t=>x(t.target.value)})]}),s.jsxs("button",{className:`${e.secondaryHeaderBtn} ${e.marginTop12}`,disabled:d||!a||!c.trim()||!l,onClick:async()=>{if(!l)return;m(!0);const t=await l({templateId:a,title:c.trim()});m(!1),p({type:t.success?"success":"error",message:t.success?"Initiative created from template.":t.error||"Failed to create initiative."})},children:[d?s.jsx(g,{size:14,className:e.spinner}):s.jsx(v,{size:14}),"Create Initiative"]}),r&&s.jsxs("div",{className:`${r.type==="success"?e.successMessage:e.errorMessage} ${e.marginTop12}`,children:[r.type==="success"?s.jsx(j,{size:14}):s.jsx(f,{size:14}),r.message]})]})})})}export{T as InitiativesModule};
@@ -0,0 +1 @@
1
+ import{r as a,j as e}from"./vendor-react-CKJs5o3c.js";import{t as ue,y as de,z,B as pe,C as me}from"./index-YJ4k5QNa.js";import{aI as ge,h as fe,U as he}from"./vendor-icons-C8EED3Oh.js";import{u as ye,a as _e}from"./vendor-router-BbWMxlnO.js";import"./vendor-markdown-BUxTU7dS.js";import"./vendor-dnd-DRzYolkg.js";const be="_plansWrapper_b8yvs_1",ve="_contentFrame_b8yvs_28",Se="_shellOwnsScroll_b8yvs_36",Ce="_withChrome_b8yvs_42",ke="_siteVariant_b8yvs_46",xe="_title_b8yvs_54",we="_subtitle_b8yvs_63",Ie="_header_b8yvs_67",je="_planCard_b8yvs_79",Ne="_grid_b8yvs_92",Te="_planName_b8yvs_98",Re="_featureText_b8yvs_102",Pe="_currentBadge_b8yvs_106",Be="_navAction_b8yvs_110",$e="_backBtn_b8yvs_111",Ee="_priceRows_b8yvs_122",Ue="_headerBar_b8yvs_139",Ae="_headerActions_b8yvs_148",Fe="_debugMeta_b8yvs_175",Le="_clickablePlanCard_b8yvs_204",Me="_activePlanCard_b8yvs_219",Ve="_callToAction_b8yvs_272",Oe="_primaryCta_b8yvs_284",Ye="_secondaryCta_b8yvs_295",qe="_currentCta_b8yvs_307",ze="_featuresList_b8yvs_321",De="_priceRow_b8yvs_122",Ge="_priceRowAmount_b8yvs_346",He="_priceRowInterval_b8yvs_352",We="_ctaRow_b8yvs_357",Qe="_featureItem_b8yvs_363",Ke="_featureIcon_b8yvs_369",Je="_emptyState_b8yvs_383",Xe="_marketingEmptyState_b8yvs_392",Ze="_emptyBadge_b8yvs_420",et="_emptyHighlights_b8yvs_435",tt="_loader_b8yvs_457",nt="_spinner_b8yvs_467",rt="_statusBanner_b8yvs_520",st="_successBanner_b8yvs_528",at="_errorBanner_b8yvs_534",n={plansWrapper:be,contentFrame:ve,shellOwnsScroll:Se,withChrome:Ce,siteVariant:ke,title:xe,subtitle:we,header:Ie,planCard:je,grid:Ne,planName:Te,featureText:Re,currentBadge:Pe,navAction:Be,backBtn:$e,priceRows:Ee,headerBar:Ue,headerActions:Ae,debugMeta:Fe,clickablePlanCard:Le,activePlanCard:Me,callToAction:Ve,primaryCta:Oe,secondaryCta:Ye,currentCta:qe,featuresList:ze,priceRow:De,priceRowAmount:Ge,priceRowInterval:He,ctaRow:We,featureItem:Qe,featureIcon:Ke,emptyState:Je,marketingEmptyState:Xe,emptyBadge:Ze,emptyHighlights:et,loader:tt,spinner:nt,statusBanner:rt,successBanner:st,errorBanner:at};function it(){const r=globalThis.__DEBUG_MODE__;return typeof r=="boolean"?r:!1}function ot(r){const i=String(r?.environment||"").trim(),_=String(r?.runtimeMode||"").trim();return!i&&!_?null:i&&_?`${i} (${_})`:i||_||null}function ct(r,i){if(r==null||!i)return"Contact Sales";try{return new Intl.NumberFormat("en-US",{style:"currency",currency:i.toUpperCase(),minimumFractionDigits:0}).format(r/100)}catch{return`${i.toUpperCase()} ${r/100}`}}function lt(){return"$0.00"}function ie(r){return r?r.pricingType==="free"?!0:r.unitAmount!=null&&r.currency!=null:!1}function oe(r){return r?r.pricingType==="free"?lt():ct(r.unitAmount,r.currency):"Unavailable"}function ce(r){const i=[r.pricing.month,r.pricing.year].filter(Boolean);if(i.some(m=>m.pricingType==="free"))return 0;const _=i.map(m=>m.pricingType==="stripe"&&typeof m.unitAmount=="number"?m.unitAmount:null).filter(m=>m!=null);return _.length>0?Math.min(..._):Number.POSITIVE_INFINITY}function ut(r){const i=String(r||"").trim().toLowerCase();return i==="active"||i==="trialing"||i==="grace"}function dt({heading:r,subtitle:i,variant:_="app",chrome:m,footer:P,isAuthenticated:B,authSessionResolved:D=!0,currentPlanId:V,currentPlanVersionId:C,currentEntitlementState:X,canManageCurrentPlan:d=!0,pricingEndpoint:f,statusBanner:b,onBack:G,backLabel:H,topActions:$,shellOwnsScroll:W=!1,showPageBackButton:c=!0,fallbackPricingSource:U=null,onSelectPlan:S}){const[w,E]=a.useState([]),[I,Q]=a.useState(null),[A,O]=a.useState(!0),[F,k]=a.useState(null),[K,Z]=a.useState(0);a.useEffect(()=>{let s=!0;return(async()=>{const y=String(f||"/api/taskforce/public/pricing").trim()||"/api/taskforce/public/pricing";s&&(O(!0),k(null));try{const l=await fetch(y,{method:"GET",credentials:"include"}),u=await l.json().catch(()=>({}));if(l.ok){s&&(E(Array.isArray(u?.plans)?u.plans:[]),Q(u?.pricingSource&&typeof u.pricingSource=="object"?u.pricingSource:null));return}throw new Error(String(u?.error||`Failed to load pricing (${l.status})`))}catch(l){if(s){const u=l instanceof Error?l.message:"Failed to load pricing";k(u||"Failed to load pricing"),Q(null)}}finally{s&&O(!1)}})(),()=>{s=!1}},[f,K]);const h=a.useMemo(()=>[...w].sort((s,g)=>{const y=ce(s),l=ce(g);if(y!==l)return y-l;const u=s.defaultVersion?.versionNumber||0,p=g.defaultVersion?.versionNumber||0;return u!==p?u-p:String(s.displayName||s.planId).localeCompare(String(g.displayName||g.planId))}),[w]),Y=a.useMemo(()=>ot(I||U),[U,I]),q=`${n.plansWrapper} ${W?n.shellOwnsScroll:"tf-scrollbar"} ${_==="site"?n.siteVariant:""} ${m?n.withChrome:""}`.trim(),j=s=>W?e.jsxs(e.Fragment,{children:[m,s,P]}):e.jsxs("div",{className:ue.standaloneWrapper,"data-theme":"dark",children:[m,s,P]});return j(A||!D?e.jsx(e.Fragment,{children:e.jsx("div",{className:q,children:e.jsx("div",{className:n.contentFrame,children:e.jsxs("div",{className:n.loader,children:[e.jsx(fe,{size:48,className:n.spinner}),e.jsx("p",{children:"Loading plans..."})]})})})}):F?e.jsx(e.Fragment,{children:e.jsx("div",{className:q,children:e.jsx("div",{className:n.contentFrame,children:e.jsxs("div",{className:n.emptyState,children:[e.jsx("h2",{children:"Connecting to plan pricing..."}),e.jsx("p",{children:F}),e.jsx("button",{className:n.backBtn,onClick:()=>Z(s=>s+1),children:"Retry"})]})})})}):e.jsx(e.Fragment,{children:e.jsx("div",{className:q,children:e.jsxs("div",{className:n.contentFrame,children:[e.jsxs("div",{className:n.header,children:[!m&&(c||$)&&e.jsxs("div",{className:n.headerBar,children:[e.jsx("div",{children:c?e.jsx("button",{className:n.backBtn,onClick:G,children:H}):null}),e.jsx("div",{className:n.headerActions,children:$})]}),e.jsx("h1",{className:n.title,children:r}),i&&e.jsx("p",{className:n.subtitle,children:i}),it()&&Y?e.jsxs("p",{className:n.debugMeta,children:["Pricing source: ",Y]}):null,b&&e.jsx("div",{className:`${n.statusBanner} ${b.type==="success"?n.successBanner:n.errorBanner}`,children:b.message})]}),h.length===0?e.jsxs("div",{className:`${n.emptyState} ${n.marketingEmptyState}`,children:[e.jsx("span",{className:n.emptyBadge,children:"Coming Soon"}),e.jsx("h2",{children:"Paid plans are getting their final polish."}),e.jsx("p",{children:"Taskforce pricing is on the way with flexible options for solo operators, teams, and larger rollouts. Check back soon for launch tiers, feature bundles, and early access details."}),e.jsxs("div",{className:n.emptyHighlights,"aria-label":"Upcoming pricing highlights",children:[e.jsx("span",{children:"Launch-ready tiers"}),e.jsx("span",{children:"Team billing controls"}),e.jsx("span",{children:"Feature-based packaging"})]})]}):e.jsx("div",{className:n.grid,children:h.map(s=>{const g=s.pricing.month,y=s.pricing.year,l=ie(g),u=ie(y),p=String(s.defaultVersion?.planVersionId||"").trim(),x=!!(p&&C&&C===p&&ut(X))||!C&&!!(V&&V===s.planId),N=l?"month":u?"year":null,L=N==="year"?y:g,T=!!p&&(x?d:!!N),J=()=>{if(p){if(x){if(!d)return;S({planId:s.planId,planVersionId:p,interval:N||"month",pricingType:L?.pricingType||"stripe",isCurrentPlan:!0});return}N&&S({planId:s.planId,planVersionId:p,interval:N,pricingType:L?.pricingType||"stripe",isCurrentPlan:!1})}};return e.jsxs("div",{className:`${n.planCard} ${x?n.activePlanCard:""} ${T?n.clickablePlanCard:""}`,"data-testid":`plan-card-${s.planId}`,role:T?"button":void 0,tabIndex:T?0:void 0,onClick:T?J:void 0,onKeyDown:T?t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),J())}:void 0,children:[x&&e.jsx("span",{className:n.currentBadge,children:"Current Plan"}),e.jsx("h3",{className:n.planName,children:s.displayName}),e.jsx("div",{className:n.featuresList,children:Array.isArray(s.features)&&s.features.length>0?s.features.map((t,o)=>e.jsxs("div",{className:n.featureItem,children:[e.jsx(ge,{className:n.featureIcon}),e.jsx("span",{className:n.featureText,children:String(t.featureKey||"").replace(/[_\-.]+/g," ").replace(/\b\w/g,v=>v.toUpperCase())})]},`${t.featureKey}-${o}`)):e.jsx("span",{className:n.featureText,children:"No additional features included"})}),e.jsxs("div",{className:n.priceRows,children:[e.jsxs("div",{className:n.priceRow,children:[e.jsx("span",{className:n.priceRowAmount,children:oe(g)}),e.jsx("span",{className:n.priceRowInterval,children:"/ month"})]}),e.jsxs("div",{className:n.priceRow,children:[e.jsx("span",{className:n.priceRowAmount,children:oe(y)}),e.jsx("span",{className:n.priceRowInterval,children:"/ year"})]})]}),x?e.jsx("button",{className:`${n.callToAction} ${n.currentCta}`,"data-testid":`plan-manage-${s.planId}`,onClick:t=>{t.stopPropagation(),d&&S({planId:s.planId,planVersionId:p,interval:N||"month",pricingType:L?.pricingType||"stripe",isCurrentPlan:!0})},disabled:!p||!d,children:B&&d?"Manage Plan":"Current Plan"}):e.jsxs("div",{className:n.ctaRow,children:[e.jsx("button",{className:`${n.callToAction} ${n.secondaryCta}`,"data-testid":`plan-select-${s.planId}-month`,onClick:t=>{t.stopPropagation(),S({planId:s.planId,planVersionId:p,interval:"month",pricingType:g?.pricingType||"stripe",isCurrentPlan:!1})},disabled:!p||!l,children:g?.pricingType==="free"?B?"Select Free":"Get Started Free":B?"Choose Monthly":"Get Started Monthly"}),e.jsx("button",{className:`${n.callToAction} ${n.primaryCta}`,"data-testid":`plan-select-${s.planId}-year`,onClick:t=>{t.stopPropagation(),S({planId:s.planId,planVersionId:p,interval:"year",pricingType:y?.pricingType||"stripe",isCurrentPlan:!1})},disabled:!p||!u,children:y?.pricingType==="free"?B?"Select Free":"Get Started Free":B?"Choose Yearly":"Get Started Yearly"})]})]},s.planId)})})]})})}))}const pt=1600,mt=new Set(["active","trialing","grace"]),M={planSelectionRequired:"Choose a plan to continue.",misconfigured:"Signup monetization is misconfigured. Contact support or a system administrator.",missingEntitlement:"No entitlement is linked to this account."};function gt(r){return r==="year"?"year":"month"}function le(r){const i=String(r||"").trim();return i?i.replace(/\/+$/,""):""}function ne(r={}){const i=new URLSearchParams;i.set("screen","plans");for(const[_,m]of Object.entries(r)){const P=String(m||"").trim();P&&i.set(_,P)}return`/?${i.toString()}`}function St({isAuthenticated:r,runtimeMode:i,authSessionResolved:_,currentTheme:m="dark",projectName:P,currentWorkspaceId:B,apiBaseUrl:D,connectedEnvironmentSource:V,embedded:C=!1,shellOwnsScroll:X=!1}){const d=ye(),f=_e(),[b,G]=a.useState(null),[H,$]=a.useState(!1),[W,c]=a.useState(null),U=a.useRef(!1),S=a.useRef(null),w=a.useMemo(()=>new URLSearchParams(f.search),[f.search]),E=String(w.get("checkout")||"").trim().toLowerCase(),I=String(w.get("gate")||"").trim().toLowerCase(),Q=String(w.get("planId")||"").trim(),A=String(w.get("planVersionId")||"").trim(),O=gt(w.get("interval")),F=String(w.get("session_id")||"").trim(),k=a.useMemo(()=>le(D),[D]),K=a.useMemo(()=>le(V),[V]),Z=a.useMemo(()=>({environment:de(K||k),runtimeMode:i==="cloud"?"cloud":"local"}),[k,K,i]),h=a.useCallback(t=>{const o=String(t||"").trim();return k?`${k}${o.startsWith("/")?o:`/${o}`}`:o},[k]),Y=a.useCallback(()=>{const t=new URLSearchParams(f.search);t.delete("screen"),t.delete("gate"),t.delete("checkout"),t.delete("planId"),t.delete("planVersionId"),t.delete("interval");const o=t.toString();d(`/${o?`?${o}`:""}${f.hash||""}`)},[f.hash,f.search,d]),q=a.useMemo(()=>[k?`${k}/api/taskforce/public/pricing`:"","/api/taskforce/public/pricing"].map(o=>String(o||"").trim()).filter((o,v,R)=>o&&R.indexOf(o)===v),[k]),j=a.useMemo(()=>{const t=String(b?.entitlementState||"").trim().toLowerCase();return mt.has(t)},[b?.entitlementState]),s=a.useMemo(()=>j?null:I==="plan_selection_required"?M.planSelectionRequired:I==="misconfigured"?M.misconfigured:I==="missing_entitlement"?M.missingEntitlement:null,[I,j]),g=a.useCallback(()=>{const t=new URLSearchParams(f.search);t.delete("checkout"),t.delete("session_id"),t.delete("gate"),t.delete("planId"),t.delete("planVersionId"),t.delete("interval");const o=t.toString();d(`${f.pathname}${o?`?${o}`:""}${f.hash||""}`,{replace:!0})},[f.hash,f.pathname,f.search,d]),y=a.useCallback(()=>{S.current!=null&&window.clearTimeout(S.current),S.current=window.setTimeout(()=>{g(),S.current=null},pt)},[g]),l=a.useCallback(async()=>{const t=h("/api/taskforce/billing/status");if(!r){G(null),z(t);return}try{const o=await pe(t);G(o)}catch{}},[h,r]),u=a.useCallback(async(t,o)=>{if(!t){c({type:"error",message:"Selected plan is missing a default plan version."});return}$(!0),c(null);try{const v=await fetch(h("/api/taskforce/billing/checkout-session"),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({planVersionId:t,interval:o})}),R=await v.json().catch(()=>({}));if(!v.ok){c({type:"error",message:String(R?.error||"Unable to start checkout for selected plan.")});return}const ee=String(R?.checkoutState||"").trim().toLowerCase();if(ee==="free"){c({type:"success",message:"Plan selected. Your access is ready."}),z(h("/api/taskforce/billing/status")),await l();return}if(ee==="updated"){c({type:"success",message:String(R?.message||"Your subscription was updated successfully.")}),z(h("/api/taskforce/billing/status")),await l();return}if(ee==="already_current_plan"){c({type:"success",message:String(R?.message||"You are already on this plan.")}),z(h("/api/taskforce/billing/status")),await l();return}const re=String(R?.returnBaseUrl||"").trim();if(i==="local"&&re)try{const te=window.location.origin,ae=new URL(re,te).origin;if(ae!==te){c({type:"error",message:`Checkout return is misconfigured for this runtime. Expected ${te} but got ${ae}.`});return}}catch{c({type:"error",message:"Checkout return URL is invalid for this runtime."});return}const se=String(R?.url||"").trim();if(!se){c({type:"error",message:"Checkout did not return a redirect URL."});return}window.location.assign(se)}catch{c({type:"error",message:"Unable to start checkout for selected plan."})}finally{$(!1)}},[h,l]),p=a.useCallback(async t=>{if(!t)return!1;try{const o=await fetch(h("/api/taskforce/billing/checkout-session/confirm"),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:t})}),v=await o.json().catch(()=>({}));return o.ok?(z(h("/api/taskforce/billing/status")),await l(),!0):(c({type:"error",message:String(v?.error||"Unable to confirm checkout completion.")}),!1)}catch{return c({type:"error",message:"Unable to confirm checkout completion."}),!1}},[h,l]),x=a.useCallback(async()=>{if(!r){d(`/login?mode=login&next=${encodeURIComponent(ne())}`);return}$(!0),c(null);try{const t=await fetch(h("/api/taskforce/billing/portal-session"),{method:"POST",credentials:"include"}),o=await t.json().catch(()=>({}));if(!t.ok){c({type:"error",message:String(o?.error||"Failed to open billing portal.")});return}const v=String(o?.url||"").trim();if(!v){c({type:"error",message:"Portal session did not return a redirect URL."});return}window.location.assign(v)}catch{c({type:"error",message:"Failed to open billing portal."})}finally{$(!1)}},[h,r,d]);a.useEffect(()=>{l()},[l]),a.useEffect(()=>{j&&I==="missing_entitlement"&&g()},[g,I,j]),a.useEffect(()=>()=>{S.current!=null&&window.clearTimeout(S.current)},[]),a.useEffect(()=>{if(E==="success"){U.current=!0,c({type:"success",message:"Checkout completed successfully. Finalizing your plan..."}),(async()=>(F&&await p(F)||await l(),c({type:"success",message:"Checkout completed successfully."}),y()))();return}if(E==="cancel"){c({type:"error",message:"Checkout was canceled. No charge was made."}),y();return}if((E==="start"||E==="free")&&r&&A&&!U.current){U.current=!0,u(A,O);return}if(s){c({type:"error",message:s});return}c(t=>!t||t.type!=="error"?t:t.message===M.planSelectionRequired||t.message===M.misconfigured||t.message===M.missingEntitlement?null:t)},[E,p,s,r,l,O,A,F,y,u]);const N=a.useCallback(async t=>{if(!r){const o=t.pricingType==="free"?"free":"start",v=ne({checkout:o,planId:t.planId,planVersionId:t.planVersionId,interval:t.interval});d(`/login?mode=register&planId=${encodeURIComponent(t.planId)}&planVersionId=${encodeURIComponent(t.planVersionId)}&interval=${encodeURIComponent(t.interval)}&next=${encodeURIComponent(v)}`);return}if(t.isCurrentPlan){if(!b?.stripeCustomerId){c({type:"success",message:"Your current plan does not use Stripe billing."});return}await x();return}if(t.pricingType==="free"){await u(t.planVersionId,t.interval);return}await u(t.planVersionId,t.interval)},[r,d,x,u]),L=a.useCallback(()=>{if(C){Y();return}if(window.history.length>1){d(-1);return}d("/")},[Y,C,d]),T=C?e.jsx(e.Fragment,{children:r&&b?.stripeCustomerId&&e.jsx("button",{className:n.navAction,onClick:()=>{x()},disabled:H,children:"Manage billing"})}):e.jsxs(e.Fragment,{children:[e.jsx("button",{className:n.navAction,onClick:L,children:"Back"}),r&&b?.stripeCustomerId&&e.jsx("button",{className:n.navAction,onClick:()=>{x()},disabled:H,children:"Manage billing"}),!r&&e.jsxs("button",{className:n.navAction,onClick:()=>d(`/login?mode=login&next=${encodeURIComponent(ne())}`),children:[e.jsx(he,{size:16,style:{marginRight:"8px",verticalAlign:"text-bottom"}}),"Sign In"]})]}),J=C?null:e.jsx(me,{projectName:P,currentWorkspaceId:B,runtimeMode:i==="cloud"?"cloud":"local",theme:m,actions:T});return e.jsx(dt,{chrome:J,heading:"Subscription Plans",subtitle:"Manage your subscription and explore available features. Your current plan is highlighted below.",isAuthenticated:r,authSessionResolved:_,currentPlanId:String(b?.planId||Q||"").trim()||null,currentPlanVersionId:String(b?.planVersionId||A||"").trim()||null,currentEntitlementState:String(b?.entitlementState||"").trim()||null,canManageCurrentPlan:!!b?.stripeCustomerId,pricingEndpoint:q[0],statusBanner:W,onBack:L,backLabel:C?"Back to Board":"Back to App",topActions:C?T:null,shellOwnsScroll:X,showPageBackButton:!C,fallbackPricingSource:Z,onSelectPlan:N})}export{St as PlansPage};