@taskforcehq/taskforce 0.3.327 → 0.3.328

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 (187) hide show
  1. package/dist/Taskforce.module.css +24 -53
  2. package/dist/components/activity/EntityActivityTimeline.js +15 -5
  3. package/dist/components/context/AttachmentPreviewHost.js +1 -1
  4. package/dist/components/context/ContextAttachmentManager.d.ts +3 -0
  5. package/dist/components/context/ContextAttachmentManager.js +116 -20
  6. package/dist/components/features/planning/PlanningEntitySummary.d.ts +3 -1
  7. package/dist/components/features/planning/PlanningEntitySummary.js +3 -2
  8. package/dist/components/features/planning/PlanningLinkPicker.d.ts +3 -1
  9. package/dist/components/features/planning/PlanningLinkPicker.js +5 -3
  10. package/dist/components/features/planning/PlanningModule.js +26 -9
  11. package/dist/components/features/planning/PlanningVisualIdentity.d.ts +14 -0
  12. package/dist/components/features/planning/PlanningVisualIdentity.js +106 -0
  13. package/dist/components/features/planning/planningWorkspaceModel.d.ts +11 -0
  14. package/dist/components/task/TaskActionHeader.d.ts +2 -1
  15. package/dist/components/task/TaskActionHeader.js +2 -2
  16. package/dist/components/task/TaskCard.js +37 -4
  17. package/dist/components/task/TaskContextUpload.d.ts +3 -0
  18. package/dist/components/task/TaskContextUpload.js +2 -2
  19. package/dist/components/task/TaskForm.d.ts +4 -0
  20. package/dist/components/task/TaskForm.js +32 -7
  21. package/dist/components/task/TaskImageReviews.js +16 -16
  22. package/dist/components/task/TaskStatusActions.js +11 -2
  23. package/dist/components/task/TaskWorkstreamPicker.js +2 -1
  24. package/dist/components/ui/DocumentTypeIcon.d.ts +7 -0
  25. package/dist/components/ui/DocumentTypeIcon.js +8 -0
  26. package/dist/components/ui/TaxonomyDropdown.d.ts +9 -1
  27. package/dist/components/ui/TaxonomyDropdown.js +30 -3
  28. package/dist/components/views/StandaloneLayout.js +62 -9
  29. package/dist/components/views/WidgetView.js +8 -5
  30. package/dist/components/views/panels/PlanningDrawer.d.ts +7 -1
  31. package/dist/components/views/panels/PlanningDrawer.js +48 -44
  32. package/dist/config/envSchema.js +1 -0
  33. package/dist/config/localServiceCloudTarget.d.ts +10 -0
  34. package/dist/config/localServiceCloudTarget.js +76 -0
  35. package/dist/core/AiProfileService.d.ts +1 -0
  36. package/dist/core/AiProfileService.js +2 -1
  37. package/dist/core/AttachmentLinkService.js +7 -4
  38. package/dist/core/DeletedTaskLifecycleService.d.ts +4 -0
  39. package/dist/core/DeletedTaskLifecycleService.js +21 -0
  40. package/dist/core/McpTokenService.d.ts +4 -0
  41. package/dist/core/McpTokenService.js +52 -0
  42. package/dist/core/TaskAttachmentLinksDurableMutationService.d.ts +5 -0
  43. package/dist/core/TaskAttachmentLinksDurableMutationService.js +20 -11
  44. package/dist/core/Taskforce.d.ts +63 -1
  45. package/dist/core/Taskforce.js +558 -73
  46. package/dist/core/types.d.ts +2 -1
  47. package/dist/documentReviews/DocumentReviewCommentStore.d.ts +11 -0
  48. package/dist/documentReviews/DocumentReviewCommentStore.js +35 -2
  49. package/dist/documentReviews/service.d.ts +4 -0
  50. package/dist/documentReviews/service.js +141 -46
  51. package/dist/hooks/tasks/useTaskFormActions.d.ts +3 -0
  52. package/dist/hooks/tasks/useTaskFormActions.js +33 -7
  53. package/dist/hooks/useTaskforce.d.ts +59 -50
  54. package/dist/hooks/useTaskforce.js +103 -1
  55. package/dist/mcp/canonicalAssetHelpers.d.ts +13 -0
  56. package/dist/mcp/canonicalAssetHelpers.js +39 -5
  57. package/dist/mcp/collaborationRegistrar.js +15 -13
  58. package/dist/mcp/documentAssetRegistrar.js +16 -9
  59. package/dist/mcp/localServiceProxy.js +4 -1
  60. package/dist/mcp/runtime.d.ts +16 -0
  61. package/dist/mcp/runtime.js +566 -171
  62. package/dist/mcp/taskAttachmentCommandAdapter.d.ts +2 -0
  63. package/dist/mcp/taskAttachmentCommandAdapter.js +14 -8
  64. package/dist/mcp/taskPlanningRegistrar.js +42 -34
  65. package/dist/mcp/toolRegistry.js +2 -2
  66. package/dist/migrations/taskSchemaMigrations.js +35 -0
  67. package/dist/runtime/appGateDefinitions.d.ts +2 -2
  68. package/dist/runtime/appGateDefinitions.js +2 -2
  69. package/dist/server/appAccess.d.ts +12 -0
  70. package/dist/server/appAccess.js +21 -0
  71. package/dist/server/authorizedWorkspaceAccess.d.ts +12 -0
  72. package/dist/server/authorizedWorkspaceAccess.js +40 -0
  73. package/dist/server/cloudCollectionRead.d.ts +25 -0
  74. package/dist/server/cloudCollectionRead.js +120 -0
  75. package/dist/server/cloudCollectionReadPool.d.ts +52 -0
  76. package/dist/server/cloudCollectionReadPool.js +140 -0
  77. package/dist/server/cloudCollectionReadWorker.d.ts +1 -0
  78. package/dist/server/cloudCollectionReadWorker.js +36 -0
  79. package/dist/server/index.d.ts +3 -11
  80. package/dist/server/index.js +53 -40
  81. package/dist/server/localServiceLease.d.ts +3 -0
  82. package/dist/server/localServiceLease.js +9 -1
  83. package/dist/server/routes/documents.d.ts +5 -2
  84. package/dist/server/routes/documents.js +160 -13
  85. package/dist/server/routes/durableTaskHttpRouters.d.ts +2 -0
  86. package/dist/server/routes/durableTaskHttpRouters.js +2 -2
  87. package/dist/server/routes/localService.js +2 -0
  88. package/dist/server/routes/primitives.d.ts +2 -0
  89. package/dist/server/routes/shared.d.ts +24 -0
  90. package/dist/server/routes/shared.js +114 -18
  91. package/dist/server/routes/sync.js +22 -0
  92. package/dist/server/routes/syncV3FeedRoutes.js +4 -2
  93. package/dist/server/routes/syncV3LocalCaptureRoutes.js +20 -2
  94. package/dist/server/routes/syncV3OperationRoutes.js +17 -2
  95. package/dist/server/routes/tasks.js +199 -89
  96. package/dist/server/routes.js +35 -7
  97. package/dist/service/localServiceCli.js +36 -25
  98. package/dist/service/localServiceClientLifecycle.js +67 -6
  99. package/dist/shared/planningIdentity.d.ts +20 -0
  100. package/dist/shared/planningIdentity.js +79 -0
  101. package/dist/storage/postgresAdapter.js +4 -0
  102. package/dist/storage/postgresRequestDiagnostics.d.ts +8 -0
  103. package/dist/storage/postgresRequestDiagnostics.js +24 -0
  104. package/dist/storage/workspaceAssetStore.d.ts +32 -0
  105. package/dist/storage/workspaceAssetStore.js +70 -0
  106. package/dist/sync/coordinator/localSyncExecutionPermitStore.d.ts +16 -0
  107. package/dist/sync/coordinator/localSyncExecutionPermitStore.js +70 -22
  108. package/dist/sync/coordinator/workspaceSyncTransportGateway.js +4 -2
  109. package/dist/sync/engine/workspaceSyncEngineRemoteServices.d.ts +5 -0
  110. package/dist/sync/engine/workspaceSyncEngineServerRemoteServices.d.ts +1 -1
  111. package/dist/sync/engine/workspaceSyncEngineServerRemoteServices.js +15 -0
  112. package/dist/sync/engine/workspaceSyncEngineServerRunnerOperations.js +26 -3
  113. package/dist/sync/engine/workspaceSyncV2ChangeDispatcher.js +2 -0
  114. package/dist/sync/syncApplyHandlers.d.ts +3 -1
  115. package/dist/sync/syncApplyHandlers.js +29 -0
  116. package/dist/sync/syncService.js +9 -0
  117. package/dist/sync/taskSyncPayload.d.ts +1 -0
  118. package/dist/sync/taskSyncPayload.js +6 -0
  119. package/dist/sync/v3/durableTaskAttachmentLinksMutationRouter.d.ts +1 -0
  120. package/dist/sync/v3/durableTaskAttachmentLinksMutationRouter.js +21 -3
  121. package/dist/sync/v3/durableTaskHttpBulkMutationRouter.js +17 -4
  122. package/dist/sync/v3/localInitiativeOutboxService.js +4 -2
  123. package/dist/sync/v3/localOutboxDispatcher.js +5 -1
  124. package/dist/sync/v3/localTaskAttachmentLinksOutboxHandler.js +12 -2
  125. package/dist/sync/v3/localTaskAttachmentLinksOutboxService.d.ts +1 -0
  126. package/dist/sync/v3/localTaskAttachmentLinksOutboxService.js +15 -3
  127. package/dist/sync/v3/localWorkstreamOutboxService.js +4 -2
  128. package/dist/sync/v3/syncDurabilityStore.d.ts +8 -0
  129. package/dist/sync/v3/syncDurabilityStore.js +171 -33
  130. package/dist/sync/v3/taskAttachmentLinksMutationService.d.ts +1 -0
  131. package/dist/sync/v3/taskAttachmentLinksMutationService.js +18 -2
  132. package/dist/sync/v3/taskMetadataCoexistence.js +4 -0
  133. package/dist/sync/v3/workspaceSyncV2ProjectionExclusions.js +1 -9
  134. package/dist/sync/v3/workspaceSyncV3CloudOperationHandler.js +1 -0
  135. package/dist/sync/v3/workspaceSyncV3CombinedFeedOrchestrator.js +7 -1
  136. package/dist/sync/v3/workspaceSyncV3CombinedLocalApply.js +15 -3
  137. package/dist/sync/v3/workspaceSyncV3CombinedRepairBaseline.d.ts +4 -0
  138. package/dist/sync/v3/workspaceSyncV3CombinedRepairBaseline.js +29 -6
  139. package/dist/sync/v3/workspaceSyncV3CombinedRepairMaterialization.d.ts +1 -0
  140. package/dist/sync/v3/workspaceSyncV3CombinedRepairMaterialization.js +29 -7
  141. package/dist/sync/v3/workspaceSyncV3CombinedRepairSnapshot.js +62 -7
  142. package/dist/sync/v3/workspaceSyncV3OperationProtocol.d.ts +1 -0
  143. package/dist/sync/v3/workspaceSyncV3RepairSqlBatching.d.ts +2 -0
  144. package/dist/sync/v3/workspaceSyncV3RepairSqlBatching.js +10 -0
  145. package/dist/sync/v3/workspaceSyncV3TaskRootProjection.d.ts +1 -1
  146. package/dist/sync/v3/workspaceSyncV3TaskRootProjection.js +1 -1
  147. package/dist/sync/workspacePullFeed.d.ts +6 -1
  148. package/dist/sync/workspacePullFeed.js +172 -161
  149. package/dist/sync/workspaceSyncModel.d.ts +11 -0
  150. package/dist/sync/workspaceSyncModel.js +27 -2
  151. package/dist/types.d.ts +8 -0
  152. package/dist/ui/assets/{AiIdentityRosterCard-DB1BLO_j.js → AiIdentityRosterCard-MZs7lVED.js} +1 -1
  153. package/dist/ui/assets/{AiProfilesModule-DPxQeF9N.js → AiProfilesModule-C3i0LOxe.js} +1 -1
  154. package/dist/ui/assets/{AnnotatedAttachmentWorkspace-DHNYaNg6.js → AnnotatedAttachmentWorkspace-DVZk5Tln.js} +1 -1
  155. package/dist/ui/assets/AssetTraySortControl-Kf1pelSy.js +1 -0
  156. package/dist/ui/assets/ContextAttachmentManager-B8boOs6Q.js +3 -0
  157. package/dist/ui/assets/{DocumentWorkspace-BC7sy5TG.js → DocumentWorkspace-DXH4XUsB.js} +4 -4
  158. package/dist/ui/assets/EntityActivityTimeline-BtSTq0ON.js +1 -0
  159. package/dist/ui/assets/PlanningModule-BPVyEa-f.js +1 -0
  160. package/dist/ui/assets/PlanningModule-CoIR9hbV.css +1 -0
  161. package/dist/ui/assets/{PlansPage-BVH_NfgT.js → PlansPage-ChqgxALc.js} +1 -1
  162. package/dist/ui/assets/TaskContextUpload-CB3ol0sN.js +1 -0
  163. package/dist/ui/assets/TaskContextUpload-qmBeUw3u.css +1 -0
  164. package/dist/ui/assets/{TaskSettings-xVsxSa0g.js → TaskSettings-g4ECKNOz.js} +1 -1
  165. package/dist/ui/assets/{TaskforceAgentsModule-CkAxW19K.js → TaskforceAgentsModule-BazdUwxZ.js} +1 -1
  166. package/dist/ui/assets/WorkflowManagerModule-DWFspC-o.js +1 -0
  167. package/dist/ui/assets/index-BUplSsv_.js +7 -0
  168. package/dist/ui/assets/index-gz2EXuoK.css +1 -0
  169. package/dist/ui/assets/{vendor-icons-B8ZNsH1g.js → vendor-icons-BkFLXavV.js} +1 -1
  170. package/dist/ui/index.html +3 -3
  171. package/dist/utils/constants.d.ts +2 -2
  172. package/dist/utils/constants.js +1 -1
  173. package/dist/utils/contextAttachmentUpload.d.ts +2 -0
  174. package/dist/utils/contextAttachmentUpload.js +7 -0
  175. package/dist/utils/contextFiles.d.ts +1 -1
  176. package/dist/utils/contextFiles.js +4 -4
  177. package/package.json +6 -1
  178. package/dist/ui/assets/AssetTraySortControl-DphbyHVc.js +0 -1
  179. package/dist/ui/assets/ContextAttachmentManager-CMxSzHqc.js +0 -3
  180. package/dist/ui/assets/EntityActivityTimeline-pJ2ZjZ-k.js +0 -1
  181. package/dist/ui/assets/PlanningModule-CeTqXMMz.css +0 -1
  182. package/dist/ui/assets/PlanningModule-t5GbvVR9.js +0 -1
  183. package/dist/ui/assets/TaskContextUpload-Ds4LnDzV.css +0 -1
  184. package/dist/ui/assets/TaskContextUpload-bl4fOOUz.js +0 -1
  185. package/dist/ui/assets/WorkflowManagerModule-BKqIGVnF.js +0 -1
  186. package/dist/ui/assets/index-BzJlVnNS.css +0 -1
  187. package/dist/ui/assets/index-Cx7vZJHL.js +0 -7
@@ -1 +1 @@
1
- import{r as f,j as a}from"./vendor-react-CKJs5o3c.js";import{ac as Qe,ad as re,O as Ue,ae as ea,af as W,t as r,U as aa,V as ra,ag as ta,ah as Re,W as ia,ai as oa,aj as te,ak as Me,al as la,Y as sa,X as Ee,$ as b,a0 as ke}from"./index-Cx7vZJHL.js";import{A as na,b as ca,r as Ce}from"./AiIdentityRosterCard-DB1BLO_j.js";import{ae as da,Z as fa,a4 as ua,h as pa,q as J,B as Le,ad as ma,ai as va}from"./vendor-icons-B8ZNsH1g.js";import"./vendor-markdown-_lhNCyq-.js";import"./vendor-dnd-CJ-AjP-Y.js";import"./vendor-router-AqJMU8Lz.js";const ga=["chat_app","ide","cli","coding_tool","taskforce_agent","agent","unclassified"];function L(o){return typeof o.avatarUrl=="string"&&o.avatarUrl.trim().length>0}function ie(o){return o?Ee(o.avatarUrl,o.avatarRevision,o.avatarUpdatedAt):""}function ha(o){return o?Ee(o.avatarSourceUrl,o.avatarRevision,o.avatarUpdatedAt):""}function ya(o){return o.find(L)||o[0]}function Pa({profile:o,className:g=""}){const A=ie(o),$=W(o),{activeImageUrl:T,handleImageError:Y}=sa(A,$);return T?a.jsx("img",{src:T,alt:"",className:g,onError:Y}):a.jsx(Le,{size:22})}function K(o){const g=te(o);return g?`taskforce-agent:${g}`:`${o.seatScope||"unknown"}:${o.name.trim().toLowerCase()}`}function oe(o){const g=o.providerMetadata?.taskforce;return!!(g&&typeof g=="object"&&!Array.isArray(g)&&String(g.taskforceAgentId||"").trim())}function Aa(o){return oe(o)?"taskforce_agent":Me(o.surfaceType)}function Te(o){return o==="taskforce_agent"?"Taskforce Agents":la(o)}function Sa(o){return oe(o)?"Taskforce Agent":o.surfaceType?Re(o.surfaceType):""}function xa(o){const g=Math.max(0,o-1);return`${g} duplicate${g===1?"":"s"}`}function we(o){return!o||typeof o!="object"?null:{used:Math.max(0,Number(o.used||0)),limit:o.limit===null||o.limit===void 0?null:Math.max(0,Number(o.limit||0)),remaining:o.remaining===null||o.remaining===void 0?null:Math.max(0,Number(o.remaining||0))}}function De(o,g){const A=g?.variant==="inline"?`${r.aiProfileSeatScopeIcon} ${r.aiProfileSeatScopeIconInline}`:g?.variant==="detail"?`${r.aiProfileSeatScopeIcon} ${r.aiProfileSeatScopeIconDetail}`:r.aiProfileSeatScopeIcon;return o==="cloud_metered"?a.jsx("span",{className:`${A} ${r.aiProfileSeatScopeIconCloud}`,title:"Cloud MCP","aria-label":"Cloud MCP",children:a.jsx(ma,{size:20})}):o==="local_unmetered"?a.jsx("span",{className:`${A} ${r.aiProfileSeatScopeIconLocal}`,title:"Local MCP","aria-label":"Local MCP",children:a.jsx(va,{size:20})}):null}function Ta({workspaceId:o,runtimeMode:g="local",cloudAuthConfigured:A=!1,authSessionResolved:$=!1,isAuthenticated:T=!1,cloudAiProfileSeatUsage:Y=null,agentTrayOpen:q=!1,onCloseAgentTray:$e,mcpSettingsNode:le=null,resolveCloudAuthUrl:B,theme:Be="dark",onNotice:w}){const[N,O]=f.useState([]),[Oe,Fe]=f.useState(null),[Ge,se]=f.useState(!1),[S,F]=f.useState(null),[G,D]=f.useState(null),[ne,X]=f.useState(null),[_e,ce]=f.useState(!1),[U,_]=f.useState(null),[de,fe]=f.useState(null),[ue,z]=f.useState(!1),[ze,P]=f.useState(null),[He,x]=f.useState(null),[R,pe]=f.useState(null),[me,k]=f.useState({}),[ve,ge]=f.useState(!1),[Z,he]=f.useState(!1),[ye,Pe]=f.useState(null),C=f.useCallback(async()=>{if(o){se(!0);try{const e=`/api/taskforce/workspace/assignee-options?workspaceId=${encodeURIComponent(o)}&kind=agent`,t=await fetch(e,{credentials:"include"}),l=t.ok?await t.json().catch(()=>({})):{},s=we(l?.aiProfileSeatUsage),d=Array.isArray(l?.assignees)?l.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"),colorSource:typeof i.colorSource=="string"?i.colorSource:null,colorUpdatedAt:typeof i.colorUpdatedAt=="string"?i.colorUpdatedAt:null,avatarUrl:typeof i.avatarUrl=="string"?i.avatarUrl:null,avatarSourceUrl:typeof i.avatarSourceUrl=="string"?i.avatarSourceUrl:null,avatarRevision:Number.isFinite(Number(i.avatarRevision))?Math.max(0,Math.floor(Number(i.avatarRevision))):0,avatarUpdatedAt:typeof i.avatarUpdatedAt=="string"?i.avatarUpdatedAt:null,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:re(i.surfaceType),seatScope:Qe(i.seatScope),providerMetadata:i.providerMetadata&&typeof i.providerMetadata=="object"&&!Array.isArray(i.providerMetadata)?i.providerMetadata:null,archivedAt:typeof i.archivedAt=="string"?i.archivedAt:null,createdAt:String(i.createdAt||""),updatedAt:String(i.updatedAt||i.createdAt||""),lastActiveAt:typeof i.lastActiveAt=="string"?i.lastActiveAt:null})):[];O(d),Fe(s),D(i=>i&&!d.some(u=>u.id===i.profileId)?null:i),X(i=>i&&!d.some(u=>u.id===i.profileId)?null:i)}finally{se(!1)}}},[o]);f.useEffect(()=>{C()},[C]),f.useEffect(()=>{const e=t=>{const l=t.detail;(String(l?.workspaceId||"").trim()||"default")===o&&l?.origin!=="ai-profiles-module"&&C()};return window.addEventListener(Ue,e),()=>window.removeEventListener(Ue,e)},[C,o]);const H=f.useMemo(()=>{const e=new Map;for(const t of N){const l=Aa(t);e.has(l)||e.set(l,new Map);const s=e.get(l),d=K(t);s.has(d)||s.set(d,[]),s.get(d).push(t)}return ga.map(t=>({section:t,label:Te(t),groups:Array.from(e.get(t)?.entries()||[]).map(([l,s])=>({groupId:`${t}:${l}`,section:t,sectionLabel:Te(t),profiles:s,primaryProfile:ya(s)}))})).filter(t=>t.groups.length>0)},[N]),j=f.useMemo(()=>H.flatMap(e=>e.groups),[H]),n=f.useMemo(()=>j.find(e=>e.groupId===U)||j[0]||null,[j,U]),p=f.useMemo(()=>N.find(e=>e.id===de)||null,[N,de]),Ae=p&&me[p.id]||null,Se=n&&me[n.primaryProfile.id]||null;f.useEffect(()=>{if(!j.length){U!==null&&_(null);return}(!U||!j.some(e=>e.groupId===U))&&_(j[0].groupId)},[j,U]);const Ve=async(e,t)=>{D(null);try{const l=await fetch("/api/taskforce/workspace/ai-profiles/merge",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({keepId:e,mergeId:t})}),s=await l.json().catch(()=>({}));if(!l.ok){w?.(String(s?.error||"Failed to merge AI profiles."),"error");return}F(null),w?.("AI profiles merged.","success"),await C(),b({workspaceId:o,profileId:e,reason:"merge",origin:"ai-profiles-module"})}catch{w?.("Failed to merge AI profiles.","error")}},xe=async e=>{if(window.confirm(`Remove ${e.name} from the active roster? This frees an AI profile seat and preserves task and comment history.`)){D(null);try{const l=await fetch("/api/taskforce/workspace/ai-profiles/archive",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:e.id,reason:"manual_archive"})}),s=await l.json().catch(()=>({}));if(!l.ok){D({profileId:e.id,message:String(s?.error||"Failed to remove AI profile from roster.")});return}(S?.keepId===e.id||S?.mergeId===e.id)&&F(null),w?.("AI profile removed from active roster.","success"),await C(),b({workspaceId:o,profileId:e.id,reason:"archive",origin:"ai-profiles-module"})}catch{D({profileId:e.id,message:"Failed to remove AI profile from roster."})}}},Je=async(e,t)=>{const l=re(t),s=new Set(e.profiles.map(u=>u.surfaceType??"")),d=l??"";if(s.size===1&&s.has(d))return;ce(!0),X(null);const i=[];try{for(const c of e.profiles){const m=await fetch("/api/taskforce/workspace/ai-profiles/surface-type",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:c.id,surfaceType:l})}),v=await m.json().catch(()=>({}));if(!m.ok||!v?.profile)throw new Error(String(v?.error||"Failed to update AI profile category."));const I=v.profile;i.push({...c,surfaceType:re(I.surfaceType),updatedAt:typeof I.updatedAt=="string"?I.updatedAt:c.updatedAt})}const u=new Map(i.map(c=>[c.id,c]));O(c=>c.map(m=>u.get(m.id)||m));const h=u.get(e.primaryProfile.id)||{...e.primaryProfile,surfaceType:l},y=Me(h.surfaceType);_(`${y}:${K(h)}`),w?.("AI profile category updated.","success");for(const c of i)b({workspaceId:o,profileId:c.id,reason:"update",origin:"ai-profiles-module"})}catch(u){X({profileId:e.primaryProfile.id,message:String(u?.message||"Failed to update AI profile category.")})}finally{ce(!1)}},je=async(e,t,l=!1)=>{he(!0),Pe(null);try{const s=K(e.primaryProfile),d=N.filter(c=>K(c)===s),i=await fetch("/api/taskforce/workspace/ai-profiles/color",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileIds:d.map(c=>c.id),color:t,reset:l})}),u=await i.text();let h={};try{h=u?JSON.parse(u):{}}catch{h={}}if(!i.ok){const c=i.status===404?"Color updates are unavailable in the running Taskforce server. Restart Taskforce and try again.":`Failed to update AI profile color (HTTP ${i.status}).`;throw new Error(String(h.error||c))}if(!Array.isArray(h.profiles))throw new Error("Taskforce returned an invalid response while updating the AI profile color.");const y=new Map(h.profiles.map(c=>[String(c.id),c]));O(c=>c.map(m=>{const v=y.get(m.id);return v?{...m,color:String(v.color||m.color),colorSource:v.colorSource??m.colorSource,colorUpdatedAt:v.colorUpdatedAt??m.colorUpdatedAt,updatedAt:v.updatedAt??m.updatedAt}:m})),ge(!1);for(const c of d)b({workspaceId:o,profileId:c.id,reason:"update",origin:"ai-profiles-module"})}catch(s){Pe(String(s?.message||"Failed to update AI profile color."))}finally{he(!1)}},Ie=e=>new Promise((t,l)=>{const s=new FileReader;s.onload=()=>t(String(s.result||"")),s.onerror=()=>l(new Error("Failed to read image file.")),s.readAsDataURL(e)}),Q=e=>{const t=String(e?.id||"").trim();t&&O(l=>l.map(s=>s.id===t?{...s,avatarUrl:typeof e.avatarUrl=="string"?e.avatarUrl:null,avatarSourceUrl:typeof e.avatarSourceUrl=="string"?e.avatarSourceUrl:null,avatarRevision:Number.isFinite(Number(e.avatarRevision))?Math.max(0,Math.floor(Number(e.avatarRevision))):s.avatarRevision,avatarUpdatedAt:typeof e.avatarUpdatedAt=="string"?e.avatarUpdatedAt:s.avatarUpdatedAt,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:s.updatedAt}:s))},Ke=async(e,t,l,s=!1)=>{const d=await Ie(t),i=l?await Ie(l):null,u={profileId:e,preserveExistingSource:s,displayImage:{dataUrl:d,mimeType:t.type||"application/octet-stream",originalName:t.name||"display-avatar"}};l&&i&&(u.sourceImage={dataUrl:i,mimeType:l.type||"application/octet-stream",originalName:l.name||"source-avatar"});const h=await fetch("/api/taskforce/workspace/ai-profiles/avatar/upload",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)}),y=await h.json().catch(()=>({}));if(!h.ok||!y?.profile)throw new Error(String(y?.error||"Failed to update AI profile avatar."));Q(y.profile),b({workspaceId:o,profileId:e,reason:"avatar",origin:"ai-profiles-module"})},We=async e=>{const t=await fetch("/api/taskforce/workspace/ai-profiles/avatar",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:e,avatarUrl:null,avatarSourceUrl:null})}),l=await t.json().catch(()=>({}));if(!t.ok||!l?.profile)throw new Error(String(l?.error||"Failed to update AI profile avatar."));Q(l.profile),b({workspaceId:o,profileId:e,reason:"avatar",origin:"ai-profiles-module"})},Ye=async e=>{if(R)return!1;const t=te(e),l=L(e);if(l&&!window.confirm(`Replace the existing avatar for ${e.name}?`))return!1;const s=t?"":window.prompt("Optional visual direction (300 characters maximum). Leave blank to use the profile details.","");if(s===null)return!1;const d=g==="local";if(d&&(!A||!$||!T||!B))return P("Sign in to Taskforce Cloud to generate profile avatars."),x(null),!1;pe(e.id),P(null),x(null),k(i=>({...i,[e.id]:{error:null,notice:null}}));try{const i=t?`/api/taskforce/agents/${encodeURIComponent(t)}/avatar/generate`:"/api/taskforce/workspace/ai-profiles/avatar/generate",u=d&&B?B(i):i,h=await fetch(u,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{workspaceId:o}:{workspaceId:o,profileId:e.id,visualDirection:s.slice(0,300),replaceExisting:l})}),y=await h.text().catch(()=>"");let c={};if(y&&!/^\s*(?:<!doctype\s+html|<html\b)/i.test(y))try{c=JSON.parse(y)}catch{c={}}if(!h.ok||!c?.profile&&!c?.agent)throw new Error(String(c?.error||(h.status?`Unable to generate avatar. HTTP ${h.status}.`:"Unable to generate avatar.")));const m=c.profile||{id:e.id,avatarUrl:c.agent?.avatarUrl??null,avatarSourceUrl:c.agent?.avatarSourceUrl??null,avatarRevision:c.agent?.avatarRevision??0,avatarUpdatedAt:c.agent?.avatarUpdatedAt??null},v=d&&B?{...m,avatarUrl:m.avatarUrl?Ce(m.avatarUrl):m.avatarUrl,avatarSourceUrl:m.avatarSourceUrl?Ce(m.avatarSourceUrl):m.avatarSourceUrl}:m;return Q(v),k(d?I=>({...I,[e.id]:{error:null,notice:`Generated photo for ${e.name} was saved in Taskforce Cloud. The local copy will be retained when sync runs.`}}):I=>({...I,[e.id]:{error:null,notice:`Generated photo for ${e.name} was saved.`}})),b({workspaceId:o,profileId:e.id,reason:"avatar",origin:"ai-profiles-module",...t?{taskforceAgentAvatar:{agentId:t,avatarUrl:typeof v.avatarUrl=="string"?v.avatarUrl:null,avatarSourceUrl:typeof v.avatarSourceUrl=="string"?v.avatarSourceUrl:null,avatarRevision:Number.isFinite(Number(v.avatarRevision))?Math.max(0,Math.floor(Number(v.avatarRevision))):0,avatarUpdatedAt:typeof v.avatarUpdatedAt=="string"?v.avatarUpdatedAt:null}}:{}}),!0}catch(i){return k(u=>({...u,[e.id]:{error:String(i?.message||"Unable to generate profile avatar."),notice:null}})),!1}finally{pe(null)}},qe=async(e,t,l)=>{if(!p)return!1;if(!e.type.startsWith("image/"))return P("AI profile photo must be an image file."),!1;z(!0),P(null),x(null),k(s=>{const d={...s};return delete d[p.id],d});try{const s=await ke(e,{maxBytes:5242880});if(s.exceededLimit)throw new Error(e.type==="image/gif"?"Animated GIF AI profile photos must be 5 MB or smaller.":"AI profile photo must be 5 MB or smaller.");const d=s.file;let i=null;if(t){const u=await ke(t,{maxBytes:5242880});if(u.exceededLimit)throw new Error(t.type==="image/gif"?"Animated GIF AI profile photos must be 5 MB or smaller.":"AI profile source photo must be 5 MB or smaller.");i=u.file}return await Ke(p.id,d,i,l?.preserveExistingSource===!0),!0}catch(s){return P(String(s?.message||"Failed to update AI profile photo.")),!1}finally{z(!1)}},Xe=async()=>{if(p){z(!0),P(null),x(null),k(e=>{const t={...e};return delete t[p.id],t});try{await We(p.id),x("Profile photo removed.")}catch(e){P(String(e?.message||"Failed to remove AI profile photo."))}finally{z(!1)}}},M=e=>{const t=String(e||"").trim();if(!t)return"Unknown";const l=Date.parse(t);return Number.isFinite(l)?new Date(l).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"}):t},be=f.useMemo(()=>{if(!n)return{attributes:[],dates:[]};const e=n.primaryProfile,t=l=>l||"Not set";return{attributes:[{label:"Category",value:Sa(e)},{label:"Connection",value:e.seatScope?ea(e.seatScope):""},{label:"Provider",value:e.provider||""},{label:"Model",value:e.model||""}].map(l=>({...l,value:t(l.value)})),dates:[{label:"Status",value:e.archivedAt?"Retired":"Active"},{label:"Recruited",value:M(e.createdAt)},{label:"Last updated",value:M(e.updatedAt)},{label:"Last active",value:M(e.lastActiveAt)}].map(l=>({...l,value:t(l.value)}))}},[n]),Ze=!!n&&n.profiles.length>1,E=!!n&&!L(n.primaryProfile)&&!!W(n.primaryProfile),Ne=A&&$&&!T,V=A?we(Y):Oe,ee=Ne?"Log into account for Cloud AI Profiles":V?`${V.used}/${V.limit===null?"Unlimited":V.limit}`:null,ae=!!le;return a.jsxs("section",{className:`${r.agentsModuleRoot} ${ae?r.agentsModuleWithTray:""} ${ae&&q?r.agentsModuleTrayOpen:""}`.trim(),children:[ae&&a.jsxs("aside",{className:`${r.agentTrayPanel} ${q?r.agentTrayPanelOpen:""}`.trim(),"aria-label":"AI Profile MCP settings tray","aria-hidden":!q,children:[a.jsxs("div",{className:r.agentTrayHeader,children:[a.jsxs("span",{className:r.agentTrayTitle,children:[a.jsx(da,{size:14}),"MCP Settings"]}),a.jsx("button",{type:"button",className:"tf-control-icon",onClick:$e,title:"Collapse AI Profile tray","aria-label":"Collapse AI Profile tray",children:a.jsx(fa,{size:16})})]}),a.jsx("div",{className:`${r.agentTrayContent} tf-scrollbar tf-scrollbar--track-transparent`,children:a.jsx("div",{className:r.agentTrayContentInner,children:le})})]}),a.jsx("div",{className:r.agentsModuleContent,children:a.jsxs("div",{className:r.aiProfilesExplorer,children:[a.jsxs("aside",{className:r.aiProfilesRosterPanel,"aria-label":"AI profile roster",children:[a.jsx("div",{className:r.taskforceAgentRosterHeader,children:a.jsxs("span",{className:r.taskforceAgentRosterTitle,children:[a.jsx(ua,{size:14}),"AI Profiles"]})}),ee&&a.jsx("div",{className:r.aiProfilesRosterSummary,children:a.jsx("div",{className:r.aiProfileSeatSummary,children:Ne?ee:`Registered Cloud AI Profiles: ${ee}`})}),Ge?a.jsxs("div",{className:r.aiProfilesRosterState,role:"status","aria-live":"polite",children:[a.jsx(pa,{size:13,className:r.spinner})," Loading profiles…"]}):N.length===0?a.jsx("div",{className:r.aiProfilesRosterState,children:"No AI profiles registered yet."}):H.length>0?a.jsx("div",{className:`${r.aiProfilesListPane} tf-scrollbar tf-scrollbar--track-transparent tf-tray-scroll-viewport`,children:a.jsx("div",{className:r.aiProfilesList,children:H.map(e=>a.jsxs("div",{className:r.aiProfilesSection,children:[a.jsx("div",{className:r.aiProfilesSectionHeader,children:e.label}),e.groups.map(t=>{const l=n?.groupId===t.groupId,s=t.primaryProfile,d=!L(s)&&!!W(s);return a.jsx(na,{name:s.name,username:s.username,subtitle:s.role||"Role not set",selected:l,onSelect:()=>_(t.groupId),avatarVariant:d?"logo":"portrait",avatar:a.jsx(Pa,{profile:s}),avatarStyle:{color:s.color},className:t.profiles.length>1?r.aiProfileGroupDuplicate:"",topUtility:De(s.seatScope),bottomUtility:a.jsx("span",{className:r.aiProfileGroupSignatureSwatch,style:{backgroundColor:s.color},title:`Signature color ${s.color}`,"aria-hidden":"true"}),footer:t.profiles.length>1?a.jsxs("span",{className:r.aiProfileDuplicateBadge,children:[a.jsx(J,{size:11})," ",xa(t.profiles.length)]}):null},t.groupId)})]},e.section))})}):null]}),a.jsx("main",{className:`${r.aiProfilesDetailViewport} tf-scrollbar`,"aria-label":"AI profile details",children:n&&a.jsx("div",{className:r.aiProfileDetailPane,children:a.jsxs("div",{className:r.aiProfileDetailCard,children:[De(n.primaryProfile.seatScope,{variant:"detail"}),a.jsxs("div",{className:r.aiProfileDetailHero,children:[a.jsx(aa,{label:"Edit AI profile photo",imageUrl:ie(n.primaryProfile),fallbackImageUrl:W(n.primaryProfile),fallback:a.jsx(Le,{size:38}),accentColor:E?null:n.primaryProfile.color,size:176,width:E?176:153,height:E?176:207,radius:E?0:6,editBadgeSize:28,editIconSize:14,loading:R===n.primaryProfile.id,loadingLabel:`Generating ${n.primaryProfile.name} photo`,error:!!Se?.error,errorLabel:Se?.error||"Profile photo generation failed",className:`${r.aiProfileDetailAvatar} ${E?r.aiProfileDetailAvatarLogo:""}`.trim(),onClick:()=>{P(null),x(null),fe(n.primaryProfile.id)}}),a.jsxs("div",{className:r.aiProfileDetailHeading,children:[a.jsx("div",{className:r.aiProfileDetailTitleRow,children:a.jsx("h5",{className:r.aiProfileDetailTitle,children:n.primaryProfile.name})}),a.jsxs("div",{className:r.aiProfileDetailMetaRow,children:[a.jsxs("span",{className:r.aiProfileDetailHandle,children:["@",n.primaryProfile.username]}),n.profiles.length>1&&a.jsxs("span",{className:r.aiProfileDetailLinkedCount,children:[n.profiles.length," linked"]})]}),a.jsxs("div",{className:r.aiProfileDetailRole,children:["Role: ",n.primaryProfile.role||"Not set"]}),n.primaryProfile.description&&a.jsx("div",{className:r.aiProfileDetailDescription,children:n.primaryProfile.description}),a.jsxs("div",{className:r.aiProfileSignatureColor,children:[a.jsx("span",{children:"Signature color"}),a.jsxs("button",{type:"button",className:r.aiProfileSignatureColorButton,onClick:()=>ge(e=>!e),disabled:Z,"aria-expanded":ve,"aria-label":"Change signature color",children:[a.jsx("span",{className:r.aiProfileSignatureSwatch,style:{backgroundColor:n.primaryProfile.color},"aria-hidden":"true"}),a.jsx("span",{children:n.primaryProfile.color})]})]}),ve&&a.jsxs("div",{className:r.aiProfileColorPicker,"aria-label":"Signature color options",children:[ca.map(e=>{const t=ra[e];return a.jsx("button",{type:"button",className:r.aiProfileColorOption,style:{backgroundColor:t},"aria-label":`Use ${e}`,"aria-pressed":n.primaryProfile.color.toLowerCase()===t.toLowerCase(),disabled:Z,onClick:()=>{je(n,t)}},e)}),a.jsx("button",{type:"button",className:r.secondaryHeaderBtn,disabled:Z,onClick:()=>{je(n,void 0,!0)},children:"Reset"})]}),ye&&a.jsx("div",{className:r.aiProfileInlineError,children:ye})]})]}),a.jsxs("div",{className:r.aiProfileDetailDataList,children:[a.jsx("div",{className:r.aiProfileDetailDataGroup,children:be.attributes.map(e=>a.jsxs("div",{className:r.aiProfileDetailDataRow,children:[a.jsx("span",{className:r.aiProfileDetailDataLabel,children:e.label}),e.label==="Category"&&!oe(n.primaryProfile)?a.jsx("span",{className:r.aiProfileDetailDataValue,children:a.jsxs("select",{className:r.aiProfileStatusSelect,"aria-label":"Agent category",value:n.primaryProfile.surfaceType??"",disabled:_e,onChange:t=>{Je(n,t.target.value)},children:[a.jsx("option",{value:"",children:"Unclassified"}),ta.map(t=>a.jsx("option",{value:t,children:Re(t)},t))]})}):a.jsx("span",{className:r.aiProfileDetailDataValue,children:e.value})]},e.label))}),a.jsx("div",{className:`${r.aiProfileDetailDataGroup} ${r.aiProfileDetailDateGroup}`,children:be.dates.map(e=>a.jsxs("div",{className:r.aiProfileDetailDataRow,children:[a.jsx("span",{className:r.aiProfileDetailDataLabel,children:e.label}),e.label==="Status"?a.jsx("span",{className:r.aiProfileDetailDataValue,children:a.jsxs("select",{className:r.aiProfileStatusSelect,"aria-label":"Agent roster status",value:n.primaryProfile.archivedAt?"retired":"active",onChange:t=>{t.target.value==="retire"&&xe(n.primaryProfile)},children:[a.jsx("option",{value:"active",children:"Active"}),n.primaryProfile.archivedAt?a.jsx("option",{value:"retired",children:"Retired"}):a.jsx("option",{value:"retire",children:"Retire from roster"})]})}):a.jsx("span",{className:r.aiProfileDetailDataValue,children:e.value})]},e.label))})]}),ne?.profileId===n.primaryProfile.id&&a.jsxs("div",{className:r.aiProfileInlineError,role:"alert",children:[a.jsx(J,{size:12}),a.jsx("span",{children:ne.message})]}),Ze?a.jsxs("div",{className:r.aiProfileInstanceSection,children:[a.jsxs("div",{className:r.aiProfileInstanceSectionHeader,children:[a.jsx("span",{children:"Profile instances"}),a.jsx("span",{className:r.settingsHint,children:"Choose a keeper here if duplicates need to be merged."})]}),a.jsx("div",{className:r.aiProfileInstanceList,children:n.profiles.map(e=>a.jsxs("div",{className:r.aiProfileInstanceCard,children:[a.jsxs("div",{className:r.aiProfileInstanceTopRow,children:[a.jsxs("div",{children:[a.jsxs("div",{className:r.aiProfileInstanceName,children:["@",e.username]}),a.jsx("div",{className:r.aiProfileIdChip,children:e.id})]}),S?.keepId===e.id&&a.jsx("span",{className:r.aiProfileKeepBadge,children:"Keeping"})]}),a.jsxs("div",{className:r.aiProfileInstanceMeta,children:[a.jsxs("span",{children:["Created ",M(e.createdAt)]}),a.jsxs("span",{children:["Updated ",M(e.updatedAt)]})]}),S?.keepId!==e.id&&a.jsx("button",{className:r.secondaryHeaderBtn,title:"Keep this profile, merge others into it",onClick:()=>{const t=n.profiles.find(l=>l.id!==e.id)?.id;t&&F({keepId:e.id,mergeId:t})},children:"Keep this"}),G?.profileId===e.id&&a.jsxs("div",{className:r.aiProfileInlineError,role:"alert",children:[a.jsx(J,{size:12}),a.jsx("span",{children:G.message})]}),a.jsx("button",{className:r.aiProfileDangerTextButton,title:"Remove this profile from the active roster",onClick:()=>{xe(e)},children:"Remove from roster"})]},e.id))}),S&&n.profiles.some(e=>e.id===S.keepId)&&a.jsxs("div",{className:r.aiProfileMergeActions,children:[a.jsx("button",{className:r.dangerBtn,onClick:()=>{Ve(S.keepId,S.mergeId)},children:"Merge duplicates"}),a.jsx("button",{className:r.secondaryHeaderBtn,onClick:()=>F(null),children:"Cancel"})]})]}):a.jsxs("div",{className:r.aiProfileIdFooter,children:[a.jsx("div",{className:r.aiProfileIdFooterValue,children:n.primaryProfile.id}),G?.profileId===n.primaryProfile.id&&a.jsxs("div",{className:r.aiProfileInlineError,role:"alert",children:[a.jsx(J,{size:12}),a.jsx("span",{children:G.message})]})]})]})})})]})}),a.jsx(ia,{isOpen:!!p,theme:Be,title:"Edit AI Profile Photo",currentImageUrl:ie(p),editorImageUrl:ha(p),fallbackInitial:(p?.name||"AI").charAt(0).toUpperCase(),accept:"image/png,image/jpeg,image/webp,image/gif",busy:ue,generating:R===p?.id,generateLabel:p&&L(p)?"Regenerate":"Generate",hasPendingImage:!1,canRemove:!!p?.avatarUrl,error:ze||Ae?.error||null,notice:He||Ae?.notice||null,onClose:()=>{ue||(fe(null),P(null),x(null))},onApplyImage:qe,onGenerateImage:p&&(!R||R===p.id)&&(oa(p)||te(p))?()=>Ye(p):void 0,onRemoveImage:Xe},p?.id||"ai-profile-avatar-closed")]})}export{Ta as AiProfilesModule};
1
+ import{r as f,j as a}from"./vendor-react-CKJs5o3c.js";import{ac as Qe,ad as re,O as Ue,ae as ea,af as W,t as r,U as aa,V as ra,ag as ta,ah as Re,W as ia,ai as oa,aj as te,ak as Me,al as la,Y as sa,X as Ee,$ as b,a0 as ke}from"./index-BUplSsv_.js";import{A as na,b as ca,r as Ce}from"./AiIdentityRosterCard-MZs7lVED.js";import{ay as da,ai as fa,U as ua,w as pa,Z as J,J as Le,ax as ma,aC as va}from"./vendor-icons-BkFLXavV.js";import"./vendor-markdown-_lhNCyq-.js";import"./vendor-dnd-CJ-AjP-Y.js";import"./vendor-router-AqJMU8Lz.js";const ga=["chat_app","ide","cli","coding_tool","taskforce_agent","agent","unclassified"];function L(o){return typeof o.avatarUrl=="string"&&o.avatarUrl.trim().length>0}function ie(o){return o?Ee(o.avatarUrl,o.avatarRevision,o.avatarUpdatedAt):""}function ha(o){return o?Ee(o.avatarSourceUrl,o.avatarRevision,o.avatarUpdatedAt):""}function ya(o){return o.find(L)||o[0]}function Pa({profile:o,className:g=""}){const A=ie(o),$=W(o),{activeImageUrl:T,handleImageError:Y}=sa(A,$);return T?a.jsx("img",{src:T,alt:"",className:g,onError:Y}):a.jsx(Le,{size:22})}function K(o){const g=te(o);return g?`taskforce-agent:${g}`:`${o.seatScope||"unknown"}:${o.name.trim().toLowerCase()}`}function oe(o){const g=o.providerMetadata?.taskforce;return!!(g&&typeof g=="object"&&!Array.isArray(g)&&String(g.taskforceAgentId||"").trim())}function Aa(o){return oe(o)?"taskforce_agent":Me(o.surfaceType)}function Te(o){return o==="taskforce_agent"?"Taskforce Agents":la(o)}function Sa(o){return oe(o)?"Taskforce Agent":o.surfaceType?Re(o.surfaceType):""}function xa(o){const g=Math.max(0,o-1);return`${g} duplicate${g===1?"":"s"}`}function we(o){return!o||typeof o!="object"?null:{used:Math.max(0,Number(o.used||0)),limit:o.limit===null||o.limit===void 0?null:Math.max(0,Number(o.limit||0)),remaining:o.remaining===null||o.remaining===void 0?null:Math.max(0,Number(o.remaining||0))}}function De(o,g){const A=g?.variant==="inline"?`${r.aiProfileSeatScopeIcon} ${r.aiProfileSeatScopeIconInline}`:g?.variant==="detail"?`${r.aiProfileSeatScopeIcon} ${r.aiProfileSeatScopeIconDetail}`:r.aiProfileSeatScopeIcon;return o==="cloud_metered"?a.jsx("span",{className:`${A} ${r.aiProfileSeatScopeIconCloud}`,title:"Cloud MCP","aria-label":"Cloud MCP",children:a.jsx(ma,{size:20})}):o==="local_unmetered"?a.jsx("span",{className:`${A} ${r.aiProfileSeatScopeIconLocal}`,title:"Local MCP","aria-label":"Local MCP",children:a.jsx(va,{size:20})}):null}function Ta({workspaceId:o,runtimeMode:g="local",cloudAuthConfigured:A=!1,authSessionResolved:$=!1,isAuthenticated:T=!1,cloudAiProfileSeatUsage:Y=null,agentTrayOpen:X=!1,onCloseAgentTray:$e,mcpSettingsNode:le=null,resolveCloudAuthUrl:B,theme:Be="dark",onNotice:w}){const[N,O]=f.useState([]),[Oe,Fe]=f.useState(null),[Ge,se]=f.useState(!1),[S,F]=f.useState(null),[G,D]=f.useState(null),[ne,Z]=f.useState(null),[_e,ce]=f.useState(!1),[U,_]=f.useState(null),[de,fe]=f.useState(null),[ue,z]=f.useState(!1),[ze,P]=f.useState(null),[He,x]=f.useState(null),[R,pe]=f.useState(null),[me,k]=f.useState({}),[ve,ge]=f.useState(!1),[q,he]=f.useState(!1),[ye,Pe]=f.useState(null),C=f.useCallback(async()=>{if(o){se(!0);try{const e=`/api/taskforce/workspace/assignee-options?workspaceId=${encodeURIComponent(o)}&kind=agent`,t=await fetch(e,{credentials:"include"}),l=t.ok?await t.json().catch(()=>({})):{},s=we(l?.aiProfileSeatUsage),d=Array.isArray(l?.assignees)?l.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"),colorSource:typeof i.colorSource=="string"?i.colorSource:null,colorUpdatedAt:typeof i.colorUpdatedAt=="string"?i.colorUpdatedAt:null,avatarUrl:typeof i.avatarUrl=="string"?i.avatarUrl:null,avatarSourceUrl:typeof i.avatarSourceUrl=="string"?i.avatarSourceUrl:null,avatarRevision:Number.isFinite(Number(i.avatarRevision))?Math.max(0,Math.floor(Number(i.avatarRevision))):0,avatarUpdatedAt:typeof i.avatarUpdatedAt=="string"?i.avatarUpdatedAt:null,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:re(i.surfaceType),seatScope:Qe(i.seatScope),providerMetadata:i.providerMetadata&&typeof i.providerMetadata=="object"&&!Array.isArray(i.providerMetadata)?i.providerMetadata:null,archivedAt:typeof i.archivedAt=="string"?i.archivedAt:null,createdAt:String(i.createdAt||""),updatedAt:String(i.updatedAt||i.createdAt||""),lastActiveAt:typeof i.lastActiveAt=="string"?i.lastActiveAt:null})):[];O(d),Fe(s),D(i=>i&&!d.some(u=>u.id===i.profileId)?null:i),Z(i=>i&&!d.some(u=>u.id===i.profileId)?null:i)}finally{se(!1)}}},[o]);f.useEffect(()=>{C()},[C]),f.useEffect(()=>{const e=t=>{const l=t.detail;(String(l?.workspaceId||"").trim()||"default")===o&&l?.origin!=="ai-profiles-module"&&C()};return window.addEventListener(Ue,e),()=>window.removeEventListener(Ue,e)},[C,o]);const H=f.useMemo(()=>{const e=new Map;for(const t of N){const l=Aa(t);e.has(l)||e.set(l,new Map);const s=e.get(l),d=K(t);s.has(d)||s.set(d,[]),s.get(d).push(t)}return ga.map(t=>({section:t,label:Te(t),groups:Array.from(e.get(t)?.entries()||[]).map(([l,s])=>({groupId:`${t}:${l}`,section:t,sectionLabel:Te(t),profiles:s,primaryProfile:ya(s)}))})).filter(t=>t.groups.length>0)},[N]),j=f.useMemo(()=>H.flatMap(e=>e.groups),[H]),n=f.useMemo(()=>j.find(e=>e.groupId===U)||j[0]||null,[j,U]),p=f.useMemo(()=>N.find(e=>e.id===de)||null,[N,de]),Ae=p&&me[p.id]||null,Se=n&&me[n.primaryProfile.id]||null;f.useEffect(()=>{if(!j.length){U!==null&&_(null);return}(!U||!j.some(e=>e.groupId===U))&&_(j[0].groupId)},[j,U]);const Ve=async(e,t)=>{D(null);try{const l=await fetch("/api/taskforce/workspace/ai-profiles/merge",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({keepId:e,mergeId:t})}),s=await l.json().catch(()=>({}));if(!l.ok){w?.(String(s?.error||"Failed to merge AI profiles."),"error");return}F(null),w?.("AI profiles merged.","success"),await C(),b({workspaceId:o,profileId:e,reason:"merge",origin:"ai-profiles-module"})}catch{w?.("Failed to merge AI profiles.","error")}},xe=async e=>{if(window.confirm(`Remove ${e.name} from the active roster? This frees an AI profile seat and preserves task and comment history.`)){D(null);try{const l=await fetch("/api/taskforce/workspace/ai-profiles/archive",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:e.id,reason:"manual_archive"})}),s=await l.json().catch(()=>({}));if(!l.ok){D({profileId:e.id,message:String(s?.error||"Failed to remove AI profile from roster.")});return}(S?.keepId===e.id||S?.mergeId===e.id)&&F(null),w?.("AI profile removed from active roster.","success"),await C(),b({workspaceId:o,profileId:e.id,reason:"archive",origin:"ai-profiles-module"})}catch{D({profileId:e.id,message:"Failed to remove AI profile from roster."})}}},Je=async(e,t)=>{const l=re(t),s=new Set(e.profiles.map(u=>u.surfaceType??"")),d=l??"";if(s.size===1&&s.has(d))return;ce(!0),Z(null);const i=[];try{for(const c of e.profiles){const m=await fetch("/api/taskforce/workspace/ai-profiles/surface-type",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:c.id,surfaceType:l})}),v=await m.json().catch(()=>({}));if(!m.ok||!v?.profile)throw new Error(String(v?.error||"Failed to update AI profile category."));const I=v.profile;i.push({...c,surfaceType:re(I.surfaceType),updatedAt:typeof I.updatedAt=="string"?I.updatedAt:c.updatedAt})}const u=new Map(i.map(c=>[c.id,c]));O(c=>c.map(m=>u.get(m.id)||m));const h=u.get(e.primaryProfile.id)||{...e.primaryProfile,surfaceType:l},y=Me(h.surfaceType);_(`${y}:${K(h)}`),w?.("AI profile category updated.","success");for(const c of i)b({workspaceId:o,profileId:c.id,reason:"update",origin:"ai-profiles-module"})}catch(u){Z({profileId:e.primaryProfile.id,message:String(u?.message||"Failed to update AI profile category.")})}finally{ce(!1)}},je=async(e,t,l=!1)=>{he(!0),Pe(null);try{const s=K(e.primaryProfile),d=N.filter(c=>K(c)===s),i=await fetch("/api/taskforce/workspace/ai-profiles/color",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileIds:d.map(c=>c.id),color:t,reset:l})}),u=await i.text();let h={};try{h=u?JSON.parse(u):{}}catch{h={}}if(!i.ok){const c=i.status===404?"Color updates are unavailable in the running Taskforce server. Restart Taskforce and try again.":`Failed to update AI profile color (HTTP ${i.status}).`;throw new Error(String(h.error||c))}if(!Array.isArray(h.profiles))throw new Error("Taskforce returned an invalid response while updating the AI profile color.");const y=new Map(h.profiles.map(c=>[String(c.id),c]));O(c=>c.map(m=>{const v=y.get(m.id);return v?{...m,color:String(v.color||m.color),colorSource:v.colorSource??m.colorSource,colorUpdatedAt:v.colorUpdatedAt??m.colorUpdatedAt,updatedAt:v.updatedAt??m.updatedAt}:m})),ge(!1);for(const c of d)b({workspaceId:o,profileId:c.id,reason:"update",origin:"ai-profiles-module"})}catch(s){Pe(String(s?.message||"Failed to update AI profile color."))}finally{he(!1)}},Ie=e=>new Promise((t,l)=>{const s=new FileReader;s.onload=()=>t(String(s.result||"")),s.onerror=()=>l(new Error("Failed to read image file.")),s.readAsDataURL(e)}),Q=e=>{const t=String(e?.id||"").trim();t&&O(l=>l.map(s=>s.id===t?{...s,avatarUrl:typeof e.avatarUrl=="string"?e.avatarUrl:null,avatarSourceUrl:typeof e.avatarSourceUrl=="string"?e.avatarSourceUrl:null,avatarRevision:Number.isFinite(Number(e.avatarRevision))?Math.max(0,Math.floor(Number(e.avatarRevision))):s.avatarRevision,avatarUpdatedAt:typeof e.avatarUpdatedAt=="string"?e.avatarUpdatedAt:s.avatarUpdatedAt,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:s.updatedAt}:s))},Ke=async(e,t,l,s=!1)=>{const d=await Ie(t),i=l?await Ie(l):null,u={profileId:e,preserveExistingSource:s,displayImage:{dataUrl:d,mimeType:t.type||"application/octet-stream",originalName:t.name||"display-avatar"}};l&&i&&(u.sourceImage={dataUrl:i,mimeType:l.type||"application/octet-stream",originalName:l.name||"source-avatar"});const h=await fetch("/api/taskforce/workspace/ai-profiles/avatar/upload",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)}),y=await h.json().catch(()=>({}));if(!h.ok||!y?.profile)throw new Error(String(y?.error||"Failed to update AI profile avatar."));Q(y.profile),b({workspaceId:o,profileId:e,reason:"avatar",origin:"ai-profiles-module"})},We=async e=>{const t=await fetch("/api/taskforce/workspace/ai-profiles/avatar",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileId:e,avatarUrl:null,avatarSourceUrl:null})}),l=await t.json().catch(()=>({}));if(!t.ok||!l?.profile)throw new Error(String(l?.error||"Failed to update AI profile avatar."));Q(l.profile),b({workspaceId:o,profileId:e,reason:"avatar",origin:"ai-profiles-module"})},Ye=async e=>{if(R)return!1;const t=te(e),l=L(e);if(l&&!window.confirm(`Replace the existing avatar for ${e.name}?`))return!1;const s=t?"":window.prompt("Optional visual direction (300 characters maximum). Leave blank to use the profile details.","");if(s===null)return!1;const d=g==="local";if(d&&(!A||!$||!T||!B))return P("Sign in to Taskforce Cloud to generate profile avatars."),x(null),!1;pe(e.id),P(null),x(null),k(i=>({...i,[e.id]:{error:null,notice:null}}));try{const i=t?`/api/taskforce/agents/${encodeURIComponent(t)}/avatar/generate`:"/api/taskforce/workspace/ai-profiles/avatar/generate",u=d&&B?B(i):i,h=await fetch(u,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{workspaceId:o}:{workspaceId:o,profileId:e.id,visualDirection:s.slice(0,300),replaceExisting:l})}),y=await h.text().catch(()=>"");let c={};if(y&&!/^\s*(?:<!doctype\s+html|<html\b)/i.test(y))try{c=JSON.parse(y)}catch{c={}}if(!h.ok||!c?.profile&&!c?.agent)throw new Error(String(c?.error||(h.status?`Unable to generate avatar. HTTP ${h.status}.`:"Unable to generate avatar.")));const m=c.profile||{id:e.id,avatarUrl:c.agent?.avatarUrl??null,avatarSourceUrl:c.agent?.avatarSourceUrl??null,avatarRevision:c.agent?.avatarRevision??0,avatarUpdatedAt:c.agent?.avatarUpdatedAt??null},v=d&&B?{...m,avatarUrl:m.avatarUrl?Ce(m.avatarUrl):m.avatarUrl,avatarSourceUrl:m.avatarSourceUrl?Ce(m.avatarSourceUrl):m.avatarSourceUrl}:m;return Q(v),k(d?I=>({...I,[e.id]:{error:null,notice:`Generated photo for ${e.name} was saved in Taskforce Cloud. The local copy will be retained when sync runs.`}}):I=>({...I,[e.id]:{error:null,notice:`Generated photo for ${e.name} was saved.`}})),b({workspaceId:o,profileId:e.id,reason:"avatar",origin:"ai-profiles-module",...t?{taskforceAgentAvatar:{agentId:t,avatarUrl:typeof v.avatarUrl=="string"?v.avatarUrl:null,avatarSourceUrl:typeof v.avatarSourceUrl=="string"?v.avatarSourceUrl:null,avatarRevision:Number.isFinite(Number(v.avatarRevision))?Math.max(0,Math.floor(Number(v.avatarRevision))):0,avatarUpdatedAt:typeof v.avatarUpdatedAt=="string"?v.avatarUpdatedAt:null}}:{}}),!0}catch(i){return k(u=>({...u,[e.id]:{error:String(i?.message||"Unable to generate profile avatar."),notice:null}})),!1}finally{pe(null)}},Xe=async(e,t,l)=>{if(!p)return!1;if(!e.type.startsWith("image/"))return P("AI profile photo must be an image file."),!1;z(!0),P(null),x(null),k(s=>{const d={...s};return delete d[p.id],d});try{const s=await ke(e,{maxBytes:5242880});if(s.exceededLimit)throw new Error(e.type==="image/gif"?"Animated GIF AI profile photos must be 5 MB or smaller.":"AI profile photo must be 5 MB or smaller.");const d=s.file;let i=null;if(t){const u=await ke(t,{maxBytes:5242880});if(u.exceededLimit)throw new Error(t.type==="image/gif"?"Animated GIF AI profile photos must be 5 MB or smaller.":"AI profile source photo must be 5 MB or smaller.");i=u.file}return await Ke(p.id,d,i,l?.preserveExistingSource===!0),!0}catch(s){return P(String(s?.message||"Failed to update AI profile photo.")),!1}finally{z(!1)}},Ze=async()=>{if(p){z(!0),P(null),x(null),k(e=>{const t={...e};return delete t[p.id],t});try{await We(p.id),x("Profile photo removed.")}catch(e){P(String(e?.message||"Failed to remove AI profile photo."))}finally{z(!1)}}},M=e=>{const t=String(e||"").trim();if(!t)return"Unknown";const l=Date.parse(t);return Number.isFinite(l)?new Date(l).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"}):t},be=f.useMemo(()=>{if(!n)return{attributes:[],dates:[]};const e=n.primaryProfile,t=l=>l||"Not set";return{attributes:[{label:"Category",value:Sa(e)},{label:"Connection",value:e.seatScope?ea(e.seatScope):""},{label:"Provider",value:e.provider||""},{label:"Model",value:e.model||""}].map(l=>({...l,value:t(l.value)})),dates:[{label:"Status",value:e.archivedAt?"Retired":"Active"},{label:"Recruited",value:M(e.createdAt)},{label:"Last updated",value:M(e.updatedAt)},{label:"Last active",value:M(e.lastActiveAt)}].map(l=>({...l,value:t(l.value)}))}},[n]),qe=!!n&&n.profiles.length>1,E=!!n&&!L(n.primaryProfile)&&!!W(n.primaryProfile),Ne=A&&$&&!T,V=A?we(Y):Oe,ee=Ne?"Log into account for Cloud AI Profiles":V?`${V.used}/${V.limit===null?"Unlimited":V.limit}`:null,ae=!!le;return a.jsxs("section",{className:`${r.agentsModuleRoot} ${ae?r.agentsModuleWithTray:""} ${ae&&X?r.agentsModuleTrayOpen:""}`.trim(),children:[ae&&a.jsxs("aside",{className:`${r.agentTrayPanel} ${X?r.agentTrayPanelOpen:""}`.trim(),"aria-label":"AI Profile MCP settings tray","aria-hidden":!X,children:[a.jsxs("div",{className:r.agentTrayHeader,children:[a.jsxs("span",{className:r.agentTrayTitle,children:[a.jsx(da,{size:14}),"MCP Settings"]}),a.jsx("button",{type:"button",className:"tf-control-icon",onClick:$e,title:"Collapse AI Profile tray","aria-label":"Collapse AI Profile tray",children:a.jsx(fa,{size:16})})]}),a.jsx("div",{className:`${r.agentTrayContent} tf-scrollbar tf-scrollbar--track-transparent`,children:a.jsx("div",{className:r.agentTrayContentInner,children:le})})]}),a.jsx("div",{className:r.agentsModuleContent,children:a.jsxs("div",{className:r.aiProfilesExplorer,children:[a.jsxs("aside",{className:r.aiProfilesRosterPanel,"aria-label":"AI profile roster",children:[a.jsx("div",{className:r.taskforceAgentRosterHeader,children:a.jsxs("span",{className:r.taskforceAgentRosterTitle,children:[a.jsx(ua,{size:14}),"AI Profiles"]})}),ee&&a.jsx("div",{className:r.aiProfilesRosterSummary,children:a.jsx("div",{className:r.aiProfileSeatSummary,children:Ne?ee:`Registered Cloud AI Profiles: ${ee}`})}),Ge?a.jsxs("div",{className:r.aiProfilesRosterState,role:"status","aria-live":"polite",children:[a.jsx(pa,{size:13,className:r.spinner})," Loading profiles…"]}):N.length===0?a.jsx("div",{className:r.aiProfilesRosterState,children:"No AI profiles registered yet."}):H.length>0?a.jsx("div",{className:`${r.aiProfilesListPane} tf-scrollbar tf-scrollbar--track-transparent tf-tray-scroll-viewport`,children:a.jsx("div",{className:r.aiProfilesList,children:H.map(e=>a.jsxs("div",{className:r.aiProfilesSection,children:[a.jsx("div",{className:r.aiProfilesSectionHeader,children:e.label}),e.groups.map(t=>{const l=n?.groupId===t.groupId,s=t.primaryProfile,d=!L(s)&&!!W(s);return a.jsx(na,{name:s.name,username:s.username,subtitle:s.role||"Role not set",selected:l,onSelect:()=>_(t.groupId),avatarVariant:d?"logo":"portrait",avatar:a.jsx(Pa,{profile:s}),avatarStyle:{color:s.color},className:t.profiles.length>1?r.aiProfileGroupDuplicate:"",topUtility:De(s.seatScope),bottomUtility:a.jsx("span",{className:r.aiProfileGroupSignatureSwatch,style:{backgroundColor:s.color},title:`Signature color ${s.color}`,"aria-hidden":"true"}),footer:t.profiles.length>1?a.jsxs("span",{className:r.aiProfileDuplicateBadge,children:[a.jsx(J,{size:11})," ",xa(t.profiles.length)]}):null},t.groupId)})]},e.section))})}):null]}),a.jsx("main",{className:`${r.aiProfilesDetailViewport} tf-scrollbar`,"aria-label":"AI profile details",children:n&&a.jsx("div",{className:r.aiProfileDetailPane,children:a.jsxs("div",{className:r.aiProfileDetailCard,children:[De(n.primaryProfile.seatScope,{variant:"detail"}),a.jsxs("div",{className:r.aiProfileDetailHero,children:[a.jsx(aa,{label:"Edit AI profile photo",imageUrl:ie(n.primaryProfile),fallbackImageUrl:W(n.primaryProfile),fallback:a.jsx(Le,{size:38}),accentColor:E?null:n.primaryProfile.color,size:176,width:E?176:153,height:E?176:207,radius:E?0:6,editBadgeSize:28,editIconSize:14,loading:R===n.primaryProfile.id,loadingLabel:`Generating ${n.primaryProfile.name} photo`,error:!!Se?.error,errorLabel:Se?.error||"Profile photo generation failed",className:`${r.aiProfileDetailAvatar} ${E?r.aiProfileDetailAvatarLogo:""}`.trim(),onClick:()=>{P(null),x(null),fe(n.primaryProfile.id)}}),a.jsxs("div",{className:r.aiProfileDetailHeading,children:[a.jsx("div",{className:r.aiProfileDetailTitleRow,children:a.jsx("h5",{className:r.aiProfileDetailTitle,children:n.primaryProfile.name})}),a.jsxs("div",{className:r.aiProfileDetailMetaRow,children:[a.jsxs("span",{className:r.aiProfileDetailHandle,children:["@",n.primaryProfile.username]}),n.profiles.length>1&&a.jsxs("span",{className:r.aiProfileDetailLinkedCount,children:[n.profiles.length," linked"]})]}),a.jsxs("div",{className:r.aiProfileDetailRole,children:["Role: ",n.primaryProfile.role||"Not set"]}),n.primaryProfile.description&&a.jsx("div",{className:r.aiProfileDetailDescription,children:n.primaryProfile.description}),a.jsxs("div",{className:r.aiProfileSignatureColor,children:[a.jsx("span",{children:"Signature color"}),a.jsxs("button",{type:"button",className:r.aiProfileSignatureColorButton,onClick:()=>ge(e=>!e),disabled:q,"aria-expanded":ve,"aria-label":"Change signature color",children:[a.jsx("span",{className:r.aiProfileSignatureSwatch,style:{backgroundColor:n.primaryProfile.color},"aria-hidden":"true"}),a.jsx("span",{children:n.primaryProfile.color})]})]}),ve&&a.jsxs("div",{className:r.aiProfileColorPicker,"aria-label":"Signature color options",children:[ca.map(e=>{const t=ra[e];return a.jsx("button",{type:"button",className:r.aiProfileColorOption,style:{backgroundColor:t},"aria-label":`Use ${e}`,"aria-pressed":n.primaryProfile.color.toLowerCase()===t.toLowerCase(),disabled:q,onClick:()=>{je(n,t)}},e)}),a.jsx("button",{type:"button",className:r.secondaryHeaderBtn,disabled:q,onClick:()=>{je(n,void 0,!0)},children:"Reset"})]}),ye&&a.jsx("div",{className:r.aiProfileInlineError,children:ye})]})]}),a.jsxs("div",{className:r.aiProfileDetailDataList,children:[a.jsx("div",{className:r.aiProfileDetailDataGroup,children:be.attributes.map(e=>a.jsxs("div",{className:r.aiProfileDetailDataRow,children:[a.jsx("span",{className:r.aiProfileDetailDataLabel,children:e.label}),e.label==="Category"&&!oe(n.primaryProfile)?a.jsx("span",{className:r.aiProfileDetailDataValue,children:a.jsxs("select",{className:r.aiProfileStatusSelect,"aria-label":"Agent category",value:n.primaryProfile.surfaceType??"",disabled:_e,onChange:t=>{Je(n,t.target.value)},children:[a.jsx("option",{value:"",children:"Unclassified"}),ta.map(t=>a.jsx("option",{value:t,children:Re(t)},t))]})}):a.jsx("span",{className:r.aiProfileDetailDataValue,children:e.value})]},e.label))}),a.jsx("div",{className:`${r.aiProfileDetailDataGroup} ${r.aiProfileDetailDateGroup}`,children:be.dates.map(e=>a.jsxs("div",{className:r.aiProfileDetailDataRow,children:[a.jsx("span",{className:r.aiProfileDetailDataLabel,children:e.label}),e.label==="Status"?a.jsx("span",{className:r.aiProfileDetailDataValue,children:a.jsxs("select",{className:r.aiProfileStatusSelect,"aria-label":"Agent roster status",value:n.primaryProfile.archivedAt?"retired":"active",onChange:t=>{t.target.value==="retire"&&xe(n.primaryProfile)},children:[a.jsx("option",{value:"active",children:"Active"}),n.primaryProfile.archivedAt?a.jsx("option",{value:"retired",children:"Retired"}):a.jsx("option",{value:"retire",children:"Retire from roster"})]})}):a.jsx("span",{className:r.aiProfileDetailDataValue,children:e.value})]},e.label))})]}),ne?.profileId===n.primaryProfile.id&&a.jsxs("div",{className:r.aiProfileInlineError,role:"alert",children:[a.jsx(J,{size:12}),a.jsx("span",{children:ne.message})]}),qe?a.jsxs("div",{className:r.aiProfileInstanceSection,children:[a.jsxs("div",{className:r.aiProfileInstanceSectionHeader,children:[a.jsx("span",{children:"Profile instances"}),a.jsx("span",{className:r.settingsHint,children:"Choose a keeper here if duplicates need to be merged."})]}),a.jsx("div",{className:r.aiProfileInstanceList,children:n.profiles.map(e=>a.jsxs("div",{className:r.aiProfileInstanceCard,children:[a.jsxs("div",{className:r.aiProfileInstanceTopRow,children:[a.jsxs("div",{children:[a.jsxs("div",{className:r.aiProfileInstanceName,children:["@",e.username]}),a.jsx("div",{className:r.aiProfileIdChip,children:e.id})]}),S?.keepId===e.id&&a.jsx("span",{className:r.aiProfileKeepBadge,children:"Keeping"})]}),a.jsxs("div",{className:r.aiProfileInstanceMeta,children:[a.jsxs("span",{children:["Created ",M(e.createdAt)]}),a.jsxs("span",{children:["Updated ",M(e.updatedAt)]})]}),S?.keepId!==e.id&&a.jsx("button",{className:r.secondaryHeaderBtn,title:"Keep this profile, merge others into it",onClick:()=>{const t=n.profiles.find(l=>l.id!==e.id)?.id;t&&F({keepId:e.id,mergeId:t})},children:"Keep this"}),G?.profileId===e.id&&a.jsxs("div",{className:r.aiProfileInlineError,role:"alert",children:[a.jsx(J,{size:12}),a.jsx("span",{children:G.message})]}),a.jsx("button",{className:r.aiProfileDangerTextButton,title:"Remove this profile from the active roster",onClick:()=>{xe(e)},children:"Remove from roster"})]},e.id))}),S&&n.profiles.some(e=>e.id===S.keepId)&&a.jsxs("div",{className:r.aiProfileMergeActions,children:[a.jsx("button",{className:r.dangerBtn,onClick:()=>{Ve(S.keepId,S.mergeId)},children:"Merge duplicates"}),a.jsx("button",{className:r.secondaryHeaderBtn,onClick:()=>F(null),children:"Cancel"})]})]}):a.jsxs("div",{className:r.aiProfileIdFooter,children:[a.jsx("div",{className:r.aiProfileIdFooterValue,children:n.primaryProfile.id}),G?.profileId===n.primaryProfile.id&&a.jsxs("div",{className:r.aiProfileInlineError,role:"alert",children:[a.jsx(J,{size:12}),a.jsx("span",{children:G.message})]})]})]})})})]})}),a.jsx(ia,{isOpen:!!p,theme:Be,title:"Edit AI Profile Photo",currentImageUrl:ie(p),editorImageUrl:ha(p),fallbackInitial:(p?.name||"AI").charAt(0).toUpperCase(),accept:"image/png,image/jpeg,image/webp,image/gif",busy:ue,generating:R===p?.id,generateLabel:p&&L(p)?"Regenerate":"Generate",hasPendingImage:!1,canRemove:!!p?.avatarUrl,error:ze||Ae?.error||null,notice:He||Ae?.notice||null,onClose:()=>{ue||(fe(null),P(null),x(null))},onApplyImage:Xe,onGenerateImage:p&&(!R||R===p.id)&&(oa(p)||te(p))?()=>Ye(p):void 0,onRemoveImage:Ze},p?.id||"ai-profile-avatar-closed")]})}export{Ta as AiProfilesModule};
@@ -1,3 +1,3 @@
1
- import{j as t,r as s,R as en}from"./vendor-react-CKJs5o3c.js";import{u as Rs,a as wa,D as As,c as Es,S as Ps,v as Ms,C as Bs,f as Fs,s as Ds,K as Os,P as Hs,d as zs}from"./vendor-dnd-CJ-AjP-Y.js";import{R as Us,f as le,e as tn,h as Gs,t as Ia,M as nn}from"./index-Cx7vZJHL.js";import{s as Ks,A as Vs}from"./AssetTraySortControl-DphbyHVc.js";import{ak as Sa,Z as Ws,S as Ys,w as qs,p as Xs,L as Js,P as Zs,V as En,T as Ca,x as Qs,h as Na,av as er,R as tr,aw as nr,ax as ar,ay as sr,az as rr,aA as Bn,C as Fn,aB as or,aC as Ba,aD as Fa,aE as Da,aF as Oa,e as Dn,G as Ta}from"./vendor-icons-B8ZNsH1g.js";import"./vendor-markdown-_lhNCyq-.js";import"./vendor-router-AqJMU8Lz.js";function ir({copied:r,disabled:l=!1,label:h,onClick:g,title:v="Copy image reference",ariaLabel:_,className:D=""}){return t.jsx(Us,{copied:r,disabled:l,label:"",onClick:g,title:v,ariaLabel:_,className:D,children:h})}const lr="_shell_1tt0t_1",cr="_shellWithImageTray_1tt0t_18",dr="_shellImageTrayOpen_1tt0t_22",ur="_imageTrayPanel_1tt0t_26",mr="_imageTrayPanelOpen_1tt0t_50",fr="_imageTrayHeader_1tt0t_58",hr="_imageTrayTitle_1tt0t_73",pr="_imageTraySearch_1tt0t_85",gr="_imageTraySearchIcon_1tt0t_91",yr="_imageTraySearchInput_1tt0t_100",br="_imageTraySortControlRow_1tt0t_117",xr="_imageTrayList_1tt0t_124",vr="_imageTrayState_1tt0t_136",_r="_imageTrayStateError_1tt0t_137",kr="_imageTrayItem_1tt0t_149",wr="_imageTrayItemActive_1tt0t_171",Ir="_imageTrayThumb_1tt0t_181",Sr="_imageTrayItemBody_1tt0t_198",Cr="_imageTrayItemTitle_1tt0t_206",Nr="_imageTrayItemTask_1tt0t_207",Tr="_imageTrayItemMetaDetails_1tt0t_208",jr="_imageTrayItemMeta_1tt0t_208",$r="_imageTrayItemReference_1tt0t_246",Lr="_panel_1tt0t_253",Rr="_sessionPanel_1tt0t_259",Ar="_detailPanel_1tt0t_260",Er="_sessionContextBar_1tt0t_266",Pr="_sessionContextLeft_1tt0t_277",Mr="_sessionContextRight_1tt0t_278",Br="_sessionContextLabel_1tt0t_293",Fr="_sessionContextSpacer_1tt0t_299",Dr="_canvasPanel_1tt0t_304",Or="_canvasWorkspace_1tt0t_311",Hr="_canvasMain_1tt0t_318",zr="_panelHeader_1tt0t_325",Ur="_panelHeaderText_1tt0t_334",Gr="_panelTitle_1tt0t_338",Kr="_canvasHeading_1tt0t_342",Vr="_sessionActions_1tt0t_346",Wr="_taskLinkModalBody_1tt0t_354",Yr="_taskLinkList_1tt0t_364",qr="_taskLinkOption_1tt0t_372",Xr="_taskLinkOptionActive_1tt0t_387",Jr="_taskLinkOptionTitle_1tt0t_395",Zr="_taskLinkActions_1tt0t_399",Qr="_sessionList_1tt0t_405",eo="_annotationList_1tt0t_406",to="_markerHelpModalBody_1tt0t_416",no="_openImageModalBody_1tt0t_422",ao="_openImageField_1tt0t_428",so="_openImageActions_1tt0t_432",ro="_markerHelpItem_1tt0t_438",oo="_markerHelpHeader_1tt0t_446",io="_markerHelpExample_1tt0t_458",lo="_sessionCard_1tt0t_462",co="_annotationCard_1tt0t_463",uo="_sessionEmptyState_1tt0t_477",mo="_sessionCardButton_1tt0t_484",fo="_annotationCardButton_1tt0t_494",ho="_sessionCardBody_1tt0t_506",po="_sessionCardActive_1tt0t_512",go="_annotationCardActive_1tt0t_513",yo="_annotationMeta_1tt0t_528",bo="_annotationDragHandle_1tt0t_535",xo="_annotationCardDragging_1tt0t_561",vo="_annotationDragOverlay_1tt0t_565",_o="_annotationDragOverlayGrip_1tt0t_572",ko="_annotationDragOverlayTitle_1tt0t_576",wo="_annotationInstructionPreview_1tt0t_582",Io="_annotationPreviewFooter_1tt0t_590",So="_annotationInstructionEditor_1tt0t_597",Co="_annotationTypeField_1tt0t_603",No="_annotationGeometryDetails_1tt0t_609",To="_annotationGeometryFields_1tt0t_618",jo="_annotationGeometryField_1tt0t_618",$o="_annotationGeometryLabel_1tt0t_631",Lo="_annotationGeometryInput_1tt0t_636",Ro="_annotationInstructionButton_1tt0t_641",Ao="_annotationInstructionField_1tt0t_650",Eo="_sessionMeta_1tt0t_654",Po="_sessionTitle_1tt0t_661",Mo="_annotationTitle_1tt0t_662",Bo="_sessionTimestamp_1tt0t_668",Fo="_annotationKind_1tt0t_669",Do="_annotationInstructionTypeIcon_1tt0t_673",Oo="_sessionInstructionPreview_1tt0t_679",Ho="_sessionInstructionEditor_1tt0t_687",zo="_sessionCardFooter_1tt0t_693",Uo="_toolRail_1tt0t_700",Go="_canvasToolRail_1tt0t_709",Ko="_toolbarCluster_1tt0t_730",Vo="_toolbarViewportCluster_1tt0t_737",Wo="_toolbarSeparator_1tt0t_741",Yo="_toolBtn_1tt0t_747",qo="_toolRailButton_1tt0t_751",Xo="_toolbarButton_1tt0t_761",Jo="_toolBtnActive_1tt0t_766",Zo="_toolbarActions_1tt0t_773",Qo="_toolbarSelectionActions_1tt0t_782",ei="_toolbarColorPicker_1tt0t_790",ti="_colorPickerButton_1tt0t_794",ni="_colorPickerSwatch_1tt0t_799",ai="_colorPickerPopover_1tt0t_807",si="_colorOption_1tt0t_822",ri="_colorOptionActive_1tt0t_832",oi="_toolbarUtilities_1tt0t_839",ii="_iconButton_1tt0t_847",li="_ghostBtn_1tt0t_852",ci="_payloadBtn_1tt0t_853",di="_backToTaskBtn_1tt0t_854",ui="_canvasScroller_1tt0t_874",mi="_canvasFrame_1tt0t_890",fi="_canvasMedia_1tt0t_899",hi="_canvasStatusOverlay_1tt0t_907",pi="_canvasStatusCard_1tt0t_919",gi="_canvasImage_1tt0t_932",yi="_overlay_1tt0t_939",bi="_overlaySelect_1tt0t_945",xi="_overlayPan_1tt0t_949",vi="_overlaySvg_1tt0t_953",_i="_overlayHitLayer_1tt0t_962",ki="_arrowHitArea_1tt0t_971",wi="_canvasHandleHit_1tt0t_978",Ii="_canvasResizeHandleHit_1tt0t_985",Si="_canvasHandleVisible_1tt0t_989",Ci="_pin_1tt0t_1006",Ni="_note_1tt0t_1007",Ti="_annotationNumberBadge_1tt0t_1024",ji="_box_1tt0t_1049",$i="_boxNumberBadge_1tt0t_1058",Li="_arrowNumberBadge_1tt0t_1064",Ri="_boxSurface_1tt0t_1068",Ai="_selected_1tt0t_1081",Ei="_textInput_1tt0t_1098",Pi="_textArea_1tt0t_1099",Mi="_select_1tt0t_1081",Bi="_sessionTitleInput_1tt0t_1108",Fi="_sessionInstructionField_1tt0t_1113",Di="_detailEmpty_1tt0t_1122",Oi="_emptyState_1tt0t_1123",Hi="_payloadModalBody_1tt0t_1135",zi="_payloadModalToolbar_1tt0t_1142",Ui="_payloadViewToggle_1tt0t_1149",Gi="_payloadModalActions_1tt0t_1150",Ki="_payloadModalPreview_1tt0t_1157",Vi="_statusBar_1tt0t_1172",Wi="_annotationSummary_1tt0t_1184",n={shell:lr,shellWithImageTray:cr,shellImageTrayOpen:dr,imageTrayPanel:ur,imageTrayPanelOpen:mr,imageTrayHeader:fr,imageTrayTitle:hr,imageTraySearch:pr,imageTraySearchIcon:gr,imageTraySearchInput:yr,imageTraySortControlRow:br,imageTrayList:xr,imageTrayState:vr,imageTrayStateError:_r,imageTrayItem:kr,imageTrayItemActive:wr,imageTrayThumb:Ir,imageTrayItemBody:Sr,imageTrayItemTitle:Cr,imageTrayItemTask:Nr,imageTrayItemMetaDetails:Tr,imageTrayItemMeta:jr,imageTrayItemReference:$r,panel:Lr,sessionPanel:Rr,detailPanel:Ar,sessionContextBar:Er,sessionContextLeft:Pr,sessionContextRight:Mr,sessionContextLabel:Br,sessionContextSpacer:Fr,canvasPanel:Dr,canvasWorkspace:Or,canvasMain:Hr,panelHeader:zr,panelHeaderText:Ur,panelTitle:Gr,canvasHeading:Kr,sessionActions:Vr,taskLinkModalBody:Wr,taskLinkList:Yr,taskLinkOption:qr,taskLinkOptionActive:Xr,taskLinkOptionTitle:Jr,taskLinkActions:Zr,sessionList:Qr,annotationList:eo,markerHelpModalBody:to,openImageModalBody:no,openImageField:ao,openImageActions:so,markerHelpItem:ro,markerHelpHeader:oo,markerHelpExample:io,sessionCard:lo,annotationCard:co,sessionEmptyState:uo,sessionCardButton:mo,annotationCardButton:fo,sessionCardBody:ho,sessionCardActive:po,annotationCardActive:go,annotationMeta:yo,annotationDragHandle:bo,annotationCardDragging:xo,annotationDragOverlay:vo,annotationDragOverlayGrip:_o,annotationDragOverlayTitle:ko,annotationInstructionPreview:wo,annotationPreviewFooter:Io,annotationInstructionEditor:So,annotationTypeField:Co,annotationGeometryDetails:No,annotationGeometryFields:To,annotationGeometryField:jo,annotationGeometryLabel:$o,annotationGeometryInput:Lo,annotationInstructionButton:Ro,annotationInstructionField:Ao,sessionMeta:Eo,sessionTitle:Po,annotationTitle:Mo,sessionTimestamp:Bo,annotationKind:Fo,annotationInstructionTypeIcon:Do,sessionInstructionPreview:Oo,sessionInstructionEditor:Ho,sessionCardFooter:zo,toolRail:Uo,canvasToolRail:Go,toolbarCluster:Ko,toolbarViewportCluster:Vo,toolbarSeparator:Wo,toolBtn:Yo,toolRailButton:qo,toolbarButton:Xo,toolBtnActive:Jo,toolbarActions:Zo,toolbarSelectionActions:Qo,toolbarColorPicker:ei,colorPickerButton:ti,colorPickerSwatch:ni,colorPickerPopover:ai,colorOption:si,colorOptionActive:ri,toolbarUtilities:oi,iconButton:ii,ghostBtn:li,payloadBtn:ci,backToTaskBtn:di,canvasScroller:ui,canvasFrame:mi,canvasMedia:fi,canvasStatusOverlay:hi,canvasStatusCard:pi,canvasImage:gi,overlay:yi,overlaySelect:bi,overlayPan:xi,overlaySvg:vi,overlayHitLayer:_i,arrowHitArea:ki,canvasHandleHit:wi,canvasResizeHandleHit:Ii,canvasHandleVisible:Si,pin:Ci,note:Ni,annotationNumberBadge:Ti,box:ji,boxNumberBadge:$i,arrowNumberBadge:Li,boxSurface:Ri,selected:Ai,textInput:Ei,textArea:Pi,select:Mi,sessionTitleInput:Bi,sessionInstructionField:Fi,detailEmpty:Di,emptyState:Oi,payloadModalBody:Hi,payloadModalToolbar:zi,payloadViewToggle:Ui,payloadModalActions:Gi,payloadModalPreview:Ki,statusBar:Vi,annotationSummary:Wi};function Yi({id:r,children:l}){return t.jsx(t.Fragment,{children:l(zs({id:r}))})}const ja=[{value:"review",label:"Review"},{value:"change",label:"Change"},{value:"question",label:"Question"}],$a=[{value:"select",label:"Select",icon:or},{value:"pin",label:"Pin",icon:Ba},{value:"box",label:"Box",icon:Fa},{value:"arrow",label:"Arrow",icon:Da},{value:"text-note",label:"Note",icon:Oa}],qi=200,La={pin:Ba,box:Fa,arrow:Da,"text-note":Oa},Ra={pin:"Pin",box:"Box",arrow:"Arrow","text-note":"Note"},Xi={review:Bn,change:Dn,question:Fn,issue:Fn,idea:Bn},an={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."'}},Tt={question:"#0f766e",change:"#2563eb",issue:"#dc2626",idea:"#d97706",review:"#7c3aed"},Ji=["#7c3aed","#2563eb","#0f766e","#dc2626","#d97706","#111827"],ye="review";function et(r){const l=String(r.displayName||"").trim();return l?`${l} review`:"Annotated session"}function Ha(){return`annotation-${Math.random().toString(36).slice(2,10)}`}function I(r){return!Number.isFinite(r)||r<=0?0:r>=1?1:r}function Ee(r){return I(Math.max(.02,r))}function Re(r){return r?[String(r.taskId||"").trim(),String(r.assetId||"").trim(),String(r.path||"").trim()].join("::"):""}function za(r){if(!(r instanceof HTMLElement))return!1;const l=r.tagName.toLowerCase();return r.isContentEditable?!0:l==="input"||l==="textarea"||l==="select"}function Zi(r){if(!(r instanceof HTMLElement))return!1;if(za(r))return!0;const l=r.tagName.toLowerCase();return l==="button"||l==="a"||r.getAttribute("role")==="button"}function Ae(r){return r.map((l,h)=>({...l,order:h}))}function Pn(r){if(!r)return"Unsaved";const l=new Date(r);return Number.isNaN(l.getTime())?"Unsaved":l.toLocaleString()}function Qi(r){const l=typeof r=="number"&&Number.isFinite(r)?Math.max(0,r):0;return l<1024?`${l}B`:l<1024*1024?`${(l/1024).toFixed(1)}KB`:`${(l/(1024*1024)).toFixed(1)}MB`}function el(r){if(!r)return"";const l=new Date(r);if(Number.isNaN(l.getTime()))return"";const g=new Date().getTime()-l.getTime(),v=Math.floor(g/(1e3*60*60*24));return v<=0?"Today":v===1?"Yesterday":v<7?`${v}d ago`:v<30?`${Math.floor(v/7)}w ago`:l.toLocaleDateString()}function sn(r){const l=String(r.createdByActor?.label||"").trim();return l||null}function tl(r){const l=String(r||"").trim().replace(/\s+/g," ");return l?l.length>110?`${l.slice(0,107)}...`:l:""}function Aa(r,l,h,g=Tt[ye]){const v={id:Ha(),order:0,instruction:"",markerType:ye,color:g};if(r==="pin")return{...v,kind:r,x:l.x,y:l.y};if(r==="text-note")return{...v,kind:r,x:l.x,y:l.y};if(r==="box"){const D=h||l;return{...v,kind:r,x:I(Math.min(l.x,D.x)),y:I(Math.min(l.y,D.y)),width:Ee(Math.abs(D.x-l.x)),height:Ee(Math.abs(D.y-l.y))}}const _=h||l;return{...v,kind:"arrow",x:l.x,y:l.y,x2:_.x,y2:_.y}}function rn(r){return r.color?r.color:Tt[r.markerType||ye]}function nl(r,l){const h=Math.max(l.width,1),g=Math.max(l.height,1),v=r.x*h,_=r.y*g,D=r.x2*h,de=r.y2*g,ue=D-v,jt=de-_,Pe=Math.hypot(ue,jt)||1,tt=ue/Pe,Me=jt/Pe,W=Math.max(10,Math.min(16,Pe-2)),Se=W*.62,nt=D-tt*W,Ce=de-Me*W,at=-Me,$=tt;return{shaftX1:v,shaftY1:_,shaftX2:nt,shaftY2:Ce,headPoints:[`${D},${de}`,`${nt+at*Se},${Ce+$*Se}`,`${nt-at*Se},${Ce-$*Se}`].join(" ")}}function al(r,l){return{...r,markerType:l,color:r.color||Tt[l]}}function sl(r,l){return{...r,id:Ha(),order:l}}function rl(r,l){const h=String(r||"").trim()||(l?et(l):"Annotated session");return/\bcopy$/i.test(h)?`${h} 2`:`${h} copy`}function ol(r,l,h){if(l===h||l<0||h<0||l>=r.length||h>=r.length)return r;const g=[...r],[v]=g.splice(l,1);return v?(g.splice(h,0,v),Ae(g)):r}function ce(r){return String(Math.round(I(r)*1e3)/10)}function il(r){const l=Number.parseFloat(r);return Number.isFinite(l)?I(l/100):null}function ll(r,l,h){return r.kind==="pin"||r.kind==="text-note"?l==="x"||l==="y"?{...r,[l]:I(h)}:r:r.kind==="box"?l==="x"||l==="y"?{...r,[l]:I(h)}:l==="width"||l==="height"?{...r,[l]:Ee(h)}:r:l==="x"||l==="y"||l==="x2"||l==="y2"?{...r,[l]:I(h)}:r}function cl(r){return r.kind==="pin"||r.kind==="text-note"?[{key:"x",label:"X",value:ce(r.x)},{key:"y",label:"Y",value:ce(r.y)}]:r.kind==="box"?[{key:"x",label:"X",value:ce(r.x)},{key:"y",label:"Y",value:ce(r.y)},{key:"width",label:"Width",value:ce(r.width)},{key:"height",label:"Height",value:ce(r.height)}]:[{key:"x",label:"Start X",value:ce(r.x)},{key:"y",label:"Start Y",value:ce(r.y)},{key:"x2",label:"End X",value:ce(r.x2)},{key:"y2",label:"End Y",value:ce(r.y2)}]}function dl(r){if(!r)return null;const l=Math.round(r.x*100),h=Math.round(r.y*100),g=Math.round(r.width*100),v=Math.round(r.height*100);return`crop ${l}%, ${h}% size ${g}% x ${v}%`}function Mn(r){return Number.isFinite(r)?Math.min(4,Math.max(.25,Number(r.toFixed(2)))):1}function Ea(r){const l=[`Annotated attachment: ${r.title||r.image.displayName}`,`Image: ${r.image.displayName}`,`Image Reference: ${r.image.referenceLabel||r.image.assetId}`,`Task ID: ${r.taskId}`,r.globalInstruction?`Global instruction: ${r.globalInstruction}`:"Global instruction: None provided.","Markers:"];return r.annotations.length===0?(l.push("0. No markers."),l.join(`
1
+ import{j as t,r as s,R as en}from"./vendor-react-CKJs5o3c.js";import{u as Rs,a as wa,D as As,c as Es,S as Ps,v as Ms,C as Bs,f as Fs,s as Ds,K as Os,P as Hs,d as zs}from"./vendor-dnd-CJ-AjP-Y.js";import{R as Us,f as le,e as tn,h as Gs,t as Ia,M as nn}from"./index-BUplSsv_.js";import{s as Ks,A as Vs}from"./AssetTraySortControl-Kf1pelSy.js";import{aE as Sa,ai as Ws,S as Ys,a5 as qs,V as Xs,q as Js,t as Zs,af as En,r as Ca,a6 as Qs,w as Na,aP as er,R as tr,aQ as nr,aR as ar,aS as sr,aT as rr,aU as Bn,C as Fn,aV as or,aW as Ba,aX as Fa,aY as Da,aZ as Oa,u as Dn,Q as Ta}from"./vendor-icons-BkFLXavV.js";import"./vendor-markdown-_lhNCyq-.js";import"./vendor-router-AqJMU8Lz.js";function ir({copied:r,disabled:l=!1,label:h,onClick:g,title:v="Copy image reference",ariaLabel:_,className:D=""}){return t.jsx(Us,{copied:r,disabled:l,label:"",onClick:g,title:v,ariaLabel:_,className:D,children:h})}const lr="_shell_1tt0t_1",cr="_shellWithImageTray_1tt0t_18",dr="_shellImageTrayOpen_1tt0t_22",ur="_imageTrayPanel_1tt0t_26",mr="_imageTrayPanelOpen_1tt0t_50",fr="_imageTrayHeader_1tt0t_58",hr="_imageTrayTitle_1tt0t_73",pr="_imageTraySearch_1tt0t_85",gr="_imageTraySearchIcon_1tt0t_91",yr="_imageTraySearchInput_1tt0t_100",br="_imageTraySortControlRow_1tt0t_117",xr="_imageTrayList_1tt0t_124",vr="_imageTrayState_1tt0t_136",_r="_imageTrayStateError_1tt0t_137",kr="_imageTrayItem_1tt0t_149",wr="_imageTrayItemActive_1tt0t_171",Ir="_imageTrayThumb_1tt0t_181",Sr="_imageTrayItemBody_1tt0t_198",Cr="_imageTrayItemTitle_1tt0t_206",Nr="_imageTrayItemTask_1tt0t_207",Tr="_imageTrayItemMetaDetails_1tt0t_208",jr="_imageTrayItemMeta_1tt0t_208",$r="_imageTrayItemReference_1tt0t_246",Lr="_panel_1tt0t_253",Rr="_sessionPanel_1tt0t_259",Ar="_detailPanel_1tt0t_260",Er="_sessionContextBar_1tt0t_266",Pr="_sessionContextLeft_1tt0t_277",Mr="_sessionContextRight_1tt0t_278",Br="_sessionContextLabel_1tt0t_293",Fr="_sessionContextSpacer_1tt0t_299",Dr="_canvasPanel_1tt0t_304",Or="_canvasWorkspace_1tt0t_311",Hr="_canvasMain_1tt0t_318",zr="_panelHeader_1tt0t_325",Ur="_panelHeaderText_1tt0t_334",Gr="_panelTitle_1tt0t_338",Kr="_canvasHeading_1tt0t_342",Vr="_sessionActions_1tt0t_346",Wr="_taskLinkModalBody_1tt0t_354",Yr="_taskLinkList_1tt0t_364",qr="_taskLinkOption_1tt0t_372",Xr="_taskLinkOptionActive_1tt0t_387",Jr="_taskLinkOptionTitle_1tt0t_395",Zr="_taskLinkActions_1tt0t_399",Qr="_sessionList_1tt0t_405",eo="_annotationList_1tt0t_406",to="_markerHelpModalBody_1tt0t_416",no="_openImageModalBody_1tt0t_422",ao="_openImageField_1tt0t_428",so="_openImageActions_1tt0t_432",ro="_markerHelpItem_1tt0t_438",oo="_markerHelpHeader_1tt0t_446",io="_markerHelpExample_1tt0t_458",lo="_sessionCard_1tt0t_462",co="_annotationCard_1tt0t_463",uo="_sessionEmptyState_1tt0t_477",mo="_sessionCardButton_1tt0t_484",fo="_annotationCardButton_1tt0t_494",ho="_sessionCardBody_1tt0t_506",po="_sessionCardActive_1tt0t_512",go="_annotationCardActive_1tt0t_513",yo="_annotationMeta_1tt0t_528",bo="_annotationDragHandle_1tt0t_535",xo="_annotationCardDragging_1tt0t_561",vo="_annotationDragOverlay_1tt0t_565",_o="_annotationDragOverlayGrip_1tt0t_572",ko="_annotationDragOverlayTitle_1tt0t_576",wo="_annotationInstructionPreview_1tt0t_582",Io="_annotationPreviewFooter_1tt0t_590",So="_annotationInstructionEditor_1tt0t_597",Co="_annotationTypeField_1tt0t_603",No="_annotationGeometryDetails_1tt0t_609",To="_annotationGeometryFields_1tt0t_618",jo="_annotationGeometryField_1tt0t_618",$o="_annotationGeometryLabel_1tt0t_631",Lo="_annotationGeometryInput_1tt0t_636",Ro="_annotationInstructionButton_1tt0t_641",Ao="_annotationInstructionField_1tt0t_650",Eo="_sessionMeta_1tt0t_654",Po="_sessionTitle_1tt0t_661",Mo="_annotationTitle_1tt0t_662",Bo="_sessionTimestamp_1tt0t_668",Fo="_annotationKind_1tt0t_669",Do="_annotationInstructionTypeIcon_1tt0t_673",Oo="_sessionInstructionPreview_1tt0t_679",Ho="_sessionInstructionEditor_1tt0t_687",zo="_sessionCardFooter_1tt0t_693",Uo="_toolRail_1tt0t_700",Go="_canvasToolRail_1tt0t_709",Ko="_toolbarCluster_1tt0t_730",Vo="_toolbarViewportCluster_1tt0t_737",Wo="_toolbarSeparator_1tt0t_741",Yo="_toolBtn_1tt0t_747",qo="_toolRailButton_1tt0t_751",Xo="_toolbarButton_1tt0t_761",Jo="_toolBtnActive_1tt0t_766",Zo="_toolbarActions_1tt0t_773",Qo="_toolbarSelectionActions_1tt0t_782",ei="_toolbarColorPicker_1tt0t_790",ti="_colorPickerButton_1tt0t_794",ni="_colorPickerSwatch_1tt0t_799",ai="_colorPickerPopover_1tt0t_807",si="_colorOption_1tt0t_822",ri="_colorOptionActive_1tt0t_832",oi="_toolbarUtilities_1tt0t_839",ii="_iconButton_1tt0t_847",li="_ghostBtn_1tt0t_852",ci="_payloadBtn_1tt0t_853",di="_backToTaskBtn_1tt0t_854",ui="_canvasScroller_1tt0t_874",mi="_canvasFrame_1tt0t_890",fi="_canvasMedia_1tt0t_899",hi="_canvasStatusOverlay_1tt0t_907",pi="_canvasStatusCard_1tt0t_919",gi="_canvasImage_1tt0t_932",yi="_overlay_1tt0t_939",bi="_overlaySelect_1tt0t_945",xi="_overlayPan_1tt0t_949",vi="_overlaySvg_1tt0t_953",_i="_overlayHitLayer_1tt0t_962",ki="_arrowHitArea_1tt0t_971",wi="_canvasHandleHit_1tt0t_978",Ii="_canvasResizeHandleHit_1tt0t_985",Si="_canvasHandleVisible_1tt0t_989",Ci="_pin_1tt0t_1006",Ni="_note_1tt0t_1007",Ti="_annotationNumberBadge_1tt0t_1024",ji="_box_1tt0t_1049",$i="_boxNumberBadge_1tt0t_1058",Li="_arrowNumberBadge_1tt0t_1064",Ri="_boxSurface_1tt0t_1068",Ai="_selected_1tt0t_1081",Ei="_textInput_1tt0t_1098",Pi="_textArea_1tt0t_1099",Mi="_select_1tt0t_1081",Bi="_sessionTitleInput_1tt0t_1108",Fi="_sessionInstructionField_1tt0t_1113",Di="_detailEmpty_1tt0t_1122",Oi="_emptyState_1tt0t_1123",Hi="_payloadModalBody_1tt0t_1135",zi="_payloadModalToolbar_1tt0t_1142",Ui="_payloadViewToggle_1tt0t_1149",Gi="_payloadModalActions_1tt0t_1150",Ki="_payloadModalPreview_1tt0t_1157",Vi="_statusBar_1tt0t_1172",Wi="_annotationSummary_1tt0t_1184",n={shell:lr,shellWithImageTray:cr,shellImageTrayOpen:dr,imageTrayPanel:ur,imageTrayPanelOpen:mr,imageTrayHeader:fr,imageTrayTitle:hr,imageTraySearch:pr,imageTraySearchIcon:gr,imageTraySearchInput:yr,imageTraySortControlRow:br,imageTrayList:xr,imageTrayState:vr,imageTrayStateError:_r,imageTrayItem:kr,imageTrayItemActive:wr,imageTrayThumb:Ir,imageTrayItemBody:Sr,imageTrayItemTitle:Cr,imageTrayItemTask:Nr,imageTrayItemMetaDetails:Tr,imageTrayItemMeta:jr,imageTrayItemReference:$r,panel:Lr,sessionPanel:Rr,detailPanel:Ar,sessionContextBar:Er,sessionContextLeft:Pr,sessionContextRight:Mr,sessionContextLabel:Br,sessionContextSpacer:Fr,canvasPanel:Dr,canvasWorkspace:Or,canvasMain:Hr,panelHeader:zr,panelHeaderText:Ur,panelTitle:Gr,canvasHeading:Kr,sessionActions:Vr,taskLinkModalBody:Wr,taskLinkList:Yr,taskLinkOption:qr,taskLinkOptionActive:Xr,taskLinkOptionTitle:Jr,taskLinkActions:Zr,sessionList:Qr,annotationList:eo,markerHelpModalBody:to,openImageModalBody:no,openImageField:ao,openImageActions:so,markerHelpItem:ro,markerHelpHeader:oo,markerHelpExample:io,sessionCard:lo,annotationCard:co,sessionEmptyState:uo,sessionCardButton:mo,annotationCardButton:fo,sessionCardBody:ho,sessionCardActive:po,annotationCardActive:go,annotationMeta:yo,annotationDragHandle:bo,annotationCardDragging:xo,annotationDragOverlay:vo,annotationDragOverlayGrip:_o,annotationDragOverlayTitle:ko,annotationInstructionPreview:wo,annotationPreviewFooter:Io,annotationInstructionEditor:So,annotationTypeField:Co,annotationGeometryDetails:No,annotationGeometryFields:To,annotationGeometryField:jo,annotationGeometryLabel:$o,annotationGeometryInput:Lo,annotationInstructionButton:Ro,annotationInstructionField:Ao,sessionMeta:Eo,sessionTitle:Po,annotationTitle:Mo,sessionTimestamp:Bo,annotationKind:Fo,annotationInstructionTypeIcon:Do,sessionInstructionPreview:Oo,sessionInstructionEditor:Ho,sessionCardFooter:zo,toolRail:Uo,canvasToolRail:Go,toolbarCluster:Ko,toolbarViewportCluster:Vo,toolbarSeparator:Wo,toolBtn:Yo,toolRailButton:qo,toolbarButton:Xo,toolBtnActive:Jo,toolbarActions:Zo,toolbarSelectionActions:Qo,toolbarColorPicker:ei,colorPickerButton:ti,colorPickerSwatch:ni,colorPickerPopover:ai,colorOption:si,colorOptionActive:ri,toolbarUtilities:oi,iconButton:ii,ghostBtn:li,payloadBtn:ci,backToTaskBtn:di,canvasScroller:ui,canvasFrame:mi,canvasMedia:fi,canvasStatusOverlay:hi,canvasStatusCard:pi,canvasImage:gi,overlay:yi,overlaySelect:bi,overlayPan:xi,overlaySvg:vi,overlayHitLayer:_i,arrowHitArea:ki,canvasHandleHit:wi,canvasResizeHandleHit:Ii,canvasHandleVisible:Si,pin:Ci,note:Ni,annotationNumberBadge:Ti,box:ji,boxNumberBadge:$i,arrowNumberBadge:Li,boxSurface:Ri,selected:Ai,textInput:Ei,textArea:Pi,select:Mi,sessionTitleInput:Bi,sessionInstructionField:Fi,detailEmpty:Di,emptyState:Oi,payloadModalBody:Hi,payloadModalToolbar:zi,payloadViewToggle:Ui,payloadModalActions:Gi,payloadModalPreview:Ki,statusBar:Vi,annotationSummary:Wi};function Yi({id:r,children:l}){return t.jsx(t.Fragment,{children:l(zs({id:r}))})}const ja=[{value:"review",label:"Review"},{value:"change",label:"Change"},{value:"question",label:"Question"}],$a=[{value:"select",label:"Select",icon:or},{value:"pin",label:"Pin",icon:Ba},{value:"box",label:"Box",icon:Fa},{value:"arrow",label:"Arrow",icon:Da},{value:"text-note",label:"Note",icon:Oa}],qi=200,La={pin:Ba,box:Fa,arrow:Da,"text-note":Oa},Ra={pin:"Pin",box:"Box",arrow:"Arrow","text-note":"Note"},Xi={review:Bn,change:Dn,question:Fn,issue:Fn,idea:Bn},an={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."'}},Tt={question:"#0f766e",change:"#2563eb",issue:"#dc2626",idea:"#d97706",review:"#7c3aed"},Ji=["#7c3aed","#2563eb","#0f766e","#dc2626","#d97706","#111827"],ye="review";function et(r){const l=String(r.displayName||"").trim();return l?`${l} review`:"Annotated session"}function Ha(){return`annotation-${Math.random().toString(36).slice(2,10)}`}function I(r){return!Number.isFinite(r)||r<=0?0:r>=1?1:r}function Ee(r){return I(Math.max(.02,r))}function Re(r){return r?[String(r.taskId||"").trim(),String(r.assetId||"").trim(),String(r.path||"").trim()].join("::"):""}function za(r){if(!(r instanceof HTMLElement))return!1;const l=r.tagName.toLowerCase();return r.isContentEditable?!0:l==="input"||l==="textarea"||l==="select"}function Zi(r){if(!(r instanceof HTMLElement))return!1;if(za(r))return!0;const l=r.tagName.toLowerCase();return l==="button"||l==="a"||r.getAttribute("role")==="button"}function Ae(r){return r.map((l,h)=>({...l,order:h}))}function Pn(r){if(!r)return"Unsaved";const l=new Date(r);return Number.isNaN(l.getTime())?"Unsaved":l.toLocaleString()}function Qi(r){const l=typeof r=="number"&&Number.isFinite(r)?Math.max(0,r):0;return l<1024?`${l}B`:l<1024*1024?`${(l/1024).toFixed(1)}KB`:`${(l/(1024*1024)).toFixed(1)}MB`}function el(r){if(!r)return"";const l=new Date(r);if(Number.isNaN(l.getTime()))return"";const g=new Date().getTime()-l.getTime(),v=Math.floor(g/(1e3*60*60*24));return v<=0?"Today":v===1?"Yesterday":v<7?`${v}d ago`:v<30?`${Math.floor(v/7)}w ago`:l.toLocaleDateString()}function sn(r){const l=String(r.createdByActor?.label||"").trim();return l||null}function tl(r){const l=String(r||"").trim().replace(/\s+/g," ");return l?l.length>110?`${l.slice(0,107)}...`:l:""}function Aa(r,l,h,g=Tt[ye]){const v={id:Ha(),order:0,instruction:"",markerType:ye,color:g};if(r==="pin")return{...v,kind:r,x:l.x,y:l.y};if(r==="text-note")return{...v,kind:r,x:l.x,y:l.y};if(r==="box"){const D=h||l;return{...v,kind:r,x:I(Math.min(l.x,D.x)),y:I(Math.min(l.y,D.y)),width:Ee(Math.abs(D.x-l.x)),height:Ee(Math.abs(D.y-l.y))}}const _=h||l;return{...v,kind:"arrow",x:l.x,y:l.y,x2:_.x,y2:_.y}}function rn(r){return r.color?r.color:Tt[r.markerType||ye]}function nl(r,l){const h=Math.max(l.width,1),g=Math.max(l.height,1),v=r.x*h,_=r.y*g,D=r.x2*h,de=r.y2*g,ue=D-v,jt=de-_,Pe=Math.hypot(ue,jt)||1,tt=ue/Pe,Me=jt/Pe,W=Math.max(10,Math.min(16,Pe-2)),Se=W*.62,nt=D-tt*W,Ce=de-Me*W,at=-Me,$=tt;return{shaftX1:v,shaftY1:_,shaftX2:nt,shaftY2:Ce,headPoints:[`${D},${de}`,`${nt+at*Se},${Ce+$*Se}`,`${nt-at*Se},${Ce-$*Se}`].join(" ")}}function al(r,l){return{...r,markerType:l,color:r.color||Tt[l]}}function sl(r,l){return{...r,id:Ha(),order:l}}function rl(r,l){const h=String(r||"").trim()||(l?et(l):"Annotated session");return/\bcopy$/i.test(h)?`${h} 2`:`${h} copy`}function ol(r,l,h){if(l===h||l<0||h<0||l>=r.length||h>=r.length)return r;const g=[...r],[v]=g.splice(l,1);return v?(g.splice(h,0,v),Ae(g)):r}function ce(r){return String(Math.round(I(r)*1e3)/10)}function il(r){const l=Number.parseFloat(r);return Number.isFinite(l)?I(l/100):null}function ll(r,l,h){return r.kind==="pin"||r.kind==="text-note"?l==="x"||l==="y"?{...r,[l]:I(h)}:r:r.kind==="box"?l==="x"||l==="y"?{...r,[l]:I(h)}:l==="width"||l==="height"?{...r,[l]:Ee(h)}:r:l==="x"||l==="y"||l==="x2"||l==="y2"?{...r,[l]:I(h)}:r}function cl(r){return r.kind==="pin"||r.kind==="text-note"?[{key:"x",label:"X",value:ce(r.x)},{key:"y",label:"Y",value:ce(r.y)}]:r.kind==="box"?[{key:"x",label:"X",value:ce(r.x)},{key:"y",label:"Y",value:ce(r.y)},{key:"width",label:"Width",value:ce(r.width)},{key:"height",label:"Height",value:ce(r.height)}]:[{key:"x",label:"Start X",value:ce(r.x)},{key:"y",label:"Start Y",value:ce(r.y)},{key:"x2",label:"End X",value:ce(r.x2)},{key:"y2",label:"End Y",value:ce(r.y2)}]}function dl(r){if(!r)return null;const l=Math.round(r.x*100),h=Math.round(r.y*100),g=Math.round(r.width*100),v=Math.round(r.height*100);return`crop ${l}%, ${h}% size ${g}% x ${v}%`}function Mn(r){return Number.isFinite(r)?Math.min(4,Math.max(.25,Number(r.toFixed(2)))):1}function Ea(r){const l=[`Annotated attachment: ${r.title||r.image.displayName}`,`Image: ${r.image.displayName}`,`Image Reference: ${r.image.referenceLabel||r.image.assetId}`,`Task ID: ${r.taskId}`,r.globalInstruction?`Global instruction: ${r.globalInstruction}`:"Global instruction: None provided.","Markers:"];return r.annotations.length===0?(l.push("0. No markers."),l.join(`
2
2
  `)):(r.annotations.forEach((h,g)=>{const v=h.markerType||ye,_=dl(h.cropHint);l.push(`${g+1}. ${h.kind} (${v})`),l.push(`Instruction: ${h.instruction||"No marker instruction."}`),_&&l.push(`Region: ${_}`)}),l.join(`
3
3
  `))}function on(r){return{title:r.title,globalInstruction:r.globalInstruction,annotations:Ae(r.annotations)}}function Pa(r){return JSON.stringify(on(r))}function Ma(r){const l=JSON.parse(r);return on({title:String(l?.title||""),globalInstruction:String(l?.globalInstruction||""),annotations:Array.isArray(l?.annotations)?l.annotations:[]})}function ul(r,l){return on({title:r?.title||l,globalInstruction:r?.globalInstruction||"",annotations:r?.annotations||[]})}function vl({runtimeMode:r="local",apiBaseUrl:l="",cloudAuthBaseUrl:h="",workspaceId:g="default",sessionLoadReady:v=!0,requestedTarget:_=null,requestedSessionId:D=null,requestedOpenVersion:de=0,imageTrayOpen:ue,onCloseImageTray:jt,resolveTaskReferenceLabel:Pe,resolveImageReferenceLabel:tt,onRequestedTargetHandled:Me,onOpenTarget:W,onContextChange:Se,viewportByContextKey:nt,onViewportChange:Ce,onBackToTask:at}){const $=r==="cloud"&&(h||l)||"",[Ua,$t]=s.useState(_),[Lt,Be]=s.useState([]),[y,Fe]=s.useState(null),[ln,st]=s.useState(!1),[De,rt]=s.useState(""),[Oe,ot]=s.useState(""),[R,me]=s.useState([]),[A,Z]=s.useState(null),[it,Q]=s.useState(!1),[On,cn]=s.useState(null),[Rt,Hn]=s.useState(Tt[ye]),[At,Et]=s.useState(!1),[E,He]=s.useState("select"),[Ga,Ne]=s.useState(!1),[Pt,zn]=s.useState(!1),[ee,te]=s.useState(!1),[Un,f]=s.useState(null),[Y,B]=s.useState("saved"),[ml,z]=s.useState(null),[Mt,Gn]=s.useState(!1),[fe,dn]=s.useState(null),[be,un]=s.useState(!1),[Ka,mn]=s.useState(!1),[fn,Kn]=s.useState("json"),[Va,Bt]=s.useState(!1),[hn,Vn]=s.useState(""),[pn,Wa]=s.useState([]),[Ft,Wn]=s.useState(!1),[ze,Yn]=s.useState(!1),[Dt,gn]=s.useState(!1),[Ot,yn]=s.useState(!1),[Ya,qn]=s.useState(!1),[qa,Ht]=s.useState(!1),[bn,zt]=s.useState(""),[lt,Xn]=s.useState(!1),[xn,Xa]=s.useState([]),[Ut,Ja]=s.useState(""),[vn,Za]=s.useState("updated"),[_n,Qa]=s.useState("desc"),[es,Jn]=s.useState(!1),[Zn,Qn]=s.useState(null),[q,ct]=s.useState(!1),[dt,ut]=s.useState(!1),[P,mt]=s.useState(1),[ts,ft]=s.useState(!1),[ns,ht]=s.useState(!1),[Gt,ea]=s.useState(!1),[T,pt]=s.useState({width:0,height:0}),ta=s.useRef(null),ne=s.useRef(null),kn=s.useRef(null),na=s.useRef(null),xe=s.useRef(D),he=s.useRef(""),Kt=s.useRef(0),wn=s.useRef(""),Te=s.useRef(0),Vt=s.useRef(null),aa=s.useRef(0),ve=s.useRef(!1),gt=s.useRef(null),In=s.useRef(null),_e=s.useRef(null),O=s.useRef(""),F=s.useRef(""),Wt=s.useRef(null),ae=s.useRef(null),Sn=s.useRef(!1),Ue=s.useRef(!1),Yt=s.useRef(null),yt=s.useRef(null),bt=s.useRef(null),Cn=s.useRef(null),xt=s.useRef(null),Ge=s.useRef(!1),Ke=s.useRef(!0),sa=s.useRef(""),ra=s.useRef(Ce),je=s.useRef(null),Ve=s.useRef(null),We=s.useRef(null),Ye=s.useRef(null),ke=s.useRef(null),se=s.useRef(null),oa=s.useRef(null),ia=s.useRef(null),Nn=s.useRef(new Map),b=s.useMemo(()=>Lt.find(e=>e.id===y)||null,[y,Lt]),U=s.useMemo(()=>`workspaceId=${encodeURIComponent(String(g||"default").trim()||"default")}`,[g]),j=s.useMemo(()=>({"x-taskforce-workspace-id":String(g||"default").trim()||"default"}),[g]),pe=s.useMemo(()=>R.find(e=>e.id===A)||null,[R,A]),vt=s.useMemo(()=>R.find(e=>e.id===On)||null,[On,R]),as=Rs(wa(Hs,{activationConstraint:{distance:6}}),wa(Os,{coordinateGetter:Ds})),re=s.useMemo(()=>Re(_),[_]),ge=typeof W=="function",d=ge?_:Ua,K=s.useMemo(()=>{const e=Re(d);return e?`${e}::${y||""}`:""},[d,y]),_t=K?nt?.[K]??null:null,qt=s.useMemo(()=>{const e=String(b?.taskId||"").trim();if(!e)return"";const a=Pe?.(e).trim()||"";if(a)return a;const o=String(d?.taskId||"").trim(),i=String(d?.taskReferenceLabel||"").trim();return e===o&&i&&i!==e?i:e},[d?.taskId,d?.taskReferenceLabel,Pe,b?.taskId]),la=s.useMemo(()=>{const e=hn.trim().toLowerCase();return e?pn.filter(a=>[a.title,a.referenceLabel,a.id].filter(Boolean).join(" ").toLowerCase().includes(e)):pn},[pn,hn]),kt=s.useMemo(()=>{const e=String(d?.assetId||"").trim();if(!e)return"";const a=tt?.(e).trim()||"";return a||String(d?.imageReferenceLabel||"").trim()},[d?.assetId,d?.imageReferenceLabel,tt]),Tn=pe?.color||Rt,ca=s.useMemo(()=>on({title:De,globalInstruction:Oe,annotations:R}),[R,Oe,De]),qe=s.useMemo(()=>Pa(ca),[ca]),da=qe!==F.current,x=s.useMemo(()=>({width:Math.max(T.width*P,0),height:Math.max(T.height*P,0)}),[T.height,T.width,P]),Xe=s.useMemo(()=>({visibleRadius:7,hitRadius:11}),[]),jn=s.useMemo(()=>`0 0 ${Math.max(x.width,1)} ${Math.max(x.height,1)}`,[x.height,x.width]),wt=typeof ue=="boolean",ua=s.useMemo(()=>{const e=Ut.trim().toLowerCase();let a=xn;return e&&(a=xn.filter(o=>[o.displayName,o.originalFilename,o.imageReferenceLabel,o.taskReferenceLabel,o.assetId].filter(Boolean).join(" ").toLowerCase().includes(e))),Ks(a,vn,_n)},[xn,Ut,vn,_n]),Je=s.useMemo(()=>{const e=ne.current;return e?P>1||x.width>e.clientWidth+1||x.height>e.clientHeight+1:P>1},[x.height,x.width,P]),$n=`${Math.round(P*100)}%`,X=Je&&(ts||ns),Ln=s.useMemo(()=>{const e=new Map;return R.forEach((a,o)=>{e.set(a.id,o+1)}),e},[R]);s.useEffect(()=>{xe.current=D},[D]),s.useEffect(()=>{const e=na.current;if(!e||!A||it)return;e.focus();const a=e.value.length;e.setSelectionRange(a,a)},[it,A]),s.useEffect(()=>{_e.current=y},[y]),s.useEffect(()=>{ra.current=Ce},[Ce]);const Xt=s.useCallback(()=>{xt.current!==null&&(window.clearTimeout(xt.current),xt.current=null);const e=Cn.current;Cn.current=null,e&&K&&ra.current?.(K,e)},[K]),oe=s.useCallback(e=>{if(Ge.current||!K)return;const a=ne.current;a&&(Cn.current={zoomLevel:e??P,scrollLeft:Math.max(0,Math.round(a.scrollLeft)),scrollTop:Math.max(0,Math.round(a.scrollTop))},xt.current===null&&(xt.current=window.setTimeout(Xt,qi)))},[K,Xt,P]),It=s.useCallback(()=>{const e=ne.current;if(!e||e.clientWidth<=0||e.clientHeight<=0||T.width<=0||T.height<=0)return;const a=Mn(Math.min(e.clientWidth/T.width,e.clientHeight/T.height)),o=T.width*a,i=T.height*a;Ke.current=!0,Ge.current=!0,mt(a),window.requestAnimationFrame(()=>{e.scrollLeft=Math.max(0,(o-e.clientWidth)/2),e.scrollTop=Math.max(0,(i-e.clientHeight)/2),oe(a),window.requestAnimationFrame(()=>{Ge.current=!1})})},[T.height,T.width,oe]);s.useEffect(()=>()=>{oe(),Xt()},[K,Xt,oe]),s.useEffect(()=>{st(!1)},[y]),s.useEffect(()=>{if(!pe){Et(!1);return}Hn(pe.color||Tt[pe.markerType||ye])},[pe]);const Jt=s.useCallback(async e=>{const a=typeof performance<"u"?performance.now():Date.now(),o=await le(`/api/taskforce/annotated-attachments/sessions?${U}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...j},body:JSON.stringify({taskId:e.taskId,baseImageAssetId:e.assetId,title:et(e),globalInstruction:"",annotations:[]})},$),i=await o.json().catch(()=>({}));if(!o.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 tn("annotated_session_create_completed",{assetId:e.assetId,taskId:e.taskId||null,sessionId:c.id,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-a),debugTimings:i?.debugTimings||null,serverTiming:typeof o.headers?.get=="function"&&o.headers.get("server-timing")||null}),c},[j,$,U]),ma=s.useCallback(e=>new Promise((a,o)=>{const i=new FileReader;i.onload=()=>a(typeof i.result=="string"?i.result:""),i.onerror=()=>o(i.error||new Error("Failed to read clipboard image.")),i.readAsDataURL(e)}),[]),L=s.useCallback(()=>{gt.current!==null&&(window.clearTimeout(gt.current),gt.current=null),bt.current!==null&&(window.clearTimeout(bt.current),bt.current=null)},[]),Ze=s.useCallback(e=>{rt(e.title),ot(e.globalInstruction),me(e.annotations),Z(a=>a&&e.annotations.some(o=>o.id===a)?a:null)},[]),we=s.useCallback((e,a)=>{const o=et(a||d||{assetId:e.baseImageAssetId,displayName:"Annotated session"}),i=ul(e,o),c=Pa(i);ve.current=!0,L(),Ze(i),F.current=c,O.current=c,Wt.current=null,Ue.current=!1,Yt.current=null,yt.current=null,z(null),B("saved"),te(!1)},[d,Ze,L]),St=s.useCallback(e=>{ve.current=!0,L(),Be([]),Fe(null),Ne(!1),st(!1),rt(et(e)),ot(""),me([]),Z(null),Q(!1),F.current="",O.current="",Wt.current=null,Ue.current=!1,Yt.current=null,yt.current=null,dn(null),mn(!1),z(null),B("saved"),te(!1)},[L]),$e=s.useCallback(async(e,a,o)=>{const i=_e.current;if(!i)return!0;if(e===F.current)return ae.current||(z(null),B("saved")),!0;if(ae.current){if(Ue.current=!0,!o?.waitForInFlight||!await ae.current)return!1;const p=O.current;return p===F.current?!0:$e(p,a,o)}L();const c=Ma(e);Yt.current=i,Wt.current=e,te(!0),f(null),z(null),B("saving");const m=(async()=>{try{const u=await le(`/api/taskforce/annotated-attachments/sessions/${encodeURIComponent(i)}?${U}`,{method:"PATCH",credentials:"include",headers:{"Content-Type":"application/json",...j},body:JSON.stringify(c)},$),p=await u.json().catch(()=>({}));if(!u.ok)throw new Error(String(p?.error||"Failed to save session."));const k=p?.session;if(!k?.id)throw new Error("Failed to save session.");Be(Nt=>{const N=Nt.findIndex(Qt=>Qt.id===k.id);if(N===-1)return[k,...Nt];const Ie=[...Nt];return Ie[N]=k,Ie}),F.current=e,yt.current=null,z(null);const w=_e.current===k.id,C=O.current,G=C!==e,Le=Ue.current||G;return Ue.current=!1,w&&!Le?(ve.current=!0,Ze(c),B("saved")):!Le&&C===F.current?B("saved"):B("pending"),!0}catch(u){const p=u instanceof Error?u.message:"Failed to save session.";return f(p),z(p),B("error"),yt.current!==e&&_e.current===i&&O.current===e&&(yt.current=e,bt.current=window.setTimeout(()=>{bt.current=null,!(_e.current!==i||O.current!==e)&&$e(e,a,{waitForInFlight:!0})},1500)),!1}finally{Wt.current=null,ae.current=null,Yt.current=null,te(!1)}})();ae.current=m;const S=await m;if(S){const u=O.current;if(u!==F.current)return $e(u,a,o)}return S},[Ze,L,j,$,U]),fa=s.useCallback(e=>{if(_e.current){if(O.current===F.current){z(null),ae.current||B("saved");return}Y!=="saving"&&B("pending"),L(),gt.current=window.setTimeout(()=>{gt.current=null,$e(O.current,"structure")},e)}},[L,$e,Y]),J=s.useCallback(e=>{In.current=e},[]),M=s.useCallback(async e=>{L();const a=O.current;return!_e.current||a===F.current?(z(null),ae.current||B("saved"),!0):$e(a,e,{waitForInFlight:!0})},[L,$e]),ss=s.useCallback(()=>{const e=F.current;e&&(L(),ve.current=!0,Ze(Ma(e)),z(null),B("saved"),f(null))},[Ze,L]),V=s.useCallback(async(e,a)=>{const o=typeof performance<"u"?performance.now():Date.now(),i=JSON.stringify({targetKey:Re(e),requestedSessionId:a?.requestedSessionId??null,autoCreateIfEmpty:a?.autoCreateIfEmpty===!0});if(Vt.current===i)return;const c=Te.current+1;Te.current=c,Vt.current=i,zn(!0),f(null);try{const m=new URLSearchParams;g&&m.set("workspaceId",g),e.taskId&&m.set("taskId",e.taskId),m.set("imageAssetId",e.assetId);const S=await le(`/api/taskforce/annotated-attachments/sessions?${m.toString()}`,{credentials:"include",headers:j,cache:"no-store"},$),u=await S.json().catch(()=>({}));if(!S.ok)throw new Error(String(u?.error||"Failed to load annotated attachment sessions."));const p=Array.isArray(u?.sessions)?u.sessions:[];if(tn("annotated_sessions_loaded",{assetId:e.assetId,taskId:e.taskId||null,requestedSessionId:a?.requestedSessionId??null,autoCreateIfEmpty:a?.autoCreateIfEmpty===!0,sessionCount:p.length,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-o),serverTiming:typeof S.headers?.get=="function"&&S.headers.get("server-timing")||null}),p.length===0&&a?.autoCreateIfEmpty&&String(e.assetId||"").trim()){const C=a?.requestedSessionId??xe.current;if(xe.current=null,C&&f("The previously selected annotation session could not be restored."),Te.current!==c)return;const G=await Jt(e);if(tn("annotated_sessions_auto_created_after_empty_load",{assetId:e.assetId,taskId:e.taskId||null,sessionId:G.id,totalDurationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-o)}),Te.current!==c)return;Be([G]),Fe(G.id),Ne(!1),we(G,e);return}if(Te.current!==c)return;Be(p),Ne(p.length===0);const k=a?.requestedSessionId??xe.current;xe.current=null;const w=p.find(C=>C.id===k)||p[0]||null;k&&!w&&f("The previously selected annotation session could not be restored."),Fe(w?.id||null),w?we(w,e):(ve.current=!0,L(),rt(et(e)),ot(""),me([]),Z(null),Q(!1),F.current="",O.current="",z(null),B("saved"))}catch(m){if(Te.current!==c)return;f(m instanceof Error?m.message:"Failed to load sessions.")}finally{Vt.current===i&&(Vt.current=null),Te.current===c&&zn(!1)}},[L,Jt,j,$,we,g]),ha=s.useCallback(async()=>{Jn(!0),Qn(null);try{const e=new URLSearchParams;e.set("workspaceId",String(g||"default").trim()||"default");const a=await le(`/api/taskforce/annotated-attachments/images?${e.toString()}`,{credentials:"include",headers:j,cache:"no-store"},$),o=await a.json().catch(()=>({}));if(!a.ok)throw new Error(String(o?.error||"Failed to load images."));Xa(Array.isArray(o?.images)?o.images:[])}catch(e){Qn(e instanceof Error?e.message:"Failed to load images.")}finally{Jn(!1)}},[j,$,g]),rs=s.useCallback(async()=>{if(typeof navigator>"u"||!navigator.clipboard||typeof navigator.clipboard.read!="function"){f("Clipboard image paste is not supported in this environment.");return}ea(!0),f(null),aa.current=Date.now()+2e3;try{const a=(await navigator.clipboard.read()).find(k=>k.types.some(w=>w.startsWith("image/"))),o=a?.types.find(k=>k.startsWith("image/"))||"";if(!a||!o)throw new Error("No image found on the clipboard.");const i=await a.getType(o),c=await ma(i);if(!c)throw new Error("Failed to read clipboard image.");const m=o==="image/jpeg"?"jpg":o==="image/webp"?"webp":o==="image/gif"?"gif":"png",S=await fetch("/api/taskforce/context-upload",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...j},body:JSON.stringify({file:c,originalName:`pasted-image.${m}`,workspaceId:String(g||"default").trim()||"default"})}),u=await S.json().catch(()=>({}));if(!S.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 p={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"};xe.current=null,ge?(he.current="",W?.(p,{sessionId:null})):($t(p),he.current=Re(p),V(p,{autoCreateIfEmpty:!0}))}catch(e){f(e instanceof Error?e.message:"Failed to paste image.")}finally{ea(!1)}},[ge,V,W,ma,j,g]),os=s.useCallback(async()=>{const e=bn.trim();if(!e){f("Enter an image reference to open.");return}Xn(!0),f(null);try{const a=new URLSearchParams({workspaceId:String(g||"default").trim()||"default"}),o=await le(`/api/taskforce/annotated-attachments/images/${encodeURIComponent(e)}?${a.toString()}`,{method:"GET",credentials:"include",headers:j}),i=await o.json().catch(()=>({}));if(!o.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};xe.current=null,Ht(!1),zt(""),ge?(he.current="",W?.(c,{sessionId:null})):($t(c),he.current=Re(c),V(c,{autoCreateIfEmpty:!0}))}catch(a){f(a instanceof Error?a.message:"Failed to open image reference.")}finally{Xn(!1)}},[ge,V,W,bn,j,g]),is=s.useCallback(async e=>{if(!e.assetId||!e.path||!await M("session-switch"))return;const o={assetId:e.assetId,path:e.path,displayName:String(e.displayName||e.originalFilename||"Image attachment").trim()||"Image attachment",...e.taskId?{taskId:e.taskId}:{},...e.taskReferenceLabel?{taskReferenceLabel:e.taskReferenceLabel}:{},...e.imageReferenceLabel?{imageReferenceLabel:e.imageReferenceLabel}:{}};xe.current=null,f(null),ge?(he.current="",W?.(o,{sessionId:null})):($t(o),he.current=Re(o),St(o),V(o,{autoCreateIfEmpty:!0}))},[M,ge,V,W,St]),Zt=s.useCallback(e=>{Be(a=>{const o=a.findIndex(c=>c.id===e.id);if(o===-1)return[e,...a];const i=[...a];return i[o]=e,i}),Fe(e.id),we(e,d)},[d,we]),pa=s.useCallback(e=>{Be(a=>{const o=a.filter(c=>c.id!==e),i=o[0]||null;return Fe(i?.id||null),i?we(i,d):(ve.current=!0,L(),rt(et(d||{displayName:"Annotated session"})),ot(""),me([]),Z(null),Q(!1),F.current="",O.current="",z(null),B("saved")),o})},[d,L,we]);s.useEffect(()=>{if(!_)return;if(ge||$t(a=>a&&Re(a)===re&&a.taskReferenceLabel===_.taskReferenceLabel&&a.imageReferenceLabel===_.imageReferenceLabel&&a.displayName===_.displayName?a:_),!v){re&&(re!==he.current||de!==Kt.current)&&re!==wn.current&&(St(_),wn.current=re,Kt.current=de,tn("annotated_sessions_load_deferred",{assetId:_.assetId,taskId:_.taskId||null,requestedTargetKey:re})),Me?.();return}re&&(re!==he.current||de!==Kt.current)&&(St(_),he.current=re,Kt.current=de,wn.current="",V(_,{autoCreateIfEmpty:!0})),Me?.()},[ge,V,Me,de,_,re,St,D,v]),s.useEffect(()=>{d&&Se?.({target:d,sessionId:y})},[d,Se,y]),s.useEffect(()=>{if(!d||typeof document>"u"||!v)return;const e=()=>{Date.now()<aa.current||O.current!==F.current||ee||Pt||V(d,{requestedSessionId:y})},a=()=>{document.visibilityState==="visible"&&e()};return document.addEventListener("visibilitychange",a),()=>{document.removeEventListener("visibilitychange",a)}},[d,V,Pt,ee,y,v]),s.useEffect(()=>{if(!d?.path){ct(!1),ut(!1),pt({width:0,height:0});return}ct(!0),ut(!1),pt({width:0,height:0}),mt(1),Ke.current=!0,ft(!1),ht(!1)},[d?.path]),s.useEffect(()=>{if(!q)return;const e=kn.current;!e||!e.complete||e.naturalWidth<=0||e.naturalHeight<=0||(pt({width:e.naturalWidth,height:e.naturalHeight}),ct(!1),ut(!1))},[d?.path,q]),s.useEffect(()=>{Je||(ft(!1),ht(!1))},[Je]),s.useEffect(()=>{if(!y||!K||q||dt||T.width<=0||T.height<=0||sa.current===K)return;if(sa.current=K,!_t){It();return}Ke.current=!1,Ge.current=!0;const e=Mn(_t.zoomLevel);mt(e),window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>{const a=ne.current;a&&(a.scrollLeft=Math.max(0,_t.scrollLeft),a.scrollTop=Math.max(0,_t.scrollTop)),Ge.current=!1})})},[K,dt,q,T.height,T.width,It,_t,y]),s.useEffect(()=>{const e=ne.current;if(!e||T.width<=0||T.height<=0)return;const a=new ResizeObserver(()=>{Ke.current&&It()});return a.observe(e),()=>a.disconnect()},[It,T.height,T.width]),s.useEffect(()=>{dn(null)},[y]),s.useEffect(()=>{if(O.current=qe,ve.current){ve.current=!1;return}if(!y){L(),z(null),B("saved");return}if(qe===F.current){L(),ae.current||(z(null),B("saved"));return}const e=In.current;if(In.current=null,Y==="error"&&e===null)return;const a=e??600;if(ae.current){Ue.current=!0,B("pending");return}fa(a)},[L,qe,Y,fa,y]),s.useEffect(()=>{y&&(ae.current||qe===F.current&&Y!=="error"&&Y!=="saved"&&(z(null),B("saved")))},[qe,Y,y]),s.useEffect(()=>{!wt||!ue||ha()},[ha,ue,wt]),s.useEffect(()=>{if(typeof window>"u")return;const e=a=>{O.current!==F.current&&(a.preventDefault(),a.returnValue="")};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[]),s.useEffect(()=>{if(typeof document>"u")return;const e=()=>{document.visibilityState==="hidden"&&M("visibility-hidden")};return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[M]),s.useEffect(()=>{if(!At||typeof document>"u")return;const e=a=>{const o=a.target;o instanceof Node&&(oa.current?.contains(o)||Et(!1))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[At]),s.useEffect(()=>{if(!ln||typeof document>"u")return;const e=a=>{const o=a.target;o instanceof Node&&(ia.current?.contains(o)||st(!1))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[ln]),s.useEffect(()=>()=>{L()},[L]),s.useEffect(()=>{if(!be)return;const e=window.setTimeout(()=>un(!1),2e3);return()=>window.clearTimeout(e)},[be]),s.useEffect(()=>{if(!Dt)return;const e=window.setTimeout(()=>gn(!1),2e3);return()=>window.clearTimeout(e)},[Dt]),s.useEffect(()=>{if(!Ot)return;const e=window.setTimeout(()=>yn(!1),2e3);return()=>window.clearTimeout(e)},[Ot]);const ie=s.useCallback((e,a,o=300)=>{me(i=>Ae(i.map(c=>c.id===e?a(c):c))),J(o)},[J]),ls=s.useCallback(e=>{pe&&(ie(pe.id,a=>({...a,color:e})),Hn(e),Et(!1))},[pe,ie]),ga=s.useCallback(async()=>{if(!(!d||!await M("session-switch"))){te(!0),f(null);try{const a=await Jt(d);Ne(!1),await V(d,{requestedSessionId:a.id,autoCreateIfEmpty:!1}),He("select")}catch(a){f(a instanceof Error?a.message:"Failed to create session."),Ne(!0)}finally{te(!1)}}},[d,Jt,M,V]),cs=s.useCallback(e=>{if(e!=="select"&&!b){ft(!1),f("No session exists for this image yet."),Ne(!0);return}f(null),Ne(!1),ft(!1),He(e)},[b]),ds=s.useCallback(async()=>{if(!(!d||!b||!await M("duplicate"))){te(!0),f(null);try{const a=Ae(R.map((m,S)=>sl(m,S))),o=await le(`/api/taskforce/annotated-attachments/sessions?${U}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...j},body:JSON.stringify({taskId:d.taskId,baseImageAssetId:d.assetId,title:rl(De||b.title,d),globalInstruction:Oe,annotations:a})},$),i=await o.json().catch(()=>({}));if(!o.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.");Zt(c),He("select")}catch(a){f(a instanceof Error?a.message:"Failed to duplicate session.")}finally{te(!1)}}},[d,R,Oe,De,Zt,M,j,$,b,U]),us=s.useCallback(async()=>M("manual"),[M]),ya=s.useCallback(async()=>{if(y){Gn(!0),f(null);try{const e=await le(`/api/taskforce/annotated-attachments/sessions/${encodeURIComponent(y)}/payload?${U}`,{credentials:"include",headers:j},$),a=await e.json().catch(()=>({}));if(!e.ok)throw new Error(String(a?.error||"Failed to load payload preview."));dn(a?.payload||null)}catch(e){f(e instanceof Error?e.message:"Failed to load payload preview.")}finally{Gn(!1)}}},[j,$,y,U]),ms=s.useCallback(()=>{y&&M("payload-preview").then(e=>{e&&(mn(!0),ya())})},[M,ya,y]),ba=s.useCallback(async e=>{if(!fe||!navigator.clipboard||typeof navigator.clipboard.writeText!="function"){f("Clipboard copy is not available in this browser.");return}try{const a=e==="json"?JSON.stringify(fe,null,2):Ea(fe);await navigator.clipboard.writeText(a),un(e)}catch(a){f(a instanceof Error?a.message:"Failed to copy payload content."),un(!1)}},[fe]),fs=s.useCallback(async()=>{if(!qt||!navigator.clipboard||typeof navigator.clipboard.writeText!="function"){f("Clipboard copy is not available in this browser.");return}try{await navigator.clipboard.writeText(qt),gn(!0)}catch(e){f(e instanceof Error?e.message:"Failed to copy task id."),gn(!1)}},[qt]),hs=s.useCallback(async()=>{if(!(!b||Ft)){Bt(!0),Vn(""),Wn(!0),f(null);try{const e=await le(`/api/taskforce/tasks?${U}`,{credentials:"include",headers:j},$),a=await e.json().catch(()=>({}));if(!e.ok)throw new Error(String(a?.error||"Failed to load tasks."));Wa(Array.isArray(a?.tasks)?a.tasks:[])}catch(e){f(e instanceof Error?e.message:"Failed to load tasks.")}finally{Wn(!1)}}},[j,$,b,Ft,U]),Rn=s.useCallback(async e=>{const a=_e.current;if(!(!a||Sn.current)){Sn.current=!0,Yn(!0);try{if(!await M("task-link"))return;f(null);const i=await le(`/api/taskforce/annotated-attachments/sessions/${encodeURIComponent(a)}?${U}`,{method:"PATCH",credentials:"include",headers:{"Content-Type":"application/json",...j},body:JSON.stringify({taskId:e||""})},$),c=await i.json().catch(()=>({}));if(!i.ok)throw new Error(String(c?.error||"Failed to update session task."));const m=c?.session;if(!m?.id)throw new Error("Failed to update session task.");Zt(m),Bt(!1)}catch(o){f(o instanceof Error?o.message:"Failed to update session task.")}finally{Sn.current=!1,Yn(!1)}}},[Zt,M,j,$,U]),ps=s.useCallback(async()=>{if(!kt||!navigator.clipboard||typeof navigator.clipboard.writeText!="function"){f("Clipboard copy is not available in this browser.");return}try{await navigator.clipboard.writeText(kt),yn(!0)}catch(e){f(e instanceof Error?e.message:"Failed to copy image reference."),yn(!1)}},[kt]),gs=s.useCallback(async()=>{if(!y||!await M("delete-session"))return;const a=(b?.title||"Untitled session").trim()||"Untitled session";if(window.confirm(`Delete the annotated attachment session "${a}"?`)){te(!0),f(null);try{const o=await le(`/api/taskforce/annotated-attachments/sessions/${encodeURIComponent(y)}?${U}`,{method:"DELETE",credentials:"include",headers:j},$),i=await o.json().catch(()=>({}));if(!o.ok)throw new Error(String(i?.error||"Failed to delete session."));pa(y),He("select")}catch(o){f(o instanceof Error?o.message:"Failed to delete session.")}finally{te(!1)}}},[M,pa,j,$,b,y,U]),xa=s.useCallback(()=>{A&&(me(e=>Ae(e.filter(a=>a.id!==A))),Z(null),Q(!1),J(300))},[J,A]),An=s.useCallback(()=>{A&&window.confirm("Delete this marker? This cannot be undone.")&&xa()},[xa,A]),Ct=s.useCallback(e=>{Z(e),Q(!1),window.requestAnimationFrame(()=>{Nn.current.get(e)?.scrollIntoView?.({block:"nearest",behavior:"smooth"})})},[]),ys=s.useCallback(e=>{if(A===e&&!it){Q(!0);return}Ct(e)},[it,Ct,A]),Qe=s.useCallback(e=>{Ke.current=!1;const a=Mn(e),o=ne.current;if(!o||a===P){mt(a),window.requestAnimationFrame(()=>oe(a));return}const i=(o.scrollLeft+o.clientWidth/2)*(a/P)-o.clientWidth/2,c=(o.scrollTop+o.clientHeight/2)*(a/P)-o.clientHeight/2;mt(a),window.requestAnimationFrame(()=>{o.scrollLeft=Math.max(0,i),o.scrollTop=Math.max(0,c),oe(a)})},[oe,P]),bs=s.useCallback(()=>{Qe(P+.25)},[Qe,P]),xs=s.useCallback(()=>{Qe(P-.25)},[Qe,P]),vs=s.useCallback(()=>{Qe(1);const e=ne.current;e&&window.requestAnimationFrame(()=>{e.scrollLeft=0,e.scrollTop=0,oe(1)})},[Qe,oe]),va=s.useCallback((e,a)=>{e!==a&&me(o=>{const i=o.findIndex(m=>m.id===e),c=o.findIndex(m=>m.id===a);return i===-1||c===-1?o:(J(300),ol(o,i,c))})},[J]),_s=s.useCallback(e=>{cn(String(e.active.id))},[]),ks=s.useCallback(e=>{const a=String(e.active.id),o=e.over?String(e.over.id):null;o&&a!==o&&va(a,o),cn(null)},[va]);s.useEffect(()=>{if(!A)return;const e=a=>{a.key!=="Delete"&&a.key!=="Backspace"||za(a.target)||(a.preventDefault(),An())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[An,A]),s.useEffect(()=>{const e=i=>{i.code==="Space"&&Je&&(Zi(i.target)||(i.preventDefault(),ht(!0)))},a=i=>{i.code==="Space"&&ht(!1)},o=()=>{ht(!1)};return window.addEventListener("keydown",e),window.addEventListener("keyup",a),window.addEventListener("blur",o),()=>{window.removeEventListener("keydown",e),window.removeEventListener("keyup",a),window.removeEventListener("blur",o)}},[Je]);const H=s.useCallback(e=>{const a=ta.current?.getBoundingClientRect();return!a||a.width<=0||a.height<=0?null:{x:I((e.clientX-a.left)/a.width),y:I((e.clientY-a.top)/a.height)}},[]),ws=s.useCallback(e=>{if(X){const i=ne.current;if(!i)return;se.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(!y)return;if(E==="select"){Z(null),Q(!1);return}const a=H(e);if(!a)return;if(E==="pin"||E==="text-note"){const i=Aa(E,a,a,Rt);me(c=>Ae([...c,i])),Z(i.id),Q(!1),J(300),He("select");return}je.current=a;const o=Aa(E,a,a,Rt);ke.current={annotationId:o.id,kind:E},e.currentTarget.setPointerCapture?.(e.pointerId),me(i=>Ae([...i,o])),Z(o.id),Q(!1),J(300)},[Rt,X,J,H,y,E]),Is=s.useCallback(e=>{if(se.current?.pointerId===e.pointerId){e.currentTarget.releasePointerCapture?.(e.pointerId);return}if(!je.current||!ke.current||E!=="box"&&E!=="arrow")return;const a=H(e);je.current=null,ke.current=null,e.currentTarget.releasePointerCapture?.(e.pointerId),a&&He("select")},[H,E]),_a=s.useCallback((e,a)=>{if(E!=="select"||X)return;const o=H(e);o&&(Ve.current={annotationId:a.id,originPointer:o,originAnnotation:a},Z(a.id),e.stopPropagation())},[X,H,E]),Ss=s.useCallback(e=>{if(se.current?.pointerId===e.pointerId){const u=ne.current;if(!u)return;const p=e.clientX-se.current.startX,k=e.clientY-se.current.startY;u.scrollLeft=se.current.scrollLeft-p,u.scrollTop=se.current.scrollTop-k;return}if(ke.current&&je.current){const u=H(e);if(!u)return;const{annotationId:p,kind:k}=ke.current,w=je.current;ie(p,C=>k==="box"&&C.kind==="box"?{...C,x:I(Math.min(w.x,u.x)),y:I(Math.min(w.y,u.y)),width:Ee(Math.abs(u.x-w.x)),height:Ee(Math.abs(u.y-w.y))}:k==="arrow"&&C.kind==="arrow"?{...C,x:w.x,y:w.y,x2:u.x,y2:u.y}:C);return}if(We.current){const u=H(e);if(!u)return;const{annotationId:p,originPointer:k,originAnnotation:w}=We.current,C=u.x-k.x,G=u.y-k.y;ie(p,()=>({...w,width:Ee(w.width+C),height:Ee(w.height+G)}));return}if(Ye.current){const u=H(e);if(!u)return;const{annotationId:p,endpoint:k,originPointer:w,originAnnotation:C}=Ye.current,G=u.x-w.x,Le=u.y-w.y;ie(p,()=>k==="tail"?{...C,x:I(C.x+G),y:I(C.y+Le)}:{...C,x2:I(C.x2+G),y2:I(C.y2+Le)});return}if(!Ve.current)return;const a=H(e);if(!a)return;const{annotationId:o,originPointer:i,originAnnotation:c}=Ve.current,m=a.x-i.x,S=a.y-i.y;ie(o,()=>c.kind==="pin"||c.kind==="text-note"?{...c,x:I(c.x+m),y:I(c.y+S)}:c.kind==="box"?{...c,x:I(c.x+m),y:I(c.y+S)}:{...c,x:I(c.x+m),y:I(c.y+S),x2:I(c.x2+m),y2:I(c.y2+S)})},[H,ie]),Cs=s.useCallback(()=>{je.current=null,Ve.current=null,We.current=null,Ye.current=null,ke.current=null,se.current=null},[]),Ns=s.useCallback(()=>{je.current=null,Ve.current=null,We.current=null,Ye.current=null,ke.current=null,se.current=null},[]),Ts=s.useCallback(()=>{Ve.current=null,We.current=null,Ye.current=null,ke.current=null,se.current=null},[]),js=s.useCallback((e,a)=>{if(E!=="select"||X)return;const o=H(e);o&&(We.current={annotationId:a.id,originPointer:o,originAnnotation:a},e.stopPropagation())},[X,H,E]),ka=s.useCallback((e,a,o)=>{if(E!=="select"||X)return;const i=H(e);i&&(Ye.current={annotationId:a.id,originPointer:i,originAnnotation:a,endpoint:o},e.stopPropagation())},[X,H,E]),$s=b?.updatedAt?Pn(b.updatedAt):"Not saved yet";return t.jsxs("div",{className:`${n.shell} ${wt?n.shellWithImageTray:""} ${wt&&ue?n.shellImageTrayOpen:""}`.trim(),children:[wt?t.jsxs("aside",{className:`${n.imageTrayPanel} ${ue?n.imageTrayPanelOpen:""}`.trim(),"aria-label":"Image tray","aria-hidden":!ue,children:[t.jsxs("div",{className:n.imageTrayHeader,children:[t.jsxs("span",{className:n.imageTrayTitle,children:[t.jsx(Sa,{size:14}),"Images"]}),t.jsx("button",{type:"button",className:"tf-control-icon",onClick:jt,title:"Collapse image tray","aria-label":"Collapse image tray",children:t.jsx(Ws,{size:16})})]}),t.jsxs("div",{className:n.imageTraySearch,children:[t.jsx(Ys,{size:12,className:n.imageTraySearchIcon}),t.jsx("input",{type:"text",placeholder:"Search images...",value:Ut,onChange:e=>Ja(e.target.value),className:n.imageTraySearchInput})]}),t.jsx("div",{className:n.imageTraySortControlRow,children:t.jsx(Vs,{field:vn,order:_n,onFieldChange:Za,onOrderChange:Qa})}),t.jsx("div",{className:`tf-scrollbar tf-tray-scroll-viewport ${n.imageTrayList}`,children:es?t.jsx("div",{className:n.imageTrayState,children:"Loading images..."}):Zn?t.jsx("div",{className:n.imageTrayStateError,children:Zn}):ua.length===0?t.jsx("div",{className:n.imageTrayState,children:Ut.trim()?"No images match your search.":"No images found."}):ua.map(e=>{const a=d?.assetId===e.assetId,o=typeof e.attachmentCount=="number"&&Number.isFinite(e.attachmentCount)?Math.max(0,e.attachmentCount):0,i=typeof e.sessionCount=="number"&&Number.isFinite(e.sessionCount)?Math.max(0,e.sessionCount):0,c=o>1?`${o} tasks linked`:o===1?e.taskReferenceLabel||"1 task linked":"Unattached",m=String(e.displayName||e.originalFilename||"Image attachment").trim()||"Image attachment";return t.jsxs("button",{type:"button",className:`${n.imageTrayItem} ${a?n.imageTrayItemActive:""}`.trim(),onClick:()=>{is(e)},title:m,children:[t.jsx("span",{className:n.imageTrayThumb,children:t.jsx("img",{src:e.path,alt:"",loading:"lazy"})}),t.jsxs("span",{className:n.imageTrayItemBody,children:[t.jsx("span",{className:n.imageTrayItemTitle,children:m}),t.jsx("span",{className:n.imageTrayItemTask,children:c}),t.jsxs("span",{className:n.imageTrayItemMeta,children:[t.jsxs("span",{className:n.imageTrayItemMetaDetails,children:[Qi(e.sizeBytes),e.updatedAt?t.jsxs(t.Fragment,{children:[" · ",el(e.updatedAt)]}):null,i>0?t.jsxs(t.Fragment,{children:[" · ",i," session",i===1?"":"s"]}):null]}),e.imageReferenceLabel?t.jsx("span",{className:n.imageTrayItemReference,children:e.imageReferenceLabel}):null]})]})]},e.assetId)})})]}):null,t.jsxs("section",{className:`tf-surface-panel ${n.panel} ${n.sessionPanel}`,children:[t.jsx("div",{className:n.sessionContextBar,children:b?.taskId?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:n.sessionContextLeft,children:at?t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${n.ghostBtn} ${n.backToTaskBtn}`,onClick:()=>{M("back-to-task").then(e=>{e&&b.taskId&&at(b.taskId)})},"aria-label":"Back to task",title:"Back to task",children:t.jsx(qs,{size:16})}):t.jsx("div",{className:n.sessionContextSpacer,"aria-hidden":"true"})}),t.jsxs("div",{className:n.sessionContextRight,children:[t.jsx(Gs,{copied:Dt,onClick:()=>{fs()},title:"Copy task id",ariaLabel:Dt?"Copied task id":"Copy task id",label:qt}),t.jsx("button",{type:"button",className:`tf-control-icon ${n.iconButton}`,onClick:()=>{Rn(null)},disabled:ze,"aria-label":"Unlink session from task",title:"Unlink session from task",children:t.jsx(Xs,{size:16})})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:n.sessionContextLeft,children:t.jsx("span",{className:`tf-label-micro ${n.sessionContextLabel}`,children:"Unattached session"})}),t.jsx("div",{className:n.sessionContextRight,children:t.jsx("div",{className:n.sessionContextSpacer,"aria-hidden":"true"})})]})}),t.jsxs("div",{className:n.panelHeader,children:[t.jsxs("div",{className:n.panelHeaderText,children:[t.jsx("div",{className:`tf-heading-card ${n.panelTitle}`,children:"Sessions"}),d?null:t.jsx("div",{className:"tf-text-secondary",children:"Open an image attachment to begin"})]}),t.jsxs("div",{className:n.sessionActions,children:[t.jsx("button",{type:"button",className:`tf-control-icon ${n.iconButton}`,onClick:()=>{hs()},disabled:!b||Ft||ze,"aria-label":b?.taskId?"Change linked task":"Link session to task",title:b?.taskId?"Change linked task":"Link session to task",children:t.jsx(Js,{size:16})}),t.jsx("button",{type:"button",className:`tf-control-icon ${n.iconButton}`,onClick:()=>{ga()},disabled:!d||ee,"aria-label":"Create session",title:"Create session",children:t.jsx(Zs,{size:16})})]})]}),d?Pt?t.jsx("div",{className:n.emptyState,children:t.jsx("p",{className:"tf-empty-copy",children:"Loading sessions…"})}):t.jsx("div",{className:`tf-scrollbar ${n.sessionList}`,children:Lt.length===0?t.jsxs("div",{className:n.sessionEmptyState,children:[t.jsx("div",{className:`tf-heading-card ${n.sessionTitle}`,children:"No sessions yet"}),t.jsx("div",{className:`tf-text-secondary ${n.annotationSummary}`,children:"Create the first annotation session for this image."})]}):Lt.map(e=>{const a=y===e.id,o=a&&ln,i=tl(a?Oe:e.globalInstruction),c=(a?De:e.title)||"Untitled session";return t.jsxs("div",{className:`tf-surface-elevated ${n.sessionCard} ${a?n.sessionCardActive:""}`,ref:a?ia:void 0,onBlur:o?m=>{const S=m.relatedTarget;S instanceof Node&&m.currentTarget.contains(S)||st(!1)}:void 0,children:[o?t.jsxs("div",{className:n.sessionCardBody,children:[t.jsxs("div",{className:n.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 ${n.textInput} ${n.sessionTitleInput}`,value:De,onChange:m=>{rt(m.target.value),J(600)},placeholder:"Session title"}),t.jsx("span",{className:`tf-text-meta ${n.sessionTimestamp}`,children:Pn(e.updatedAt)})]}),sn(e)?t.jsxs("div",{className:`tf-text-secondary ${n.sessionCreator}`,children:["Created by ",sn(e)]}):null,t.jsxs("div",{className:n.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 ${n.textArea} ${n.sessionInstructionField}`,value:Oe,onChange:m=>{ot(m.target.value),J(600)},placeholder:"Add overall instructions, context, or framing for this session."})]}),t.jsxs("div",{className:`tf-text-secondary ${n.annotationSummary}`,children:[e.annotations.length," annotation",e.annotations.length===1?"":"s"]})]}):t.jsxs("button",{type:"button",className:n.sessionCardButton,onClick:()=>{if(a){st(!0);return}M("session-switch").then(m=>{m&&(Fe(e.id),we(e,d))})},"aria-pressed":a,children:[t.jsxs("div",{className:n.sessionMeta,children:[t.jsx("span",{className:`tf-heading-card ${n.sessionTitle}`,children:c}),t.jsx("span",{className:`tf-text-meta ${n.sessionTimestamp}`,children:Pn(e.updatedAt)})]}),sn(e)?t.jsxs("div",{className:`tf-text-secondary ${n.sessionCreator}`,children:["Created by ",sn(e)]}):null,i?t.jsx("div",{className:`tf-text-secondary ${n.sessionInstructionPreview}`,children:i}):null,t.jsxs("div",{className:`tf-text-secondary ${n.annotationSummary}`,children:[e.annotations.length," annotation",e.annotations.length===1?"":"s"]})]}),a?t.jsx("div",{className:n.sessionCardFooter,children:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:`tf-button-ghost ${n.toolRailButton} ${n.iconButton}`,onClick:()=>{ds()},disabled:ee,"aria-label":"Duplicate session",title:`Duplicate session "${c}"`,children:t.jsx(En,{size:16})}),t.jsx("button",{type:"button",className:`tf-button-ghost ${n.toolRailButton} ${n.iconButton}`,onClick:()=>{gs()},disabled:ee,"aria-label":"Delete session",title:`Delete session "${c}"`,children:t.jsx(Ca,{size:16})})]})}):null]},e.id)})}):t.jsxs("div",{className:n.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 ${n.panel} ${n.canvasPanel}`,children:[t.jsxs("div",{className:n.panelHeader,children:[t.jsxs("div",{className:n.canvasHeading,children:[t.jsx("div",{className:"tf-heading-card",children:d?.displayName||"Annotated attachment"}),t.jsx("div",{className:"tf-text-secondary",children:b?`${R.length} markers · ${$s}`:"Pick or create a session"})]}),kt?t.jsx(ir,{copied:Ot,onClick:()=>{ps()},title:d?.displayName||"Annotated attachment",ariaLabel:Ot?"Copied image reference":"Copy image reference",label:kt}):null]}),t.jsxs("div",{className:n.toolRail,children:[t.jsxs("div",{className:`${n.toolbarCluster} ${n.toolbarViewportCluster}`,children:[t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${n.ghostBtn} ${n.toolbarButton}`,onClick:()=>{us()},disabled:!b||ee||!da&&Y!=="error","aria-label":ee?"Saving session":"Save session",title:ee?"Saving session":"Save session",children:t.jsx(Qs,{size:18})}),t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${n.ghostBtn} ${n.toolbarButton}`,onClick:()=>Ht(!0),disabled:lt,"aria-label":"Open image",title:"Open image",children:t.jsx(Sa,{size:18})}),t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${n.ghostBtn} ${n.toolbarButton}`,onClick:()=>{rs()},disabled:Gt,"aria-label":Gt?"Pasting image":"Paste image",title:Gt?"Pasting image":"Paste image",children:Gt?t.jsx(Na,{size:18,className:Ia.spin}):t.jsx(er,{size:18})}),t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${n.ghostBtn} ${n.toolbarButton}`,onClick:()=>{b&&ss()},disabled:!b||!da,"aria-label":"Reset unsaved changes",title:"Reset unsaved changes",children:t.jsx(tr,{size:18})}),t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${n.ghostBtn} ${n.toolbarButton}`,onClick:It,disabled:!d||q||T.width<=0||T.height<=0,"aria-label":"Fit image to viewport",title:"Fit image to viewport",children:t.jsx(nr,{size:18})}),t.jsx("button",{type:"button",className:`tf-button-ghost ${n.toolRailButton} ${n.iconButton}`,onClick:xs,disabled:!d||q||P<=.25,"aria-label":"Zoom out",children:t.jsx(ar,{size:18})}),t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${n.ghostBtn} ${n.toolbarButton}`,onClick:vs,disabled:!d||q||P===1,"aria-label":`Reset zoom to 100 percent (currently ${$n})`,title:`Reset zoom to 100% (currently ${$n})`,children:t.jsx("span",{children:$n})}),t.jsx("button",{type:"button",className:`tf-button-ghost ${n.toolRailButton} ${n.iconButton}`,onClick:bs,disabled:!d||q||P>=4,"aria-label":"Zoom in",children:t.jsx(sr,{size:18})}),t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${n.toolBtn} ${n.toolbarButton} ${X?n.toolBtnActive:""}`,onClick:()=>ft(e=>!e),disabled:!d||q||!Je,"aria-label":"Pan canvas",title:"Pan canvas",children:t.jsx(rr,{size:18})})]}),t.jsx("span",{className:n.toolbarSeparator,"aria-hidden":"true"}),t.jsxs("div",{className:n.toolbarActions,children:[t.jsx("div",{className:n.toolbarSelectionActions,children:pe?t.jsxs(t.Fragment,{children:[t.jsxs("div",{ref:oa,className:n.toolbarColorPicker,children:[t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${n.ghostBtn} ${n.toolbarButton} ${n.colorPickerButton}`,onClick:()=>Et(e=>!e),"aria-label":"Marker color","aria-expanded":At,title:"Marker color",children:t.jsx("span",{className:n.colorPickerSwatch,style:{backgroundColor:Tn},"aria-hidden":"true"})}),At?t.jsx("div",{className:n.colorPickerPopover,role:"menu","aria-label":"Marker color options",children:Ji.map(e=>t.jsx("button",{type:"button",className:`${n.colorOption} ${Tn===e?n.colorOptionActive:""}`,style:{backgroundColor:e},onClick:()=>ls(e),"aria-label":`Use marker color ${e}`,"aria-pressed":Tn===e},e))}):null]}),t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${n.ghostBtn} ${n.toolbarButton}`,onClick:An,"aria-label":"Delete marker",title:"Delete selected marker",children:t.jsx(Ca,{size:18})})]}):null}),t.jsxs("div",{className:n.toolbarUtilities,children:[t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${n.ghostBtn} ${n.payloadBtn} ${n.toolbarButton}`,onClick:ms,disabled:!b||Mt,"aria-label":Mt?"Loading payload preview":"Preview payload",title:Mt?"Loading payload preview":"Preview payload",children:t.jsx(Bn,{size:18})}),t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${n.ghostBtn} ${n.toolbarButton}`,onClick:()=>qn(!0),"aria-label":"How to use marker tools",title:"How to use marker tools",children:t.jsx(Fn,{size:18})})]})]})]}),t.jsxs("div",{className:n.canvasWorkspace,children:[t.jsx("div",{className:n.canvasToolRail,"aria-label":"Annotation tools",children:$a.map(e=>{const a=e.icon;return t.jsx("button",{type:"button",className:`tf-button-ghost ${n.toolRailButton} ${E===e.value?n.toolBtnActive:""}`,onClick:()=>cs(e.value),disabled:!d,title:e.label,"aria-label":`${e.label} tool. ${an[e.value].short}`,children:t.jsx(a,{size:18})},e.value)})}),t.jsx("div",{className:n.canvasMain,children:t.jsx("div",{ref:ne,className:`tf-scrollbar ${n.canvasScroller}`,onScroll:()=>{Ge.current||(Ke.current=!1),oe()},children:d?t.jsxs(t.Fragment,{children:[q&&!dt?t.jsx("div",{className:n.canvasStatusOverlay,"aria-live":"polite",children:t.jsxs("div",{className:n.canvasStatusCard,children:[t.jsx(Na,{size:20,className:Ia.spinner}),t.jsx("span",{children:"Loading image…"})]})}):null,dt?t.jsx("div",{className:n.canvasStatusOverlay,"aria-live":"polite",children:t.jsx("div",{className:n.canvasStatusCard,children:t.jsx("span",{children:"Image failed to load."})})}):null,t.jsx("div",{className:n.canvasFrame,children:t.jsxs("div",{className:n.canvasMedia,style:{width:x.width?`${x.width}px`:void 0,height:x.height?`${x.height}px`:void 0},children:[t.jsx("img",{ref:kn,src:d.path,alt:d.displayName,className:n.canvasImage,onLoad:()=>{const e=kn.current;pt({width:e?.naturalWidth||0,height:e?.naturalHeight||0}),ct(!1),ut(!1)},onError:()=>{pt({width:0,height:0}),ct(!1),ut(!0)}}),!q&&!dt&&b?t.jsxs("div",{ref:ta,className:`${n.overlay} ${E==="select"?n.overlaySelect:""} ${X?n.overlayPan:""}`,onPointerDown:ws,onPointerMove:Ss,onPointerUp:e=>{Is(e),Ts()},"data-testid":"annotated-attachment-overlay",onPointerLeave:Cs,onPointerCancel:Ns,children:[t.jsx("svg",{className:n.overlaySvg,viewBox:jn,preserveAspectRatio:"none","aria-hidden":"true",children:R.filter(e=>e.kind==="arrow").map(e=>{const a=nl(e,x),o=rn(e),i=A===e.id;return t.jsxs(en.Fragment,{children:[i?t.jsxs(t.Fragment,{children:[t.jsx("line",{x1:a.shaftX1,y1:a.shaftY1,x2:a.shaftX2,y2:a.shaftY2,stroke:"color-mix(in srgb, var(--surface-elevated) 92%, transparent)",strokeWidth:14,strokeLinecap:"round"}),t.jsx("polygon",{points:a.headPoints,fill:o,stroke:"color-mix(in srgb, var(--surface-elevated) 92%, transparent)",strokeWidth:4,strokeLinejoin:"round"})]}):null,t.jsx("line",{x1:a.shaftX1,y1:a.shaftY1,x2:a.shaftX2,y2:a.shaftY2,stroke:o,strokeWidth:i?10:6,strokeLinecap:"round"}),t.jsx("polygon",{points:a.headPoints,fill:o})]},e.id)})}),t.jsx("svg",{className:n.overlayHitLayer,viewBox:jn,preserveAspectRatio:"none",children:R.filter(e=>e.kind==="arrow").map(e=>t.jsxs(en.Fragment,{children:[t.jsx("line",{x1:e.x*x.width,y1:e.y*x.height,x2:e.x2*x.width,y2:e.y2*x.height,className:n.arrowHitArea,"data-testid":`annotated-arrow-hit-${e.id}`,"aria-label":`Arrow marker ${Ln.get(e.id)||0}`,onPointerDown:a=>_a(a,e),onClick:a=>{a.stopPropagation(),Ct(e.id)}}),A===e.id?t.jsxs(t.Fragment,{children:[t.jsx("circle",{cx:e.x*x.width,cy:e.y*x.height,r:Xe.hitRadius,className:n.canvasHandleHit,role:"button",tabIndex:0,"aria-label":"Move arrow tail",onPointerDown:a=>ka(a,e,"tail")}),t.jsx("circle",{cx:e.x*x.width,cy:e.y*x.height,r:Xe.visibleRadius,className:n.canvasHandleVisible,"aria-hidden":"true"}),t.jsx("circle",{cx:e.x2*x.width,cy:e.y2*x.height,r:Xe.hitRadius,className:n.canvasHandleHit,role:"button",tabIndex:0,"aria-label":"Move arrow tip",onPointerDown:a=>ka(a,e,"tip")}),t.jsx("circle",{cx:e.x2*x.width,cy:e.y2*x.height,r:Xe.visibleRadius,className:n.canvasHandleVisible,"aria-hidden":"true"})]}):null]},`hit-${e.id}`))}),R.filter(e=>e.kind==="arrow").map(e=>t.jsx("div",{className:`${n.annotationNumberBadge} ${n.arrowNumberBadge}`,style:{left:`${(e.x+e.x2)/2*100}%`,top:`${(e.y+e.y2)/2*100}%`,backgroundColor:rn(e)},"aria-hidden":"true",children:Ln.get(e.id)||0},`arrow-number-${e.id}`)),R.filter(e=>e.kind!=="arrow").map(e=>{const a=rn(e),o=Ln.get(e.id)||0,i={onPointerDown:c=>_a(c,e),onClick:c=>{c.stopPropagation(),Ct(e.id)}};return e.kind==="pin"?t.jsx("button",{type:"button",...i,className:`${n.pin} ${A===e.id?n.selected:""}`,style:{left:`${e.x*100}%`,top:`${e.y*100}%`,backgroundColor:a},children:o},e.id):e.kind==="text-note"?t.jsx("button",{type:"button",...i,className:`${n.note} ${A===e.id?n.selected:""}`,style:{left:`${e.x*100}%`,top:`${e.y*100}%`,backgroundColor:a},children:o},e.id):t.jsxs("div",{className:`${n.box} ${A===e.id?n.selected:""}`,style:{left:`${e.x*100}%`,top:`${e.y*100}%`,width:`${e.width*100}%`,height:`${e.height*100}%`,borderColor:a},children:[t.jsx("span",{className:`${n.annotationNumberBadge} ${n.boxNumberBadge}`,style:{backgroundColor:a},"aria-hidden":"true",children:o}),t.jsx("button",{type:"button",...i,className:n.boxSurface,"aria-label":`Box marker ${o}`})]},e.id)}),t.jsx("svg",{className:n.overlaySvg,viewBox:jn,preserveAspectRatio:"none",children:R.filter(e=>e.kind==="box"&&A===e.id).map(e=>t.jsxs(en.Fragment,{children:[t.jsx("circle",{cx:(e.x+e.width)*x.width,cy:(e.y+e.height)*x.height,r:Xe.hitRadius,className:`${n.canvasHandleHit} ${n.canvasResizeHandleHit}`,role:"button",tabIndex:0,"aria-label":"Resize box marker",onPointerDown:a=>js(a,e)}),t.jsx("circle",{cx:(e.x+e.width)*x.width,cy:(e.y+e.height)*x.height,r:Xe.visibleRadius,className:n.canvasHandleVisible,"aria-hidden":"true"})]},`box-handle-${e.id}`))})]}):null]})})]}):t.jsx("div",{className:n.emptyState,children:t.jsx("p",{className:"tf-empty-copy",children:"Select an image attachment to annotate."})})})})]}),t.jsxs("div",{className:n.statusBar,children:[t.jsx("span",{children:Y==="error"?"Save failed. Retry now.":Y==="saving"||Y==="pending"?"Saving…":"Saved"}),Un?t.jsx("span",{children:Un}):t.jsx("span",{children:b?X?"Drag on the image to pan.":E==="select"?"Select a marker to edit it.":`Click on the image to place a ${E}.`:"Create a session to begin placing markers on this image."}),d&&!b&&Ga?t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${n.ghostBtn} ${n.toolbarButton}`,onClick:()=>{ga()},disabled:ee||Pt,children:ee?"Creating…":"Create one now"}):null]})]}),t.jsx("section",{className:`tf-surface-panel ${n.panel} ${n.detailPanel}`,children:b?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:n.panelHeader,children:t.jsxs("div",{className:n.panelHeaderText,children:[t.jsx("div",{className:`tf-heading-card ${n.panelTitle}`,children:"Markers"}),t.jsxs("div",{className:"tf-text-secondary",children:[R.length," in this session"]})]})}),t.jsxs(As,{sensors:as,collisionDetection:Es,onDragStart:_s,onDragEnd:ks,onDragCancel:()=>cn(null),children:[t.jsx("div",{className:`tf-scrollbar ${n.annotationList}`,children:R.length===0?t.jsx("div",{className:n.detailEmpty,children:t.jsx("p",{className:"tf-empty-copy",children:"Add a marker on the image to begin."})}):t.jsx(Ps,{items:R.map(e=>e.id),strategy:Ms,children:R.map((e,a)=>{const o=La[e.kind],i=Ra[e.kind],c=`${i} ${a+1}`,m=Xi[e.markerType||ye],S=ja.find(k=>k.value===(e.markerType||ye))?.label||"Review",u=A===e.id,p=u&&!it;return t.jsx(Yi,{id:e.id,children:({attributes:k,listeners:w,setNodeRef:C,transform:G,transition:Le,isDragging:Nt})=>t.jsxs("div",{className:`tf-surface-elevated ${n.annotationCard} ${u?n.annotationCardActive:""} ${Nt?n.annotationCardDragging:""}`,ref:N=>{C(N),N?Nn.current.set(e.id,N):Nn.current.delete(e.id)},style:{...u?{"--annotation-card-accent":rn(e)}:{},transform:Bs.Transform.toString(G),transition:Le},onBlur:N=>{N.currentTarget.contains(N.relatedTarget)||Q(!0)},children:[t.jsxs("div",{className:n.annotationMeta,children:[t.jsx("button",{type:"button",className:n.annotationDragHandle,"aria-label":`Reorder ${c}`,title:"Drag to reorder. Press Space, then use the arrow keys to reorder with the keyboard.",...k,...w,children:t.jsx(Ta,{size:16})}),t.jsx("button",{type:"button",className:n.annotationCardButton,onClick:()=>{ys(e.id)},"aria-label":i,"aria-expanded":p,children:t.jsx("span",{className:`tf-heading-card ${n.annotationTitle}`,children:c})}),t.jsx("span",{className:`tf-text-meta ${n.annotationKind}`,"aria-hidden":"true",children:t.jsx(o,{size:16})})]}),p?t.jsxs("div",{className:n.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?na:null,className:`tf-field-shell ${n.textArea} ${n.annotationInstructionField}`,value:e.instruction,onChange:N=>{ie(e.id,Ie=>({...Ie,instruction:N.target.value}),600)},onBlur:()=>{M("text")},placeholder:"What should the AI focus on for this marker?"}),t.jsxs("div",{className:n.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 ${n.select}`,value:e.markerType||ye,onChange:N=>{ie(e.id,Ie=>al(Ie,N.target.value))},children:ja.map(N=>t.jsx("option",{value:N.value,children:N.label},N.value))})]}),t.jsxs("details",{className:n.annotationGeometryDetails,children:[t.jsx("summary",{className:"tf-field-label",children:"Precise placement"}),t.jsx("div",{className:n.annotationGeometryFields,"aria-label":"Marker geometry percent controls",children:cl(e).map(N=>t.jsxs("label",{className:n.annotationGeometryField,children:[t.jsx("span",{className:`tf-text-meta ${n.annotationGeometryLabel}`,children:N.label}),t.jsx("input",{className:`tf-field-shell ${n.annotationGeometryInput}`,type:"number",min:0,max:100,step:.1,value:N.value,onChange:Ie=>{const Qt=il(Ie.target.value);Qt!==null&&ie(e.id,Ls=>ll(Ls,N.key,Qt))},"aria-label":`${N.label} percent`})]},N.key))})]})]}):t.jsx("button",{type:"button",className:n.annotationInstructionButton,onClick:()=>{Ct(e.id)},"aria-label":`Edit ${i} instruction`,children:t.jsxs("div",{className:n.annotationInstructionEditor,children:[e.instruction.trim()?t.jsx("div",{className:`tf-text-secondary ${n.annotationInstructionPreview}`,children:e.instruction.trim()}):null,t.jsx("div",{className:n.annotationPreviewFooter,children:t.jsx("span",{className:`tf-text-meta ${n.annotationInstructionTypeIcon}`,"aria-label":`Instruction type: ${S}`,title:S,children:t.jsx(m,{size:16})})})]})})]})},e.id)})})}),t.jsx(Fs,{children:vt?t.jsxs("div",{className:`tf-surface-elevated ${n.annotationCard} ${n.annotationDragOverlay}`,"data-testid":"annotation-drag-overlay",children:[t.jsxs("div",{className:n.annotationMeta,children:[t.jsx(Ta,{size:16,className:n.annotationDragOverlayGrip}),t.jsx("span",{className:`tf-heading-card ${n.annotationTitle} ${n.annotationDragOverlayTitle}`,children:Ra[vt.kind]}),t.jsx("span",{className:`tf-text-meta ${n.annotationKind}`,"aria-hidden":"true",children:en.createElement(La[vt.kind],{size:16})})]}),vt.instruction.trim()?t.jsx("div",{className:`tf-text-secondary ${n.annotationInstructionPreview}`,children:vt.instruction.trim()}):null]}):null})]})]}):t.jsxs("div",{className:n.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(nn,{isOpen:qa,onClose:()=>{lt||(Ht(!1),zt(""))},title:"Open Image",size:"sm",children:t.jsxs("form",{className:n.openImageModalBody,onSubmit:e=>{e.preventDefault(),os()},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 ${n.textInput} ${n.openImageField}`,value:bn,onChange:e=>zt(e.target.value),placeholder:"I-24",autoFocus:!0}),t.jsxs("div",{className:n.openImageActions,children:[t.jsx("button",{type:"button",className:"tf-button-ghost tf-button-compact",onClick:()=>{Ht(!1),zt("")},disabled:lt,children:"Cancel"}),t.jsx("button",{type:"submit",className:"tf-button-primary tf-button-compact",disabled:lt,children:lt?"Opening…":"Open"})]})]})}),t.jsx(nn,{isOpen:Ya,onClose:()=>qn(!1),title:"How To Use Markers",size:"md",children:t.jsx("div",{className:n.markerHelpModalBody,children:$a.filter(e=>e.value!=="select").map(e=>t.jsxs("div",{className:`tf-surface-inset ${n.markerHelpItem}`,children:[t.jsxs("div",{className:n.markerHelpHeader,children:[t.jsx("strong",{className:"tf-heading-card",children:e.label}),t.jsx("span",{className:"tf-text-meta",children:an[e.value].short})]}),t.jsx("p",{className:"tf-text-secondary",children:an[e.value].detail}),t.jsx("p",{className:`tf-text-body ${n.markerHelpExample}`,children:an[e.value].example})]},e.value))})}),t.jsx(nn,{isOpen:Va,onClose:()=>{ze||Bt(!1)},title:"Link Session to Task",size:"sm",children:t.jsxs("div",{className:n.taskLinkModalBody,children:[t.jsx("p",{className:"tf-text-secondary",children:"This links the review session only. The image stays unattached."}),t.jsx("input",{className:`tf-field-shell ${n.textInput}`,value:hn,onChange:e=>Vn(e.target.value),placeholder:"Search tasks...","aria-label":"Search tasks",autoFocus:!0}),Ft?t.jsx("div",{className:n.detailEmpty,children:t.jsx("p",{className:"tf-empty-copy",children:"Loading tasks…"})}):la.length===0?t.jsx("div",{className:n.detailEmpty,children:t.jsx("p",{className:"tf-empty-copy",children:"No tasks match your search."})}):t.jsx("div",{className:`tf-scrollbar ${n.taskLinkList}`,children:la.map(e=>{const a=String(e.referenceLabel||e.id).trim()||e.id,o=e.id===b?.taskId;return t.jsxs("button",{type:"button",className:`tf-surface-elevated ${n.taskLinkOption} ${o?n.taskLinkOptionActive:""}`,onClick:()=>{Rn(e.id)},disabled:ze||o,children:[t.jsx("span",{className:n.taskLinkOptionTitle,children:e.title}),t.jsxs("span",{className:"tf-text-meta",children:[a,o?" · Linked":""]})]},e.id)})}),t.jsxs("div",{className:n.taskLinkActions,children:[t.jsx("button",{type:"button",className:"tf-button-ghost tf-button-compact",onClick:()=>Bt(!1),disabled:ze,children:"Cancel"}),b?.taskId?t.jsx("button",{type:"button",className:"tf-button-ghost tf-button-compact",onClick:()=>{Rn(null)},disabled:ze,children:"Unlink"}):null]})]})}),t.jsx(nn,{isOpen:Ka,onClose:()=>mn(!1),title:"AI Payload",size:"lg",children:t.jsxs("div",{className:n.payloadModalBody,children:[t.jsxs("div",{className:n.payloadModalToolbar,children:[t.jsxs("div",{className:n.payloadViewToggle,children:[t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${n.toolBtn} ${fn==="json"?n.toolBtnActive:""}`,onClick:()=>Kn("json"),children:"JSON"}),t.jsx("button",{type:"button",className:`tf-button-ghost tf-button-compact ${n.toolBtn} ${fn==="brief"?n.toolBtnActive:""}`,onClick:()=>Kn("brief"),children:"AI Brief"})]}),t.jsxs("div",{className:n.payloadModalActions,children:[t.jsxs("button",{type:"button",className:`tf-button-ghost tf-button-compact ${n.ghostBtn}`,onClick:()=>{ba("json")},disabled:!fe,"aria-label":be==="json"?"Copied JSON":"Copy JSON",title:be==="json"?"Copied JSON":"Copy JSON",children:[be==="json"?t.jsx(Dn,{size:16}):t.jsx(En,{size:16}),t.jsx("span",{children:"JSON"})]}),t.jsxs("button",{type:"button",className:`tf-button-ghost tf-button-compact ${n.ghostBtn}`,onClick:()=>{ba("brief")},disabled:!fe,"aria-label":be==="brief"?"Copied AI Brief":"Copy AI Brief",title:be==="brief"?"Copied AI Brief":"Copy AI Brief",children:[be==="brief"?t.jsx(Dn,{size:16}):t.jsx(En,{size:16}),t.jsx("span",{children:"AI Brief"})]})]})]}),Mt?t.jsx("div",{className:n.detailEmpty,children:t.jsx("p",{className:"tf-empty-copy",children:"Loading payload…"})}):fe?t.jsx("pre",{className:`tf-surface-inset tf-scrollbar ${n.payloadModalPreview}`,children:fn==="json"?JSON.stringify(fe,null,2):Ea(fe)}):t.jsx("div",{className:n.detailEmpty,children:t.jsx("p",{className:"tf-empty-copy",children:"Load a payload preview to inspect the current session contract."})})]})})]})}export{vl as AnnotatedAttachmentWorkspaceShell};
@@ -0,0 +1 @@
1
+ import{R as _,j as o}from"./vendor-react-CKJs5o3c.js";import{i as k}from"./index-BUplSsv_.js";import{ah as v,a as I,A as N,v as x,u as w}from"./vendor-icons-BkFLXavV.js";const y=[{value:"updated",label:"Updated"},{value:"reference",label:"Reference"},{value:"name",label:"Name"},{value:"size",label:"Size"},{value:"created",label:"Created"}];function g(e){if(typeof e?.referenceNumber=="number"&&Number.isFinite(e.referenceNumber))return e.referenceNumber;const r=String(e?.referenceLabel||e?.imageReferenceLabel||"").match(/(\d+)/);return r?parseInt(r[1],10):0}function j(e){if(!e)return"";const t=e.displayName||e.title||e.originalFilename||e.fsPath||e.path||e.storageKey||"";return String(t).toLowerCase()}function A(e){return k(e).toLowerCase()}function m(e,t){return String(t(e)||"").toLowerCase()}function S(e){const t=e?.sizeBytes;return typeof t=="number"&&Number.isFinite(t)?t:0}function p(e,t){const r=e?.createdAt,u=e?.updatedAt,a=t?r||u:u||r;if(!a)return 0;const n=Date.parse(String(a));return Number.isNaN(n)?0:n}function C(e,t,r,u,a=j){let n=0;if(r==="reference"){const l=g(e),d=g(t);n=l-d,n===0&&(n=m(e,a).localeCompare(m(t,a)))}else r==="name"?n=m(e,a).localeCompare(m(t,a)):r==="size"?n=S(e)-S(t):r==="created"?n=p(e,!0)-p(t,!0):n=p(e,!1)-p(t,!1);return n!==0?u==="desc"?-n:n:(n=g(t)-g(e),n!==0?n:m(e,a).localeCompare(m(t,a)))}function D(e,t,r,u){return[...e].sort((a,n)=>C(a,n,t,r,u))}function q(e,t,r){return D(e,t,r,A)}const R="_root_7pmuk_1",O="_trigger_7pmuk_9",T="_directionToggle_7pmuk_10",z="_triggerOpen_7pmuk_38",$="_triggerLabel_7pmuk_45",F="_menu_7pmuk_51",E="_menuLabel_7pmuk_64",P="_menuItem_7pmuk_72",U="_menuItemActive_7pmuk_94",K="_menuItemLabel_7pmuk_99",c={root:R,trigger:O,directionToggle:T,triggerOpen:z,triggerLabel:$,menu:F,menuLabel:E,menuItem:P,menuItemActive:U,menuItemLabel:K};function G({field:e,order:t,onFieldChange:r,onOrderChange:u,className:a}){const[n,l]=_.useState(!1),d=_.useRef(null),f=y.find(s=>s.value===e)??y[0],L=t==="desc"?N:x;_.useEffect(()=>{if(!n)return;const s=b=>{d.current?.contains(b.target)||l(!1)},i=b=>{b.key==="Escape"&&l(!1)};return document.addEventListener("mousedown",s),document.addEventListener("keydown",i),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",i)}},[n]);const h=s=>{r(s),l(!1)};return o.jsxs("div",{ref:d,className:`${c.root} ${a||""}`.trim(),children:[o.jsxs("button",{type:"button",className:`${c.trigger} ${n?c.triggerOpen:""}`.trim(),onClick:()=>l(s=>!s),"aria-haspopup":"menu","aria-expanded":n,"aria-label":`Sort tray by ${f.label}`,title:`Sort by ${f.label}`,children:[o.jsx(v,{size:13}),o.jsx("span",{className:c.triggerLabel,children:f.label}),o.jsx(I,{size:13})]}),o.jsx("button",{type:"button",className:c.directionToggle,onClick:()=>u(t==="desc"?"asc":"desc"),"aria-label":`Sort tray ${t==="desc"?"descending":"ascending"}`,title:t==="desc"?"Sort descending":"Sort ascending",children:o.jsx(L,{size:13})}),n?o.jsxs("div",{className:c.menu,role:"menu","aria-label":"Sort tray items",children:[o.jsx("div",{className:c.menuLabel,children:"Sort by"}),y.map(s=>{const i=s.value===e;return o.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":i,className:`${c.menuItem} ${i?c.menuItemActive:""}`.trim(),onClick:()=>h(s.value),children:[o.jsx("span",{className:c.menuItemLabel,children:s.label}),i?o.jsx(w,{size:13}):null]},s.value)})]}):null]})}export{G as A,q as a,D as s};
@@ -0,0 +1,3 @@
1
+ import{r as l,j as e,a as Ce}from"./vendor-react-CKJs5o3c.js";import{t as o,aZ as ke,a_ as je,a$ as xt,aY as Wt,b0 as wt,u as ve,b1 as Ee,b2 as Ae,b3 as Ie,b4 as Re,R as De,b5 as Te,b6 as Ne}from"./index-BUplSsv_.js";import{w as Yt,t as Le,bo as ot,af as bt,q as Se,X as $e,Z as Pe,bp as Fe,a3 as Zt,bq as Vt,a1 as Jt,r as Qt,u as te,ak as Me,a2 as ze}from"./vendor-icons-BkFLXavV.js";import"./vendor-markdown-_lhNCyq-.js";import"./vendor-dnd-CJ-AjP-Y.js";import"./vendor-router-AqJMU8Lz.js";const ae=[".png",".jpg",".jpeg",".webp",".gif",".pdf",".txt",".md",".csv",".json",".doc",".docx",".html",".js",".ts",".tsx",".css",".py",".java",".go",".rs",".sh"].join(","),Ue=new Set(["image/png","image/jpeg","image/webp"]),Oe=new Set(ae.split(",").map(c=>c.trim().toLowerCase())),Be=10*1024*1024,_e=3500;function oe(c){const u=c.trim().toLowerCase(),y=u.lastIndexOf(".");return y===-1?"":u.slice(y)}function yt(c){if(c.length===0)return"";const u=c.slice(0,3).join(", "),y=c.length-3;return y>0?`${u}, +${y} more`:u}function Ke(c){return`${c.name.trim().toLowerCase()}::${c.size}::${c.lastModified}`}function J(c){return/\.(png|jpe?g|webp|gif)(\?|#|$)/i.test(c)}function qe(c){const u=c.types;if(!u)return null;for(const y of Array.from(u)){const v=String(y||"").trim().toLowerCase();if(Ue.has(v))return v}return null}function ee(c,u){const y=c.includes("?")?"&":"?";return`${c}${y}download=1&filename=${encodeURIComponent(u)}`}function ne(c){return typeof c=="string"?c.split("/").pop()||"Context file":c.displayName||c.originalFilename||c.caption||c.fsPath||c.path.split("/").pop()||"Context file"}function Xe(c){const u=typeof c=="string"?[c]:[c.originalFilename,c.displayName,c.caption,c.fsPath,c.path];for(const v of u){if(!v)continue;const W=oe(v);if(W)return W.replace(".","").slice(0,5).toUpperCase()}const y=typeof c=="string"?c:c.path;return/^https?:\/\//i.test(y)?"LINK":"FILE"}function Qe(c){const{ownerType:u="task",ownerId:y,ownerReferenceLabel:v,workspaceId:W,attachments:N,onAddAttachment:Ct,onRemoveAttachment:kt,onUpdateAttachmentCaption:se,cardCoverAssetId:re=null,onSetCardCover:jt,cardCoverDisabled:vt=!1,readOnly:g=!1,defaultExpanded:st=!0,supplementalContent:le}=c,L=l.useRef(null),rt=l.useRef(null),[Et,lt]=l.useState(!1),[At,E]=l.useState(null),[it,ct]=l.useState(""),[Q,I]=l.useState(null),[M,k]=l.useState(null),[It,ut]=l.useState(null),[dt,tt]=l.useState(st),[S,R]=l.useState(!1),[Y,P]=l.useState(!1),[D,x]=l.useState(null),[A,T]=l.useState(null),[ie,ce]=l.useState({top:0,left:0}),[j,$]=l.useState(null),[ue,Rt]=l.useState(null),z=l.useRef(null);l.useEffect(()=>()=>{z.current!==null&&window.clearTimeout(z.current)},[]),l.useEffect(()=>{ut(null)},[y,u,W]);const de=async t=>{try{await navigator.clipboard.writeText(t)}catch{const n=document.createElement("textarea");n.value=t,document.body.appendChild(n),n.select(),document.execCommand("copy"),n.remove()}Rt(t),z.current!==null&&window.clearTimeout(z.current),z.current=window.setTimeout(()=>{Rt(null),z.current=null},1200)},[Dt,U]=l.useState(!1),[Ge,O]=l.useState(0),Tt=l.useRef(null),B=l.useRef(null),Nt=l.useRef(null),Z=l.useRef(null),Lt=l.useRef(null),_=l.useRef(null),pt=l.useRef(null),et=l.useRef(null),K=l.useRef(null),St=l.useRef(null),F=l.useRef(new Set),ft=l.useRef(new Set),nt=l.useRef(0),$t=l.useRef(""),Pt=t=>(t||"").trim(),at=(t,n)=>{const a=[],s=Pt(t),d=Pt(n);return s&&a.push(`path:${s}`),d&&a.push(`fs:${d}`),a},ht=l.useMemo(()=>{const t=new Set;return N.forEach(n=>{if(typeof n=="string"){at(n).forEach(a=>t.add(a));return}at(n.path,n.fsPath).forEach(a=>t.add(a))}),t},[N]);l.useEffect(()=>{F.current=new Set(ht)},[ht]);const Ft=(t,n)=>n.some(a=>t.has(a)),Mt=(t,n)=>n.forEach(a=>t.add(a)),q=String(W||"").trim(),C=String(y||"").trim(),mt=`${q}\0${u}\0${C}`;l.useLayoutEffect(()=>($t.current=mt,nt.current+=1,ft.current.clear(),F.current=new Set(ht),lt(!1),E(null),ct(""),I(null),k(null),tt(st),R(!1),P(!1),x(null),T(null),$(null),U(!1),O(0),L.current&&(L.current.value=""),()=>{nt.current+=1}),[st,mt]);const pe=u==="initiative"?"initiative":u==="workstream"?"workstream":"task",zt=(t,n=!0,a=F.current)=>{const s=t.trim();if(!s||!/^https?:\/\//i.test(s))return"invalid";const i=s,p=at(i);if(Ft(a,p))return"duplicate";const f=s.split(/[\\/]/).pop()||s;return Ct({path:i,caption:f,timestamp:new Date().toISOString()}),Mt(a,p),n&&ct(""),I(null),"added"};l.useEffect(()=>{if(!M)return;const t=window.setTimeout(()=>{k(null)},_e);return()=>window.clearTimeout(t)},[M]),l.useEffect(()=>{if(!S&&D===null&&A===null)return;const t=n=>{const a=n.target;S&&!Tt.current?.contains(a)&&R(!1),D!==null&&!a?.closest('[data-context-actions-menu="true"]')&&x(null),A!==null&&!_.current?.contains(a)&&!pt.current?.contains(a)&&T(null)};return document.addEventListener("pointerdown",t),()=>document.removeEventListener("pointerdown",t)},[D,A,S]),l.useEffect(()=>{Y&&St.current?.focus()},[Y]),l.useEffect(()=>{S&&Nt.current?.focus()},[S]),l.useEffect(()=>{D!==null&&Lt.current?.focus()},[D]),l.useEffect(()=>{A!==null&&et.current?.focus()},[A]),l.useLayoutEffect(()=>{if(A===null)return;const t=()=>{const n=_.current?.getBoundingClientRect();if(!n)return;const a=pt.current?.getBoundingClientRect(),s=a?.width||150,d=a?.height||108,i=4,p=8,f=Math.max(p,Math.min(n.right-s,window.innerWidth-s-p)),w=n.bottom+i,m=w+d<=window.innerHeight-p?w:Math.max(p,n.top-d-i);ce({top:m,left:f})};return t(),window.addEventListener("resize",t),window.addEventListener("scroll",t,!0),()=>{window.removeEventListener("resize",t),window.removeEventListener("scroll",t,!0)}},[A]),l.useEffect(()=>{g&&(R(!1),P(!1),x(null),T(null),$(null),U(!1),O(0))},[g]);const Ut=async t=>{if(t.length===0)return;const n=mt,a=nt.current,s=()=>$t.current===n&&nt.current===a;if(!s())return;E(null),k(null);const d=t,i=[],p=[],f=[],w=[],m=new Set(ft.current);d.forEach(r=>{const H=oe(r.name);if(!Oe.has(H)){i.push(r.name);return}if(r.size>Be){p.push(r.name);return}const V=Ke(r);if(m.has(V)){f.push(r.name);return}m.add(V),w.push({file:r,fingerprint:V})});const b=[];if(i.length>0&&b.push(`${i.length} unsupported file${i.length===1?"":"s"} skipped: ${yt(i)}.`),p.length>0&&b.push(`${p.length} file${p.length===1?"":"s"} over 10 MB skipped: ${yt(p)}.`),f.length>0&&b.push(`${f.length} local duplicate file${f.length===1?"":"s"} skipped before upload: ${yt(f)}.`),w.length===0){b.length>0&&k(b.join(" ")),L.current&&(L.current.value="");return}lt(!0);const h=new Set(F.current);let G=0;try{for(const{file:H,fingerprint:V}of w){const gt=await Te(H,{ownerType:u,ownerId:C||null,workspaceId:q||null});if(!s())return;const Ht=at(gt.path,gt.fsPath);if(Ft(h,Ht)){G+=1;continue}Ct(gt),Ne({workspaceId:q||"default",ownerType:u,ownerId:C||null,taskId:u==="task"&&C||null,reason:"upload"}),Mt(h,Ht),ft.current.add(V)}if(!s())return;const r=[...b];G>0&&r.push(`${G} duplicate file${G===1?"":"s"} skipped.`),k(r.length>0?r.join(" "):null),F.current=h}catch(r){s()&&E(r instanceof Error?r.message:"Failed to upload context file")}finally{s()&&(lt(!1),L.current&&(L.current.value=""))}},Ot=async t=>{!t||t.length===0||await Ut(Array.from(t))},fe=async()=>{if(E(null),k(null),!navigator.clipboard||typeof navigator.clipboard.read!="function"){E("Clipboard image paste is not available in this browser.");return}try{const t=await navigator.clipboard.read(),n=[];for(const a of t){const s=qe(a);if(!s)continue;const d=await a.getType(s),i=s.toLowerCase()==="image/png"?"png":s.toLowerCase()==="image/webp"?"webp":"jpg";n.push(new globalThis.File([d],`pasted-image-${Date.now()}.${i}`,{type:s}))}if(n.length===0){E("Clipboard does not currently contain a supported image.");return}await Ut(n)}catch(t){E(t?.message||"Failed to read an image from the clipboard.")}},he=t=>{const n=new Set,a=t.dataTransfer.getData("text/uri-list")||"",s=t.dataTransfer.getData("text/plain")||"",d=`${a}
2
+ ${s}`.split(`
3
+ `).map(i=>i.trim()).filter(i=>!!i&&!i.startsWith("#"));for(const i of d){if(/^file:\/\//i.test(i)){try{const p=new URL(i),f=decodeURIComponent(p.pathname||"").trim();f&&n.add(f)}catch{}continue}n.add(i)}return Array.from(n)},me=t=>{if(t.preventDefault(),t.stopPropagation(),U(!1),O(0),E(null),I(null),k(null),t.dataTransfer.files&&t.dataTransfer.files.length>0){Ot(t.dataTransfer.files);return}const n=he(t);if(n.length===0){E("Drop a file or URL.");return}const a=new Set(F.current);let s=0,d=0,i=0;n.forEach(f=>{const w=zt(f,!1,a);w==="duplicate"&&(s+=1),w==="added"&&(d+=1),w==="invalid"&&(i+=1)});const p=[];s>0&&p.push(`${s} duplicate link${s===1?"":"s"} skipped.`),i>0&&p.push(`${i} local path${i===1?"":"s"} skipped. Upload files to attach them, or drop an http(s) URL to link.`),k(p.length>0?p.join(" "):d>0?null:M),F.current=a},ge=t=>{t.preventDefault(),t.stopPropagation(),O(n=>n+1),U(!0)},xe=t=>{t.preventDefault(),t.stopPropagation(),O(n=>{const a=Math.max(0,n-1);return a===0&&U(!1),a})},we=t=>{t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect="copy"},be=()=>{tt(!0),P(!1),I(null),x(null),R(t=>!t)},ye=()=>{tt(!0),R(!1),P(!0),I(null)},Bt=()=>{P(!1),I(null),window.requestAnimationFrame(()=>B.current?.focus())},_t=()=>{if(!it.trim()){I("Enter an http(s) URL to link.");return}const t=zt(it,!0);if(t==="invalid"){I("Only external http(s) URLs can be linked here. Upload files to attach them.");return}if(t==="duplicate"){k(`Link already exists in ${pe} context.`);return}k(null),P(!1),window.requestAnimationFrame(()=>B.current?.focus())},Kt=(t,n)=>{x(null),$({index:t,value:n,originalValue:n})},X=(t=!1)=>{if(!j)return;const n=j.index,a=j.value.trim();a!==j.originalValue&&se(j.index,a),$(null),t&&window.requestAnimationFrame(()=>{if(K.current?.isConnected){K.current.focus();return}rt.current?.querySelector(`[data-context-caption-index="${n}"]`)?.focus()})},qt=()=>{const t=j?.index;$(null),window.requestAnimationFrame(()=>{if(K.current?.isConnected){K.current.focus();return}t!==void 0&&rt.current?.querySelector(`[data-context-caption-index="${t}"]`)?.focus()})},Xt=N.filter(t=>{const n=typeof t=="string"?t:t.path;return J(n)}),Gt=N.filter(t=>{const n=typeof t=="string"?t:t.path;return!J(n)});return e.jsxs("div",{ref:rt,className:o.specialistSection,children:[e.jsx(ke,{label:"Context",count:N.length,showZeroCount:!0,expanded:dt,expandedTitle:"Hide context",collapsedTitle:"Show context",onToggle:()=>{const t=!dt;tt(t),t||(R(!1),P(!1),x(null),T(null),$(null),U(!1),O(0))},actions:g?void 0:e.jsxs("div",{ref:Tt,className:o.contextMenuControl,onKeyDown:t=>{t.key!=="Escape"||!S||(t.preventDefault(),t.stopPropagation(),R(!1),B.current?.focus())},children:[e.jsx("button",{ref:B,type:"button",className:"tf-control-icon","aria-label":"Add context",title:"Add context","aria-expanded":S,onClick:be,disabled:Et,children:Et?e.jsx(Yt,{size:14,className:o.spinner}):e.jsx(Le,{size:14})}),S&&e.jsxs("div",{className:`${o.contextMenu} ${o.contextAddMenu}`,role:"group","aria-label":"Add context",children:[e.jsxs("button",{ref:Nt,type:"button",onClick:()=>{R(!1),B.current?.focus(),L.current?.click()},children:[e.jsx(ot,{size:14}),"Upload file"]}),e.jsxs("button",{type:"button",onClick:()=>{R(!1),B.current?.focus(),fe()},children:[e.jsx(bt,{size:14}),"Paste image"]}),e.jsxs("button",{type:"button",onClick:ye,children:[e.jsx(Se,{size:14}),"Add link"]})]})]})}),!g&&e.jsx("input",{ref:L,type:"file",accept:ae,multiple:!0,className:o.hiddenInput,onChange:t=>{Ot(t.target.files)}}),dt&&e.jsxs("div",{className:`${o.contextContent} ${Dt?o.contextContentDropActive:""}`,role:"region","aria-label":"Context attachments",onDragEnter:g?void 0:ge,onDragLeave:g?void 0:xe,onDragOver:g?void 0:we,onDrop:g?void 0:me,children:[Dt&&e.jsxs("div",{className:o.contextDropOverlay,"aria-hidden":"true",children:[e.jsx(ot,{size:18}),"Drop files or URLs here"]}),le,Y&&e.jsxs("div",{className:o.contextLinkComposer,children:[e.jsx("input",{ref:St,type:"text",className:o.input,"aria-label":"External context URL","aria-invalid":!!Q,placeholder:"Add external URL (https://...)",value:it,onChange:t=>{ct(t.target.value),Q&&I(null),M&&k(null)},onKeyDown:t=>{t.key==="Enter"&&(t.preventDefault(),t.stopPropagation(),_t()),t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),Bt())}}),e.jsx("button",{type:"button",className:"tf-button-ghost tf-button-compact",onClick:_t,children:"Add link"}),e.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact","aria-label":"Cancel adding link",title:"Cancel",onClick:()=>{Bt()},children:e.jsx($e,{size:14})})]}),At&&e.jsx("div",{className:o.error,role:"alert",children:At}),M&&e.jsx("div",{className:o.contextNotice,role:"status",children:M}),Y&&Q&&e.jsx("div",{className:o.error,role:"alert",children:Q}),N.length===0&&!Y&&e.jsxs("div",{className:o.contextEmptyState,children:[e.jsx(ot,{size:14}),e.jsx("span",{children:"Drop files here"})]}),Xt.length>0&&e.jsxs("section",{"aria-label":"Images",children:[Gt.length>0&&e.jsx("div",{className:o.contextGroupLabel,children:"Images"}),e.jsx("div",{className:o.attachmentGrid,children:N.map((t,n)=>{const a=typeof t=="string"?t:t.path;if(!J(a))return null;const s=typeof t=="string"?void 0:t.fsPath,d=typeof t=="string"?"":t.caption||"",i=ne(t),p=J(a),f=/^https?:\/\//i.test(a),w=u==="task"&&je(t),m=typeof t=="string"?"":String(t.assetId||"").trim(),b=!!(m&&m===re),h=u==="task"&&!!C&&!!m&&typeof t!="string"&&t.linkRole==="image"&&!!jt&&!g,G=!!(s||!f||!g);return e.jsxs("div",{className:o.attachmentCard,children:[e.jsxs("div",{className:o.attachmentPreviewContainer,children:[p?e.jsx("button",{type:"button",className:o.attachmentPreviewButton,"aria-label":`Open ${d||i}`,onClick:()=>{xt(t,{ownerType:u,ownerId:C||null,ownerReferenceLabel:v,workspaceId:q||null})||u==="task"&&Wt(t,{taskId:C,taskReferenceLabel:v})||window.open(a,"_blank")},children:e.jsx("img",{src:a,alt:"",onError:r=>{r.currentTarget.style.display="none",r.currentTarget.parentElement?.parentElement?.classList.add(o.brokenImage)}})}):e.jsxs("button",{type:"button",className:o.contextFileLink,onClick:()=>{const r=u==="task"?typeof t=="string"?{path:t,taskId:C}:{...t,taskId:C}:t;wt(r,s)||window.open(a,"_blank")},title:"Open file",children:[e.jsx(ot,{size:16}),e.jsx("span",{children:d||s||a.split("/").pop()||"Context file"})]}),e.jsxs("div",{className:o.brokenImagePlaceholder,children:[e.jsx(Pe,{size:16}),e.jsx("span",{children:"Preview unavailable"})]}),e.jsxs("div",{className:o.attachmentActions,children:[h&&e.jsx("button",{type:"button",className:`${o.attachmentActionBtn} ${b?o.attachmentActionBtnActive:""}`,"aria-pressed":b,"aria-label":b?"Remove from task card":"Show on task card",onClick:r=>{r.stopPropagation(),ut(m),E(null),Promise.resolve(jt?.(b?null:m)).then(()=>{k(b?"Removed image from task card.":"Image shown on task card.")}).catch(H=>{E(H instanceof Error?H.message:"Unable to update the task card image.")}).finally(()=>ut(null))},disabled:vt||It!==null,title:vt?"Attachment is still saving":b?"Remove from task card":"Show on task card",children:It===m?e.jsx(Yt,{size:12,className:o.spinner}):e.jsx(Fe,{size:12})}),w&&e.jsx("button",{type:"button",className:o.attachmentActionBtn,"aria-label":"Annotate image",onClick:r=>{r.stopPropagation(),Wt(t,{taskId:C,taskReferenceLabel:v})},title:"Annotate",children:e.jsx(Zt,{size:12})}),G&&e.jsx("button",{type:"button",className:o.attachmentActionBtn,"aria-label":`Actions for ${i}`,"aria-expanded":A===n,onClick:r=>{r.stopPropagation(),_.current=r.currentTarget,x(null),T(A===n?null:n)},title:"More actions",children:e.jsx(Vt,{size:12})}),A===n&&Ce.createPortal(e.jsxs("div",{ref:pt,className:`${o.contextMenu} ${o.attachmentImageActionsMenu}`,role:"group","aria-label":`Actions for ${i}`,style:ie,onClick:r=>r.stopPropagation(),onKeyDown:r=>{r.key==="Escape"&&(r.preventDefault(),r.stopPropagation(),T(null),_.current?.focus())},children:[s&&e.jsxs("button",{ref:et,type:"button",onClick:()=>{navigator.clipboard.writeText(s),T(null),window.requestAnimationFrame(()=>_.current?.focus())},children:[e.jsx(bt,{size:14})," Copy path"]}),!f&&e.jsxs("button",{ref:s?void 0:et,type:"button",onClick:()=>{window.open(ee(a,d||i),"_blank"),T(null),window.requestAnimationFrame(()=>_.current?.focus())},children:[e.jsx(Jt,{size:14})," Download"]}),!g&&e.jsxs("button",{ref:!s&&f?et:void 0,type:"button",className:o.contextDestructiveMenuItem,onClick:()=>{kt(n),T(null)},children:[e.jsx(Qt,{size:14})," Delete"]})]}),document.body)]})]}),j?.index===n?e.jsxs("div",{className:o.contextCaptionEditor,onBlur:r=>{r.currentTarget.contains(r.relatedTarget)||X(!1)},children:[e.jsx("input",{autoFocus:!0,type:"text",className:o.attachmentCaptionInput,"aria-label":`Rename ${i}`,value:j.value,onChange:r=>$({...j,value:r.target.value}),onKeyDown:r=>{r.key==="Enter"&&(r.preventDefault(),r.stopPropagation(),X(!0)),r.key==="Escape"&&(r.preventDefault(),r.stopPropagation(),qt())}}),e.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact","aria-label":"Save label",onClick:()=>X(!0),children:e.jsx(te,{size:12})})]}):g?e.jsx("span",{className:o.attachmentCaptionLabel,children:d||i}):e.jsx("button",{type:"button",className:o.attachmentCaptionLabel,"data-context-caption-index":n,title:"Edit label",onClick:r=>{K.current=r.currentTarget,Kt(n,d)},children:d||i})]},n)})})]}),Gt.length>0&&e.jsxs("section",{"aria-label":"Documents",children:[Xt.length>0&&e.jsx("div",{className:o.contextGroupLabel,children:"Documents"}),e.jsx("div",{className:o.documentAttachmentList,children:N.map((t,n)=>{const a=typeof t=="string"?t:t.path;if(J(a))return null;const s=typeof t=="string"?void 0:t.fsPath,d=typeof t=="string"?"":t.caption||"",i=ne(t),p=Xe(t),f=typeof t=="string"?"":ve(t),w=/^https?:\/\//i.test(a),m=u==="task"?typeof t=="string"?{path:t,taskId:C}:{...t,taskId:C}:t,b=Ee(m,s)&&!!(Ae(m,s)||Ie(m));return e.jsxs("div",{className:o.documentAttachmentItem,children:[e.jsxs("div",{className:o.documentAttachmentRow,children:[e.jsxs("div",{className:o.documentAttachmentMain,children:[e.jsx(Re,{label:p}),f&&e.jsx(De,{label:f,copied:ue===f,title:`Copy document reference ${f}`,ariaLabel:`Copy document reference ${f}`,className:o.documentAttachmentReference,onClick:()=>{de(f)}}),e.jsx("button",{type:"button",className:o.documentAttachmentLink,onClick:()=>{xt(t,{ownerType:u,ownerId:C||null,ownerReferenceLabel:v,workspaceId:q||null})||wt(m,s)||window.open(a,"_blank")},title:i,"aria-label":`${d||i} ${p}`,children:e.jsx("span",{className:o.documentAttachmentName,children:d||i})})]}),(!g||!!s||!w)&&e.jsxs("div",{className:o.contextMenuControl,"data-context-actions-menu":"true",onKeyDown:h=>{h.key!=="Escape"||D!==n||(h.preventDefault(),h.stopPropagation(),x(null),Z.current?.focus())},children:[e.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact","aria-label":`Actions for ${i}`,title:"More actions","aria-expanded":D===n,onClick:h=>{Z.current=h.currentTarget,x(D===n?null:n)},children:e.jsx(Vt,{size:14})}),D===n&&e.jsxs("div",{className:`${o.contextMenu} ${o.contextActionsMenu}`,role:"group","aria-label":`Actions for ${i}`,children:[e.jsxs("button",{ref:Lt,type:"button",onClick:()=>{xt(t,{ownerType:u,ownerId:C||null,ownerReferenceLabel:v,workspaceId:q||null})||window.open(a,"_blank"),x(null)},children:[e.jsx(Me,{size:14})," Preview"]}),b&&e.jsxs("button",{type:"button",onClick:()=>{wt(m,s)||window.open(a,"_blank"),x(null)},children:[e.jsx(ze,{size:14})," Open"]}),!g&&e.jsxs("button",{type:"button",onClick:()=>{K.current=Z.current,Kt(n,d),x(null)},children:[e.jsx(Zt,{size:14})," Rename"]}),s&&e.jsxs("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(s),x(null),window.requestAnimationFrame(()=>Z.current?.focus())},children:[e.jsx(bt,{size:14})," Copy path"]}),!w&&e.jsxs("button",{type:"button",onClick:()=>{window.open(ee(a,d||i),"_blank"),x(null),window.requestAnimationFrame(()=>Z.current?.focus())},children:[e.jsx(Jt,{size:14})," Download"]}),!g&&e.jsxs("button",{type:"button",className:o.contextDestructiveMenuItem,onClick:()=>{kt(n),x(null)},children:[e.jsx(Qt,{size:14})," Delete"]})]})]})]}),j?.index===n&&e.jsxs("div",{className:o.contextCaptionEditor,onBlur:h=>{h.currentTarget.contains(h.relatedTarget)||X(!1)},children:[e.jsx("input",{autoFocus:!0,type:"text",className:o.documentAttachmentCaptionInput,"aria-label":`Rename ${i}`,value:j.value,onChange:h=>$({...j,value:h.target.value}),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),h.stopPropagation(),X(!0)),h.key==="Escape"&&(h.preventDefault(),h.stopPropagation(),qt())}}),e.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact","aria-label":"Save label",onClick:()=>X(!0),children:e.jsx(te,{size:12})})]})]},n)})})]})]})]})}export{Qe as ContextAttachmentManager};