@useorgx/openclaw-plugin 0.4.8 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (284) hide show
  1. package/README.md +35 -0
  2. package/dashboard/dist/assets/BJgZIVUQ.js +53 -0
  3. package/dashboard/dist/assets/BJgZIVUQ.js.br +0 -0
  4. package/dashboard/dist/assets/BJgZIVUQ.js.gz +0 -0
  5. package/dashboard/dist/assets/BXWDRGm-.js +1 -0
  6. package/dashboard/dist/assets/BXWDRGm-.js.br +0 -0
  7. package/dashboard/dist/assets/BXWDRGm-.js.gz +0 -0
  8. package/dashboard/dist/assets/BgOYB78t.js +4 -0
  9. package/dashboard/dist/assets/BgOYB78t.js.br +0 -0
  10. package/dashboard/dist/assets/BgOYB78t.js.gz +0 -0
  11. package/dashboard/dist/assets/C-KIc3Wc.js.br +0 -0
  12. package/dashboard/dist/assets/C-KIc3Wc.js.gz +0 -0
  13. package/dashboard/dist/assets/CE38zU4U.js +1 -0
  14. package/dashboard/dist/assets/CE38zU4U.js.br +0 -0
  15. package/dashboard/dist/assets/CE38zU4U.js.gz +0 -0
  16. package/dashboard/dist/assets/CFGKRAzG.js +1 -0
  17. package/dashboard/dist/assets/CFGKRAzG.js.br +0 -0
  18. package/dashboard/dist/assets/CFGKRAzG.js.gz +0 -0
  19. package/dashboard/dist/assets/CGGR2GZh.js +1 -0
  20. package/dashboard/dist/assets/CGGR2GZh.js.br +0 -0
  21. package/dashboard/dist/assets/CGGR2GZh.js.gz +0 -0
  22. package/dashboard/dist/assets/CL_wXqR7.js +1 -0
  23. package/dashboard/dist/assets/CL_wXqR7.js.br +0 -0
  24. package/dashboard/dist/assets/CL_wXqR7.js.gz +0 -0
  25. package/dashboard/dist/assets/CPFiTmlw.js +8 -0
  26. package/dashboard/dist/assets/CPFiTmlw.js.br +0 -0
  27. package/dashboard/dist/assets/CPFiTmlw.js.gz +0 -0
  28. package/dashboard/dist/assets/CZZTvkQZ.js +1 -0
  29. package/dashboard/dist/assets/CZZTvkQZ.js.br +0 -0
  30. package/dashboard/dist/assets/CZZTvkQZ.js.gz +0 -0
  31. package/dashboard/dist/assets/{CpJsfbXo.js → CxQ08qFN.js} +2 -2
  32. package/dashboard/dist/assets/CxQ08qFN.js.br +0 -0
  33. package/dashboard/dist/assets/CxQ08qFN.js.gz +0 -0
  34. package/dashboard/dist/assets/D-bf6hEI.js +213 -0
  35. package/dashboard/dist/assets/D-bf6hEI.js.br +0 -0
  36. package/dashboard/dist/assets/D-bf6hEI.js.gz +0 -0
  37. package/dashboard/dist/assets/DG6y9wJI.js +2 -0
  38. package/dashboard/dist/assets/DG6y9wJI.js.br +0 -0
  39. package/dashboard/dist/assets/DG6y9wJI.js.gz +0 -0
  40. package/dashboard/dist/assets/DNxKz-GV.js +1 -0
  41. package/dashboard/dist/assets/DNxKz-GV.js.br +0 -0
  42. package/dashboard/dist/assets/DNxKz-GV.js.gz +0 -0
  43. package/dashboard/dist/assets/DW_rKUic.js +11 -0
  44. package/dashboard/dist/assets/DW_rKUic.js.br +0 -0
  45. package/dashboard/dist/assets/DW_rKUic.js.gz +0 -0
  46. package/dashboard/dist/assets/DbNoijHm.js +1 -0
  47. package/dashboard/dist/assets/DbNoijHm.js.br +0 -0
  48. package/dashboard/dist/assets/DbNoijHm.js.gz +0 -0
  49. package/dashboard/dist/assets/DjcdE6jC.js +2 -0
  50. package/dashboard/dist/assets/DjcdE6jC.js.br +0 -0
  51. package/dashboard/dist/assets/DjcdE6jC.js.gz +0 -0
  52. package/dashboard/dist/assets/FZYuCDnt.js +1 -0
  53. package/dashboard/dist/assets/FZYuCDnt.js.br +0 -0
  54. package/dashboard/dist/assets/FZYuCDnt.js.gz +0 -0
  55. package/dashboard/dist/assets/PAUiij_z.js +1 -0
  56. package/dashboard/dist/assets/PAUiij_z.js.br +0 -0
  57. package/dashboard/dist/assets/PAUiij_z.js.gz +0 -0
  58. package/dashboard/dist/assets/cNrhgGc1.js +8 -0
  59. package/dashboard/dist/assets/cNrhgGc1.js.br +0 -0
  60. package/dashboard/dist/assets/cNrhgGc1.js.gz +0 -0
  61. package/dashboard/dist/assets/h5biQs2I.css +1 -0
  62. package/dashboard/dist/assets/h5biQs2I.css.br +0 -0
  63. package/dashboard/dist/assets/h5biQs2I.css.gz +0 -0
  64. package/dashboard/dist/assets/ic2FaMnh.js +1 -0
  65. package/dashboard/dist/assets/ic2FaMnh.js.br +0 -0
  66. package/dashboard/dist/assets/ic2FaMnh.js.gz +0 -0
  67. package/dashboard/dist/assets/nByHNHoW.js +1 -0
  68. package/dashboard/dist/assets/nByHNHoW.js.br +0 -0
  69. package/dashboard/dist/assets/nByHNHoW.js.gz +0 -0
  70. package/dashboard/dist/assets/qm8xLgv-.css +1 -0
  71. package/dashboard/dist/assets/qm8xLgv-.css.br +0 -0
  72. package/dashboard/dist/assets/qm8xLgv-.css.gz +0 -0
  73. package/dashboard/dist/assets/tS9mbYZi.js +1 -0
  74. package/dashboard/dist/assets/tS9mbYZi.js.br +0 -0
  75. package/dashboard/dist/assets/tS9mbYZi.js.gz +0 -0
  76. package/dashboard/dist/brand/anthropic-mark.svg.br +0 -0
  77. package/dashboard/dist/brand/anthropic-mark.svg.gz +0 -0
  78. package/dashboard/dist/brand/openai-mark.svg.br +0 -0
  79. package/dashboard/dist/brand/openai-mark.svg.gz +0 -0
  80. package/dashboard/dist/brand/openclaw-mark.svg.br +0 -0
  81. package/dashboard/dist/brand/openclaw-mark.svg.gz +0 -0
  82. package/dashboard/dist/brand/xandy-orchestrator.png +0 -0
  83. package/dashboard/dist/index.html +7 -5
  84. package/dashboard/dist/index.html.br +0 -0
  85. package/dashboard/dist/index.html.gz +0 -0
  86. package/dist/activity-actor-fields.js +26 -4
  87. package/dist/activity-store.js +38 -26
  88. package/dist/agent-context-store.js +84 -42
  89. package/dist/agent-run-store.js +49 -28
  90. package/dist/agent-suite.d.ts +9 -0
  91. package/dist/agent-suite.js +150 -17
  92. package/dist/artifacts/artifact-domain-schemas.d.ts +66 -0
  93. package/dist/artifacts/artifact-domain-schemas.js +357 -0
  94. package/dist/artifacts/register-artifact.d.ts +4 -3
  95. package/dist/artifacts/register-artifact.js +170 -57
  96. package/dist/auth/flows.d.ts +47 -0
  97. package/dist/auth/flows.js +169 -0
  98. package/dist/auth-store.js +6 -26
  99. package/dist/byok-store.js +5 -19
  100. package/dist/chat-store.d.ts +157 -0
  101. package/dist/chat-store.js +586 -0
  102. package/dist/cli/orgx.d.ts +66 -0
  103. package/dist/cli/orgx.js +102 -0
  104. package/dist/config/refresh.d.ts +32 -0
  105. package/dist/config/refresh.js +55 -0
  106. package/dist/config/resolution.d.ts +37 -0
  107. package/dist/config/resolution.js +178 -0
  108. package/dist/contracts/client.d.ts +43 -3
  109. package/dist/contracts/client.js +159 -30
  110. package/dist/contracts/retro-schema.d.ts +81 -0
  111. package/dist/contracts/retro-schema.js +80 -0
  112. package/dist/contracts/shared-types.d.ts +306 -0
  113. package/dist/contracts/shared-types.js +179 -0
  114. package/dist/contracts/skill-pack-schema.d.ts +192 -0
  115. package/dist/contracts/skill-pack-schema.js +180 -0
  116. package/dist/contracts/types.d.ts +224 -132
  117. package/dist/contracts/types.js +5 -0
  118. package/dist/entities/auto-assignment.d.ts +36 -0
  119. package/dist/entities/auto-assignment.js +141 -0
  120. package/dist/entity-comment-store.js +5 -25
  121. package/dist/event-sanitization.d.ts +11 -0
  122. package/dist/event-sanitization.js +113 -0
  123. package/dist/fs-utils.js +13 -1
  124. package/dist/gateway-watchdog.d.ts +5 -0
  125. package/dist/gateway-watchdog.js +50 -0
  126. package/dist/hash-utils.d.ts +2 -0
  127. package/dist/hash-utils.js +12 -0
  128. package/dist/hooks/post-reporting-event.mjs +1 -5
  129. package/dist/http/helpers/activity-headline.d.ts +10 -0
  130. package/dist/http/helpers/activity-headline.js +73 -0
  131. package/dist/http/helpers/artifact-fallback.d.ts +13 -0
  132. package/dist/http/helpers/artifact-fallback.js +148 -0
  133. package/dist/http/helpers/auto-continue-engine.d.ts +486 -0
  134. package/dist/http/helpers/auto-continue-engine.js +3563 -0
  135. package/dist/http/helpers/autopilot-operations.d.ts +176 -0
  136. package/dist/http/helpers/autopilot-operations.js +554 -0
  137. package/dist/http/helpers/autopilot-runtime.d.ts +43 -0
  138. package/dist/http/helpers/autopilot-runtime.js +607 -0
  139. package/dist/http/helpers/autopilot-slice-utils.d.ts +56 -0
  140. package/dist/http/helpers/autopilot-slice-utils.js +899 -0
  141. package/dist/http/helpers/decision-mapper.d.ts +52 -0
  142. package/dist/http/helpers/decision-mapper.js +260 -0
  143. package/dist/http/helpers/dispatch-lifecycle.d.ts +119 -0
  144. package/dist/http/helpers/dispatch-lifecycle.js +809 -0
  145. package/dist/http/helpers/hash-utils.d.ts +1 -0
  146. package/dist/http/helpers/hash-utils.js +1 -0
  147. package/dist/http/helpers/kickoff-context.d.ts +12 -0
  148. package/dist/http/helpers/kickoff-context.js +228 -0
  149. package/dist/http/helpers/llm-client.d.ts +47 -0
  150. package/dist/http/helpers/llm-client.js +256 -0
  151. package/dist/http/helpers/mission-control.d.ts +193 -0
  152. package/dist/http/helpers/mission-control.js +1383 -0
  153. package/dist/http/helpers/openclaw-cli.d.ts +37 -0
  154. package/dist/http/helpers/openclaw-cli.js +283 -0
  155. package/dist/http/helpers/runtime-sse.d.ts +20 -0
  156. package/dist/http/helpers/runtime-sse.js +110 -0
  157. package/dist/http/helpers/sentinel-catalog.d.ts +23 -0
  158. package/dist/http/helpers/sentinel-catalog.js +193 -0
  159. package/dist/http/helpers/session-classification.d.ts +9 -0
  160. package/dist/http/helpers/session-classification.js +564 -0
  161. package/dist/http/helpers/slice-experience-v2.d.ts +137 -0
  162. package/dist/http/helpers/slice-experience-v2.js +677 -0
  163. package/dist/http/helpers/slice-run-projections.d.ts +72 -0
  164. package/dist/http/helpers/slice-run-projections.js +860 -0
  165. package/dist/http/helpers/triage-mapper.d.ts +43 -0
  166. package/dist/http/helpers/triage-mapper.js +549 -0
  167. package/dist/http/helpers/value-utils.d.ts +6 -0
  168. package/dist/http/helpers/value-utils.js +72 -0
  169. package/dist/http/helpers/workspace-scope.d.ts +15 -0
  170. package/dist/http/helpers/workspace-scope.js +170 -0
  171. package/dist/http/index.d.ts +88 -0
  172. package/dist/http/index.js +3610 -0
  173. package/dist/http/router.d.ts +23 -0
  174. package/dist/http/router.js +23 -0
  175. package/dist/http/routes/agent-control.d.ts +79 -0
  176. package/dist/http/routes/agent-control.js +684 -0
  177. package/dist/http/routes/agent-suite.d.ts +38 -0
  178. package/dist/http/routes/agent-suite.js +397 -0
  179. package/dist/http/routes/agents-catalog.d.ts +40 -0
  180. package/dist/http/routes/agents-catalog.js +128 -0
  181. package/dist/http/routes/billing.d.ts +23 -0
  182. package/dist/http/routes/billing.js +55 -0
  183. package/dist/http/routes/chat.d.ts +19 -0
  184. package/dist/http/routes/chat.js +522 -0
  185. package/dist/http/routes/debug.d.ts +14 -0
  186. package/dist/http/routes/debug.js +21 -0
  187. package/dist/http/routes/decision-actions.d.ts +20 -0
  188. package/dist/http/routes/decision-actions.js +103 -0
  189. package/dist/http/routes/delegation.d.ts +19 -0
  190. package/dist/http/routes/delegation.js +32 -0
  191. package/dist/http/routes/dispatch-gateway-envelope.d.ts +25 -0
  192. package/dist/http/routes/dispatch-gateway-envelope.js +26 -0
  193. package/dist/http/routes/entities.d.ts +63 -0
  194. package/dist/http/routes/entities.js +440 -0
  195. package/dist/http/routes/entity-dynamic.d.ts +25 -0
  196. package/dist/http/routes/entity-dynamic.js +191 -0
  197. package/dist/http/routes/health.d.ts +22 -0
  198. package/dist/http/routes/health.js +49 -0
  199. package/dist/http/routes/live-legacy.d.ts +115 -0
  200. package/dist/http/routes/live-legacy.js +112 -0
  201. package/dist/http/routes/live-misc.d.ts +81 -0
  202. package/dist/http/routes/live-misc.js +426 -0
  203. package/dist/http/routes/live-snapshot.d.ts +136 -0
  204. package/dist/http/routes/live-snapshot.js +916 -0
  205. package/dist/http/routes/live-terminal.d.ts +11 -0
  206. package/dist/http/routes/live-terminal.js +261 -0
  207. package/dist/http/routes/live-triage.d.ts +61 -0
  208. package/dist/http/routes/live-triage.js +248 -0
  209. package/dist/http/routes/mission-control-actions.d.ts +131 -0
  210. package/dist/http/routes/mission-control-actions.js +1791 -0
  211. package/dist/http/routes/mission-control-read.d.ts +73 -0
  212. package/dist/http/routes/mission-control-read.js +1640 -0
  213. package/dist/http/routes/onboarding.d.ts +34 -0
  214. package/dist/http/routes/onboarding.js +101 -0
  215. package/dist/http/routes/realtime-orchestrator.d.ts +10 -0
  216. package/dist/http/routes/realtime-orchestrator.js +74 -0
  217. package/dist/http/routes/run-control.d.ts +27 -0
  218. package/dist/http/routes/run-control.js +96 -0
  219. package/dist/http/routes/runtime-hooks.d.ts +69 -0
  220. package/dist/http/routes/runtime-hooks.js +437 -0
  221. package/dist/http/routes/sentinels-catalog.d.ts +7 -0
  222. package/dist/http/routes/sentinels-catalog.js +24 -0
  223. package/dist/http/routes/settings-byok.d.ts +23 -0
  224. package/dist/http/routes/settings-byok.js +163 -0
  225. package/dist/http/routes/summary.d.ts +18 -0
  226. package/dist/http/routes/summary.js +49 -0
  227. package/dist/http/routes/usage.d.ts +24 -0
  228. package/dist/http/routes/usage.js +362 -0
  229. package/dist/http/routes/work-artifacts.d.ts +9 -0
  230. package/dist/http/routes/work-artifacts.js +55 -0
  231. package/dist/http/shared-state.d.ts +16 -0
  232. package/dist/http/shared-state.js +1 -0
  233. package/dist/http-handler.d.ts +1 -88
  234. package/dist/http-handler.js +1 -10605
  235. package/dist/index.js +287 -2284
  236. package/dist/json-utils.d.ts +1 -0
  237. package/dist/json-utils.js +8 -0
  238. package/dist/local-openclaw.js +29 -6
  239. package/dist/mcp-client-setup.js +3 -3
  240. package/dist/mcp-http-handler.js +33 -59
  241. package/dist/next-up-queue-store.d.ts +16 -1
  242. package/dist/next-up-queue-store.js +93 -25
  243. package/dist/outbox.d.ts +5 -0
  244. package/dist/outbox.js +113 -9
  245. package/dist/paths.js +24 -5
  246. package/dist/reporting/rollups.d.ts +53 -0
  247. package/dist/reporting/rollups.js +148 -0
  248. package/dist/retro/domain-templates.d.ts +45 -0
  249. package/dist/retro/domain-templates.js +297 -0
  250. package/dist/retro/quality-rubric.d.ts +33 -0
  251. package/dist/retro/quality-rubric.js +213 -0
  252. package/dist/runtime-cleanup.d.ts +18 -0
  253. package/dist/runtime-cleanup.js +87 -0
  254. package/dist/runtime-instance-store.js +5 -31
  255. package/dist/services/background.d.ts +34 -0
  256. package/dist/services/background.js +45 -0
  257. package/dist/services/experiment-randomization.d.ts +21 -0
  258. package/dist/services/experiment-randomization.js +63 -0
  259. package/dist/services/instrumentation.d.ts +29 -0
  260. package/dist/services/instrumentation.js +136 -0
  261. package/dist/skill-pack-state.d.ts +36 -5
  262. package/dist/skill-pack-state.js +273 -29
  263. package/dist/snapshot-store.js +5 -25
  264. package/dist/stores/json-store.d.ts +11 -0
  265. package/dist/stores/json-store.js +42 -0
  266. package/dist/sync/local-agent-telemetry.d.ts +13 -0
  267. package/dist/sync/local-agent-telemetry.js +128 -0
  268. package/dist/sync/outbox-replay.d.ts +55 -0
  269. package/dist/sync/outbox-replay.js +621 -0
  270. package/dist/team-context-store.d.ts +23 -0
  271. package/dist/team-context-store.js +116 -0
  272. package/dist/telemetry/posthog.js +4 -2
  273. package/dist/tools/core-tools.d.ts +72 -0
  274. package/dist/tools/core-tools.js +2270 -0
  275. package/dist/types.d.ts +2 -0
  276. package/dist/types.js +2 -0
  277. package/dist/worker-supervisor.js +23 -0
  278. package/package.json +14 -4
  279. package/dashboard/dist/assets/B3ziCA02.js +0 -8
  280. package/dashboard/dist/assets/BNeJ0kpF.js +0 -1
  281. package/dashboard/dist/assets/BzkiMPmM.js +0 -215
  282. package/dashboard/dist/assets/CUV9IHHi.js +0 -1
  283. package/dashboard/dist/assets/Ie7d9Iq2.css +0 -1
  284. package/dashboard/dist/assets/sAhvFnpk.js +0 -4
@@ -0,0 +1,213 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DW_rKUic.js","assets/cNrhgGc1.js","assets/C-KIc3Wc.js","assets/BJgZIVUQ.js","assets/qm8xLgv-.css","assets/BXWDRGm-.js","assets/nByHNHoW.js","assets/CxQ08qFN.js","assets/DNxKz-GV.js","assets/DbNoijHm.js","assets/CFGKRAzG.js","assets/CZZTvkQZ.js","assets/CL_wXqR7.js","assets/ic2FaMnh.js","assets/CGGR2GZh.js","assets/DjcdE6jC.js","assets/PAUiij_z.js","assets/tS9mbYZi.js","assets/DG6y9wJI.js","assets/CPFiTmlw.js","assets/FZYuCDnt.js","assets/CE38zU4U.js"])))=>i.map(i=>d[i]);
2
+ var Tl=Object.defineProperty;var El=(e,t,s)=>t in e?Tl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var er=(e,t,s)=>El(e,typeof t!="symbol"?t+"":t,s);import{r as o,u as sa,a as ds,b as mn,j as n,c as Rl,d as Dl,D as ya,e as Ll,Q as Fl}from"./cNrhgGc1.js";import{b as $l}from"./C-KIc3Wc.js";import{m as be,A as pt,u as Xn}from"./CxQ08qFN.js";import{F as Bo,T as Pl}from"./BJgZIVUQ.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const c of a.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).observe(document,{childList:!0,subtree:!0});function s(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function r(i){if(i.ep)return;i.ep=!0;const a=s(i);fetch(i.href,a)}})();const Ol="modulepreload",Bl=function(e){return"/orgx/live/"+e},ba={},qt=function(t,s,r){let i=Promise.resolve();if(s&&s.length>0){let c=function(u){return Promise.all(u.map(h=>Promise.resolve(h).then(y=>({status:"fulfilled",value:y}),y=>({status:"rejected",reason:y}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),d=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));i=c(s.map(u=>{if(u=Bl(u),u in ba)return;ba[u]=!0;const h=u.endsWith(".css"),y=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${y}`))return;const b=document.createElement("link");if(b.rel=h?"stylesheet":Ol,h||(b.as="script"),b.crossOrigin="",b.href=u,d&&b.setAttribute("nonce",d),document.head.appendChild(b),h)return new Promise((p,w)=>{b.addEventListener("load",p),b.addEventListener("error",()=>w(new Error(`Unable to preload CSS for ${u}`)))})}))}function a(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return i.then(c=>{for(const l of c||[])l.status==="rejected"&&a(l.reason);return t().catch(a)})},wa=()=>{const e=new Date,t=s=>new Date(e.getTime()-s*60*1e3).toISOString();return{connection:"connected",lastActivity:"2m ago",lastSnapshotAt:e.toISOString(),snapshotVersion:1,sessions:{groups:[{id:"init-1",label:"Q4 Feature Ship",status:"active"},{id:"init-2",label:"Black Friday Email",status:"active"}],edges:[{parentId:"run-1",childId:"run-2"},{parentId:"run-1",childId:"run-3"}],nodes:[{id:"run-1",parentId:null,runId:"run-1",title:"Q4 Feature Ship – Planning",agentId:"eli",agentName:"Eli",status:"running",progress:45,initiativeId:"init-1",workstreamId:null,groupId:"init-1",groupLabel:"Q4 Feature Ship",startedAt:t(120),updatedAt:t(2),lastEventAt:t(2),lastEventSummary:"Delegated work to design and data agents.",blockers:[]},{id:"run-2",parentId:"run-1",runId:"run-2",title:"Dashboard UI pass",agentId:"dana",agentName:"Dana",status:"running",progress:70,initiativeId:"init-1",workstreamId:"ws-4",groupId:"init-1",groupLabel:"Q4 Feature Ship",startedAt:t(80),updatedAt:t(5),lastEventAt:t(5),lastEventSummary:"Drafted handoff for approval.",blockers:["Approval pending"]},{id:"run-3",parentId:"run-1",runId:"run-3",title:"Usage tracking instrumentation",agentId:"pace",agentName:"Pace",status:"queued",progress:0,initiativeId:"init-1",workstreamId:"ws-5",groupId:"init-1",groupLabel:"Q4 Feature Ship",startedAt:t(30),updatedAt:t(12),lastEventAt:t(12),lastEventSummary:"Waiting for data pipeline access.",blockers:["Access to events table"]},{id:"run-4",parentId:null,runId:"run-4",title:"Black Friday Email Campaign",agentId:"mark",agentName:"Mark",status:"running",progress:55,initiativeId:"init-2",workstreamId:null,groupId:"init-2",groupLabel:"Black Friday Email",startedAt:t(90),updatedAt:t(8),lastEventAt:t(8),lastEventSummary:"Drafted subject line variants.",blockers:[]}]},activity:[{id:"activity-1",type:"decision_requested",title:"Decision requested",description:"Approve dashboard UI layout for Q4 Feature Ship.",agentId:"dana",agentName:"Dana",requesterAgentId:"dana",requesterAgentName:"Dana",executorAgentId:"dana",executorAgentName:"Dana",runId:"run-2",initiativeId:"init-1",timestamp:t(2)},{id:"activity-2",type:"artifact_created",title:"Artifact created: Subject line variants",description:"Drafted 3 subject line variants for approval.",agentId:"mark",agentName:"Mark",requesterAgentId:"mark",requesterAgentName:"Mark",executorAgentId:"mark",executorAgentName:"Mark",runId:"run-4",initiativeId:"init-2",timestamp:t(8)},{id:"activity-3",type:"delegation",title:"Task delegated",description:"Spin up data agent for instrumentation plan.",agentId:"eli",agentName:"Eli",requesterAgentId:"eli",requesterAgentName:"Eli",executorAgentId:"eli",executorAgentName:"Eli",runId:"run-1",initiativeId:"init-1",timestamp:t(18)}],handoffs:[{id:"handoff-1",title:"Dashboard UI approval",status:"created",priority:"high",summary:"Need approval on dashboard UI layout and component hierarchy.",currentActorType:"user",currentActorId:"me",createdAt:t(12),updatedAt:t(2),events:[{id:"handoff-event-1",handoffId:"handoff-1",eventType:"created",actorType:"agent",actorId:"dana",payload:{summary:"Draft layout ready for review."},createdAt:t(12)}]}],decisions:[{id:"decision-1",title:"Approve dashboard copy update",context:"Marketing requested a copy refresh before final launch. Confirm wording changes.",status:"pending",agentName:"Mark",requestedAt:t(22),updatedAt:t(2),waitingMinutes:22}],sliceRuns:[{id:"slice-run-1",sliceRunId:"slice-run-1",runId:"run-2",initiativeId:"init-1",workstreamId:"ws-4",workstreamTitle:"Dashboard UI pass",taskIds:["task-1"],milestoneIds:[],status:"awaiting_input",statusExplainer:"Needs your decision to proceed with this slice.",primaryAction:"resolve_decision",hasArtifact:!1,artifactCount:0,artifacts:[],decisionCount:1,blockingDecisionCount:1,decisionOptions:[{id:"approve-layout",label:"Approve layout",description:"Proceed with the current dashboard layout.",impliedStatus:"approved",requiresNote:!1}],sourceClient:"codex",runtimeState:"active",startedAt:t(80),updatedAt:t(2),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(2),lastEventSummary:"Waiting on approval before implementation continues.",correlationId:"run-2",confidence:"high"},{id:"slice-run-2",sliceRunId:"slice-run-2",runId:"run-4",initiativeId:"init-2",workstreamId:"ws-9",workstreamTitle:"Email campaign generation",taskIds:["task-2"],milestoneIds:[],status:"completed",statusExplainer:"Completed with verified output artifacts.",primaryAction:"open_artifact",hasArtifact:!0,artifactCount:1,artifacts:[{id:"artifact-1",type:"document",title:"Subject line variants",url:null,createdAt:t(8)}],decisionCount:0,blockingDecisionCount:0,decisionOptions:[],sourceClient:"openclaw",runtimeState:"stopped",startedAt:t(90),updatedAt:t(8),completedAt:t(8),failedAt:null,archivedAt:null,lastEventAt:t(8),lastEventSummary:"Produced subject line variants and attached artifact.",correlationId:"run-4",confidence:"high"}],outbox:{pendingTotal:0,pendingByQueue:{},oldestEventAt:null,newestEventAt:null,replayStatus:"idle",lastReplayAttemptAt:null,lastReplaySuccessAt:null,lastReplayFailureAt:null,lastReplayError:null},chat:{threads:[],total:0,updatedAt:e.toISOString()}}},di="all";function Kn(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function ql(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search);return Kn(e.get("workspace_id"))??Kn(e.get("workspaceId"))??Kn(e.get("command_center_id"))??Kn(e.get("commandCenterId"))??Kn(e.get("center"))??Kn(e.get("project_id"))??Kn(e.get("projectId"))}catch{return null}}function us(e,t,s){const r=Kn(t);if(!r){s!=null&&s.allTokenWhenMissing&&(e.set("workspace_id",di),e.set("command_center_id",di),e.set("center",di));return}e.set("workspace_id",r),e.set("command_center_id",r),e.set("center",r)}function zl(e){const t=Kn(e);return t?{"x-orgx-workspace-id":t}:{}}function _t(e){const t={};e.contentTypeJson&&(t["Content-Type"]="application/json"),e.embedMode&&(t["X-Orgx-Embed"]="true"),e.authToken&&(t.Authorization=`Bearer ${e.authToken}`);const s=e.workspaceId??ql();return Object.assign(t,zl(s)),t}const Ul=[[/opus/i,"Opus"],[/sonnet/i,"Sonnet"],[/haiku/i,"Haiku"],[/kimi/i,"Kimi"],[/gemini/i,"Gemini"],[/gpt-4o/i,"GPT-4o"],[/gpt-4/i,"GPT-4"],[/qwen/i,"Qwen"],[/deepseek/i,"DeepSeek"],[/llama/i,"Llama"]];function gr(e){if(!e)return"";for(const[s,r]of Ul)if(s.test(e))return r;const t=e.split("/");return t[t.length-1]??e}const qo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,zo=/^[0-9a-f]{20,}$/i;function as(e){return qo.test(e)?`#${e.slice(0,4)}`:zo.test(e)?`#${e.slice(0,4)}`:e}function ms(e){return qo.test(e)||zo.test(e)}function _s(e,t=4){let s=e.replace(/^\/Users\/[^/]+\//,"~/").replace(/^~\/Code\//,"").replace(/^~\//,"");const r=s.split("/");return r.length>t&&(s=r.slice(-t).join("/")),s}function lt(e){let t=e;return t=t.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,s=>`#${s.slice(0,4)}`),t=t.replace(/(?:anthropic|openrouter|openai)\/[a-z0-9._/-]+/gi,s=>gr(s)),t=t.replace(/\/Users\/[a-zA-Z0-9_-]+\/[^\s"']+/g,s=>_s(s)),t}function Bt(e){let t=e;return t=t.replace(/\[?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\]?/gi,""),t=t.replace(/\[workstream\s*\]/gi,""),t=t.replace(/\[workstream\b[^\]]*\]/gi,""),t=t.replace(/\/var\/folders\/[^\s"']*/g,"(local file)"),t=t.replace(/\/tmp\/[^\s"']*/g,"(temp file)"),t=t.replace(/\/Users\/[^\s"']*/g,s=>_s(s)),t=t.replace(/telegram:\d+/g,"Telegram session"),t=t.replace(/discord:\d+/g,"Discord session"),t=t.replace(/\s{2,}/g," ").trim(),t||"Untitled session"}function pr(e){const t=e.toLowerCase().trim();return t==="main"?"You":t==="system"||t==="system / unknown"||t==="openclaw"||t==="local_openclaw"?"OrgX":t==="not assigned"||t==="unassigned"?"Pending":e}function bn(e){return/agent catalog unavailable|listagents/i.test(e)?"Agent details are still loading.":/timed out|timeout|request cancelled|signal is aborted/i.test(e)?"Live sync is taking longer than expected. Data will refresh automatically.":/budget.*exhaust/i.test(e)?"Token budget reached":/unknown api endpoint|route is unavailable|missing required live routes/i.test(e)?"This plugin build is missing required routes. Update and restart the plugin.":/unauthorized|forbidden|authentication|api key/i.test(e)?"Authentication needs attention. Reconnect OrgX in Settings.":/worker exited without structured output|worker close|signal=null/i.test(e)?"An agent run ended before returning a structured result.":/mcp handshake failed/i.test(e)?"The agent connection handshake failed. Retry after reconnecting.":/run not found/i.test(e)?"This session is no longer available.":/500|internal server error/i.test(e)?"Something went wrong on the server. Retrying automatically.":/ECONNREFUSED|network error|fetch failed/i.test(e)?"Connection issue. Retrying automatically.":/40[13]/.test(e)?"Access issue. You may need to reconnect your workspace.":/blocked without an explicit reason/i.test(e)?"This item was paused without a specific reason.":Bt(lt(e))}function Wl(e,t){if(e==null&&t==null||e===0&&t)return null;const s=e??0,r=t??0,i=a=>a>=1e6?`${(a/1e6).toFixed(1)}M`:a>=1e3?`${Math.round(a/1e3)}K`:`${a}`;return r>0?`${i(s)} / ${i(r)} (${Math.round(s/r*100)}%)`:i(s)}function Hl(e){const t=e.metadata??{},s=Ps(t,"task_title")??Ps(t,"workstream_title"),r=s?Bt(String(s)):e.title?Bt(e.title):null,i=Ps(t,"user_summary")??Ps(t,"summary"),a=i?Bt(String(i)):e.summary?Bt(e.summary):e.description?Bt(e.description):null,c=Ps(t,"next_step")??Ps(t,"nextStep"),l=c?Bt(String(c)):null;return{taskDescription:r,outcomeDescription:a&&a===r?null:a,nextStep:l&&(l===r||l===a)?null:l}}function Ps(e,t){const s=e[t];return typeof s=="string"&&s.trim().length>0?s.trim():null}const Vl={auto_continue_stopped:"Autopilot paused",budget_exhausted:"Token budget reached",error:"Encountered an error",blocked:"Waiting for input",stopped:"Manually stopped",rate_limited:"Rate limited — retrying shortly",timeout:"Timed out",timed_out:"Timed out",cancelled:"Cancelled",completed:"Completed"};function tr(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return Vl[t]??e.replace(/_/g," ")}const Kl={running:"Active",waiting_for_capacity:"Waiting for capacity",rate_limited:"Rate limited",idle:"Idle",blocked:"Blocked",queued:"Queued"};function uh(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return Kl[t]??e.replace(/_/g," ")}function mh(e,t){return e.toLowerCase().includes("path")?_s(t):ms(t)?as(t):t.includes(",")?t.split(",").map(r=>{const i=r.trim();return ms(i)?as(i):i}).join(", "):Bt(t)}function Gl(e){if(!Number.isFinite(e)||e<1)return"just now";if(e<60)return`${Math.round(e)} min`;const t=Math.floor(e/60),s=Math.round(e%60);if(t<24)return s>0?`${t} hr ${s} min`:`${t} hr`;const r=Math.floor(t/24);return r<7?`${r} day${r===1?"":"s"}`:r<14?"over a week":`${Math.floor(r/7)} weeks`}function ph(e){const t=Gl(e);return!Number.isFinite(e)||e<60?{text:t,tone:"normal"}:e<1440?{text:t,tone:"attention"}:{text:t,tone:"urgent"}}function Gr(e){const t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleString()}function It(e){const s=(e instanceof Date?e:new Date(e)).getTime()-Date.now();if(Number.isNaN(s))return"unknown";const r=Math.floor(Math.abs(s)/1e3),i=s<0?"past":"future";if(r<10)return i==="past"?"just now":"soon";if(r<60)return i==="past"?`${r}s ago`:`in ${r}s`;const a=Math.floor(r/60);if(a<60)return i==="past"?`${a}m ago`:`in ${a}m`;const c=Math.floor(a/60);if(c<24)return i==="past"?`${c}h ago`:`in ${c}h`;const l=Math.floor(c/24);return i==="past"?`${l}d ago`:`in ${l}d`}const Xl=8e3,Ql=320,Jl=300,Yl=80,Zl=80,ec=120,va=6e4,tc=3500,nc=180,ra={pendingTotal:0,pendingByQueue:{},oldestEventAt:null,newestEventAt:null,replayStatus:"idle",lastReplayAttemptAt:null,lastReplaySuccessAt:null,lastReplayFailureAt:null,lastReplayError:null},Nr={phase:"idle",action:null,targetCount:0,message:null,startedAt:null,completedAt:null},Ms={threads:[],total:0,updatedAt:null},ka={running:0,active:0,queued:1,in_progress:1,working:1,planning:1,handoff:1,review:2,pending:2,blocked:3,failed:4,cancelled:5,paused:6,completed:6,archived:7},Uo=new Set(["running","active","queued","in_progress","working","planning","handoff","review","pending","blocked"]),ja=45*6e4;function sc(e){const t=e.trim().toLowerCase();return t?t.includes("aborterror")||t.includes("signal is aborted")||t.includes("aborted")||t.includes("request cancelled")||t.includes("request canceled"):!1}function rc(e){const t=e.map(a=>a.trim()).filter(Boolean);if(t.length===0)return"Live data is unavailable right now. OrgX Live will retry automatically.";const s=t.map(a=>a.toLowerCase());return s.every(a=>a.includes("timed out")||a.includes("timeout")||a.includes("signal is aborted")||a.includes("request cancelled")||a.includes("request canceled"))?"Live sync is taking longer than expected. OrgX Live is retrying in the background.":s.some(a=>a.includes("unknown api endpoint"))?"This plugin runtime is missing required live routes. Restart the plugin, then update if needed.":s.some(a=>a.includes("unauthorized")||a.includes("forbidden"))?"OrgX authorization needs attention. Reconnect your API key in Settings.":Array.from(new Set(t.map(a=>{const c=a.replace(/^[^:]+:\s*/,"").trim();return c.length>0?c:a}))).slice(0,2).map(a=>bn(a)).filter(a=>a.length>0).join(" ")}function ic(e){const t=e.trim().toLowerCase();if(!t)return"";if(t.includes("timed out")||t.includes("timeout")||t.includes("request cancelled")||t.includes("request canceled")||t.includes("signal is aborted"))return"Live sync is slower than expected. Some panels may refresh a few seconds late.";if(t.includes("unauthorized")||t.includes("forbidden"))return"OrgX authorization needs attention. Reconnect your API key in Settings.";if(t.includes("unknown api endpoint")||t.includes("route is unavailable"))return"This plugin runtime is missing required live routes. Restart the plugin after updating.";const s=e.replace(/^[^:]+:\s*/,"").replace(/\s+/g," ").trim();return bn(s.length>0?s:e.trim())}function ac(e){const t=e.map(s=>ic(s)).filter(s=>s.length>0);return Array.from(new Set(t)).slice(0,2)}function ht(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Xr(e,t){const s=ka[e.status]??99,r=ka[t.status]??99;if(s!==r)return s-r;const i=ht(e.updatedAt??e.lastEventAt??e.startedAt),a=ht(t.updatedAt??t.lastEventAt??t.startedAt);return i!==a?a-i:e.id.localeCompare(t.id)}function oc(e){return(e??"").trim().toLowerCase()}function Na(e){return Uo.has(oc(e.status))}function ui(e){const t=[];return e.id&&t.push(`id:${e.id}`),e.runId&&t.push(`run:${e.runId}`),t}function Ia(e,t){if(!e.nodes.length)return t;if(!t.nodes.length){const p=Date.now(),w=e.nodes.filter(C=>{const j=ht(C.updatedAt??C.lastEventAt??C.startedAt);return Na(C)||p-j<=ja});if(!w.length)return t;const v=new Set(w.map(C=>C.id)),x=new Set(w.map(C=>C.groupId));return{nodes:w.sort(Xr),edges:e.edges.filter(C=>v.has(C.parentId)&&v.has(C.childId)),groups:e.groups.filter(C=>x.has(C.id))}}const s=new Set,r=[...t.nodes];for(const p of t.nodes)for(const w of ui(p))s.add(w);const i=Date.now(),a=[];for(const p of e.nodes){if(ui(p).some(C=>s.has(C)))continue;const v=ht(p.updatedAt??p.lastEventAt??p.startedAt),x=i-v<=ja;if(Na(p)||x){a.push(p),r.push(p);for(const C of ui(p))s.add(C)}}if(!a.length)return t;const c=new Set(r.map(p=>p.id)),l=new Map(e.groups.map(p=>[p.id,p])),d=new Map(t.groups.map(p=>[p.id,p])),u=[...t.groups];for(const p of a){if(d.has(p.groupId))continue;const w=l.get(p.groupId)??{id:p.groupId,label:p.groupLabel||p.agentName||"Ungrouped",status:null};d.set(p.groupId,w),u.push(w)}const h=p=>`${p.parentId}->${p.childId}`,y=new Set,b=[];for(const p of t.edges){if(!c.has(p.parentId)||!c.has(p.childId))continue;const w=h(p);y.has(w)||(y.add(w),b.push(p))}for(const p of e.edges){if(!c.has(p.parentId)||!c.has(p.childId))continue;const w=h(p);y.has(w)||(y.add(w),b.push(p))}return{nodes:r.sort(Xr),edges:b,groups:u}}function nr(e,t){if(e.nodes.length<=t)return e;const s=[...e.nodes].sort(Xr).slice(0,t),r=new Set(s.map(a=>a.id)),i=new Set(s.map(a=>a.groupId));return{nodes:s,edges:e.edges.filter(a=>r.has(a.parentId)&&r.has(a.childId)),groups:e.groups.filter(a=>i.has(a.id))}}function Aa(e,t){return e.length<=t?e:[...e].sort((s,r)=>ht(r.updatedAt)-ht(s.updatedAt)).slice(0,t)}function lc(e){const t=e.requestedAt??e.updatedAt??null,s=e.updatedAt??t,r=Number.isFinite(e.waitingMinutes)?Math.max(0,Math.floor(e.waitingMinutes)):t?Math.max(0,Math.floor((Date.now()-ht(t))/6e4)):0;return{id:e.id,title:e.title,context:e.context??null,status:e.status??"pending",agentName:e.agentName??null,requestedAt:t,updatedAt:s,waitingMinutes:r,metadata:e.metadata}}function Wo(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s].id!==t[s].id||e[s].timestamp!==t[s].timestamp||e[s].type!==t[s].type||e[s].title!==t[s].title||e[s].requesterAgentId!==t[s].requesterAgentId||e[s].requesterAgentName!==t[s].requesterAgentName||e[s].executorAgentId!==t[s].executorAgentId||e[s].executorAgentName!==t[s].executorAgentName)return!1;return!0}function Sa(e,t){if(e.nodes.length!==t.nodes.length||e.edges.length!==t.edges.length||e.groups.length!==t.groups.length)return!1;for(let s=0;s<e.nodes.length;s+=1){const r=e.nodes[s],i=t.nodes[s];if(r.id!==i.id||r.status!==i.status||r.title!==i.title||r.progress!==i.progress||r.updatedAt!==i.updatedAt||r.lastEventAt!==i.lastEventAt)return!1}for(let s=0;s<e.edges.length;s+=1){const r=e.edges[s],i=t.edges[s];if(r.parentId!==i.parentId||r.childId!==i.childId)return!1}for(let s=0;s<e.groups.length;s+=1){const r=e.groups[s],i=t.groups[s];if(r.id!==i.id||r.label!==i.label||r.status!==i.status)return!1}return!0}function _a(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s].id!==t[s].id||e[s].updatedAt!==t[s].updatedAt||e[s].status!==t[s].status||e[s].title!==t[s].title)return!1;return!0}function Ca(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s].id!==t[s].id||e[s].status!==t[s].status||e[s].updatedAt!==t[s].updatedAt||e[s].waitingMinutes!==t[s].waitingMinutes)return!1;return!0}function Ho(e){if(!e||typeof e!="object")return ra;const t=e.pendingByQueue&&typeof e.pendingByQueue=="object"?Object.fromEntries(Object.entries(e.pendingByQueue).filter(([r])=>typeof r=="string"&&r.length>0).map(([r,i])=>[r,Number.isFinite(Number(i))?Math.max(0,Math.floor(Number(i))):0])):{},s=e.replayStatus==="running"||e.replayStatus==="success"||e.replayStatus==="error"?e.replayStatus:"idle";return{pendingTotal:Number.isFinite(e.pendingTotal)?Math.max(0,Math.floor(e.pendingTotal)):Object.values(t).reduce((r,i)=>r+i,0),pendingByQueue:t,oldestEventAt:e.oldestEventAt??null,newestEventAt:e.newestEventAt??null,replayStatus:s,lastReplayAttemptAt:e.lastReplayAttemptAt??null,lastReplaySuccessAt:e.lastReplaySuccessAt??null,lastReplayFailureAt:e.lastReplayFailureAt??null,lastReplayError:e.lastReplayError??null}}function cc(e,t){if(e.pendingTotal!==t.pendingTotal||e.oldestEventAt!==t.oldestEventAt||e.newestEventAt!==t.newestEventAt||e.replayStatus!==t.replayStatus||e.lastReplayAttemptAt!==t.lastReplayAttemptAt||e.lastReplaySuccessAt!==t.lastReplaySuccessAt||e.lastReplayFailureAt!==t.lastReplayFailureAt||e.lastReplayError!==t.lastReplayError)return!1;const s=Object.keys(e.pendingByQueue),r=Object.keys(t.pendingByQueue);if(s.length!==r.length)return!1;for(const i of s)if(e.pendingByQueue[i]!==t.pendingByQueue[i])return!1;return!0}function dc(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function js(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r!="string")continue;const i=r.trim();if(i.length>0)return i}return null}const uc=new Set(["autopilot_slice_result","auto_continue_started","auto_continue_stopped","next_up_manual_dispatch_started","autopilot_slice_mcp_handshake_failed","autopilot_slice_timeout","autopilot_slice_log_stall","auto_continue_spawn_guard_blocked","auto_continue_spawn_guard_rate_limited","autopilot_autofix_scheduled","autopilot_autofix_executed","autopilot_autofix_skipped"]);function mc(e){const t=dc(e.metadata),s=t==null?void 0:t.event,r=typeof s=="string"?s.trim().toLowerCase():"";if(!r||!uc.has(r))return null;const i=(typeof e.runId=="string"&&e.runId.trim().length>0?e.runId.trim():null)??js(t,["run_id","runId","slice_run_id","sliceRunId","active_run_id","activeRunId","last_run_id","lastRunId"]),a=js(t,["correlation_id","correlationId"]),c=(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null)??js(t,["initiative_id","initiativeId"]),l=js(t,["workstream_id","workstreamId"]),d=js(t,["task_id","taskId"]),u=js(t,["stop_reason","stopReason"]),h=js(t,["parsed_status","parsedStatus"]),y=(e.title??"").trim().toLowerCase();return!i&&!a&&!l&&!d?null:[r,c??"",l??"",d??"",i??"",a??"",u??"",h??"",y].join("|")}function Vo(e,t){const s=new Set,r=new Set,i=[];for(const a of e){if(s.has(a.id))continue;s.add(a.id);const c=mc(a);if(!(c&&r.has(c))&&(c&&r.add(c),i.push(a),i.length>=t))break}return i}function pc(e,t,s){if(t.length===0)return e;const r=new Map;for(const l of e)r.set(l.id,l);let i=!1;for(const l of t){const d=r.get(l.id);if(!d){r.set(l.id,l),i=!0;continue}(d.timestamp!==l.timestamp||d.type!==l.type||d.title!==l.title||d.description!==l.description||d.summary!==l.summary||d.kind!==l.kind||d.agentId!==l.agentId||d.agentName!==l.agentName||d.requesterAgentId!==l.requesterAgentId||d.requesterAgentName!==l.requesterAgentName||d.executorAgentId!==l.executorAgentId||d.executorAgentName!==l.executorAgentName||d.runId!==l.runId||d.initiativeId!==l.initiativeId||d.decisionRequired!==l.decisionRequired||JSON.stringify(d.metadata??null)!==JSON.stringify(l.metadata??null))&&(r.set(l.id,l),i=!0)}if(!i)return e;const a=Array.from(r.values()).sort((l,d)=>{const u=ht(d.timestamp)-ht(l.timestamp);return u!==0?u:d.id.localeCompare(l.id)}),c=Vo(a,s);return Wo(e,c)?e:c}function mi(e,t){const s=[...e].sort((r,i)=>{const a=ht(i.timestamp)-ht(r.timestamp);return a!==0?a:i.id.localeCompare(r.id)});return Vo(s,t)}function Ma(e,t){const s=e.filter(a=>!!a&&typeof a.id=="string"&&a.id.length>0).map(lc).sort((a,c)=>a.waitingMinutes!==c.waitingMinutes?c.waitingMinutes-a.waitingMinutes:ht(c.requestedAt??c.updatedAt)-ht(a.requestedAt??a.updatedAt)).slice(0,t),r=new Set,i=[];for(const a of s)r.has(a.id)||(r.add(a.id),i.push(a));return i}function Ta(e){return e==="run_failed"||e==="blocker_created"?"blocked":e==="run_completed"||e==="milestone_completed"?"completed":e==="decision_requested"||e==="handoff_requested"?"pending":e==="decision_resolved"||e==="handoff_fulfilled"?"completed":"running"}function fc(e){const t=e.toLowerCase();return t==="running"||t==="active"?"running":t==="queued"||t==="pending"?"queued":t==="blocked"?"blocked":t==="failed"?"failed":t==="completed"||t==="done"?"completed":"archived"}function hc(e,t){return!!(Uo.has(t)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0)}function Ir(e){return e?`Initiative ${e.length>16?`${e.slice(0,8)}…`:e}`:"Unscoped"}function pi(e){if(!Array.isArray(e))return[];const t=[];for(const s of e)typeof s=="string"&&s.trim().length>0&&t.push(s.trim());return t}function gc(e,t,s){const r=new Map,i=[...e].sort((l,d)=>ht(d.timestamp)-ht(l.timestamp));for(const l of i){if(!l.runId)continue;const d=l.runId,u=r.get(d),h=l.timestamp;if(!u){const y=l.initiativeId??null;r.set(d,{id:d,parentId:null,runId:d,title:l.title,agentId:l.agentId??null,agentName:l.agentName??null,status:Ta(l.type),progress:null,initiativeId:y,workstreamId:null,groupId:y??"unscoped",groupLabel:Ir(y),startedAt:h,updatedAt:h,lastEventAt:h,lastEventSummary:l.title,blockers:l.type==="blocker_created"&&l.description?[l.description]:[]});continue}(!u.startedAt||ht(h)<ht(u.startedAt))&&(u.startedAt=h),ht(h)>=ht(u.updatedAt??u.lastEventAt)&&(u.updatedAt=h,u.lastEventAt=h,u.lastEventSummary=l.title,u.status=Ta(l.type),l.agentName&&(u.agentName=l.agentName),l.agentId&&(u.agentId=l.agentId),l.initiativeId&&(u.initiativeId=l.initiativeId,u.groupId=l.initiativeId,u.groupLabel=Ir(l.initiativeId)),(!u.title||u.title.length<4)&&(u.title=l.title)),l.type==="blocker_created"&&l.description&&(u.blockers.includes(l.description)||u.blockers.push(l.description))}for(const l of t??[]){const d=l.runId??`agent:${l.id}`,u=r.get(d),h=fc(l.status),y=new Date().toISOString(),b=hc(l,h),p=l.startedAt??(b?y:null),w=l.initiativeId??null,v=l.currentTask&&l.currentTask.trim().length>0?l.currentTask.trim():`${l.name??l.id} ${h==="archived"?"idle":h}`;if(!u){r.set(d,{id:d,parentId:null,runId:d,title:v,agentId:l.id,agentName:l.name??l.id,status:h,progress:null,initiativeId:w,workstreamId:null,groupId:w??"unscoped",groupLabel:Ir(w),startedAt:p,updatedAt:p,lastEventAt:p,lastEventSummary:l.currentTask,blockers:pi(l.blockers)});continue}!u.agentName&&l.name&&(u.agentName=l.name),u.agentId||(u.agentId=l.id),(!u.title||u.title===u.runId)&&(u.title=v),b&&(u.updatedAt=p??u.updatedAt??y,u.lastEventAt=p??u.lastEventAt??y),u.status==="archived"&&h!=="archived"&&(u.status=h),pi(l.blockers).length>0&&(u.blockers=pi(l.blockers)),w&&!u.initiativeId&&(u.initiativeId=w,u.groupId=w,u.groupLabel=Ir(w))}const a=Array.from(r.values()).sort(Xr).slice(0,s),c=new Map;for(const l of a)c.has(l.groupId)||c.set(l.groupId,{id:l.groupId,label:l.groupLabel,status:l.status});return{nodes:a,edges:[],groups:Array.from(c.values())}}async function xc(e,t,s){var h;const r=Number.isFinite(s.timeoutMs)?Math.max(100,Math.floor(s.timeoutMs)):0,i=r>0?new AbortController:null,a=t==null?void 0:t.signal,c=(i==null?void 0:i.signal)??a,l=c?{...t??{},signal:c}:t??{};let d=null,u=null;if(i){if(a!=null&&a.aborted)i.abort();else if(a){const y=()=>i.abort();a.addEventListener("abort",y,{once:!0}),u=()=>a.removeEventListener("abort",y)}d=setTimeout(()=>i.abort(),r)}try{const y=await fetch(e,l),p=(((h=y.headers.get("content-type"))==null?void 0:h.toLowerCase())??"").includes("application/json");if(!y.ok){let w=`${y.status} ${y.statusText}`;if(p){const v=await y.json().catch(()=>null);v!=null&&v.error&&(w=`${y.status} ${v.error}`)}else{const v=(await y.text().catch(()=>"")).replace(/\s+/g," ").slice(0,80);v.length>0&&(w=`${y.status} ${v}`)}return{ok:!1,status:y.status,data:null,error:w}}if(!p){const w=(await y.text().catch(()=>"")).replace(/\s+/g," ").slice(0,80);return{ok:!1,status:y.status,data:null,error:`Unexpected content type for ${e}${w?`: ${w}`:""}`}}return{ok:!0,status:y.status,data:await y.json(),error:null}}catch(y){const b=y instanceof Error?y.message:"Network error",p=!!(i!=null&&i.signal.aborted)&&!(a!=null&&a.aborted);return y instanceof DOMException&&y.name==="AbortError"||sc(b)?{ok:!1,status:0,data:null,error:p&&r>0?`request timed out after ${r}ms`:"request cancelled"}:{ok:!1,status:0,data:null,error:b}}finally{d&&clearTimeout(d),u&&u()}}function yc(e,t,s,r,i=[],a=ra,c=null,l=1,d=[],u=Ms,h){var w,v,x;const y=((w=t[0])==null?void 0:w.timestamp)??null,b=((v=r[0])==null?void 0:v.requestedAt)??((x=r[0])==null?void 0:x.updatedAt)??null,p=ht(y)>=ht(b)?y:b;return{connection:"connected",lastActivity:p?It(p):null,lastSnapshotAt:c,snapshotVersion:l,sessions:e,activity:t,handoffs:s,decisions:r,sliceRuns:i,outbox:Ho(a),chat:Br(u),runtimeInstances:d,workSliceProjections:(h==null?void 0:h.workSliceProjections)??[],timelineNarrative:(h==null?void 0:h.timelineNarrative)??[],nextUpByInitiative:(h==null?void 0:h.nextUpByInitiative)??[],runningWorkSlices:(h==null?void 0:h.runningWorkSlices)??0,needsInputTotal:(h==null?void 0:h.needsInputTotal)??0,failedActionableTotal:(h==null?void 0:h.failedActionableTotal)??0,completedTodayTotal:(h==null?void 0:h.completedTodayTotal)??0,consistencyFlags:(h==null?void 0:h.consistencyFlags)??[],dataHealth:h==null?void 0:h.dataHealth}}function Ea(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map;for(const s of e){if(!s||typeof s!="object"||typeof s.id!="string")continue;const r=s.id.trim();r&&t.set(r,s)}return Array.from(t.values()).sort((s,r)=>ht(r.lastEventAt??r.lastHeartbeatAt)-ht(s.lastEventAt??s.lastHeartbeatAt))}function Ra(e,t){const s=e??[],r=t??[];if(s.length!==r.length)return!1;for(let i=0;i<s.length;i+=1)if(s[i].id!==r[i].id||s[i].state!==r[i].state||s[i].lastEventAt!==r[i].lastEventAt||s[i].runId!==r[i].runId||s[i].progressPct!==r[i].progressPct)return!1;return!0}function bc(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map;for(const s of e){if(!s||typeof s!="object"||typeof s.id!="string")continue;const r=s.id.trim();r&&t.set(r,{...s,id:r,watcherIds:Array.isArray(s.watcherIds)?s.watcherIds.filter(Boolean):[],watcherNames:Array.isArray(s.watcherNames)?s.watcherNames.filter(Boolean):[],latestLaunch:s.latestLaunch&&typeof s.latestLaunch=="object"?{...s.latestLaunch,watcherIds:Array.isArray(s.latestLaunch.watcherIds)?s.latestLaunch.watcherIds.filter(Boolean):[],watcherNames:Array.isArray(s.latestLaunch.watcherNames)?s.latestLaunch.watcherNames.filter(Boolean):[],warnings:Array.isArray(s.latestLaunch.warnings)?s.latestLaunch.warnings.filter(Boolean):[]}:null})}return Array.from(t.values()).sort((s,r)=>ht(r.lastActivityAt??r.updatedAt)-ht(s.lastActivityAt??s.updatedAt))}function Br(e){if(!e||typeof e!="object")return Ms;const t=bc(Array.isArray(e.threads)?e.threads:[]),s=typeof e.total=="number"&&Number.isFinite(e.total)?Math.max(t.length,Math.floor(e.total)):t.length;return{threads:t,total:s,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}function wc(e,t){const s=e??Ms,r=t??Ms;if(s.total!==r.total||s.updatedAt!==r.updatedAt||s.threads.length!==r.threads.length)return!1;for(let i=0;i<s.threads.length;i+=1){const a=s.threads[i],c=r.threads[i];if(a.id!==c.id||a.status!==c.status||a.lastActivityAt!==c.lastActivityAt||a.lastSnippet!==c.lastSnippet||a.assigneeId!==c.assigneeId||a.launchCount!==c.launchCount||a.messageCount!==c.messageCount)return!1}return!0}function qr(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map,s=(r,i)=>{const a=[],c=l=>{if(typeof l!="string")return;const d=l.trim();d&&(a.some(u=>u.toLowerCase()===d.toLowerCase())||a.push(d))};if(Array.isArray(r))for(const l of r)c(l);else if(typeof r=="string")for(const l of r.split(/[\n,;]+/g))c(l);return i&&c(i),a};for(const r of e){if(!r||typeof r!="object")continue;const i=typeof r.sliceRunId=="string"&&r.sliceRunId.trim().length>0?r.sliceRunId.trim():typeof r.id=="string"&&r.id.trim().length>0?r.id.trim():null;if(!i)continue;const a=s(r.initiativeIds,r.initiativeId??null),c=s(r.workstreamIds,r.workstreamId??null),l=s(r.iwmtIds,r.iwmtId??null),d=typeof r.initiativeId=="string"&&r.initiativeId.trim().length>0?r.initiativeId.trim():a[0]??null,u=typeof r.workstreamId=="string"&&r.workstreamId.trim().length>0?r.workstreamId.trim():c[0]??null,h=typeof r.iwmtId=="string"&&r.iwmtId.trim().length>0?r.iwmtId.trim():l[0]??null;t.set(i,{...r,id:i,sliceRunId:i,initiativeId:d,initiativeIds:a,workstreamId:u,workstreamIds:c,iwmtId:h,iwmtIds:l,artifacts:Array.isArray(r.artifacts)?r.artifacts:[],decisionOptions:Array.isArray(r.decisionOptions)?r.decisionOptions:[],taskIds:Array.isArray(r.taskIds)?r.taskIds:[],milestoneIds:Array.isArray(r.milestoneIds)?r.milestoneIds:[]})}return Array.from(t.values()).sort((r,i)=>ht(i.updatedAt??i.lastEventAt)-ht(r.updatedAt??r.lastEventAt))}function Ar(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map;for(const s of e){if(!s||typeof s!="object")continue;const r=typeof s.sliceRunId=="string"&&s.sliceRunId.trim().length>0?s.sliceRunId.trim():null;if(!r)continue;const i=s.lineage&&typeof s.lineage=="object"?s.lineage:null;t.set(r,{...s,sliceRunId:r,consistencyFlags:Array.isArray(s.consistencyFlags)?s.consistencyFlags:[],lineage:{initiativeIds:Array.isArray(i==null?void 0:i.initiativeIds)?i.initiativeIds:[],initiativeTitles:Array.isArray(i==null?void 0:i.initiativeTitles)?i.initiativeTitles:[],workstreamIds:Array.isArray(i==null?void 0:i.workstreamIds)?i.workstreamIds:[],workstreamTitles:Array.isArray(i==null?void 0:i.workstreamTitles)?i.workstreamTitles:[],taskIds:Array.isArray(i==null?void 0:i.taskIds)?i.taskIds:[],milestoneIds:Array.isArray(i==null?void 0:i.milestoneIds)?i.milestoneIds:[],iwmtIds:Array.isArray(i==null?void 0:i.iwmtIds)?i.iwmtIds:[],sliceRunId:r,sessionId:typeof(i==null?void 0:i.sessionId)=="string"?i.sessionId:null},artifacts:Array.isArray(s.artifacts)?s.artifacts:[]})}return Array.from(t.values()).sort((s,r)=>ht(r.updatedAt??r.completedAt??r.failedAt)-ht(s.updatedAt??s.completedAt??s.failedAt))}function fi(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map;for(const s of e){if(!s||typeof s!="object")continue;const r=typeof s.sliceRunId=="string"&&s.sliceRunId.trim().length>0?s.sliceRunId.trim():null;r&&t.set(r,{...s,sliceRunId:r,highlights:Array.isArray(s.highlights)?s.highlights:[],technicalTrace:s.technicalTrace??{eventCount:0,eventIds:[]}})}return Array.from(t.values()).sort((s,r)=>ht(r.occurredAt)-ht(s.occurredAt))}function hi(e){return!Array.isArray(e)||e.length===0?[]:e.filter(t=>t&&typeof t=="object").map(t=>({initiativeId:typeof t.initiativeId=="string"&&t.initiativeId.trim().length>0?t.initiativeId.trim():null,initiativeTitle:typeof t.initiativeTitle=="string"&&t.initiativeTitle.trim().length>0?t.initiativeTitle.trim():"Unscoped initiative",pendingCount:typeof t.pendingCount=="number"&&Number.isFinite(t.pendingCount)?Math.max(0,Math.floor(t.pendingCount)):0,queue:Array.isArray(t.queue)?t.queue:[]})).sort((t,s)=>s.pendingCount-t.pendingCount)}function Da(e){var s;if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const r of e){if(r.sliceKind!=="work_slice")continue;const i=r.lineage.initiativeIds[0]??null,a=r.lineage.workstreamIds[0]??null,c=r.lineage.workstreamTitles[0]??r.lineage.workstreamIds[0]??null,l=r.lifecycleState==="completed"&&r.outcomeState==="succeeded_without_artifacts"?"needs_review":r.lifecycleState,d=((s=r.actionContract)==null?void 0:s.actionType)??null,u=d==="open_artifact"||d==="open_logs"||d==="open_session"||d==="open_run"||d==="open_workstream"||d==="open_task"||d==="open_initiative"||d==="open_pr"||d==="open_diff"||d==="open_branch"?"open_artifact":d==="approve"||d==="reject"||d==="provide_context"||d==="request_info"||d==="confirm_scope"||d==="connect_provider"||d==="refresh_credentials"||d==="reassign"||d==="escalate"?"resolve_decision":d==="retry"||d==="resume"||d==="start"||d==="auto_fix"?"retry_slice":r.outcomeState==="succeeded_without_artifacts"?"review_output":"none";t.push({id:r.sliceRunId,sliceRunId:r.sliceRunId,runId:r.runId,initiativeId:i,initiativeIds:r.lineage.initiativeIds,workstreamId:a,workstreamIds:r.lineage.workstreamIds,iwmtId:r.lineage.iwmtIds[0]??null,iwmtIds:r.lineage.iwmtIds,workstreamTitle:c,taskIds:r.lineage.taskIds,milestoneIds:r.lineage.milestoneIds,status:l,statusExplainer:r.statusExplainer,primaryAction:u,hasArtifact:r.hasArtifact,artifactCount:r.artifactCount,artifacts:r.artifacts.map(h=>({id:h.artifactId,type:h.type,title:h.title,url:h.url,createdAt:h.producedAt})),decisionCount:r.outcomeState==="needs_input"?1:0,blockingDecisionCount:r.outcomeState==="needs_input"?1:0,decisionOptions:[],sourceClient:r.sourceClient,runtimeState:r.runtimeState,startedAt:null,updatedAt:r.updatedAt,completedAt:r.completedAt,failedAt:r.failedAt,archivedAt:r.archivedAt,lastEventAt:r.updatedAt,lastEventSummary:r.statusExplainer,correlationId:r.sliceRunId,confidence:r.confidence})}return qr(t)}function vc(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const r=e[s],i=t[s];if(r.sliceRunId!==i.sliceRunId||r.status!==i.status||r.updatedAt!==i.updatedAt||r.lastEventAt!==i.lastEventAt||r.artifactCount!==i.artifactCount||r.decisionCount!==i.decisionCount||r.blockingDecisionCount!==i.blockingDecisionCount||r.runtimeState!==i.runtimeState)return!1}return!0}function kc(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const r=e[s],i=t[s];if(r.sliceRunId!==i.sliceRunId||r.lifecycleState!==i.lifecycleState||r.outcomeState!==i.outcomeState||r.updatedAt!==i.updatedAt||r.artifactCount!==i.artifactCount||r.lineage.sessionId!==i.lineage.sessionId)return!1}return!0}function jc(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const r=e[s],i=t[s];if(r.sliceRunId!==i.sliceRunId||r.occurredAt!==i.occurredAt||r.outcome.state!==i.outcome.state||r.outcome.artifactCount!==i.outcome.artifactCount)return!1}return!0}function Nc(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const r=e[s],i=t[s];if(r.initiativeId!==i.initiativeId||r.pendingCount!==i.pendingCount||r.queue.length!==i.queue.length)return!1}return!0}function Ic(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s]!==t[s])return!1;return!0}function Ac(e,t){return!e&&!t?!0:!e||!t?!1:e.status===t.status&&e.totals.slices===t.totals.slices&&e.totals.missingTerminal===t.totals.missingTerminal&&e.totals.lineageGap===t.totals.lineageGap&&e.totals.artifactMismatch===t.totals.artifactMismatch&&e.totals.invalidActor===t.totals.invalidActor}function Sc(e={}){const{enabled:t=!0,pollInterval:s=Xl,useMock:r=!1,enableDecisions:i=!0,initiativeId:a=null,projectId:c=null,maxSessions:l=Ql,maxActivityItems:d=Jl,maxHandoffs:u=Yl,maxDecisions:h=Zl,batchWindowMs:y=ec}=e,b=typeof a=="string"&&a.trim().length>0?a.trim():null,p=typeof c=="string"&&c.trim().length>0?c.trim():null,[w,v]=o.useState(wa()),[x,C]=o.useState(Nr),[j,g]=o.useState(!r),[S,W]=o.useState(null),Y=o.useRef(),K=o.useRef(null),me=o.useRef(null),[ge,Z]=o.useState(!1),ae=o.useRef(0),ke=o.useRef(!1),Fe=o.useRef(`${b??"__all__"}::${p??"__all__"}`),G=o.useRef(!1),Se=o.useRef(null),Ae=o.useCallback((V,k)=>{Se.current&&(clearTimeout(Se.current),Se.current=null),C(V),k!=null&&k.autoResetMs&&k.autoResetMs>0&&(Se.current=setTimeout(()=>{Se.current=null,C(Nr)},k.autoResetMs))},[]);o.useEffect(()=>()=>{Se.current&&(clearTimeout(Se.current),Se.current=null)},[]),o.useEffect(()=>{const V=`${b??"__all__"}::${p??"__all__"}`;Fe.current!==V&&(Fe.current=V,G.current=!0,Ae(Nr),v(k=>({...k,sessions:{nodes:[],edges:[],groups:[]},activity:[],handoffs:[],decisions:[],sliceRuns:[],chat:Ms,runtimeInstances:[],workSliceProjections:[],timelineNarrative:[],nextUpByInitiative:[],runningWorkSlices:0,needsInputTotal:0,failedActionableTotal:0,completedTodayTotal:0,consistencyFlags:[],lastActivity:null,lastSnapshotAt:null,snapshotVersion:(k.snapshotVersion??0)+1})),g(!0),W(null))},[b,p,Ae]);const xe=o.useCallback((V,k,z,O=null,oe=null,ie=null,Me=null,ue=null,R=null,$=null)=>{ae.current=Date.now(),ke.current=!1,v(X=>{const te=G.current;te&&(G.current=!1);const Le=k===null?te?[]:X.activity:mi(k,d),qe=z===null?te?[]:X.handoffs:Aa(z,u),_e=nr(V===null?te?{nodes:[],edges:[],groups:[]}:X.sessions:te?nr(V,l):Ia(X.sessions,nr(V,l)),l),M=O===null?te?[]:X.decisions:Ma(O,h),B=oe===null?te?[]:X.sliceRuns:qr(oe),ne=ie===null?te?ra:X.outbox:Ho(ie),fe=ue===null?te?[]:X.runtimeInstances??[]:Ea(ue),De=R===null?te?Ms:X.chat??Ms:Br(R),et=($==null?void 0:$.workSliceProjections)==null?te?[]:X.workSliceProjections??[]:Ar($.workSliceProjections),tt=($==null?void 0:$.timelineNarrative)==null?te?[]:X.timelineNarrative??[]:fi($.timelineNarrative),Re=($==null?void 0:$.nextUpByInitiative)==null?te?[]:X.nextUpByInitiative??[]:hi($.nextUpByInitiative),Je=typeof($==null?void 0:$.runningWorkSlices)=="number"&&Number.isFinite($.runningWorkSlices)?Math.max(0,Math.floor($.runningWorkSlices)):X.runningWorkSlices??0,We=typeof($==null?void 0:$.needsInputTotal)=="number"&&Number.isFinite($.needsInputTotal)?Math.max(0,Math.floor($.needsInputTotal)):X.needsInputTotal??0,ft=typeof($==null?void 0:$.failedActionableTotal)=="number"&&Number.isFinite($.failedActionableTotal)?Math.max(0,Math.floor($.failedActionableTotal)):X.failedActionableTotal??0,ot=typeof($==null?void 0:$.completedTodayTotal)=="number"&&Number.isFinite($.completedTodayTotal)?Math.max(0,Math.floor($.completedTodayTotal)):X.completedTodayTotal??0,nt=($==null?void 0:$.consistencyFlags)==null?X.consistencyFlags??[]:$.consistencyFlags.filter(je=>typeof je=="string"),we=($==null?void 0:$.dataHealth)===void 0||($==null?void 0:$.dataHealth)===null?X.dataHealth:$.dataHealth,Ge=(X.snapshotVersion??0)+1;return Sa(X.sessions,_e)&&Wo(X.activity,Le)&&_a(X.handoffs,qe)&&Ca(X.decisions,M)&&vc(X.sliceRuns,B)&&cc(X.outbox,ne)&&wc(X.chat,De)&&Ra(X.runtimeInstances,fe)&&kc(X.workSliceProjections??[],et)&&jc(X.timelineNarrative??[],tt)&&Nc(X.nextUpByInitiative??[],Re)&&(X.runningWorkSlices??0)===Je&&(X.needsInputTotal??0)===We&&(X.failedActionableTotal??0)===ft&&(X.completedTodayTotal??0)===ot&&Ic(X.consistencyFlags??[],nt)&&Ac(X.dataHealth,we)&&X.lastSnapshotAt===Me&&X.connection==="connected"?X:yc(_e,Le,qe,M,B,ne,Me,Ge,fe,De,{workSliceProjections:et,timelineNarrative:tt,nextUpByInitiative:Re,runningWorkSlices:Je,needsInputTotal:We,failedActionableTotal:ft,completedTodayTotal:ot,consistencyFlags:nt,dataHealth:we})}),g(!1)},[d,h,u,l]),re=o.useCallback(async()=>{if(!t){v(z=>z.connection==="disconnected"?z:{...z,connection:"disconnected"}),g(!1),W(null);return}const V=`${b??"__all__"}::${p??"__all__"}`;if(K.current&&me.current===V)return K.current;if(r){v(wa()),g(!1);return}const k=(async()=>{try{const z=new URLSearchParams({sessionsLimit:String(l),activityLimit:String(d),decisionsLimit:String(h),include_idle:"true"});p&&us(z,p),b&&z.set("initiative",b);const O=[{label:"live/snapshot-v2",url:`/orgx/api/live/snapshot-v2?${z.toString()}`},{label:"dashboard-bundle",url:`/orgx/api/dashboard-bundle?${z.toString()}`},{label:"live/snapshot",url:`/orgx/api/live/snapshot?${z.toString()}`}],oe=[];let ie=null,Me=!1;for(let se=0;se<O.length;se+=1){const Ce=O[se];se>0&&await new Promise(Pe=>{setTimeout(Pe,nc)});const $e=await xc(Ce.url,{headers:_t({workspaceId:p})},{timeoutMs:tc});if($e.ok&&$e.data){ie=$e.data;break}($e.status===401||$e.status===403)&&(Me=!0),oe.push(`${Ce.label}: ${$e.error??"unavailable"}`)}if(!ie){if(Me){const se=new Error("Unauthorized. Update your OrgX API key in Settings (use a user-scoped oxk_... key; userId should be blank).");throw se.code="ORGX_AUTH",se}throw new Error(rc(oe))}if(Fe.current!==V)return;const ue=Array.isArray(ie.degraded)?ie.degraded.filter(se=>typeof se=="string"):[],R=ue.map(se=>se.toLowerCase()),$=(...se)=>R.some(Ce=>se.some($e=>Ce.includes($e))),X=Array.isArray(ie.activity)?ie.activity:[],te=Array.isArray(ie.handoffs)?ie.handoffs:[],Le=Array.isArray(ie.decisions)?ie.decisions:[],qe=X.length===0&&$("activity unavailable","activity local fallback failed"),_e=$("sessions unavailable","sessions local fallback failed"),M=te.length===0&&$("handoffs unavailable"),B=Le.length===0&&$("decisions unavailable"),ne=Ar(Array.isArray(ie.projections)?ie.projections:[]),fe=Br(ie.chat??null),De=fi(Array.isArray(ie.timelineNarrative)?ie.timelineNarrative:[]),et=hi(Array.isArray(ie.nextUpByInitiative)?ie.nextUpByInitiative:[]),tt=ne.length>0?Da(ne):qr(Array.isArray(ie.sliceRuns)?ie.sliceRuns:[]),Re=ie.sessions&&Array.isArray(ie.sessions.nodes)&&Array.isArray(ie.sessions.edges)&&Array.isArray(ie.sessions.groups)?ie.sessions:gc(X,ie.agents,l),Je=tt.length===0&&ne.length===0&&$("activity unavailable","sessions unavailable","decisions unavailable","next-up unavailable","next-up queue"),We=et.length===0&&$("next-up unavailable","next-up queue"),ft=qe?null:X,ot=M?null:te,nt=B?null:Le,we=_e&&Re.nodes.length===0?null:Re,Ge=Je?null:ne,je=Je?null:De,H=Je?null:tt,Oe=We?null:et;xe(we,ft,ot,nt,H,ie.outbox??null,ie.generatedAt??null,ie.runtimeInstances??null,fe,{workSliceProjections:Ge,timelineNarrative:je,nextUpByInitiative:Oe,runningWorkSlices:Je?null:ie.runningWorkSlices??null,needsInputTotal:Je?null:ie.needsInput??null,failedActionableTotal:Je?null:ie.failedActionable??null,completedTodayTotal:Je?null:ie.completedToday??null,consistencyFlags:Array.isArray(ie.consistencyFlags)?ie.consistencyFlags:null,dataHealth:ie.dataHealth??null});const U=ue.length>0?ac(ue):[];U.length>0?(W(`Partial live data: ${U.join("; ")}`),v(se=>se.connection==="connected"?se:{...se,connection:"connected"}),Z(!1)):(W(null),v(se=>se.connection==="connected"?se:{...se,connection:"connected"}))}catch(z){if(Fe.current!==V)return;const O=z instanceof Error?z.message:"Unknown error",oe=!!(z&&typeof z=="object"&&"code"in z&&z.code==="ORGX_AUTH");oe&&(ke.current=!0);const ie=ae.current>0&&Date.now()-ae.current>va;W(O),v(Me=>{const ue=oe||ie?"disconnected":"reconnecting";return Me.connection===ue?Me:{...Me,connection:ue}}),Z(!oe),g(!1)}finally{me.current===V&&(K.current=null,me.current=null)}})();return K.current=k,me.current=V,k},[xe,t,i,d,h,u,l,p,b,r]),le=o.useCallback(async(V,k,z)=>{var R,$,X;if(!i)throw new Error("OrgX decisions are unavailable while disconnected.");const O=Array.from(new Set(V.filter(Boolean)));if(O.length===0)return{updated:0,failed:0};const oe=((R=z==null?void 0:z.note)==null?void 0:R.trim())||void 0,ie=(($=z==null?void 0:z.optionId)==null?void 0:$.trim())||void 0;if(r){const te=new Set(O);return v(Le=>{const qe=Le.decisions.filter(ne=>te.has(ne.id));if(qe.length===0)return Le;const _e=new Date().toISOString(),M=qe.map(ne=>({id:`decision:${k}:${ne.id}:${Date.now()}`,type:"decision_resolved",title:k==="approve"?`Approved: ${ne.title}`:`Rejected: ${ne.title}`,description:ne.context,agentId:null,agentName:ne.agentName,requesterAgentId:null,requesterAgentName:ne.agentName??null,executorAgentId:null,executorAgentName:ne.agentName??null,runId:null,initiativeId:null,timestamp:_e,metadata:{decisionId:ne.id,action:k}})),B=mi(M.concat(Le.activity),d);return{...Le,decisions:Le.decisions.filter(ne=>!te.has(ne.id)),activity:B,lastActivity:It(_e)}}),{updated:te.size,failed:0,firstError:void 0}}const Me=new Date().toISOString(),ue=await fetch("/orgx/api/live/decisions/approve",{method:"POST",headers:_t({contentTypeJson:!0,workspaceId:p}),body:JSON.stringify({ids:O,action:k,...oe?{note:oe}:{},...ie?{option_id:ie}:{}})});try{const te=await ue.json().catch(()=>null),Le=Array.isArray(te==null?void 0:te.results)?te.results:[],qe=new Set(Le.filter(fe=>fe.ok).map(fe=>fe.id)),M=((X=Le.filter(fe=>!fe.ok).find(fe=>typeof fe.error=="string"&&fe.error.trim().length>0))==null?void 0:X.error)??(typeof(te==null?void 0:te.error)=="string"&&te.error.trim().length>0?te.error:void 0);if(!ue.ok&&ue.status!==207){const fe=M??`Decision action failed (${ue.status})`;throw new Error(fe)}if(qe.size===0&&ue.ok&&((te==null?void 0:te.failed)??0)===0)for(const fe of O)qe.add(fe);qe.size>0?v(fe=>{const De=fe.decisions.filter(We=>qe.has(We.id));if(De.length===0)return fe;const et=new Date().toISOString(),tt=De.map(We=>({id:`decision:${k}:${We.id}:${Date.now()}`,type:"decision_resolved",title:k==="approve"?`Approved: ${We.title}`:`Rejected: ${We.title}`,description:We.context,agentId:null,agentName:We.agentName,requesterAgentId:null,requesterAgentName:We.agentName??null,executorAgentId:null,executorAgentName:We.agentName??null,runId:null,initiativeId:null,timestamp:et,metadata:{decisionId:We.id,action:k}})),Re=mi(tt.concat(fe.activity),d);return{...fe,decisions:fe.decisions.filter(We=>!qe.has(We.id)),activity:Re,lastActivity:It(et)}}):ue.ok&&O.length>0&&v(fe=>({...fe,decisions:fe.decisions.filter(De=>!O.includes(De.id))})),re();const B=(te==null?void 0:te.updated)??qe.size,ne=(te==null?void 0:te.failed)??Math.max(0,O.length-qe.size);return Ae({phase:ne>0?"error":"success",action:k,targetCount:O.length,message:ne>0?`${k==="approve"?"Approve":"Reject"} completed with ${ne} failure${ne===1?"":"s"}.`:k==="approve"?`Approved ${B} decision${B===1?"":"s"}.`:`Rejected ${B} decision${B===1?"":"s"}.`,startedAt:Me,completedAt:new Date().toISOString()},{autoResetMs:ne>0?8e3:4e3}),{updated:B,failed:ne,firstError:M}}catch(te){throw Ae({phase:"error",action:k,targetCount:O.length,message:te instanceof Error?te.message:"Decision update failed.",startedAt:Me,completedAt:new Date().toISOString()}),te}},[i,re,d,p,Ae,r]),Ee=o.useCallback(async(V,k)=>le([V],"approve",k),[le]),ee=o.useCallback(async(V,k)=>le([V],"reject",k),[le]),q=o.useCallback(async()=>{let V=[];return v(k=>(V=k.decisions.map(z=>z.id),k)),V.length===0?{updated:0,failed:0}:le(V,"approve")},[le]),J=o.useCallback(async(V,k,z)=>le(V,k,z?{note:z}:void 0),[le]);return o.useEffect(()=>{i||Ae(Nr)},[i,Ae]),o.useEffect(()=>{if(!t){Z(!1),g(!1),W(null);return}if(r){re();return}if(re(),p){Z(!0);return}const V=new URLSearchParams;p&&us(V,p),b&&V.set("initiative",b);const k=V.toString()?`/orgx/api/live/stream?${V.toString()}`:"/orgx/api/live/stream",z=new EventSource(k),O=new EventSource("/orgx/api/hooks/runtime/stream");let oe=null,ie=null,Me=null,ue=null,R=[],$=null,X;const te=()=>{if(X=void 0,oe){ae.current=Date.now(),ke.current=!1;const _e=oe;oe=null,Me=null,ue=null,R=[],$=null,ie=null,xe(_e.sessions,_e.activity,_e.handoffs,_e.decisions,_e.sliceRuns,_e.outbox,_e.generatedAt,_e.runtimeInstances,_e.chat,_e.v2);return}!Me&&!ue&&!$&&!ie&&R.length===0||(ae.current=Date.now(),ke.current=!1,v(_e=>{var B;let M=_e;if(Me){const ne=nr(Me,l),fe=nr(Ia(M.sessions,ne),l);Me=null,Sa(M.sessions,fe)||(M={...M,sessions:fe})}if(ue){const ne=Aa(ue,u);ue=null,_a(M.handoffs,ne)||(M={...M,handoffs:ne})}if($){const ne=Ma($,h);$=null,Ca(M.decisions,ne)||(M={...M,decisions:ne})}if(ie){const ne=Ea(ie);ie=null,Ra(M.runtimeInstances,ne)||(M={...M,runtimeInstances:ne})}if(R.length>0){const ne=pc(M.activity,R,d);R=[],ne!==M.activity&&(M={...M,activity:ne,lastActivity:(B=ne[0])!=null&&B.timestamp?It(ne[0].timestamp):M.lastActivity})}return M===_e?_e:M.connection==="connected"?M:{...M,connection:"connected"}}),W(null),g(!1))},Le=()=>{X||(X=setTimeout(te,y))};z.onopen=()=>{ae.current=Date.now(),ke.current=!1,Z(!1),v(_e=>_e.connection==="connected"?_e:{..._e,connection:"connected"}),W(null)},z.onerror=()=>{if(ke.current){v(M=>M.connection==="disconnected"?M:{...M,connection:"disconnected"}),Z(!1);return}const _e=ae.current>0&&Date.now()-ae.current>va;v(M=>M.connection===(_e?"disconnected":"reconnecting")?M:{...M,connection:_e?"disconnected":"reconnecting"}),Z(!0)},z.addEventListener("snapshot",_e=>{try{const M=JSON.parse(_e.data),B=typeof M.generatedAt=="string"&&M.generatedAt.length>0?M.generatedAt:new Date().toISOString();oe={sessions:M.sessions,activity:M.activity??[],handoffs:M.handoffs??[],decisions:M.decisions??null,sliceRuns:Array.isArray(M.sliceRuns)?qr(M.sliceRuns):Array.isArray(M.projections)?Da(Ar(M.projections)):null,outbox:M.outbox??null,generatedAt:B,runtimeInstances:Array.isArray(M.runtimeInstances)?M.runtimeInstances:null,chat:Br(M.chat??null),v2:{workSliceProjections:Array.isArray(M.projections)?Ar(M.projections):null,timelineNarrative:Array.isArray(M.timelineNarrative)?fi(M.timelineNarrative):null,nextUpByInitiative:Array.isArray(M.nextUpByInitiative)?hi(M.nextUpByInitiative):null,runningWorkSlices:typeof M.runningWorkSlices=="number"?M.runningWorkSlices:null,needsInputTotal:typeof M.needsInput=="number"?M.needsInput:null,failedActionableTotal:typeof M.failedActionable=="number"?M.failedActionable:null,completedTodayTotal:typeof M.completedToday=="number"?M.completedToday:null,consistencyFlags:Array.isArray(M.consistencyFlags)?M.consistencyFlags:null,dataHealth:M.dataHealth??null}},Le()}catch(M){W(M instanceof Error?M.message:"Invalid snapshot")}}),z.addEventListener("activity.appended",_e=>{try{const M=JSON.parse(_e.data);if(M.length===0)return;R=R.concat(M),Le()}catch{}}),z.addEventListener("session.updated",_e=>{try{Me=JSON.parse(_e.data),Le()}catch{}});const qe=_e=>{try{const M=JSON.parse(_e.data);ie=Array.isArray(M)?M:[M],Le()}catch{}};return z.addEventListener("runtime.updated",qe),O.addEventListener("runtime.updated",qe),z.addEventListener("handoff.updated",_e=>{try{ue=JSON.parse(_e.data),Le()}catch{}}),z.addEventListener("decision.updated",_e=>{try{$=JSON.parse(_e.data),Le()}catch{}}),()=>{X&&clearTimeout(X),z.close(),O.close()}},[xe,y,t,i,re,d,h,u,l,b,p,r]),o.useEffect(()=>{if(!(!t||r||(Y.current&&clearInterval(Y.current),!ge&&!!!p)))return Y.current=setInterval(re,s),()=>{Y.current&&clearInterval(Y.current)}},[t,re,p,s,ge,r]),{data:w,isLoading:j,error:S,refetch:re,approveDecision:Ee,rejectDecision:ee,approveAllDecisions:q,bulkDecisionAction:J,decisionMutation:x}}const xr=[{id:"live",label:"Last hour",minutes:null},{id:"24h",label:"Today",minutes:null},{id:"7d",label:"This week",minutes:10080},{id:"custom",label:"Custom",minutes:null},{id:"all",label:"All",minutes:null}];function Ko(e){return xr.find(t=>t.id===e)??xr[0]}function yr(e,t=Date.now()){if(e==="all")return null;if(e==="live")return t-60*6e4;if(e==="24h"){const r=new Date(t);return r.setHours(0,0,0,0),r.getTime()}if(e==="custom")return null;const s=xr.find(r=>r.id===e);return!s||s.minutes===null?null:t-s.minutes*6e4}function _c(e,t=Date.now()){const s=yr(e,t);return s?new Date(s).toISOString():null}const Cc=new Set(["ungrouped","unscoped","unknown"]),Mc="orgx.demo_mode",Tc="orgx.show_synthetic_entities";function Es(e){const t=(e??"").trim().toLowerCase();return!!(!t||Cc.has(t)||/^init-\d+$/.test(t)||t.startsWith("mock-"))}function $t(){if(typeof window>"u")return!1;try{if(new URLSearchParams(window.location.search).get("demo")==="1")return!0}catch{}try{return window.localStorage.getItem(Mc)==="1"}catch{return!1}}function Ec(){if(typeof window>"u")return!1;if($t())return!0;try{return window.localStorage.getItem(Tc)==="1"}catch{return!1}}function Rc(e){return $t()?!0:!Es(e)}function Hi(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Go(e,t){const s=Hi(t.timestamp)-Hi(e.timestamp);return s!==0?s:String(t.id).localeCompare(String(e.id))}function Dc(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Lc(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r!="string")continue;const i=r.trim();if(i.length>0)return i}return null}function Xo(e){const t=typeof e.initiativeId=="string"?e.initiativeId.trim():"";if(t.length>0)return t;const s=Dc(e.metadata);return Lc(s,["initiative_id","initiativeId"])}function gi(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Vi(e,t){if(Object.is(e,t))return!0;if(typeof e!=typeof t)return!1;if(e===null||t===null)return e===t;if(typeof e!="object")return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let c=0;c<e.length;c+=1)if(!Vi(e[c],t[c]))return!1;return!0}const s=e,r=t,i=Object.keys(s).sort(),a=Object.keys(r).sort();if(i.length!==a.length)return!1;for(let c=0;c<i.length;c+=1){const l=i[c];if(l!==a[c]||!Vi(s[l],r[l]))return!1}return!0}const Fc=typeof window<"u"&&/[?&]debug_feed/.test(window.location.search);function Us(e,...t){}function $c(e,t,s,r){const i=new Map,a=t.sinceEpoch,c=t.untilEpoch;let l=0,d=0,u=0;for(const h of e??[]){if(!h||typeof h.id!="string")continue;if(s&&h.runId!==s){l++;continue}if(r&&Xo(h)!==r){d++;continue}const y=Hi(h.timestamp);if(y){if(a!==null&&y<a){u++;continue}if(c!==null&&y>c){u++;continue}i.set(h.id,h)}}return Us("normalizeSeed",{inputCount:(e==null?void 0:e.length)??0,outputCount:i.size,runId:s,initiativeId:r,skippedRun:l,skippedInitiative:d,skippedTime:u,sinceEpoch:a?new Date(a).toISOString():null,untilEpoch:c?new Date(c).toISOString():null}),Array.from(i.values()).sort(Go)}function La(e,t){if(t.length===0)return e;const s=new Map;for(const c of e)s.set(c.id,c);let r=0,i=0,a=!1;for(const c of t){const l=s.get(c.id);if(!l){s.set(c.id,c),a=!0,r++;continue}(l.timestamp!==c.timestamp||l.type!==c.type||l.title!==c.title||l.description!==c.description||l.summary!==c.summary||!Vi(l.metadata??null,c.metadata??null))&&(s.set(c.id,c),a=!0,i++)}return Us("mergeById",{currentCount:e.length,incomingCount:t.length,added:r,updated:i,changed:a,resultCount:s.size}),a?Array.from(s.values()).sort(Go):e}function Pc(e){const{seed:t,timeFilterId:s,customSinceIso:r=null,customUntilIso:i=null,runId:a=null,initiativeId:c=null,projectId:l=null,pageSize:d=50,demoMode:u=$t()}=e,h=o.useMemo(()=>gi(a),[a]),y=o.useMemo(()=>gi(c),[c]),b=o.useMemo(()=>gi(l),[l]),p=o.useMemo(()=>yr(s),[s]),w=o.useMemo(()=>_c(s),[s]),v=o.useMemo(()=>{if(s==="custom"){const q=(r==null?void 0:r.trim())??"";return q.length>0?q:null}return w},[r,w,s]),x=o.useMemo(()=>{if(s!=="custom")return null;const q=(i==null?void 0:i.trim())??"";return q.length>0?q:null},[i,s]),C=o.useMemo(()=>{if(v){const q=Date.parse(v);if(Number.isFinite(q))return q}return p},[p,v]),j=o.useMemo(()=>{if(!x)return null;const q=Date.parse(x);return Number.isFinite(q)?q:null},[x]),g=o.useMemo(()=>$c(t,{sinceEpoch:C,untilEpoch:j},h,y),[t,C,j,h,y]),S=u?null:"",[W,Y]=o.useState(g),[K,me]=o.useState(()=>S),[ge,Z]=o.useState(!1),[ae,ke]=o.useState(null),[Fe,G]=o.useState(null),Se=o.useRef(null),Ae=o.useRef(!1),xe=o.useRef(g);xe.current=g;const re=o.useMemo(()=>`${h??""}|${y??""}|${s}|${v??""}|${x??""}|${b??""}|${u?"demo":"live"}`,[h,y,s,v,x,b,u]),le=o.useRef(re);o.useEffect(()=>{le.current!==re&&(le.current=re,Us("RESET",{reason:"filter/run change",runId:h,initiativeId:y,projectId:b,timeFilterId:s,sinceIso:v,untilIso:x,seedCount:xe.current.length}),Y(xe.current),me(S),ke(null),G(null),Ae.current=!1)},[re,S,h,y,b,s,v,x]),o.useEffect(()=>{Y(q=>{const J=La(q,g);return J!==q&&Us("SSE_MERGE",{prevCount:q.length,seedCount:g.length,nextCount:J.length,delta:J.length-q.length}),J})},[g]);const Ee=o.useCallback(async()=>{if(u){me(null),ke(null);return}if(K===null)return;if(Se.current)return Se.current;Z(!0);const q=(async()=>{try{const J=new URLSearchParams;J.set("limit",String(Math.max(1,Math.min(500,d)))),K.trim().length>0&&J.set("cursor",K),v&&J.set("since",v),x&&J.set("until",x),h&&J.set("run",h),y&&J.set("initiative",y),b&&us(J,b);const V=await fetch(`/orgx/api/live/activity/page?${J.toString()}`,{headers:_t({workspaceId:b})}),k=await V.json().catch(()=>null);if(!V.ok||!k){const oe=typeof(k==null?void 0:k.error)=="string"&&k.error.trim()||typeof(k==null?void 0:k.message)=="string"&&k.message.trim()||`Activity paging failed (${V.status})`;throw new Error(oe)}const z=Array.isArray(k.activities)?k.activities:[],O=z.filter(oe=>!y||Xo(oe)===y);Us("PAGE_FETCH",{cursor:K,rawCount:z.length,afterFilter:O.length,filteredOut:z.length-O.length,initiativeId:y,runId:h,nextCursor:k.nextCursor??null}),Y(oe=>{const ie=La(oe,O);return Us("PAGE_MERGE",{prevCount:oe.length,pageCount:O.length,nextCount:ie.length,added:ie.length-oe.length}),ie}),me(k.nextCursor??null),G(k.storeUpdatedAt??null),ke(null)}catch(J){const V=J instanceof Error?J.message:"";ke(V?bn(V):"Activity paging failed"),me(k=>k===""?null:k)}finally{Z(!1),Se.current=null}})();return Se.current=q,q},[K,u,y,d,b,h,v,x]);return o.useEffect(()=>{K===""&&(Ae.current||(Ae.current=!0,Ee()))},[K,Ee]),{items:W,hasMore:K!==null,isLoadingMore:ge,error:ae,storeUpdatedAt:Fe,loadMore:Ee,cutoffEpoch:C,sinceIso:v,untilIso:x}}const Oc="phc_s4KPgkYEFZgvkMYw4zXG41H5FN6haVwbEWPYHfNjxOc",Bc="".trim().toLowerCase()==="true"||"".trim()==="1",qc="".trim().toLowerCase()==="true"||"".trim()==="1",zc={api_host:"https://us.i.posthog.com",defaults:"2026-01-30",person_profiles:"identified_only"};let xi=null,Fa=!1,$a=!1,ia=!1;function Uc(){if(typeof window>"u")return!1;const e=window.location.hostname.trim().toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function ri(){return ia||!Bc?!1:qc?!0:!Uc()}function Wc(){return ri()?(xi||(xi=qt(()=>import("./BgOYB78t.js"),[]).then(e=>e.default).catch(()=>(ia=!0,null))),xi):Promise.resolve(null)}function Hc(e){if(Fa)return!0;try{return e.init(Oc,zc),Fa=!0,!0}catch{return ia=!0,!1}}async function aa(){const e=await Wc();return!e||!Hc(e)?null:e}function Vc(e){if(typeof window>"u")return;const t=window;if(typeof t.requestIdleCallback=="function"){t.requestIdleCallback(()=>e(),{timeout:1500});return}window.setTimeout(e,1)}function Kc(){!ri()||typeof window>"u"||$a||($a=!0,Vc(()=>{aa()}))}function Gc(e){if(!ri())return;const t=e.trim();t&&aa().then(s=>{if(s)try{s.identify(t)}catch{}})}function rs(e,t){ri()&&e.trim()&&aa().then(s=>{if(s)try{s.capture(e,t)}catch{}})}const Xc="https://orgx.mintlify.site/guides/openclaw-plugin-setup",Qc=1500,yi="orgx.onboarding.skip",Jc=680,Yc=`<!doctype html>
3
+ <html lang="en">
4
+ <head>
5
+ <meta charset="utf-8" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
7
+ <title>Connecting to OrgX</title>
8
+ <style>
9
+ :root {
10
+ --bg: #02040a;
11
+ --surface: #0c0e14;
12
+ --surface-soft: #0f121a;
13
+ --line: rgba(255, 255, 255, 0.1);
14
+ --text: #f2f7ff;
15
+ --muted: rgba(242, 247, 255, 0.62);
16
+ --lime: #bfff00;
17
+ --teal: #14b8a6;
18
+ --iris: #7c7cff;
19
+ }
20
+
21
+ * { box-sizing: border-box; }
22
+
23
+ body {
24
+ margin: 0;
25
+ min-height: 100vh;
26
+ background:
27
+ radial-gradient(920px 460px at 14% 14%, rgba(124, 124, 255, 0.12), transparent 68%),
28
+ radial-gradient(840px 420px at 84% 88%, rgba(20, 184, 166, 0.12), transparent 72%),
29
+ var(--bg);
30
+ color: var(--text);
31
+ font-family: "SF Pro Text", "SF Pro Display", Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
32
+ display: grid;
33
+ place-items: center;
34
+ padding: 24px;
35
+ }
36
+
37
+ .shell {
38
+ width: min(640px, 100%);
39
+ border-radius: 22px;
40
+ border: 1px solid var(--line);
41
+ background:
42
+ linear-gradient(180deg, rgba(255, 255, 255, 0.04), rgba(255, 255, 255, 0.015)),
43
+ var(--surface);
44
+ box-shadow:
45
+ 0 28px 80px rgba(0, 0, 0, 0.58),
46
+ inset 0 1px 0 rgba(255, 255, 255, 0.05);
47
+ overflow: hidden;
48
+ }
49
+
50
+ .header {
51
+ display: flex;
52
+ align-items: center;
53
+ justify-content: space-between;
54
+ gap: 12px;
55
+ padding: 16px 18px;
56
+ border-bottom: 1px solid rgba(255, 255, 255, 0.08);
57
+ background: rgba(0, 0, 0, 0.16);
58
+ }
59
+
60
+ .brand {
61
+ display: inline-flex;
62
+ align-items: center;
63
+ gap: 10px;
64
+ }
65
+
66
+ .brand-mark {
67
+ width: 22px;
68
+ height: 22px;
69
+ color: var(--lime);
70
+ opacity: 0.95;
71
+ }
72
+
73
+ .brand-name {
74
+ font-size: 14px;
75
+ font-weight: 700;
76
+ letter-spacing: 0.01em;
77
+ color: rgba(242, 247, 255, 0.92);
78
+ }
79
+
80
+ .chip {
81
+ display: inline-flex;
82
+ align-items: center;
83
+ gap: 6px;
84
+ border: 1px solid rgba(191, 255, 0, 0.3);
85
+ background: rgba(191, 255, 0, 0.12);
86
+ color: #d8ffa1;
87
+ border-radius: 999px;
88
+ padding: 4px 10px;
89
+ font-size: 11px;
90
+ font-weight: 600;
91
+ letter-spacing: 0.06em;
92
+ text-transform: uppercase;
93
+ }
94
+
95
+ .dot {
96
+ width: 7px;
97
+ height: 7px;
98
+ border-radius: 50%;
99
+ background: var(--lime);
100
+ box-shadow: 0 0 0 0 rgba(191, 255, 0, 0.56);
101
+ animation: pulse 1.6s infinite ease-out;
102
+ }
103
+
104
+ .content {
105
+ padding: 20px 20px 18px;
106
+ }
107
+
108
+ h1 {
109
+ margin: 0;
110
+ font-size: 24px;
111
+ line-height: 1.18;
112
+ letter-spacing: -0.02em;
113
+ }
114
+
115
+ .subtitle {
116
+ margin: 8px 0 0;
117
+ color: var(--muted);
118
+ font-size: 14px;
119
+ line-height: 1.5;
120
+ }
121
+
122
+ .steps {
123
+ margin-top: 16px;
124
+ display: grid;
125
+ gap: 8px;
126
+ }
127
+
128
+ .step {
129
+ display: flex;
130
+ align-items: center;
131
+ gap: 9px;
132
+ border: 1px solid rgba(255, 255, 255, 0.08);
133
+ background: var(--surface-soft);
134
+ border-radius: 12px;
135
+ padding: 10px 12px;
136
+ font-size: 12px;
137
+ }
138
+
139
+ .step svg {
140
+ flex-shrink: 0;
141
+ width: 14px;
142
+ height: 14px;
143
+ }
144
+
145
+ .meta {
146
+ margin-top: 12px;
147
+ padding-top: 12px;
148
+ border-top: 1px solid rgba(255, 255, 255, 0.08);
149
+ color: rgba(242, 247, 255, 0.42);
150
+ font-size: 11px;
151
+ }
152
+
153
+ @keyframes pulse {
154
+ 0% { box-shadow: 0 0 0 0 rgba(191, 255, 0, 0.56); }
155
+ 100% { box-shadow: 0 0 0 12px rgba(191, 255, 0, 0); }
156
+ }
157
+ </style>
158
+ </head>
159
+ <body>
160
+ <main class="shell">
161
+ <header class="header">
162
+ <div class="brand">
163
+ <svg class="brand-mark" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
164
+ <path d="M5.5 7h5.8l6.7 6"></path>
165
+ <path d="M5.5 17h5.8l6.7-6"></path>
166
+ <path d="M5.5 12h12.5"></path>
167
+ <path d="m15.3 9.3 2.7 2.7-2.7 2.7"></path>
168
+ </svg>
169
+ <span class="brand-name">OrgX</span>
170
+ </div>
171
+ <div class="chip"><span class="dot"></span>Pairing</div>
172
+ </header>
173
+ <section class="content">
174
+ <h1>Connecting to OrgX</h1>
175
+ <p class="subtitle">Preparing a secure workspace session. This window will continue automatically.</p>
176
+ <div class="steps">
177
+ <div class="step">
178
+ <svg viewBox="0 0 24 24" fill="none" stroke="#7C7CFF" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
179
+ <circle cx="12" cy="12" r="9"></circle>
180
+ <circle cx="12" cy="12" r="4.5"></circle>
181
+ </svg>
182
+ <span>Initializing plugin handshake</span>
183
+ </div>
184
+ <div class="step">
185
+ <svg viewBox="0 0 24 24" fill="none" stroke="#14B8A6" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
186
+ <path d="M5 3v18"></path>
187
+ <path d="m5 4 12 1-2 4 2 4-12-1z"></path>
188
+ </svg>
189
+ <span>Opening browser approval for this workspace</span>
190
+ </div>
191
+ <div class="step">
192
+ <svg viewBox="0 0 24 24" fill="none" stroke="#BFFF00" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
193
+ <rect x="4" y="4" width="16" height="16" rx="4"></rect>
194
+ <path d="M9 12.2 11 14.2 15.2 10"></path>
195
+ </svg>
196
+ <span>Syncing initiatives, tasks, and decisions</span>
197
+ </div>
198
+ </div>
199
+ <div class="meta">If redirect does not start, return to OpenClaw and click “Approve in browser”.</div>
200
+ </section>
201
+ </main>
202
+ </body>
203
+ </html>`,zr={status:"idle",hasApiKey:!1,connectionVerified:!1,workspaceName:null,lastError:null,nextAction:"connect",docsUrl:Xc,keySource:"none",installationId:null,connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null};function Os(){return{...zr,status:"connected",hasApiKey:!0,connectionVerified:!0,workspaceName:"Demo Workspace",nextAction:"open_dashboard",keySource:"legacy-dev",lastError:null}}function Zc(e){if(typeof e=="string")return e;if(e&&typeof e=="object")return JSON.stringify(e)}async function sr(e){const t=await e,s=await t.json().catch(()=>null);return t.ok?s??{}:{ok:!1,error:Zc(s==null?void 0:s.error)??`Request failed (${t.status})`}}function Sr(e){if(e)try{Gc(e)}catch{}}function ed(){const[e,t]=o.useState(()=>$t()?Os():zr),[s,r]=o.useState(()=>!$t()),[i,a]=o.useState(!1),[c,l]=o.useState(!1),d=o.useRef(null),[u,h]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(yi)==="1"),y=o.useCallback(async()=>{if($t()){const g=Os();return t(g),g}const j=await sr(fetch("/orgx/api/onboarding/status",{method:"GET"}));if(!j.ok||!j.data){const g=j.error??"Failed to load onboarding state",S={...zr,status:"error",lastError:g,nextAction:"retry"};return t(S),S}return Sr(j.data.installationId??null),t(j.data),j.data},[]);o.useEffect(()=>{if($t()){t(Os()),r(!1);return}let j=!1;return(async()=>{r(!0);const g=await y();j||(t(g),r(!1))})(),()=>{j=!0}},[y]),o.useEffect(()=>{if(!(e.status==="awaiting_browser_auth"||e.status==="pairing"))return;const g=Math.max(900,e.pollIntervalMs??Qc),S=window.setInterval(async()=>{const W=await sr(fetch("/orgx/api/onboarding/status",{method:"GET"}));W.ok&&W.data&&(Sr(W.data.installationId??null),t(W.data))},g);return()=>{window.clearInterval(S)}},[e.pollIntervalMs,e.status]),o.useEffect(()=>{if(!(typeof window>"u")){if(u){window.localStorage.setItem(yi,"1");return}window.localStorage.removeItem(yi)}},[u]);const b=o.useCallback(()=>{if(typeof window>"u")return null;try{const j=window.open("","_blank");return j?(j.opener=null,j.document.title="Connecting to OrgX…",j.document.open(),j.document.write(Yc),j.document.close(),j):null}catch{return null}},[]),p=o.useCallback(async()=>{if($t()){const g=Os();t(g);return}const j=b();d.current=j,a(!0);try{const g=await sr(fetch("/orgx/api/onboarding/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceName:navigator.platform||"OpenClaw Device",platform:navigator.platform})})),S=g.data;if(!g.ok||!(S!=null&&S.state)){j&&!j.closed&&j.close();const Y=g.error??"Could not start pairing";t(K=>({...K,status:"error",lastError:Y,nextAction:"enter_manual_key"}));return}t(S.state);const W=S.connectUrl;if(W){const Y=d.current;let K=!1;if(Y&&!Y.closed)try{window.setTimeout(()=>{if(!Y.closed)try{Y.location.href=W}catch{}},Jc),K=!0}catch{K=!1}K||(K=!!window.open(W,"_blank","noopener,noreferrer")),K||t(me=>({...me,lastError:'Popup was blocked. Use "Approve in browser" below.',nextAction:"open_browser"}))}}finally{d.current=null,a(!1)}},[b]),w=o.useCallback(async j=>{if($t()){const g=Os();return t(g),g}l(!0);try{const g=j.trim(),S=g.replace(/^[a-z]+_/i,""),W=Array.from(new Set([g,S?`oxk_${S}`:"",S?`orgx_${S}`:""].map(K=>K.trim()).filter(K=>K.length>0)));let Y="Manual key validation failed";for(const K of W){const me={"Content-Type":"application/json","X-OrgX-Api-Key":K,Authorization:`Bearer ${K}`},ge=await sr(fetch("/orgx/api/onboarding/manual-key",{method:"POST",headers:me,body:JSON.stringify({apiKey:K})}));if(ge.ok&&ge.data)return Sr(ge.data.installationId??null),t(ge.data),ge.data;Y=ge.error??Y}throw t(K=>({...K,status:"manual_key",lastError:Y,nextAction:"enter_manual_key"})),new Error(Y)}finally{l(!1)}},[]),v=o.useCallback(async()=>{if($t()){const S=Os();return t(S),S}const j=await sr(fetch("/orgx/api/onboarding/disconnect",{method:"POST"}));if(j.ok&&j.data)return Sr(j.data.installationId??null),t(j.data),j.data;const g={...zr,status:"idle"};return t(g),g},[]),x=o.useCallback(()=>{t(j=>({...j,status:"idle",lastError:null,nextAction:"connect",connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null}))},[]),C=o.useMemo(()=>$t()||u?!1:!(e.hasApiKey&&e.connectionVerified&&e.status==="connected"),[u,e.connectionVerified,e.hasApiKey,e.status]);return{state:e,showGate:C,isLoading:s,isStarting:i,isSubmittingManual:c,refreshStatus:y,startPairing:p,submitManualKey:w,disconnect:v,skipGate:()=>h(!0),resumeGate:()=>h(!1),backToPairing:x,setManualMode:()=>t(j=>({...j,status:"manual_key",nextAction:"enter_manual_key"}))}}const Gn={liveData:e=>["live-data",{authToken:e.authToken??null,embedMode:e.embedMode??!1,useMock:e.useMock??!1,projectId:e.projectId??null}],sessions:e=>["sessions",{activeMinutes:e.activeMinutes??null,limit:e.limit??null,authToken:e.authToken??null,embedMode:e.embedMode??!1}],initiativeDetails:e=>["initiative-details",{initiativeId:e.initiativeId,authToken:e.authToken??null,embedMode:e.embedMode??!1}],entities:e=>["entities",{type:e.type,authToken:e.authToken??null,embedMode:e.embedMode??!1,projectId:e.projectId??null}],missionControlGraph:e=>["mission-control-graph",{initiativeId:e.initiativeId,authToken:e.authToken??null,embedMode:e.embedMode??!1}],missionControlSlices:e=>{var t;return["mission-control-slices",{workspaceId:e.workspaceId??null,initiativeId:e.initiativeId??null,level:e.level,orderMode:e.orderMode??null,includeCompleted:e.includeCompleted??!1,search:((t=e.search)==null?void 0:t.trim().toLowerCase())??"",offset:Math.max(0,e.offset??0),limit:Math.max(1,e.limit??24),authToken:e.authToken??null,embedMode:e.embedMode??!1}]},nextUpQueue:e=>["mission-control-next-up",{initiativeId:e.initiativeId??null,authToken:e.authToken??null,embedMode:e.embedMode??!1,projectId:e.projectId??null,offset:Math.max(0,e.offset??0),limit:Math.max(1,Math.min(300,e.limit??24))}],autoContinueStatus:e=>["auto-continue-status",{initiativeId:e.initiativeId,authToken:e.authToken??null,embedMode:e.embedMode??!1}],liveInitiatives:e=>["live-initiatives",{limit:(e==null?void 0:e.limit)??300,projectId:(e==null?void 0:e.projectId)??null}],initiativeSearch:e=>["initiative-search",{query:e.query.trim().toLowerCase(),projectId:e.projectId??null}],artifactsByEntity:e=>["artifacts-by-entity",{entityType:e.entityType,entityId:e.entityId,authToken:e.authToken??null,embedMode:e.embedMode??!1}],artifactDetail:e=>["artifact-detail",{artifactId:e.artifactId,authToken:e.authToken??null,embedMode:e.embedMode??!1}],triageQueue:e=>["triage-queue",{workspaceId:e.workspaceId??null,status:e.status??"open",authToken:e.authToken??null,embedMode:e.embedMode??!1}]};class td extends Error{constructor(s,r){super(s);er(this,"code","upgrade_required");er(this,"currentPlan");er(this,"requiredPlan");er(this,"actions");this.name="UpgradeRequiredError",this.currentPlan=(r==null?void 0:r.currentPlan)??null,this.requiredPlan=((r==null?void 0:r.requiredPlan)??"starter").trim()||"starter",this.actions=(r==null?void 0:r.actions)??null}}function nd(e){if(!e||typeof e!="object")return null;const t=e;if(t.code!=="upgrade_required")return null;const s=typeof t.error=="string"&&t.error.trim()?t.error.trim():"Upgrade required.";return new td(s,{currentPlan:typeof t.currentPlan=="string"&&t.currentPlan.trim()?t.currentPlan.trim():null,requiredPlan:typeof t.requiredPlan=="string"&&t.requiredPlan.trim()?t.requiredPlan.trim():null,actions:t.actions??null})}function fh(e){const t=(e??"").trim().toLowerCase();return t?t==="free"?"Free":t==="starter"?"Starter":t==="team"?"Team":t==="enterprise"?"Enterprise":t[0].toUpperCase()+t.slice(1):"Unknown"}const sd=750;async function rr(e){return await e.json().catch(()=>null)}function rd(e,t){if(e.status!==404)return!1;const s=typeof(t==null?void 0:t.error)=="string"?t.error:"",r=typeof(t==null?void 0:t.message)=="string"?t.message:"";return/unknown api endpoint/i.test(`${s} ${r}`)}function _r(e,t,s){if(rd(e,t))return`${s}. This queue route is unavailable in the running plugin build.`;if(e.status===401||e.status===403)return`${s}. Reconnect OrgX authentication in Settings.`;if(e.status>=500)return`${s}. OrgX is temporarily unavailable.`;const r=typeof(t==null?void 0:t.error)=="string"&&t.error.trim()||typeof(t==null?void 0:t.message)=="string"&&t.message.trim()||s;return bn(r)}function id(e,t){const s=e instanceof Error?e.message:"",r=s.trim().toLowerCase();return r.includes("timed out")||r.includes("timeout")||r.includes("request cancelled")||r.includes("signal is aborted")?`${t}. Request timed out while waiting for queue data.`:r.includes("failed to fetch")||r.includes("network")?`${t}. Unable to reach the queue service right now.`:s?bn(s):t}function ad(e){const t=new Date().toISOString(),s=[{initiativeId:"init-1",initiativeTitle:"Q4 Feature Ship",initiativeStatus:"active",initiativePriority:"high",initiativePriorityNum:25,workstreamId:"ws-4",workstreamTitle:"Dashboard UI pass",workstreamStatus:"active",nextTaskId:"task-1",nextTaskTitle:"Polish timeline controls",nextTaskPriority:1,nextTaskDueAt:null,runnerAgentId:"dana",runnerAgentName:"Dana",runnerAgents:[{id:"dana",name:"Dana"}],runnerSource:"assigned",queueState:"running",blockReason:null,queueOrigin:"system",autoContinue:{status:"running",activeTaskId:"task-1",activeRunId:"run-2",stopReason:null,updatedAt:t}},{initiativeId:"init-2",initiativeTitle:"Black Friday Email",initiativeStatus:"active",initiativePriority:"medium",initiativePriorityNum:50,workstreamId:"ws-9",workstreamTitle:"Email campaign generation",workstreamStatus:"queued",nextTaskId:"task-2",nextTaskTitle:"Draft launch variants",nextTaskPriority:2,nextTaskDueAt:null,runnerAgentId:"mark",runnerAgentName:"Mark",runnerAgents:[{id:"mark",name:"Mark"}],runnerSource:"assigned",queueState:"queued",blockReason:null,queueOrigin:"system",autoContinue:{status:"stopped",activeTaskId:null,activeRunId:null,stopReason:null,updatedAt:t}}],r=typeof e=="string"&&e.trim().length>0?s.filter(i=>i.initiativeId===e.trim()):s;return Ur({ok:!0,generatedAt:t,total:r.length,items:r,pagination:{offset:0,limit:r.length||1,total:r.length,nextCursor:null,hasMore:!1},degraded:[]})}function od(e){var s,r;const t=((s=e.autoContinue)==null?void 0:s.status)??"stopped";return t==="running"?"running":t==="stopping"?"stopping":((r=e.autoContinue)==null?void 0:r.stopReason)==="error"?"error":"idle"}function ld(e){if(!e.autoContinue)return!1;const t=e.autoContinue.status;if(t!=="running"&&t!=="stopping"||e.autoContinue.stopReason==="error")return!1;if(e.queueState==="running"||e.queueState==="blocked")return!0;const s=!!(e.autoContinue.activeRunId||e.autoContinue.activeTaskId),r=!!(Array.isArray(e.autoContinue.activeRunIds)&&e.autoContinue.activeRunIds.length>0);if(s||r)return!0;const i=Date.parse(e.autoContinue.updatedAt??"");return Number.isFinite(i)?Date.now()-i<=45e3:!1}function oa(e){const t=typeof e=="string"?e.trim():"";if(!t)return"unassigned";const s=t.toLowerCase();return s==="undefined"||s==="null"||s==="main"?"unassigned":t}function la(e,t){const s=typeof e=="string"?e.trim():"";if(!s)return t==="unassigned"?"Unassigned":t;const r=s.toLowerCase();return r==="undefined"||r==="null"||r==="main"&&t==="unassigned"?t==="unassigned"?"Unassigned":t:s}function Qo(e,t,s){if(!Array.isArray(e))return t==="unassigned"?[]:[{id:t,name:s}];const r=[],i=new Set;for(const a of e){if(!a||typeof a!="object"||Array.isArray(a))continue;const c=a,l=oa(typeof c.id=="string"?c.id:null),d=la(typeof c.name=="string"?c.name:null,l);if(l==="unassigned"&&d==="Unassigned")continue;const u=l.toLowerCase();i.has(u)||(i.add(u),r.push({id:l,name:d}))}return r.length===0&&t!=="unassigned"?[{id:t,name:s}]:r}function cd(e,t){return e==="assigned"||e==="inferred"||e==="fallback"?e:t==="unassigned"?"fallback":"inferred"}function dd(e){const t=oa(e.runnerAgentId),s=la(e.runnerAgentName,t),r=Qo(e.runnerAgents,t,s),i=r[0]??null,a=(i==null?void 0:i.id)??t,c=(i==null?void 0:i.name)??s,l=cd(e.runnerSource,a),d=Array.isArray(e.sliceTaskIds)&&e.sliceTaskIds.length>0?e.sliceTaskIds.filter(h=>typeof h=="string"&&h.trim().length>0):e.nextTaskId?[e.nextTaskId]:[],u=e.sliceScope==="workstream"||e.sliceScope==="milestone"||e.sliceScope==="task"?e.sliceScope:null;return{...e,runnerAgentId:a,runnerAgentName:c,runnerAgents:r,runnerSource:l,playbackState:e.queueState,autoIntentEnabled:ld(e),autoRuntimeState:od(e),queueOrigin:e.queueOrigin??"system",sliceScope:u,sliceTaskIds:d,sliceTaskCount:typeof e.sliceTaskCount=="number"&&Number.isFinite(e.sliceTaskCount)?Math.max(0,Math.floor(e.sliceTaskCount)):d.length,executionPolicy:e.executionPolicy??null}}function Ur(e){const t=e.items.map(u=>dd(u)),s=typeof e.total=="number"&&Number.isFinite(e.total)?Math.max(e.total,t.length):t.length,r=e.pagination&&typeof e.pagination=="object"?e.pagination:null,i=r&&Number.isFinite(r.offset)?Math.max(0,Math.floor(r.offset)):0,a=r&&Number.isFinite(r.limit)?Math.max(1,Math.floor(r.limit)):Math.max(1,t.length),c=i+a<s,l=r&&typeof r.hasMore=="boolean"?r.hasMore:c,d=r&&typeof r.nextCursor=="string"?r.nextCursor:l?String(i+a):null;return{...e,items:t,total:s,pagination:{offset:i,limit:a,total:s,nextCursor:d,hasMore:l}}}function ud(e){const t=(e.queueState??"").trim().toLowerCase();if(t==="queued"||t==="running"||t==="blocked"||t==="idle")return t;const s=e.status.trim().toLowerCase();return s==="running"||s==="in_progress"||s==="dispatching"?"running":s==="active"?"queued":e.runnable===!1||s==="blocked"||s==="failed"||s==="error"?"blocked":s==="completed"||s==="done"||s==="resolved"?"idle":"queued"}function md(e){if(!e)return"Workstream";const t=e.trim();return t.length===0?"Workstream":/^[a-f0-9-]{16,}$/i.test(t)?`Workstream ${t.slice(0,8)}`:t}function pd(e){var y,b,p,w,v,x,C,j,g,S,W,Y,K,me,ge,Z;const t=((b=(y=e.lineage)==null?void 0:y.initiativeIds)==null?void 0:b.filter(ae=>typeof ae=="string"&&ae.trim().length>0))??[],s=((w=(p=e.lineage)==null?void 0:p.workstreamIds)==null?void 0:w.filter(ae=>typeof ae=="string"&&ae.trim().length>0))??[],r=((v=e.initiativeId)==null?void 0:v.trim())||t[0]||null,i=((x=e.workstreamId)==null?void 0:x.trim())||((j=(C=e.sourceWorkstreamIds)==null?void 0:C.find(ae=>typeof ae=="string"&&ae.trim().length>0))==null?void 0:j.trim())||s[0]||null;if(!r||!i)return null;const a=((S=(g=e.lineage)==null?void 0:g.taskIds)==null?void 0:S.filter(ae=>typeof ae=="string"&&ae.trim().length>0))??[],c=e.level==="workstream"||e.level==="milestone"||e.level==="task"?e.level:null,l=oa(e.runnerAgentId??null),d=la(e.runnerAgentName??null,l),u=Qo(e.runnerAgents??null,l,d),h=u[0]??null;return{initiativeId:r,initiativeTitle:((W=e.initiativeTitle)==null?void 0:W.trim())||t[0]||r,initiativeStatus:"active",initiativePriority:null,initiativePriorityNum:null,workstreamId:i,workstreamTitle:((Y=e.workstreamTitle)==null?void 0:Y.trim())||((K=e.title)==null?void 0:K.trim())||((me=e.milestoneTitle)==null?void 0:me.trim())||((ge=e.taskTitle)==null?void 0:ge.trim())||md(i),workstreamStatus:e.status,nextTaskId:e.taskId,nextTaskTitle:((Z=e.taskTitle)==null?void 0:Z.trim())||null,nextTaskPriority:typeof e.priorityNum=="number"?e.priorityNum:null,nextTaskDueAt:e.dueAt,runnerAgentId:(h==null?void 0:h.id)??l,runnerAgentName:(h==null?void 0:h.name)??d,runnerAgents:u,runnerSource:e.runnerSource??(h?"inferred":"fallback"),queueState:ud(e),blockReason:e.blockReason??null,queueOrigin:"system",sliceScope:c,sliceTaskIds:a.length>0?a:e.taskId?[e.taskId]:[],sliceTaskCount:a.length>0?a.length:e.taskId?1:0,sliceMilestoneId:e.milestoneId,executionPolicy:null,autoContinue:null}}function fd(e){const t=new Map;for(const s of e){const r=t.get(s.initiativeId);if(r){r.workstreamCount+=1,r.workstreamIds.push(s.workstreamId),r.items.push(s);for(const a of s.runnerAgents??[])r.runnerAgents.some(c=>c.id===a.id)||r.runnerAgents.push(a);const i=a=>a==="running"?3:a==="blocked"?2:a==="queued"?1:0;i(s.queueState)>i(r.queueState)&&(r.queueState=s.queueState)}else t.set(s.initiativeId,{initiativeId:s.initiativeId,initiativeTitle:s.initiativeTitle??s.initiativeId,initiativeStatus:s.initiativeStatus??"active",initiativePriority:typeof s.initiativePriority=="string"?s.initiativePriority:null,initiativePriorityNum:typeof s.initiativePriorityNum=="number"?s.initiativePriorityNum:null,workstreamCount:1,workstreamIds:[s.workstreamId],runnerAgents:[...s.runnerAgents??[]],queueState:s.queueState,items:[s]})}return Array.from(t.values())}function hd(e){return e.map(t=>({milestoneId:t.sliceMilestoneId??null,milestoneTitle:t.sliceMilestoneId?`Milestone ${t.sliceMilestoneId.slice(0,8)}`:t.workstreamTitle??"Workstream",workstreamId:t.workstreamId,workstreamTitle:t.workstreamTitle??t.workstreamId,initiativeId:t.initiativeId,initiativeTitle:t.initiativeTitle??t.initiativeId,taskCount:t.sliceTaskCount??0,queueState:t.queueState,item:t}))}function gd({initiativeId:e=null,projectId:t=null,offset:s=0,limit:r=100,authToken:i=null,embedMode:a=!1,enabled:c=!0,snapshotVersion:l=null,zoomLevel:d="workstream"}){var ae,ke,Fe,G,Se,Ae,xe,re,le,Ee;const u=sa(),h=$t(),y=Math.max(0,s),b=Math.max(1,Math.min(300,r)),p=o.useRef(null);o.useEffect(()=>()=>{p.current&&(clearTimeout(p.current),p.current=null)},[]);const w=o.useMemo(()=>Gn.nextUpQueue({initiativeId:e,projectId:t,offset:y,limit:b,authToken:i,embedMode:a}),[e,t,y,b,i,a]),v=o.useRef(l);o.useEffect(()=>{l!==null&&v.current!==null&&l!==v.current&&u.invalidateQueries({queryKey:w}),v.current=l},[l,u,w]);const x=()=>{p.current&&(clearTimeout(p.current),p.current=null),p.current=setTimeout(()=>{p.current=null,u.invalidateQueries({queryKey:Gn.liveData({authToken:i,embedMode:a,projectId:t})})},sd)},C=async()=>{await Promise.all([u.invalidateQueries({queryKey:w}),u.invalidateQueries({queryKey:Gn.autoContinueStatus({initiativeId:e,authToken:i,embedMode:a})}),u.invalidateQueries({queryKey:Gn.missionControlGraph({initiativeId:e,authToken:i,embedMode:a})})]),x()},j=async(ee,q)=>{if(h)return ad(e);const J=new URLSearchParams;e&&J.set("initiative_id",e),us(J,t,{allTokenWhenMissing:!0}),J.set("offset",String(ee)),J.set("limit",String(q));let V;try{V=await fetch(`/orgx/api/mission-control/next-up?${J.toString()}`,{headers:_t({authToken:i,embedMode:a})})}catch(Me){throw new Error(id(Me,"Failed to load next up queue"))}const k=await rr(V);if(!V.ok){const Me=_r(V,k,"Failed to load next up queue");throw new Error(Me)}const z=k??null;if(!z||z.ok!==!0)return{ok:!0,generatedAt:new Date().toISOString(),total:0,items:[],pagination:{offset:ee,limit:q,total:0,nextCursor:null,hasMore:!1},degraded:["next-up queue response missing expected payload"]};if(Ec())return Ur(z);const O=z.items.filter(Me=>!Es(Me.initiativeId));let oe=Ur({...z,items:O});if(oe.items.length>0)return oe;const ie=new URLSearchParams;e&&ie.set("initiative_id",e),us(ie,t,{allTokenWhenMissing:!0}),ie.set("level","workstream"),ie.set("include_completed","0"),ie.set("offset",String(ee)),ie.set("limit",String(Math.max(q,24)));try{const Me=await fetch(`/orgx/api/mission-control/slices?${ie.toString()}`,{headers:_t({authToken:i,embedMode:a})}),ue=await rr(Me);if(Me.ok&&(ue!=null&&ue.ok)&&Array.isArray(ue.items)){const R=ue.items.map($=>pd($)).filter($=>!!$).filter($=>!Es($.initiativeId));R.length>0&&(oe=Ur({ok:!0,generatedAt:new Date().toISOString(),total:typeof ue.total=="number"&&Number.isFinite(ue.total)?Math.max(ue.total,R.length):R.length,items:R,pagination:ue.pagination&&typeof ue.pagination=="object"?{offset:typeof ue.pagination.offset=="number"?Math.max(0,Math.floor(ue.pagination.offset)):ee,limit:typeof ue.pagination.limit=="number"?Math.max(1,Math.floor(ue.pagination.limit)):Math.max(q,24),total:typeof ue.pagination.total=="number"?Math.max(0,Math.floor(ue.pagination.total)):R.length,nextCursor:typeof ue.pagination.nextCursor=="string"?ue.pagination.nextCursor:null,hasMore:typeof ue.pagination.hasMore=="boolean"?ue.pagination.hasMore:!1}:void 0,degraded:Array.from(new Set([...z.degraded??[],"Queue derived from slices while live queue stabilizes."]))}))}}catch{}return oe},g=ds({queryKey:w,enabled:c,queryFn:async()=>j(y,b),refetchInterval:ee=>{const q=ee.state.data;return!q||!Array.isArray(q.items)||q.items.length===0?1e4:q.items.some(V=>V.queueState==="running")?2500:8e3}}),S=o.useRef(null);o.useEffect(()=>{var J;const ee=(J=g.data)==null?void 0:J.pagination;if(!c||!(ee!=null&&ee.hasMore)||!ee.nextCursor||S.current===ee.nextCursor)return;const q=Number.parseInt(ee.nextCursor,10);Number.isFinite(q)&&(S.current=ee.nextCursor,u.prefetchQuery({queryKey:Gn.nextUpQueue({initiativeId:e,projectId:t,offset:q,limit:b,authToken:i,embedMode:a}),queryFn:()=>j(q,b),staleTime:15e3}))},[c,(ke=(ae=g.data)==null?void 0:ae.pagination)==null?void 0:ke.hasMore,(G=(Fe=g.data)==null?void 0:Fe.pagination)==null?void 0:G.nextCursor,e,t,b,i,a,u]);const W=mn({mutationFn:async ee=>{if(h)return{ok:!0,initiativeId:ee.initiativeId,workstreamId:ee.workstreamId,dispatchMode:"slice",sessionId:null};const q=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:_t({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:ee.initiativeId,workstreamId:ee.workstreamId,agentId:ee.agentId??void 0,scope:ee.scope??void 0,maxParallelSlices:typeof ee.maxParallelSlices=="number"&&Number.isFinite(ee.maxParallelSlices)?Math.max(1,Math.floor(ee.maxParallelSlices)):void 0,parallelMode:ee.parallelMode==="iwmt"?"iwmt":void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})}),J=await rr(q);if(!q.ok)throw new Error(_r(q,J,"Failed to dispatch queued workstream"));return J},onMutate:async ee=>{await u.cancelQueries({queryKey:w});const q=u.getQueryData(w);return q?(u.setQueryData(w,{...q,items:q.items.map(J=>J.initiativeId===ee.initiativeId&&J.workstreamId===ee.workstreamId?{...J,queueState:"running",playbackState:"running"}:J.queueState==="running"?{...J,queueState:"idle",playbackState:"idle"}:J)}),{previous:q}):{previous:q}},onError:(ee,q,J)=>{J!=null&&J.previous&&u.setQueryData(w,J.previous)},onSuccess:()=>{C()}}),Y=mn({mutationFn:async ee=>{if(h)return;const q={initiativeId:ee.initiativeId,agentId:ee.agentId??void 0,tokenBudgetTokens:ee.tokenBudgetTokens,ignoreSpawnGuardRateLimit:!0};ee.scope==="workstream"&&ee.workstreamId&&(q.workstreamIds=[ee.workstreamId]),typeof ee.maxParallelSlices=="number"&&Number.isFinite(ee.maxParallelSlices)&&(q.maxParallelSlices=ee.maxParallelSlices),ee.parallelMode==="iwmt"&&(q.parallelMode=ee.parallelMode);const J=await fetch("/orgx/api/mission-control/auto-continue/start",{method:"POST",headers:_t({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify(q)}),V=await rr(J);if(!J.ok){const k=nd(V);throw k||new Error(_r(J,V,"Failed to start auto-continue"))}},onSuccess:()=>{C()}}),K=mn({mutationFn:async ee=>{if(h)return;const q=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:_t({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:ee.initiativeId})}),J=await rr(q);if(!q.ok)throw new Error(_r(q,J,"Failed to stop auto-continue"))},onSuccess:()=>{C()}}),me=((Se=g.data)==null?void 0:Se.items)??[],ge=o.useMemo(()=>d==="initiative"?fd(me):[],[me,d]),Z=o.useMemo(()=>d==="milestone"?hd(me):[],[me,d]);return{items:me,total:((Ae=g.data)==null?void 0:Ae.total)??0,pagination:((xe=g.data)==null?void 0:xe.pagination)??null,generatedAt:((re=g.data)==null?void 0:re.generatedAt)??null,degraded:((le=g.data)==null?void 0:le.degraded)??[],isLoading:g.isLoading,isFetching:g.isFetching,error:((Ee=g.error)==null?void 0:Ee.message)??null,refetch:g.refetch,playWorkstream:W.mutateAsync,startWorkstreamAutoContinue:Y.mutateAsync,stopInitiativeAutoContinue:K.mutateAsync,isPlaying:W.isPending,isStartingAutoContinue:Y.isPending,isStoppingAutoContinue:K.isPending,zoomLevel:d,initiativeGroups:ge,milestoneGroups:Z}}const xd=750;async function tn(e){return await e.json().catch(()=>null)}function zs(e,t){if(e.status!==404)return!1;const s=typeof(t==null?void 0:t.error)=="string"?t.error:"",r=typeof(t==null?void 0:t.message)=="string"?t.message:"";return/unknown api endpoint/i.test(`${s} ${r}`)}function nn(e,t,s){if(zs(e,t))return`${s}. This queue control is unavailable in the running plugin build.`;if(e.status===401||e.status===403)return`${s}. Reconnect OrgX authentication in Settings.`;if(e.status>=500)return`${s}. OrgX is temporarily unavailable. Try again in a moment.`;const r=typeof(t==null?void 0:t.error)=="string"&&t.error.trim()||typeof(t==null?void 0:t.message)=="string"&&t.message.trim()||`${s}.`;return bn(r)}function yd(e){const t=e.authToken??null,s=e.embedMode??!1,r=$t(),i=sa(),a=o.useRef(null);o.useEffect(()=>()=>{a.current&&(clearTimeout(a.current),a.current=null)},[]);const c=()=>{a.current&&(clearTimeout(a.current),a.current=null),a.current=setTimeout(()=>{a.current=null,i.invalidateQueries({queryKey:["live-data"]})},xd)},l=async()=>{await Promise.all([i.invalidateQueries({queryKey:["mission-control-next-up"]}),i.invalidateQueries({queryKey:["mission-control-graph"]}),i.invalidateQueries({queryKey:["mission-control-slices"]})]),c()},d=async g=>{if(r)return{ok:!0,demo:!0,initiativeId:g.initiativeId,workstreamId:g.workstreamId,placement:g.placement??"top"};const S=await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(g)}),W=await tn(S);if(S.ok)return W;if(!zs(S,W))throw new Error(nn(S,W,"Failed to move Next Up item"));const Y=await fetch("/orgx/api/mission-control/next-up",{headers:_t({authToken:t,embedMode:s})}),K=await tn(Y);if(!Y.ok)throw new Error(nn(Y,K,"Failed to read queue for move fallback"));const ge=(Array.isArray(K==null?void 0:K.items)?K.items:[]).map(G=>{const Se=typeof(G==null?void 0:G.initiativeId)=="string"?G.initiativeId:null,Ae=typeof(G==null?void 0:G.workstreamId)=="string"?G.workstreamId:null;return!Se||!Ae?null:{initiativeId:Se,workstreamId:Ae}}).filter(G=>!!G);if(ge.length===0)throw new Error("Queue placement controls require a newer plugin runtime. Refresh to latest main and retry.");const Z=ge.findIndex(G=>G.initiativeId===g.initiativeId&&G.workstreamId===g.workstreamId);if(Z===-1)return{ok:!0,fallback:"reorder-move-skip"};const[ae]=ge.splice(Z,1);(g.placement??"top")==="bottom"?ge.push(ae):ge.unshift(ae);const ke=await fetch("/orgx/api/mission-control/next-up/reorder",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({order:ge})}),Fe=await tn(ke);if(!ke.ok)throw new Error(nn(ke,Fe,"Failed to move Next Up item with reorder fallback"));return Fe??{ok:!0,fallback:"reorder-move"}},u=async g=>{if(r)return{ok:!0,demo:!0,initiativeId:g.initiativeId,workstreamId:g.workstreamId};const S=await fetch("/orgx/api/mission-control/next-up/remove",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(g)}),W=await tn(S);if(S.ok)return W;if(zs(S,W)){const Y=await fetch("/orgx/api/mission-control/next-up/unpin",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(g)}),K=await tn(Y);if(!Y.ok)throw new Error(nn(Y,K,"Failed to remove item from queue with legacy fallback"));return K??{ok:!0,fallback:"next-up-unpin"}}throw new Error(nn(S,W,"Failed to remove item from queue"))},h=mn({mutationFn:async g=>{if(r)return{ok:!0,demo:!0};const S=await fetch("/orgx/api/mission-control/next-up/pin",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(g)}),W=await tn(S);if(!S.ok)throw new Error(nn(S,W,"Failed to pin Next Up item"))},onSuccess:()=>{l()}}),y=mn({mutationFn:async g=>{if(r)return{ok:!0,demo:!0};const S=await fetch("/orgx/api/mission-control/next-up/unpin",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(g)}),W=await tn(S);if(!S.ok)throw new Error(nn(S,W,"Failed to unpin Next Up item"))},onSuccess:()=>{l()}}),b=mn({mutationFn:async g=>{if(r)return{ok:!0,demo:!0,updated:g.order.length};const S=await fetch("/orgx/api/mission-control/next-up/reorder",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(g)}),W=await tn(S);if(!S.ok)throw new Error(nn(S,W,"Failed to reorder Next Up queue"))},onSuccess:()=>{l()}}),p=mn({mutationFn:d,onSuccess:()=>{l()}}),w=mn({mutationFn:async g=>{if(r)return{ok:!0,demo:!0,initiativeId:g.initiativeId,workstreamId:g.workstreamId};const S=await fetch("/orgx/api/mission-control/next-up/triage/stop",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(g)}),W=await tn(S);if(!S.ok){if(zs(S,W)){const Y=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({initiativeId:g.initiativeId})}),K=await tn(Y);if(!Y.ok)throw new Error(nn(Y,K,"Failed to pause triage with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(nn(S,W,"Failed to stop triage"))}return W},onSuccess:()=>{l()}}),v=mn({mutationFn:u,onSuccess:()=>{l()}}),x=mn({mutationFn:async g=>{if(r)return{ok:!0,demo:!0,cleared:!0};const S=await fetch("/orgx/api/mission-control/next-up/clear",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(g)}),W=await tn(S);if(!S.ok){if(zs(S,W)&&g.initiativeId){const Y=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({initiativeId:g.initiativeId})}),K=await tn(Y);if(!Y.ok)throw new Error(nn(Y,K,"Failed to clear lifecycle state with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(nn(S,W,"Failed to clear Next Up lifecycle state"))}return W},onSuccess:()=>{l()}}),C=mn({mutationFn:async g=>{var Y;if(r)return{ok:!0,demo:!0,dispatched:((Y=g.workstreamIds)==null?void 0:Y.length)??1};const S=await fetch("/orgx/api/mission-control/next-up/launch",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({initiativeId:g.initiativeId,workstreamIds:g.workstreamIds,scope:g.scope,ignoreSpawnGuardRateLimit:!0})}),W=await tn(S);if(!S.ok)throw new Error(nn(S,W,"Failed to launch workstreams"));return W??{ok:!0,dispatched:0}},onSuccess:()=>{l()}}),j=mn({mutationFn:async g=>{if(r)return{ok:!0,demo:!0,updated:g.items.length,failed:0,errors:[],fallback:"demo"};const S=await fetch("/orgx/api/mission-control/next-up/bulk",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(g)}),W=await tn(S);if(!S.ok){if(!zs(S,W))throw new Error(nn(S,W,"Failed to apply bulk queue action"));const Y=await Promise.all(g.items.map(async Z=>{try{return g.action==="remove"?await u(Z):await d({initiativeId:Z.initiativeId,workstreamId:Z.workstreamId,placement:g.action==="move_top"?"top":"bottom"}),{ok:!0,error:null}}catch(ae){return{ok:!1,error:ae instanceof Error?ae.message:"Queue action failed"}}})),K=Y.filter(Z=>Z.ok).length,me=Y.length-K,ge=Y.filter(Z=>!Z.ok&&Z.error).map(Z=>Z.error);return{ok:me===0,updated:K,failed:me,errors:ge,fallback:"sequential"}}return W},onSuccess:()=>{l()}});return{pin:h.mutateAsync,unpin:y.mutateAsync,reorder:b.mutateAsync,move:p.mutateAsync,remove:v.mutateAsync,stopTriage:w.mutateAsync,clear:x.mutateAsync,bulk:j.mutateAsync,launch:C.mutateAsync,isPinning:h.isPending,isUnpinning:y.isPending,isReordering:b.isPending,isMoving:p.isPending,isRemoving:v.isPending,isStoppingTriage:w.isPending,isClearing:x.isPending,isBulking:j.isPending,isLaunching:C.isPending}}const Pa={critical:0,high:1,medium:2,low:3},bd=new Set(["review_required"]);function Jo(e,t){const s={"Content-Type":"application/json"};return e&&(s.Authorization=`Bearer ${e}`),t&&(s["X-OrgX-Embed"]="1"),s}async function wd(e,t,s,r,i,a){const c=new URLSearchParams;e&&c.set("workspace_id",e),t&&c.set("status",t),c.set("limit","100"),i&&i!=="medium"&&c.set("noise_threshold",i),a!=null&&a!==6e4&&c.set("dedup_window",String(a));const l=`/orgx/api/live/triage?${c.toString()}`,d=await fetch(l,{headers:Jo(s,r)});if(!d.ok)throw new Error(`Triage fetch failed: ${d.status}`);return d.json()}function vd(e,t){return t==="all"||t==="low"?e:t==="high"?e.filter(s=>s.severity==="critical"||s.severity==="high"):e.filter(s=>!(s.severity==="low"&&bd.has(s.kind)))}function kd(e,t){const s=new Map;for(const r of e){const i=r.title.trim().toLowerCase(),a=s.get(i);if(!a){s.set(i,{item:r,members:[r],count:1});continue}const c=new Date(a.item.lastSeenAt).getTime(),l=new Date(r.lastSeenAt).getTime();Math.abs(c-l)<=t?(a.members.push(r),a.count+=1,l>c&&(a.item=r)):s.set(`${i}::${r.id}`,{item:r,members:[r],count:1})}return Array.from(s.values())}function jd(e){return[...e].sort((t,s)=>{const r=Pa[t.item.severity]??3,i=Pa[s.item.severity]??3;return r!==i?r-i:new Date(s.item.lastSeenAt).getTime()-new Date(t.item.lastSeenAt).getTime()})}async function Nd(e,t,s,r){const a=`/orgx/api/live/triage/action?${new URLSearchParams({id:e}).toString()}`,c=await fetch(a,{method:"POST",headers:Jo(s,r),body:JSON.stringify(t)});if(!c.ok){const l=await c.json().catch(()=>({}));throw new Error(l.error??`Action failed: ${c.status}`)}return c.json()}function Id(e={}){var g;const{enabled:t=!0,workspaceId:s=null,status:r="open",authToken:i=null,embedMode:a=!1,noiseThreshold:c="medium",dedupWindowMs:l=6e4}=e,d=sa(),u=Gn.triageQueue({workspaceId:s,status:r,authToken:i,embedMode:a}),h=ds({queryKey:u,queryFn:()=>wd(s,r,i,a,c,l),enabled:t,refetchInterval:8e3,staleTime:4e3}),y=mn({mutationFn:async({itemId:S,payload:W})=>Nd(S,W,i,a),onSuccess:()=>{d.invalidateQueries({queryKey:u})}}),b=o.useCallback(async(S,W,Y)=>y.mutateAsync({itemId:S,payload:{action:W,note:Y==null?void 0:Y.note,optionId:Y==null?void 0:Y.optionId,snoozeDurationMinutes:Y==null?void 0:Y.snoozeDurationMinutes}}),[y]),p=((g=h.data)==null?void 0:g.items)??[],{filteredItems:w,suppressedCount:v}=o.useMemo(()=>{const S=vd(p,c);return{filteredItems:S,suppressedCount:p.length-S.length}},[p,c]),x=o.useMemo(()=>jd(kd(w,l)),[w,l]),C=o.useMemo(()=>{var S,W;return{items:p,groups:x,total:((S=h.data)==null?void 0:S.total)??0,filteredTotal:w.length,suppressedCount:v,isLoading:h.isLoading,isFetching:h.isFetching,error:h.error,degraded:((W=h.data)==null?void 0:W.degraded)??[],refetch:h.refetch}},[p,x,w.length,v,h]),j=o.useMemo(()=>({performAction:b,isActing:y.isPending,lastActionError:y.error?y.error.message:null}),[b,y.isPending,y.error]);return{model:C,actions:j}}function pe(...e){return e.filter(Boolean).join(" ")}const F={lime:"#BFFF00",teal:"#14B8A6",cyan:"#0AD4C4",iris:"#7C7CFF",amber:"#F5B700",red:"#FF6B88",background:"#02040A",cardBg:"#08090D",cardBgElevated:"#0C0E14",cardBorderStrong:"rgba(255, 255, 255, 0.12)",text:"#F2F7FF",textMuted:"#8F9AB7"},Ad={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",System:"#14B8A6",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},Sd={Pace:"Product",Eli:"Engineering",Dana:"Product Design",Mark:"Marketing",System:"System",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"};function _d(e){return Ad[e]??"rgba(255, 255, 255, 0.4)"}function Yo(e){return Sd[e]??null}function Cd(e){return e.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2)}function zt(e){return e.trim().toLowerCase().replace(/[\s-]+/g,"_")}const Gt={durationStandard:220,durationEntrance:360,easingStandard:[.22,1,.36,1],easingEntrance:[.16,1,.3,1],easingSpring:{stiffness:400,damping:35},easingBounce:{type:"spring",stiffness:320,damping:28,mass:.7}},hh={hidden:{opacity:0,y:8},visible:e=>({opacity:1,y:0,transition:{delay:Math.min(e,8)*.04,duration:Gt.durationStandard/1e3,ease:Gt.easingStandard}})},gh={initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.15}},ii="/orgx/live/assets/Fm0FhtnV.png";function Zo({size:e=14,className:t="",stroke:s="currentColor",strokeWidth:r=1.8,withBackground:i=!1,backgroundColor:a="transparent"}){return n.jsxs("svg",{className:t,width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:s,strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:r,children:[i?n.jsx("rect",{x:"2",y:"2",width:"20",height:"20",rx:"6",fill:a,stroke:"none"}):null,n.jsx("path",{d:"M6 6c3 0 5 6 8 6"}),n.jsx("path",{d:"M6 18c3 0 5-6 8-6"}),n.jsx("path",{d:"M6 12h12"}),n.jsx("path",{d:"m14 8 4 4-4 4"}),n.jsx("circle",{cx:"6",cy:"6",r:"1.5",fill:s,stroke:"none"}),n.jsx("circle",{cx:"6",cy:"12",r:"1.5",fill:s,stroke:"none"}),n.jsx("circle",{cx:"6",cy:"18",r:"1.5",fill:s,stroke:"none"})]})}function yn({type:e,className:t="",size:s=14,accent:r,hierarchyLabel:i}){const a={className:i?"":t,width:s,height:s,viewBox:"0 0 24 24",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.8};let c;if(e==="initiative"){const l=r??F.iris;c=n.jsxs("svg",{...a,stroke:l,children:[n.jsx("circle",{cx:"12",cy:"12",r:"9",fill:`${l}1A`}),n.jsx("circle",{cx:"12",cy:"12",r:"5"}),n.jsx("circle",{cx:"12",cy:"12",r:"1.5",fill:l,stroke:"none"})]})}else if(e==="workstream"){const l=r??F.lime;c=n.jsx(Zo,{size:s,className:i?"":t,stroke:l,strokeWidth:a.strokeWidth,withBackground:!0,backgroundColor:`${l}1A`})}else if(e==="milestone"){const l=r??F.teal;c=n.jsxs("svg",{...a,stroke:l,children:[n.jsx("path",{d:"M5 3v18"}),n.jsx("path",{d:"m5 4 12 1-2 4 2 4-12-1z",fill:`${l}1A`})]})}else if(e==="task")c=n.jsxs("svg",{...a,stroke:"rgba(255,255,255,0.76)",children:[n.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"4",fill:"rgba(255,255,255,0.12)"}),n.jsx("path",{d:"M9 12.2 11 14.2 15.2 10"})]});else if(e==="decision"){const l=r??F.amber;c=n.jsxs("svg",{...a,stroke:l,children:[n.jsx("path",{d:"M12 3 5.2 6.1v5.7c0 4.8 3.2 7.5 6.8 9 3.6-1.5 6.8-4.2 6.8-9V6.1z",fill:`${l}1A`}),n.jsx("path",{d:"m9.3 12.1 1.8 1.9 3.6-3.6"})]})}else if(e==="session"){const l=r??F.teal;c=n.jsxs("svg",{...a,stroke:l,children:[n.jsx("rect",{x:"4",y:"5",width:"16",height:"14",rx:"4",fill:`${l}14`}),n.jsx("path",{d:"M8 9h8"}),n.jsx("path",{d:"M8 13h5"}),n.jsx("path",{d:"M8 17h3"})]})}else if(e==="active"){const l=r??F.lime;c=n.jsxs("svg",{...a,stroke:l,children:[n.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"6",fill:`${l}12`}),n.jsx("path",{d:"M7 13h2l1.6-6 3.1 12 1.6-6H17"})]})}else if(e==="blocked"){const l=r??F.red;c=n.jsxs("svg",{...a,stroke:l,children:[n.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"6",fill:`${l}12`}),n.jsx("rect",{x:"7.5",y:"11",width:"9",height:"7",rx:"2",fill:"rgba(255,255,255,0.03)"}),n.jsx("path",{d:"M9 11V9.2a3 3 0 0 1 6 0V11"})]})}else if(e==="failed"){const l=r??F.red;c=n.jsxs("svg",{...a,stroke:l,children:[n.jsx("circle",{cx:"12",cy:"12",r:"9",fill:`${l}12`}),n.jsx("path",{d:"M9 9l6 6"}),n.jsx("path",{d:"M15 9l-6 6"})]})}else if(e==="handoff"){const l=r??F.iris;c=n.jsxs("svg",{...a,stroke:l,children:[n.jsx("path",{d:"M7 12h10"}),n.jsx("path",{d:"m13 8 4 4-4 4"}),n.jsx("path",{d:"M7 8v8",opacity:"0.55"})]})}else if(e==="outbox"){const l=r??F.amber;c=n.jsxs("svg",{...a,stroke:l,children:[n.jsx("path",{d:"M4 12h16"}),n.jsx("path",{d:"M6 7h12l2 5v7a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-7z",fill:`${l}12`}),n.jsx("path",{d:"M9 14h6"})]})}else{const l=r??F.cyan;c=n.jsxs("svg",{...a,stroke:l,children:[n.jsx("path",{d:"M12 3a6 6 0 0 0-6 6v2.9c0 .7-.3 1.4-.8 1.9L4 15.2h16l-1.2-1.4a2.8 2.8 0 0 1-.8-1.9V9a6 6 0 0 0-6-6z",fill:`${l}1A`}),n.jsx("path",{d:"M9.2 18a2.8 2.8 0 0 0 5.6 0"})]})}return i?n.jsxs("span",{className:`inline-flex items-center gap-1 ${t}`,children:[c,n.jsx("span",{className:"text-[10px] tracking-wider uppercase font-mono tabular-nums opacity-60 hover:opacity-100 transition-opacity leading-none select-none",title:i,children:i})]}):n.jsx(n.Fragment,{children:c})}const Md=[{label:"Model Routing",desc:"Right model, right cost, every prompt",iconType:"initiative"},{label:"Live Operations",desc:"Decisions, handoffs, sessions in real time",iconType:"workstream"},{label:"Quality Gates",desc:"Automated checkpoints before shipping",iconType:"milestone"}],Wr=[{id:"hierarchy",kicker:"Mission Control",title:"Map the full execution ladder in one place",description:"Trace initiatives through workstreams, milestones, and tasks with sticky context, dependency mapping, and inline edits.",highlights:[{type:"initiative",label:"Initiative",detail:"Top-level outcomes with owner and status."},{type:"workstream",label:"Workstream",detail:"Operational lanes and runner context."},{type:"milestone",label:"Milestone",detail:"Checkpoints that gate readiness."},{type:"task",label:"Task",detail:"Priority, ETA, budget, and dependencies."}],footnote:"Use the hierarchy filters to isolate open, blocked, or done work instantly."},{id:"activity",kicker:"Activity + Decisions",title:"Stay in flow while execution evolves",description:"Track agent output as it happens, review decision payloads, and keep operational context attached from plan to completion.",highlights:[{type:"notification",label:"Live feed",detail:"Messages, failures, and progress in one stream."},{type:"decision",label:"Decision queue",detail:"Approve or reject with full execution context."},{type:"workstream",label:"Handoffs",detail:"Runner transitions across domains and tasks."},{type:"task",label:"Artifacts",detail:"Completion evidence attached where it belongs."}],footnote:"Focus a session to pin a run while the rest of the org remains visible."},{id:"dispatch",kicker:"Autopilot + Next Up",title:"Dispatch work confidently with clear guardrails",description:"Queue the next workstream, open the owning initiative instantly, and escalate from manual play to controlled auto-continue.",highlights:[{type:"workstream",label:"Next Up",detail:"Queued workstreams with resolved runner and next task."},{type:"initiative",label:"Open target",detail:"Jump to the owning initiative and sticky hierarchy."},{type:"milestone",label:"Guardrails",detail:"Blocked states are surfaced before dispatch."},{type:"notification",label:"System notices",detail:"Inline success and failure feedback loops."}],footnote:"Start with Play, then enable auto-continue when queue health is stable."}],Td=[{type:"initiative",label:"Live Initiative Sync",detail:"Initiatives and ownership stay aligned with OpenClaw execution."},{type:"decision",label:"Decision Control",detail:"Review approvals in-app without losing mission context."},{type:"workstream",label:"Queue Visibility",detail:"Understand what runs next, who runs it, and why."}],Oa="openclaw plugins install @useorgx/openclaw-plugin",Ba="orgx.demo_mode",Ed=6500;function Rd(e){switch(e){case"config":return"Plugin config";case"environment":return"Environment variable";case"persisted":return"Saved local credential";case"openclaw-config-file":return"OpenClaw config file";case"legacy-dev":return"Local development key";default:return"Not detected"}}const Dd={hidden:{},visible:{transition:{staggerChildren:.07}}},is={hidden:{opacity:0,y:14},visible:{opacity:1,y:0,transition:{duration:.45,ease:[.16,1,.3,1]}}},Ld={initiative:"text-[#A8A0FF]",workstream:"text-[#BFFF00]",milestone:"text-[#43E7D8]",task:"text-primary",session:"text-[#43E7D8]",active:"text-[#BFFF00]",blocked:"text-[#FF6B88]",failed:"text-[#FF6B88]",handoff:"text-[#A8A0FF]",outbox:"text-[#F5D37A]",decision:"text-[#F5D37A]",notification:"text-[#7EEDE1]"};function bi(e){const t=Wr.length;return(e+t)%t}function Fd({state:e,isStarting:t,onConnect:s,onUseManualKey:r,onContinueWithoutOrgX:i}){const a=!!e.lastError,[c,l]=o.useState("idle"),[d,u]=o.useState("idle"),[h,y]=o.useState(0),[b,p]=o.useState(!1),w=e.hasApiKey&&e.keySource&&e.keySource!=="none",v=Wr[h];o.useEffect(()=>{if(c==="idle")return;const j=window.setTimeout(()=>l("idle"),2e3);return()=>window.clearTimeout(j)},[c]),o.useEffect(()=>{if(d==="idle")return;const j=window.setTimeout(()=>u("idle"),2e3);return()=>window.clearTimeout(j)},[d]),o.useEffect(()=>{if(b)return;const j=window.setInterval(()=>{y(g=>bi(g+1))},Ed);return()=>window.clearInterval(j)},[b]);const x=async()=>{try{await navigator.clipboard.writeText(Oa),l("ok")}catch{l("error")}},C=async()=>{try{const j={at:new Date().toISOString(),onboarding:{status:e.status,nextAction:e.nextAction,hasApiKey:e.hasApiKey,keySource:e.keySource,installationId:e.installationId,lastError:e.lastError},page:typeof window<"u"?window.location.href:null,userAgent:typeof navigator<"u"?navigator.userAgent:null};await navigator.clipboard.writeText(JSON.stringify(j,null,2)),u("ok")}catch{u("error")}};return n.jsxs(be.section,{variants:Dd,initial:"hidden",animate:"visible",className:"bg-[--orgx-surface-elevated] border border-[--orgx-border] soft-shadow rounded-2xl",children:[n.jsxs("div",{className:"px-6 pt-4 sm:px-8 sm:pt-5",children:[n.jsxs(be.div,{variants:is,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:ii,alt:"OrgX",className:"h-7 w-7 rounded-lg object-contain"}),n.jsx("span",{className:"text-body font-semibold text-primary",children:"OrgX"})]}),n.jsxs(be.h2,{variants:is,className:"mt-3 flex items-center gap-2.5 text-[24px] font-semibold leading-[1.2] tracking-[-0.02em] text-white sm:text-[28px]",children:[n.jsx(yn,{type:"workstream",size:19,className:"opacity-95"}),"Connect your workspace"]}),n.jsx(be.p,{variants:is,className:"mt-2 max-w-2xl text-heading leading-relaxed text-secondary",children:"Orchestrate agents, approve decisions, and track progress from a single live dashboard."})]}),n.jsxs("div",{className:"mt-3 grid gap-3 px-6 sm:px-8 lg:grid-cols-[1.24fr_0.86fr]",children:[n.jsxs(be.div,{variants:is,className:"space-y-2.5",children:[n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] p-3.5",onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(yn,{type:"workstream",size:14,className:"text-[#BFFF00]"}),n.jsx("p",{className:"text-micro uppercase tracking-[0.1em] text-secondary",children:"Guided Tour"})]}),n.jsxs("span",{className:"chip text-micro",children:[h+1,"/",Wr.length]})]}),n.jsx(pt,{initial:!1,mode:"wait",children:n.jsxs(be.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},transition:{duration:.24,ease:[.22,1,.36,1]},className:"mt-2.5 min-h-[214px] space-y-2.5",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.09em] text-muted",children:v.kicker}),n.jsx("h3",{className:"text-title font-semibold leading-snug text-white/94",children:v.title}),n.jsx("p",{className:"text-body leading-relaxed text-secondary",children:v.description}),n.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2",children:v.highlights.map(j=>n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(yn,{type:j.type,size:12,className:"flex-shrink-0 opacity-92"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:j.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:j.detail})]},`${v.id}-${j.label}`))}),n.jsx("p",{className:"text-micro leading-relaxed text-muted",children:v.footnote})]},v.id)}),n.jsxs("div",{className:"mt-1.5 flex items-center justify-between",children:[n.jsx("div",{className:"flex items-center gap-1.5",children:Wr.map((j,g)=>{const S=g===h;return n.jsx("button",{type:"button",onClick:()=>y(g),"aria-label":`View slide ${g+1}`,className:`h-1.5 rounded-full transition-all ${S?"w-6 bg-[#BFFF00]":"w-2 bg-white/24 hover:bg-white/38"}`},j.id)})}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:()=>y(j=>bi(j-1)),className:"rounded-full border border-strong bg-white/[0.03] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.08] hover:text-white",children:"Prev"}),n.jsx("button",{type:"button",onClick:()=>y(j=>bi(j+1)),className:"rounded-full border border-strong bg-white/[0.03] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.08] hover:text-white",children:"Next"})]})]})]}),n.jsx("div",{className:"grid grid-cols-1 gap-2.5 sm:grid-cols-3",children:Md.map(j=>n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.025] px-3 py-2.5",children:[n.jsx("div",{className:`mb-1.5 ${Ld[j.iconType]}`,children:n.jsx(yn,{type:j.iconType,size:15})}),n.jsx("p",{className:"text-caption font-semibold text-white",children:j.label}),n.jsx("p",{className:"mt-0.5 text-micro leading-snug text-white/44",children:j.desc})]},j.label))}),n.jsxs(be.div,{variants:is,className:"flex flex-wrap items-center gap-2.5",children:[n.jsx("button",{type:"button",onClick:s,disabled:t,className:"inline-flex items-center gap-2 rounded-full bg-[#BFFF00] px-5 py-2.5 text-body font-semibold text-black shadow-[0_0_24px_rgba(191,255,0,0.12)] transition-all hover:bg-[#d3ff42] hover:shadow-[0_0_32px_rgba(191,255,0,0.22)] disabled:cursor-not-allowed disabled:opacity-50",children:t?n.jsxs(n.Fragment,{children:[n.jsxs("svg",{className:"h-3.5 w-3.5 animate-spin",viewBox:"0 0 16 16",fill:"none",children:[n.jsx("circle",{cx:"8",cy:"8",r:"6",stroke:"currentColor",strokeWidth:"2",opacity:"0.2"}),n.jsx("path",{d:"M14 8a6 6 0 00-6-6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),"Connecting..."]}):"Connect OrgX"}),n.jsx("button",{type:"button",onClick:r,className:"rounded-full border border-white/[0.1] px-4 py-2 text-body text-secondary transition hover:border-white/[0.18] hover:text-bright",children:"Use API key"})]})]}),n.jsxs(be.div,{variants:is,className:"space-y-2.5",children:[n.jsxs("div",{className:"rounded-xl border border-[#14B8A6]/20 bg-[#14B8A6]/[0.06] px-3.5 py-3",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(yn,{type:"workstream",size:12,className:"text-[#7EEDE1]"}),n.jsx("p",{className:"text-caption uppercase tracking-[0.08em] text-[#7EEDE1]",children:"OpenClaw Integration"})]}),n.jsx("p",{className:"mt-1 text-caption leading-relaxed text-[#CFF8F3]",children:"OrgX syncs with OpenClaw so initiatives, workstreams, milestones, and tasks stay aligned with live execution."})]}),n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3.5 py-3",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(yn,{type:"task",size:12,className:"opacity-90"}),n.jsx("p",{className:"text-caption uppercase tracking-[0.08em] text-muted",children:"Quick Setup"})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[n.jsx("code",{className:"rounded-md border border-white/[0.08] bg-black/30 px-2 py-1 font-mono text-caption text-primary",children:Oa}),n.jsx("button",{type:"button",onClick:()=>{x()},className:"rounded-full border border-strong px-3 py-1 text-caption text-secondary transition hover:border-white/[0.2] hover:text-bright",children:c==="ok"?"Copied":c==="error"?"Copy failed":"Copy command"})]}),w&&n.jsxs("p",{className:"mt-2 text-caption text-secondary",children:["API key source detected: ",Rd(e.keySource)]})]}),n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3.5 py-3",children:[n.jsx("p",{className:"text-caption uppercase tracking-[0.08em] text-muted",children:"What Unlocks After Connect"}),n.jsx("div",{className:"mt-2 space-y-1.5",children:Td.map(j=>n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(yn,{type:j.type,size:12,className:"flex-shrink-0 opacity-90"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:j.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:j.detail})]},j.label))})]})]})]}),n.jsx(be.div,{variants:is,className:"mx-6 mt-2 sm:mx-8",children:a?n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-red-500/15 bg-red-500/[0.04] px-4 py-3",children:[n.jsx("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-red-500/15",children:n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:n.jsx("path",{d:"M5 2.5v3M5 7.5h.004",stroke:"#FF6B88",strokeWidth:"1.4",strokeLinecap:"round"})})}),n.jsx("div",{className:"min-w-0 flex-1",children:n.jsx("p",{className:"text-body text-red-300/80",children:e.lastError})}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>void C(),className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption font-medium text-primary transition hover:bg-white/[0.08] hover:text-white",title:"Copy debug details for support",children:d==="ok"?"Copied":d==="error"?"Copy failed":"Copy debug"}),n.jsx("button",{type:"button",onClick:r,className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption font-medium text-primary transition hover:bg-white/[0.08] hover:text-white",children:"Use API key"}),n.jsx("button",{type:"button",onClick:s,disabled:t,className:"rounded-full border border-red-500/20 bg-red-500/[0.06] px-3 py-1 text-caption font-semibold text-red-200/85 transition hover:bg-red-500/[0.09] hover:text-red-100 disabled:opacity-50",children:"Retry"})]})]}):n.jsxs("div",{className:"flex items-center gap-2 rounded-xl border border-subtle bg-white/[0.02] px-3.5 py-2",children:[n.jsx("span",{className:"relative flex h-1.5 w-1.5",children:n.jsx("span",{className:"relative inline-flex h-1.5 w-1.5 rounded-full bg-white/40"})}),n.jsx("span",{className:"text-body text-muted",children:"Ready to connect"})]})}),n.jsxs(be.div,{variants:is,className:"mt-2 flex flex-wrap items-center justify-between gap-2 border-t border-subtle px-6 py-2 sm:px-8",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.jsx("button",{type:"button",onClick:()=>{try{window.localStorage.setItem(Ba,"1")}catch{}i()},className:"text-left text-caption text-muted transition hover:text-secondary",children:"Explore demo dashboard"}),n.jsx("button",{type:"button",onClick:()=>{try{window.localStorage.removeItem(Ba)}catch{}i()},className:"text-left text-caption text-faint transition hover:text-secondary",children:"Continue offline"})]}),n.jsxs("a",{href:e.docsUrl,target:"_blank",rel:"noopener noreferrer",className:"group inline-flex items-center gap-1 text-caption text-muted transition hover:text-secondary",children:["Setup guide",n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",className:"transition-transform group-hover:translate-x-0.5",children:n.jsx("path",{d:"M3.5 2.5l3 2.5-3 2.5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})]})}const $d={hidden:{},visible:{transition:{staggerChildren:.06}}},Ns={hidden:{opacity:0,y:10},visible:{opacity:1,y:0,transition:{duration:.35,ease:[.16,1,.3,1]}}};function Pd({isSubmitting:e,onSubmit:t,onBack:s}){const[r,i]=o.useState(""),[a,c]=o.useState(null),l="https://www.useorgx.com/settings#security",d=async()=>{c(null);const h=r.trim();if(!h){c("API key is required.");return}const y=/^[a-z]+_/i.test(h)?h:`oxk_${h}`;try{await t(y),i("")}catch(b){c(b instanceof Error?b.message:"Failed to validate API key.")}},u=a!==null;return n.jsxs(be.section,{variants:$d,initial:"hidden",animate:"visible",className:"bg-[--orgx-surface-elevated] border border-[--orgx-border] soft-shadow rounded-2xl",children:[n.jsxs("div",{className:"px-6 pt-6 sm:px-8 sm:pt-8",children:[n.jsxs(be.div,{variants:Ns,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:ii,alt:"OrgX",className:"h-7 w-7 rounded-lg object-contain"}),n.jsx("span",{className:"text-body font-semibold text-primary",children:"OrgX"})]}),n.jsx(be.h3,{variants:Ns,className:"mt-5 text-[22px] font-semibold tracking-[-0.02em] text-white",children:"Manual API key"}),n.jsxs(be.p,{variants:Ns,className:"mt-1.5 text-heading leading-relaxed text-secondary",children:["Paste a key from your ",n.jsx("span",{className:"text-secondary",children:"useorgx.com"})," dashboard. Browser pairing is recommended."]}),n.jsxs(be.p,{variants:Ns,className:"mt-1 text-body text-muted",children:["Paste full key or only the part after ",n.jsx("span",{className:"font-mono text-secondary",children:"oxk_"}),"."]}),n.jsx(be.div,{variants:Ns,className:"mt-3",children:n.jsxs("a",{href:l,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-2 rounded-full border border-white/[0.10] bg-white/[0.03] px-3 py-1.5 text-body font-semibold text-secondary transition hover:bg-white/[0.06] hover:text-primary",title:"Open OrgX settings to generate an API key",children:["Generate an API key",n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none","aria-hidden":"true",children:[n.jsx("path",{d:"M4.5 2.5h5v5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"}),n.jsx("path",{d:"M9.5 2.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"}),n.jsx("path",{d:"M2.75 3.5H2.5c-.55 0-1 .45-1 1v5c0 .55.45 1 1 1h5c.55 0 1-.45 1-1V9.5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"})]})]})})]}),n.jsxs(be.div,{variants:Ns,className:"mt-6 space-y-4 px-6 sm:px-8",children:[n.jsxs("label",{className:"block",children:[n.jsx("span",{className:"mb-1.5 block text-caption font-medium uppercase tracking-[0.14em] text-muted",children:"API key"}),n.jsxs("div",{className:`flex items-stretch overflow-hidden rounded-xl border transition-colors focus-within:border-[#BFFF00]/40 ${u?"border-red-500/30":"border-white/[0.08]"}`,children:[n.jsx("span",{className:"flex items-center border-r border-subtle bg-white/[0.03] px-3 font-mono text-body text-faint select-none",children:"oxk_"}),n.jsx("input",{value:r,onChange:h=>{i(h.target.value),a&&c(null)},placeholder:"paste your key",className:"w-full bg-transparent px-3 py-2.5 font-mono text-body text-white outline-none placeholder:text-faint"})]}),u&&n.jsx(be.p,{initial:{opacity:0,y:-3},animate:{opacity:1,y:0},className:"mt-1.5 text-body text-red-400/70",children:a})]}),n.jsxs("p",{className:"text-body text-muted",children:["User-scoped keys (",n.jsx("span",{className:"font-mono text-secondary",children:"oxk_..."}),") do not require a separate user ID header."]})]}),n.jsxs(be.div,{variants:Ns,className:"mt-6 flex flex-wrap items-center gap-3 px-6 sm:px-8",children:[n.jsx("button",{type:"button",onClick:()=>{d()},disabled:e,className:"inline-flex items-center gap-2 rounded-full bg-[#BFFF00] px-5 py-2.5 text-body font-semibold text-black shadow-[0_0_24px_rgba(191,255,0,0.12)] transition-all hover:bg-[#d3ff42] hover:shadow-[0_0_32px_rgba(191,255,0,0.22)] disabled:cursor-not-allowed disabled:opacity-50",children:e?n.jsxs(n.Fragment,{children:[n.jsxs("svg",{className:"h-3.5 w-3.5 animate-spin",viewBox:"0 0 16 16",fill:"none",children:[n.jsx("circle",{cx:"8",cy:"8",r:"6",stroke:"currentColor",strokeWidth:"2",opacity:"0.2"}),n.jsx("path",{d:"M14 8a6 6 0 00-6-6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),"Validating..."]}):"Validate & Connect"}),n.jsx("button",{type:"button",onClick:s,className:"rounded-full border border-white/[0.1] px-4 py-2 text-body text-secondary transition hover:border-white/[0.18] hover:text-bright",children:"Back to pairing"})]}),n.jsx("div",{className:"mt-6 border-t border-subtle px-6 py-4 sm:px-8",children:n.jsx("p",{className:"text-body text-faint",children:"Keys are stored locally and never leave your device."})})]})}const qa="orgx.user.display-name",za="orgx.user.avatar-seed-suffix";function Ua(e){return typeof window>"u"?"":window.localStorage.getItem(e)??""}function Wa(e,t){typeof window>"u"||(t?window.localStorage.setItem(e,t):window.localStorage.removeItem(e))}function Od(){const[e,t]=o.useState(()=>Ua(qa)),[s,r]=o.useState(()=>Ua(za)),i=(e||"orgx-user")+s,a=o.useCallback(l=>{const d=l.trim();Wa(qa,d),t(d)},[]),c=o.useCallback(()=>{const l=String(Date.now());Wa(za,l),r(l)},[]);return{displayName:e,avatarSeed:i,updateName:a,regenerateAvatar:c}}function Bd(e){let t=5381;for(let s=0;s<e.length;s++)t=(t<<5)+t+e.charCodeAt(s)>>>0;return t}function qd(e){let t=e|0;return()=>{t=t+1831565813|0;let s=Math.imul(t^t>>>15,1|t);return s=s+Math.imul(s^s>>>7,61|s)^s,((s^s>>>14)>>>0)/4294967296}}const Ha=[F.lime,F.teal,F.iris,F.cyan];function zd(e,t,s,r,i,a){const c=S=>S*Math.PI/180,l=Math.cos,d=Math.sin,u=c(i),h=c(a),y=a-i>180?1:0,b=e+r*l(u),p=t+r*d(u),w=e+r*l(h),v=t+r*d(h),x=e+s*l(h),C=t+s*d(h),j=e+s*l(u),g=t+s*d(u);return[`M ${b} ${p}`,`A ${r} ${r} 0 ${y} 1 ${w} ${v}`,`L ${x} ${C}`,`A ${s} ${s} 0 ${y} 0 ${j} ${g}`,"Z"].join(" ")}function Ud(e){const t=qd(Bd(e)),s=3+Math.floor(t()*2),r=[],i=50,a=50;for(let c=0;c<s;c++){const l=8+c*10,d=l+9,u=6+Math.floor(t()*6),h=360/u,y=1.5+t()*2;for(let b=0;b<u;b++){if(t()<.15)continue;const p=b*h+y/2,w=(b+1)*h-y/2,v=Ha[Math.floor(t()*Ha.length)],x=.25+t()*.55;r.push({d:zd(i,a,l,d,p,w),fill:v,opacity:x})}}return r}function Wd({seed:e,size:t,className:s,animate:r=!0}){const i=o.useMemo(()=>Ud(e),[e]);return n.jsxs(be.svg,{viewBox:"0 0 100 100",width:t,height:t,className:pe("flex-shrink-0",s),initial:r?{opacity:0,scale:.85,rotate:-30}:!1,animate:{opacity:1,scale:1,rotate:0},transition:{duration:.5,ease:Gt.easingEntrance},children:[n.jsxs("defs",{children:[n.jsx("clipPath",{id:`avatar-clip-${e}`,children:n.jsx("circle",{cx:"50",cy:"50",r:"48"})}),n.jsxs("radialGradient",{id:`avatar-glow-${e}`,cx:"50%",cy:"50%",r:"50%",children:[n.jsx("stop",{offset:"0%",stopColor:F.lime,stopOpacity:"0.08"}),n.jsx("stop",{offset:"100%",stopColor:F.lime,stopOpacity:"0"})]})]}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:F.cardBg}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:`url(#avatar-glow-${e})`}),n.jsx("g",{clipPath:`url(#avatar-clip-${e})`,children:i.map((a,c)=>n.jsx(be.path,{d:a.d,fill:a.fill,initial:r?{opacity:0,scale:.85}:!1,animate:{opacity:a.opacity,scale:1},transition:{delay:c*.012,duration:.35,ease:Gt.easingEntrance},style:{transformOrigin:"50px 50px"}},c))}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:"none",stroke:"rgba(255,255,255,0.08)",strokeWidth:"1"})]},e)}function Hd({onComplete:e}){const{displayName:t,updateName:s}=Od(),[r,i]=o.useState(t),a=o.useCallback(()=>{s(r),e()},[r,s,e]),c=o.useCallback(()=>{e()},[e]),l=o.useCallback(u=>{u.key==="Enter"&&a()},[a]),d=(r.trim()||"orgx-user")+"";return n.jsx(be.div,{initial:{opacity:0,y:14,scale:.985},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-8,scale:.985},transition:{duration:.32,ease:Gt.easingEntrance},className:"flex items-center justify-center",children:n.jsx("div",{className:"w-full max-w-md rounded-2xl border border-white/[0.08] bg-[--orgx-surface-elevated] p-6 sm:p-8",children:n.jsxs("div",{className:"flex flex-col items-center text-center",children:[n.jsx(Wd,{seed:d,size:96}),n.jsx("h2",{className:"mt-5 text-title font-medium text-white",children:"Welcome to OrgX"}),n.jsx("p",{className:"mt-2 text-body leading-relaxed text-secondary",children:"What should we call you? This appears in your settings and is stored locally."}),n.jsx("input",{type:"text",value:r,onChange:u=>i(u.target.value),onKeyDown:l,maxLength:64,autoFocus:!0,placeholder:"Your name",className:"mt-5 h-10 w-full max-w-xs rounded-xl border border-white/[0.12] bg-white/[0.04] px-4 text-center text-body text-white placeholder:text-muted focus:border-lime/30 focus:outline-none"}),n.jsx("button",{type:"button",onClick:a,className:"mt-5 rounded-full bg-lime px-6 py-2.5 text-body font-medium text-black transition hover:brightness-110",children:r.trim()?"Continue":"Continue without name"}),r.trim()&&n.jsx("button",{type:"button",onClick:c,className:"mt-3 text-caption text-secondary transition hover:text-white",children:"Skip"})]})})})}const Vd=[{label:"Terms",href:"https://www.useorgx.com/terms"},{label:"Privacy",href:"https://www.useorgx.com/privacy"},{label:"IP notice",href:"https://www.useorgx.com/legal"}];function Kd({className:e,compact:t=!1}){return n.jsxs("div",{className:pe("flex flex-wrap items-center gap-x-3 gap-y-1 text-muted",t?"text-micro":"text-caption",e),children:[n.jsxs("span",{className:"text-faint",children:["© ",new Date().getFullYear()," OrgX"]}),Vd.map(s=>n.jsx("a",{href:s.href,target:"_blank",rel:"noopener noreferrer nofollow",className:"transition-colors hover:text-secondary",children:s.label},s.label))]})}const Va="orgx.user.name-asked";function Gd(e){switch(e){case"starting":return"Starting secure session...";case"awaiting_browser_auth":return"Waiting for browser approval...";case"pairing":return"Confirming connection...";case"manual_key":return"Manual key entry";case"connected":return"Connected";case"error":return"Connection issue";default:return"Ready to connect"}}function Xd(e){switch(e){case"config":return"Config key";case"environment":return"Env key";case"persisted":return"Saved key";case"openclaw-config-file":return"OpenClaw key";case"legacy-dev":return"Local dev key";default:return"No key"}}function Qd(e){return e==="awaiting_browser_auth"||e==="pairing"||e==="starting"?"active":e==="error"?"error":e==="connected"?"active":"idle"}const Ka={idle:"bg-white/40",active:"bg-[#BFFF00]",error:"bg-red-400"},wi="orgx.onboarding.mc_hint.dismissed",vi={initial:{opacity:0,y:14,scale:.985},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-8,scale:.985},transition:{duration:.32,ease:[.16,1,.3,1]}};function Jd({state:e,isLoading:t,isStarting:s,isSubmittingManual:r,onRefresh:i,onStartPairing:a,onSubmitManualKey:c,onBackToPairing:l,onUseManualKey:d,onSkip:u}){const[h,y]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(wi)==="1"),[b,p]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(Va)!=="1"),w=o.useCallback(()=>{typeof window<"u"&&window.localStorage.setItem(Va,"1"),p(!1)},[]);o.useEffect(()=>{typeof window>"u"||(h?window.localStorage.setItem(wi,"1"):window.localStorage.removeItem(wi))},[h]);const v=e.status==="manual_key",x=e.status==="awaiting_browser_auth"||e.status==="pairing",C=Qd(e.status),j=C==="active"&&e.status!=="connected",g=e.status==="connected"&&!h;return n.jsx("div",{className:"relative flex min-h-screen items-start justify-center px-4 pb-6 pt-0 sm:pt-2",style:{backgroundColor:"#02040A"},children:n.jsxs(be.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.45},className:`relative z-10 w-full ${v?"max-w-lg":"max-w-[1120px]"}`,children:[t?n.jsxs("div",{className:"bg-[--orgx-surface-elevated] border border-[--orgx-border] rounded-2xl p-6 sm:p-8",children:[n.jsx("div",{className:"shimmer-skeleton h-7 w-28 rounded-lg"}),n.jsx("div",{className:"shimmer-skeleton mt-5 h-8 w-3/4 rounded-lg"}),n.jsx("div",{className:"shimmer-skeleton mt-3 h-4 w-2/3 rounded-lg"}),n.jsxs("div",{className:"mt-7 grid grid-cols-3 gap-2.5",children:[n.jsx("div",{className:"shimmer-skeleton h-24 rounded-xl"}),n.jsx("div",{className:"shimmer-skeleton h-24 rounded-xl"}),n.jsx("div",{className:"shimmer-skeleton h-24 rounded-xl"})]}),n.jsx("div",{className:"shimmer-skeleton mt-7 h-10 w-36 rounded-full"})]}):n.jsx(pt,{mode:"wait",children:e.status==="connected"&&b?n.jsx(be.div,{...vi,children:n.jsx(Hd,{onComplete:w})},"welcome-name"):v?n.jsx(be.div,{...vi,children:n.jsx(Pd,{isSubmitting:r,onSubmit:c,onBack:l})},"manual"):n.jsx(be.div,{...vi,children:n.jsx(Fd,{state:e,isStarting:s,onConnect:()=>{a()},onUseManualKey:d,onContinueWithoutOrgX:u})},"explainer")}),!t&&(x||e.status==="connected")&&n.jsxs(be.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},exit:{opacity:0,y:6},transition:{delay:.15,duration:.35,ease:[.16,1,.3,1]},className:"mt-4 flex items-center justify-between rounded-xl border border-subtle bg-white/[0.025] px-4 py-3",children:[n.jsxs("div",{className:"flex items-center gap-2.5",children:[n.jsxs("span",{className:"relative flex h-2 w-2",children:[j&&n.jsx("span",{className:`absolute inline-flex h-full w-full animate-ping rounded-full ${Ka[C]} opacity-40`}),n.jsx("span",{className:`relative inline-flex h-2 w-2 rounded-full ${Ka[C]}`})]}),n.jsx("span",{className:"text-body text-secondary",children:Gd(e.status)}),e.workspaceName&&n.jsxs("span",{className:"chip",children:["Account: ",e.workspaceName]}),e.keySource&&e.keySource!=="none"&&n.jsx("span",{className:"chip",children:Xd(e.keySource)})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[e.expiresAt&&n.jsx("span",{className:"text-caption text-muted",children:new Date(e.expiresAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),e.connectUrl&&x&&n.jsx("a",{href:e.connectUrl,target:"_blank",rel:"noopener noreferrer",className:"rounded-full border border-[#BFFF00]/25 bg-[#BFFF00]/[0.05] px-3 py-1 text-caption font-medium text-[#D8FFA1] transition hover:bg-[#BFFF00]/[0.1]",children:"Approve in browser"}),n.jsx("button",{type:"button",onClick:()=>{i()},className:"rounded-full border border-white/[0.08] px-2.5 py-1 text-caption text-muted transition hover:bg-white/[0.04] hover:text-secondary",children:"Refresh"})]})]}),g&&n.jsxs(be.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{delay:.2,duration:.3},className:"mt-3 rounded-xl border border-[#7C7CFF]/25 bg-[#7C7CFF]/10 px-4 py-3",children:[n.jsx("p",{className:"text-caption uppercase tracking-[0.08em] text-[#CFCBFF]",children:"Mission Control Tip"}),n.jsx("p",{className:"mt-1 text-body leading-relaxed text-[#E6E4FF]",children:"Open Mission Control to see initiative → workstream → milestone → task flow with dependencies and recent todos in one expandable view."}),n.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[n.jsx("a",{href:"/orgx/live?view=mission-control",className:"rounded-full border border-[#BFFF00]/30 bg-[#BFFF00]/15 px-3 py-1 text-caption font-medium text-[#D8FFA1]",children:"Open Mission Control"}),n.jsx("button",{type:"button",onClick:()=>y(!0),className:"text-caption text-secondary underline underline-offset-2",children:"Dismiss"})]})]}),!t&&n.jsx("div",{className:"mt-3 flex justify-center",children:n.jsx(Kd,{compact:!0})})]})})}function Yd({children:e,color:t,pulse:s,title:r}){const i=t??F.lime;return n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-micro font-semibold uppercase tracking-[0.14em]",title:r,style:{backgroundColor:`${i}22`,border:`1px solid ${i}5a`,color:i},children:[n.jsxs("span",{className:"relative flex h-1.5 w-1.5",children:[s&&n.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full opacity-75",style:{backgroundColor:i}}),n.jsx("span",{className:"relative inline-flex h-1.5 w-1.5 rounded-full",style:{backgroundColor:i}})]}),e]})}function ai({open:e,onClose:t,children:s,maxWidth:r="max-w-2xl",fitContent:i=!1,closeOnBackdropClick:a=!0,closeOnEscape:c=!0,closeOnEscapeWhenTyping:l=!0}){const d=o.useRef(null),u=o.useRef(null);o.useEffect(()=>{if(!e)return;u.current=document.activeElement instanceof HTMLElement?document.activeElement:null,(()=>{const w=d.current;if(!w)return;const v=w.querySelector('[data-modal-autofocus="true"]');if(v){v.focus();return}const x=w.querySelectorAll('a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])');x.length>0?x[0].focus():w.focus()})();const b=w=>{if(w.key==="Escape"){if(!c)return;if(!l){const S=w.target;if(S&&(S.tagName==="INPUT"||S.tagName==="TEXTAREA"||S.tagName==="SELECT"||S.isContentEditable))return}w.preventDefault(),t();return}if(w.key!=="Tab")return;const v=d.current;if(!v)return;const x=v.querySelectorAll('a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])');if(x.length===0){w.preventDefault(),v.focus();return}const C=x[0],j=x[x.length-1],g=document.activeElement;!w.shiftKey&&g===j?(w.preventDefault(),C.focus()):w.shiftKey&&g===C&&(w.preventDefault(),j.focus())},p=document.body.style.overflow;return document.body.style.overflow="hidden",document.addEventListener("keydown",b),()=>{var w;document.body.style.overflow=p,document.removeEventListener("keydown",b),(w=u.current)==null||w.focus()}},[e,t,c,l]);const h=n.jsx(pt,{children:e&&n.jsxs(be.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[420] flex items-stretch justify-center p-0 sm:items-center sm:p-6",onClick:()=>{a&&t()},"aria-hidden":!e,children:[n.jsx("div",{className:"absolute inset-0 bg-black/80 backdrop-blur-md"}),n.jsxs(be.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:20},transition:{duration:.24,ease:[.16,1,.3,1]},className:`glass-panel soft-shadow relative flex flex-col w-full ${r} overflow-hidden ${i?"h-auto max-h-[100dvh] rounded-none sm:max-h-[88vh] sm:rounded-2xl":"h-[100dvh] max-h-[100dvh] rounded-none sm:h-[88vh] sm:max-h-[88vh] sm:rounded-2xl"}`,style:{backgroundColor:F.cardBgElevated,borderColor:F.cardBorderStrong},onClick:y=>y.stopPropagation(),role:"dialog","aria-modal":"true",tabIndex:-1,ref:d,children:[n.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-white/50 to-transparent"}),s]})]})});return typeof document>"u"?h:Rl.createPortal(h,document.body)}const Zd=[{id:"agents",label:"Agents",icon:n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),n.jsx("circle",{cx:"12",cy:"7",r:"4"})]})},{id:"activity",label:"Activity",icon:n.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"22 12 18 12 15 21 9 3 6 12 2 12"})})},{id:"decisions",label:"Decisions",icon:n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z"}),n.jsx("path",{d:"m9 12 2 2 4-4"})]})},{id:"initiatives",label:"Next Up",icon:n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"}),n.jsx("line",{x1:"4",x2:"4",y1:"22",y2:"15"})]})}];function eu({activeTab:e,onTabChange:t,pendingDecisionCount:s=0}){return n.jsx("nav",{className:"pointer-events-none fixed inset-x-0 z-40 flex justify-center px-3 lg:hidden",style:{bottom:"max(10px, env(safe-area-inset-bottom))"},"aria-label":"Mobile sections",children:n.jsx("div",{className:"pointer-events-auto relative flex items-stretch gap-1 rounded-[24px] border border-strong bg-[#090d16]/90 p-1.5 shadow-[0_20px_50px_rgba(0,0,0,0.52)] backdrop-blur-xl",children:Zd.map(r=>{const i=e===r.id;return n.jsxs("button",{type:"button",onClick:()=>t(r.id),"aria-current":i?"page":void 0,className:pe("relative flex min-w-[76px] flex-1 flex-col items-center gap-1 overflow-hidden rounded-[18px] px-2 pb-1.5 pt-2.5 transition-colors",i?"text-lime":"text-secondary hover:text-white/72"),children:[i&&n.jsxs(n.Fragment,{children:[n.jsx(be.span,{layoutId:"mobile-tab-active-pill",className:"absolute inset-0 rounded-[18px] border border-[#BFFF00]/28 bg-[#BFFF00]/[0.1]",transition:{type:"spring",stiffness:420,damping:34,mass:.8}}),n.jsx(be.span,{layoutId:"mobile-tab-active-line",className:"absolute inset-x-3 top-0.5 h-[2px] rounded-full",style:{backgroundColor:F.lime},transition:{type:"spring",stiffness:440,damping:36,mass:.75}})]}),n.jsxs("span",{className:pe("relative inline-flex h-8 w-8 items-center justify-center rounded-full border transition-colors",i?"border-[#BFFF00]/35 bg-[#BFFF00]/[0.12] text-[#D8FFA1]":"border-white/[0.1] bg-white/[0.03]"),children:[n.jsx("span",{className:"relative z-[1]",children:r.icon}),r.id==="decisions"&&s>0&&n.jsx("span",{className:"absolute -right-1.5 -top-1 flex h-3.5 min-w-[14px] items-center justify-center rounded-full border border-black/35 px-1 text-[8px] font-bold text-black shadow-[0_2px_8px_rgba(0,0,0,0.35)]",style:{backgroundColor:F.amber},children:s>99?"99+":s})]}),n.jsx("span",{className:pe("relative z-[1] text-micro font-medium",i?"text-[#D8FFA1]":"text-secondary"),children:r.label})]},r.id)})})})}function Hs({children:e,className:t="",surface:s=!0}){return n.jsx("section",{className:pe("relative overflow-hidden rounded-2xl",s?"surface-tier-1":"",t),children:e})}const tu={xs:"w-6 h-6 text-micro",sm:"w-8 h-8 text-micro",md:"w-10 h-10 text-body",lg:"w-16 h-16 text-title"},nu="/orgx/live/",cn=e=>`${nu.replace(/\/+$/,"/")}${e}`,su={pace:cn("brand/product-orchestrator.png"),eli:cn("brand/engineering-autopilot.png"),mark:cn("brand/launch-captain.png"),sage:cn("brand/pipeline-intelligence.png"),orion:cn("brand/control-tower.png"),dana:cn("brand/design-codex.png"),xandy:cn("brand/xandy-orchestrator.png"),nova:cn("brand/xandy-orchestrator.png"),openclaw:cn("brand/openclaw-mark.svg"),codex:cn("brand/openai-mark.svg"),openai:cn("brand/openai-mark.svg"),anthropic:cn("brand/anthropic-mark.svg"),orgx:cn("brand/orgx-logo.png")},ru=[{test:/\bpace\b|product|nova|strategist/i,key:"pace"},{test:/\beli\b|engineering|dev-delivery|executor/i,key:"eli"},{test:/\bmark\b|marketing|launch-captain/i,key:"mark"},{test:/\bsage\b|sales|pipeline-intelligence|sales-sage/i,key:"sage"},{test:/\borion\b|operations|ops-orbit|control-tower/i,key:"orion"},{test:/\bdana\b|design/i,key:"dana"},{test:/\bxandy\b|orchestrator|router-all-agents/i,key:"xandy"},{test:/\bholt\b|openclaw/i,key:"openclaw"},{test:/openai|gpt|o[1345]-|codex/i,key:"codex"},{test:/anthropic|claude/i,key:"anthropic"},{test:/\borgx\b/i,key:"orgx"}];function iu(...e){const t=e.map(s=>typeof s=="string"?s.trim():"").filter(Boolean).join(" ").toLowerCase();if(!t)return null;for(const s of ru)if(s.test.test(t))return su[s.key];return null}function Ot({name:e,size:t="xs",hint:s,src:r}){const i=_d(e),[a,c]=o.useState(!1),l=o.useMemo(()=>r&&r.trim()?r:iu(e,s),[s,e,r]),d=!!(l&&!a);return n.jsx("div",{"data-agent-avatar":"true",className:`${tu[t]} overflow-hidden rounded-full flex items-center justify-center font-semibold flex-shrink-0`,style:{backgroundColor:`${i}20`,color:i,border:`1px solid ${i}30`},children:d?n.jsx("img",{src:l??void 0,alt:e,className:"h-full w-full rounded-full object-cover",onError:()=>c(!0),loading:"lazy"}):Cd(e)})}Ot.displayName="AgentAvatar";const au={neutral:"border-strong bg-white/[0.04] text-primary",muted:"border-strong bg-white/[0.03] text-secondary",lime:"border-lime/28 bg-lime/[0.12] text-[#D8FFA1]",cyan:"border-cyan-300/28 bg-cyan-500/[0.12] text-cyan-100",red:"border-red-300/28 bg-red-500/[0.12] text-red-100"};function gn({children:e,tone:t="muted",className:s,...r}){const i=o.Children.toArray(e).some(a=>{if(!o.isValidElement(a))return!1;const c=a.type;return c.displayName==="AgentAvatar"||c.name==="AgentAvatar"});return n.jsx("span",{className:pe("inline-flex h-7 items-center rounded-full border text-caption font-medium leading-none whitespace-nowrap",i?"gap-1.5 pl-[3px] pr-2.5 [&>[data-agent-avatar]]:h-5 [&>[data-agent-avatar]]:w-5":"gap-1.5 px-2.5",au[t],s),...r,children:e})}function ou(e){var s,r;const t=[];if(e.initiativeId){const i={id:e.initiativeId,label:e.initiativeTitle||Cs(e.initiativeId,"Initiative"),type:"initiative",children:[]};if(e.workstreamId){const a=el(e.status),c={id:e.workstreamId,label:e.workstreamTitle||Cs(e.workstreamId,"Workstream"),type:"workstream",status:a,progress:e.scopeProgress?{done:e.scopeProgress.completedTasks,total:e.scopeProgress.totalTasks}:void 0,agent:e.agentName?{name:e.agentName,id:e.agentId}:null,children:[]};if((s=e.scopeProgress)!=null&&s.milestones&&e.scopeProgress.milestones.length>0)for(const l of e.scopeProgress.milestones){const d=l.done>=l.total?"done":l.done>0?"active":"pending",u={id:l.id,label:l.title||Cs(l.id,"Milestone"),type:"milestone",status:d,progress:{done:l.done,total:l.total}};l.total>0&&(u.children=Array.from({length:l.total},(h,y)=>({id:`${l.id}-task-${y}`,label:`Task ${y+1}`,type:"task",status:y<l.done?"done":"pending"}))),c.children.push(u)}else if(e.taskIds&&e.taskIds.length>0){const l=((r=e.scopeProgress)==null?void 0:r.completedTasks)??0;c.children=e.taskIds.map((d,u)=>({id:d,label:Cs(d,"Task"),type:"task",status:u<l?"done":"pending"}))}i.children.push(c)}t.push(i)}return t}function xh(e){const t=[];if(!e.initiativeId&&!e.workstreamId)return t;const s=e.initiativeId?{id:e.initiativeId,label:e.initiativeTitle||Cs(e.initiativeId,"Initiative"),type:"initiative",children:[]}:null,r=e.workstreamId?{id:e.workstreamId,label:e.workstreamTitle||Cs(e.workstreamId,"Workstream"),type:"workstream",status:el(e.status),agent:e.agentName?{name:e.agentName,id:e.agentId}:null,children:[]}:null,i=e.taskId?{id:e.taskId,label:e.taskTitle||Cs(e.taskId,"Task"),type:"task",highlight:!0}:null;return r&&i&&(r.children=[i]),s&&r?(s.children=[r],t.push(s)):r?t.push(r):s&&t.push(s),t}function Cs(e,t){return!e||e.length<8?t:`${t} ${e.slice(0,6)}`}function el(e){return e?e==="completed"||e==="done"?"done":e==="running"||e==="in_progress"||e==="needs_review"?"active":e==="failed"?"failed":e==="blocked"||e==="awaiting_input"?"blocked":"pending":"pending"}function tl(e){switch(e){case"done":return F.lime;case"active":return F.teal;case"blocked":return F.amber;case"failed":return F.red;default:return"rgba(255,255,255,0.15)"}}function lu(e){const t=tl(e);return{backgroundColor:e==="pending"?"transparent":t,borderColor:t,borderWidth:1.5,borderStyle:"solid"}}const cu=o.memo(function({done:t,total:s,color:r}){const i=s>0?Math.max(2,Math.round(t/s*100)):0;return n.jsx("div",{className:"h-[3px] w-full overflow-hidden rounded-full bg-white/[0.06]",children:n.jsx(be.div,{className:"h-full rounded-full",style:{backgroundColor:r},initial:{width:0},animate:{width:`${i}%`},transition:{duration:.5,ease:[.22,1,.36,1]}})})}),du=16,uu=14,Ga=8,mu=8,pu=28,fu=24,hu=24,gu=20,ki="rgba(255,255,255,0.07)";function xu(e){const t=e?uu:du,s=t+mu+4;return{iconSz:t,colW:s,rowH:e?hu:pu,rowHTask:e?gu:fu}}function nl({node:e,depth:t,isLast:s,activeId:r,compact:i,index:a,taskLimit:c,expanded:l,onToggleExpand:d}){const u=r===e.id||e.highlight,h=e.progress&&e.progress.total>0,y=e.type==="task",{iconSz:b,colW:p,rowH:w,rowHTask:v}=xu(i),x=y?v:w,C=e.children??[],j=C.filter(ge=>ge.type==="task"),g=C.filter(ge=>ge.type!=="task"),S=j.length>c&&!l,W=S?j.slice(0,c):j,Y=j.length-W.length,K=[...g,...W],me=K.length>0||S;return n.jsxs("div",{className:"relative",style:{minHeight:x},children:[t>0&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"absolute w-px",style:{backgroundColor:ki,left:(t-1)*p+p/2,top:0,bottom:s?void 0:0,height:s?x/2:void 0}}),n.jsx("div",{className:"absolute h-px",style:{backgroundColor:ki,left:(t-1)*p+p/2,top:x/2,width:p}})]}),n.jsxs(be.div,{initial:{opacity:0,x:-3},animate:{opacity:1,x:0},transition:{delay:a*.02,duration:.15},className:`flex items-center ${u?"rounded-md bg-white/[0.03]":""}`,style:{height:x,paddingLeft:t*p},children:[n.jsx("div",{className:"flex flex-shrink-0 items-center justify-center",style:{width:p,height:x},children:y?n.jsx("span",{className:"inline-block rounded-full",style:{...lu(e.status),width:Ga,height:Ga}}):n.jsx(yn,{type:e.type,size:b,accent:u?F.lime:void 0})}),n.jsxs("div",{className:"min-w-0 flex-1 pr-1",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:`min-w-0 truncate ${y?`text-[12px] leading-none ${e.status==="done"?"text-white/40 line-through decoration-white/10":"text-white/35"}`:e.type==="milestone"?"text-[13px] font-medium leading-none text-white/55":t===0?"text-[13px] font-medium leading-none text-white/80":"text-[13px] font-medium leading-none text-white/70"} ${u?"!text-white/90 !no-underline":""}`,children:e.label}),h&&n.jsxs("span",{className:"flex-shrink-0 text-[10px] tabular-nums leading-none text-white/20",children:[e.progress.done,"/",e.progress.total]}),e.agent&&n.jsx("span",{className:"ml-auto flex-shrink-0 rounded-full bg-white/[0.05] px-1.5 py-px text-[9px] font-medium leading-none text-white/25",children:e.agent.name})]}),h&&!y&&n.jsx("div",{className:"mt-1.5 max-w-[160px]",children:n.jsx(cu,{done:e.progress.done,total:e.progress.total,color:tl(e.status)})})]})]}),me&&n.jsx("div",{className:"absolute w-px",style:{backgroundColor:ki,left:t*p+p/2,top:x/2,height:x/2}}),me&&n.jsxs("div",{children:[K.map((ge,Z)=>n.jsx(nl,{node:ge,depth:t+1,isLast:Z===K.length-1&&!S,activeId:r,compact:i,index:a+Z+1,taskLimit:c,expanded:l,onToggleExpand:d},ge.id)),S&&n.jsxs(be.button,{type:"button",initial:{opacity:0},animate:{opacity:1},transition:{delay:(a+K.length+1)*.02},onClick:d,className:"flex items-center text-[10px] font-medium text-white/25 transition-colors hover:text-white/45",style:{height:v,paddingLeft:(t+1)*p+p},children:["+",Y," more · see all"]}),n.jsx(pt,{children:l&&j.length>c&&n.jsx(be.button,{type:"button",initial:{opacity:0,height:0},animate:{opacity:1,height:v},exit:{opacity:0,height:0},onClick:d,className:"flex items-center text-[10px] font-medium text-white/25 transition-colors hover:text-white/45",style:{paddingLeft:(t+1)*p+p},children:"show less"})})]})]})}const yu=o.memo(function({nodes:t,className:s,activeId:r,compact:i,taskLimit:a=4}){const[c,l]=o.useState(!1);return t.length===0?null:n.jsx("div",{className:s,children:t.map((d,u)=>n.jsx(nl,{node:d,depth:0,isLast:u===t.length-1,activeId:r,compact:i,index:u,taskLimit:a,expanded:c,onToggleExpand:()=>l(h=>!h)},d.id))})}),Ki={engineering:{domain:"engineering",displayName:"Engineering",gradient:["#22c55e","#14b8a6"],accentColor:"#22c55e",glowColor:"#22c55e33",icon:"hammer",progressStyle:"linear",verb:"Building"},design:{domain:"design",displayName:"Design",gradient:["#a78bfa","#ec4899"],accentColor:"#a78bfa",glowColor:"#a78bfa33",icon:"palette",progressStyle:"wave",verb:"Designing"},product:{domain:"product",displayName:"Product",gradient:["#3b82f6","#6366f1"],accentColor:"#3b82f6",glowColor:"#3b82f633",icon:"compass",progressStyle:"stepped",verb:"Specifying"},marketing:{domain:"marketing",displayName:"Marketing",gradient:["#f59e0b","#ef4444"],accentColor:"#f59e0b",glowColor:"#f59e0b33",icon:"megaphone",progressStyle:"wave",verb:"Crafting"},sales:{domain:"sales",displayName:"Sales",gradient:["#06b6d4","#3b82f6"],accentColor:"#06b6d4",glowColor:"#06b6d433",icon:"handshake",progressStyle:"linear",verb:"Preparing"},operations:{domain:"operations",displayName:"Operations",gradient:["#64748b","#475569"],accentColor:"#64748b",glowColor:"#64748b33",icon:"shield",progressStyle:"stepped",verb:"Securing"},orchestrator:{domain:"orchestrator",displayName:"Orchestrator",gradient:["#8b5cf6","#6366f1"],accentColor:"#8b5cf6",glowColor:"#8b5cf633",icon:"workflow",progressStyle:"linear",verb:"Coordinating"}},bu=Object.keys(Ki),wu={eli:"engineering",dana:"design",mark:"marketing",sage:"sales",orion:"operations",xandy:"orchestrator",pace:"product"};function Xa(e){if(!e)return"engineering";const t=e.trim().toLowerCase(),s=wu[t];if(s)return s;for(const r of bu)if(t.includes(r))return r;return"engineering"}function Qa(e){return Ki[e]??Ki.engineering}const Bs={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},ir={Eli:"Engineering",Pace:"Product",Dana:"Design",Mark:"Marketing",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"},Ja={engineering:"Eli",product:"Pace",design:"Dana",marketing:"Mark",strategy:"Strategy",sales:"Sage",operations:"Orion",orchestrator:"Xandy",research:"Nova"},Ya={eli:"Eli",pace:"Pace",dana:"Dana",mark:"Mark",sage:"Sage",orion:"Orion",xandy:"Xandy",nova:"Nova","engineering-agent":"Eli","product-agent":"Pace","design-agent":"Dana","marketing-agent":"Mark","strategy-agent":"Sage","sales-agent":"Sage","operations-agent":"Orion","orchestrator-agent":"Xandy","research-agent":"Nova","engineering-bot":"Eli","product-bot":"Pace","design-bot":"Dana","marketing-bot":"Mark","dev-delivery":"Eli","launch-captain":"Mark","pipeline-intelligence":"Sage","control-tower":"Orion","design-codex":"Dana","router-all-agents":"Xandy","ops-orbit":"Orion","sales-sage":"Sage"};function sl(e,t){const s={name:(t==null?void 0:t.trim())||"OrgX",domain:"",color:"rgba(255,255,255,0.4)",displayLabel:(t==null?void 0:t.trim())||"OrgX"};if(e){const r=e.trim().toLowerCase(),i=Ya[r];if(i){const a=ir[i]??"";return{name:i,domain:a,color:Bs[i]??s.color,displayLabel:a?`${i} (${a})`:i}}for(const[a,c]of Object.entries(Ja))if(r.includes(a)){const l=ir[c]??"";return{name:c,domain:l,color:Bs[c]??s.color,displayLabel:l?`${c} (${l})`:c}}}if(t){const r=t.trim();if(Bs[r]){const c=ir[r]??"";return{name:r,domain:c,color:Bs[r],displayLabel:c?`${r} (${c})`:r}}const i=r.toLowerCase(),a=Ya[i];if(a){const c=ir[a]??"";return{name:a,domain:c,color:Bs[a]??s.color,displayLabel:c?`${a} (${c})`:a}}for(const[c,l]of Object.entries(Ja))if(i.includes(c)){const d=ir[l]??"";return{name:l,domain:d,color:Bs[l]??s.color,displayLabel:d?`${l} (${d})`:l}}}return s}function yh({agents:e,max:t=4}){if(!e.length)return null;const s=e.slice(0,t),r=e.length-t;return n.jsxs("div",{className:"inline-flex min-w-0 items-center justify-end -space-x-1.5 pl-1",children:[s.map(i=>n.jsx("div",{className:"relative flex-shrink-0",title:`${i.name} (${i.confidence} confidence)`,style:{borderRadius:"9999px",border:i.confidence==="high"?"1.5px solid rgba(255,255,255,0.25)":i.confidence==="medium"?"1.5px dashed rgba(255,255,255,0.15)":"1.5px dotted rgba(255,255,255,0.10)"},children:n.jsx(Ot,{name:i.name,size:"xs"})},i.id)),r>0&&n.jsxs("span",{className:"ml-1 flex-shrink-0 text-micro text-muted",children:["+",r]})]})}const vu=new Set(["running","active","in_progress","working","planning","dispatching"]),ku=new Set(["running","dispatching"]),ju=3*6e4;function Nu(e){if(!e)return!1;const t=Date.parse(e);return Number.isFinite(t)?Date.now()-t<=ju:!1}function Iu(e){const t=zt(e.status??""),s=zt(e.state??"");return s==="stale"||t==="stale"||s==="stopped"&&t!=="blocked"?!1:vu.has(t)?!0:t==="queued"||t==="pending"||t==="paused"||t==="completed"?!1:e.lastHeartbeatAt?Nu(e.lastHeartbeatAt):!1}function rl(e){return e.replace(/_/g," ").replace(/^\w/,t=>t.toUpperCase())}function Au(e){const t=zt(e);return t==="running"||t==="active"||t==="in_progress"||t==="working"||t==="dispatching"?"border-teal-300/28 bg-teal-400/[0.10] text-teal-100":t==="blocked"||t==="failed"||t==="error"?"border-red-400/26 bg-red-500/[0.10] text-red-100":t==="paused"||t==="pending"||t==="queued"?"border-amber-300/28 bg-amber-300/[0.10] text-amber-100":"border-[#BFFF00]/24 bg-[#BFFF00]/[0.10] text-[#E8FFD0]"}function Su(e){const t=zt(e);return t==="running"||t==="active"||t==="in_progress"||t==="working"||t==="dispatching"?"from-teal-300/0 via-teal-300/65 to-teal-300/0":t==="blocked"||t==="failed"||t==="error"?"from-red-300/0 via-red-300/65 to-red-300/0":t==="paused"||t==="pending"||t==="queued"?"from-amber-300/0 via-amber-300/65 to-amber-300/0":"from-[#BFFF00]/0 via-[#BFFF00]/70 to-[#BFFF00]/0"}function il(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function Cr(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Is(e,t){const s=[],r=i=>{if(typeof i!="string")return;const a=i.trim();a&&(s.some(c=>c.toLowerCase()===a.toLowerCase())||s.push(a))};if(Array.isArray(e))for(const i of e)r(i);return r(t??null),s}function Gi(e,t){if(!e)return t;const s=e.trim();return s?ms(s)?`${t} ${as(s)}`:s:t}function al({sessions:e,sliceRuns:t=[],initiatives:s=[]}){var y,b,p,w,v;const r=new Map;for(const x of s)x.id&&r.set(x.id,x.name??x.id);const i=new Map;for(const x of e){const C=(y=x.runId)==null?void 0:y.trim();!C||i.has(C)||i.set(C,x)}const a=new Map;for(const x of e){const C=((b=x.initiativeId)==null?void 0:b.trim())??"",j=((p=x.workstreamId)==null?void 0:p.trim())??"";if(!C||!j)continue;const g=`${C}:${j}`;a.has(g)||a.set(g,x)}const c=new Set;for(const x of e){const C=(w=x.runId)==null?void 0:w.trim();C&&c.add(C)}const l=[];for(const x of t){if(!ku.has(x.status))continue;const C=(x.runId??x.sliceRunId??"").trim();if(!C)continue;const j=Is(x.initiativeIds,x.initiativeId),g=Is(x.workstreamIds,x.workstreamId),S=j[0]??null,W=g[0]??null,Y=[];for(const ae of j)for(const ke of g)!ae||!ke||Y.push(`${ae}:${ke}`);if(!(c.has(C)||Y.some(ae=>a.has(ae))))continue;const me=i.get(C)??(Y.length>0?Y.map(ae=>a.get(ae)??null).find(ae=>!!ae)??null:null),ge=S?r.get(S)??S:null,Z=x.scopeProgress&&typeof x.scopeProgress.totalTasks=="number"&&x.scopeProgress.totalTasks>0?Math.round(x.scopeProgress.completedTasks/x.scopeProgress.totalTasks*100):null;l.push({key:`slice:${x.sliceRunId}`,source:"slice",session:me??null,runId:C,status:zt(x.status),title:x.workstreamTitle??(me==null?void 0:me.title)??`Work slice ${x.sliceRunId.slice(0,8)}`,subtitle:x.statusExplainer??x.lastEventSummary??(me==null?void 0:me.lastEventSummary)??null,progress:Z??(me==null?void 0:me.progress)??null,initiativeId:S,initiativeIds:j,initiativeTitle:ge,workstreamId:W,workstreamIds:g,iwmtId:x.iwmtId??null,iwmtIds:Is(x.iwmtIds,x.iwmtId),workstreamTitle:x.workstreamTitle??(me==null?void 0:me.title)??null,taskIds:Array.isArray(x.taskIds)?x.taskIds:[],milestoneIds:Array.isArray(x.milestoneIds)?x.milestoneIds:[],artifactCount:x.artifactCount??0,decisionCount:x.blockingDecisionCount??x.decisionCount??0,updatedAt:x.updatedAt??x.lastEventAt??(me==null?void 0:me.updatedAt)??null,scope:x.scope,milestoneProgress:(v=x.scopeProgress)==null?void 0:v.milestones})}if(l.sort((x,C)=>Cr(C.updatedAt)-Cr(x.updatedAt)),l.length>0)return l;const d=e.filter(Iu);d.sort((x,C)=>{const j=Cr(x.updatedAt??x.lastEventAt??x.startedAt);return Cr(C.updatedAt??C.lastEventAt??C.startedAt)-j});const u=[],h=new Set;for(const x of d){const C=x.workstreamId&&x.workstreamId.trim().length>0?`${x.initiativeId??"none"}:${x.workstreamId}`:x.runId;h.has(C)||(h.add(C),u.push(x))}return u.map(x=>{var C;return{key:`session:${x.id}`,source:"session",session:x,runId:x.runId,status:zt(x.status??""),title:x.title,subtitle:(C=x.lastEventSummary)!=null&&C.trim()?x.lastEventSummary.trim():null,progress:x.progress,initiativeId:x.initiativeId,initiativeIds:Is(void 0,x.initiativeId),initiativeTitle:x.initiativeId?r.get(x.initiativeId)??x.groupLabel??null:x.groupLabel??null,workstreamId:x.workstreamId,workstreamIds:Is(void 0,x.workstreamId),iwmtId:null,iwmtIds:[],workstreamTitle:x.title,taskIds:[],milestoneIds:[],artifactCount:0,decisionCount:0,updatedAt:x.updatedAt??x.lastEventAt??x.startedAt??null}})}const _u=o.memo(function({sessions:t,sliceRuns:s=[],initiatives:r=[],title:i="In Progress",className:a,showHeader:c=!0,panelStyle:l="card",needsAttentionCount:d=0,onSwitchToNeedsAttention:u,onOpenSession:h,onFocusRunId:y,onPlayWorkstream:b,onPauseWorkstream:p,onResumeWorkstream:w,onRestartSession:v,onIntervene:x,onOpenSliceDetail:C}){const[j,g]=o.useState(null),[S,W]=o.useState(null),[Y,K]=o.useState(null),[me,ge]=o.useState(null),Z=o.useMemo(()=>{const re=new Map;if(!Array.isArray(s))return re;for(const le of s){const Ee=Is(le.initiativeIds,le.initiativeId),ee=Is(le.workstreamIds,le.workstreamId);for(const J of Ee)for(const V of ee){if(!J||!V)continue;const k=`${J}:${V}`;re.has(k)||re.set(k,le)}const q=(le.runId??le.sliceRunId??"").trim();q&&!re.has(`run:${q}`)&&re.set(`run:${q}`,le)}return re},[s]),ae=o.useMemo(()=>al({sessions:t,sliceRuns:s,initiatives:r}),[r,t,s]),ke=o.useMemo(()=>{const re=new Map;for(const le of ae){const Ee=zt(le.status);re.set(Ee,(re.get(Ee)??0)+1)}return Array.from(re.entries()).sort((le,Ee)=>Ee[1]-le[1]).map(([le,Ee])=>({status:le,count:Ee}))},[ae]),Fe=o.useMemo(()=>j?ae.filter(re=>zt(re.status)===j):ae,[j,ae]),G=o.useMemo(()=>{var ee,q;const re=new Map,le=[];for(const J of Fe){const V=(((ee=J.initiativeIds)==null?void 0:ee[0])??J.initiativeId??"").trim(),k=(((q=J.workstreamIds)==null?void 0:q[0])??J.workstreamId??"").trim();if(!V){le.push(J);continue}let z=re.get(V);z||(z={title:J.initiativeTitle??V,wsMap:new Map},re.set(V,z));const O=k||"__none__";let oe=z.wsMap.get(O);oe||(oe={title:J.workstreamTitle??(k||"Unassigned"),rows:[],completedCount:0,lastActivity:null},z.wsMap.set(O,oe));const ie=zt(J.status);if(ie==="completed"||ie==="done"?oe.completedCount+=1:oe.rows.push(J),J.updatedAt){const Me=Date.parse(J.updatedAt),ue=oe.lastActivity?Date.parse(oe.lastActivity):0;Number.isFinite(Me)&&Me>ue&&(oe.lastActivity=J.updatedAt)}}const Ee=[];for(const[J,V]of re){const k=[];for(const[z,O]of V.wsMap)k.push({workstreamId:z,workstreamTitle:O.title,rows:O.rows,completedCount:O.completedCount,lastActivityAt:O.lastActivity});k.sort((z,O)=>{const oe=z.lastActivityAt?Date.parse(z.lastActivityAt):0;return(O.lastActivityAt?Date.parse(O.lastActivityAt):0)-oe}),Ee.push({initiativeId:J,initiativeTitle:V.title,workstreams:k})}return Ee.sort((J,V)=>{const k=Math.max(0,...J.workstreams.map(O=>O.lastActivityAt?Date.parse(O.lastActivityAt):0));return Math.max(0,...V.workstreams.map(O=>O.lastActivityAt?Date.parse(O.lastActivityAt):0))-k}),{groups:Ee,ungrouped:le}},[Fe]),[Se,Ae]=o.useState(new Set),xe=async(re,le,Ee)=>{if(re.session){ge(null),W(re.session.id);try{await le(re.session),ge(Ee)}catch(ee){const q=ee instanceof Error?ee.message:"";ge(q?bn(q):"Workstream action failed")}finally{W(null)}}};return n.jsxs(Hs,{surface:l==="card",className:`flex h-full min-h-0 flex-col overflow-hidden ${l==="flat"?"!rounded-none !border-none !bg-transparent !shadow-none":""} ${a??""}`,children:[c?n.jsx("div",{className:"flex items-center justify-between gap-2 border-b border-subtle px-4 py-3",children:n.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n.jsx("h2",{className:"truncate text-heading font-semibold text-white",children:i}),n.jsx("span",{className:"chip text-micro",children:ae.length})]})}):null,ke.length>1&&n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 border-b border-subtle px-3 py-2",children:[n.jsxs("button",{type:"button",onClick:()=>g(null),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold transition-colors ${j===null?"border-[#BFFF00]/30 bg-[#BFFF00]/12 text-[#E1FFB2]":"border-strong bg-white/[0.04] text-secondary hover:bg-white/[0.08]"}`,children:["All",n.jsx("span",{className:"tabular-nums opacity-70",children:ae.length})]}),ke.map(({status:re,count:le})=>n.jsxs("button",{type:"button",onClick:()=>g(Ee=>Ee===re?null:re),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold capitalize transition-colors ${j===re?"border-[#BFFF00]/30 bg-[#BFFF00]/12 text-[#E1FFB2]":"border-strong bg-white/[0.04] text-secondary hover:bg-white/[0.08]"}`,children:[rl(re),n.jsx("span",{className:"tabular-nums opacity-70",children:le})]},re))]}),me&&n.jsx("div",{className:"border-b border-subtle px-3 py-2 text-caption text-secondary",children:me}),Fe.length===0?ae.length===0&&d>0&&u?n.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-4 px-6 py-10 text-center",children:[n.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full border border-white/[0.08] bg-white/[0.03]",children:n.jsx("svg",{viewBox:"0 0 20 20",fill:"none",className:"h-5 w-5 text-secondary","aria-hidden":!0,children:n.jsx("path",{d:"M10 6v4m0 4h.01M3 10a7 7 0 1114 0 7 7 0 01-14 0z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n.jsxs("div",{children:[n.jsx("p",{className:"text-body font-medium text-primary",children:"All clear"}),n.jsxs("p",{className:"mt-1 text-caption leading-relaxed text-secondary",children:["No active runs right now."," ",n.jsx("span",{className:"tabular-nums font-semibold text-[#F5B700]/90",children:d})," ",d===1?"item needs":"items need"," your attention."]})]}),n.jsxs("button",{type:"button",onClick:u,className:"inline-flex h-8 items-center gap-1.5 rounded-full border border-[#F5B700]/25 bg-[#F5B700]/[0.08] px-4 text-caption font-semibold text-[#FFE7A8] transition-colors hover:border-[#F5B700]/40 hover:bg-[#F5B700]/[0.14]",children:[n.jsx("span",{children:"Review needs attention"}),n.jsx("span",{className:"tabular-nums opacity-80",children:d})]})]}):n.jsx("div",{className:"flex flex-1 items-center justify-center px-4 py-10",children:n.jsx("p",{className:"text-body text-secondary",children:ae.length===0?"No runs in progress.":"No runs match this filter."})}):n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-3 py-2",children:n.jsxs(be.div,{className:"space-y-4",initial:"hidden",animate:"show",variants:{show:{transition:{staggerChildren:.04}}},children:[G.groups.map(re=>n.jsxs("div",{children:[n.jsx("h3",{className:"text-[15px] font-semibold text-white/90 mb-2",children:Bt(re.initiativeTitle&&!ms(re.initiativeTitle)?re.initiativeTitle:Gi(re.initiativeId,"Initiative"))}),re.workstreams.map(le=>{var oe,ie;const Ee=`${re.initiativeId}:${le.workstreamId}`,ee=Se.has(Ee),q=le.rows[0]??null,J=q?sl((oe=q.session)==null?void 0:oe.agentId,(ie=q.session)==null?void 0:ie.agentName):null,V=q!=null&&q.milestoneProgress?q.milestoneProgress.reduce((Me,ue)=>Me+ue.total,0):null,k=q!=null&&q.milestoneProgress?q.milestoneProgress.reduce((Me,ue)=>Me+ue.done,0):null,z=V&&V>0?`Task ${(k??0)+1} of ${V}`:null,O=V&&V>0?Math.round((k??0)/V*100):(q==null?void 0:q.progress)!=null?il(q.progress):null;return n.jsxs("div",{className:"pl-4 border-l border-white/[0.08] mb-3",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[J&&n.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[n.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-bold flex-shrink-0",style:{backgroundColor:`${J.color}20`,color:J.color},children:J.name.charAt(0).toUpperCase()}),n.jsx("span",{className:"text-[13px] font-medium truncate",style:{color:J.color},children:J.displayLabel})]}),z&&n.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[n.jsx("span",{className:"font-mono tabular-nums text-[11px] text-white/50",children:z}),n.jsx("div",{className:"h-1 rounded-full bg-white/10 w-24",children:n.jsx("div",{className:"h-full rounded-full transition-[width] duration-500",style:{width:`${Math.max(3,O??0)}%`,backgroundColor:(J==null?void 0:J.color)??"#14B8A6"}})})]}),le.lastActivityAt&&n.jsx("span",{className:"font-mono tabular-nums text-[11px] text-white/40 ml-auto flex-shrink-0",children:Bo(new Date(le.lastActivityAt),{addSuffix:!0})})]}),n.jsx("div",{className:"space-y-2",children:le.rows.map((Me,ue)=>n.jsx(Za,{row:Me,index:ue,sliceRunByScope:Z,busySessionId:S,expandedRowKey:Y,setExpandedRowKey:K,onOpenSession:h,onFocusRunId:y,onPauseWorkstream:p,onResumeWorkstream:w,onRestartSession:v,onPlayWorkstream:b,onIntervene:x,onOpenSliceDetail:C,runWorkstreamAction:xe,showInitiativeLabel:!1},Me.key))}),le.completedCount>0&&n.jsx("div",{className:"mt-1.5",children:n.jsx("button",{type:"button",onClick:()=>Ae(Me=>{const ue=new Set(Me);return ue.has(Ee)?ue.delete(Ee):ue.add(Ee),ue}),className:"text-[11px] text-[#14B8A6] cursor-pointer hover:underline",children:ee?`Hide ${le.completedCount} completed`:`${le.completedCount} completed`})})]},le.workstreamId)})]},re.initiativeId)),G.ungrouped.length>0&&n.jsxs("div",{children:[G.groups.length>0&&n.jsx("h3",{className:"text-[15px] font-semibold text-white/90 mb-2",children:"Ungrouped"}),n.jsx("div",{className:"space-y-2",children:G.ungrouped.map((re,le)=>n.jsx(Za,{row:re,index:le,sliceRunByScope:Z,busySessionId:S,expandedRowKey:Y,setExpandedRowKey:K,onOpenSession:h,onFocusRunId:y,onPauseWorkstream:p,onResumeWorkstream:w,onRestartSession:v,onPlayWorkstream:b,onIntervene:x,onOpenSliceDetail:C,runWorkstreamAction:xe,showInitiativeLabel:!0},re.key))})]})]})})]})});function Za({row:e,index:t,sliceRunByScope:s,busySessionId:r,expandedRowKey:i,setExpandedRowKey:a,onOpenSession:c,onFocusRunId:l,onPauseWorkstream:d,onResumeWorkstream:u,onRestartSession:h,onPlayWorkstream:y,onIntervene:b,onOpenSliceDetail:p,runWorkstreamAction:w,showInitiativeLabel:v=!0}){var le,Ee,ee,q,J,V,k,z,O;const x=zt(e.status??""),C=e.updatedAt,j=e.subtitle?e.subtitle:C?`Updated ${It(C)}`:null,g=v&&(e.initiativeTitle||e.initiativeId)?Bt(e.initiativeTitle&&!ms(e.initiativeTitle)?e.initiativeTitle:Gi(e.initiativeId,"Initiative")):null,S=(le=e.title)!=null&&le.trim()?e.title:e.workstreamTitle??"",W=Gi(e.workstreamId??e.runId,e.scope==="milestone"?"Milestone":e.scope==="task"?"Task":"Workstream"),Y=Bt(S&&!ms(S)?S:W),K=j?Bt(j):null,me=il(e.progress),ge=["running","active","in_progress","working","planning","dispatching"].includes(x),Z=["paused","blocked","queued","pending"].includes(x),ae=h??y,ke=me===null&&["running","active","in_progress","working","planning","dispatching"].includes(x),Fe=e.session?r===e.session.id:!1,G=i===e.key,Se=e.source==="slice"&&(e.taskIds.length>0||e.milestoneIds.length>0||e.artifactCount>0||e.decisionCount>0),Ae=(e.initiativeId&&e.workstreamId?s.get(`${e.initiativeId}:${e.workstreamId}`)??null:null)??(e.runId?s.get(`run:${e.runId}`)??null:null),xe=sl((Ee=e.session)==null?void 0:Ee.agentId,(ee=e.session)==null?void 0:ee.agentName),re=e.subtitle&&e.subtitle!==K?e.subtitle:null;return n.jsxs(be.article,{initial:{opacity:0,y:10,scale:.985},animate:{opacity:1,y:0,scale:1},transition:{duration:.24,delay:Math.min(t,7)*.02,ease:[.22,1,.36,1]},className:"group hover-lift relative overflow-visible rounded-2xl border border-white/[0.08] bg-white/[0.02] px-3 py-2.5 cursor-pointer transition-colors hover:border-white/[0.14]",onClick:()=>p==null?void 0:p(e,Ae),role:"button",tabIndex:0,onKeyDown:oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),p==null||p(e,Ae))},children:[n.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${Su(x)}`,"aria-hidden":!0}),n.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[n.jsx("div",{className:e.status==="running"?"agent-glow-ring rounded-full":"",style:e.status==="running"?{"--agent-glow-color":xe.color}:void 0,children:n.jsx(Ot,{name:((q=e.session)==null?void 0:q.agentName)??"OrgX",hint:((J=e.session)==null?void 0:J.agentId)??e.runId,size:"sm"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[g?n.jsx("p",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:g}):null,n.jsxs("div",{className:"flex min-w-0 items-start gap-1.5",children:[n.jsx(yn,{type:"session",size:12,className:"mt-[3px] flex-shrink-0 opacity-80"}),n.jsx("p",{className:"min-w-0 line-clamp-2 text-body font-semibold leading-snug text-white",title:Y,children:Y})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[e.scope&&e.scope!=="task"&&n.jsx(gn,{tone:e.scope==="milestone"?"cyan":"lime",children:e.scope}),n.jsx("span",{className:`inline-flex rounded-full border px-2 py-[1px] text-micro font-semibold uppercase tracking-[0.08em] ${Au(x)}`,children:rl(x)}),C&&n.jsx("span",{className:"font-mono tabular-nums text-[11px] text-white/40 ml-auto",children:Bo(new Date(C),{addSuffix:!0})})]}),K?n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",title:K,children:K}):null,re?n.jsx("p",{className:"mt-1 line-clamp-2 text-[11px] text-white/50 italic",children:Bt(re)}):null,(me!==null||ke)&&n.jsxs("div",{className:"mt-2",children:[n.jsxs("div",{className:"mb-1 flex items-center justify-between text-micro",children:[n.jsx("span",{className:"text-secondary",children:"Progress"}),n.jsx("span",{className:"font-semibold text-primary tabular-nums",children:me===null?"In progress":`${me}%`})]}),n.jsx("div",{className:`h-1.5 overflow-hidden rounded-full bg-white/[0.09]${me===100?" shimmer-on-complete":""}`,children:me===null?n.jsx("div",{className:"h-full w-1/3 animate-pulse rounded-full bg-[#7dd3c0]/70"}):n.jsx("div",{className:"h-full rounded-full transition-[width] duration-500",style:{width:`${Math.max(3,me)}%`,background:`linear-gradient(90deg, ${Qa(Xa((V=e.session)==null?void 0:V.agentId)).gradient[0]}, ${Qa(Xa((k=e.session)==null?void 0:k.agentId)).gradient[1]})`}})})]}),e.milestoneProgress&&e.milestoneProgress.length>0&&n.jsx("div",{className:"mt-2",children:n.jsx(yu,{nodes:ou({initiativeId:e.initiativeId,initiativeTitle:e.initiativeTitle,workstreamId:e.workstreamId,workstreamTitle:e.workstreamTitle,taskIds:e.taskIds,milestoneIds:e.milestoneIds,scopeProgress:e.milestoneProgress?{totalTasks:e.milestoneProgress.reduce((oe,ie)=>oe+ie.total,0),completedTasks:e.milestoneProgress.reduce((oe,ie)=>oe+ie.done,0),milestones:e.milestoneProgress}:null,status:e.status,agentName:((z=e.session)==null?void 0:z.agentName)??null,agentId:((O=e.session)==null?void 0:O.agentId)??null}),activeId:e.workstreamId,compact:!0})}),Se?n.jsxs("div",{className:"mt-2",children:[n.jsx("button",{type:"button",onClick:oe=>{oe.stopPropagation(),a(ie=>ie===e.key?null:e.key)},className:"inline-flex h-6 items-center gap-1 rounded-full border border-white/[0.12] bg-white/[0.03] px-2 text-micro font-semibold text-secondary transition-colors hover:bg-white/[0.08] hover:text-white",children:G?"Hide details":"Slice details"}),G?n.jsxs("div",{className:"mt-2 space-y-2 rounded-lg border border-white/[0.08] bg-black/[0.18] px-2.5 py-2",children:[e.workstreamTitle?n.jsxs("p",{className:"text-caption text-secondary",children:["Workstream: ",n.jsx("span",{className:"text-white/90",children:e.workstreamTitle})]}):null,n.jsxs("div",{className:"flex flex-wrap gap-1.5 text-micro",children:[n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Tasks ",e.taskIds.length]}),n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Milestones ",e.milestoneIds.length]}),n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Artifacts ",e.artifactCount]}),n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Needs input ",e.decisionCount]})]})]}):null]}):null,n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5 border-t border-white/[0.07] pt-2",onClick:oe=>oe.stopPropagation(),children:[n.jsx("button",{type:"button",onClick:()=>{if(e.session){c==null||c(e.session.id);return}l==null||l(e.runId)},className:"control-pill h-7 px-2.5 text-micro font-semibold",title:e.session?"Open session detail":"Focus in Activity",children:e.session?"Open":"Focus"}),e.session&&ge&&d&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:Fe,onClick:()=>void w(e,d,`Paused ${e.title}.`),className:"control-pill h-7 px-2.5 text-micro font-semibold disabled:opacity-45",title:"Pause and return this workstream to queue",children:"Pause"}),e.session&&Z&&u&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:Fe,onClick:()=>void w(e,u,`Resumed ${e.title}.`),className:"control-pill h-7 px-2.5 text-micro font-semibold disabled:opacity-45",title:"Resume this workstream",children:"Resume"}),e.session&&ae&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:Fe,onClick:()=>void w(e,ae,`Restarted ${e.title}.`),className:"control-pill h-7 px-2.5 text-micro font-semibold disabled:opacity-45",title:"Restart this workstream",children:"Restart"}),e.session&&b&&n.jsx("button",{type:"button",disabled:Fe,onClick:()=>void w(e,b,`Opened intervention for ${e.title}.`),className:"control-pill h-7 px-2.5 text-micro font-semibold disabled:opacity-45",title:"Intervene with context and guidance",children:"Intervene"})]})]})]})]},e.key)}const Cu=new Set(["awaiting_input","needs_review","failed"]);function eo(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Mu(e){var i,a;const t=e.initiativeId??((i=e.initiativeIds)==null?void 0:i[0])??"none",s=e.workstreamId??((a=e.workstreamIds)==null?void 0:a[0])??"none",r=(e.statusExplainer??"").trim().toLowerCase();return[t,s,e.status,e.primaryAction,r].join("|")}function ol(e){const t=e.filter(r=>Cu.has(r.status)).sort((r,i)=>eo(i.updatedAt??i.lastEventAt??"")-eo(r.updatedAt??r.lastEventAt??"")),s=new Map;for(const r of t){const i=Mu(r),a=s.get(i);if(!a){s.set(i,{item:r,duplicateCount:1});continue}a.duplicateCount+=1}return Array.from(s.values())}const to={critical:0,high:1,medium:2,low:3};function Tu(e){return e==="critical"||e==="high"?"border-l-4 border-l-[#FF6B88]":e==="medium"?"border-l-4 border-l-[#F5B700]":"border-l-4 border-l-white/20"}function ji(e){var s,r,i;if(e.severity)return e.severity;const t=(((s=e.impact)==null?void 0:s.initiativeCount)??0)+(((r=e.impact)==null?void 0:r.workstreamCount)??0)+(((i=e.impact)==null?void 0:i.downstreamBlockedCount)??0);return e.blocking||t>=3?"high":e.kind==="review_required"?"low":"medium"}function Eu(e){return e==="approve"?"Approve":e==="reject"?"Reject":e==="retry"?"Retry":e==="autofix"?"Autofix":e==="defer"?"Defer":e==="snooze"?"Snooze":e==="dismiss"?"Dismiss":e==="choose"?"Choose Option":e==="provide_info"?"Provide Info":e==="review"?"Review":"Resolve"}function Ru(e){return e==="failed"?"#FF6B88":e==="needs_review"?"#F5B700":"#BFFF00"}function Du(e){return e==="awaiting_input"?"Input":e==="needs_review"?"Review":e==="failed"?"Failed":e.replace(/_/g," ")}function Lu(e){if(e.artifactCount>0)return`${e.artifactCount} artifact${e.artifactCount===1?"":"s"} ready`;if(e.blockingDecisionCount>0||e.decisionCount>0){const t=Math.max(e.blockingDecisionCount,e.decisionCount);return`${t} decision${t===1?"":"s"} pending`}return e.status==="failed"?"Execution stopped":e.status==="needs_review"?"Output ready for review":"Needs your attention"}function Xi(e,t){if(!e||e.trim().length===0)return t;const s=e.trim();return ms(s)?`${t} ${as(s)}`:s}function Fu(e){if(!e)return null;const t=Bt(e);return t.length<12?null:t.length>96?`${t.slice(0,93)}…`:t}function $u(e,t,s){const r=(t==null?void 0:t.trim())??"";if(r&&!ms(r)){const a=Bt(r);if(a!=="Untitled session")return a}const i=Fu(e.statusExplainer);return i||(s?Xi(s,"Workstream"):Xi(e.sliceRunId,"Slice"))}const Pu=o.memo(function({sliceRuns:t,initiatives:s=[],triageGroups:r=[],onTriageAction:i,title:a="Needs Input",className:c,showHeader:l=!0,panelStyle:d="card",onOpenDecisions:u,onFocusRunId:h,onReviewActivity:y,onOpenSliceDetail:b,onAcceptSlice:p}){const w=o.useMemo(()=>ol(t),[t]),[v,x]=o.useState(new Set),[C,j]=o.useState(new Set),[g,S]=o.useState(null),[W,Y]=o.useState(new Set),[K,me]=o.useState(new Set),ge=o.useMemo(()=>!r||r.length===0?[]:[...r].sort((k,z)=>{const O=to[ji(k.item)]??3,oe=to[ji(z.item)]??3;return O!==oe?O-oe:new Date(z.item.lastSeenAt).getTime()-new Date(k.item.lastSeenAt).getTime()}),[r]),Z=o.useCallback(k=>{Y(z=>{const O=new Set(z);return O.has(k)?O.delete(k):O.add(k),O})},[]),ae=o.useCallback(async(k,z)=>{me(O=>new Set(O).add(k)),S(`Resolving ${k.slice(0,8)}...`);try{await(i==null?void 0:i(k,z)),S(`Resolved ${k.slice(0,8)}`)}catch{S(`Failed to resolve ${k.slice(0,8)}`)}finally{setTimeout(()=>{me(O=>{const oe=new Set(O);return oe.delete(k),oe})},400)}},[i]),ke=w.length+ge.length,Fe=o.useMemo(()=>{const k=new Map;for(const z of s)z.id&&k.set(z.id,z.name??z.id);return k},[s]),G=o.useMemo(()=>{const k=new Map;for(const z of s)for(const O of z.workstreams??[])O.id&&(k.has(O.id)||k.set(O.id,O.name??O.id));return k},[s]),Se=o.useCallback(k=>{x(z=>{const O=new Set(z);return O.has(k)?O.delete(k):O.add(k),O})},[]),Ae=o.useMemo(()=>w.length>0&&w.every(k=>v.has(k.item.sliceRunId)),[w,v]),xe=o.useCallback(()=>{x(k=>Ae?new Set:new Set(w.map(z=>z.item.sliceRunId)))},[Ae,w]),re=v.size,le=o.useCallback(async(k,z)=>{const O=k.sliceRunId??k.id??"";try{S(`Accepting ${O.slice(0,8)}…`),j(oe=>new Set(oe).add(O));try{await(p==null?void 0:p(k,z))}catch{}S(`Accepted ${O.slice(0,8)}`)}catch(oe){S(`Failed: ${oe instanceof Error?oe.message:"network error"}`)}finally{j(oe=>{const ie=new Set(oe);return ie.delete(O),ie})}},[p]),Ee=o.useCallback(()=>{const k=w.filter(z=>v.has(z.item.sliceRunId)&&z.item.status==="needs_review");if(k.length!==0){S(`Accepting ${k.length} items…`);for(const z of k)le(z.item);x(new Set)}},[w,v,le]),ee=o.useCallback(k=>{var z;if(k.primaryAction==="resolve_decision"){u==null||u();return}if(k.primaryAction==="review_output"||k.primaryAction==="retry_slice"){y==null||y(k);return}if(k.primaryAction==="open_artifact"){const O=(z=k.artifacts.find(oe=>oe.url))==null?void 0:z.url;if(O&&typeof window<"u"){window.open(O,"_blank","noopener,noreferrer");return}y==null||y(k);return}if(k.runId){h==null||h(k.runId);return}k.sliceRunId&&(h==null||h(k.sliceRunId))},[u,y,h]),q=o.useMemo(()=>w.filter(k=>k.item.status==="needs_review"),[w]),J=o.useMemo(()=>q.filter(k=>v.has(k.item.sliceRunId)).length,[q,v]),V=d==="card"?Hs:"div";return n.jsxs(V,{className:`flex h-full min-h-0 flex-col overflow-hidden ${c??""}`,children:[l?n.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-white/[0.06] px-4 py-2.5",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n.jsx("h2",{className:"truncate text-body font-semibold text-white/90",children:a}),n.jsx("span",{className:"rounded-full bg-white/[0.06] px-1.5 py-px text-[10px] font-medium tabular-nums text-white/40",children:ke})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[w.length>1&&n.jsx("button",{type:"button",onClick:xe,className:"rounded-md px-2 py-1 text-[11px] font-medium text-white/40 transition-colors hover:bg-white/[0.04] hover:text-white/60",children:Ae?"Clear":"Select all"}),re>0&&J>0&&p&&n.jsx("button",{type:"button",disabled:C.size>0,onClick:Ee,className:"rounded-md bg-[#BFFF00]/10 px-2.5 py-1 text-[11px] font-semibold text-[#BFFF00] transition-colors hover:bg-[#BFFF00]/18 disabled:opacity-40 disabled:pointer-events-none",children:C.size>0?"Accepting...":`Accept ${J}`})]})]}):null,g&&n.jsxs("div",{className:"flex items-center gap-1.5 border-b border-white/[0.04] px-4 py-1 text-[10px] text-[#0AD4C4]/70 animate-pulse",children:[n.jsx("span",{className:"h-1 w-1 rounded-full bg-[#0AD4C4]"}),g]}),ke===0?n.jsx("div",{className:"px-4 py-6 text-center text-caption text-white/30",children:"Nothing needs attention right now."}):n.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[ge.length>0&&n.jsx(pt,{mode:"popLayout",children:ge.map((k,z)=>{const O=k.item,oe=ji(O),ie=Tu(oe),Me=W.has(O.id),ue=K.has(O.id),R=O.actionContract.find($=>$.available);return n.jsxs(be.div,{initial:{opacity:0,y:6},animate:{opacity:ue?.4:1,y:0},exit:{height:0,opacity:0},transition:{type:"spring",stiffness:400,damping:35,delay:Math.min(z,5)*.015},className:`${ie} border-b border-b-white/[0.06] bg-[#08090D] px-4 py-3 transition-colors hover:bg-white/[0.02]`,children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rounded-full",style:{backgroundColor:oe==="critical"||oe==="high"?"#FF6B88":oe==="medium"?"#F5B700":"rgba(255,255,255,0.35)"}}),n.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] font-medium leading-tight text-white/90",children:O.title}),n.jsx("span",{className:"flex-shrink-0 text-[10px] tabular-nums text-white/25",children:It(O.lastSeenAt)})]}),O.summary&&n.jsx("div",{className:"mt-1 pl-[14px] text-[11px] text-white/50",children:O.summary.length>120?`${O.summary.slice(0,117)}...`:O.summary}),(O.initiativeTitle||O.workstreamTitle)&&n.jsxs("div",{className:"mt-px flex items-center gap-1 pl-[14px] text-[10px] text-white/20",children:[O.initiativeTitle&&n.jsxs(n.Fragment,{children:[n.jsx(yn,{type:"initiative",size:8,className:"opacity-50"}),n.jsx("span",{className:"truncate",children:O.initiativeTitle})]}),O.initiativeTitle&&O.workstreamTitle&&n.jsx("span",{className:"text-white/10",children:"/"}),O.workstreamTitle&&n.jsx("span",{className:"truncate",children:O.workstreamTitle})]}),k.count>1&&n.jsxs("button",{type:"button",onClick:()=>Z(O.id),className:"mt-1.5 ml-[14px] inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-white/5 text-[10px] font-mono text-white/50 hover:bg-white/8 transition-colors",children:[k.count," similar",n.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`transition-transform ${Me?"rotate-180":""}`,children:n.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),n.jsx(pt,{children:Me&&k.members.length>1&&n.jsx(be.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.22,ease:[.22,1,.36,1]},className:"mt-1.5 ml-[14px] overflow-hidden",children:k.members.slice(1).map($=>n.jsxs("div",{className:"border-l border-white/[0.06] pl-2 py-1 text-[11px] text-white/35",children:[n.jsx("span",{className:"truncate",children:$.title}),n.jsx("span",{className:"ml-2 text-[10px] text-white/20",children:It($.lastSeenAt)})]},$.id))})}),i&&n.jsxs("div",{className:"flex items-center gap-2 mt-3 pt-3 border-t border-white/[0.06]",children:[R&&n.jsx("button",{type:"button",disabled:ue,onClick:()=>ae(O.id,R.action),className:"px-3 py-1 rounded-full text-[11px] font-medium bg-[#BFFF00]/10 text-[#BFFF00] border border-[#BFFF00]/20 hover:bg-[#BFFF00]/20 disabled:opacity-40 disabled:pointer-events-none transition-colors",children:Eu(R.action)}),n.jsx("button",{type:"button",disabled:ue,onClick:()=>ae(O.id,"dismiss"),className:"px-3 py-1 rounded-full text-[11px] font-medium border border-white/10 text-white/50 hover:text-white/70 disabled:opacity-40 disabled:pointer-events-none transition-colors",children:"Dismiss"})]})]},O.id)})}),n.jsx(pt,{mode:"popLayout",children:w.map(({item:k,duplicateCount:z},O)=>{const oe=(Array.isArray(k.initiativeIds)&&k.initiativeIds.length>0?k.initiativeIds[0]:k.initiativeId)??null,ie=(Array.isArray(k.workstreamIds)&&k.workstreamIds.length>0?k.workstreamIds[0]:k.workstreamId)??null,Me=(oe?Fe.get(oe):null)??Xi(oe,"Initiative"),ue=k.workstreamTitle??(ie?G.get(ie)??null:null),R=$u(k,ue,ie),$=Bt(Lu(k)),X=Bt(Me),te=k.updatedAt??k.lastEventAt??null,Le=Ru(k.status),qe=v.has(k.sliceRunId),_e=C.has(k.sliceRunId),M=k.status==="needs_review";return n.jsx(be.article,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,x:120,scale:.97},transition:{duration:.2,delay:Math.min(O,5)*.015,ease:[.22,1,.36,1]},className:"group relative cursor-pointer border-b border-subtle transition-colors hover:bg-white/[0.02]",style:{backgroundColor:qe?"rgba(191,255,0,0.03)":void 0,opacity:_e?.5:void 0},role:"button",tabIndex:0,onClick:B=>{B.target.closest("button, input, [data-stop-row]")||(S("Opening detail…"),b==null||b(k))},onKeyDown:B=>{(B.key==="Enter"||B.key===" ")&&(B.preventDefault(),b==null||b(k))},children:n.jsxs("div",{className:"flex items-start gap-2.5 py-2.5 pl-3 pr-3",children:[n.jsx("div",{className:"flex-shrink-0 pt-0.5",children:n.jsx("input",{type:"checkbox",checked:qe,onChange:()=>Se(k.sliceRunId),className:"h-4 w-4 rounded-sm border-white/15 bg-transparent text-[#BFFF00] focus:ring-0 focus:ring-offset-0 cursor-pointer"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rounded-full",style:{backgroundColor:Le}}),n.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] font-medium leading-tight text-white/90",children:R}),n.jsx("span",{className:"flex-shrink-0 text-[10px] tabular-nums text-white/25",children:te?It(te):Du(k.status)})]}),n.jsxs("div",{className:"mt-0.5 flex items-baseline gap-1.5 pl-[14px]",children:[n.jsx("span",{className:"min-w-0 truncate text-[11px] leading-relaxed text-white/35",children:$}),z>1&&n.jsxs("span",{className:"flex-shrink-0 text-[10px] text-white/20",children:["+",z-1]})]}),n.jsxs("div",{className:"mt-px flex items-center gap-1 pl-[14px] text-[10px] text-white/20",children:[n.jsx(yn,{type:"initiative",size:8,className:"opacity-50"}),n.jsx("span",{className:"truncate",children:X})]})]}),n.jsx("div",{className:"flex flex-shrink-0 items-center gap-1 self-center",children:M&&p?n.jsxs("button",{type:"button",disabled:_e,onClick:()=>le(k),className:"flex h-6 items-center gap-1 rounded-md bg-[#BFFF00]/8 px-2 text-[11px] font-medium text-[#BFFF00]/70 transition-all hover:bg-[#BFFF00]/15 hover:text-[#BFFF00] disabled:opacity-40",children:[n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"20 6 9 17 4 12"})}),_e?"Accepting...":"Accept"]}):n.jsx("button",{type:"button",onClick:()=>ee(k),className:"flex h-6 items-center rounded-md px-2 text-[11px] font-medium text-white/45 opacity-100 transition-all md:opacity-0 md:group-hover:opacity-100 hover:bg-white/[0.04] hover:text-white/70",children:k.status==="failed"?"Retry":"View"})})]})},k.sliceRunId)})})]})]})});function Ou(e){const t=e.toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function Bu(e){if(!e)return 0;const t=new Date(e),s=new Date;return Math.max(0,Math.ceil((t.getTime()-s.getTime())/864e5))}function qu(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function zu(e){return{id:e.id,name:e.title,status:Ou(e.status),rawStatus:e.status??null,priority:e.priority??null,health:e.progress_pct??0,daysRemaining:Bu(e.target_date),targetDate:e.target_date??null,createdAt:e.created_at??null,updatedAt:e.updated_at??e.created_at??null,activeAgents:0,totalAgents:0,description:e.summary??void 0}}const no=150,Uu=12;function so(e){const t=Date.parse(e??"");return Number.isFinite(t)?t:0}function Wu(){const e=new Date,t=864e5;return[{id:"init-1",name:"Q4 Feature Ship",status:"active",rawStatus:"active",priority:"high",health:38,daysRemaining:16,targetDate:new Date(e.getTime()+16*t).toISOString(),createdAt:new Date(e.getTime()-18*t).toISOString(),updatedAt:new Date(e.getTime()-5*6e4).toISOString(),activeAgents:2,totalAgents:3,description:"Finalize launch readiness for the Q4 initiative."},{id:"init-2",name:"Black Friday Email",status:"active",rawStatus:"active",priority:"medium",health:55,daysRemaining:10,targetDate:new Date(e.getTime()+10*t).toISOString(),createdAt:new Date(e.getTime()-22*t).toISOString(),updatedAt:new Date(e.getTime()-15*6e4).toISOString(),activeAgents:1,totalAgents:2,description:"Generate and validate campaign assets for holiday launch."}]}function ll(e,t=null){return ds({queryKey:Gn.entities({type:"initiative",projectId:t}),queryFn:async()=>{var l;if($t())return Wu();const s=[],r=(t==null?void 0:t.trim())??"";let i=0;for(let d=0;d<Uu;d+=1){const u=new URLSearchParams({type:"initiative",limit:String(no),offset:String(i)});r&&us(u,r);const h=await fetch(`/orgx/api/entities?${u.toString()}`,{headers:_t({workspaceId:r})});if(!h.ok)break;const y=await h.json(),b=y.data??[];if(s.push(...b),!!!((l=y.pagination)!=null&&l.has_more)||b.length===0)break;i+=no}const a=r.length>0&&s.some(d=>(d.command_center_id??d.commandCenterId??"").trim().length>0),c=new Map;for(const d of s){const u=c.get(d.id);if(!u){c.set(d.id,d);continue}so(d.updated_at??d.created_at)>so(u.updated_at??u.created_at)&&c.set(d.id,d)}return Array.from(c.values()).filter(d=>!r||!a?!0:(d.command_center_id??d.commandCenterId??"").trim()===r).filter(d=>qu(d.status)).sort((d,u)=>{const h=Date.parse(d.updated_at??d.created_at??"")||0;return(Date.parse(u.updated_at??u.created_at??"")||0)-h}).map(zu)},enabled:e,staleTime:6e4})}const Mr=50,ro=8;function Hu(e){const t=(e??"").toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function Vu(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function Ku(e){return{id:e.id,name:e.title,status:Hu(e.status),rawStatus:e.status??null,priority:e.priority??null,category:void 0,health:Math.max(0,Math.min(100,Math.round(e.progress??0))),daysRemaining:0,targetDate:e.targetDate??e.dueDate??e.etaEndAt??null,createdAt:e.createdAt??null,updatedAt:e.updatedAt??null,activeAgents:0,totalAgents:0,description:void 0}}function Gu(e,t=null){return ds({queryKey:Gn.liveInitiatives({limit:Mr*ro,projectId:t}),queryFn:async()=>{var c;if($t())return[];const s=[];let r=0;for(let l=0;l<ro;l+=1){const d=new URLSearchParams({limit:String(Mr),offset:String(r)});t&&t.trim().length>0&&us(d,t);const u=await fetch(`/orgx/api/live/initiatives?${d.toString()}`,{headers:_t({workspaceId:t})});if(!u.ok)break;const h=await u.json(),y=h.initiatives??[];s.push(...y);const b=typeof h.total=="number"?h.total:null,p=(c=h.pagination)==null?void 0:c.has_more;if(!(typeof p=="boolean"?p:b!==null?r+y.length<b:y.length===Mr)||y.length===0)break;r+=Mr}const i=(t==null?void 0:t.trim())??"",a=i.length>0&&s.some(l=>(l.command_center_id??l.commandCenterId??"").trim().length>0);return s.filter(l=>!i||!a?!0:(l.command_center_id??l.commandCenterId??"").trim()===i).filter(l=>Vu(l.status)).map(Ku)},enabled:e,staleTime:3e4})}const cl=o.createContext(null),io={artifactId:null,contentBlob:null,detectedLanguage:null,agentColor:null};function Xu({children:e}){const[t,s]=o.useState(io),r=o.useCallback((c,l,d)=>{s({artifactId:c,context:l,contentBlob:(d==null?void 0:d.contentBlob)??null,detectedLanguage:(d==null?void 0:d.detectedLanguage)??null,agentColor:(d==null?void 0:d.agentColor)??null})},[]),i=o.useCallback(()=>{s(io)},[]),a=o.useCallback(c=>{s(l=>({...l,contentBlob:c.contentBlob!==void 0?c.contentBlob:l.contentBlob,detectedLanguage:c.detectedLanguage!==void 0?c.detectedLanguage:l.detectedLanguage,agentColor:c.agentColor!==void 0?c.agentColor:l.agentColor}))},[]);return n.jsx(cl.Provider,{value:{state:t,open:r,close:i,setContentMeta:a},children:e})}function dl(){const e=o.useContext(cl);if(!e)throw new Error("useArtifactViewer must be used within ArtifactViewerProvider");return e}function Qu(e){const{running:t,blocked:s,decisionsCount:r,completedToday:i,onDecisionsClick:a,onBlockedClick:c,onNewInitiative:l}=e,d=r+s;return t===0&&d===0&&i===0?{key:"idle-empty",segments:[{text:"All caught up. "},l?{text:"Start something new?",color:F.lime,clickable:!0,onClick:l}:{text:"Nothing running."}]}:t===0&&d===0?{key:"idle-done",segments:[{text:`${i} done today`,color:F.teal},{text:" · all caught up"}]}:s>0&&r>0?{key:`blocked-decisions-${s}-${r}-${t}`,segments:[...t>0?[{text:`${t} running · `}]:[],{text:`${s} blocked`,color:F.red,clickable:!0,onClick:c},{text:" · "},{text:`${r} need your input`,color:F.amber,clickable:!0,onClick:a}]}:s>0?{key:`blocked-${s}-${t}`,segments:[{text:`${s} blocked`,color:F.red,clickable:!0,onClick:c},...t>0?[{text:` · ${t} running`}]:[]]}:r>0?{key:`decisions-${r}-${t}`,segments:[...t>0?[{text:`${t} running`,color:F.lime},{text:" · "}]:[],{text:`${r} need your input`,color:F.amber,clickable:!0,onClick:a}]}:{key:`running-${t}`,segments:[{text:`${t} running`,color:F.lime},{text:" · all systems go"}]}}function ao(e){const{className:t}=e,{key:s,segments:r}=Qu(e);return n.jsx("div",{className:`flex items-center gap-1.5 whitespace-nowrap text-body ${t??""}`,children:n.jsx(pt,{mode:"wait",children:n.jsx(be.span,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.18,ease:[.22,1,.36,1]},className:"inline-flex flex-wrap items-baseline gap-0",children:r.map((i,a)=>i.clickable&&i.onClick?n.jsx("button",{onClick:i.onClick,className:"font-semibold transition-opacity hover:opacity-80",style:{color:i.color},children:i.text},a):n.jsx("span",{className:i.color?"font-semibold":"text-secondary",style:i.color?{color:i.color}:void 0,children:i.text},a))},s)})})}const Ju={done:"text-[#14B8A6] bg-[#14B8A6]/10 border-[#14B8A6]/20",completed:"text-[#14B8A6] bg-[#14B8A6]/10 border-[#14B8A6]/20",in_progress:"text-[#BFFF00] bg-[#BFFF00]/10 border-[#BFFF00]/20",active:"text-[#BFFF00] bg-[#BFFF00]/10 border-[#BFFF00]/20",blocked:"text-[#FF6B88] bg-[#FF6B88]/10 border-[#FF6B88]/20",todo:"text-white/60 bg-white/5 border-white/10"},bh=e=>Ju[zt(e)]??"text-white/60 bg-white/5 border-white/10",wh=e=>{const t=zt(e);return t==="done"||t==="completed"?"text-[#14B8A6] bg-[#14B8A6]/10 border-[#14B8A6]/20":t==="active"||t==="in_progress"?"text-[#BFFF00] bg-[#BFFF00]/10 border-[#BFFF00]/20":"text-white/60 bg-white/5 border-white/10"},vh=e=>e.replace(/[_-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase()),kh=e=>{const t=zt(e);return t==="blocked"?0:t==="in_progress"||t==="active"?1:t==="todo"||t==="planned"?2:t==="done"||t==="completed"?3:4},As=e=>{const t=zt(e);return t==="blocked"||t==="failed"||t==="cancelled"?F.red:t==="active"||t==="in_progress"||t==="running"?F.lime:t==="handoff"||t==="review"||t==="done"||t==="completed"?F.teal:t==="paused"||t==="queued"||t==="pending"||t==="working"||t==="planning"?F.amber:t==="archived"||t==="draft"?"rgba(255,255,255,0.5)":"rgba(255,255,255,0.35)"},jh={Queued:"text-white/60 bg-white/5 border-white/10",Dispatching:"text-[#0AD4C4] bg-[#0AD4C4]/10 border-[#0AD4C4]/20","In Progress":"text-[#14B8A6] bg-[#14B8A6]/10 border-[#14B8A6]/20",Blocked:"text-[#FF6B88] bg-[#FF6B88]/10 border-[#FF6B88]/20",Completed:"text-[#14B8A6] bg-[#14B8A6]/10 border-[#14B8A6]/20",Paused:"text-[#F5B700] bg-[#F5B700]/10 border-[#F5B700]/20",Failed:"text-[#FF6B88] bg-[#FF6B88]/10 border-[#FF6B88]/20"},Nh={Queued:"rgba(255,255,255,0.6)",Dispatching:"#0AD4C4","In Progress":"#14B8A6",Blocked:"#FF6B88",Completed:"#14B8A6",Paused:"#F5B700",Failed:"#FF6B88"},Qr={codex:{id:"codex",label:"Codex",accent:"#10B981",tint:"rgba(16, 185, 129, 0.18)"},openai:{id:"openai",label:"OpenAI",accent:"#10B981",tint:"rgba(16, 185, 129, 0.18)"},anthropic:{id:"anthropic",label:"Anthropic",accent:"#F5B700",tint:"rgba(245, 183, 0, 0.18)"},openclaw:{id:"openclaw",label:"OpenClaw",accent:"#FF4D4D",tint:"rgba(255, 77, 77, 0.18)"},orgx:{id:"orgx",label:"OrgX",accent:F.lime,tint:"rgba(191, 255, 0, 0.18)"},unknown:{id:"unknown",label:"Agent",accent:F.teal,tint:"rgba(20, 184, 166, 0.18)"}},Yu=["provider","vendor","model","runtime","engine","agent","name","title","label","summary","description","source"];function Hr(e,t,s,r){if(!(e==null||s>2)){if(typeof e=="string"){const i=e.trim();i.length>0&&t.push(i);return}if(Array.isArray(e)){for(const i of e)Hr(i,t,s+1,r);return}if(typeof e=="object"){if(r.has(e))return;r.add(e);for(const[i,a]of Object.entries(e)){const c=i.toLowerCase();typeof a=="string"?(Yu.some(l=>c.includes(l))||c.startsWith("meta")||c.endsWith("id"))&&Hr(a,t,s+1,r):typeof a=="object"&&a!==null&&Hr(a,t,s+1,r)}}}}function Zu(e){const t=e.toLowerCase();return/\bcodex\b/.test(t)||/\bcursor\b/.test(t)||t.includes("openai/codex")?"codex":t.includes("openclaw")||t.includes("clawdbot")||t.includes("moltbot")?"openclaw":t.includes("anthropic")||t.includes("claude")||t.includes("sonnet")||t.includes("opus")?"anthropic":t.includes("openai")||t.includes("chatgpt")||/\bgpt[-\s]?\d/.test(t)||/\bo[134]/.test(t)?"openai":t.includes("orgx")?"orgx":null}function os(...e){const t=[],s=new Set;for(const r of e)Hr(r,t,0,s);for(const r of t){const i=Zu(r);if(i)return Qr[i]}return Qr.unknown}function em(e){return Qr[e]??Qr.unknown}const tm={xs:18,sm:24,md:30};function nm({provider:e}){switch(e){case"openai":case"codex":return n.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:n.jsx("path",{fill:"currentColor",d:"M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.872zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z"})});case"anthropic":return n.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:n.jsx("path",{fill:"currentColor",d:"M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z"})});case"openclaw":return n.jsxs("svg",{viewBox:"0 0 120 120","aria-hidden":"true",children:[n.jsx("path",{d:"M60 10C30 10 15 35 15 55C15 75 30 95 45 100V110H55V100C55 100 60 102 65 100V110H75V100C90 95 105 75 105 55C105 35 90 10 60 10Z",fill:"currentColor"}),n.jsx("path",{d:"M20 45C5 40 0 50 5 60C10 70 20 65 25 55C28 48 25 45 20 45Z",fill:"currentColor"}),n.jsx("path",{d:"M100 45C115 40 120 50 115 60C110 70 100 65 95 55C92 48 95 45 100 45Z",fill:"currentColor"}),n.jsx("circle",{cx:"45",cy:"35",r:"6",fill:"rgba(2,4,10,0.92)"}),n.jsx("circle",{cx:"75",cy:"35",r:"6",fill:"rgba(2,4,10,0.92)"})]});case"orgx":return n.jsx("img",{src:ii,alt:"","aria-hidden":"true",className:"h-full w-full rounded-[4px] object-contain"});default:return n.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:[n.jsx("circle",{cx:"12",cy:"12",r:"8",stroke:"currentColor",strokeWidth:"1.8",fill:"none"}),n.jsx("path",{d:"m12 6-2 7h3l-1 5 4-8h-3l1-4Z",fill:"currentColor"})]})}}function Vs({provider:e,size:t="sm",className:s,showRing:r=!0}){const i=em(e),a=tm[t];return n.jsx("span",{className:pe("inline-flex items-center justify-center rounded-md",s),style:{width:a,height:a,color:i.accent,backgroundColor:i.tint,border:r?`1px solid ${i.accent}55`:"none"},title:i.label,"aria-label":i.label,children:n.jsx("span",{style:{width:Math.round(a*.66),height:Math.round(a*.66),display:"inline-flex",alignItems:"center",justifyContent:"center"},children:n.jsx(nm,{provider:e})})})}function sm({running:e,blocked:t,paused:s,size:r=36,children:i}){const a=Xn(),c=e+t+s,l=o.useMemo(()=>{if(c===0)return[];const p=[];return e>0&&p.push({color:F.lime,fraction:e/c}),t>0&&p.push({color:F.red,fraction:t/c}),s>0&&p.push({color:F.amber,fraction:s/c}),p},[e,t,s,c]),d=2.5,u=(r-d)/2,h=2*Math.PI*u,y=r/2;if(c===0)return n.jsxs("div",{className:"relative inline-flex items-center justify-center",style:{width:r,height:r},children:[n.jsx("svg",{width:r,height:r,className:"absolute inset-0",style:{transform:"rotate(-90deg)"},children:n.jsx("circle",{cx:y,cy:y,r:u,fill:"none",stroke:"rgba(255,255,255,0.08)",strokeWidth:d})}),n.jsx("div",{className:"relative z-10",children:i})]});let b=0;return n.jsxs("div",{className:"relative inline-flex items-center justify-center",style:{width:r,height:r},children:[n.jsxs("svg",{width:r,height:r,className:"absolute inset-0",style:{transform:"rotate(-90deg)"},children:[n.jsx("circle",{cx:y,cy:y,r:u,fill:"none",stroke:"rgba(255,255,255,0.06)",strokeWidth:d}),l.map((p,w)=>{const v=p.fraction*h,x=-b;return b+=v,n.jsx(be.circle,{cx:y,cy:y,r:u,fill:"none",stroke:p.color,strokeWidth:d,strokeLinecap:"round",strokeDasharray:`${v} ${h-v}`,strokeDashoffset:x,initial:a?!1:{strokeDasharray:`0 ${h}`},animate:{strokeDasharray:`${v} ${h-v}`},transition:{duration:.5,delay:w*.08,ease:[.22,1,.36,1]},style:{opacity:.85}},w)})]}),n.jsx("div",{className:"relative z-10",children:i})]})}const Tr={initiativeId:"",workstreams:[],milestones:[],tasks:[]},rm=(e,t)=>({id:e.id,name:e.name??"Untitled workstream",summary:e.summary??null,status:e.status??"planned",progress:typeof e.progress=="number"&&!Number.isNaN(e.progress)?Math.max(0,Math.min(100,e.progress<=1?e.progress*100:e.progress)):null,initiativeId:e.initiative_id??t,createdAt:e.created_at??null}),im=(e,t)=>({id:e.id,title:e.title??"Untitled milestone",description:e.description??null,status:e.status??"planned",dueDate:e.due_date??null,initiativeId:e.initiative_id??t,workstreamId:e.workstream_id??null,createdAt:e.created_at??null}),am=(e,t)=>({id:e.id,title:e.title??"Untitled task",description:e.description??null,status:e.status??"todo",priority:e.priority??null,dueDate:e.due_date??null,initiativeId:e.initiative_id??t,milestoneId:e.milestone_id??null,workstreamId:e.workstream_id??null,createdAt:e.created_at??null});function om(e){const t=new Date().toISOString();return e==="init-1"?{initiativeId:e,workstreams:[{id:"ws-4",name:"Dashboard UI pass",summary:"Polish interaction details and close accessibility feedback.",status:"active",progress:70,initiativeId:e,createdAt:t},{id:"ws-5",name:"Usage tracking instrumentation",summary:"Waiting on events table access.",status:"blocked",progress:25,initiativeId:e,createdAt:t}],milestones:[{id:"ms-1",title:"UX polish complete",description:"All blocking review comments resolved.",status:"active",dueDate:null,initiativeId:e,workstreamId:"ws-4",createdAt:t}],tasks:[{id:"task-1",title:"Polish timeline controls",description:null,status:"in_progress",priority:"high",dueDate:null,initiativeId:e,milestoneId:"ms-1",workstreamId:"ws-4",createdAt:t},{id:"task-2",title:"Validate mobile overlays",description:null,status:"todo",priority:"medium",dueDate:null,initiativeId:e,milestoneId:"ms-1",workstreamId:"ws-4",createdAt:t},{id:"task-3",title:"Grant data pipeline access",description:null,status:"blocked",priority:"high",dueDate:null,initiativeId:e,milestoneId:null,workstreamId:"ws-5",createdAt:t}]}:{initiativeId:e,workstreams:[{id:"ws-9",name:"Email campaign generation",summary:"Final review of subject line variants.",status:"active",progress:55,initiativeId:e,createdAt:t}],milestones:[],tasks:[{id:"task-9",title:"Prepare launch variants",description:null,status:"in_progress",priority:"medium",dueDate:null,initiativeId:e,milestoneId:null,workstreamId:"ws-9",createdAt:t}]}}function lm({initiativeId:e,authToken:t=null,embedMode:s=!1,enabled:r=!0}){var l;const i=Rc(e),a=o.useMemo(()=>Gn.initiativeDetails({initiativeId:e,authToken:t,embedMode:s}),[e,t,s]),c=ds({queryKey:a,enabled:r&&!!e&&i,queryFn:async()=>{if(!e)return Tr;if($t())return om(e);if(!i)return{...Tr,initiativeId:e};const d={};s&&(d["X-Orgx-Embed"]="true"),t&&(d.Authorization=`Bearer ${t}`);const u=Object.keys(d).length?d:void 0,h=async C=>{try{const j=new URLSearchParams({type:C,initiative_id:e,limit:"100"}),g=await fetch(`/orgx/api/entities?${j.toString()}`,{headers:u});return g.ok?await g.json():{data:[]}}catch{return{data:[]}}},[y,b,p]=await Promise.all([h("workstream"),h("milestone"),h("task")]),w=Array.isArray(y.data)?y.data.map(C=>rm(C,e)):[],v=Array.isArray(b.data)?b.data.map(C=>im(C,e)):[],x=Array.isArray(p.data)?p.data.map(C=>am(C,e)):[];return{initiativeId:e,workstreams:w,milestones:v,tasks:x}}});return{details:(i?c.data:null)??(e?{...Tr,initiativeId:e}:Tr),isLoading:i?c.isLoading:!1,error:i?((l=c.error)==null?void 0:l.message)??null:null,refetch:c.refetch}}function cm(){const e=new Date().toISOString();return{generatedAt:e,agents:[{id:"eli",name:"Eli",workspace:"Q4 Feature Ship",model:"gpt-5",isDefault:!0,status:"running",currentTask:"Planning",runId:"run-1",startedAt:e,blockers:[],context:null},{id:"dana",name:"Dana",workspace:"Q4 Feature Ship",model:"claude-sonnet-4.5",isDefault:!1,status:"running",currentTask:"Dashboard UI pass",runId:"run-2",startedAt:e,blockers:["Approval pending"],context:null},{id:"mark",name:"Mark",workspace:"Black Friday Email",model:"gpt-5-mini",isDefault:!1,status:"running",currentTask:"Campaign variants",runId:"run-4",startedAt:e,blockers:[],context:null}]}}function ca({enabled:e=!0,staleTime:t=5e3,refetchInterval:s}={}){return ds({queryKey:["openclaw-agent-catalog"],queryFn:async()=>{if($t())return cm();const r=await fetch("/orgx/api/agents/catalog");if(!r.ok){const i=await r.text().catch(()=>"");throw new Error(i||`Agent catalog failed (${r.status})`)}return await r.json()},enabled:e,staleTime:t,refetchInterval:s??(e?8e3:!1)})}function ar(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:F.lime,bg:"rgba(191,255,0,0.12)"}:t==="blocked"?{label:"Blocked",color:"#fb7185",bg:"rgba(244, 63, 94, 0.12)"}:t==="idle"?{label:"Idle",color:"rgba(255,255,255,0.55)",bg:"rgba(255,255,255,0.06)"}:{label:e||"Unknown",color:F.iris,bg:"rgba(124,124,255,0.10)"}}function dm(e){return[...e.workstreams].sort((t,s)=>t.name.localeCompare(s.name))}function um(e,t){return[...t?e.tasks.filter(r=>r.workstreamId===t):e.tasks].sort((r,i)=>r.title.localeCompare(i.title))}function mm({open:e,onClose:t,onLaunched:s}){var z,O,oe,ie,Me,ue;const r=ca({enabled:e,staleTime:2e3,refetchInterval:e?3e3:!1}),{data:i}=ll(e),[a,c]=o.useState(""),[l,d]=o.useState(""),[u,h]=o.useState(""),[y,b]=o.useState(""),[p,w]=o.useState("auto"),[v,x]=o.useState(""),[C,j]=o.useState(null),[g,S]=o.useState(null),[W,Y]=o.useState("starter"),[K,me]=o.useState(!1),[ge,Z]=o.useState(1),ae=$t(),ke=o.useMemo(()=>{const R=l.trim();return R?(i==null?void 0:i.find($=>$.id===R))??null:null},[i,l]),{details:Fe}=lm({initiativeId:ke?ke.id:null,enabled:e&&!!ke}),G=o.useMemo(()=>dm(Fe),[Fe]),Se=o.useMemo(()=>um(Fe,u||null),[Fe,u]),Ae=((z=r.data)==null?void 0:z.agents)??[],xe=o.useMemo(()=>{const R=a.trim();return R?Ae.find($=>$.id===R)??null:null},[Ae,a]);o.useEffect(()=>{var $,X;if(!e)return;const R=(($=Ae.find(te=>te.isDefault))==null?void 0:$.id)??((X=Ae[0])==null?void 0:X.id)??"";!a&&R&&c(R)},[Ae,e,a]),o.useEffect(()=>{if(!e||l.trim())return;const R=i??[],$=R.length===1?R[0]:null;$&&d($.id)},[i,e,l]),o.useEffect(()=>{if(!e)return;const R=(xe==null?void 0:xe.model)??"",$=R.includes("openrouter")?"openrouter":R.includes("anthropic")?"anthropic":R.includes("openai")?"openai":"auto";w($)},[e,xe==null?void 0:xe.model,a]),o.useEffect(()=>{e&&(j(null),S(null),Y("starter"),Z(1))},[e]),o.useEffect(()=>{h(""),b("")},[l]),o.useEffect(()=>{b("")},[u]),o.useEffect(()=>{e&&(v.trim().length>0||ke&&x(`Kick off: ${ke.name}`))},[v,e,ke]);const re=!!a.trim()&&!!l.trim(),le=ge===1?!!a.trim():ge===2?!!l.trim():re,Ee=async()=>{var qe;const R=(g==null?void 0:g.checkout)??"/orgx/api/billing/checkout",$=W&&W.trim().length>0?W.trim():"starter",te=await(await fetch(R,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:$,billingCycle:"monthly"})})).json().catch(()=>null),Le=((qe=te==null?void 0:te.data)==null?void 0:qe.url)??(te==null?void 0:te.url)??null;if(!Le)throw new Error((te==null?void 0:te.error)??"Checkout unavailable");window.open(Le,"_blank","noopener,noreferrer")},ee=async()=>{var Le;const R=(g==null?void 0:g.portal)??"/orgx/api/billing/portal",X=await(await fetch(R,{method:"POST"})).json().catch(()=>null),te=((Le=X==null?void 0:X.data)==null?void 0:Le.url)??(X==null?void 0:X.url)??null;if(!te)throw new Error((X==null?void 0:X.error)??"Billing portal unavailable");window.open(te,"_blank","noopener,noreferrer")},q=async()=>{if(!(!re||K)){if(ae){t(),s==null||s();return}j(null),S(null),me(!0);try{const R={agentId:a.trim(),message:v.trim()?v.trim():void 0,initiativeId:l.trim(),initiativeTitle:(ke==null?void 0:ke.name)??null,workstreamId:u.trim()?u.trim():null,taskId:y.trim()?y.trim():null,provider:p!=="auto"?p:null},$=new URLSearchParams;$.set("agentId",R.agentId),$.set("initiativeId",R.initiativeId),R.initiativeTitle&&$.set("initiativeTitle",R.initiativeTitle),R.workstreamId&&$.set("workstreamId",R.workstreamId),R.taskId&&$.set("taskId",R.taskId),R.message&&$.set("message",R.message),R.provider&&$.set("provider",R.provider);const X=await fetch(`/orgx/api/agents/launch?${$.toString()}`,{method:"POST"}),te=await X.json().catch(()=>null);if(!X.ok||!(te!=null&&te.ok))throw(te==null?void 0:te.code)==="upgrade_required"&&(S(te.actions??null),Y(te.requiredPlan??"starter")),new Error((te==null?void 0:te.error)??`Launch failed (${X.status})`);t(),s==null||s()}catch(R){j(R instanceof Error?R.message:"Launch failed")}finally{me(!1)}}},J=!!((O=xe==null?void 0:xe.run)!=null&&O.runId)&&!!((oe=xe==null?void 0:xe.run)!=null&&oe.pid),V=async()=>{var R;if(!(!((R=xe==null?void 0:xe.run)!=null&&R.runId)||!J||K)&&!ae){j(null),me(!0);try{const $=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(xe.run.runId)}`,{method:"POST"}),X=await $.json().catch(()=>null);if(!$.ok||!(X!=null&&X.ok))throw new Error((X==null?void 0:X.error)??`Stop failed (${$.status})`);await r.refetch()}catch($){j($ instanceof Error?$.message:"Stop failed")}finally{me(!1)}}},k=async()=>{var R;if(!(!((R=xe==null?void 0:xe.run)!=null&&R.runId)||K)){if(ae){t(),s==null||s();return}j(null),me(!0);try{const $=new URLSearchParams;$.set("runId",xe.run.runId),v.trim()&&$.set("message",v.trim()),p&&p!=="auto"&&$.set("provider",p);const X=await fetch(`/orgx/api/agents/restart?${$.toString()}`,{method:"POST"}),te=await X.json().catch(()=>null);if(!X.ok||!(te!=null&&te.ok))throw new Error((te==null?void 0:te.error)??`Restart failed (${X.status})`);t(),s==null||s()}catch($){j($ instanceof Error?$.message:"Restart failed")}finally{me(!1)}}};return e?n.jsx(ai,{open:e,onClose:t,maxWidth:"max-w-2xl",children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[n.jsx("div",{className:"border-b border-subtle px-5 py-4 sm:px-6",children:n.jsxs("div",{className:"flex items-start justify-between gap-4",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-heading font-semibold text-white",children:"Launch OpenClaw Agent"}),n.jsx("p",{className:"mt-1 text-body text-secondary",children:"Starts a background agent turn and scopes the resulting sessions/activity to the selected OrgX initiative."}),n.jsx("div",{className:"mt-3 inline-flex items-center gap-1 rounded-full border border-strong bg-white/[0.03] p-1 text-micro uppercase tracking-[0.12em] text-secondary",children:[[1,"Agent"],[2,"Scope"],[3,"Message"]].map(([R,$])=>n.jsxs("button",{type:"button",onClick:()=>Z(R),className:pe("rounded-full px-3 py-1 transition-colors",ge===R?"bg-white/[0.12] text-white":"hover:bg-white/[0.06]"),children:[R,". ",$]},R))})]}),n.jsx("button",{type:"button",onClick:t,className:"rounded-lg border border-strong bg-white/[0.03] px-3 py-1.5 text-body text-secondary hover:bg-white/[0.08] hover:text-white",children:"Close"})]})}),n.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-5 py-4 sm:px-6",children:[r.isLoading&&n.jsx("div",{className:"rounded-xl border border-subtle bg-white/[0.02] p-4 text-body text-secondary",children:"Loading agent catalog…"}),r.error&&n.jsx("div",{className:"rounded-xl border border-rose-300/20 bg-rose-400/10 p-4 text-body text-rose-100",children:r.error.message}),n.jsx(pt,{mode:"wait",children:n.jsxs(be.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},transition:{duration:.22,ease:[.16,1,.3,1]},className:"mt-3 space-y-4",children:[ge===1&&n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-caption uppercase tracking-[0.1em] text-muted",children:"Agent"}),n.jsx("select",{value:a,onChange:R=>c(R.target.value),className:"mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-[#BFFF00]/30",children:Ae.map(R=>{const $=ar(R.status);return n.jsxs("option",{value:R.id,children:[R.name," (",R.id,") · ",$.label]},R.id)})})]}),xe&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] p-3 text-body text-secondary",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:"font-medium text-primary",children:xe.name}),n.jsx("span",{className:"rounded-full border px-2 py-0.5 text-micro uppercase tracking-[0.12em]",style:{borderColor:`${ar(xe.status).color}55`,color:ar(xe.status).color,backgroundColor:ar(xe.status).bg},children:ar(xe.status).label})]}),n.jsxs("div",{className:"mt-2 space-y-2",children:[n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Model:"})," ",xe.model??"unknown"]}),n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Workspace:"})," ",xe.workspace??"unknown"]}),((ie=xe.context)==null?void 0:ie.initiativeId)&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Scoped:"})," ",xe.context.initiativeTitle??xe.context.initiativeId]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Provider"}),n.jsxs("select",{value:p,onChange:R=>w(R.target.value),className:"mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-[#BFFF00]/30",children:[n.jsx("option",{value:"auto",children:"Auto (keep agent model)"}),n.jsx("option",{value:"anthropic",children:"Anthropic"}),n.jsx("option",{value:"openrouter",children:"OpenRouter"}),n.jsx("option",{value:"openai",children:"OpenAI"})]}),n.jsx("p",{className:"mt-1 text-micro text-muted",children:"Selecting a provider updates the agent's default model before launch."})]}),xe.run&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Tracked run:"})," ",xe.run.runId.slice(0,8),"…"," ",n.jsxs("span",{className:"text-muted",children:["(",xe.run.status,")"]})]}),xe.run&&n.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-1",children:[n.jsx("button",{type:"button",onClick:V,disabled:!J||K,className:"rounded-lg border border-rose-300/25 bg-rose-400/10 px-3 py-2 text-caption font-semibold text-rose-100 transition-colors hover:bg-rose-400/20 disabled:opacity-45",children:"Stop Run"}),n.jsx("button",{type:"button",onClick:k,disabled:K,className:"rounded-lg border border-strong bg-white/[0.03] px-3 py-2 text-caption font-semibold text-primary transition-colors hover:bg-white/[0.08] disabled:opacity-45",children:"Restart"})]})]})]})]}),ge===2&&n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-caption uppercase tracking-[0.1em] text-muted",children:"Initiative Scope"}),n.jsxs("select",{value:l,onChange:R=>d(R.target.value),className:"mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-[#BFFF00]/30",children:[n.jsx("option",{value:"",children:"Select an initiative…"}),(i??[]).map(R=>n.jsx("option",{value:R.id,children:R.name},R.id))]})]}),n.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Workstream (optional)"}),n.jsxs("select",{value:u,onChange:R=>h(R.target.value),disabled:!ke,className:pe("mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-[#BFFF00]/30",!ke&&"opacity-50"),children:[n.jsx("option",{value:"",children:"Any workstream"}),G.map(R=>n.jsx("option",{value:R.id,children:R.name},R.id))]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Task (optional)"}),n.jsxs("select",{value:y,onChange:R=>b(R.target.value),disabled:!ke,className:pe("mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-[#BFFF00]/30",!ke&&"opacity-50"),children:[n.jsx("option",{value:"",children:"Any task"}),Se.slice(0,80).map(R=>n.jsx("option",{value:R.id,children:R.title},R.id))]}),Se.length>80&&n.jsx("p",{className:"mt-1 text-micro text-muted",children:"Showing first 80 tasks to keep the menu usable."})]})]})]}),ge===3&&n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-caption uppercase tracking-[0.1em] text-muted",children:"Kickoff Message"}),n.jsx("textarea",{value:v,onChange:R=>x(R.target.value),rows:4,className:"mt-1 w-full resize-none rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-[#BFFF00]/30",placeholder:"Optional. If left blank, a default kickoff message is used."})]}),n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] p-3 text-body text-secondary",children:[n.jsx("p",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Review"}),n.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2",children:[n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Agent"}),n.jsx("div",{className:"mt-0.5 truncate text-body text-primary",children:((xe==null?void 0:xe.name)??a.trim())||"—"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Initiative"}),n.jsx("div",{className:"mt-0.5 truncate text-body text-primary",children:((ke==null?void 0:ke.name)??l.trim())||"—"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Workstream"}),n.jsx("div",{className:"mt-0.5 truncate text-body text-primary",children:u.trim()?((Me=G.find(R=>R.id===u))==null?void 0:Me.name)??u:"Any"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Task"}),n.jsx("div",{className:"mt-0.5 truncate text-body text-primary",children:y.trim()?((ue=Se.find(R=>R.id===y))==null?void 0:ue.title)??y:"Any"})]})]})]})]})]},ge)}),C&&n.jsx("div",{className:"mt-3 rounded-xl border border-rose-300/20 bg-rose-400/10 px-3 py-2 text-body text-rose-100",children:n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx("div",{children:C}),g&&n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>void Ee().catch(R=>j(R instanceof Error?R.message:"Checkout failed")),className:"rounded-full border border-amber-200/25 bg-amber-200/10 px-3 py-1.5 text-caption font-semibold text-amber-100 transition-colors hover:bg-amber-200/15",children:"Upgrade"}),n.jsx("button",{type:"button",onClick:()=>void ee().catch(R=>j(R instanceof Error?R.message:"Portal failed")),className:"rounded-full border border-strong bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-primary transition-colors hover:bg-white/[0.08]",children:"Billing portal"}),g.pricing&&n.jsx("a",{href:g.pricing,target:"_blank",rel:"noopener noreferrer",className:"text-caption text-secondary underline decoration-white/20 hover:text-primary",children:"View pricing"})]})]})})]}),n.jsxs("div",{className:"flex items-center justify-between gap-3 border-t border-subtle px-5 py-3.5 sm:px-6",children:[n.jsx("div",{className:"text-caption text-secondary",children:ge===1?"Pick an agent to configure.":ge===2?"Select an initiative scope (required).":re?"Launch will update sessions/activity under the selected initiative.":"Select an agent and initiative to launch."}),n.jsxs("div",{className:"flex items-center gap-2",children:[ge>1&&n.jsx("button",{type:"button",onClick:()=>Z(R=>R>1?R-1:R),disabled:K,className:"rounded-xl border border-strong bg-white/[0.03] px-4 py-2 text-body font-semibold text-primary transition-colors hover:bg-white/[0.08] disabled:opacity-45",children:"Back"}),ge<3?n.jsx("button",{type:"button",onClick:()=>Z(R=>R<3?R+1:R),disabled:!le||K,className:pe("rounded-xl px-4 py-2 text-body font-semibold transition-colors",le&&!K?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:le&&!K?{backgroundColor:F.lime}:void 0,children:"Next"}):n.jsx("button",{type:"button",onClick:q,disabled:!re||K,className:pe("rounded-xl px-4 py-2 text-body font-semibold transition-colors",re&&!K?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:re&&!K?{backgroundColor:F.lime}:void 0,children:K?"Launching…":"Launch"})]})]})]})}):null}const Ni=10,pm=20;function fm(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:F.lime,bg:"rgba(191,255,0,0.12)"}:t==="blocked"?{label:"Blocked",color:"#fb7185",bg:"rgba(244, 63, 94, 0.12)"}:t==="idle"?{label:"Idle",color:"rgba(255,255,255,0.55)",bg:"rgba(255,255,255,0.06)"}:{label:e||"Unknown",color:F.iris,bg:"rgba(124,124,255,0.10)"}}function hm(e){return e?e.includes("error")||e.includes("fail")?F.red:e.includes("decision")||e.includes("block")?F.amber:e.includes("complete")||e.includes("success")?F.teal:e.includes("start")||e.includes("launch")?F.lime:F.iris:F.iris}function gm({open:e,onClose:t,agentName:s,catalogAgent:r,sessions:i,activity:a,onSelectSession:c,onRefresh:l}){var me,ge,Z,ae,ke,Fe;const[d,u]=o.useState(!1),[h,y]=o.useState(!1),[b,p]=o.useState(null),w=Yo(s),v=fm((r==null?void 0:r.status)??null),x=o.useMemo(()=>{let G=0,Se=0,Ae=0,xe=0;for(const re of i)re.status==="running"||re.status==="queued"||re.status==="pending"?G++:re.status==="blocked"?Se++:re.status==="failed"||re.status==="cancelled"?Ae++:(re.status==="completed"||re.status==="archived")&&xe++;return{running:G,blocked:Se,failed:Ae,completed:xe}},[i]),C=o.useMemo(()=>[...i].sort((G,Se)=>Date.parse(Se.updatedAt??Se.lastEventAt??Se.startedAt??"")-Date.parse(G.updatedAt??G.lastEventAt??G.startedAt??"")),[i]),j=d?C:C.slice(0,Ni),g=C.length>Ni,S=o.useMemo(()=>[...a].sort((G,Se)=>Date.parse(Se.timestamp)-Date.parse(G.timestamp)).slice(0,pm),[a]),W=!!((me=r==null?void 0:r.run)!=null&&me.runId)&&!!((ge=r==null?void 0:r.run)!=null&&ge.pid),Y=async()=>{var G;if(!(!((G=r==null?void 0:r.run)!=null&&G.runId)||!W||h)){p(null),y(!0);try{const Se=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(r.run.runId)}`,{method:"POST"}),Ae=await Se.json().catch(()=>null);if(!Se.ok||!(Ae!=null&&Ae.ok))throw new Error((Ae==null?void 0:Ae.error)??`Stop failed (${Se.status})`);l==null||l()}catch(Se){p(Se instanceof Error?Se.message:"Stop failed")}finally{y(!1)}}},K=async()=>{var G;if(!(!((G=r==null?void 0:r.run)!=null&&G.runId)||h)){p(null),y(!0);try{const Se=new URLSearchParams;Se.set("runId",r.run.runId);const Ae=await fetch(`/orgx/api/agents/restart?${Se.toString()}`,{method:"POST"}),xe=await Ae.json().catch(()=>null);if(!Ae.ok||!(xe!=null&&xe.ok))throw new Error((xe==null?void 0:xe.error)??`Restart failed (${Ae.status})`);l==null||l()}catch(Se){p(Se instanceof Error?Se.message:"Restart failed")}finally{y(!1)}}};return e?n.jsx(ai,{open:e,onClose:t,maxWidth:"max-w-3xl",children:n.jsxs("div",{className:"flex h-full min-h-0 w-full flex-col",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 px-8 pt-6 pb-2",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0 text-[13px] text-secondary",children:[n.jsx("span",{children:"Agents"}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",className:"flex-shrink-0 opacity-40",children:n.jsx("path",{d:"m9 18 6-6-6-6"})}),n.jsx("span",{className:"truncate text-white font-medium",children:s})]}),n.jsx("button",{type:"button",onClick:t,"aria-label":"Close detail",className:"inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full text-muted transition-colors hover:bg-white/[0.06] hover:text-white focus:outline-none",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6L6 18"}),n.jsx("path",{d:"M6 6l12 12"})]})})]}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-8 py-6 space-y-8",children:[n.jsxs("div",{className:"flex items-start gap-5",children:[n.jsx(Ot,{name:s,size:"lg",hint:s}),n.jsxs("div",{className:"min-w-0 flex-1 pt-1",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("h3",{className:"text-[28px] font-medium leading-none text-white truncate",children:s}),n.jsx("span",{className:"rounded-full px-2 py-0.5 text-[10px] font-semibold uppercase tracking-widest",style:{color:v.color,backgroundColor:v.bg},children:v.label})]}),w&&n.jsx("p",{className:"text-[15px] text-secondary mt-2",children:w})]})]}),n.jsx("div",{className:"flex items-center gap-12 pt-2 pb-6 border-b border-white/[0.04]",children:[{label:"Running",value:x.running,color:F.lime},{label:"Blocked",value:x.blocked,color:F.red},{label:"Failed",value:x.failed,color:F.amber},{label:"Completed",value:x.completed,color:F.teal}].map(G=>n.jsxs("div",{children:[n.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-widest text-muted",children:G.label}),n.jsx("p",{className:"mt-1 text-2xl font-light",style:{color:G.value>0?G.color:"rgba(255,255,255,0.2)",fontVariantNumeric:"tabular-nums"},children:G.value})]},G.label))}),n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-12 pt-4",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-widest text-muted mb-6",children:"Sessions"}),i.length===0?n.jsx("p",{className:"text-body text-muted italic",children:"No sessions recorded."}):n.jsxs("div",{className:"relative border-l border-white/[0.06] pl-6 ml-2 space-y-6",children:[j.map(G=>n.jsxs("div",{className:"relative group",children:[n.jsx("div",{className:"absolute -left-[29px] top-1.5 h-2 w-2 rounded-full border border-black ring-4 ring-black",style:{backgroundColor:As(G.status)}}),n.jsxs("button",{onClick:()=>{c(G.id),t()},className:"w-full text-left focus:outline-none group-hover:bg-white/[0.02] -mx-3 px-3 py-2 rounded-lg transition-colors",children:[n.jsxs("div",{className:"flex items-center justify-between gap-4",children:[n.jsx("p",{className:"truncate text-[14px] font-medium text-white transition-colors group-hover:text-lime",children:G.title}),n.jsx("span",{className:"flex-shrink-0 text-[12px] text-muted tabular-nums",children:It(G.updatedAt??G.lastEventAt??G.startedAt??Date.now())})]}),n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-[12px] text-secondary",children:[n.jsx("span",{className:"capitalize",children:G.status}),G.progress!==null&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-white/[0.15]",children:"·"}),n.jsxs("span",{children:[Math.round(G.progress),"%"]})]})]})]})]},G.id)),g&&n.jsx("button",{type:"button",onClick:()=>u(G=>!G),className:"text-[12px] font-medium text-secondary hover:text-white transition-colors focus:outline-none",children:d?"Collapse timeline":`View ${C.length-Ni} older sessions`})]})]}),n.jsxs("div",{children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-widest text-muted mb-6",children:"Live Activity"}),S.length===0?n.jsx("p",{className:"text-body text-muted italic",children:"No recent activity."}):n.jsx("div",{className:"relative border-l border-white/[0.06] pl-6 ml-2 space-y-5",children:S.map((G,Se)=>n.jsxs("div",{className:"relative group",children:[n.jsx("div",{className:"absolute -left-[27px] top-1.5 h-1.5 w-1.5 rounded-full ring-4 ring-black",style:{backgroundColor:hm(G.type)}}),n.jsxs("div",{className:"flex items-start justify-between gap-4 py-0.5",children:[n.jsx("p",{className:"text-[13px] leading-relaxed text-secondary group-hover:text-white transition-colors line-clamp-2",children:G.title??G.summary??G.description??"Activity"}),n.jsx("span",{className:"flex-shrink-0 text-[11px] text-muted tabular-nums mt-0.5",children:It(G.timestamp)})]})]},G.id??Se))})]})]}),(r==null?void 0:r.run)&&n.jsxs("div",{className:"pt-4 border-t border-white/[0.04]",children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-widest text-muted mb-4",children:"Controls"}),n.jsxs("div",{className:"flex flex-wrap items-center gap-6",children:[n.jsxs("p",{className:"text-[13px] text-secondary",children:[n.jsx("span",{className:"text-muted mr-2",children:"Tracked run:"}),r.run.runId.slice(0,8),"…",n.jsxs("span",{className:"text-muted ml-2",children:["(",r.run.status,")"]})]}),n.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[n.jsx("button",{type:"button",onClick:Y,disabled:!W||h,className:"rounded-lg px-4 py-2 text-[13px] font-medium text-rose-400 transition-colors hover:text-rose-300 hover:bg-rose-400/10 disabled:opacity-40 focus:outline-none",children:h?"Stopping…":"Stop Run"}),n.jsx("button",{type:"button",onClick:K,disabled:h,className:"rounded-lg px-4 py-2 text-[13px] font-medium text-white bg-white/[0.06] transition-colors hover:bg-white/[0.12] disabled:opacity-40 focus:outline-none",children:h?"Restarting…":"Restart"})]}),b&&n.jsx("p",{className:"w-full text-caption text-rose-400",children:b})]})]}),r&&n.jsxs("div",{className:"pt-4 border-t border-white/[0.04]",children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-widest text-muted mb-4",children:"Settings"}),n.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-y-4 gap-x-8",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-[11px] text-muted mb-1",children:"Provider"}),n.jsx("p",{className:"text-[14px] text-primary",children:(Z=r.model)!=null&&Z.includes("openrouter")?"OpenRouter":(ae=r.model)!=null&&ae.includes("anthropic")?"Anthropic":(ke=r.model)!=null&&ke.includes("openai")?"OpenAI":"Auto"})]}),n.jsxs("div",{children:[n.jsx("p",{className:"text-[11px] text-muted mb-1",children:"Model"}),n.jsx("p",{className:pe("text-[14px] truncate",r.model?"text-primary":"text-muted"),children:r.model??"Not configured"})]}),r.workspace&&n.jsxs("div",{children:[n.jsx("p",{className:"text-[11px] text-muted mb-1",children:"Workspace"}),n.jsx("p",{className:"text-[14px] text-primary truncate",children:r.workspace})]}),((Fe=r.context)==null?void 0:Fe.initiativeTitle)&&n.jsxs("div",{children:[n.jsx("p",{className:"text-[11px] text-muted mb-1",children:"Initiative"}),n.jsx("p",{className:"text-[14px] text-primary truncate",children:r.context.initiativeTitle})]})]})]})]})]})}):null}const Er=120,oo=10,xm=24,lo=520,ym=58,bm=56,wm=20,vm=8,da=new Set(["running","active","in_progress","working","planning","handoff","review"]),km=new Set(["blocked","failed"]),jm=10,Nm=[{id:"orchestrator",name:"Orchestrator",role:"Coordinates cross-team execution"},{id:"engineering",name:"Engineering",role:"Builds and ships technical work"},{id:"product",name:"Product",role:"Defines features and requirements"},{id:"marketing",name:"Marketing",role:"Drives campaigns and content"},{id:"design",name:"Design",role:"Creates interfaces and experiences"},{id:"operations",name:"Operations",role:"Manages reliability and processes"}],Im=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Qi=[{id:"eli",name:"Eli",role:"Engineering",aliases:[/\beli\b/i,/\borgx[\s_-]*engineering\b/i,/^\s*engineering\s*$/i]},{id:"dana",name:"Dana",role:"Product Design",aliases:[/\bdana\b/i,/\borgx[\s_-]*design\b/i,/\borgx[\s_-]*product\b/i,/\bproduct[\s_-]*design\b/i]},{id:"mark",name:"Mark",role:"Marketing",aliases:[/\bmark\b/i,/\borgx[\s_-]*marketing\b/i,/^\s*marketing\s*$/i]},{id:"sage",name:"Sage",role:"Sales",aliases:[/\bsage\b/i,/\borgx[\s_-]*sales\b/i,/^\s*sales\s*$/i]},{id:"orion",name:"Orion",role:"Operations",aliases:[/\borion\b/i,/\borgx[\s_-]*operations\b/i,/^\s*operations\s*$/i]},{id:"xandy",name:"Xandy",role:"Orchestrator",aliases:[/\bxandy\b/i,/\borgx[\s_-]*orchestrator\b/i,/^\s*orchestrator\s*$/i]},{id:"pace",name:"Pace",role:"Product",aliases:[/\bpace\b/i,/\borgx[\s_-]*pace\b/i,/\borgx[\s_-]*product\b/i]}];function it(e){const t=e==null?void 0:e.trim().toLowerCase();return t&&t.length>0?t:null}function xn(e,t){const s=it(e),r=it(t);if(!s&&!r)return null;const i=[s,r].filter(Boolean).join(" ");if(!i)return null;for(const a of Qi)if(a.aliases.some(c=>c.test(i)))return{agentId:`orgx:${a.id}`,agentName:a.name,role:a.role};return null}function Am(e){const t=xn(e.agentId,e.agentName);if(t)return t;const s=[e.groupLabel,e.title,e.runtimeLabel,e.lastEventSummary];for(const r of s){const i=xn(null,r);if(i)return i}return null}function Sm(e){const t=it(e.runtimeClient);if(t==="codex")return"codex";if(t==="claude-code")return"claude-code";if(t==="openclaw")return"openclaw";if(t==="api")return"api";const s=[e.title,e.lastEventSummary,e.runtimeLabel,e.runtimeProvider,e.groupLabel].filter(r=>typeof r=="string"&&r.trim().length>0).join(" ").toLowerCase();return s.includes("claude-code")||s.includes("anthropic")||s.includes("claude")?"claude-code":s.includes("openclaw")?"openclaw":s.includes("codex")||s.includes("openai")?"codex":s.includes("orgx api")||s.includes("source_client=api")?"api":null}function ul(e){const t=Am(e);if(t)return{agentId:t.agentId,agentName:t.agentName};const s=it(e.agentId),r=it(e.agentName);if(s||r)return{agentId:e.agentId??null,agentName:e.agentName??null};const i=Sm(e);return i==="codex"?{agentId:"runtime:codex",agentName:"Codex"}:i==="claude-code"?{agentId:"runtime:claude-code",agentName:"Claude Code"}:i==="openclaw"?{agentId:"runtime:openclaw",agentName:"OpenClaw"}:i==="api"?{agentId:"runtime:api",agentName:"OrgX API"}:{agentId:null,agentName:null}}function _m(e){const t=ul(e),s=it(t.agentId);if(s)return`id:${s}`;const r=it(t.agentName);return r?`name:${r}`:"unassigned"}function Cm(e){const t=e.trim();return t?Im.test(t)?`${t.slice(0,8)}…${t.slice(-4)}`:!t.includes(" ")&&t.length>64?`${t.slice(0,48)}…`:t:"OrgX"}function Jr(e){const t=(e??"").trim();return t?Es(t):!1}function Mm(e){var t,s;return!!(Jr((t=e.context)==null?void 0:t.initiativeId)||Jr(((s=e.run)==null?void 0:s.initiativeId)??null))}function Ii(e){if(xn(e.agentId,e.agentName))return!0;const s=it(e.agentId);return!!(s!=null&&s.startsWith("orgx"))}function dn(e){const t=it(e.status)??"archived";if(t==="blocked"||t==="failed"||t==="completed"||t==="cancelled")return t;const s=it(e.phase);if(s==="blocked")return"blocked";if(s==="handoff")return"handoff";if(s==="completed")return"completed";if(s==="review")return"review";const r=it(e.state);return r==="error"?"failed":r==="stopped"?"paused":r==="stale"?"queued":da.has(t)?t:Array.isArray(e.blockers)&&e.blockers.length>0?"blocked":t}function Ji(e){const t=it(e);return t?da.has(t)||km.has(t):!1}function co(e){const t=it(e);return t?da.has(t):!1}function Rr(e){return e?!!(Ji(e.status)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0):!1}function Tm(e){return e?e.state==="active":!1}function Em(e){return e==="codex"?"codex":e==="openai"?"openai":e==="anthropic"?"anthropic":e==="openclaw"?"openclaw":e==="orgx"?"orgx":"unknown"}function An(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Ai(e,t){return An(t.updatedAt??t.lastEventAt??t.startedAt)-An(e.updatedAt??e.lastEventAt??e.startedAt)}function Rm({status:e,nodes:t,onSelectSession:s,selectedSessionId:r}){const[i,a]=o.useState(!1),c=As(e),l=e==="blocked"?"blocked":e==="failed"?"failed":"paused";return n.jsxs("div",{children:[n.jsxs("button",{onClick:()=>a(d=>!d),className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left transition-colors hover:bg-white/[0.05]",children:[n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full",style:{backgroundColor:c}}),n.jsxs("span",{className:"flex-1 text-body text-secondary",children:[t.length," ",l," sessions"]}),n.jsx(be.span,{animate:{rotate:i?90:0},transition:{duration:.15},className:"text-micro text-muted",children:"▸"})]}),n.jsx(pt,{children:i&&n.jsx(be.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"overflow-hidden pl-4",children:t.map((d,u)=>{const h=r===d.id,y=os(d.agentName,d.title,d.lastEventSummary,d);return n.jsx(be.button,{onClick:()=>s(d.id),initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.12,delay:Math.min(u*.02,.1)},className:pe("w-full rounded-lg px-2.5 py-1.5 text-left transition-colors",h?"bg-white/[0.09]":"bg-white/[0.02] hover:bg-white/[0.05]"),children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Vs,{provider:y.id,size:"xs"}),n.jsx("p",{className:"min-w-0 flex-1 truncate text-body text-bright",title:d.title,children:d.title}),n.jsx("span",{className:"text-micro text-muted",children:It(d.updatedAt??d.lastEventAt??d.startedAt??Date.now())})]})},d.id)})})})]})}const Dm=o.memo(function({sessions:t,activity:s,selectedSessionId:r,onSelectSession:i,timeFilterId:a,onAgentFilter:c,agentFilter:l,onReconnect:d,onLaunched:u,connectionStatus:h,runtimeInstances:y=[],showSyntheticEntities:b=!1}){var M;const[p,w]=o.useState(new Set),[v,x]=o.useState(!1),[C,j]=o.useState(!1),[g,S]=o.useState(0),[W,Y]=o.useState(null),K=ca({enabled:!0}),me=((M=K.data)==null?void 0:M.agents)??[],ge=o.useMemo(()=>yr(a),[a]),Z=o.useMemo(()=>ge===null?s:s.filter(B=>An(B.timestamp)>=ge),[s,ge]);o.useMemo(()=>{var fe,De,et;const B=new Map,ne=[...Z].sort((tt,Re)=>An(Re.timestamp)-An(tt.timestamp));for(const tt of ne){const Re=tt.runId;if(!Re||B.has(Re))continue;const Je=((fe=tt.summary)==null?void 0:fe.trim())??((De=tt.description)==null?void 0:De.trim())??((et=tt.title)==null?void 0:et.trim())??"";Je.length>0&&B.set(Re,Je)}return B},[Z]);const{agents:ae,hiddenGroupCount:ke,filteredOutGroupsByDate:Fe,filteredOutSessionsByDate:G,visibleSessionCount:Se,archivedGroups:Ae,sessionCountInScope:xe}=o.useMemo(()=>{var Oe;const B=b?t.nodes:t.nodes.filter(U=>!Jr(U.initiativeId)),ne=b?me:me.filter(U=>!Mm(U)),fe=b?y:y.filter(U=>!Jr(U.initiativeId)),De=new Map,et=new Map,tt=[...fe].sort((U,se)=>An(se.lastEventAt??se.lastHeartbeatAt)-An(U.lastEventAt??U.lastHeartbeatAt));for(const U of tt){U.runId&&!De.has(U.runId)&&De.set(U.runId,U);const se=xn(U.agentId,U.agentName??U.displayName),Ce=it((se==null?void 0:se.agentId)??U.agentId);if(Ce){const $e=et.get(Ce)??[];$e.push(U),et.set(Ce,$e)}}const Re=new Map;for(const U of B){const se=ul(U),Ce=_m(U),$e=it(se.agentId),Pe=it(se.agentName);let Be=Re.get(Ce)??null;if(!Be&&$e&&Pe){const Te=`name:${Pe}`,He=Re.get(Te);He&&(Re.delete(Te),He.groupKey=Ce,Re.set(Ce,He),Be=He)}if(!Be&&Pe){const Te=Array.from(Re.values()).find(He=>it(He.agentName)===Pe);Te&&(Be=Te)}Be?(Be.nodes.push(U),!Be.agentId&&se.agentId&&(Be.agentId=se.agentId),(Be.agentName==="OrgX"||!Be.agentName)&&se.agentName&&(Be.agentName=se.agentName)):Re.set(Ce,{groupKey:Ce,agentId:se.agentId,agentName:se.agentName??se.agentId??"OrgX",nodes:[U],latest:U,runtime:null,runtimeActiveCount:0})}for(const U of ne){const se=xn(U.id,U.name),Ce=(se==null?void 0:se.agentId)??U.id,$e=(se==null?void 0:se.agentName)??U.name,Pe=it(Ce),Be=it($e),Te=Pe?`id:${Pe}`:null,He=Be?`name:${Be}`:null;let st=null;if(Te&&Re.has(Te))st=Te;else if(He&&Re.has(He))st=He;else{const Ve=Array.from(Re.entries()).find(([,Pt])=>Pe&&it(Pt.agentId)===Pe||Be&&it(Pt.agentName)===Be);st=(Ve==null?void 0:Ve[0])??null}if(st){const Ve=Re.get(st);Ve.catalogAgent=U,!Ve.agentId&&Ce&&(Ve.agentId=Ce),(Ve.agentName==="OrgX"||!Ve.agentName)&&$e&&(Ve.agentName=$e),Te&&Ve.groupKey!==Te&&!Re.has(Te)&&(Re.delete(Ve.groupKey),Ve.groupKey=Te,Re.set(Te,Ve))}else{const Ve=Te??He??`catalog:${$e.toLowerCase()}`;Re.set(Ve,{groupKey:Ve,agentId:Ce,agentName:$e,nodes:[],latest:null,catalogAgent:U,runtime:null,runtimeActiveCount:0})}}for(const U of Qi){const se=`orgx:${U.id}`,Ce=`id:${se}`;let $e=Re.get(Ce)??null;if(!$e){const Pe=Array.from(Re.entries()).find(([,Be])=>{const Te=xn(Be.agentId,Be.agentName);return it(Te==null?void 0:Te.agentId)===it(se)});Pe&&(Re.delete(Pe[0]),$e=Pe[1],$e.groupKey=Ce,Re.set(Ce,$e))}if($e||($e={groupKey:Ce,agentId:se,agentName:U.name,nodes:[],latest:null,runtime:null,runtimeActiveCount:0},Re.set(Ce,$e)),$e.agentId=se,$e.agentName=U.name,!$e.catalogAgent){const Pe=ne.find(Be=>{const Te=xn(Be.id,Be.name);return it(Te==null?void 0:Te.agentId)===it(se)});Pe&&($e.catalogAgent=Pe)}}const Je=new Map(Qi.map((U,se)=>[it(`orgx:${U.id}`),se]));for(const U of Re.values()){U.nodes.length>0&&(U.nodes.sort(Ai),U.latest=U.nodes[0]);const se=[],Ce=new Set;if((Oe=U.latest)!=null&&Oe.runId){const Pe=De.get(U.latest.runId);Pe&&!Ce.has(Pe.id)&&(se.push(Pe),Ce.add(Pe.id))}for(const Pe of U.nodes){if(!Pe.runId)continue;const Be=De.get(Pe.runId);Be&&!Ce.has(Be.id)&&(se.push(Be),Ce.add(Be.id))}const $e=it(U.agentId);if($e)for(const Pe of et.get($e)??[])Ce.has(Pe.id)||(se.push(Pe),Ce.add(Pe.id));se.sort((Pe,Be)=>An(Be.lastEventAt??Be.lastHeartbeatAt)-An(Pe.lastEventAt??Pe.lastHeartbeatAt)),U.runtime=se[0]??null,U.runtimeActiveCount=se.filter(Pe=>Tm(Pe)).length}const We=Array.from(Re.values()).sort((U,se)=>{const Ce=Ii(U),$e=Ii(se);if(Ce!==$e)return Ce?-1:1;if(Ce&&$e){const Pe=xn(U.agentId,U.agentName),Be=xn(se.agentId,se.agentName),Te=Je.get(it((Pe==null?void 0:Pe.agentId)??U.agentId))??999,He=Je.get(it((Be==null?void 0:Be.agentId)??se.agentId))??999;if(Te!==He)return Te-He}return U.latest&&se.latest?Ai(U.latest,se.latest):U.latest&&!se.latest?-1:!U.latest&&se.latest?1:U.agentName.localeCompare(se.agentName)}),ft=Ko(a),ot=ft.id==="live",nt=ft.minutes===null||ot?null:Date.now()-ft.minutes*6e4,we=[],Ge=[];let je=0,H=0;for(const U of We){const se=(U.runtimeActiveCount??0)>0,Ce=Ii(U);if(U.nodes.length===0){const Te=Rr(U.catalogAgent);(Ce||ot&&(Te||se))&&we.push(U);continue}if(ot){const Te=U.nodes.filter(Ve=>Ji(dn(Ve))),He=U.nodes.filter(Ve=>!Ji(dn(Ve))),st=Rr(U.catalogAgent);if(Te.length===0){Ce||st||se?we.push({...U,nodes:[],latest:null}):(je+=1,H+=U.nodes.length,Ge.push(U));continue}H+=He.length,He.length>0&&Ge.push({...U,nodes:He,latest:He[0]??null}),we.push({...U,nodes:Te,latest:Te[0]??null});continue}if(nt===null){we.push(U);continue}const $e=U.nodes.filter(Te=>co(dn(Te))?!0:An(Te.updatedAt??Te.lastEventAt??Te.startedAt)>=nt),Pe=Rr(U.catalogAgent);if($e.length===0){Ce||Pe||se?we.push({...U,nodes:[],latest:null}):(je+=1,H+=U.nodes.length,Ge.push(U));continue}const Be=U.nodes.filter(Te=>co(dn(Te))?!1:An(Te.updatedAt??Te.lastEventAt??Te.startedAt)<nt);H+=Be.length,Be.length>0&&Ge.push({...U,nodes:Be,latest:Be[0]}),we.push({...U,nodes:$e,latest:$e[0]})}return{agents:we.slice(0,Er),hiddenGroupCount:Math.max(0,we.length-Er),filteredOutGroupsByDate:je,filteredOutSessionsByDate:H,visibleSessionCount:we.slice(0,Er).reduce((U,se)=>U+se.nodes.length,0),archivedGroups:Ge,sessionCountInScope:B.length}},[a,t.nodes,me,y,b]);o.useEffect(()=>{j(!1),S(0)},[a]);const re=o.useMemo(()=>Ae.reduce((B,ne)=>B+ne.nodes.length,0),[Ae]),le=o.useMemo(()=>ae.filter(B=>B.nodes.length>0).map(B=>B.groupKey),[ae]),Ee=o.useMemo(()=>{if(le.length===0)return{allCollapsed:!1,allExpanded:!0};let B=0;for(const ne of le)p.has(ne)&&(B+=1);return{allCollapsed:B===le.length,allExpanded:B===0}},[p,le]),ee=o.useMemo(()=>{const B=[];for(const ne of Ae)for(const fe of ne.nodes)B.push({node:fe,agentName:ne.agentName});return B.sort((ne,fe)=>Ai(ne.node,fe.node)),B.slice(0,(g+1)*jm)},[Ae,g]),q=B=>{w(ne=>{const fe=new Set(ne);return fe.has(B)?fe.delete(B):fe.add(B),fe})},J=()=>{w(()=>Ee.allCollapsed?new Set:new Set(le))},V=o.useMemo(()=>W?ae.find(B=>B.groupKey===W)??null:null,[ae,W]),k=o.useMemo(()=>(V==null?void 0:V.nodes)??[],[V]),z=o.useMemo(()=>{if(!V)return[];const B=it(V.agentName),ne=it(V.agentId),fe=xn(V.agentId,V.agentName);return Z.filter(De=>{const et=it(De.agentName),tt=it(De.agentId),Re=xn(De.agentId,De.agentName);return B!==null&&et===B||ne!==null&&tt===ne||fe!==null&&Re!==null&&it(fe.agentId)===it(Re.agentId)})},[Z,V]),O=xe===0,oe=me.length>0,ie=o.useRef(null),[Me,ue]=o.useState(0),[R,$]=o.useState(0),X=o.useCallback(B=>{const ne=B.currentTarget.scrollTop;ue(fe=>Math.abs(fe-ne)<1?fe:ne)},[]);o.useEffect(()=>{const B=ie.current;if(!B)return;const ne=()=>{const fe=B.clientHeight,De=B.scrollTop;$(et=>et===fe?et:fe),ue(et=>Math.abs(et-De)<1?et:De)};if(ne(),typeof ResizeObserver<"u"){const fe=new ResizeObserver(()=>ne());return fe.observe(B),()=>fe.disconnect()}return window.addEventListener("resize",ne),()=>window.removeEventListener("resize",ne)},[ae.length]);const{visibleAgentGroups:te,topVirtualSpacerPx:Le,bottomVirtualSpacerPx:qe,virtualizationEnabled:_e}=o.useMemo(()=>{if(!(ae.length>xm&&R>0))return{visibleAgentGroups:ae,topVirtualSpacerPx:0,bottomVirtualSpacerPx:0,virtualizationEnabled:!1};const ne=ae.map(We=>{const ot=p.has(We.groupKey)?0:Math.min(We.nodes.length,oo);let nt=ym;return ot>0&&(nt+=wm+ot*bm,We.nodes.length>ot&&(nt+=20)),nt+vm}),fe=new Array(ne.length+1).fill(0);for(let We=0;We<ne.length;We+=1)fe[We+1]=fe[We]+ne[We];const De=fe[fe.length-1],et=Math.max(0,Me-lo),tt=Me+R+lo;let Re=0;for(;Re<ae.length&&fe[Re+1]<et;)Re+=1;let Je=Re;for(;Je<ae.length&&fe[Je]<tt;)Je+=1;return Je<=Re&&(Je=Math.min(ae.length,Re+1)),{visibleAgentGroups:ae.slice(Re,Je),topVirtualSpacerPx:fe[Re],bottomVirtualSpacerPx:Math.max(0,De-fe[Je]),virtualizationEnabled:!0}},[ae,p,Me,R]);return n.jsxs(Hs,{className:"flex h-full min-h-0 flex-col card-enter",children:[n.jsx(mm,{open:v,onClose:()=>x(!1),onLaunched:()=>{K.refetch(),u==null||u()}}),n.jsx(gm,{open:W!==null,onClose:()=>Y(null),agentName:(V==null?void 0:V.agentName)??"",catalogAgent:(V==null?void 0:V.catalogAgent)??null,sessions:k,activity:z,onSelectSession:i,onRefresh:()=>K.refetch()}),n.jsx("div",{className:"border-b border-subtle px-4 py-3.5",children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n.jsx("h2",{className:"min-w-0 truncate text-heading font-semibold text-white",children:"Agents"}),n.jsxs("span",{className:"chip flex-shrink-0 text-caption tabular-nums",children:[Se," of ",xe]})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",onClick:J,disabled:le.length===0,className:"control-pill hidden flex-shrink-0 px-3 text-caption font-semibold sm:inline-flex",title:Ee.allCollapsed?"Expand all agent groups":"Collapse all agent groups",children:Ee.allCollapsed?"Expand":"Collapse"}),n.jsx("button",{type:"button",onClick:()=>x(!0),className:"control-pill flex-shrink-0 px-3 text-caption font-semibold",children:"Launch"})]})]})}),n.jsxs("div",{ref:ie,onScroll:X,className:"flex-1 space-y-2 overflow-y-auto p-3",children:[ae.length===0&&!O&&n.jsxs("div",{className:"flex flex-col items-center gap-2.5 rounded-xl border border-subtle bg-white/[0.02] px-3 py-6 text-center",children:[n.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"text-faint",children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),n.jsx("p",{className:"text-body text-secondary",children:"No sessions match the selected activity window."})]}),ae.length===0&&O&&!d&&n.jsxs("div",{className:"flex flex-col items-center gap-2.5 rounded-xl border border-subtle bg-white/[0.02] px-3 py-6 text-center",children:[n.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"text-faint",children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),n.jsx("p",{className:"text-body text-secondary",children:"No active chats yet. Start a session to see agents here."})]}),l&&c&&n.jsxs("div",{className:"flex items-center justify-between rounded-lg bg-[#0AD4C4]/[0.08] px-3 py-1.5 text-caption text-[#0AD4C4]",children:[n.jsxs("span",{children:["Filtered: ",l]}),n.jsx("button",{type:"button",onClick:()=>c(null),className:"text-micro underline underline-offset-2",children:"Clear"})]}),n.jsxs("div",{className:"space-y-1.5",children:[_e&&Le>0&&n.jsx("div",{"aria-hidden":"true",style:{height:Le}}),te.map(B=>{var Te;const ne=B.groupKey,fe=p.has(ne),De=B.latest,et=De?dn(De):null,tt=B.nodes.length>0,Re=B.nodes.length===1,Je=Rr(B.catalogAgent),We=B.runtime??null,ft=(B.runtimeActiveCount??0)>0,ot=!tt&&ft&&We!==null,nt=tt||ot,we=De?r===De.id:!1,Ge=B.agentName||((Te=B.catalogAgent)==null?void 0:Te.name)||B.agentId||"OrgX",je=xn(B.agentId,Ge),H=(je==null?void 0:je.agentName)??Cm(Ge),Oe=(je==null?void 0:je.role)??Yo(H),U=os(B.agentId,H,We==null?void 0:We.displayName,De==null?void 0:De.runtimeProvider,De==null?void 0:De.runtimeClient),se=je===null&&(U.id==="codex"||U.id==="openai"||U.id==="anthropic"||U.id==="openclaw"),Ce=Oe?`${Ge} — ${Oe}`:Ge,$e=fe?[]:tt?B.nodes.slice(0,oo):[],Pe=Math.max(0,tt?B.nodes.length-$e.length:0),Be=it(l)===it(H)||it(l)===it(Ce);return n.jsxs(be.div,{layout:!0,transition:{type:"spring",stiffness:260,damping:30,mass:.75},className:pe("overflow-hidden rounded-xl border border-subtle bg-white/[0.02] transition-all",we&&"border-white/20 bg-white/[0.05]",Be&&"border-[#0AD4C4]/30",!tt&&!Je&&!ft&&"opacity-55"),children:[n.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-2",children:[n.jsxs("button",{type:"button",onClick:()=>{Re?i(B.nodes[0].id):ot?q(ne):!tt&&Je?Y(ne):c?c(Be?null:H):De&&i(De.id)},className:"flex flex-1 items-start gap-2.5 rounded-lg px-1 py-0.5 text-left transition-colors hover:bg-white/[0.03]",children:[n.jsxs("div",{className:"relative flex-shrink-0",children:[se?n.jsx("span",{className:"inline-flex h-8 w-8 items-center justify-center rounded-lg border border-strong bg-white/[0.03]",children:n.jsx(Vs,{provider:U.id,size:"sm",showRing:!1})}):n.jsx(sm,{running:B.nodes.filter(He=>{const st=dn(He);return st==="running"||st==="handoff"||st==="review"}).length,blocked:B.nodes.filter(He=>{const st=dn(He);return st==="blocked"||st==="failed"}).length,paused:B.nodes.filter(He=>{const st=dn(He);return st==="paused"||st==="cancelled"}).length,size:36,children:n.jsx(Ot,{name:H,size:"sm",hint:`${B.agentId??""} ${H}`})}),je&&n.jsx("span",{className:"absolute -bottom-1 -left-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-[#08090D] bg-[#08090D]",children:n.jsx("img",{src:"/orgx/live/brand/orgx-logo.png",alt:"","aria-hidden":"true",className:"h-3 w-3 rounded-full object-contain",loading:"lazy"})}),De&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:As(et??De.status),borderColor:F.cardBg}}),!De&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:Je?As("running"):"rgba(255,255,255,0.2)",borderColor:F.cardBg}})]}),n.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[n.jsx("div",{className:"flex min-w-0 items-baseline",title:Oe?`${Ge} — ${Oe}`:Ge,children:n.jsxs("span",{className:"truncate text-body font-semibold text-white",children:[H,Oe&&n.jsxs("span",{className:"ml-1.5 font-normal text-muted",children:["— ",Oe]})]})}),n.jsx("div",{className:"flex items-center gap-1.5",children:tt?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex h-1.5 flex-1 overflow-hidden rounded-full",title:(()=>{const He={};for(const st of B.nodes){const Ve=dn(st);He[Ve]=(He[Ve]??0)+1}return Object.entries(He).map(([st,Ve])=>`${Ve} ${st}`).join(" · ")})(),children:(()=>{const He={};for(const Ve of B.nodes){const Pt=dn(Ve);He[Pt]=(He[Pt]??0)+1}const st=B.nodes.length;return Object.entries(He).map(([Ve,Pt])=>n.jsx("span",{style:{width:`${Pt/st*100}%`,backgroundColor:As(Ve)}},Ve))})()}),n.jsx("span",{className:"w-6 flex-shrink-0 text-right text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:B.nodes.length})]}):Je||ft?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex h-1.5 flex-1 overflow-hidden rounded-full bg-white/[0.06]",children:n.jsx("span",{className:"h-1.5 w-full",style:{backgroundColor:As("running")}})}),n.jsx("span",{className:"w-6 flex-shrink-0 text-right text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:Math.max(1,B.runtimeActiveCount??0)})]}):n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex h-1.5 flex-1 overflow-hidden rounded-full bg-white/[0.06]"}),n.jsx("span",{className:"w-6 flex-shrink-0 text-right text-micro text-muted",style:{fontVariantNumeric:"tabular-nums"},children:"0"})]})})]})]}),n.jsx("button",{type:"button",onClick:()=>Y(ne),"aria-label":`View ${H} details`,className:"flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-md text-muted transition-colors hover:bg-white/[0.05] hover:text-primary",children:n.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"M12 16v-4"}),n.jsx("path",{d:"M12 8h.01"})]})}),n.jsx("button",{type:"button",onClick:()=>{nt&&q(ne)},disabled:!nt,"aria-label":nt?fe?"Expand sessions":"Collapse sessions":"No sessions to expand",className:pe("flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-md text-muted transition-colors",nt?"hover:bg-white/[0.05] hover:text-primary":"cursor-default opacity-35"),children:n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:pe("transition-transform",nt&&!fe?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})})]}),n.jsx(pt,{initial:!1,children:nt&&!fe&&n.jsx(be.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"overflow-hidden border-t border-subtle",children:n.jsxs("div",{className:"max-h-[500px] space-y-1.5 overflow-y-auto p-2",children:[(()=>{const He=new Map,st=[];for(const Qe of $e){const Mt=dn(Qe);if(Mt==="blocked"||Mt==="paused"||Mt==="failed"){const Yt=`${Mt}:${Qe.blockerReason??""}`,mt=He.get(Yt)??[];mt.push(Qe),He.set(Yt,mt)}else st.push(Qe)}const Ve=[];for(const[Qe,Mt]of He)Mt.length>3?Ve.push({status:Qe.split(":")[0],nodes:Mt}):st.push(...Mt);const Pt=(Qe,Mt)=>{const Yt=r===Qe.id,mt=dn(Qe),rn=os(Qe.agentName,Qe.title,Qe.lastEventSummary,Qe);return n.jsx(be.button,{onClick:()=>i(Qe.id),initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.16,delay:Math.min(Mt*.015,.12)},className:pe("w-full rounded-lg px-2.5 py-2 text-left transition-colors",Yt?"bg-white/[0.09]":"bg-white/[0.02] hover:bg-white/[0.05]"),children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Vs,{provider:rn.id,size:"xs"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"truncate text-body text-bright",title:Qe.title,children:Qe.title}),n.jsxs("div",{className:"flex items-center gap-1.5 text-micro text-secondary",children:[n.jsx("span",{className:"font-semibold uppercase tracking-[0.08em]",style:{color:rn.accent},children:rn.label}),n.jsx("span",{className:"uppercase tracking-[0.08em]",children:mt}),n.jsx("span",{title:Gr(Qe.updatedAt??Qe.lastEventAt??Qe.startedAt??Date.now()),children:It(Qe.updatedAt??Qe.lastEventAt??Qe.startedAt??Date.now())})]}),Qe.progress!==null&&n.jsx("div",{className:"mt-1 h-0.5 rounded-full bg-white/[0.08]",children:n.jsx("div",{className:"h-0.5 rounded-full",style:{width:`${Math.round(Qe.progress)}%`,background:`linear-gradient(90deg, ${F.lime}, ${F.teal})`}})})]}),n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full",style:{backgroundColor:As(mt)},"aria-label":mt,title:mt})]})},Qe.id)};return n.jsxs(n.Fragment,{children:[st.map((Qe,Mt)=>Pt(Qe,Mt)),Ve.map(Qe=>n.jsx(Rm,{status:Qe.status,nodes:Qe.nodes,onSelectSession:i,selectedSessionId:r},`cg-${Qe.status}-${Qe.nodes.length}`))]})})(),Pe>0&&n.jsxs("p",{className:"px-1 text-micro text-muted",children:["+",Pe," older sessions hidden"]})]})})})]},ne)}),_e&&qe>0&&n.jsx("div",{"aria-hidden":"true",style:{height:qe}})]}),ke>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] px-3 py-2 text-caption text-secondary",children:["Showing ",Er," most recent agent groups (",ke," older groups omitted)."]}),d&&h!=="connected"&&!oe&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] text-caption text-secondary",children:[n.jsx("p",{className:"px-3 pt-2 pb-1.5 text-micro uppercase tracking-[0.1em] text-muted",children:"OrgX Agent Roster"}),n.jsx("div",{className:"space-y-1 px-2 pb-2",children:Nm.map(B=>n.jsxs("div",{className:"flex items-center gap-2.5 rounded-lg px-2 py-1.5 opacity-55",children:[n.jsx("div",{className:"flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md border border-white/[0.08] bg-white/[0.03]",children:n.jsx("span",{className:"text-micro font-semibold text-secondary",children:B.name.charAt(0)})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-caption font-medium text-secondary",children:B.name}),n.jsx("p",{className:"text-micro text-muted",children:B.role})]}),n.jsx("button",{onClick:d,className:"rounded-md border border-lime/25 bg-lime/10 px-2 py-0.5 text-micro font-semibold text-lime transition-colors hover:bg-lime/20",children:"Connect"})]},B.id))})]}),G>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] text-caption text-secondary",children:[n.jsxs("button",{onClick:()=>{j(B=>!B),C&&S(0)},className:"flex w-full items-center gap-2 px-3 py-2 text-left transition-colors hover:bg-white/[0.03]",children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:pe("transition-transform",C?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),n.jsxs("span",{children:[re," archived session",re===1?"":"s",Fe>0?` across ${Fe} agent${Fe===1?"":"s"}`:""]})]}),n.jsx(pt,{initial:!1,children:C&&n.jsx(be.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"overflow-hidden",children:n.jsxs("div",{className:"space-y-1.5 border-t border-subtle p-2",children:[ee.map(({node:B,agentName:ne})=>{const fe=dn(B),De=B.runtimeProvider?{id:Em(B.runtimeProvider)}:os(B.agentName,B.title,B.lastEventSummary,B);return n.jsxs("button",{onClick:()=>i(B.id),className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left opacity-60 transition-colors hover:bg-white/[0.05] hover:opacity-80",children:[n.jsx(Vs,{provider:De.id,size:"xs"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"truncate text-caption font-medium text-primary",children:ne}),n.jsx("span",{className:"text-micro text-muted",title:Gr(B.updatedAt??B.lastEventAt??B.startedAt??Date.now()),children:It(B.updatedAt??B.lastEventAt??B.startedAt??Date.now())})]}),n.jsx("p",{className:"truncate text-micro text-secondary",children:B.title}),n.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:fe})]})]},B.id)}),ee.length<re&&n.jsxs("button",{onClick:()=>S(B=>B+1),className:"w-full rounded-lg border border-white/[0.08] bg-white/[0.02] px-3 py-1.5 text-micro text-secondary transition-colors hover:bg-white/[0.05]",children:["Load more (",re-ee.length," remaining)"]})]})})})]})]})]})}),Lm=new Set(["failed","error","timed_out","timeout","aborted","crashed","fatal"]),Fm=new Set(["awaiting_input","needs_review","needs_decision","review_required"]),$m=new Set(["blocked","paused","rate_limited","waiting_dependency","stopping"]),Pm=new Set(["completed","complete","done","resolved","success","succeeded","archived","cancelled","stopped"]),Om=new Set(["running","active","in_progress","working","planning","dispatching","queued","pending","resumed","handoff"]);function qs(e){return e?zt(e):""}function Si(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.round(e))}function Bm(e){return e.some(t=>Lm.has(t))}function qm(e){return e.some(t=>Fm.has(t))}function zm(e){return e.some(t=>$m.has(t))}function Um(e){return e.some(t=>Pm.has(t))}function Wm(e){return e.some(t=>Om.has(t))}function Hn(e,t,s){const r=e==="in_progress"?"In progress":e==="needs_attention"?"Needs attention":e==="completed"?"Completed":e==="failed"?"Failed":"Update",i=(s==null?void 0:s.tone)??(e==="completed"?"positive":e==="failed"?"critical":e==="needs_attention"?"warning":"neutral"),a=e==="completed"||e==="failed",c=e==="needs_attention"||e==="failed";return{status:e,label:r,sentence:t,nextAction:(s==null?void 0:s.nextAction)??null,tone:i,isTerminal:a,isActionRequired:c}}function Hm(e){const t=qs(e.sessionStatus),s=qs(e.sessionPhase),r=qs(e.sessionState),i=qs(e.sliceStatus),a=qs(e.activityStatus),c=qs(e.stopReason),l=(e.activityType??"").toString().trim().toLowerCase(),d=[t,s,r,i,a,c].filter(S=>S.length>0),u=Si(e.blockingDecisionCount),h=Si(e.nonBlockingDecisionCount),y=Si(e.blockerCount),b=l==="run_failed",p=l==="run_completed"||l==="milestone_completed"||l==="decision_resolved",w=b||Bm(d),v=qm(d)||l==="decision_requested"||u>0||e.decisionRequired===!0,x=zm(d)||y>0,C=p||Um(d),j=Wm(d)||l==="run_started";if(w)return Hn("failed","Execution failed and needs intervention.",{nextAction:"Review evidence",tone:"critical"});if(C&&!v&&!w&&y===0&&!e.blockerReason)return h>0?Hn("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):Hn("completed","Execution completed successfully.",{tone:"positive"});if(v||x)return u>0||e.decisionRequired===!0||l==="decision_requested"?Hn("needs_attention","Execution is waiting for a decision.",{nextAction:"Resolve decision",tone:"warning"}):Hn("needs_attention","Execution is blocked and needs intervention.",{nextAction:"Review blocker",tone:x?"critical":"warning"});if(C)return h>0?Hn("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):Hn("completed","Execution completed successfully.",{tone:"positive"});if(j){const S=h>0?`Running with ${h} optional decision${h===1?"":"s"} available.`:"Running.";return Hn("in_progress",S,{tone:"neutral"})}return Hn("unknown","Status is available but not fully classified yet.",{tone:"neutral"})}const _i=/\[([^\]]+)\]\(([^)\s]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|__([^_]+)__|\*([^*\n]+)\*|_([^_\n]+)_/g;function Vm(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Ss(e,t){const s=[];let r=0,i=0;_i.lastIndex=0;for(let a=_i.exec(e);a;a=_i.exec(e)){const[c]=a,l=a.index;l>r&&s.push(e.slice(r,l));const d=`${t}-${i++}`,u=a[1],h=a[2],y=a[3],b=a[4],p=a[5],w=a[6],v=a[7];u&&h&&Vm(h)?s.push(n.jsx("a",{href:h,target:"_blank",rel:"noopener noreferrer",className:"text-[#D8FFA1] underline decoration-white/35 underline-offset-2 transition hover:text-[#ECFFC6]",children:u},d)):y?s.push(n.jsx("code",{className:"rounded bg-white/[0.08] px-1 py-0.5 font-mono text-[0.93em] text-bright",children:y},d)):b||p?s.push(n.jsx("strong",{className:"font-semibold text-white",children:b??p},d)):w||v?s.push(n.jsx("em",{className:"italic text-bright",children:w??v},d)):s.push(c),r=l+c.length}return r<e.length&&s.push(e.slice(r)),s}function Km(e,t){const s=e.split(`
204
+ `),r=[];return s.forEach((i,a)=>{r.push(...Ss(i,`${t}-line-${a}`)),a<s.length-1&&r.push(n.jsx("br",{},`${t}-br-${a}`))}),r}function Vr(e){return e.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function Gm(e){const t=Vr(e);return t.length===0?!1:t.every(s=>/^:?-{3,}:?$/.test(s))}function Xm(e){const t=e.trim(),s=t.startsWith(":"),r=t.endsWith(":");return s&&r?"center":r?"right":"left"}function Qm(e){const t=e.replace(/\r\n/g,`
205
+ `).split(`
206
+ `),s=[];let r=0;for(;r<t.length;){const i=t[r]??"",a=i.trim();if(!a){r+=1;continue}const c=i.includes("|"),l=t[r+1]??"";if(c&&l.includes("|")&&Gm(l)){const b=Vr(i),w=Vr(l).map(x=>Xm(x));r+=2;const v=[];for(;r<t.length;){const x=t[r]??"";if(!x.trim()||!x.includes("|"))break;v.push(Vr(x)),r+=1}s.push(n.jsx("div",{className:"overflow-x-auto rounded-xl border border-white/[0.1] bg-black/25",children:n.jsxs("table",{className:"min-w-full border-collapse text-left",children:[n.jsx("thead",{children:n.jsx("tr",{className:"border-b border-white/[0.08] bg-white/[0.03]",children:b.map((x,C)=>n.jsx("th",{className:"px-3 py-2 text-caption font-semibold uppercase tracking-[0.08em] text-primary",style:{textAlign:w[C]??"left"},children:Ss(x,`tbl-h-${r}-${C}`)},`tbl-h-${C}`))})}),n.jsx("tbody",{children:v.map((x,C)=>n.jsx("tr",{className:C<v.length-1?"border-b border-subtle":void 0,children:b.map((j,g)=>n.jsx("td",{className:"px-3 py-2 text-body leading-relaxed text-primary align-top",style:{textAlign:w[g]??"left"},children:Ss(x[g]??"",`tbl-r-${r}-${C}-${g}`)},`tbl-r-${C}-c-${g}`))},`tbl-r-${C}`))})]})},`tbl-${r}`));continue}if(a.startsWith("```")){const b=a.slice(3).trim(),p=[];for(r+=1;r<t.length&&!(t[r]??"").trim().startsWith("```");)p.push(t[r]??""),r+=1;r<t.length&&(r+=1),s.push(n.jsxs("div",{className:"rounded-xl border border-white/[0.1] bg-black/40 p-3",children:[b&&n.jsx("p",{className:"mb-1 text-micro uppercase tracking-[0.12em] text-muted",children:b}),n.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap font-mono text-caption leading-relaxed text-primary",children:n.jsx("code",{children:p.join(`
207
+ `)})})]},`code-${r}`));continue}const d=a.match(/^(#{1,3})\s+(.+)$/);if(d){const b=d[1].length,p=d[2],w=b===1?"text-title font-semibold":b===2?"text-heading font-semibold":"text-body font-medium";s.push(n.jsx("p",{className:pe("tracking-[-0.01em] text-white",w),children:Ss(p,`h-${r}`)},`h-${r}`)),r+=1;continue}if(i.match(/^\s*[-*]\s+(.+)$/)){const b=[];for(;r<t.length;){const w=(t[r]??"").match(/^\s*[-*]\s+(.+)$/);if(!w)break;b.push(w[1]),r+=1}s.push(n.jsx("ul",{className:"space-y-1.5 pl-4",children:b.map((p,w)=>n.jsx("li",{className:"list-disc text-body leading-relaxed text-primary",children:Ss(p,`ul-${r}-${w}`)},`ul-${r}-${w}`))},`ul-${r}`));continue}if(i.match(/^\s*\d+\.\s+(.+)$/)){const b=[];for(;r<t.length;){const w=(t[r]??"").match(/^\s*\d+\.\s+(.+)$/);if(!w)break;b.push(w[1]),r+=1}s.push(n.jsx("ol",{className:"space-y-1.5 pl-4",children:b.map((p,w)=>n.jsx("li",{className:"list-decimal text-body leading-relaxed text-primary",children:Ss(p,`ol-${r}-${w}`)},`ol-${r}-${w}`))},`ol-${r}`));continue}const y=[];for(;r<t.length;){const b=t[r]??"",p=b.trim();if(!p||/^(#{1,3})\s+/.test(p)||/^\s*[-*]\s+/.test(b)||/^\s*\d+\.\s+/.test(b)||p.startsWith("```"))break;y.push(b),r+=1}s.push(n.jsx("p",{className:"text-body leading-relaxed text-primary",children:Km(y.join(`
208
+ `),`p-${r}`)},`p-${r}`))}return s}function Yr({text:e,mode:t="inline",className:s}){const r=e.replace(/\r\n/g,`
209
+ `);return r.trim()?t==="inline"?n.jsx("span",{className:s,children:Ss(r,"inline")}):n.jsx("div",{className:pe("space-y-2",s),children:Qm(r)}):null}function ml(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Jm(e){if(!e)return;const t=ml(e.metadata);return t?{...e,...t}:e}const pl={run_started:{icon:"play",label:"Run started",color:F.teal},run_completed:{icon:"check_circle",label:"Run completed",color:F.lime},run_failed:{icon:"alert_triangle",label:"Run failed",color:F.red},artifact_created:{icon:"file",label:"Artifact",color:F.cyan},decision_requested:{icon:"shield",label:"Decision requested",color:F.amber},decision_resolved:{icon:"shield_check",label:"Decision resolved",color:F.lime},handoff_requested:{icon:"handoff",label:"Handoff requested",color:F.iris},handoff_claimed:{icon:"handoff_claimed",label:"Handoff claimed",color:F.teal},handoff_fulfilled:{icon:"sparkles",label:"Handoff fulfilled",color:F.lime},blocker_created:{icon:"octagon_x",label:"Blocker",color:F.red},milestone_completed:{icon:"flag",label:"Milestone",color:F.cyan},delegation:{icon:"workflow",label:"Delegation",color:F.iris}};function Fn(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r=="string"&&r.trim().length>0)return r.trim()}return null}function Yi(e){return e?e.toLowerCase():""}function Ym(e,t){return[e.type,e.kind,e.phase,e.state,e.title,e.summary,e.description,Fn(t,["source","event","eventType","artifact_type","action","kind"]),Fn(t,["task","taskName","workstream","milestone","status"])].filter(s=>typeof s=="string"&&s.trim().length>0).join(" ").toLowerCase()}function Zm(e,t){const s=Yi(Fn(e,["artifact_type","artifactType"]));return s.includes("pr")||/pull request|merge request/.test(t)?{icon:"file_code",label:"Pull request",color:F.cyan}:s.includes("commit")||/commit|diff|patch/.test(t)?{icon:"git_commit",label:"Commit",color:F.cyan}:s.includes("config")?{icon:"checkpoint",label:"Config",color:F.cyan}:s.includes("design")?{icon:"compass",label:"Design output",color:F.cyan}:s.includes("report")||s.includes("document")||/memo|doc/.test(t)?{icon:"file",label:"Document",color:F.cyan}:pl.artifact_created}function ep(e){const t=Jm(ml(e.metadata)),s=Ym(e,t),r=Yi(Fn(t,["source"])),i=Yi(Fn(t,["action"])),a=Fn(t,["event","event_name","eventName"]);if(a==="auto_continue_started"||a==="auto_continue_stopped"||a==="autopilot_transition"||a==="autopilot_slice_result"||a==="autopilot_slice_finished"){if(a==="auto_continue_started"||a==="autopilot_transition"&&Fn(t,["new_state"])==="running")return{icon:"infinity",label:"Autopilot started",color:F.teal};if(a==="auto_continue_stopped"){const l=Fn(t,["stop_reason"]);return l==="error"||l==="blocked"?{icon:"infinity",label:"Autopilot blocked",color:F.red}:l==="budget_exhausted"?{icon:"infinity",label:"Budget exhausted",color:F.amber}:{icon:"infinity",label:"Autopilot stopped",color:F.amber}}if(a==="autopilot_transition"){const l=Fn(t,["new_state"]);return l==="blocked"||l==="error"?{icon:"infinity",label:"Autopilot blocked",color:F.red}:{icon:"infinity",label:"Autopilot transition",color:F.teal}}const c=Fn(t,["parsed_status","status"]);return c==="completed"||c==="success"?{icon:"check_circle",label:"Slice completed",color:F.lime}:{icon:"infinity",label:"Autopilot slice",color:F.teal}}if(/heartbeat|heart beat|alive signal/.test(s))return{icon:"heartbeat",label:"Heartbeat",color:F.teal};if(/soul/.test(s))return{icon:"compass",label:"Soul state",color:F.iris};if(/memory sync|sync memory|workspace state|sync completed|memory file/.test(s))return{icon:"memory_sync",label:"Memory sync",color:F.teal};if(/checkpoint|rollback|restore point/.test(s))return{icon:"checkpoint",label:"Save point",color:F.amber};if(/quality gate|quality score|quality check/.test(s))return{icon:"quality_gate",label:"Quality gate",color:F.lime};if(/model routing|routed model|model tier/.test(s))return{icon:"route",label:"Model routing",color:F.iris};if(r==="local_openclaw")return{icon:"terminal",label:"Local",color:F.teal};if(e.type==="artifact_created")return Zm(t,s);if(e.type==="decision_resolved")return i==="reject"||/rejected|declined/.test(s)?{icon:"shield_x",label:"Decision rejected",color:F.red}:{icon:"shield_check",label:"Decision approved",color:F.lime};if(e.type==="delegation"){if(/dispatch|spawn|launched|kickoff|started/.test(s))return{icon:"workflow",label:"Dispatch",color:F.iris};if(/message|chat|reply|summary/.test(s))return{icon:"message",label:"Message",color:F.teal}}return pl[e.type]??{icon:"message",label:"Activity",color:F.textMuted}}function tp({icon:e,size:t=14,className:s}){const r={width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round",className:s};switch(e){case"play":return n.jsx("svg",{...r,children:n.jsx("path",{d:"m8 6 10 6-10 6z"})});case"check_circle":return n.jsxs("svg",{...r,children:[n.jsx("circle",{cx:"12",cy:"12",r:"9"}),n.jsx("path",{d:"m8.5 12 2.5 2.5 4.5-5"})]});case"alert_triangle":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"m12 3 9 16H3z"}),n.jsx("path",{d:"M12 9v4"}),n.jsx("path",{d:"M12 17h.01"})]});case"file":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7z"}),n.jsx("path",{d:"M14 2v5h5"})]});case"file_code":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7z"}),n.jsx("path",{d:"M14 2v5h5"}),n.jsx("path",{d:"m10 13-2 2 2 2"}),n.jsx("path",{d:"m14 13 2 2-2 2"})]});case"git_commit":return n.jsxs("svg",{...r,children:[n.jsx("circle",{cx:"12",cy:"12",r:"3"}),n.jsx("path",{d:"M3 12h6M15 12h6"})]});case"shield":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M12 3 5 6v6c0 5 3.3 7.8 7 9 3.7-1.2 7-4 7-9V6z"}),n.jsx("path",{d:"M12 9v4"}),n.jsx("path",{d:"M12 16h.01"})]});case"shield_check":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M12 3 5 6v6c0 5 3.3 7.8 7 9 3.7-1.2 7-4 7-9V6z"}),n.jsx("path",{d:"m9 12.5 2 2 4-4"})]});case"shield_x":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M12 3 5 6v6c0 5 3.3 7.8 7 9 3.7-1.2 7-4 7-9V6z"}),n.jsx("path",{d:"m10 10 4 4M14 10l-4 4"})]});case"handoff":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M7 8h6a3 3 0 1 1 0 6H8"}),n.jsx("path",{d:"m10 14-3 3-3-3"}),n.jsx("path",{d:"M17 10h-4"})]});case"handoff_claimed":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M8.5 12.5 12 9l3.5 3.5"}),n.jsx("path",{d:"M6 14h12"}),n.jsx("path",{d:"M7 18h10"})]});case"sparkles":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"m12 3 1.5 3.5L17 8l-3.5 1.5L12 13l-1.5-3.5L7 8l3.5-1.5z"}),n.jsx("path",{d:"m5 14 .8 1.8L8 16.6l-2.2.8L5 19l-.8-1.6L2 16.6l2.2-.8z"}),n.jsx("path",{d:"m19 14 .8 1.8 2.2.8-2.2.8L19 19l-.8-1.6-2.2-.8 2.2-.8z"})]});case"octagon_x":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"m10.2 3-5.8 3.3v11.4L10.2 21h3.6l5.8-3.3V6.3L13.8 3z"}),n.jsx("path",{d:"m9 9 6 6M15 9l-6 6"})]});case"flag":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M5 3v18"}),n.jsx("path",{d:"m5 4 12 1-2 4 2 4-12-1"})]});case"workflow":return n.jsx(Zo,{size:t,className:s,strokeWidth:1.8});case"memory_sync":return n.jsxs("svg",{...r,children:[n.jsx("ellipse",{cx:"12",cy:"5.5",rx:"6.5",ry:"2.5"}),n.jsx("path",{d:"M5.5 5.5v6c0 1.4 2.9 2.5 6.5 2.5s6.5-1.1 6.5-2.5v-6"}),n.jsx("path",{d:"m8 17-2 2 2 2"}),n.jsx("path",{d:"M16 17l2 2-2 2"})]});case"heartbeat":return n.jsx("svg",{...r,children:n.jsx("path",{d:"M3 12h4l2-4 3 8 2-4h7"})});case"checkpoint":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M12 3v6"}),n.jsx("path",{d:"M8 5h8"}),n.jsx("path",{d:"M7 11h10v10H7z"}),n.jsx("path",{d:"M9 14h6"})]});case"quality_gate":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M12 3 5 6v6c0 5 3.3 7.8 7 9 3.7-1.2 7-4 7-9V6z"}),n.jsx("path",{d:"m9 12.5 2 2 4-4"})]});case"route":return n.jsxs("svg",{...r,children:[n.jsx("circle",{cx:"6",cy:"6",r:"2"}),n.jsx("circle",{cx:"18",cy:"18",r:"2"}),n.jsx("path",{d:"M8 6h4a4 4 0 0 1 4 4v6"}),n.jsx("path",{d:"M16 6h2"})]});case"terminal":return n.jsxs("svg",{...r,children:[n.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),n.jsx("path",{d:"m7 9 3 3-3 3"}),n.jsx("path",{d:"M13 15h4"})]});case"compass":return n.jsxs("svg",{...r,children:[n.jsx("circle",{cx:"12",cy:"12",r:"9"}),n.jsx("path",{d:"m10 10 6-2-2 6-6 2z"})]});case"infinity":return n.jsx("svg",{...r,children:n.jsx("path",{d:"M18.178 8c5.096 0 5.096 8 0 8-5.095 0-7.133-8-12.739-8-4.585 0-4.585 8 0 8 5.606 0 7.644-8 12.74-8z"})});case"message":default:return n.jsx("svg",{...r,children:n.jsx("path",{d:"M21 12a8 8 0 0 1-8 8H7l-4 2 1.5-4A8 8 0 1 1 21 12z"})})}}function Zr(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Zi(e){if(!e)return;const t=Zr(e.metadata);return t?{...e,...t}:e}function np(e){try{return new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}catch{return""}}function sp(e){let t=0;for(const s of e){const r=Zi(Zr(s.metadata)),i=r==null?void 0:r.costTotal;typeof i=="number"&&(t+=i)}return t<=0?null:t<.01?"<$0.01":`$${t.toFixed(2)}`}const rp=o.memo(function({items:t,session:s,agentName:r,onBack:i,onOpenItem:a}){const[c,l]=o.useState(!1),d=o.useMemo(()=>[...t].sort((p,w)=>Date.parse(p.timestamp)-Date.parse(w.timestamp)),[t]),u=o.useMemo(()=>sp(d),[d]),h=o.useMemo(()=>{if(d.length<2)return null;const p=Date.parse(d[0].timestamp),v=Date.parse(d[d.length-1].timestamp)-p;return v<6e4?`${Math.round(v/1e3)}s`:v<36e5?`${Math.round(v/6e4)}m`:`${(v/36e5).toFixed(1)}h`},[d]),y=o.useMemo(()=>{let p=null,w=null,v=null,x=null,C=null;for(const g of d){const S=Zi(Zr(g.metadata));if(S&&(!p&&typeof S.domain=="string"&&(p=S.domain),!w&&typeof S.provider=="string"&&(w=S.provider),!v&&typeof S.model=="string"&&(v=S.model),!x&&typeof S.spawn_guard_model_tier=="string"&&(x=S.spawn_guard_model_tier),!C&&typeof S.kickoff_context_hash=="string"&&(C=S.kickoff_context_hash),p&&(w||v)&&x&&C))break}return!(p||w||v||x||C)?null:{domain:p,provider:w,model:v,modelTier:x,kickoffContextHash:C}},[d]),b=(s==null?void 0:s.title)??r??"Session";return n.jsxs("div",{className:"flex h-full flex-col",children:[n.jsxs("div",{className:"border-b border-subtle px-4 py-3",children:[n.jsxs("button",{onClick:i,className:"mb-2 flex items-center gap-1.5 text-caption text-secondary transition-colors hover:text-primary",children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m15 18-6-6 6-6"})}),"Back to timeline"]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:F.lime,boxShadow:`0 0 12px ${F.lime}55`}}),n.jsx("h3",{className:"text-heading font-semibold text-white",children:lt(b)})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-micro text-secondary",children:[r&&n.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-subtle px-1 py-0.5",children:[n.jsx(Ot,{name:r,hint:(s==null?void 0:s.id)??(s==null?void 0:s.runId)??null,size:"xs"}),n.jsx("span",{children:r})]}),n.jsxs("span",{children:[d.length," turn",d.length!==1?"s":""]}),h&&n.jsx("span",{children:h}),u&&n.jsx("span",{className:"text-muted",children:u}),(y==null?void 0:y.domain)&&n.jsx("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:lt(y.domain)}),(s==null?void 0:s.status)&&n.jsx("span",{className:"rounded-full px-1.5 py-0.5 text-micro uppercase tracking-wider",style:{backgroundColor:s.status==="running"?`${F.lime}20`:s.status==="failed"?`${F.red}20`:`${F.teal}20`,color:s.status==="running"?F.lime:s.status==="failed"?F.red:F.teal},children:s.status}),y&&(y.provider||y.model||y.modelTier||y.kickoffContextHash)&&n.jsxs("button",{type:"button",onClick:()=>l(p=>!p),className:"inline-flex items-center gap-1 text-micro text-muted transition-colors hover:text-secondary",children:[n.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:`transition-transform duration-150 ${c?"rotate-180":""}`,children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),"Info"]})]}),c&&y&&n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5 text-micro",children:[(y.provider||y.model)&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:[y.provider?`${lt(y.provider)} · `:"",y.model?gr(y.model):"—"]}),y.modelTier&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:["tier: ",lt(y.modelTier)]}),y.kickoffContextHash&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 font-mono text-secondary",children:["kickoff ",y.kickoffContextHash.slice(0,8),"…"]})]})]}),n.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3",children:[n.jsx(pt,{mode:"popLayout",children:n.jsxs("div",{className:"relative",children:[n.jsx("div",{className:"absolute left-[7px] top-3 bottom-3 w-px",style:{backgroundColor:`${F.iris}25`}}),n.jsx("div",{className:"space-y-1",children:d.map((p,w)=>{var K;const v=ep(p),x=v.color,C=(K=Zi(Zr(p.metadata)))==null?void 0:K.model,j=typeof C=="string"?gr(C):null,g=lt(p.title??""),S=p.type==="run_failed",W=p.type==="artifact_created",Y=p.type==="decision_requested"||p.type==="decision_resolved";return n.jsxs(be.button,{type:"button",initial:{opacity:0,x:-8},animate:{opacity:1,x:0},transition:{duration:.2,delay:w*.02},onClick:()=>a==null?void 0:a(p),className:"group relative flex w-full items-start gap-2.5 rounded-lg py-1.5 pl-0 pr-2 text-left transition-colors hover:bg-white/[0.02] focus:outline-none focus-visible:ring-2 focus-visible:ring-[#BFFF00]/35 focus-visible:ring-offset-1 focus-visible:ring-offset-[#02040A]",children:[n.jsx("span",{className:"relative z-10 mt-1.5 flex h-[15px] w-[15px] flex-shrink-0 items-center justify-center rounded-full text-[8px]",style:{backgroundColor:`${x}20`,color:x,border:`1px solid ${x}40`},children:n.jsx(tp,{icon:v.icon,size:8,className:"opacity-95"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:`text-body leading-snug ${S?"text-red-400":Y?"text-amber-300":W?"text-cyan-300":"text-bright"}`,children:g}),p.summary&&p.summary!==g&&n.jsx("p",{className:"mt-0.5 text-caption leading-relaxed text-muted",children:lt(p.summary)})]}),n.jsxs("div",{className:"flex flex-shrink-0 flex-col items-end gap-0.5 pt-0.5",children:[n.jsx("span",{className:"text-micro text-muted",title:Gr(p.timestamp),children:np(p.timestamp)}),j&&n.jsx("span",{className:"text-micro text-faint",children:j})]})]},p.id)})})]})}),d.length===0&&n.jsxs("div",{className:"flex flex-col items-center gap-2 py-8 text-center",children:[n.jsx("p",{className:"text-body text-secondary",children:"No activity in this session yet."}),n.jsx("p",{className:"text-caption text-muted animate-pulse",children:"Activity may take a moment to appear."})]}),d.length>0&&n.jsxs("div",{className:"mt-4 rounded-lg border border-subtle bg-white/[0.02] px-3 py-2 text-micro text-muted",children:[d.length," turn",d.length!==1?"s":"",h?` over ${h}`:"",u?` · ${u}`:""," · ",n.jsx("span",{title:Gr(d[d.length-1].timestamp),children:It(d[d.length-1].timestamp)})]})]})]})});function ip({completedCount:e,decisionsCount:t,blockerCount:s,visible:r,onDismiss:i}){if(!(e>0||t>0||s>0))return null;const c=[];return e>0&&c.push(`${e} task${e===1?"":"s"} completed`),t>0&&c.push(`${t} need${t===1?"s":""} decisions`),s>0&&c.push(`${s} new blocker${s===1?"":"s"}`),n.jsx(pt,{children:r&&n.jsx(be.div,{initial:{opacity:0,height:0,marginBottom:0},animate:{opacity:1,height:"auto",marginBottom:12},exit:{opacity:0,height:0,marginBottom:0},transition:{duration:.3,ease:[.22,1,.36,1]},className:"overflow-hidden",children:n.jsx("div",{className:"rounded-xl px-4 py-3",style:{backgroundColor:`${F.teal}08`,border:`1px solid ${F.teal}20`},children:n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-caption font-semibold text-white",children:"While you were away"}),n.jsx("p",{className:"mt-1 text-body text-secondary",children:c.join(" · ")})]}),n.jsx("button",{onClick:i,className:"flex-shrink-0 rounded-md px-2.5 py-1 text-caption font-medium text-secondary transition-colors hover:bg-white/[0.06] hover:text-white",children:"Got it"})]})})})})}const ap={initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.98}};function op({renderKey:e,displayTitle:t,headline:s,contextLabel:r,detailText:i,displayAgentName:a,railColor:c,userStateLabel:l,userStateWhy:d,relativeTime:u,timeLabel:h,isRecent:y,enableMotion:b,onOpen:p,ariaLabel:w,artifactSnippet:v}){const x="group w-full rounded-xl border border-white/[0.08] bg-white/[0.02] px-3.5 py-3 text-left transition-colors hover:border-strong hover:bg-white/[0.05] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#BFFF00]/45 cv-auto",C=n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx("div",{className:"mt-0.5",children:n.jsx(Ot,{name:a,hint:a,size:"xs"})}),n.jsxs("div",{className:"relative min-w-0 flex-1 pl-3",children:[n.jsx("span",{className:pe("absolute inset-y-0 left-0 w-[2px] rounded-full",y&&"pulse-soft"),style:{backgroundColor:c,boxShadow:`0 0 14px ${c}66`}}),n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"truncate text-caption text-secondary",title:r,children:r}),n.jsx("p",{className:"mt-0.5 line-clamp-1 break-words text-body font-semibold leading-snug text-bright",children:s||t})]}),n.jsxs("div",{className:"flex shrink-0 flex-col items-end gap-1",children:[n.jsx("span",{className:"text-caption text-secondary",children:h}),n.jsx("span",{className:"text-micro text-muted",children:u})]})]}),v?n.jsxs("div",{className:"mt-2 flex items-center gap-2 rounded-lg border border-cyan-400/20 bg-cyan-500/[0.06] px-2.5 py-1.5",children:[n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#67e8f9",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"flex-shrink-0",children:[n.jsx("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),n.jsx("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"})]}),n.jsxs("span",{className:"min-w-0 flex-1 truncate text-caption text-cyan-200/90",children:[n.jsx("span",{className:"font-semibold",children:v.label}),v.preview&&n.jsx("span",{className:"ml-1.5 text-cyan-200/60",children:v.preview})]}),n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#67e8f9",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:"flex-shrink-0 opacity-50",children:n.jsx("path",{d:"m9 18 6-6-6-6"})})]}):i?n.jsx("div",{className:"mt-1.5 line-clamp-2 text-caption leading-relaxed text-secondary",children:n.jsx(Yr,{mode:"inline",text:i})}):null,n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5 text-micro",children:[n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border px-2 py-0.5 font-semibold tracking-[0.01em]",style:{borderColor:`${c}55`,backgroundColor:`${c}1A`,color:c},title:d,children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:c}}),l]}),n.jsx("span",{className:"inline-flex max-w-[220px] items-center gap-1 rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",title:a,children:n.jsx("span",{className:"truncate",children:a})})]})]})]});return b?n.jsx(be.button,{type:"button",variants:ap,initial:"initial",animate:"animate",exit:"exit",transition:{duration:.25,ease:[.4,0,.2,1]},whileHover:{y:-1.5},whileTap:{scale:.995},onClick:p,className:x,"aria-label":w,children:C},e):n.jsx("button",{type:"button",onClick:p,className:pe(x,"transform-gpu transition-[transform,background-color,border-color,color] hover:-translate-y-[1px] active:scale-[0.995]"),"aria-label":w,children:C},e)}function lp({open:e,onClose:t,children:s}){return n.jsx(ai,{open:e,onClose:t,maxWidth:"max-w-3xl",closeOnEscape:!1,children:s})}function cp(e){const t=e.metadata??{},s=e.phase??e.state??t.phase??"",r=e.state??"",i=t.event??t.event_name??"";if(s==="completed"||i==="auto_continue_started"||r==="completed")return"teal";if(s==="blocked"||r==="blocked"||r==="error"||i==="auto_continue_stopped"){const a=t.stop_reason??"";return a==="error"||a==="blocked"?"red":a==="budget_exhausted"||a==="stopped"?"amber":s==="blocked"||r==="error"?"red":"amber"}return e.decisionRequired||r==="needs_input"?"amber":"neutral"}const dp={teal:{border:"border-[#0AD4C4]/20",bg:"bg-[#0AD4C4]/[0.04]",dot:"bg-[#0AD4C4]",label:"text-[#7AEDE5]"},amber:{border:"border-[#F5B700]/20",bg:"bg-[#F5B700]/[0.04]",dot:"bg-[#F5B700]",label:"text-[#FFE7A8]"},red:{border:"border-[#FF6B6B]/20",bg:"bg-[#FF6B6B]/[0.04]",dot:"bg-[#FF6B6B]",label:"text-[#FFA8A8]"},neutral:{border:"border-white/[0.04]",bg:"bg-white/[0.02]",dot:"bg-white/40",label:"text-secondary"}};function up({item:e,className:t}){const s=o.useMemo(()=>Hl(e),[e]),r=cp(e),i=dp[r];return!s.taskDescription&&!s.outcomeDescription&&!s.nextStep?null:n.jsxs("div",{className:`rounded-lg border ${i.border} ${i.bg} p-6 space-y-5 ${t??""}`,children:[s.taskDescription&&n.jsx(Ci,{label:"Task",value:s.taskDescription,styles:i}),s.outcomeDescription&&n.jsx(Ci,{label:"Outcome",value:s.outcomeDescription,styles:i}),s.nextStep&&n.jsx(Ci,{label:"Next step",value:s.nextStep,styles:i})]})}function Ci({label:e,value:t,styles:s}){return n.jsx("div",{className:"flex items-start gap-4",children:n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("span",{className:`text-[10px] font-semibold uppercase tracking-widest ${s.label}`,children:e}),n.jsx("p",{className:"text-[14px] leading-relaxed text-white mt-1",children:t})]})})}const uo=new Set(["orgx-orchestrator","xandy","dispatcher","router-all-agents"]),mp=[{id:"eli",name:"Eli",handle:"eli",domain:"engineering",domainLabel:"Engineering",role:"Engineering"},{id:"dana",name:"Dana",handle:"dana",domain:"design",domainLabel:"Product Design",role:"Product Design"},{id:"mark",name:"Mark",handle:"mark",domain:"marketing",domainLabel:"Marketing",role:"Marketing"},{id:"sage",name:"Sage",handle:"sage",domain:"sales",domainLabel:"Sales",role:"Sales"},{id:"orion",name:"Orion",handle:"orion",domain:"operations",domainLabel:"Operations",role:"Operations"},{id:"pace",name:"Pace",handle:"pace",domain:"product",domainLabel:"Product",role:"Product"}],or=[{id:"auto",label:"Auto (best available)",shortLabel:"Auto",accent:"#8F9AB7",icon:"auto"},{id:"anthropic",label:"Claude Code",shortLabel:"Claude",accent:"#F5B700",icon:"anthropic"},{id:"openai",label:"Codex",shortLabel:"Codex",accent:"#10B981",icon:"openai"}],mo={type:"spring",stiffness:400,damping:25},po={scale:.985};function Jt(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function pp(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?"Unknown size":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function lr(e,t){const s=(e??"").trim().toLowerCase();return s.includes("unknown api endpoint")?"Chat API unavailable in current runtime. Restart the plugin so /orgx/api/chat/* routes are active.":s.includes("network error")||s.includes("failed to fetch")?t==="load"?"Could not load thread details. Check connection and retry.":"Connection lost while sending. Draft is preserved.":s?Bt(bn(e??"Request failed.")):t==="send"?"Message send failed. Draft is preserved.":t==="launch"?"Launch request failed. Thread remains saved.":"Request failed."}function fp(e){return[e.title,e.summary??"",e.lastSnippet??"",e.assigneeName??"",e.initiativeTitle??"",...e.watcherNames??[]].join(" ").toLowerCase()}function hp(e,t){return t==="all"?!0:t==="completed"?e.status==="completed":t==="in_progress"?e.status==="queued"||e.status==="running":t==="needs_attention"?e.status==="blocked"||e.status==="failed":!0}function ei(e){return e==="message_only"?"Message sent":e==="queued"?"Queued":e==="running"?"Running":e==="blocked"?"Blocked":e==="completed"?"Completed":e==="failed"?"Failed":e}function Ks(e){return e==="running"?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":e==="completed"?"border-teal/30 bg-teal/[0.12] text-teal-100":e==="blocked"||e==="failed"?"border-rose-400/30 bg-rose-400/[0.12] text-rose-100":e==="queued"?"border-white/[0.18] bg-white/[0.08] text-primary":"border-white/[0.12] bg-white/[0.04] text-secondary"}function fl(e){return e==="user"?"You":e==="agent"?"Agent":"System"}function gp(e){return e==="agent"?"assistant":e}function xp(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join("").trim()}function yp(e,t){return t.map(s=>({id:s.id,role:gp(s.role),metadata:{threadId:e,messageId:s.id,source:"thread-store"},parts:[{type:"text",text:s.body,state:"done"}]}))}function hl(e){return e==="queued"?"queued":e==="running"?"running":e==="blocked"?"blocked":e==="completed"?"completed":e==="failed"?"failed":"message_only"}function Gs(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Kr(e){const t=Gs(e);if(!t)return null;const s=typeof t.id=="string"?t.id.trim():"";if(!s)return null;const r=Gs(t.latestMessage),i=Gs(t.latestLaunch);return{id:s,commandCenterId:typeof t.commandCenterId=="string"?t.commandCenterId:null,initiativeId:typeof t.initiativeId=="string"?t.initiativeId:null,initiativeTitle:typeof t.initiativeTitle=="string"?t.initiativeTitle:null,workstreamId:typeof t.workstreamId=="string"?t.workstreamId:null,taskId:typeof t.taskId=="string"?t.taskId:null,title:typeof t.title=="string"&&t.title.trim().length>0?t.title:"Untitled thread",summary:typeof t.summary=="string"?t.summary:null,status:t.status==="queued"||t.status==="running"||t.status==="blocked"||t.status==="completed"||t.status==="failed"||t.status==="message_only"?t.status:"message_only",assigneeId:typeof t.assigneeId=="string"?t.assigneeId:null,assigneeName:typeof t.assigneeName=="string"?t.assigneeName:null,watcherIds:Array.isArray(t.watcherIds)?t.watcherIds.filter(a=>typeof a=="string"):[],watcherNames:Array.isArray(t.watcherNames)?t.watcherNames.filter(a=>typeof a=="string"):[],messageCount:typeof t.messageCount=="number"?Math.max(0,Math.floor(t.messageCount)):0,launchCount:typeof t.launchCount=="number"?Math.max(0,Math.floor(t.launchCount)):0,lastMessageAt:typeof t.lastMessageAt=="string"?t.lastMessageAt:null,lastLaunchAt:typeof t.lastLaunchAt=="string"?t.lastLaunchAt:null,lastActivityAt:typeof t.lastActivityAt=="string"&&t.lastActivityAt.length>0?t.lastActivityAt:new Date().toISOString(),lastSnippet:typeof t.lastSnippet=="string"?t.lastSnippet:null,createdAt:typeof t.createdAt=="string"?t.createdAt:new Date().toISOString(),updatedAt:typeof t.updatedAt=="string"?t.updatedAt:new Date().toISOString(),latestMessage:r?{id:typeof r.id=="string"?r.id:`msg_${s}`,threadId:typeof r.threadId=="string"?r.threadId:s,role:r.role==="agent"||r.role==="system"?r.role:"user",body:typeof r.body=="string"?r.body:"",senderId:typeof r.senderId=="string"?r.senderId:null,senderName:typeof r.senderName=="string"?r.senderName:null,createdAt:typeof r.createdAt=="string"?r.createdAt:typeof t.lastMessageAt=="string"?t.lastMessageAt:new Date().toISOString(),updatedAt:typeof r.updatedAt=="string"?r.updatedAt:typeof t.lastMessageAt=="string"?t.lastMessageAt:new Date().toISOString(),attachments:Array.isArray(r.attachments)?r.attachments.filter(a=>!!a&&typeof a=="object"):[],metadata:r.metadata&&typeof r.metadata=="object"?r.metadata:{}}:null,latestLaunch:i?{id:typeof i.id=="string"?i.id:`launch_${s}`,threadId:typeof i.threadId=="string"?i.threadId:s,messageId:typeof i.messageId=="string"?i.messageId:typeof t.lastMessageAt=="string"?`msg_${t.lastMessageAt}`:`msg_${s}`,assigneeId:typeof i.assigneeId=="string"?i.assigneeId:null,assigneeName:typeof i.assigneeName=="string"?i.assigneeName:null,watcherIds:Array.isArray(i.watcherIds)?i.watcherIds.filter(a=>typeof a=="string"):[],watcherNames:Array.isArray(i.watcherNames)?i.watcherNames.filter(a=>typeof a=="string"):[],executionMode:i.executionMode==="cloud"||i.executionMode==="hybrid"?i.executionMode:"local_queue",provider:typeof i.provider=="string"?i.provider:null,runId:typeof i.runId=="string"?i.runId:null,status:i.status==="queued"||i.status==="running"||i.status==="blocked"||i.status==="completed"||i.status==="failed"||i.status==="requested"?i.status:"requested",blockedReason:typeof i.blockedReason=="string"?i.blockedReason:null,warnings:Array.isArray(i.warnings)?i.warnings.filter(a=>typeof a=="string"):[],requestedAt:typeof i.requestedAt=="string"?i.requestedAt:typeof t.lastLaunchAt=="string"?t.lastLaunchAt:new Date().toISOString(),updatedAt:typeof i.updatedAt=="string"?i.updatedAt:typeof t.lastLaunchAt=="string"?t.lastLaunchAt:new Date().toISOString(),metadata:i.metadata&&typeof i.metadata=="object"?i.metadata:{}}:null}}function bp(e){const t=Gs(e);if(!t)return null;const s=Kr({...t,latestMessage:Array.isArray(t.messages)?t.messages[t.messages.length-1]:null,latestLaunch:Array.isArray(t.launches)?t.launches[0]:null});if(!s)return null;const r=Array.isArray(t.messages)?t.messages.map(a=>Gs(a)).filter(a=>!!a).map(a=>{const c=a.role==="agent"||a.role==="system"?a.role:"user";return{id:typeof a.id=="string"?a.id:`msg_${s.id}`,threadId:typeof a.threadId=="string"?a.threadId:s.id,role:c,body:typeof a.body=="string"?a.body:"",senderId:typeof a.senderId=="string"?a.senderId:null,senderName:typeof a.senderName=="string"?a.senderName:null,createdAt:typeof a.createdAt=="string"?a.createdAt:s.createdAt,updatedAt:typeof a.updatedAt=="string"?a.updatedAt:s.updatedAt,attachments:Array.isArray(a.attachments)?a.attachments.filter(l=>!!l&&typeof l=="object"):[],metadata:a.metadata&&typeof a.metadata=="object"?a.metadata:{}}}):[],i=Array.isArray(t.launches)?t.launches.map(a=>Gs(a)).filter(a=>!!a).map(a=>{const c=a.executionMode==="cloud"||a.executionMode==="hybrid"?a.executionMode:"local_queue",l=a.status==="queued"||a.status==="running"||a.status==="blocked"||a.status==="completed"||a.status==="failed"||a.status==="requested"?a.status:"requested";return{id:typeof a.id=="string"?a.id:`launch_${s.id}`,threadId:typeof a.threadId=="string"?a.threadId:s.id,messageId:typeof a.messageId=="string"?a.messageId:"",assigneeId:typeof a.assigneeId=="string"?a.assigneeId:null,assigneeName:typeof a.assigneeName=="string"?a.assigneeName:null,watcherIds:Array.isArray(a.watcherIds)?a.watcherIds.filter(d=>typeof d=="string"):[],watcherNames:Array.isArray(a.watcherNames)?a.watcherNames.filter(d=>typeof d=="string"):[],executionMode:c,provider:typeof a.provider=="string"?a.provider:null,runId:typeof a.runId=="string"?a.runId:null,status:l,blockedReason:typeof a.blockedReason=="string"?a.blockedReason:null,warnings:Array.isArray(a.warnings)?a.warnings.filter(d=>typeof d=="string"):[],requestedAt:typeof a.requestedAt=="string"?a.requestedAt:s.updatedAt,updatedAt:typeof a.updatedAt=="string"?a.updatedAt:s.updatedAt,metadata:a.metadata&&typeof a.metadata=="object"?a.metadata:{}}}):[];return{...s,messages:r.sort((a,c)=>Jt(a.createdAt)-Jt(c.createdAt)),launches:i.sort((a,c)=>Jt(c.requestedAt)-Jt(a.requestedAt))}}function wp(e,t,s){const r=Jt(e.lastActivityAt);if(!r)return!1;if(t==="custom"){const a=Jt(s.startIso),c=Jt(s.endIso);return!(a&&r<a||c&&r>c)}const i=yr(t,Date.now());return i?r>=i:!0}async function cr(e,t){try{const s=await fetch(e,t),r=await s.json().catch(()=>null);return s.ok?{ok:!0,status:s.status,data:r,error:null}:{ok:!1,status:s.status,data:null,error:(r&&typeof r.error=="string"?r.error:null)??`Request failed (${s.status})`}}catch(s){return{ok:!1,status:0,data:null,error:s instanceof Error?s.message:"Network error"}}}function Mi(e,t){const s=new Map;for(const r of e)s.set(r.id,r);return s.set(t.id,t),Array.from(s.values()).sort((r,i)=>Jt(i.lastActivityAt??i.updatedAt)-Jt(r.lastActivityAt??r.updatedAt))}function vp(e,t){const s=new Map;for(const r of e)s.set(r.id,r);for(const r of t)s.set(r.id,r);return Array.from(s.values()).sort((r,i)=>Jt(i.lastActivityAt??i.updatedAt)-Jt(r.lastActivityAt??r.updatedAt))}const gl=o.createContext(null),xl=o.createContext(null);function ua(){const e=o.useContext(gl);if(!e)throw new Error("useChatDockState must be used within ChatDockProvider");return e}function ma(){const e=o.useContext(xl);if(!e)throw new Error("useChatDockDispatch must be used within ChatDockProvider");return e}function kp({children:e,sessions:t,initiatives:s,workspaceId:r,query:i,statusFilter:a,sortOrder:c,timeFilterId:l,customTimeRange:d,snapshot:u,onRequestRefresh:h}){const[y,b]=o.useState((u==null?void 0:u.threads)??[]),[p,w]=o.useState(null),[v,x]=o.useState(null),[C,j]=o.useState(!1),[g,S]=o.useState(null),[W,Y]=o.useState("resting"),[K,me]=o.useState(""),[ge,Z]=o.useState(!1),[ae,ke]=o.useState(!1),[Fe,G]=o.useState(null),[Se,Ae]=o.useState(null),[xe,re]=o.useState([]),[le,Ee]=o.useState(""),[ee,q]=o.useState([]),[J,V]=o.useState(""),[k,z]=o.useState(null),[O,oe]=o.useState(""),[ie,Me]=o.useState(!1),[ue,R]=o.useState(""),[$,X]=o.useState([]),[te,Le]=o.useState(!1),[qe,_e]=o.useState("auto"),[M,B]=o.useState(!1),[ne,fe]=o.useState(!1),[De,et]=o.useState(!1),tt=o.useRef(null),Re=o.useRef(null),Je=o.useRef(null),We=o.useRef(null);o.useEffect(()=>{u!=null&&u.threads&&b(D=>vp(D,u.threads))},[u==null?void 0:u.threads,u==null?void 0:u.updatedAt]),o.useEffect(()=>{p&&b(D=>D.sort((he,de)=>Jt(de.lastActivityAt)-Jt(he.lastActivityAt)))},[p]);const{data:ft}=ca({enabled:!0,refetchInterval:8e3}),ot=o.useMemo(()=>{var he,de;const D=new Map;for(const Ie of mp)D.set(Ie.id,{id:Ie.id,name:Ie.name,handle:Ie.handle,domain:Ie.domain,domainLabel:Ie.domainLabel,role:Ie.role,status:"idle",currentTask:null,isSystem:!1});if(ft!=null&&ft.agents)for(const Ie of ft.agents){const xt=D.get(Ie.id);xt?(xt.status=Ie.status==="running"?"running":(he=Ie.blockers)!=null&&he.length?"blocked":"idle",xt.currentTask=Ie.currentTask??null):D.set(Ie.id,{id:Ie.id,name:Ie.name,handle:Ie.id,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:Ie.status==="running"?"running":(de=Ie.blockers)!=null&&de.length?"blocked":"idle",currentTask:Ie.currentTask??null,isSystem:uo.has(Ie.id)})}for(const Ie of t){const xt=(Ie.agentId??"").trim(),Ye=(Ie.agentName??"").trim();!xt||!Ye||D.has(xt)||D.set(xt,{id:xt,name:Ye,handle:xt,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:"idle",currentTask:null,isSystem:uo.has(xt)})}return Array.from(D.values()).filter(Ie=>!Ie.isSystem).sort((Ie,xt)=>Ie.name.localeCompare(xt.name))},[ft,t]),nt=o.useMemo(()=>s.map(D=>({id:D.id,name:D.name})).sort((D,he)=>D.name.localeCompare(he.name)),[s]),we=o.useMemo(()=>ot.find(D=>D.id===le)??null,[ot,le]),Ge=o.useMemo(()=>{const D=new Set(ee);return ot.filter(he=>D.has(he.id))},[ot,ee]),je=o.useMemo(()=>nt.find(D=>D.id===J)??null,[nt,J]);o.useEffect(()=>{le&&q(D=>D.filter(he=>he!==le))},[le]);const H=o.useMemo(()=>ot.slice(0,8),[ot]),Oe=o.useMemo(()=>{const D=O.trim().toLowerCase();return D?ot.filter(he=>he.name.toLowerCase().includes(D)||he.handle.toLowerCase().includes(D)||he.domain.toLowerCase().includes(D)||he.role.toLowerCase().includes(D)):ot},[ot,O]),U=o.useMemo(()=>{const D=ue.trim().toLowerCase();return D?nt.filter(he=>he.name.toLowerCase().includes(D)):nt},[nt,ue]),se=o.useMemo(()=>{const D=i.trim().toLowerCase(),he=y.filter(de=>!hp(de,a)||!wp(de,l,d)?!1:D.length===0?!0:fp(de).includes(D));return he.sort((de,Ie)=>{const xt=Jt(Ie.lastActivityAt)-Jt(de.lastActivityAt);return c==="newest"?xt:-xt}),he},[d,i,c,a,y,l]),Ce=o.useMemo(()=>{if(!p||se.some(he=>he.id===p))return se;const D=y.find(he=>he.id===p);return D?[D,...se]:se},[p,se,y]),$e=o.useMemo(()=>y.find(D=>D.id===p)??null,[p,y]),Pe=o.useMemo(()=>xe.filter(D=>D.status!=="ready").length,[xe]),Te=K.trim().length>0&&!ge,He=o.useMemo(()=>Pe>0?`${Pe} attachment(s) still processing.`:"Press Enter to send.",[Pe]),st=o.useMemo(()=>ge?"Sending…":ae?"Launching…":"Send",[ae,ge]),Ve=o.useMemo(()=>new Pl({api:"/orgx/api/chat/usechat"}),[]),{messages:Pt,setMessages:Qe,sendMessage:Mt,status:Yt,error:mt,clearError:rn}=Dl({id:`orgx-chat-guidance-${r??"global"}`,transport:Ve,onError:D=>{G(lr((D==null?void 0:D.message)??null,"send"))}});o.useEffect(()=>{if(!v){Qe([]);return}Qe(yp(v.id,v.messages))},[v,Qe]);const _n=o.useMemo(()=>{const D=[...Pt].reverse().find(de=>de.role==="assistant");if(!D)return null;const he=xp(D);return he.length>0?he:null},[Pt]),ps=o.useRef(null);o.useEffect(()=>{if(Yt!=="ready"&&Yt!=="error"||!_n)return;const D=[...Pt].reverse().find(he=>he.role==="assistant");!D||D.id===ps.current||(ps.current=D.id,X(he=>[...he,{id:`guidance_${D.id}`,role:"agent",body:_n,timestamp:new Date().toISOString()}]))},[Yt,_n,Pt]);const gt=o.useCallback(()=>{me(""),re([]),fe(!1),et(!1),G(null),Ae(null)},[]),Wt=o.useCallback(D=>{X(he=>[...he,{...D,id:`inline_${crypto.randomUUID()}`,timestamp:new Date().toISOString()}])},[]),Cn=o.useCallback(()=>X([]),[]),Qn=o.useCallback(()=>Le(D=>!D),[]),Rt=o.useMemo(()=>or.find(D=>D.id===qe)??or[0],[qe]),$n=o.useCallback(()=>{_e(D=>{const he=or.findIndex(de=>de.id===D);return or[(he+1)%or.length].id})},[]),jt=o.useCallback(async()=>{typeof h=="function"&&await h()},[h]),Dt=o.useCallback(async D=>{var Ie;j(!0),S(null);const he=await cr(`/orgx/api/chat/threads/${encodeURIComponent(D)}`);if(!he.ok||!((Ie=he.data)!=null&&Ie.thread))return j(!1),S(lr(he.error,"load")),null;const de=bp(he.data.thread);return de?(x(de),j(!1),de):(j(!1),S("Thread detail payload was invalid."),null)},[]),Ct=o.useCallback(async(D,he)=>{he&&(Je.current=he),w(D),await Dt(D),requestAnimationFrame(()=>{var de;return(de=Re.current)==null?void 0:de.focus()})},[Dt]),Mn=o.useCallback(()=>{var D;w(null),x(null),S(null),j(!1),(D=Je.current)==null||D.focus()},[]),Pn=o.useCallback(D=>{window.setTimeout(()=>{re(he=>he.map(de=>de.id===D?{...de,status:"indexing",updatedAt:new Date().toISOString()}:de))},80),window.setTimeout(()=>{re(he=>he.map(de=>{var Ye;if(de.id!==D)return de;const Ie=((Ye=de.mimeType)==null?void 0:Ye.toLowerCase())==="application/x-msdownload"||de.name.toLowerCase().endsWith(".exe"),xt=(de.sizeBytes??0)>25*1024*1024;return Ie?{...de,status:"failed",error:"Unsupported file type.",updatedAt:new Date().toISOString()}:xt?{...de,status:"failed",error:"File exceeds 25 MB extraction limit.",updatedAt:new Date().toISOString()}:{...de,status:"ready",error:null,updatedAt:new Date().toISOString()}}))},420)},[]),Rs=o.useCallback(D=>{if(!D||D.length===0)return;const he=new Date().toISOString(),de=Array.from(D).map(Ie=>({id:`draft_att_${crypto.randomUUID()}`,name:Ie.name,mimeType:Ie.type||null,sizeBytes:Number.isFinite(Ie.size)?Ie.size:null,status:"preparing",error:null,masked:!1,createdAt:he,updatedAt:he}));re(Ie=>Ie.concat(de)),de.forEach(Ie=>Pn(Ie.id)),rs("chat_attachment_state_changed",{count:de.length,state:"preparing"})},[Pn]),fs=o.useCallback(D=>{re(he=>he.map(de=>de.id===D?{...de,status:"preparing",error:null,updatedAt:new Date().toISOString()}:de)),Pn(D),rs("chat_attachment_state_changed",{state:"retry"})},[Pn]),Zt=o.useCallback(D=>{Ee(he=>he===D?"":D),q(he=>he.filter(de=>de!==D)),z(null),oe("")},[]),Xt=o.useCallback(D=>{q(he=>he.includes(D)?he.filter(de=>de!==D):he.concat(D))},[]),Ht=o.useCallback(()=>{Me(!1),R(""),z(D=>D==="assignee"?null:"assignee"),oe("")},[]),Jn=o.useCallback(()=>{Me(!1),R(""),z(D=>D==="watcher"?null:"watcher"),oe("")},[]),pn=o.useCallback(()=>{z(null),oe(""),Me(D=>!D),R("")},[]),Yn=o.useCallback(async(D,he)=>{var Ye;B(!0);const de=nt.find(rt=>rt.id===he)??null,Ie=await cr("/orgx/api/chat/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:D,project_id:r??void 0,initiativeId:(de==null?void 0:de.id)??null,initiativeTitle:(de==null?void 0:de.name)??null,relinked:!0})});if(B(!1),!Ie.ok||!((Ye=Ie.data)!=null&&Ye.thread)){S(Ie.error??"Scope link failed.");return}const xt=Kr(Ie.data.thread);xt&&b(rt=>Mi(rt,xt)),await Dt(D),await jt(),rs("chat_thread_linked_initiative",{threadId:D,initiativeId:(de==null?void 0:de.id)??null})},[nt,Dt,jt,r]),Zn=o.useCallback(async D=>{rn(),await Mt({text:D.prompt},{body:{threadId:D.thread.id,project_id:r??void 0,initiativeId:D.thread.initiativeId??(je==null?void 0:je.id)??void 0,initiativeTitle:D.thread.initiativeTitle??(je==null?void 0:je.name)??void 0,assigneeId:(we==null?void 0:we.id)??D.thread.assigneeId??void 0,assigneeName:(we==null?void 0:we.name)??D.thread.assigneeName??void 0,watcherIds:Ge.map(he=>he.id),watcherNames:Ge.map(he=>he.name)}}),await jt(),await Dt(D.thread.id)},[rn,Dt,jt,we==null?void 0:we.id,we==null?void 0:we.name,je==null?void 0:je.id,je==null?void 0:je.name,Ge,Mt,r]),Tn=o.useCallback(async()=>{var xt,Ye;const D=K.trim();if(!D)return G("Write a message before sending."),{thread:null,messageId:null};G(null),Ae(null),Z(!0);const he=await cr("/orgx/api/chat/messages",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:p??void 0,project_id:r??void 0,initiativeId:(je==null?void 0:je.id)??(v==null?void 0:v.initiativeId)??void 0,initiativeTitle:(je==null?void 0:je.name)??(v==null?void 0:v.initiativeTitle)??void 0,assigneeId:(we==null?void 0:we.id)??(v==null?void 0:v.assigneeId)??void 0,assigneeName:(we==null?void 0:we.name)??(v==null?void 0:v.assigneeName)??void 0,watcherIds:Ge.map(rt=>rt.id),watcherNames:Ge.map(rt=>rt.name),body:D,attachments:xe.map(rt=>({id:rt.id,name:rt.name,mimeType:rt.mimeType,sizeBytes:rt.sizeBytes,status:rt.status,error:rt.error,masked:rt.masked}))})});if(Z(!1),!he.ok||!((xt=he.data)!=null&&xt.thread))return G(lr(he.error,"send")),rs("chat_message_send_failed",{reason:he.error??"unknown"}),{thread:null,messageId:null};const de=Kr(he.data.thread);if(!de)return G("Send succeeded but thread payload was invalid."),{thread:null,messageId:null};b(rt=>Mi(rt,de)),Wt({role:"user",body:D}),qe!=="auto"&&we&&Wt({role:"system",body:`Routing to ${we.name} via ${Rt.label}`}),rs("chat_message_sent",{threadId:de.id,watcherCount:de.watcherIds.length}),await jt();const Ie=he.data.message&&typeof he.data.message.id=="string"?he.data.message.id:((Ye=de.latestMessage)==null?void 0:Ye.id)??null;return w(de.id),await Dt(de.id),Zn({thread:de,prompt:D}).catch(rt=>{Wt({role:"error",body:lr(rt instanceof Error?rt.message:String(rt??""),"send")})}),gt(),Y("reviewing"),{thread:de,messageId:Ie}},[v==null?void 0:v.assigneeId,v==null?void 0:v.assigneeName,v==null?void 0:v.initiativeId,v==null?void 0:v.initiativeTitle,p,K,xe,Dt,jt,gt,Zn,we==null?void 0:we.id,we==null?void 0:we.name,je==null?void 0:je.id,je==null?void 0:je.name,qe,Rt,Ge,r]),es=o.useCallback(async(D,he)=>{var kt,fn,On,gs,kn,xs,Bn;if(!he){Wt({role:"error",body:"Send a message first to launch."});return}if(!we){Wt({role:"error",body:"Pick an agent with @ before launching."});return}if(Pe>0&&!De){fe(!0),Wt({role:"error",body:"Some attachments are still processing. Confirm to continue."});return}ke(!0),G(null),Ae(null);const de=await cr("/orgx/api/agents/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:we.id,message:K.trim().length>0?K.trim():D.lastSnippet??D.title,initiativeId:D.initiativeId??(je==null?void 0:je.id)??void 0,initiativeTitle:D.initiativeTitle??(je==null?void 0:je.name)??void 0,workstreamId:D.workstreamId??void 0,taskId:D.taskId??void 0,provider:qe!=="auto"?qe:void 0})}),Ie=((kt=de.data)==null?void 0:kt.sessionId)??((fn=de.data)==null?void 0:fn.runId)??null,xt=de.ok&&Ie?"running":de.ok?"queued":"blocked",Ye=de.ok?null:de.error??"Launch request failed before queueing.",rt=await cr("/orgx/api/chat/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:D.id,messageId:he,assigneeId:we.id,assigneeName:we.name,watcherIds:Ge.map(Tt=>Tt.id),watcherNames:Ge.map(Tt=>Tt.name),executionMode:"local_queue",provider:((On=de.data)==null?void 0:On.provider)??(qe!=="auto"?qe:"openclaw"),runId:Ie??void 0,status:xt,blockedReason:Ye??void 0,warnings:Pe>0?[`${Pe} attachment(s) were not ready at launch.`]:[]})});if(ke(!1),et(!1),fe(!1),!rt.ok||!((gs=rt.data)!=null&&gs.thread)){G(rt.error?lr(rt.error,"launch"):Ye??"Launch state could not be persisted. Message remained saved."),rs("chat_launch_failed",{threadId:D.id,reason:rt.error??Ye??"unknown"});return}const hs=Kr(rt.data.thread);if(hs&&b(Tt=>Mi(Tt,hs)),await Dt(D.id),await jt(),!de.ok){G(`Launch blocked: ${Ye??"Set assignee and retry."}`),rs("chat_launch_blocked",{threadId:D.id,reason:Ye??"unknown"});return}const bt=((kn=de.data)==null?void 0:kn.provider)==="anthropic"?"Claude Code":((xs=de.data)==null?void 0:xs.provider)==="openai"?"Codex":Rt.shortLabel,ns=(Bn=de.data)!=null&&Bn.model?` (${de.data.model})`:"";Ae(Ie?`Launch started via ${bt}${ns}. Thread timeline now tracks execution state.`:`Launch queued locally via ${bt}. Run starts when a worker is available.`),rs(Ie?"chat_launch_started":"chat_launch_queued",{threadId:D.id,runId:Ie,assigneeId:we.id})},[K,De,Dt,jt,we,je==null?void 0:je.id,je==null?void 0:je.name,qe,Rt,Ge,Pe]),Ft=o.useCallback(async()=>{var he;const D=await Tn();(he=D.thread)!=null&&he.id&&await Ct(D.thread.id)},[Ct,Tn]),wn=o.useCallback(async()=>{const D=await Tn();D.thread&&(await es(D.thread,D.messageId),await Ct(D.thread.id))},[es,Ct,Tn]),an=o.useCallback(async()=>{if(Te){if(we){await wn();return}await Ft()}},[Te,wn,Ft,we]),ts=o.useMemo(()=>({threads:y,activeThreadId:p,activeThread:v,activeThreadSummary:$e,displayedThreads:Ce,composerMode:W,draft:K,draftAttachments:xe,sending:ge,launching:ae,composerError:Fe,composerNotice:Se,selectedAssigneeId:le,selectedAssignee:we,selectedWatcherIds:ee,selectedWatchers:Ge,selectedInitiativeId:J,selectedInitiative:je,agentOptions:ot,quickAssigneeOptions:H,initiativeOptions:nt,agentPickerMode:k,agentPickerQuery:O,filteredAgentOptions:Oe,scopePickerOpen:ie,scopePickerQuery:ue,filteredInitiativeOptions:U,panelLoading:C,panelError:g,scopeSaving:M,launchWarningOpen:ne,launchWarningAccepted:De,unresolvedAttachmentCount:Pe,canSend:Te,composerGuidance:He,primaryActionLabel:st,guidanceStatus:Yt,guidancePreview:_n,guidanceError:mt??null,inlineMessages:$,threadSidebarOpen:te,workspaceId:r,selectedProvider:qe,selectedProviderDef:Rt}),[y,p,v,$e,Ce,W,K,xe,ge,ae,Fe,Se,le,we,ee,Ge,J,je,ot,H,nt,k,O,Oe,ie,ue,U,C,g,M,ne,De,Pe,Te,He,st,Yt,_n,mt,$,te,r,qe,Rt]),vn=o.useMemo(()=>({setDraft:me,setComposerMode:Y,setDraftAttachments:re,selectAssignee:Zt,toggleWatcher:Xt,setSelectedInitiativeId:V,toggleAssigneePicker:Ht,toggleWatcherPicker:Jn,toggleScopePicker:pn,setAgentPickerQuery:oe,setScopePickerQuery:R,setAgentPickerMode:z,setScopePickerOpen:Me,handlePrimaryAction:an,handleFilesAdded:Rs,handleRetryAttachment:fs,openThreadPanel:Ct,closeThreadPanel:Mn,loadThreadDetail:Dt,applyScopeLink:Yn,resetComposer:gt,setComposerError:G,setComposerNotice:Ae,setLaunchWarningAccepted:et,pushInlineMessage:Wt,clearInlineMessages:Cn,toggleThreadSidebar:Qn,setSelectedProvider:_e,cycleProvider:$n,fileInputRef:tt,panelHeadingRef:Re,composerShellRef:We}),[Zt,Xt,Ht,Jn,pn,an,Rs,fs,Ct,Mn,Dt,Yn,gt,Wt,Cn,Qn,$n]);return n.jsx(gl.Provider,{value:ts,children:n.jsx(xl.Provider,{value:vn,children:e})})}const jp={type:"spring",stiffness:500,damping:35,mass:.5};function Np({messages:e,isStreaming:t,collapsed:s,onClick:r}){var l;const i=Xn(),a=o.useRef(null);o.useEffect(()=>{const d=a.current;d&&d.scrollTo({top:d.scrollHeight,behavior:"smooth"})},[e.length,(l=e[e.length-1])==null?void 0:l.body]);const c=s?e.slice(-2):e;return c.length===0?null:n.jsx(be.div,{initial:i?!1:{opacity:0,height:0},animate:i?{}:{opacity:1,height:"auto"},exit:i?{}:{opacity:0,height:0},transition:i?void 0:{duration:.25,ease:[.22,1,.36,1]},className:"overflow-hidden",children:n.jsx("div",{ref:a,onClick:r,role:r?"button":void 0,tabIndex:r?0:void 0,className:pe("max-h-[200px] space-y-1.5 overflow-y-auto px-1 pb-2 pt-1","scroll-smooth",r&&"cursor-pointer"),children:n.jsx(pt,{initial:!1,children:c.map(d=>n.jsx(be.div,{initial:i?!1:{opacity:0,y:8,scale:.97},animate:i?{}:{opacity:1,y:0,scale:1},transition:i?void 0:jp,className:pe("flex",d.role==="user"?"justify-end":"justify-start",d.role==="system"&&"justify-center"),children:d.role==="system"?n.jsx("p",{className:"text-micro italic text-muted",children:d.body}):n.jsxs("div",{className:pe("max-w-[85%] rounded-2xl px-3 py-2",d.role==="user"&&"bg-lime/[0.1]",d.role==="agent"&&"bg-white/[0.05]",d.role==="error"&&"bg-rose-400/[0.1]"),children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:pe("text-micro font-medium",d.role==="user"&&"text-[#E1FFB2]/80",d.role==="agent"&&"text-secondary",d.role==="error"&&"text-rose-200"),children:d.role==="user"?"You":d.role==="error"?"Error":"Agent"}),n.jsx("time",{className:"text-[10px] text-muted/60",dateTime:d.timestamp,children:It(d.timestamp)})]}),n.jsxs("p",{className:pe("mt-0.5 whitespace-pre-wrap text-caption leading-relaxed",d.role==="user"&&"text-primary",d.role==="agent"&&"text-primary",d.role==="error"&&"text-rose-100"),children:[d.body,t&&d===c[c.length-1]&&d.role==="agent"&&n.jsx("span",{className:"ml-0.5 inline-block h-[14px] w-[2px] translate-y-[2px] rounded-full bg-white/50",style:{animation:"pulse 1s cubic-bezier(0.4, 0, 0.6, 1) infinite"}})]})]})},d.id))})})})}function fo({open:e,onClose:t}){const s=Xn(),{displayedThreads:r,activeThreadId:i,activeThread:a,activeThreadSummary:c,panelLoading:l,panelError:d,scopeSaving:u,initiativeOptions:h}=ua(),{openThreadPanel:y,closeThreadPanel:b,loadThreadDetail:p,applyScopeLink:w,panelHeadingRef:v}=ma(),x=(a==null?void 0:a.id)??(c==null?void 0:c.id)??null,C=o.useCallback((g,S)=>{y(g,S)},[y]),j=o.useCallback(()=>{b(),t()},[b,t]);return n.jsx(pt,{children:e&&n.jsxs(n.Fragment,{children:[n.jsx(be.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:j,className:"fixed inset-0 z-[24] bg-black/30"}),n.jsxs(be.section,{initial:s?!1:{y:"100%"},animate:s?{}:{y:0},exit:s?{}:{y:"100%"},transition:s?void 0:{duration:Gt.durationEntrance/1e3,ease:Gt.easingEntrance},"aria-label":"Thread history","data-testid":"thread-drawer",className:"fixed bottom-0 left-0 right-0 z-25 flex max-h-[min(60vh,480px)] flex-col rounded-t-[22px] border-t border-white/[0.14] bg-[#0A0E16]/95 shadow-[0_-12px_40px_rgba(0,0,0,0.4)] backdrop-blur-xl",style:{paddingBottom:"max(12px, env(safe-area-inset-bottom))"},children:[n.jsx("div",{className:"flex justify-center py-2",children:n.jsx("div",{className:"h-1 w-10 rounded-full bg-white/[0.16]"})}),n.jsxs("header",{className:"flex items-center justify-between gap-2 px-4 pb-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("h3",{className:"text-body font-semibold text-primary",children:"Threads"}),n.jsx("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.04] px-2 py-0.5 text-micro text-secondary",children:r.length})]}),n.jsx("button",{type:"button",onClick:j,className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.14] bg-white/[0.03] text-secondary hover:bg-white/[0.08] hover:text-primary","aria-label":"Close thread drawer",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),n.jsxs("div",{className:pe("grid min-h-0 flex-1 overflow-hidden",i&&"lg:grid-cols-[minmax(260px,0.8fr)_minmax(0,1.2fr)]"),children:[n.jsx("div",{className:"min-h-0 overflow-y-auto px-3 pb-3",children:r.length===0?n.jsx("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-3 text-caption text-secondary",children:"No threads yet. Send a message to start one."}):n.jsx("div",{className:"space-y-1.5",children:r.map(g=>n.jsxs("button",{type:"button",onClick:S=>C(g.id,S.currentTarget),className:pe("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",i===g.id?"border-lime/35 bg-lime/[0.08]":"border-white/[0.08] bg-white/[0.02] hover:border-white/[0.16] hover:bg-white/[0.05]"),children:[n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsx("p",{className:"min-w-0 truncate text-caption font-semibold text-primary",children:g.lastSnippet?`"${g.lastSnippet.length>40?g.lastSnippet.slice(0,40)+"...":g.lastSnippet}"`:g.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:g.lastActivityAt,children:It(g.lastActivityAt)})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[g.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx("span",{className:"text-secondary",children:"@"})," ",g.assigneeName]}),n.jsx("span",{children:g.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:pe("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Ks(g.status)),children:ei(g.status)})]})]},g.id))})}),n.jsx(pt,{initial:!1,children:i&&n.jsxs(be.div,{initial:s?!1:{opacity:0,x:12},animate:s?{}:{opacity:1,x:0},exit:s?{}:{opacity:0,x:12},transition:s?void 0:{duration:Gt.durationStandard/1e3,ease:Gt.easingStandard},className:"hidden min-h-0 flex-col overflow-hidden border-l border-white/[0.08] lg:flex",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-white/[0.06] px-4 py-2",children:[n.jsx("h4",{ref:v,tabIndex:-1,className:"truncate text-caption font-semibold text-primary outline-none",children:(a==null?void 0:a.title)??(c==null?void 0:c.title)??"Thread"}),n.jsx("span",{className:pe("rounded-full border px-2 py-0.5 text-micro font-semibold",Ks((c==null?void 0:c.status)??"message_only")),children:ei((c==null?void 0:c.status)??"message_only")})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-2",children:l?n.jsxs("div",{className:"space-y-2","aria-label":"Loading thread",children:[n.jsx("div",{className:"h-10 w-[78%] animate-pulse rounded-xl border border-white/[0.08] bg-white/[0.04]"}),n.jsx("div",{className:"ml-auto h-10 w-[68%] animate-pulse rounded-xl border border-white/[0.08] bg-white/[0.04]"})]}):d?n.jsxs("div",{className:"rounded-md border border-rose-400/30 bg-rose-400/[0.12] px-2.5 py-2 text-caption text-rose-100",children:[n.jsx("p",{children:d}),x&&n.jsx("button",{type:"button",onClick:()=>void p(x),className:"mt-1.5 inline-flex min-h-[28px] items-center rounded-full border border-rose-200/30 bg-rose-400/[0.12] px-2 text-micro text-rose-100 hover:bg-rose-400/[0.2]",children:"Retry"})]}):a&&a.messages.length>0?n.jsx("div",{className:"space-y-2",children:a.messages.map(g=>n.jsx("article",{className:pe("flex",g.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:pe("max-w-[90%] rounded-xl border px-2.5 py-1.5",g.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":g.role==="agent"?"border-teal/25 bg-teal/[0.1] text-primary":"border-lime/25 bg-lime/[0.1] text-primary"),children:[n.jsxs("div",{className:"mb-0.5 flex items-center justify-between gap-2 text-micro text-muted",children:[n.jsx("span",{children:g.senderName??fl(g.role)}),n.jsx("time",{dateTime:g.createdAt,children:It(g.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:g.body})]})},g.id))}):n.jsx("p",{className:"text-caption text-secondary",children:"No messages yet."})}),a&&a.launches.length>0&&n.jsxs("div",{className:"border-t border-white/[0.06] px-4 py-2",children:[n.jsxs("p",{className:"text-micro font-semibold text-muted",children:[a.launches.length," launch",a.launches.length===1?"":"es"]}),a.launches.slice(0,2).map(g=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:pe("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Ks(hl(g.status))),children:g.status}),n.jsx("span",{children:g.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:g.requestedAt,children:It(g.requestedAt)})]},g.id))]})]})})]})]})]})})}function ho(){const e=Xn(),{displayedThreads:t,activeThreadId:s,activeThread:r,activeThreadSummary:i,panelLoading:a,panelError:c,scopeSaving:l,initiativeOptions:d,threadSidebarOpen:u}=ua(),{openThreadPanel:h,closeThreadPanel:y,loadThreadDetail:b,applyScopeLink:p,setComposerMode:w,toggleThreadSidebar:v,panelHeadingRef:x}=ma(),C=(r==null?void 0:r.id)??(i==null?void 0:i.id)??null,j=o.useCallback(()=>{v()},[v]);return u?n.jsx(pt,{children:u&&n.jsxs(n.Fragment,{children:[n.jsx(be.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:j,className:"fixed inset-0 z-[24] bg-black/30"},"sidebar-backdrop"),n.jsxs(be.section,{initial:e?!1:{x:"-100%"},animate:e?{}:{x:0},exit:e?{}:{x:"-100%"},transition:e?void 0:{duration:Gt.durationEntrance/1e3,ease:Gt.easingEntrance},"aria-label":"Thread sidebar","data-testid":"thread-sidebar",className:"fixed inset-y-0 left-0 z-25 flex w-[380px] max-w-[85vw] flex-col border-r border-white/[0.14] bg-[#0A0E16]/95 shadow-[12px_0_40px_rgba(0,0,0,0.4)] backdrop-blur-xl",children:[n.jsxs("header",{className:"flex items-center justify-between gap-2 border-b border-white/[0.08] px-4 py-3",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("h3",{className:"text-body font-semibold text-primary",children:"Threads"}),n.jsx("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.04] px-2 py-0.5 text-micro text-secondary",children:t.length})]}),n.jsx("button",{type:"button",onClick:j,className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.14] bg-white/[0.03] text-secondary hover:bg-white/[0.08] hover:text-primary","aria-label":"Close thread sidebar",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-3 py-3",children:t.length===0?n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-3 text-caption text-secondary",children:[n.jsx("p",{className:"text-primary",children:"No threads yet."}),n.jsx("p",{className:"mt-0.5",children:"Send a message to start one."}),n.jsx(be.button,{type:"button",whileHover:e?void 0:{y:-1},whileTap:e?void 0:po,transition:mo,onClick:()=>{j(),w("focused"),requestAnimationFrame(()=>{const g=document.getElementById("chat-dock-input");g instanceof HTMLTextAreaElement&&g.focus()})},className:"mt-2 inline-flex min-h-[34px] items-center rounded-full border border-lime/30 bg-lime/[0.12] px-2.5 text-micro font-semibold text-[#E1FFB2] hover:bg-lime/[0.18]",children:"Start thread"})]}):n.jsx("div",{className:"space-y-1.5",children:t.map((g,S)=>n.jsxs(be.button,{type:"button",initial:e?!1:{opacity:0,x:-8},animate:e?{}:{opacity:1,x:0},transition:{...e?{}:mo,delay:e?0:Math.min(S*.02,.16)},whileHover:e?void 0:{x:2},whileTap:e?void 0:po,onClick:W=>void h(g.id,W.currentTarget),className:pe("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",s===g.id?"border-lime/35 bg-lime/[0.08]":"border-white/[0.08] bg-white/[0.02] hover:border-white/[0.16] hover:bg-white/[0.05]"),children:[n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsx("p",{className:"min-w-0 truncate text-caption font-semibold text-primary",children:g.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:g.lastActivityAt,children:It(g.lastActivityAt)})]}),n.jsx("p",{className:"mt-0.5 line-clamp-1 text-micro text-secondary",children:g.lastSnippet??g.summary??"No message yet."}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[g.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(Ot,{name:g.assigneeName,hint:g.assigneeName,size:"xs"}),n.jsx("span",{children:g.assigneeName})]}),n.jsx("span",{children:g.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:pe("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Ks(g.status)),children:ei(g.status)})]})]},g.id))})}),n.jsx(pt,{initial:!1,children:s&&n.jsxs(be.div,{initial:e?!1:{opacity:0,y:12},animate:e?{}:{opacity:1,y:0},exit:e?{}:{opacity:0,y:12},transition:e?void 0:{duration:Gt.durationStandard/1e3,ease:Gt.easingStandard},className:"flex min-h-0 max-h-[50%] flex-col border-t border-white/[0.08]",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-white/[0.06] px-4 py-2",children:[n.jsx("h4",{ref:x,tabIndex:-1,className:"truncate text-caption font-semibold text-primary outline-none",children:(r==null?void 0:r.title)??(i==null?void 0:i.title)??"Thread"}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:pe("rounded-full border px-2 py-0.5 text-micro font-semibold",Ks((i==null?void 0:i.status)??"message_only")),children:ei((i==null?void 0:i.status)??"message_only")}),n.jsx("button",{type:"button",onClick:y,className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-white/[0.14] bg-white/[0.03] text-micro text-secondary hover:bg-white/[0.08] hover:text-primary","aria-label":"Close thread detail",children:"×"})]})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-2",children:a?n.jsxs("div",{className:"space-y-2","aria-label":"Loading thread",children:[n.jsx("div",{className:"h-10 w-[78%] animate-pulse rounded-xl border border-white/[0.08] bg-white/[0.04]"}),n.jsx("div",{className:"ml-auto h-10 w-[68%] animate-pulse rounded-xl border border-white/[0.08] bg-white/[0.04]"})]}):c?n.jsxs("div",{className:"rounded-md border border-rose-400/30 bg-rose-400/[0.12] px-2.5 py-2 text-caption text-rose-100",children:[n.jsx("p",{children:c}),C&&n.jsx("button",{type:"button",onClick:()=>void b(C),className:"mt-1.5 inline-flex min-h-[28px] items-center rounded-full border border-rose-200/30 bg-rose-400/[0.12] px-2 text-micro text-rose-100 hover:bg-rose-400/[0.2]",children:"Retry"})]}):r&&r.messages.length>0?n.jsx("div",{className:"space-y-2",children:r.messages.map(g=>n.jsx("article",{className:pe("flex",g.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:pe("max-w-[90%] rounded-xl border px-2.5 py-1.5",g.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":g.role==="agent"?"border-teal/25 bg-teal/[0.1] text-primary":"border-lime/25 bg-lime/[0.1] text-primary"),children:[n.jsxs("div",{className:"mb-0.5 flex items-center justify-between gap-2 text-micro text-muted",children:[n.jsx("span",{children:g.senderName??fl(g.role)}),n.jsx("time",{dateTime:g.createdAt,children:It(g.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:g.body})]})},g.id))}):n.jsx("p",{className:"text-caption text-secondary",children:"No messages yet."})}),r&&r.launches.length>0&&n.jsxs("div",{className:"border-t border-white/[0.06] px-4 py-2",children:[n.jsxs("p",{className:"text-micro font-semibold text-muted",children:[r.launches.length," launch",r.launches.length===1?"":"es"]}),r.launches.slice(0,2).map(g=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:pe("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Ks(hl(g.status))),children:g.status}),n.jsx("span",{children:g.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:g.requestedAt,children:It(g.requestedAt)})]},g.id))]})]})})]},"sidebar-panel")]})}):null}const Ip={type:"spring",stiffness:500,damping:30,mass:.5};function Ap({open:e,agents:t,query:s,activeIndex:r,onSelect:i}){const a=Xn(),c=o.useRef(null);o.useEffect(()=>{if(!e||!c.current)return;const u=c.current.querySelector('[data-active="true"]');u&&u.scrollIntoView({block:"nearest"})},[r,e]);const l=s.length>0?t.filter(u=>{const h=s.toLowerCase();return u.name.toLowerCase().includes(h)||u.handle.toLowerCase().includes(h)||u.domain.toLowerCase().includes(h)||u.role.toLowerCase().includes(h)}):t;if(!e||l.length===0)return null;const d=l.slice(0,6);return n.jsx(pt,{children:n.jsx(be.div,{initial:a?!1:{opacity:0,y:8,scale:.96},animate:a?{}:{opacity:1,y:0,scale:1},exit:a?{}:{opacity:0,y:8,scale:.96},transition:a?void 0:Ip,className:pe("absolute bottom-[calc(100%+6px)] left-0 z-30 w-[280px]","rounded-2xl border border-white/[0.1] bg-[#0D1117]/98 p-1","shadow-[0_16px_48px_rgba(0,0,0,0.5),0_0_0_1px_rgba(255,255,255,0.04)] backdrop-blur-2xl"),role:"listbox","aria-label":"Agent suggestions",children:n.jsx("div",{ref:c,className:"space-y-px",children:d.map((u,h)=>{const y=h===r;return n.jsxs("button",{type:"button",role:"option","aria-selected":y,"data-active":y,onClick:()=>i(u),onMouseDown:b=>b.preventDefault(),className:pe("flex w-full items-center gap-2.5 rounded-xl px-2.5 py-2 text-left","transition-colors duration-[60ms]",y?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:[n.jsx(Ot,{name:u.name,hint:u.name,size:"xs"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"truncate text-caption font-medium",children:u.name}),u.status==="running"&&n.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rounded-full bg-lime","aria-label":"Running"})]}),n.jsx("span",{className:"text-micro text-muted",children:u.domainLabel})]})]},u.id)})})})})}const Sp={type:"spring",stiffness:500,damping:30,mass:.5};function _p({open:e,initiatives:t,query:s,activeIndex:r,onSelect:i}){const a=Xn(),c=o.useRef(null);o.useEffect(()=>{if(!e||!c.current)return;const u=c.current.querySelector('[data-active="true"]');u&&u.scrollIntoView({block:"nearest"})},[r,e]);const l=s.length>0?t.filter(u=>u.name.toLowerCase().includes(s.toLowerCase())):t;if(!e)return null;const d=l.slice(0,6);return n.jsx(pt,{children:n.jsx(be.div,{initial:a?!1:{opacity:0,y:8,scale:.96},animate:a?{}:{opacity:1,y:0,scale:1},exit:a?{}:{opacity:0,y:8,scale:.96},transition:a?void 0:Sp,className:pe("absolute bottom-[calc(100%+6px)] left-0 z-30 w-[280px]","rounded-2xl border border-white/[0.1] bg-[#0D1117]/98 p-1","shadow-[0_16px_48px_rgba(0,0,0,0.5),0_0_0_1px_rgba(255,255,255,0.04)] backdrop-blur-2xl"),role:"listbox","aria-label":"Initiative scope suggestions",children:n.jsxs("div",{ref:c,className:"space-y-px",children:[n.jsx("button",{type:"button",role:"option","aria-selected":r===0,"data-active":r===0,onClick:()=>i(null),onMouseDown:u=>u.preventDefault(),className:pe("flex w-full items-center gap-2 rounded-xl px-2.5 py-2 text-left text-caption","transition-colors duration-[60ms]",r===0?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:"Unscoped"}),d.map((u,h)=>{const y=h+1===r;return n.jsx("button",{type:"button",role:"option","aria-selected":y,"data-active":y,onClick:()=>i(u),onMouseDown:b=>b.preventDefault(),className:pe("flex w-full items-center gap-2 rounded-xl px-2.5 py-2 text-left text-caption","transition-colors duration-[60ms]",y?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:n.jsx("span",{className:"truncate",children:u.name})},u.id)})]})})})}function Cp({open:e,mode:t,agents:s,quickAgents:r,query:i,selectedAssigneeId:a,selectedWatcherIds:c,onQueryChange:l,onSelectAssignee:d,onToggleWatcher:u,onClose:h,onSwitchMode:y,anchorRef:b}){const p=Xn();return n.jsx(pt,{children:e&&n.jsxs(be.div,{initial:p?!1:{opacity:0,scale:.95,y:8},animate:p?{}:{opacity:1,scale:1,y:0},exit:p?{}:{opacity:0,scale:.95,y:8},transition:p?void 0:Gt.easingBounce,className:"absolute bottom-[calc(100%+8px)] left-0 z-30 w-[320px] rounded-xl border border-white/[0.14] bg-[#0A0E16]/98 p-2.5 shadow-[0_20px_44px_rgba(0,0,0,0.45)] backdrop-blur-xl",children:[n.jsx("div",{className:"absolute -bottom-[6px] left-4 h-0 w-0 border-l-[6px] border-r-[6px] border-t-[6px] border-l-transparent border-r-transparent border-t-white/[0.14]","aria-hidden":!0}),n.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[n.jsxs("div",{className:"flex gap-1",children:[n.jsx("button",{type:"button",onClick:()=>y("assignee"),className:pe("rounded-full px-2 py-0.5 text-micro",t==="assignee"?"bg-white/[0.1] text-primary":"text-secondary hover:text-primary"),children:"Assignee"}),n.jsx("button",{type:"button",onClick:()=>y("watcher"),className:pe("rounded-full px-2 py-0.5 text-micro",t==="watcher"?"bg-white/[0.1] text-primary":"text-secondary hover:text-primary"),children:"Watchers"})]}),n.jsx("button",{type:"button",onClick:h,className:"h-7 rounded-full border border-white/[0.12] bg-white/[0.03] px-2 text-micro text-secondary hover:bg-white/[0.08] hover:text-primary",children:"Close"})]}),r.length>0&&t==="assignee"&&n.jsx("div",{className:"mb-2 flex items-center gap-1.5 overflow-x-auto border-b border-white/[0.06] pb-2 scrollbar-none",children:r.map(w=>{const v=a===w.id;return n.jsx("button",{type:"button",onClick:()=>d(w.id),title:w.name,className:pe("flex-shrink-0 rounded-full p-0.5 transition-all duration-[120ms]",v?"ring-2 ring-lime/60 ring-offset-1 ring-offset-[#0A0E16]":"ring-1 ring-white/[0.12] hover:ring-white/[0.24]"),"aria-pressed":v,"aria-label":`Select ${w.name} as assignee`,children:n.jsx(Ot,{name:w.name,hint:w.name,size:"xs"})},w.id)})}),n.jsx("input",{value:i,onChange:w=>l(w.target.value),placeholder:"Search agents...",className:"mb-2 h-9 w-full rounded-lg border border-white/[0.12] bg-black/35 px-2.5 text-caption text-primary outline-none focus:border-lime/35",autoFocus:!0}),n.jsx("div",{className:"max-h-[240px] space-y-1 overflow-y-auto",children:s.map(w=>{const v=a===w.id,x=c.includes(w.id);return n.jsxs("button",{type:"button",onClick:()=>{if(t==="assignee"){d(w.id);return}v||u(w.id)},className:pe("flex min-h-[38px] w-full items-center justify-between rounded-lg border px-2 py-1.5 text-left text-caption",v?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":x?"border-teal/30 bg-teal/[0.12] text-teal-100":"border-white/[0.1] bg-white/[0.02] text-secondary hover:bg-white/[0.08] hover:text-primary"),children:[n.jsxs("span",{className:"inline-flex items-center gap-2",children:[n.jsx(Ot,{name:w.name,hint:w.name,size:"xs"}),n.jsx("span",{children:w.name})]}),n.jsx("span",{className:"text-micro",children:v?"Assignee":x?"Watcher":"Select"})]},w.id)})})]})})}const go=24,xo=200;function yo(e){return e?e.startsWith("application/pdf")?"#EF4444":e.startsWith("image/")?"#A78BFA":e.includes("spreadsheet")||e.includes("csv")?"#22C55E":e.includes("presentation")?"#F97316":"#8F9AB7":"#8F9AB7"}function Mp(e,t){var r;if(e!=null&&e.startsWith("application/pdf"))return"PDF";if(e!=null&&e.startsWith("image/"))return"Image";if(e!=null&&e.includes("spreadsheet")||e!=null&&e.includes("csv"))return"Sheet";if(e!=null&&e.includes("presentation"))return"Slides";const s=(r=t.split(".").pop())==null?void 0:r.toUpperCase();return s&&s.length<=5?s:"File"}function bo({icon:e,className:t}){return e==="anthropic"?n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",className:t,children:n.jsx("path",{d:"M16.5 2.3L12 21.7l-1.7-6.5L3.8 13l6.5-1.7L12 4.8l1.7 6.5 6.5 1.7-6.5 1.7L12 21.7"})}):e==="openai"?n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M12 2a7 7 0 0 1 7 7c0 2.38-1.19 4.47-3 5.74V17a2 2 0 0 1-2 2h-4a2 2 0 0 1-2-2v-2.26C6.19 13.47 5 11.38 5 9a7 7 0 0 1 7-7z"}),n.jsx("line",{x1:"10",y1:"21",x2:"14",y2:"21"})]}):n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M12 2l2.4 7.2L22 12l-7.6 2.8L12 22l-2.4-7.2L2 12l7.6-2.8z"})})}const ea="orgx-chat-dock-collapsed";function Tp(){try{return localStorage.getItem(ea)==="1"}catch{return!1}}function Ep(){const e=ua(),t=ma(),s=Xn(),r=o.useRef(null),i=o.useRef(null),[a,c]=o.useState(Tp),l=o.useCallback(()=>{c(H=>{const Oe=!H;try{localStorage.setItem(ea,Oe?"1":"0")}catch{}return Oe})},[]),[d,u]=o.useState(!1),[h,y]=o.useState(!1),b=o.useRef(null),[p,w]=o.useState(!1),[v,x]=o.useState(""),[C,j]=o.useState(0),[g,S]=o.useState(-1),[W,Y]=o.useState(!1),[K,me]=o.useState(""),[ge,Z]=o.useState(0),[ae,ke]=o.useState(-1),{composerMode:Fe,draft:G,draftAttachments:Se,sending:Ae,launching:xe,selectedAssigneeId:re,selectedAssignee:le,selectedWatcherIds:Ee,selectedInitiative:ee,agentOptions:q,quickAssigneeOptions:J,agentPickerMode:V,agentPickerQuery:k,filteredAgentOptions:z,initiativeOptions:O,canSend:oe,activeThreadId:ie,guidanceStatus:Me,inlineMessages:ue,displayedThreads:R,launchWarningOpen:$,launchWarningAccepted:X,selectedProvider:te,selectedProviderDef:Le}=e,qe=G.trim(),_e=ue.length>0;qe.length>0;const M=o.useCallback(()=>{const H=r.current;if(!H)return;H.style.height="0";const Oe=Math.min(Math.max(H.scrollHeight,go),xo);H.style.height=`${Oe}px`},[]);o.useLayoutEffect(()=>{M()},[G,M]);const B=o.useMemo(()=>{if(!p)return q;const H=v.toLowerCase();return H?q.filter(Oe=>Oe.name.toLowerCase().includes(H)||Oe.handle.toLowerCase().includes(H)||Oe.domain.toLowerCase().includes(H)||Oe.role.toLowerCase().includes(H)):q},[q,p,v]),ne=o.useMemo(()=>{if(!W)return O;const H=K.toLowerCase();return H?O.filter(Oe=>Oe.name.toLowerCase().includes(H)):O},[O,W,K]);o.useEffect(()=>{if(b.current&&clearTimeout(b.current),ue.length<=2){y(!1);return}return y(!1),b.current=window.setTimeout(()=>{y(!0)},5e3),()=>{b.current&&clearTimeout(b.current)}},[ue.length]),o.useEffect(()=>{const H=Oe=>{if((Oe.metaKey||Oe.ctrlKey)&&Oe.key==="k"){if(Oe.preventDefault(),a){c(!1);try{localStorage.setItem(ea,"0")}catch{}}t.setComposerMode("focused"),requestAnimationFrame(()=>{var U;return(U=r.current)==null?void 0:U.focus()})}};return window.addEventListener("keydown",H),()=>window.removeEventListener("keydown",H)},[t,a]);const fe=o.useCallback(()=>{Fe==="resting"&&t.setComposerMode("focused")},[Fe,t]),De=o.useCallback(()=>{window.setTimeout(()=>{qe.length===0&&!_e&&!p&&!W&&Se.length===0&&t.composerShellRef.current&&!t.composerShellRef.current.contains(document.activeElement)&&(t.setComposerMode("resting"),t.setAgentPickerMode(null),w(!1),Y(!1))},100)},[qe,_e,p,W,Se.length,t]),et=o.useCallback(H=>{const Oe=H.target.value,U=H.target.selectionStart??Oe.length;t.setDraft(Oe),(Fe==="resting"||Fe==="focused")&&t.setComposerMode("composing");const se=Oe.slice(0,U),Ce=se.match(/@(\w*)$/);if(Ce){w(!0),x(Ce[1]),j(0),S(U-Ce[0].length),Y(!1);return}const $e=se.match(/#(\w*)$/);if($e){Y(!0),me($e[1]),Z(0),ke(U-$e[0].length),w(!1);return}p&&w(!1),W&&Y(!1)},[Fe,t,p,W]),tt=o.useCallback(H=>{var Ce;const Oe=G.slice(0,g),U=G.slice(((Ce=r.current)==null?void 0:Ce.selectionStart)??G.length),se=`${Oe}@${H.name} ${U}`;t.setDraft(se),t.selectAssignee(H.id),w(!1),x(""),requestAnimationFrame(()=>{if(r.current){const $e=Oe.length+H.name.length+2;r.current.setSelectionRange($e,$e),r.current.focus()}})},[G,g,t]),Re=o.useCallback(H=>{var se;const Oe=G.slice(0,ae),U=G.slice(((se=r.current)==null?void 0:se.selectionStart)??G.length);if(H){const Ce=`${Oe}#${H.name} ${U}`;t.setDraft(Ce),t.setSelectedInitiativeId(H.id),requestAnimationFrame(()=>{if(r.current){const $e=Oe.length+H.name.length+2;r.current.setSelectionRange($e,$e),r.current.focus()}})}else{const Ce=`${Oe}${U}`;t.setDraft(Ce),t.setSelectedInitiativeId(""),requestAnimationFrame(()=>{r.current&&(r.current.setSelectionRange(Oe.length,Oe.length),r.current.focus())})}Y(!1),me("")},[G,ae,t]),Je=o.useCallback(H=>{if(p&&B.length>0){if(H.key==="ArrowDown"){H.preventDefault(),j(Oe=>(Oe+1)%B.length);return}if(H.key==="ArrowUp"){H.preventDefault(),j(Oe=>(Oe-1+B.length)%B.length);return}if(H.key==="Enter"||H.key==="Tab"){H.preventDefault(),tt(B[C]);return}if(H.key==="Escape"){H.preventDefault(),w(!1);return}}if(W){const Oe=ne.length+1;if(H.key==="ArrowDown"){H.preventDefault(),Z(U=>(U+1)%Oe);return}if(H.key==="ArrowUp"){H.preventDefault(),Z(U=>(U-1+Oe)%Oe);return}if(H.key==="Enter"||H.key==="Tab"){H.preventDefault(),Re(ge===0?null:ne[ge-1]);return}if(H.key==="Escape"){H.preventDefault(),Y(!1);return}}if(H.key==="Enter"&&!H.shiftKey){H.preventDefault(),t.handlePrimaryAction();return}H.key==="Escape"&&(H.preventDefault(),V?t.setAgentPickerMode(null):_e?t.clearInlineMessages():(t.setComposerMode("resting"),H.target.blur()))},[t,V,_e,p,B,C,tt,W,ne,ge,Re]),We=o.useCallback(()=>{t.toggleThreadSidebar()},[t]),ft=Ae||xe?n.jsx("svg",{className:"h-4 w-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:n.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2.5",strokeDasharray:"52",strokeDashoffset:"16",strokeLinecap:"round"})}):n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"5"}),n.jsx("polyline",{points:"5 12 12 5 19 12"})]}),ot=(Fe==="reviewing"||_e)&&ue.length>0,nt=Me==="submitted"||Me==="streaming",we=o.useRef(ue.length),[Ge,je]=o.useState(0);return o.useEffect(()=>{if(!a){we.current=ue.length,je(0);return}const H=ue.length-we.current;H>0&&je(H)},[a,ue.length]),a?n.jsxs(n.Fragment,{children:[n.jsx(fo,{open:d,onClose:()=>u(!1)}),n.jsx(ho,{}),n.jsx("div",{className:"sticky bottom-0 z-20 flex justify-end px-4 pb-4 pt-2",style:{paddingBottom:"max(16px, env(safe-area-inset-bottom))"},children:n.jsxs(be.button,{type:"button",onClick:()=>{l(),requestAnimationFrame(()=>{var H;return(H=r.current)==null?void 0:H.focus()})},initial:s?!1:{scale:.8,opacity:0},animate:s?{}:{scale:1,opacity:1},whileHover:s?void 0:{scale:1.08},whileTap:s?void 0:{scale:.92},transition:{type:"spring",stiffness:500,damping:28},className:pe("relative inline-flex h-12 w-12 items-center justify-center rounded-full","border border-white/[0.14] bg-[#0A0E16]/90 text-primary backdrop-blur-xl","shadow-[0_8px_32px_rgba(0,0,0,0.4),inset_0_1px_0_rgba(255,255,255,0.05)]","hover:border-white/[0.22] hover:bg-[#0A0E16]"),"aria-label":"Open chat",children:[n.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),n.jsx(pt,{children:Ge>0&&n.jsx(be.span,{initial:{scale:0},animate:{scale:1},exit:{scale:0},transition:{type:"spring",stiffness:500,damping:20},className:pe("absolute -right-1 -top-1 flex h-5 min-w-[20px] items-center justify-center rounded-full","bg-lime px-1 text-[10px] font-bold text-[#0A0E16]"),children:Ge>9?"9+":Ge},"unread")}),ie&&Ge===0&&n.jsx("span",{className:"absolute -right-0.5 -top-0.5 h-2.5 w-2.5 rounded-full border-2 border-[#0A0E16] bg-lime"})]})})]}):n.jsxs(n.Fragment,{children:[n.jsx(fo,{open:d,onClose:()=>u(!1)}),n.jsx(ho,{}),n.jsxs("div",{ref:H=>{t.composerShellRef.current=H},className:"sticky bottom-0 z-20 px-4 pb-4 pt-2",style:{paddingBottom:"max(16px, env(safe-area-inset-bottom))"},children:[n.jsx(pt,{children:$&&n.jsxs(be.div,{initial:s?!1:{opacity:0,y:4},animate:s?{}:{opacity:1,y:0},exit:s?{}:{opacity:0},transition:{duration:.15},className:"mb-2 rounded-lg border border-amber-300/35 bg-amber-300/[0.12] px-2.5 py-2 text-caption text-amber-100",children:[n.jsx("p",{children:"Launch includes non-ready attachments. Continue anyway?"}),n.jsxs("label",{className:"mt-1.5 flex items-center gap-2",children:[n.jsx("input",{type:"checkbox",checked:X,onChange:H=>t.setLaunchWarningAccepted(H.target.checked)}),n.jsx("span",{children:"I understand unresolved attachment extraction may reduce context quality."})]})]},"launch-warning")}),n.jsx("div",{className:"relative",children:n.jsx(Cp,{open:V!==null,mode:V??"assignee",agents:z,quickAgents:J,query:k,selectedAssigneeId:re,selectedWatcherIds:Ee,onQueryChange:t.setAgentPickerQuery,onSelectAssignee:t.selectAssignee,onToggleWatcher:t.toggleWatcher,onClose:()=>t.setAgentPickerMode(null),onSwitchMode:t.setAgentPickerMode,anchorRef:i})}),n.jsxs(be.section,{"data-testid":"chat-dock","data-state":Fe,initial:s?!1:{opacity:0,y:20},animate:s?{}:{opacity:1,y:0},transition:s?void 0:{duration:Gt.durationEntrance/1e3,ease:Gt.easingEntrance},className:pe("group/dock relative rounded-[22px] border border-white/[0.12] bg-[#0A0E16]/80 px-3 py-2.5 backdrop-blur-xl","shadow-[inset_0_1px_0_rgba(255,255,255,0.035),0_14px_34px_rgba(0,0,0,0.36)]","transition-[border-color] duration-200",Fe!=="resting"&&"border-white/[0.16]"),children:[n.jsx("button",{type:"button",onClick:l,className:pe("absolute -right-1 -top-1 z-10 flex h-6 w-6 items-center justify-center rounded-full","border border-white/[0.14] bg-[#0A0E16] text-secondary","opacity-0 transition-opacity duration-200","hover:bg-white/[0.08] hover:text-primary","group-hover/dock:opacity-100"),"aria-label":"Minimize chat",title:"Minimize to icon",children:n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"6 9 12 15 18 9"})})}),n.jsx("input",{ref:H=>{t.fileInputRef.current=H},type:"file",multiple:!0,className:"hidden",onChange:H=>{t.handleFilesAdded(H.target.files),H.currentTarget.value=""}}),n.jsx(pt,{children:ot&&n.jsx(Np,{messages:ue,isStreaming:nt,collapsed:h,onClick:We})}),n.jsxs("div",{className:"relative",children:[n.jsx(Ap,{open:p,agents:B,query:v,activeIndex:C,anchorRect:null,onSelect:tt,onClose:()=>w(!1)}),n.jsx(_p,{open:W,initiatives:ne,query:K,activeIndex:ge,onSelect:Re,onClose:()=>Y(!1)})]}),n.jsx(pt,{initial:!1,children:Se.length>0&&n.jsx(be.div,{initial:s?!1:{opacity:0,height:0},animate:s?{}:{opacity:1,height:"auto"},exit:s?{}:{opacity:0,height:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"mb-2 overflow-hidden",children:n.jsx("div",{className:"flex flex-wrap items-start gap-2","aria-live":"polite",children:Se.map(H=>n.jsxs("div",{className:pe("group relative flex items-center gap-2.5 rounded-xl border px-3 py-2","transition-colors duration-150",H.status==="failed"?"border-rose-400/30 bg-rose-400/[0.08]":"border-white/[0.1] bg-white/[0.04]"),children:[n.jsx("div",{className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:`${yo(H.mimeType)}20`},children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:yo(H.mimeType),strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n.jsx("polyline",{points:"14 2 14 8 20 8"})]})}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"max-w-[180px] truncate text-caption font-medium text-primary",children:H.name}),n.jsxs("p",{className:"text-micro text-muted",children:[Mp(H.mimeType,H.name),H.sizeBytes?` · ${pp(H.sizeBytes)}`:""]})]}),n.jsx("button",{type:"button",onClick:()=>t.setDraftAttachments(Oe=>Oe.filter(U=>U.id!==H.id)),className:pe("absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full","border border-white/[0.16] bg-[#0A0E16] text-[10px] text-secondary","opacity-0 transition-opacity duration-150 group-hover:opacity-100","hover:bg-white/[0.1] hover:text-primary"),"aria-label":`Remove ${H.name}`,children:"×"}),H.status!=="ready"&&H.status!=="failed"&&n.jsx("div",{className:"absolute bottom-0.5 left-3 right-3 h-0.5 overflow-hidden rounded-full bg-white/[0.06]",children:n.jsx("div",{className:"h-full w-1/2 animate-pulse rounded-full bg-white/[0.2]"})}),H.status==="failed"&&n.jsx("button",{type:"button",onClick:()=>t.handleRetryAttachment(H.id),className:"ml-1 rounded-md border border-rose-300/20 bg-rose-400/[0.12] px-1.5 py-0.5 text-micro text-rose-200 hover:bg-rose-400/[0.2]",children:"Retry"})]},H.id))})})}),n.jsxs("div",{className:"flex items-end gap-2",children:[n.jsx("button",{type:"button",onClick:()=>{var H;return(H=t.fileInputRef.current)==null?void 0:H.click()},className:pe("mb-0.5 inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full","border border-white/[0.12] bg-transparent text-secondary","transition-colors duration-150","hover:bg-white/[0.06] hover:text-primary"),"aria-label":"Add files and more",children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),n.jsxs(be.button,{type:"button",onClick:t.cycleProvider,whileTap:s?void 0:{scale:.93},transition:{duration:.1},className:pe("mb-0.5 inline-flex h-7 flex-shrink-0 items-center gap-1.5 rounded-full px-2","border text-micro font-medium","transition-all duration-200",te==="anthropic"?"border-[#F5B700]/30 bg-[#F5B700]/[0.08] text-[#F5B700]":te==="openai"?"border-emerald-400/30 bg-emerald-400/[0.08] text-emerald-300":"border-white/[0.12] bg-white/[0.04] text-muted"),title:`Provider: ${Le.label}. Click to switch.`,"aria-label":`Current provider: ${Le.label}. Click to cycle.`,children:[n.jsx(bo,{icon:Le.icon}),n.jsx("span",{children:Le.shortLabel})]}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("label",{htmlFor:"chat-dock-input",className:"sr-only",children:"Chat composer"}),n.jsx("textarea",{ref:r,id:"chat-dock-input",value:G,onFocus:fe,onBlur:De,onChange:et,onKeyDown:Je,placeholder:"Ask anything",rows:1,className:pe("w-full resize-none border-none bg-transparent py-1 text-[13px] leading-[22px] text-primary","placeholder:text-muted/60 focus:outline-none"),style:{minHeight:go,maxHeight:xo,overflowY:"auto"},"aria-expanded":Fe!=="resting"})]}),R.length>0&&n.jsxs("button",{type:"button",onClick:()=>{window.innerWidth>=768?t.toggleThreadSidebar():u(!0)},className:pe("mb-0.5 inline-flex h-7 min-w-[28px] flex-shrink-0 items-center justify-center gap-1 rounded-full px-1.5","text-micro text-muted transition-colors duration-150","hover:bg-white/[0.06] hover:text-secondary"),"aria-label":`${R.length} thread${R.length===1?"":"s"}`,children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),R.length]}),n.jsx(be.button,{type:"button",onClick:()=>void t.handlePrimaryAction(),disabled:!oe,"data-action":"chat-send-primary",whileTap:s?void 0:{scale:.92},transition:{duration:.1},className:pe("mb-0.5 inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full","transition-all duration-200",oe?"bg-lime text-[#0A0E16] shadow-[0_0_12px_rgba(191,255,0,0.25)]":"bg-white/[0.08] text-muted"),title:le?`Send to ${le.name} via ${Le.shortLabel}`:`Send via ${Le.shortLabel}`,"aria-label":le?`Send to ${le.name} via ${Le.shortLabel}`:`Send message via ${Le.shortLabel}`,children:ft})]}),n.jsx(pt,{children:(le||ee)&&Fe!=="resting"&&n.jsxs(be.div,{initial:s?!1:{opacity:0},animate:s?{}:{opacity:1},exit:s?{}:{opacity:0},transition:{duration:.15},className:"mt-1.5 flex items-center gap-2 px-10",children:[le&&n.jsxs("button",{ref:H=>{i.current=H},type:"button",onClick:t.toggleWatcherPicker,className:pe("inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-micro","text-[#E1FFB2]/80 transition-colors duration-150 hover:bg-lime/[0.08]"),children:[n.jsx(Ot,{name:le.name,hint:le.name,size:"xs"}),n.jsxs("span",{className:"max-w-[100px] truncate",children:["@",le.name]}),le.status==="running"&&n.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rounded-full bg-lime"})]}),ee&&n.jsxs("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-micro text-cyan-100/70",children:["#",ee.name]}),te!=="auto"&&n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-micro",style:{color:Le.accent},children:[n.jsx(bo,{icon:Le.icon}),Le.shortLabel]})]})})]})]})]})}const Ti=50,Rp=50,dr=20,wo=3600,vo=12e3,Dp=140,Lp=3e3,Dr={all:"All",completed:"Completed",needs_attention:"Needs attention",in_progress:"In progress"};function Fp(e){return e==="codex"?"codex":e==="openai"?"openai":e==="anthropic"?"anthropic":e==="openclaw"?"openclaw":e==="orgx"?"orgx":"unknown"}function ko(e){return e==="codex"||e==="openai"||e==="anthropic"||e==="openclaw"}function ls(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Lr(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?new Date(t):null}function Fr(e){return e?e.toLocaleString([],{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}):"—"}function Ei(e){return e?new Date(e.getTime()-e.getTimezoneOffset()*6e4).toISOString().slice(0,16):""}function jo(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?new Date(t):null}function Ts(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function pa(e){if(!e)return;let t={...e},s=Ts(t.metadata),r=0;for(;s&&r<4;)t={...t,...s},s=Ts(s.metadata),r+=1;return t}function At(e){const t=Ts(e==null?void 0:e.metadata);return pa(t)}function $p(e){const t=pa(e);if(!t)return"";const s=[];for(const[r,i]of Object.entries(t))typeof i=="string"&&(r.toLowerCase().includes("type")||r.toLowerCase().includes("kind")||r.toLowerCase().includes("summary")||r.toLowerCase().includes("message")||r.toLowerCase().includes("artifact")||r.toLowerCase().includes("decision")||r.toLowerCase().includes("run")||r.toLowerCase().includes("title")||r.toLowerCase().includes("task")||r.toLowerCase().includes("workstream")||r.toLowerCase().includes("milestone"))&&s.push(i);return s.join(" ")}function ta(e){if(e.runId)return e.runId;const t=At(e);if(!t)return null;const s=["runId","run_id","sliceRunId","slice_run_id","sessionId","session_id","agentRunId"];for(const r of s){const i=t[r];if(typeof i=="string"&&i.trim().length>0)return i.trim()}return null}function fr(e){const t=At(e);if(!t)return{agentId:null,agentName:null};const s=(typeof t.agent_id=="string"&&t.agent_id.trim().length>0?t.agent_id.trim():null)??(typeof t.agentId=="string"&&t.agentId.trim().length>0?t.agentId.trim():null)??(typeof e.agentId=="string"&&e.agentId.trim().length>0?e.agentId.trim():null),r=(typeof t.agent_name=="string"&&t.agent_name.trim().length>0?t.agent_name.trim():null)??(typeof t.agentName=="string"&&t.agentName.trim().length>0?t.agentName.trim():null)??(typeof e.agentName=="string"&&e.agentName.trim().length>0?e.agentName.trim():null);return{agentId:s,agentName:r}}function No(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}const Pp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Op=/^[0-9a-f]{20,}$/i,yl=/^\d+$/,bl=/^(user|usr|clerk)_[a-z0-9]+$/i;function sn(e){if(!e)return null;const t=e.trim();return!t||Pp.test(t)||Op.test(t)||yl.test(t)||bl.test(t)?null:t}const Bp=new Set(["main","system","local","cli","openclaw","runtime","unknown"]);function qp(e){if(!e||e.trim().length===0||e.trim()==="—")return{primary:"OrgX",secondary:null};const t=e.trim(),s=t.toLowerCase();return Bp.has(s)?{primary:"You",secondary:t}:{primary:t,secondary:null}}function Io(e,t,s){if(!e)return null;let r=null;for(const a of t){const c=sn(No(e[a]));if(c){r=c;break}}let i=null;for(const a of s){const c=sn(No(e[a]));if(c){i=c;break}}return!r&&!i?null:{id:r,name:i,label:i??r??"OrgX"}}function zp(e,t){var s,r;if(!e||!t)return!1;if(e.id&&t.id){const i=e.id.trim().toLowerCase(),a=t.id.trim().toLowerCase();if(i===a){const c=((s=e.name)==null?void 0:s.trim().toLowerCase())??null,l=((r=t.name)==null?void 0:r.trim().toLowerCase())??null;return c&&l&&c!==l?!1:["unknown","system","agent","none","null","undefined"].includes(i)?!!(c&&l&&c===l):!0}}return!e.name||!t.name?!1:e.name.trim().toLowerCase()===t.name.trim().toLowerCase()}function Ao(e){const t=At(e),s=fr(e),r=si(e),i=sn(s.agentId),a=sn(s.agentName),c=sn(e.requesterAgentId??null),l=sn(e.requesterAgentName??null),u=(c||l?{id:c,name:l,label:l??c??"OrgX"}:null)??Io(t,["requested_by_agent_id","requestedByAgentId","requester_agent_id","requesterAgentId","runner_agent_id","runnerAgentId"],["requested_by_agent_name","requestedByAgentName","requester_agent_name","requesterAgentName","requester_name","requesterName","runner_agent_name","runnerAgentName"])??null,h=sn(e.executorAgentId??null),y=sn(e.executorAgentName??null),p=(h||y?{id:h,name:y,label:y??h??"Agent"}:null)??Io(t,["executed_by_agent_id","executedByAgentId","executor_agent_id","executorAgentId","delegated_to_agent_id","delegatedToAgentId","handoff_to_agent_id","handoffToAgentId","agent_id","agentId"],["executed_by_agent_name","executedByAgentName","executor_agent_name","executorAgentName","delegated_to_agent_name","delegatedToAgentName","handoff_to_agent_name","handoffToAgentName","agent_name","agentName"])??(i||a?{id:i,name:a,label:a??i??"Agent"}:null);return u&&p?zp(u,p)?{requester:u,executor:p,mode:"single",primaryLabel:p.label,subtitle:p.label}:{requester:u,executor:p,mode:"handoff",primaryLabel:p.label,subtitle:`${u.label} -> ${p.label}`}:u&&!p?{requester:u,executor:null,mode:"requested",primaryLabel:u.label,subtitle:`${u.label} requested dispatch`}:!u&&p?{requester:null,executor:p,mode:"single",primaryLabel:p.label,subtitle:p.label}:r.isSystem?{requester:null,executor:null,mode:"system",primaryLabel:"OrgX",subtitle:"OrgX"}:{requester:null,executor:null,mode:"system",primaryLabel:sn(e.agentName??null)??sn(e.agentId??null)??"OrgX",subtitle:sn(e.agentName??null)??sn(e.agentId??null)??"OrgX"}}function Ri(e){return e?[e.id,e.name,e.label].filter(Boolean).join(" "):""}function ur(e){const t=At(e);if(!t)return null;const s=["workstreamId","workstream_id"];for(const i of s){const a=t[i];if(typeof a=="string"&&a.trim().length>0)return a.trim()}const r=t.orgx_context;if(r&&typeof r=="object"&&!Array.isArray(r)){const i=r,a=i.workstreamId??i.workstream_id;if(typeof a=="string"&&a.trim().length>0)return a.trim()}return null}function Di(e){const t=At(e);if(!t)return null;const s=["artifact_id","artifactId","work_artifact_id"];for(const r of s){const i=t[r];if(typeof i=="string"&&i.length>0)return i}return null}const So=new Map([["autopilot_slice_artifact_buffered","artifact"],["decision_buffered","decision"],["auto_continue_spawn_guard_blocked","decision"],["auto_continue_spawn_guard_rate_limited","decision"],["agent_launch_spawn_guard_blocked","decision"],["agent_launch_spawn_guard_rate_limited","decision"],["agent_restart_spawn_guard_blocked","decision"],["agent_restart_spawn_guard_rate_limited","decision"],["next_up_fallback_spawn_guard_blocked","decision"],["next_up_fallback_spawn_guard_rate_limited","decision"],["autopilot_slice_mcp_handshake_failed","decision"],["autopilot_slice_timeout","decision"],["autopilot_slice_log_stall","decision"],["autopilot_autofix_scheduled","decision"],["autopilot_autofix_executed","message"],["autopilot_autofix_skipped","message"]]);function $r(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="artifact"?"artifact":t==="decision"?"decision":t==="message"?"message":null}function Up(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r=="boolean")return r;if(typeof r=="string"){const i=r.trim().toLowerCase();if(i==="true")return!0;if(i==="false")return!1}}return null}function Ws(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r=="number"&&Number.isFinite(r))return Math.max(0,r);if(typeof r=="string"){const i=Number(r);if(Number.isFinite(i))return Math.max(0,i)}}return null}function Wp(e){if(!e)return null;const t=e.event;if(typeof t!="string")return null;const s=t.trim().toLowerCase();return s.length>0?s:null}function Hp(e){const t=At(e),s=$r(e.kind)??$r(t==null?void 0:t.activity_bucket)??$r(t==null?void 0:t.activityBucket)??$r(t==null?void 0:t.bucket);if(s)return s;if(e.type==="artifact_created")return"artifact";if(e.type==="decision_requested"||e.type==="decision_resolved")return"decision";const r=Wp(t),i=e.decisionRequired===!0||Up(t,["decision_required","decisionRequired"])===!0,a=Ws(t,["artifacts","artifact_count","artifactCount"])??0,c=Ws(t,["decisions","decision_count","decisionCount"])??0,l=Ws(t,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??0,d=Ws(t,["non_blocking_decisions","nonBlockingDecisions","non_blocking_decision_count","nonBlockingDecisionCount"])??0;if(r==="autopilot_slice_result")return i||l>0?"decision":a>0?"artifact":c>0||d>0?"decision":"message";if(r==="auto_continue_stopped"){const h=Sn(ct(t,["stop_reason","stopReason"])??"");if(h==="blocked"||h==="error")return"decision"}return r&&So.has(r)?So.get(r):typeof(t==null?void 0:t.artifact_id)=="string"||typeof(t==null?void 0:t.artifactId)=="string"||typeof(t==null?void 0:t.work_artifact_id)=="string"||a>0?"artifact":i||c>0||l>0||d>0?"decision":"message"}function ti(e){return{run_started:"Run started",run_completed:"Run completed",run_failed:"Run failed",artifact_created:"Artifact created",decision_requested:"Decision requested",decision_resolved:"Decision resolved",handoff_requested:"Handoff requested",handoff_claimed:"Handoff claimed",handoff_fulfilled:"Handoff fulfilled",blocker_created:"Blocker created",milestone_completed:"Milestone completed",delegation:"Delegation"}[e]}function Vp(e){const t=new Date(e);if(Number.isNaN(t.getTime()))return"unknown";const s=new Date(t.getFullYear(),t.getMonth(),t.getDate());return String(s.getTime())}function Kp(e){const t=Number(e);if(!Number.isFinite(t))return"Unknown day";const s=new Date(t),r=new Date,i=new Date(r.getFullYear(),r.getMonth(),r.getDate()),a=new Date(i);return a.setDate(i.getDate()-1),s.getTime()===i.getTime()?"Today":s.getTime()===a.getTime()?"Yesterday":s.toLocaleDateString(void 0,{month:"short",day:"numeric",year:s.getFullYear()===r.getFullYear()?void 0:"numeric"})}function Li(e){return e==="completed"?"Completed":e==="needs_input"?"Needs attention":e==="issue"?"Issue":e==="in_progress"?"In progress":"Update"}function Fi(e){return e==="completed"?F.lime:e==="needs_input"?F.amber:e==="issue"?F.red:F.teal}function Gp(e,t){var s;return t.status==="failed"?{state:"issue",why:t.sentence}:t.status==="needs_attention"?{state:(((s=t.nextAction)==null?void 0:s.toLowerCase())??"").includes("decision")?"needs_input":"issue",why:t.sentence}:t.status==="in_progress"?{state:"in_progress",why:t.sentence}:t.status==="completed"?{state:"completed",why:t.sentence}:e==="artifact"?{state:"completed",why:"Produced an artifact output."}:{state:"update",why:t.sentence}}function _o(e){if(!e||Object.keys(e).length===0)return null;try{return JSON.stringify(e,null,2)}catch{return null}}function cs(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Number(e);if(Number.isFinite(t))return t}return null}function Vn(e){const t=cs(e);if(t!==null)return Math.max(0,Math.round(t));if(Array.isArray(e))return e.length;if(e&&typeof e=="object"&&!Array.isArray(e)){const s=e,r=cs(s.count??s.total??s.size);if(r!==null)return Math.max(0,Math.round(r))}return null}function Xp(e){const t=cs(e);if(t===null)return null;const s=t>0&&t<=1?t*100:t;return Math.max(0,Math.min(100,Math.round(s)))}function Qp(e,t){for(const s of t){const r=Xp(e[s]);if(r!==null)return r}return null}function Pr(e,t){const s=[],r=new Set,i=a=>{if(typeof a!="string")return;const c=a.trim();!c||r.has(c)||(r.add(c),s.push(c))};for(const a of t){const c=e[a];if(Array.isArray(c)){for(const l of c)i(l);continue}i(c)}return s}function wl(e){if(!e)return{decisionIds:[],blockingDecisionIds:[],nonBlockingDecisionIds:[]};const t=Pr(e,["blocking_decision_ids","blockingDecisionIds"]),s=Pr(e,["non_blocking_decision_ids","nonBlockingDecisionIds"]),r=Pr(e,["decision_id","decisionId","decision_ids","decisionIds"]),i=new Set([...r,...t,...s]),a=e.decisions_needed??e.decisionsNeeded;if(Array.isArray(a))for(const c of a){if(!c||typeof c!="object"||Array.isArray(c))continue;const l=c,d=Pr(l,["id","decision_id","decisionId"]),u=l.blocking!==!1;for(const h of d)i.add(h),u?t.includes(h)||t.push(h):s.includes(h)||s.push(h)}return{decisionIds:Array.from(i),blockingDecisionIds:t,nonBlockingDecisionIds:s}}function vl(e){if(!e)return null;const t=At(e);if(!t)return null;const s=typeof t.event=="string"&&t.event.trim().length>0?t.event.trim():null,r=s??"",i=r.startsWith("autopilot_slice")&&!r.includes("artifact")||r.startsWith("autopilot_autofix");if(!s||!i&&s!=="auto_continue_started"&&s!=="auto_continue_stopped"&&s!=="next_up_manual_dispatch_started")return null;const a=fr(e),c=(typeof t.requested_by_agent_id=="string"&&t.requested_by_agent_id.trim().length>0?t.requested_by_agent_id.trim():null)??(typeof t.requestedByAgentId=="string"&&t.requestedByAgentId.trim().length>0?t.requestedByAgentId.trim():null)??(typeof t.runner_agent_id=="string"&&t.runner_agent_id.trim().length>0?t.runner_agent_id.trim():null)??(typeof t.runnerAgentId=="string"&&t.runnerAgentId.trim().length>0?t.runnerAgentId.trim():null)??a.agentId,l=(typeof t.requested_by_agent_name=="string"&&t.requested_by_agent_name.trim().length>0?t.requested_by_agent_name.trim():null)??(typeof t.requestedByAgentName=="string"&&t.requestedByAgentName.trim().length>0?t.requestedByAgentName.trim():null)??(typeof t.runner_agent_name=="string"&&t.runner_agent_name.trim().length>0?t.runner_agent_name.trim():null)??(typeof t.runnerAgentName=="string"&&t.runnerAgentName.trim().length>0?t.runnerAgentName.trim():null)??a.agentName,d=(typeof t.source_client=="string"&&t.source_client.trim().length>0?t.source_client.trim():null)??(typeof t.sourceClient=="string"&&t.sourceClient.trim().length>0?t.sourceClient.trim():null)??(typeof e.runtimeClient=="string"&&e.runtimeClient.trim().length>0?e.runtimeClient.trim():null),u=t.required_skills??t.requiredSkills,h=Array.isArray(u)?u.filter(X=>typeof X=="string"&&X.trim().length>0):[],y=rf(h),b=t.task_ids??t.taskIds,p=Array.isArray(b)?b.filter(X=>typeof X=="string"&&X.trim().length>0):[],w=t.milestone_ids??t.milestoneIds,v=Array.isArray(w)?w.filter(X=>typeof X=="string"&&X.trim().length>0):[],x=ct(t,["initiative_id","initiativeId"])??(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null),C=ct(t,["initiative_title","initiativeTitle"]),j=ct(t,["initiative_status","initiativeStatus"]),g=ur(e),S=ct(t,["workstream_title","workstreamTitle"]),W=ct(t,["workstream_status","workstreamStatus"]),Y=ct(t,["task_title","taskTitle"]),K=ct(t,["milestone_title","milestoneTitle"]),me=ct(t,["domain"]),ge=ct(t,["phase","slice_phase","slicePhase"]),Z=ct(t,["next_step","nextStep"]),ae=Qp(t,["progress_pct","progressPct","progress_percent","progressPercent","completion_pct","completionPct","slice_progress_pct","sliceProgressPct"]),ke=typeof t.parsed_status=="string"?t.parsed_status:typeof t.parsedStatus=="string"?t.parsedStatus:null,Fe=typeof t.has_output=="boolean"?t.has_output:typeof t.hasOutput=="boolean"?t.hasOutput:null,G=typeof t.log_path=="string"?t.log_path:typeof t.logPath=="string"?t.logPath:null,Se=typeof t.output_path=="string"?t.output_path:typeof t.outputPath=="string"?t.outputPath:null,Ae=typeof t.error=="string"?t.error:null,xe=Vn(t.artifacts??t.artifact_count??t.artifactCount),re=Vn(t.decisions??t.decision_count??t.decisionCount),le=wl(t),Ee=t.decisions_needed??t.decisionsNeeded;let ee=Vn(t.blocking_decisions??t.blockingDecisions??t.blocking_decision_count??t.blockingDecisionCount),q=Vn(t.non_blocking_decisions??t.nonBlockingDecisions??t.non_blocking_decision_count??t.nonBlockingDecisionCount);if((ee===null||q===null)&&Array.isArray(Ee)){let X=0,te=0;for(const Le of Ee){if(!Le||typeof Le!="object"||Array.isArray(Le))continue;Le.blocking===!1?te+=1:X+=1}ee===null&&(ee=X),q===null&&(q=te)}ee===null&&re!==null&&e.decisionRequired===!0&&(ee=re>0?re:1),q===null&&re!==null&&ee!==null&&(q=Math.max(0,re-ee)),ee===null&&re!==null&&q!==null&&(ee=Math.max(0,re-q));const J=Vn(t.status_updates_applied??t.statusUpdatesApplied),V=Vn(t.task_updates??t.taskUpdates),k=Vn(t.milestone_updates??t.milestoneUpdates),z=J??(V!==null||k!==null?(V??0)+(k??0):null),O=Vn(t.status_updates_buffered??t.statusUpdatesBuffered),oe=typeof t.stop_reason=="string"?t.stop_reason:typeof t.stopReason=="string"?t.stopReason:null,ie=cs(t.token_budget??t.tokenBudget),Me=cs(t.tokens_used??t.tokensUsed),ue=a.agentId??(typeof t.runner_agent_id=="string"&&t.runner_agent_id.trim().length>0?t.runner_agent_id.trim():null)??(typeof t.runnerAgentId=="string"&&t.runnerAgentId.trim().length>0?t.runnerAgentId.trim():null),R=a.agentName??(typeof t.runner_agent_name=="string"&&t.runner_agent_name.trim().length>0?t.runner_agent_name.trim():null)??(typeof t.runnerAgentName=="string"&&t.runnerAgentName.trim().length>0?t.runnerAgentName.trim():null)??y,$=y&&!a.agentName?null:ue;return{event:s,agentId:$,agentName:R,requesterAgentId:c,requesterAgentName:l,dispatcherClient:d,initiativeId:x,domain:me,phase:ge,progressPct:ae,nextStep:Z,requiredSkills:h,initiativeStatus:j,initiativeTitle:C,workstreamId:g,workstreamStatus:W,workstreamTitle:S,taskTitle:Y,milestoneTitle:K,taskIds:p,milestoneIds:v,parsedStatus:ke,hasOutput:Fe,artifacts:xe,decisions:re,blockingDecisions:ee,nonBlockingDecisions:q,decisionIds:le.decisionIds,blockingDecisionIds:le.blockingDecisionIds,nonBlockingDecisionIds:le.nonBlockingDecisionIds,statusUpdatesApplied:z,statusUpdatesBuffered:O,stopReason:oe,tokenBudget:ie,tokensUsed:Me,logPath:G,outputPath:Se,error:Ae}}function $i(e){const t=e.trim();return t?/^https?:\/\//i.test(t)?t:`/orgx/api/live/filesystem/open?path=${encodeURIComponent(t)}`:""}function Jp(e){return/^https?:\/\//i.test(e.trim())}function Yp(e){const t=pa(e);if(!t)return null;const s=t,r=s.orgx_provenance,i=r&&typeof r=="object"&&!Array.isArray(r)?r:null,a=i!=null&&i.skill_pack&&typeof i.skill_pack=="object"&&!Array.isArray(i.skill_pack)?i.skill_pack:null,c=(typeof s.orgx_plugin_version=="string"?s.orgx_plugin_version:null)??(typeof(i==null?void 0:i.plugin_version)=="string"?i.plugin_version:null),l=(typeof s.skill_pack_name=="string"?s.skill_pack_name:null)??(typeof(a==null?void 0:a.name)=="string"?a.name:null),d=(typeof s.skill_pack_version=="string"?s.skill_pack_version:null)??(typeof(a==null?void 0:a.version)=="string"?a.version:null),u=(typeof s.skill_pack_checksum=="string"?s.skill_pack_checksum:null)??(typeof(a==null?void 0:a.checksum)=="string"?a.checksum:null),h=(typeof s.skill_pack_source=="string"?s.skill_pack_source:null)??(typeof(a==null?void 0:a.source)=="string"?a.source:null),y=typeof s.kickoff_context_hash=="string"?s.kickoff_context_hash:null,b=typeof s.kickoff_context_source=="string"?s.kickoff_context_source:null,p=typeof s.spawn_guard_model_tier=="string"?s.spawn_guard_model_tier:null,w=typeof s.provider=="string"?s.provider:null,v=typeof s.model=="string"?s.model:null,x=typeof s.domain=="string"?s.domain:null,C=s.required_skills??s.requiredSkills,j=Array.isArray(C)?C.filter(S=>typeof S=="string"&&S.trim().length>0):[];return!!c||!!(l||d||u)||!!y||!!(p||w||v||x)||j.length>0?{pluginVersion:c,skillPack:l||d||u||h?{name:l,version:d,checksum:u,source:h}:null,kickoffContextHash:y,kickoffContextSource:b,modelTier:p,provider:w,model:v,domain:x,requiredSkills:j}:null}function kl(e){if(!e)return null;const t=At(e);if(!t||typeof t!="object")return null;const s=["artifact","artifacts","output","outputs","result","results","payload","toolOutput","toolOutputs","toolResult","toolResults"];for(const r of s){const i=t[r];if(i!=null)return{source:r,value:i}}return e.type==="artifact_created"?{source:"metadata",value:t}:null}function Zp(e){const t=At(e),s=!!(t&&typeof t.artifact_id=="string"||t&&typeof t.artifactId=="string"||t&&typeof t.work_artifact_id=="string"),r=kl(e);if(!r&&!s)return null;let i="Artifact";e.type==="artifact_created"?i="Created artifact":(r==null?void 0:r.source)==="toolOutput"||(r==null?void 0:r.source)==="toolOutputs"?i="Tool output":(r==null?void 0:r.source)==="toolResult"||(r==null?void 0:r.source)==="toolResults"?i="Result":(r==null?void 0:r.source)==="output"||(r==null?void 0:r.source)==="outputs"?i="Output":s&&(i="Registered artifact");let a="";if(r){const c=r.value;if(typeof c=="string")a=c.length>80?c.slice(0,80)+"…":c;else if(Array.isArray(c))a=`${c.length} item${c.length===1?"":"s"}`;else if(c&&typeof c=="object"){const l=Object.keys(c);a=l.length<=4?l.join(", "):`${l.length} fields`}}return{label:i,preview:a,hasRegisteredId:s}}function ef(e){const t=e.trim();return!t||/^[a-z]+:\/\//i.test(t)||/^data:/i.test(t)?!1:t.startsWith("/")||t.startsWith("~/")||/^[A-Za-z]:[\\/]/.test(t)||/^[.]{1,2}\//.test(t)?!0:t.includes("/")&&!/\s{2,}/.test(t)}function jl(e){const t=At(e);if(!t)return[];const s=[],r=new Set,i=4,a=(l,d)=>{if(typeof d!="string")return;const u=d.trim();if(!u||!ef(u))return;const h=u.toLowerCase();r.has(h)||(r.add(h),s.push({key:l,path:u}))},c=(l,d="",u=0)=>{if(!(u>i))for(const[h,y]of Object.entries(l)){const b=d?`${d}.${h}`:h,p=h.toLowerCase(),w=p.includes("path")||p.includes("pointer")||p.includes("log")||p.includes("stdout")||p.includes("stderr")||p==="url"||p==="uri"||p==="file"||p==="files"||p==="logs"||p.endsWith("url")||p.endsWith("_file")||p.endsWith("file")||p.includes("artifact");if(Array.isArray(y)){for(let v=0;v<y.length;v+=1){const x=y[v];w&&a(b,x),x&&typeof x=="object"&&!Array.isArray(x)&&c(x,`${b}[${v}]`,u+1)}continue}w&&a(b,y),y&&typeof y=="object"&&c(y,b,u+1)}};return c(t),s}function tf(e,t){const s=[],r=i=>{if(!i)return;const a=i.trim();!a||Jp(a)||s.includes(a)||s.push(a)};r((e==null?void 0:e.logPath)??null);for(const i of t){const a=i.key.toLowerCase();(a.includes("log")||a.includes("stdout")||a.includes("stderr")||i.path.toLowerCase().endsWith(".log"))&&r(i.path)}r((e==null?void 0:e.outputPath)??null);for(const i of t)r(i.path);return s.length>0?s[0]:null}function ct(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r=="string"&&r.trim().length>0)return r.trim()}return null}function nf(e){if(!e)return{domainCurrent:null,domainMax:null,totalCurrent:null,totalMax:null};const t=e.match(/rate limit:\s*(\d+)\s*\/\s*(\d+)\s*domain(?:\s*,\s*(\d+)\s*\/\s*(\d+)\s*total)?/i);return t?{domainCurrent:Number.isFinite(Number(t[1]))?Number(t[1]):null,domainMax:Number.isFinite(Number(t[2]))?Number(t[2]):null,totalCurrent:Number.isFinite(Number(t[3]))?Number(t[3]):null,totalMax:Number.isFinite(Number(t[4]))?Number(t[4]):null}:{domainCurrent:null,domainMax:null,totalCurrent:null,totalMax:null}}function sf(e,t){if(!e)return null;const s=At(e);if(!s)return null;const r=ct(s,["event","event_name","eventName"]),i=Ts(s.spawn_guard),a=Ts(i==null?void 0:i.checks),c=Ts((a==null?void 0:a.rateLimit)??(a==null?void 0:a.rate_limit)),l=ct(s,["blocked_reason","blockedReason","last_error","lastError"])??(t==null?void 0:t.error)??null,d=nf(l),u=cs(c==null?void 0:c.current)??d.domainCurrent,h=cs(c==null?void 0:c.max)??d.domainMax,y=d.totalCurrent,b=d.totalMax,p=typeof(c==null?void 0:c.passed)=="boolean"?c.passed:null,w=((r==null?void 0:r.includes("rate_limited"))??!1)||!!(l&&/rate limit/i.test(l))||p===!1;return!((r==null?void 0:r.includes("spawn_guard"))??!1)&&!w&&!i&&!l?null:{event:r,blockedReason:l,domain:ct(s,["domain"])??ct(i,["domain","task_domain"]),modelTier:ct(s,["spawn_guard_model_tier","model_tier"])??ct(i,["modelTier","model_tier"]),domainCurrent:u,domainMax:h,totalCurrent:y,totalMax:b,retryAt:ct(s,["next_retry_at","nextRetryAt"]),retryInMs:cs(s.next_retry_in_ms??s.nextRetryInMs),isRateLimited:w}}function rf(e){var r;if(e.length!==1)return null;const t=(r=e[0])==null?void 0:r.trim();if(!t)return null;const s={"orgx-marketing-agent":"OrgX Marketing","orgx-engineering-agent":"OrgX Engineering","orgx-design-agent":"OrgX Design","orgx-product-agent":"OrgX Product","orgx-sales-agent":"OrgX Sales","orgx-operations-agent":"OrgX Operations","orgx-orchestrator-agent":"OrgX Orchestrator"};if(s[t])return s[t];if(t.endsWith("-agent")){const i=t.replace(/^orgx-/,"").replace(/-agent$/,"").trim();return i.length===0?null:`OrgX ${lt(i)}`}return null}function af(e){if(!e)return!1;const t=e.trim().toLowerCase();return t.startsWith("orgx ")?t==="orgx engineering"||t==="orgx product"||t==="orgx marketing"||t==="orgx sales"||t==="orgx operations"||t==="orgx design"||t==="orgx orchestrator":!1}function Pi(e,t,s){const r=typeof e=="string"&&e.trim().length>0?e.trim():null,i=typeof t=="string"&&t.trim().length>0?t.trim():null,a=i?(s==null?void 0:s.get(i))??null:null,c=r&&a&&af(r)?a:r??a;if(c)return pr(c);if(!i)return"OrgX";const l=i.toLowerCase();return l==="main"||l==="system"||l==="unknown"||l==="runtime"||l==="orgx"||l==="openclaw"||l==="null"||l==="undefined"?pr(i):mr.test(i)||of.test(i)||yl.test(i)||bl.test(i)?"OrgX":pr(i)}const mr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,of=/^[0-9a-f]{20,}$/i,lf=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;function ni(e){const t=new Set;if(!e)return t;for(const a of[e.title,e.summary,e.description])if(typeof a=="string")for(const c of a.match(lf)??[]){const l=c.trim().toLowerCase();mr.test(l)&&t.add(l)}typeof e.runId=="string"&&mr.test(e.runId.trim())&&t.add(e.runId.trim().toLowerCase());const s=At(e);if(!s)return t;const r=["run_id","runId","last_run_id","lastRunId","active_run_id","activeRunId","slice_id","sliceId","worker_run_id","workerRunId","correlation_id","correlationId","initiative_id","initiativeId","workstream_id","workstreamId","task_id","taskId","milestone_id","milestoneId","decision_id","decisionId","outbox_event_id","outboxEventId"],i=["task_ids","taskIds","milestone_ids","milestoneIds","decision_ids","decisionIds","blocking_decision_ids","blockingDecisionIds","non_blocking_decision_ids","nonBlockingDecisionIds","allowed_workstream_ids","allowedWorkstreamIds"];for(const a of r){const c=s[a];if(typeof c=="string"){const l=c.trim().toLowerCase();mr.test(l)&&t.add(l)}}for(const a of i){const c=s[a];if(Array.isArray(c))for(const l of c){if(typeof l!="string")continue;const d=l.trim().toLowerCase();mr.test(d)&&t.add(d)}}return t}function cf(e){if(!e)return[];const t=At(e);return wl(t).decisionIds}function df(e,t,s){if(!e)return[];const r=At(e),i=ct(r,["workstream_id","workstreamId"]),a=ct(r,["initiative_id","initiativeId"]),c=ni(e);if(!i&&!a&&c.size===0)return[];const l=ls(e.timestamp),d=[];for(const b of t){if(b.id===e.id)continue;const p=At(b);if(!p)continue;const w=ct(p,["workstream_id","workstreamId"]),v=ct(p,["initiative_id","initiativeId"]),x=ni(b),C=c.size>0&&Array.from(c).some(K=>x.has(K)),j=!!i&&!!w&&i===w;if(!C&&!j&&!(!!a&&!!v&&a===v))continue;const S=jl(b).filter(K=>!s.has(K.path));if(S.length===0)continue;const W=Math.abs(ls(b.timestamp)-l);if(!C&&W>7200*1e3)continue;const Y=C?0:j?1:2;!C&&W>1200*1e3||d.push({priority:Y,delta:W,evidence:S})}if(d.length===0)return[];d.sort((b,p)=>b.priority!==p.priority?b.priority-p.priority:b.delta-p.delta);const u=[],h=new Set(s),y=d[0].priority;for(const b of d){if(b.priority!==y)break;for(const p of b.evidence)if(!h.has(p.path)&&(h.add(p.path),u.push({key:`related.${p.key}`,path:p.path}),u.length>=8))return u}return u}function uf(e,t){if(!e)return null;const s=At(e),r=ct(s,["workstream_id","workstreamId"]),i=ct(s,["initiative_id","initiativeId"]),a=ni(e);if(!r&&!i&&a.size===0)return null;const c=ls(e.timestamp),l=[];for(const u of t){if(u.id===e.id)continue;const h=vl(u);if(!h)continue;const y=At(u);if(!y)continue;const b=ct(y,["workstream_id","workstreamId"]),p=ct(y,["initiative_id","initiativeId"]),w=ni(u),v=a.size>0&&Array.from(a).some(W=>w.has(W)),x=!!r&&!!b&&r===b;if(!v&&!x&&!(!!i&&!!p&&i===p))continue;const j=Math.abs(ls(u.timestamp)-c);if(!v&&j>1200*1e3)continue;const g=v?"shared_id":x?"workstream":"initiative",S=g==="shared_id"?0:g==="workstream"?1:2;l.push({priority:S,delta:j,relation:g,detail:h})}if(l.length===0)return null;l.sort((u,h)=>u.priority!==h.priority?u.priority-h.priority:u.delta-h.delta);const d=l[0];return{detail:d.detail,relation:d.relation}}function Sn(e){return e?e.trim().toLowerCase().replace(/[\s-]+/g,"_"):""}function oi(e){const t=Sn(e);return["done","complete","completed","stopped","success"].includes(t)}function mf(e){const t=Sn(e.parsedStatus),s=Sn(e.event);return t==="failed"||t==="error"||t==="timed_out"||t==="timeout"||t==="aborted"||s.includes("error")||s.includes("timeout")?"critical":t==="blocked"||e.stopReason==="blocked"?"warning":oi(t)||e.stopReason==="completed"?"positive":"neutral"}function pf(e){if(oi(e.parsedStatus)||e.stopReason==="completed")return 100;const t=Sn(e.parsedStatus);if(t==="blocked"||t==="error"||t==="failed")return 100;const s=e.event;return s==="auto_continue_started"?3:s==="next_up_manual_dispatch_started"?8:s==="autopilot_slice_dispatched"?14:s==="autopilot_slice_status_updates_buffered"?72:s==="autopilot_slice_result"?92:s==="autopilot_autofix_scheduled"?6:s==="autopilot_autofix_executed"?18:s==="autopilot_autofix_skipped"||s==="auto_continue_stopped"?100:s.startsWith("autopilot_slice")?56:null}function Nl(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function ff(e,t){if(!e&&t===null)return null;const s=e?mf(e):"neutral",r=l=>l>=100&&(s==="warning"||s==="critical"),i="Reached a terminal blocked state. Resolve blockers to continue.";if((e==null?void 0:e.progressPct)!==null&&(e==null?void 0:e.progressPct)!==void 0){const l=Nl(e.progressPct)??0,d=r(l);return{pct:l,source:"metadata",label:d?i:"Reported by slice metadata",tone:s,terminalStop:d}}if(t!==null){const l=r(t);return{pct:t,source:"session",label:l?i:"Derived from runtime session",tone:s,terminalStop:l}}if(!e)return null;const a=pf(e);if(a===null)return null;const c=r(a);return{pct:a,source:"lifecycle",label:c?i:"Estimated from dispatch lifecycle",tone:s,terminalStop:c}}function hf(e,t,s,r=null){var C;const i=At(e),a=Sn(ct(i,["event","event_name","eventName"])??(t==null?void 0:t.event)??""),c=Sn(e.state??e.phase??e.kind??e.type),l=Sn((s==null?void 0:s.parsedStatus)??(t==null?void 0:t.parsedStatus)??c),d=Sn((s==null?void 0:s.stopReason)??(t==null?void 0:t.stopReason)),u=ct(i,["blocked_reason","blockedReason","error","message"])??(t==null?void 0:t.error)??e.description??null,h=Math.max(0,(s==null?void 0:s.decisions)??(t==null?void 0:t.decisions)??0),y=Math.max(0,(s==null?void 0:s.blockingDecisions)??(t==null?void 0:t.blockingDecisions)??(e.decisionRequired===!0?Math.max(1,h):0)),b=Math.max(0,(s==null?void 0:s.nonBlockingDecisions)??(t==null?void 0:t.nonBlockingDecisions)??Math.max(0,h-y)),p=e.decisionRequired===!0||e.type==="decision_requested"||y>0||l==="needs_decision"&&b===0,w=e.type==="run_completed"||e.type==="milestone_completed"||oi(l)||d==="completed",v=a.includes("spawn_guard_rate_limited")||!!(u&&/rate limit/i.test(u)),x=a.includes("spawn_guard_blocked");if(a==="auto_continue_started")return{label:"Autopilot on",summary:Lt(e.title)??"Autopilot is active and will continue dispatching work from the Next Up queue.",hint:"Watch Activity and Next Up for newly dispatched slices.",tone:"positive"};if(a==="auto_continue_stopped"){if(d==="budget_exhausted")return{label:"Budget exhausted",summary:Lt(e.title)??"Autopilot stopped because the configured token budget was exhausted.",hint:"Restart with an explicit token budget or a narrower workstream scope.",tone:"warning"};if(d==="completed")return{label:"Completed",summary:Lt(e.title)??"Autopilot stopped because the current dispatch scope is complete.",hint:null,tone:"positive"};if(d==="stopped")return{label:"Stopped",summary:Lt(e.title)??"Autopilot was stopped by request.",hint:"Start again to resume continuous dispatch.",tone:"neutral"};if(d==="blocked")return{label:p?"Needs decision":"Blocked",summary:Lt(e.title)??(p?"Autopilot is paused pending a decision.":"Autopilot is blocked and needs intervention."),hint:p?"Open the Decisions panel and approve the pending item to continue.":"Resolve the blocker, then restart autopilot.",tone:p?"warning":"critical"};if(d==="error")return{label:"Error",summary:Lt(e.title)??u??"Autopilot stopped because of an error.",hint:"Open evidence and logs, then retry or pause the workstream.",tone:"critical"}}if(a==="autopilot_transition"){const j=String((i==null?void 0:i.old_state)??""),g=String((i==null?void 0:i.new_state)??""),S=String((i==null?void 0:i.reason)??"");return g==="running"?{label:"Autopilot activated",summary:`State changed from ${j} to running.`,hint:"Autopilot will dispatch work from the Next Up queue.",tone:"positive"}:g==="blocked"||g==="error"?{label:g==="error"?"Autopilot error":"Autopilot blocked",summary:`State changed from ${j} to ${g}${S?`: ${S}`:""}.`,hint:"Review the triage queue for actionable items.",tone:"critical"}:{label:"Autopilot state change",summary:`${j} → ${g}${S?` (${S})`:""}.`,hint:null,tone:"neutral"}}if(v)return{label:"Rate limited",summary:u?Lt(u)??"Spawn guard rate limit reached.":"Spawn guard rate limit reached.",hint:"Adjust limits in settings or wait for the window to reset before retrying.",tone:"warning"};if(x)return{label:"Spawn guard blocked",summary:u?Lt(u)??"Spawn guard denied dispatch.":"Spawn guard denied dispatch.",hint:"Review guard checks, then retry or approve an override.",tone:"critical"};if(r){if(r.status==="completed")return{label:b>0?"Completed + follow-up":"Completed",summary:b>0?`Execution completed. ${b} non-blocking decision${b===1?"":"s"} were logged for optional follow-up.`:r.sentence,hint:r.nextAction,tone:"positive"};if(r.status==="failed")return{label:"Failed",summary:u?Lt(u)??r.sentence:r.sentence,hint:r.nextAction,tone:"critical"};if(r.status==="needs_attention"){const j=p||(((C=r.nextAction)==null?void 0:C.toLowerCase().includes("decision"))??!1);return{label:j?"Needs decision":"Needs attention",summary:r.sentence,hint:r.nextAction??(j?"Review the Decisions panel and resolve the pending item.":"Review blocker details and resume when resolved."),tone:j?"warning":"critical"}}if(r.status==="in_progress")return{label:"In progress",summary:r.sentence,hint:null,tone:"neutral"}}return e.type==="run_failed"||e.type==="blocker_created"||l==="blocked"||l==="failed"||l==="error"||d==="blocked"||d==="error"?{label:"Blocked",summary:u?Lt(u)??"Execution is blocked.":"Execution is blocked and needs intervention.",hint:p?"Resolve the pending decision, then resume the session.":"Open the session and retry after fixing the blocker.",tone:"critical"}:p?{label:"Needs decision",summary:"Execution paused pending approval or a human choice.",hint:"Review the Decisions panel and approve the pending item to continue.",tone:"warning"}:w&&b>0?{label:"Completed + follow-up",summary:`Execution completed. ${b} non-blocking decision${b===1?"":"s"} were logged for optional follow-up.`,hint:"Review the decision for optimization, but no approval is required to mark this slice complete.",tone:"positive"}:e.type==="decision_resolved"?{label:"Decision resolved",summary:"A pending decision was completed.",hint:null,tone:"positive"}:w?{label:"Completed",summary:"Execution completed successfully.",hint:null,tone:"positive"}:e.type==="run_started"||c==="running"||c==="in_progress"?{label:"In progress",summary:"Execution is actively running.",hint:null,tone:"neutral"}:null}function Il(e){if(typeof e=="string")return n.jsx(Yr,{mode:"block",text:e,className:"text-body leading-relaxed text-primary"});if(typeof e=="number"||typeof e=="boolean")return n.jsx("p",{className:"text-body text-primary",children:String(e)});if(Array.isArray(e))return n.jsx("div",{className:"space-y-1.5",children:e.map((t,s)=>n.jsx("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:Il(t)},`artifact-list-${s}`))});if(e&&typeof e=="object"){const t=Object.entries(e);return n.jsx("dl",{className:"space-y-1.5",children:t.map(([s,r])=>n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsx("dt",{className:"text-micro font-semibold tracking-[0.02em] text-secondary",children:lt(s)}),n.jsx("dd",{className:"mt-1 text-body text-primary",children:typeof r=="string"||typeof r=="number"||typeof r=="boolean"?String(r):Array.isArray(r)?`${r.length} item${r.length===1?"":"s"}`:r&&typeof r=="object"?`${Object.keys(r).length} field${Object.keys(r).length===1?"":"s"}`:"—"})]},s))})}return n.jsx("p",{className:"text-body text-secondary",children:"No artifact payload."})}function Lt(e){if(!e)return null;const t=e.trim();if(!t)return null;const s=gr(t);return s&&s!==t&&/^[a-z0-9._/-]+$/i.test(t)?s:lt(t)}const gf=[/^User:\s*System:/i,/Exec failed/i,/SIGKILL/i,/SIGTERM/i,/stack trace/i,/Traceback \(most recent/i,/^\s*\{[\s"]/,/Error: /,/execution policy/i,/outbox replay/i,/changeset replayed/i];function xf(e){return gf.some(t=>t.test(e))}function si(e){const t=e.title??"";return xf(t)?/Exec failed|SIGKILL|SIGTERM|Error: /i.test(t)?{title:"Execution failed",isSystem:!0}:/outbox replay|changeset replayed/i.test(t)?{title:"Changes synced",isSystem:!0}:/execution policy/i.test(t)?{title:"System directive",isSystem:!0}:{title:"System event",isSystem:!0}:{title:lt(t)||lt(ti(e.type)),isSystem:!1}}const yf=new Set(["changeset_replayed","changeset_applied","changeset.replayed","changeset.applied","outbox_replay_applied","outbox_replayed","sync_applied","sync.applied","sentinel_changeset_applied","sentinel_decision_applied","sentinel.changeset.applied","sentinel.decision.applied"]);function hr(e){const t=At(e);if(!t)return!1;const s=(typeof t.event=="string"&&t.event.trim().length>0?t.event.trim().toLowerCase():null)??(typeof t.event_name=="string"&&t.event_name.trim().length>0?t.event_name.trim().toLowerCase():null)??(typeof t.eventName=="string"&&t.eventName.trim().length>0?t.eventName.trim().toLowerCase():null),r=(typeof t.source_client=="string"?t.source_client:null)??(typeof t.sourceClient=="string"?t.sourceClient:null),i=(r==null?void 0:r.toLowerCase())??"",a=(typeof e.kind=="string"&&e.kind.trim().length>0?e.kind.trim().toLowerCase():null)??(typeof t.kind=="string"&&t.kind.trim().length>0?t.kind.trim().toLowerCase():null)??(typeof t.event_kind=="string"&&t.event_kind.trim().length>0?t.event_kind.trim().toLowerCase():null)??(typeof t.eventKind=="string"&&t.eventKind.trim().length>0?t.eventKind.trim().toLowerCase():null)??"",c=/(changeset[\._ ]?(applied|replayed)|sync[\._ ]?applied|sentinel[\._ ]?(changeset|decision)[\._ ]?applied)/i.test(a),l=t.replayed===!0,d=typeof t.changeset_id=="string"&&t.changeset_id.trim().length>0||typeof t.changesetId=="string"&&t.changesetId.trim().length>0,u=/changes synced|changeset replayed|changeset applied|outbox replay/i.test(`${e.title??""} ${e.summary??""} ${e.description??""}`);return!!(s&&yf.has(s)||c||l&&(d||u)||d&&(u||i.includes("outbox")||i.includes("replay"))||i.includes("outbox_replay")&&u)}function Co(e){var d;if(!e||!hr(e))return null;const t=At(e),s=Vn((t==null?void 0:t.applied_count)??(t==null?void 0:t.appliedCount)??(t==null?void 0:t.applied)??null),r=(typeof(t==null?void 0:t.idempotency_key)=="string"?t.idempotency_key:null)??(typeof(t==null?void 0:t.idempotencyKey)=="string"?t.idempotencyKey:null),i=((d=r==null?void 0:r.match(/sentinel:([a-z_]+):/i))==null?void 0:d[1])??null,a=ct(t,["entity_type","entityType"])??i??(e.type==="milestone_completed"?"milestone":null),c=s!==null?`${s} change${s===1?"":"s"}`:"Queued changes",l=a?` for ${lt(a).toLowerCase()}`:"";return`${c}${l} were synced from local replay.`}function Oi(e){if(!hr(e))return null;const t=At(e);if(!t)return null;const s=ct(t,["idempotency_key","idempotencyKey"]);if(s)return`idem:${s.toLowerCase()}`;const r=ct(t,["event","event_name","eventName"])??"",i=ct(t,["changeset_id","changesetId"])??"",a=ct(t,["entity_type","entityType"])??"",c=ct(t,["entity_id","entityId"])??"",l=ta(e)??"",d=si(e).title.trim().toLowerCase();return`fallback:${r.toLowerCase()}:${i.toLowerCase()}:${a.toLowerCase()}:${c.toLowerCase()}:${l.toLowerCase()}:${d}`}function bf(e){if(!e)return null;const t=At(e);if(!t||typeof t!="object")return null;const s=typeof t.source=="string"?t.source.trim():"",r=typeof t.turnId=="string"?t.turnId.trim():"";if(s!=="local_openclaw"||!r)return null;const i=typeof t.sessionKey=="string"&&t.sessionKey.trim().length>0?t.sessionKey.trim():null;return{turnId:r,sessionKey:i,runId:e.runId??null}}function Mo(e){return e.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/\*([^*\n]+)\*/g,"$1").replace(/_([^_\n]+)_/g,"$1")}function To(e,t){const r=(Lt(t??e.summary)??Lt(e.description)??lt(e.title||ti(e.type))).replace(/\r\n/g,`
210
+ `).replace(/```[\s\S]*?```/g," ").replace(/^\s{0,3}#{1,6}\s+/gm,"").replace(/^\s*[-*]\s+/gm,"").replace(/\s+/g," ").trim(),i=r.split(`
211
+ `).map(c=>Mo(c).trim()).filter(c=>c.length>0&&!/^\|?[:\-| ]+\|?$/.test(c));let a=i[0]??Mo(r);return a.length<24&&i.length>1&&(a=`${a} ${i[1]}`.trim()),a.length>108?`${a.slice(0,107).trimEnd()}…`:a}const wf=o.memo(function({activity:t,sessions:s,sliceRuns:r=[],initiatives:i=[],timelineNarrative:a=[],selectedRunIds:c,selectedSessionLabel:l=null,selectedWorkstreamId:d=null,selectedWorkstreamLabel:u=null,agentFilter:h=null,timeFilterId:y="live",onTimeFilterChange:b,customTimeRange:p={startIso:null,endIso:null},onCustomTimeRangeChange:w,hasMore:v=!1,isLoadingMore:x=!1,onLoadMore:C,onClearSelection:j,onClearWorkstreamFilter:g,onClearAgentFilter:S,onFocusRunId:W,onOpenDecision:Y,requestedActivityItemId:K=null,onActivityItemRequestHandled:me,onPlayNextUp:ge,onStartAutopilot:Z,onPauseWorkstream:ae,onCreateInitiative:ke,onOpenMissionControl:Fe,onOpenSettings:G,workspaceId:Se=null,chatSnapshot:Ae,onRefreshData:xe,isLoading:re=!1}){var fa;const le=Xn(),{open:Ee}=dl(),[ee,q]=o.useState("all"),[J,V]=o.useState(!1),[k,z]=o.useState(!1),[O,oe]=o.useState(""),[ie,Me]=o.useState(new Set),[ue,R]=o.useState({}),[$,X]=o.useState("newest"),[te,Le]=o.useState(!1),[qe,_e]=o.useState(!1),[M,B]=o.useState(Ti),[ne,fe]=o.useState(null),[De,et]=o.useState(null),[tt,Re]=o.useState(!1),[Je,We]=o.useState(1),[ft,ot]=o.useState("structured"),[nt,we]=o.useState(null),[Ge,je]=o.useState("feed"),[H,Oe]=o.useState(null),[U,se]=o.useState(null),[Ce,$e]=o.useState(!1),[Pe,Be]=o.useState(null),[Te,He]=o.useState(null),[st,Ve]=o.useState(!1),[Pt,Qe]=o.useState(null),[Mt,Yt]=o.useState(0),[mt,rn]=o.useState({status:"idle",path:null,text:"",lineCount:0,truncated:!1,updatedAt:null,error:null}),[_n,ps]=o.useState(!1),gt=o.useRef(Date.now()),Wt=o.useRef(null),Cn=o.useRef(null),Qn=o.useRef(null),Rt=o.useRef(null),$n=o.useRef(null),[jt,Dt]=o.useState(()=>Lr(p.startIso)),[Ct,Mn]=o.useState(()=>Lr(p.endIso)),[Pn,Rs]=o.useState(()=>typeof window>"u"?!1:window.innerWidth<=640),fs=o.useMemo(()=>Ko(y),[y]),Zt=o.useMemo(()=>Lr(p.startIso),[p.startIso]),Xt=o.useMemo(()=>Lr(p.endIso),[p.endIso]),Ht=o.useMemo(()=>!jt||!Ct?!1:Ct.getTime()>=jt.getTime(),[Ct,jt]),Jn=o.useMemo(()=>y!=="custom"?fs.label:Zt&&Xt?`${Fr(Zt)} - ${Fr(Xt)}`:"Custom range",[Xt,Zt,y,fs.label]);o.useEffect(()=>{Dt(Zt),Mn(Xt)},[Xt,Zt]),o.useEffect(()=>{if(typeof window>"u")return;const f=()=>Rs(window.innerWidth<=640);return f(),window.addEventListener("resize",f),()=>window.removeEventListener("resize",f)},[]),o.useEffect(()=>{const _=()=>{gt.current=Date.now()};window.addEventListener("pointerdown",_),window.addEventListener("keydown",_);const I=setInterval(()=>{Date.now()-gt.current>3e5&&ps(!0)},3e4);return()=>{window.removeEventListener("pointerdown",_),window.removeEventListener("keydown",_),clearInterval(I)}},[]);const pn=o.useMemo(()=>{const f=s.filter(T=>T.status==="completed").length,_=s.filter(T=>T.status==="blocked"||T.status==="failed").length,I=t.filter(T=>{var ye;return T.type==="decision_requested"&&((ye=T.metadata)==null?void 0:ye.status)==="pending"}).length;return{completed:f,blocked:_,decisions:I}},[s,t]),Yn=o.useMemo(()=>{const f=new Map;for(const _ of s)f.set(_.runId,_.title),f.set(_.id,_.title);return f},[s]),Zn=o.useMemo(()=>{const f=new Map;for(const _ of s)_.status&&(f.set(_.runId,_.status),f.set(_.id,_.status));return f},[s]),Tn=o.useMemo(()=>{var _;const f=new Map;for(const I of s){const T={status:I.status??null,phase:I.phase??null,state:I.state??null,blockerCount:Array.isArray(I.blockers)?I.blockers.length:0,blockerReason:I.blockerReason??((_=I.blockerDiagnostics)==null?void 0:_.reason)??null};f.set(I.runId,T),f.set(I.id,T)}return f},[s]),es=o.useMemo(()=>{const f=new Map;for(const _ of r){const I={status:_.status??null,blockingDecisions:Math.max(0,_.blockingDecisionCount??0),nonBlockingDecisions:Math.max(0,(_.decisionCount??0)-(_.blockingDecisionCount??0)),updatedEpoch:ls(_.updatedAt??_.lastEventAt??_.startedAt??null)},T=[_.runId,_.sliceRunId].filter(ye=>typeof ye=="string"&&ye.trim().length>0).map(ye=>ye.trim());for(const ye of T){const ve=f.get(ye);(!ve||I.updatedEpoch>=ve.updatedEpoch)&&f.set(ye,I)}}return f},[r]),Ft=o.useMemo(()=>{const f=new Map;for(const _ of s){const I=Nl(_.progress);I!==null&&(f.set(_.runId,I),f.set(_.id,I))}return f},[s]),wn=o.useMemo(()=>{const f=new Map;for(const _ of s)!_.agentId||!_.agentName||f.set(_.agentId,_.agentName);return f},[s]),an=o.useMemo(()=>{const f=new Map;for(const _ of s){const I=_.workstreamId??null;f.set(_.runId,I),f.set(_.id,I)}return f},[s]),ts=o.useMemo(()=>{const f=new Map;for(const _ of i)f.set(_.id,_.name);return f},[i]),vn=o.useMemo(()=>{const f=new Map;for(const _ of i)for(const I of _.workstreams??[])f.set(I.id,I.name);return f},[i]);o.useMemo(()=>{const f=[...s];return f.sort((_,I)=>{const T=ls(_.updatedAt??_.lastEventAt??_.startedAt??null);return ls(I.updatedAt??I.lastEventAt??I.startedAt??null)-T}),f},[s]);const D=o.useMemo(()=>t.map(f=>{const _=ta(f),I=Hp(f),T=At(f),ye=_?Tn.get(_)??null:null,ve=_?es.get(_)??null:null,Xe=Hm({sessionStatus:(ye==null?void 0:ye.status)??(_?Zn.get(_)??null:null),sessionPhase:(ye==null?void 0:ye.phase)??null,sessionState:(ye==null?void 0:ye.state)??null,sliceStatus:(ve==null?void 0:ve.status)??null,activityType:f.type,activityStatus:ct(T,["status","state","phase","lifecycle_state","lifecycleState","parsed_status","parsedStatus","run_status","runStatus"]),stopReason:ct(T,["stop_reason","stopReason"]),decisionRequired:f.decisionRequired??!1,blockingDecisionCount:Ws(T,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??(ve==null?void 0:ve.blockingDecisions)??0,nonBlockingDecisionCount:Ws(T,["non_blocking_decisions","nonBlockingDecisions","decision_count","decisionCount","decisions"])??(ve==null?void 0:ve.nonBlockingDecisions)??0,blockerCount:(ye==null?void 0:ye.blockerCount)??0,blockerReason:(ye==null?void 0:ye.blockerReason)??null}),vt=Gp(I,Xe),en=[f.title,f.description,f.summary,f.agentName,$p(T)].filter(Kt=>typeof Kt=="string"&&Kt.length>0).join(" ").toLowerCase(),yt=T==null?void 0:T.scope,ut=yt==="milestone"||yt==="workstream"?yt:void 0;return{item:f,bucket:I,userState:vt.state,userStateWhy:vt.why,canonicalProjection:Xe,runId:_,timestampEpoch:ls(f.timestamp),searchText:en,scopeGroupId:ut?_??null:null,scope:ut}}),[t,Tn,Zn,es]),he=o.useMemo(()=>{let f=0;for(const _ of D)f=Math.max(f,_.timestampEpoch);return f<=0?!1:Date.now()-f<6e4},[D]),de=o.useMemo(()=>new Set(c.filter(f=>f&&f.trim().length>0)),[c]),Ie=de.size>0,xt=o.useMemo(()=>xr.filter(f=>["live","24h","7d","all"].includes(f.id)),[]),Ye=o.useMemo(()=>{if(!Ie)return null;for(const f of de){const _=s.find(I=>I.runId===f||I.id===f);if(_)return _}return null},[Ie,de,s]),rt=o.useMemo(()=>Ie?Ye!=null&&Ye.runtimeProvider?{id:Fp(Ye.runtimeProvider)}:os(Ye==null?void 0:Ye.agentId,Ye==null?void 0:Ye.agentName,Ye==null?void 0:Ye.title,Ye==null?void 0:Ye.lastEventSummary,Ye==null?void 0:Ye.runtimeClient,l):os(),[Ye,Ie,l]),hs=o.useMemo(()=>h?os(h):os(),[h]),{filtered:bt,filteredTotal:ns,hiddenCount:kt,hiddenSyncCount:fn}=o.useMemo(()=>{const f=[];let _=0,I=0;const T=new Set,ye=O.trim().toLowerCase();for(const yt of D){const ut=yt.runId;if(Ie&&(!ut||!de.has(ut)))continue;if(d){const hn=ur(yt.item),$s=ut?an.get(ut)??null:null;if((hn??$s)!==d)continue}const Kt=fr(yt.item);if(h&&Kt.agentName!==h)continue;const ks=Oi(yt.item);if(ks){if(T.has(ks)){I+=1;continue}if(T.add(ks),!J){I+=1;continue}}else if(!J&&hr(yt.item)){I+=1;continue}if(!(ee==="completed"&&yt.userState!=="completed")&&!(ee==="needs_attention"&&yt.userState!=="needs_input"&&yt.userState!=="issue")&&!(ee==="in_progress"&&yt.userState!=="in_progress")){if(ye.length>0){const hn=ut?Yn.get(ut)??ut:"";if(!`${yt.searchText} ${hn.toLowerCase()}`.includes(ye))continue}f.length<vo?f.push(yt):_+=1}}const ve=[...f].sort((yt,ut)=>{const Kt=ut.timestampEpoch-yt.timestampEpoch;return $==="newest"?Kt:-Kt}),Xe=Math.min(Math.max(1,Math.min(wo,M)),ve.length),vt=ve.slice(0,Xe),en=ve.length+_;return{filtered:vt,filteredTotal:en,hiddenCount:Math.max(0,en-vt.length),hiddenSyncCount:I}},[ee,h,D,Ie,O,Yn,M,d,de,an,J,$]),On=o.useMemo(()=>{const f=new Map;for(const I of bt){const T=Vp(I.item.timestamp),ye=f.get(T);ye?ye.push(I):f.set(T,[I])}return Array.from(f.keys()).sort((I,T)=>{const ye=Number(T)-Number(I);return $==="newest"?ye:-ye}).map(I=>({key:I,label:Kp(I),items:f.get(I)??[]}))},[bt,$]),gs=o.useMemo(()=>On.map(f=>{const _=new Map;for(const I of f.items){const T=si(I.item).title.trim().toLowerCase(),ye=Oi(I.item),ve=ye?`${I.item.type}::sync::${ye}`:`${I.item.type}::${T}`,Xe=_.get(ve);Xe?(Xe.count+=1,Xe.firstTimestamp=Math.min(Xe.firstTimestamp,I.timestampEpoch),Xe.allItems.push(I),I.timestampEpoch>Xe.representative.timestampEpoch&&(Xe.representative=I)):_.set(ve,{key:ve,representative:I,count:1,firstTimestamp:I.timestampEpoch,allItems:[I]})}return{...f,clusters:Array.from(_.values())}}),[On]),kn=o.useCallback(f=>{Me(_=>{const I=new Set(_);return I.has(f)?I.delete(f):I.add(f),I}),R(_=>{if(Object.prototype.hasOwnProperty.call(_,f)){const I={..._};return delete I[f],I}return{..._,[f]:dr}})},[]),xs=o.useCallback((f,_)=>{R(I=>{const T=I[f]??dr,ye=Math.min(_,T+dr);return ye===T?I:{...I,[f]:ye}})},[]),Bn=o.useCallback(()=>{!w||!b||!jt||!Ct||Ct.getTime()<jt.getTime()||(w({startIso:jt.toISOString(),endIso:Ct.toISOString()}),b("custom"),_e(!1))},[Ct,jt,w,b]),Tt=o.useCallback(()=>{Dt(null),Mn(null),w==null||w({startIso:null,endIso:null}),y==="custom"&&(b==null||b("live"))},[w,b,y]),jn=o.useMemo(()=>Math.min(wo,Math.min(vo,ns)),[ns]);o.useEffect(()=>{B(Ti),Me(new Set),R({})},[ee,h,Ie,O,d,J,$,y]),o.useEffect(()=>{if(!te)return;const f=I=>{var ye;const T=I.target;T instanceof Node&&((ye=Wt.current)!=null&&ye.contains(T)||Le(!1))},_=I=>{I.key==="Escape"&&Le(!1)};return window.addEventListener("pointerdown",f),window.addEventListener("keydown",_),()=>{window.removeEventListener("pointerdown",f),window.removeEventListener("keydown",_)}},[te]),o.useEffect(()=>{if(!qe)return;const f=I=>{var ye;const T=I.target;T instanceof Node&&((ye=Cn.current)!=null&&ye.contains(T)||_e(!1))},_=I=>{I.key==="Escape"&&_e(!1)};return window.addEventListener("pointerdown",f),window.addEventListener("keydown",_),()=>{window.removeEventListener("pointerdown",f),window.removeEventListener("keydown",_)}},[qe]);const Nn=o.useRef(C);Nn.current=C;const ys=o.useRef(v);ys.current=v;const En=o.useRef(x);En.current=x,o.useEffect(()=>{const f=Qn.current,_=Rt.current;if(!f||!_)return;const I=new IntersectionObserver(T=>{var ve;if(T.some(Xe=>Xe.isIntersecting)){if(bt.length<jn){B(Xe=>Math.min(jn,Math.max(Xe,Ti)+Rp));return}ys.current&&!En.current&&((ve=Nn.current)==null||ve.call(Nn))}},{root:f,rootMargin:"0px 0px 600px 0px"});return I.observe(_),()=>I.disconnect()},[bt.length,jn]);const Qt=o.useMemo(()=>ne?bt.findIndex(f=>f.item.id===ne):-1,[ne,bt]),L=Qt>=0?bt[Qt]:null,Xs=o.useMemo(()=>{var _;const f=new Map;for(const I of a){const T=(_=I==null?void 0:I.sliceRunId)==null?void 0:_.trim();!T||f.has(T)||f.set(T,I)}return f},[a]),qn=o.useMemo(()=>{if(!L)return null;const f=L.runId??ta(L.item);return f?Xs.get(f)??null:null},[L,Xs]),zn=o.useMemo(()=>kl((L==null?void 0:L.item)??null),[L]),Ds=o.useMemo(()=>Di((L==null?void 0:L.item)??null),[L]),Vt=o.useMemo(()=>vl((L==null?void 0:L.item)??null),[L]),Un=o.useMemo(()=>Vt?null:uf((L==null?void 0:L.item)??null,t),[Vt,L,t]),Ke=o.useMemo(()=>L?Ao(L.item):null,[L]),Rn=o.useMemo(()=>Ke?Ke.executor??Ke.requester:null,[Ke]),ce=Vt??(Un==null?void 0:Un.detail)??null,Dn=o.useMemo(()=>{var f,_;return Pi((ce==null?void 0:ce.requesterAgentName)??((f=Ke==null?void 0:Ke.requester)==null?void 0:f.name)??null,(ce==null?void 0:ce.requesterAgentId)??((_=Ke==null?void 0:Ke.requester)==null?void 0:_.id)??null,wn)},[ce,Ke,wn]),on=o.useMemo(()=>qp(Dn),[Dn]),Ls=o.useMemo(()=>{var _,I;const f=Pi((ce==null?void 0:ce.agentName)??((_=Ke==null?void 0:Ke.executor)==null?void 0:_.name)??null,(ce==null?void 0:ce.agentId)??((I=Ke==null?void 0:Ke.executor)==null?void 0:I.id)??null,wn);return f==="—"?(Ke==null?void 0:Ke.primaryLabel)??"Codex":f},[ce,Ke,wn]),bs=o.useMemo(()=>L!=null&&L.runId?Ft.get(L.runId)??null:null,[L,Ft]),Ut=o.useMemo(()=>ff(ce,bs),[ce,bs]),P=o.useMemo(()=>{const f=ce;if(!f)return null;const _=f.initiativeId??(L==null?void 0:L.item.initiativeId)??null,I=_?i.find(hn=>hn.id===_)??null:null,T=f.initiativeTitle??(I==null?void 0:I.name)??null,ye=f.initiativeStatus??(I==null?void 0:I.status)??null,ve=(I==null?void 0:I.workstreams)??[],Xe=ve.length>0?ve.length:null,vt=Xe!==null?ve.filter(hn=>oi(hn.status)).length:null,en=Xe&&vt!==null?Math.round(vt/Xe*100):null,yt=f.workstreamId??null,ut=yt&&ve.length>0?ve.find(hn=>hn.id===yt)??null:null,Kt=f.workstreamTitle??(ut==null?void 0:ut.name)??(yt?vn.get(yt)??null:null),ks=f.workstreamStatus??(ut==null?void 0:ut.status)??null;return{initiativeId:_,initiativeTitle:T,initiativeStatus:ye,totalInitiativeWorkstreams:Xe,doneInitiativeWorkstreams:vt,initiativeWorkstreamPct:en,workstreamId:yt,workstreamTitle:Kt,workstreamStatus:ks,taskTitle:f.taskTitle,milestoneTitle:f.milestoneTitle,scopedTaskCount:f.taskIds.length,scopedMilestoneCount:f.milestoneIds.length,statusUpdatesApplied:f.statusUpdatesApplied,statusUpdatesBuffered:f.statusUpdatesBuffered,artifacts:f.artifacts,decisions:f.decisions,blockingDecisions:f.blockingDecisions,nonBlockingDecisions:f.nonBlockingDecisions,tokensUsed:f.tokensUsed,tokenBudget:f.tokenBudget,nextStep:f.nextStep,phase:f.phase,stopReason:f.stopReason,parsedStatus:f.parsedStatus}},[ce,L,i,vn]),Et=o.useMemo(()=>L?hf(L.item,ce,P?{decisions:P.decisions,blockingDecisions:P.blockingDecisions,nonBlockingDecisions:P.nonBlockingDecisions,stopReason:P.stopReason,parsedStatus:P.parsedStatus}:null,L.canonicalProjection??null):null,[ce,L,P]),br=o.useMemo(()=>{if(!P)return[];const f=[];Et&&f.push({label:"Status",value:Et.label}),P.scopedTaskCount>0&&f.push({label:"Tasks",value:P.scopedTaskCount}),P.scopedMilestoneCount>0&&f.push({label:"Milestones",value:P.scopedMilestoneCount});const _=P.artifacts??0;_>0&&f.push({label:"Artifacts",value:_});const I=P.decisions??0;I>0&&f.push({label:"Decisions",value:I}),P.blockingDecisions&&P.blockingDecisions>0&&f.push({label:"Blocking",value:P.blockingDecisions,tone:"critical"}),P.stopReason&&f.push({label:"Stop reason",value:tr(P.stopReason)??lt(P.stopReason)});const T=Wl(P.tokensUsed,P.tokenBudget);return T&&f.push({label:"Token usage",value:T}),f},[P,Et]),Fs=o.useMemo(()=>{const f=new Set;for(const _ of cf((L==null?void 0:L.item)??null))f.add(_);for(const _ of(ce==null?void 0:ce.decisionIds)??[])f.add(_);for(const _ of(ce==null?void 0:ce.blockingDecisionIds)??[])f.add(_);for(const _ of(ce==null?void 0:ce.nonBlockingDecisionIds)??[])f.add(_);return Array.from(f)},[ce,L]),ln=o.useMemo(()=>Y?Fs.length>0||(L==null?void 0:L.item.decisionRequired)===!0||((P==null?void 0:P.blockingDecisions)??0)>0?!0:(Et==null?void 0:Et.label)==="Needs decision":!1,[Fs,L,P,Et,Y]),wr=o.useMemo(()=>Ut?Ut.tone==="positive"?F.lime:Ut.tone==="warning"?F.amber:Ut.tone==="critical"?F.red:F.teal:F.teal,[Ut]),vr=(Ut==null?void 0:Ut.terminalStop)===!0,at=o.useMemo(()=>Yp(At((L==null?void 0:L.item)??null)),[L]),kr=o.useMemo(()=>At((L==null?void 0:L.item)??null),[L]),wt=o.useMemo(()=>sf((L==null?void 0:L.item)??null,ce),[ce,L]),Qs=o.useMemo(()=>{if(!(wt!=null&&wt.retryAt))return null;const f=new Date(wt.retryAt);if(!Number.isFinite(f.getTime()))return null;const _=f.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),I=It(wt.retryAt);return I?`${_} (${I})`:_},[wt]),Js=o.useMemo(()=>L?fr(L.item):{agentId:null,agentName:null},[L]),ss=o.useMemo(()=>_o(Ts(L==null?void 0:L.item.metadata)??void 0),[L]);o.useMemo(()=>_o(kr),[kr]);const In=o.useMemo(()=>{const f=jl((L==null?void 0:L.item)??null);return f.length>0?f:df((L==null?void 0:L.item)??null,t,new Set)},[L,t]),St=o.useMemo(()=>tf(ce,In),[ce,In]),Ys=o.useMemo(()=>St?$i(St):null,[St]),Wn=o.useMemo(()=>L?L.userState==="in_progress"?!0:Ut?Ut.terminalStop!==!0:!1:!1,[Ut,L]),Zs=o.useMemo(()=>{if(In.length===0)return null;const f=In[0];return f?$i(f.path):null},[In]),m=o.useMemo(()=>{const f=Lt(nt);if(f)return f;const _=Co((L==null?void 0:L.item)??null);return _||(Lt(L==null?void 0:L.item.summary)??Lt(L==null?void 0:L.item.description))},[nt,L]),A=o.useMemo(()=>L?hr(L.item):!1,[L]),E=o.useMemo(()=>{if(!ce||!L)return null;const f=ce.initiativeId??L.item.initiativeId??null,_=ce.workstreamId??ur(L.item);if(!f||!_)return null;const I=Sn((P==null?void 0:P.parsedStatus)??ce.parsedStatus),T=Sn((P==null?void 0:P.stopReason)??ce.stopReason),ye=Math.max(0,(P==null?void 0:P.blockingDecisions)??ce.blockingDecisions??(L.item.decisionRequired?1:0)),ve=Math.max(0,(P==null?void 0:P.nonBlockingDecisions)??ce.nonBlockingDecisions??0),Xe=I==="blocked"||I==="error"||I==="failed"||T==="blocked"||T==="error"||L.item.type==="blocker_created",vt=!Xe&&ye===0&&ve>0&&(I==="needs_decision"||I==="completed"||T==="completed");return!Xe&&!vt?null:{initiativeId:f,workstreamId:_,runId:L.runId??null,event:ce.event,requestedByAgentId:ce.requesterAgentId??L.item.requesterAgentId??null,requestedByAgentName:ce.requesterAgentName??L.item.requesterAgentName??null,actionLabel:Xe?"Auto-fix in 10s":"Auto-continue in 10s",helperText:Xe?"Pause this workstream within 10 seconds to cancel the auto-fix.":"Optional decision captured. Slice will continue automatically after the grace window.",isBlockedFlow:Xe}},[ce,L,P]),N=o.useCallback(()=>{fe(null)},[]),Q=o.useCallback(async(f,_)=>{if(_){He(null),Be(f);try{await _()}catch(I){He(I instanceof Error?I.message:"Action failed")}finally{Be(I=>I===f?null:I)}}},[]),Ne=o.useCallback(async()=>{var f;if(!(!E||st)){Ve(!0),Qe(null);try{const _=await fetch("/orgx/api/mission-control/activity/auto-fix",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({initiativeId:E.initiativeId,workstreamId:E.workstreamId,runId:E.runId,event:E.event,requestedByAgentId:E.requestedByAgentId,requestedByAgentName:E.requestedByAgentName,graceMs:1e4})}),I=await _.json().catch(()=>null);if(!_.ok||(I==null?void 0:I.ok)!==!0)throw new Error((I==null?void 0:I.error)||`Request failed (${_.status})`);const T=(f=I==null?void 0:I.scheduled)!=null&&f.dueAt?new Date(I.scheduled.dueAt):null,ye=T&&Number.isFinite(T.getTime())?T.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):null;Qe(ye?`Scheduled. Auto action starts by ${ye} unless you pause first.`:"Scheduled. Auto action starts in 10s unless you pause first.")}catch(_){const I=_ instanceof Error?_.message:"Failed to schedule auto-fix";Qe(bn(I)||I)}finally{Ve(!1)}}},[E,st]);o.useEffect(()=>{if(!ne||!St){rn(T=>T.status==="idle"&&T.path===null?T:{status:"idle",path:null,text:"",lineCount:0,truncated:!1,updatedAt:null,error:null});return}let f=!1;const _=async()=>{rn(T=>({status:T.status==="ready"&&T.path===St?"ready":"loading",path:St,text:T.path===St?T.text:"",lineCount:T.path===St?T.lineCount:0,truncated:T.path===St?T.truncated:!1,updatedAt:T.path===St?T.updatedAt:null,error:null}));try{const T=new URLSearchParams({path:St,lines:String(Dp)}),ye=await fetch(`/orgx/api/live/terminal/tail?${T.toString()}`,{method:"GET"}),ve=await ye.json().catch(()=>null);if(!ye.ok||(ve==null?void 0:ve.ok)!==!0){const en=`Failed to load CLI output (${ye.status}).`;throw new Error(typeof(ve==null?void 0:ve.error)=="string"&&ve.error.trim().length>0?ve.error:en)}if(f)return;const Xe=typeof ve.text=="string"?ve.text:"",vt=typeof ve.line_count=="number"&&Number.isFinite(ve.line_count)?Math.max(0,Math.floor(ve.line_count)):Xe.length>0?Xe.split(`
212
+ `).length:0;rn({status:"ready",path:typeof ve.path=="string"&&ve.path.trim().length>0?ve.path.trim():St,text:Xe,lineCount:vt,truncated:ve.truncated===!0,updatedAt:typeof ve.updated_at=="string"&&ve.updated_at.trim().length>0?ve.updated_at:null,error:null})}catch(T){if(f)return;const ye=T instanceof Error?T.message:"Failed to load CLI output.";rn(ve=>({status:"error",path:St,text:ve.path===St?ve.text:"",lineCount:ve.path===St?ve.lineCount:0,truncated:ve.path===St?ve.truncated:!1,updatedAt:ve.path===St?ve.updatedAt:null,error:bn(ye)||ye}))}};if(_(),!Wn)return()=>{f=!0};const I=window.setInterval(()=>{_()},Lp);return()=>{f=!0,window.clearInterval(I)}},[St,Wn,ne,Mt]),o.useEffect(()=>{if(!De)return;const f=window.setTimeout(()=>et(null),2e3);return()=>window.clearTimeout(f)},[De]),o.useEffect(()=>{He(null)},[ee,O,y]),o.useEffect(()=>{if(!K){$n.current=null;return}const f=K.trim();!f||$n.current===f||!t.some(I=>I.id===f)||($n.current=f,z(!1),q("all"),oe(""),We(1),fe(f),me==null||me(f))},[t,me,K]);const ze=o.useCallback(async(f,_)=>{if(_)try{await navigator.clipboard.writeText(_),et(`${f} copied`)}catch{et("Copy failed")}},[]),Ue=o.useCallback(()=>{Yt(f=>f+1)},[]);o.useEffect(()=>{ot("structured"),Re(!1),Ve(!1),Qe(null)},[ne]),o.useEffect(()=>{we(null),je("feed");const f=bf((L==null?void 0:L.item)??null);if(!f||$t())return;const _=new URLSearchParams({turnId:f.turnId});f.sessionKey&&_.set("sessionKey",f.sessionKey),f.runId&&_.set("run",f.runId);const I=new AbortController;return fetch(`/orgx/api/live/activity/detail?${_.toString()}`,{method:"GET",signal:I.signal}).then(async T=>{var ve;return T.ok?((ve=(await T.json()).detail)==null?void 0:ve.summary)??null:(T.status===404&&je("missing"),null)}).then(T=>{typeof T=="string"&&T.trim().length>0?(we(T),je("local")):je("missing")}).catch(T=>{T instanceof DOMException&&T.name==="AbortError"||je("missing")}),()=>I.abort()},[L]),o.useEffect(()=>{Oe(null),se(null);const f=L==null?void 0:L.item;if(!f||Ce)return;const _=(nt??f.summary??f.description??f.title??"").trim();if(!_||$t())return;const I=new AbortController;return fetch("/orgx/api/live/activity/headline",{method:"POST",headers:{"Content-Type":"application/json"},signal:I.signal,body:JSON.stringify({text:_,title:f.title??null,type:f.type})}).then(async T=>T.ok?await T.json():((T.status===404||T.status===405)&&$e(!0),null)).then(T=>{const ye=T==null?void 0:T.headline;typeof ye=="string"&&ye.trim().length>0&&($e(!1),Oe(ye.trim()),se((T==null?void 0:T.source)??null))}).catch(T=>{T instanceof DOMException&&T.name}),()=>I.abort()},[L,nt,Ce]);const Ze=o.useCallback(f=>{var T;if(bt.length===0)return;const I=((Qt>=0?Qt:0)+f+bt.length)%bt.length;We(f),fe(((T=bt[I])==null?void 0:T.item.id)??null)},[Qt,bt]);o.useEffect(()=>{ne&&(Qt>=0||fe(null))},[Qt,ne]),o.useEffect(()=>{if(!ne)return;const f=_=>{_.key==="ArrowRight"||_.key.toLowerCase()==="l"?(_.preventDefault(),Ze(1)):(_.key==="ArrowLeft"||_.key.toLowerCase()==="h")&&(_.preventDefault(),Ze(-1))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[ne,Ze]);const dt=de.size===1,Nt=dt?[...de][0]:null,li=Nt?s.find(f=>f.runId===Nt||f.id===Nt)??null:null,ws=o.useMemo(()=>{if(!dt)return[];const f=[],_=new Set;for(const I of D){if(!I.runId||!de.has(I.runId))continue;const T=Oi(I.item);if(T){if(_.has(T)||(_.add(T),!J))continue}else if(!J&&hr(I.item))continue;f.push(I.item)}return f},[dt,D,de,J]),vs=!le&&bt.length<=160,Ln=(f,_,I)=>{const T=f.item,ye=I??T.id,ve=fr(T),Xe=Ao(T),vt=Xe.executor??Xe.requester,en=Pi(sn((vt==null?void 0:vt.name)??Xe.primaryLabel??T.agentName??ve.agentName??null),sn((vt==null?void 0:vt.id)??T.agentId??ve.agentId??null),wn)||"OrgX",yt=Fi(f.userState),ut=$==="newest"&&_<2,Kt=f.runId,ks=Co(T),{title:hn}=si(T),$s=ks??Lt(T.summary),jr=Lt(T.description),ha=To(T,$s??jr??null),ga=T.initiativeId?ts.get(T.initiativeId)??lt(T.initiativeId):null,ci=ur(T)??(Kt?an.get(Kt)??null:null),xa=ci?vn.get(ci)??lt(ci):null,Al=[ga,xa].filter(Boolean).join(" > ")||ga||xa||lt(T.type),Sl=Li(f.userState),_l=new Date(T.timestamp).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),Cl=It(T.timestamp),Ml=f.bucket==="artifact"?Zp(T):null;return n.jsx(op,{renderKey:ye,displayTitle:hn,headline:ha,contextLabel:Al,detailText:($s??jr)!==ha?$s??jr:null,displayAgentName:en,railColor:yt,userStateLabel:Sl,userStateWhy:f.userStateWhy,relativeTime:Cl,timeLabel:_l,isRecent:ut,enableMotion:vs,onOpen:()=>{We(1),fe(T.id)},ariaLabel:`Open activity details for ${hn||ti(T.type)}`,artifactSnippet:Ml},ye)};return n.jsx(kp,{sessions:s,initiatives:i??[],workspaceId:Se??null,query:O,statusFilter:ee,sortOrder:$,timeFilterId:y,customTimeRange:p,snapshot:Ae,onRequestRefresh:xe,children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[dt&&ws.length>0?n.jsx(rp,{items:ws,session:li,agentName:((fa=ws[0])==null?void 0:fa.agentName)??null,onBack:j,onOpenItem:f=>{We(1),fe(f.id)}}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"border-b border-subtle px-4 py-3.5",children:n.jsxs("div",{className:"flex flex-col gap-2.5",children:[n.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2.5",children:[n.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[n.jsx("h2",{className:"text-heading font-semibold text-white",children:"Activity"}),n.jsx("span",{className:"rounded-full border border-strong bg-white/[0.05] px-2 py-0.5 text-micro text-primary tabular-nums",children:ns}),kt>0&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-micro text-secondary tabular-nums",children:["+",kt," hidden"]}),fn>0&&!J&&n.jsxs("button",{type:"button",onClick:()=>V(!0),className:"rounded-full border border-white/[0.14] bg-white/[0.03] px-2 py-0.5 text-micro text-secondary tabular-nums transition-colors hover:bg-white/[0.08] hover:text-primary",title:"Show low-signal sync replay events",children:[fn," sync hidden"]}),J&&n.jsx("button",{type:"button",onClick:()=>V(!1),className:"rounded-full border border-lime/30 bg-lime/[0.10] px-2 py-0.5 text-micro text-[#E1FFB2] transition-colors hover:bg-lime/[0.16]",title:"Hide low-signal sync replay events",children:"Sync visible"}),n.jsxs("div",{className:"relative",ref:Cn,children:[n.jsxs("button",{type:"button",onClick:()=>{_e(f=>!f),Le(!1)},"aria-haspopup":"menu","aria-expanded":qe,className:pe("inline-flex h-7 items-center gap-1.5 rounded-full border px-2.5 text-micro font-semibold transition-colors",qe?"border-lime/30 bg-lime/[0.10] text-[#E1FFB2]":"border-white/[0.14] bg-white/[0.03] text-secondary hover:bg-white/[0.08] hover:text-primary"),children:[n.jsx("span",{className:"max-w-[240px] truncate",children:Jn}),n.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",className:pe("transition-transform duration-200",qe&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(pt,{children:qe&&n.jsx(be.div,{initial:{opacity:0,y:-6,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.98},transition:{duration:.18,ease:[.22,1,.36,1]},className:"absolute left-0 z-30 mt-2 w-[min(92vw,380px)] rounded-xl border border-white/[0.12] bg-[#0A0D14]/95 p-3 shadow-[0_12px_40px_rgba(0,0,0,0.45)] backdrop-blur-xl",role:"menu","aria-label":"Activity time range",children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Presets"}),n.jsx("div",{className:"flex flex-wrap gap-1",children:xr.filter(f=>f.id!=="custom").map(f=>{const _=y===f.id;return n.jsx("button",{type:"button",onClick:()=>{b==null||b(f.id),_e(!1)},className:pe("rounded-full border px-2.5 py-1 text-micro font-semibold transition-colors",_?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:f.label},f.id)})})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] p-2.5",children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Custom range"}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("label",{className:"block text-micro uppercase tracking-[0.06em] text-secondary",children:"Start"}),Pn?n.jsx("input",{type:"datetime-local",step:300,value:Ei(jt),onChange:f=>Dt(jo(f.target.value)),className:"orgx-datepicker-input w-full rounded-lg border border-white/[0.12] bg-black/30 px-2.5 py-1.5 text-caption text-primary outline-none transition-colors focus:border-lime/35"}):n.jsx(ya,{selected:jt,onChange:f=>Dt(f instanceof Date?f:null),selectsStart:!0,startDate:jt,endDate:Ct,showTimeSelect:!0,timeIntervals:5,dateFormat:"MMM d, yyyy h:mm aa",className:"orgx-datepicker-input w-full rounded-lg border border-white/[0.12] bg-black/30 px-2.5 py-1.5 text-caption text-primary outline-none transition-colors focus:border-lime/35",calendarClassName:"orgx-datepicker",popperClassName:"orgx-datepicker-popper",popperPlacement:"bottom-start",showPopperArrow:!1}),n.jsx("label",{className:"block text-micro uppercase tracking-[0.06em] text-secondary",children:"End"}),Pn?n.jsx("input",{type:"datetime-local",step:300,min:Ei(jt),value:Ei(Ct),onChange:f=>Mn(jo(f.target.value)),className:"orgx-datepicker-input w-full rounded-lg border border-white/[0.12] bg-black/30 px-2.5 py-1.5 text-caption text-primary outline-none transition-colors focus:border-lime/35"}):n.jsx(ya,{selected:Ct,onChange:f=>Mn(f instanceof Date?f:null),selectsEnd:!0,minDate:jt??void 0,startDate:jt,endDate:Ct,showTimeSelect:!0,timeIntervals:5,dateFormat:"MMM d, yyyy h:mm aa",className:"orgx-datepicker-input w-full rounded-lg border border-white/[0.12] bg-black/30 px-2.5 py-1.5 text-caption text-primary outline-none transition-colors focus:border-lime/35",calendarClassName:"orgx-datepicker",popperClassName:"orgx-datepicker-popper",popperPlacement:"bottom-start",showPopperArrow:!1})]}),n.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-micro text-secondary",children:Ht?`${Fr(jt)} - ${Fr(Ct)}`:"Pick start and end to apply"}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:Tt,className:"rounded-full border border-white/[0.14] bg-white/[0.03] px-2.5 py-1 text-micro font-semibold text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:"Clear"}),n.jsx("button",{type:"button",onClick:Bn,disabled:!Ht,className:"rounded-full border border-lime/30 bg-lime/[0.14] px-2.5 py-1 text-micro font-semibold text-[#E1FFB2] transition-colors hover:bg-lime/[0.2] disabled:opacity-45",children:"Apply"})]})]})]})]})})})]}),n.jsx("span",{className:pe("h-1.5 w-1.5 flex-shrink-0 rounded-full",he&&"pulse-soft"),style:{backgroundColor:F.lime},"aria-label":"Live",title:he?"New activity within the last minute":"Live activity feed"})]}),n.jsx("div",{className:"flex w-full items-center gap-2 md:w-[320px]",children:n.jsxs("div",{className:"relative min-w-0 flex-1",children:[n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-muted",children:[n.jsx("circle",{cx:"11",cy:"11",r:"7"}),n.jsx("path",{d:"m20 20-3.5-3.5"})]}),n.jsx("input",{value:O,onChange:f=>oe(f.target.value),placeholder:"Search activity...",className:"w-full rounded-lg border border-white/[0.08] bg-white/[0.03] py-2 pl-9 pr-2 text-body text-primary placeholder:text-muted transition-colors focus:border-[#BFFF00]/30 focus:outline-none","aria-label":"Search activity"})]})})]}),n.jsx("div",{className:"flex items-center gap-2 overflow-x-auto pb-0.5 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[(Ie||d||h)&&n.jsxs(n.Fragment,{children:[Ie&&n.jsxs("button",{onClick:j,className:"chip chip-avatar inline-flex min-w-0 items-center","aria-label":"Clear session filter",children:[ko(rt.id)?n.jsx(Vs,{provider:rt.id,size:"xs"}):n.jsx(Ot,{name:(Ye==null?void 0:Ye.agentName)??"OrgX",hint:l??null,size:"xs"}),n.jsxs("span",{className:"min-w-0 truncate",children:["Session",l?`: ${l}`:""]}),n.jsx("span",{className:"ml-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro text-secondary",children:"×"})]}),d&&n.jsxs("button",{onClick:g,className:"chip inline-flex min-w-0 items-center gap-2",style:{borderColor:"rgba(191,255,0,0.28)",color:"#D8FFA1"},"aria-label":"Clear workstream filter",children:[n.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro",children:"↳"}),n.jsxs("span",{className:"min-w-0 truncate",children:["Workstream",u?`: ${u}`:""]}),n.jsx("span",{className:"ml-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro text-secondary",children:"×"})]}),h&&n.jsxs("button",{onClick:S,className:"chip chip-avatar inline-flex min-w-0 items-center",style:{borderColor:"rgba(10,212,196,0.3)",color:"#0AD4C4"},"aria-label":"Clear agent filter",children:[ko(hs.id)?n.jsx(Vs,{provider:hs.id,size:"xs"}):n.jsx(Ot,{name:h,hint:h,size:"xs"}),n.jsxs("span",{className:"min-w-0 truncate",children:["Agent: ",h]}),n.jsx("span",{className:"ml-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro text-secondary",children:"×"})]})]}),n.jsx("div",{className:"inline-flex flex-shrink-0 items-center gap-1 rounded-full border border-white/[0.08] bg-white/[0.02] p-0.5",role:"group","aria-label":"Activity status filters",children:Object.keys(Dr).map(f=>{const _=ee===f;return n.jsx("button",{type:"button",onClick:()=>q(f),"aria-pressed":_,className:pe("rounded-full px-3 py-1.5 text-micro font-semibold transition-colors",_?"border border-lime/25 bg-lime/[0.10] text-[#E1FFB2]":"border border-transparent text-secondary hover:bg-white/[0.08] hover:text-bright"),children:Dr[f]},f)})}),n.jsx("button",{type:"button",onClick:()=>z(f=>!f),className:pe("inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full border bg-white/[0.03] text-muted transition-colors hover:bg-white/[0.08] hover:text-primary",k?"border-lime/30 text-lime":"border-white/[0.1]"),"aria-pressed":k,"aria-label":k?"Expand activity density":"Compact activity density",title:k?"Expand activity density":"Compact activity density",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",children:[n.jsx("path",{d:"M4 7h16"}),n.jsx("path",{d:k?"M4 12h16":"M4 12h10"}),n.jsx("path",{d:"M4 17h16"})]})}),n.jsxs("div",{className:"relative flex-shrink-0",ref:Wt,children:[n.jsxs("button",{type:"button",onClick:()=>{Le(f=>!f),_e(!1)},"aria-haspopup":"menu","aria-expanded":te,"aria-label":"Activity filters",title:"Activity filters",className:pe("inline-flex h-8 items-center gap-1.5 rounded-full border px-2.5 text-caption font-semibold transition-colors",te?"border-lime/30 bg-lime/[0.10] text-[#E1FFB2]":"border-white/[0.1] bg-white/[0.03] text-primary hover:bg-white/[0.08]"),children:[n.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M4 6h16"}),n.jsx("path",{d:"M7 12h10"}),n.jsx("path",{d:"M10 18h4"})]}),n.jsx("span",{className:"hidden sm:inline",children:"Filters"}),n.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",className:pe("transition-transform duration-200",te&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(pt,{children:te&&n.jsx(be.div,{initial:{opacity:0,y:-6,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.98},transition:{duration:.18,ease:[.22,1,.36,1]},className:"absolute right-0 z-20 mt-2 w-[290px] rounded-xl border border-white/[0.12] bg-[#0A0D14]/95 p-3 shadow-[0_12px_40px_rgba(0,0,0,0.45)] backdrop-blur-xl",role:"menu","aria-label":"Activity view controls",children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Sort"}),n.jsx("div",{className:"grid grid-cols-2 gap-1",children:[{id:"newest",label:"Newest"},{id:"oldest",label:"Oldest"}].map(f=>n.jsx("button",{type:"button",onClick:()=>{X(f.id),Le(!1)},className:pe("rounded-lg border px-2 py-1.5 text-caption font-medium transition-colors",$===f.id?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:f.label},f.id))})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Time window"}),n.jsx("p",{className:"mt-1 text-caption text-secondary",children:"Use the time dropdown beside Activity count for presets and custom date/time ranges."})]}),n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Status"}),n.jsx("div",{className:"grid grid-cols-2 gap-1",children:Object.keys(Dr).map(f=>{const _=ee===f;return n.jsx("button",{type:"button",onClick:()=>{q(f),Le(!1)},className:pe("rounded-lg border px-2 py-1.5 text-caption font-medium transition-colors",_?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:Dr[f]},f)})})]}),n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Signal"}),n.jsx("button",{type:"button",onClick:()=>{V(f=>!f)},className:pe("w-full rounded-lg border px-2.5 py-2 text-left text-caption transition-colors",J?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:J?"Hide sync replay events":"Show sync replay events"}),n.jsx("p",{className:"mt-1 text-micro leading-relaxed text-muted",children:"Changeset replay and outbox sync events are low-signal operational noise for most users."})]})]})})})]})]})})]})}),n.jsxs("div",{ref:Qn,className:"flex-1 overflow-y-auto overscroll-y-contain scroll-smooth px-4 py-3 pb-24",children:[bt.length===0&&n.jsx("div",{className:"rounded-xl border border-subtle bg-white/[0.02] px-4 py-5",children:n.jsxs("div",{className:"mx-auto max-w-2xl",children:[n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx("span",{className:"mt-0.5 inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full border border-white/[0.1] bg-white/[0.04] text-secondary",children:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"22 12 18 12 15 21 9 3 6 12 2 12"})})}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"text-body font-semibold text-primary",children:re?"Syncing activity feed...":Ie?"No activity yet for this session":d?"No activity yet for this workstream":"No matching activity right now."}),n.jsx("p",{className:"mt-1 text-caption leading-relaxed text-secondary",children:re?"Live updates usually appear within a few seconds after dispatch.":`Try widening the time window (${Jn}), changing filters, or launch the next workstream.`})]})]}),n.jsx("div",{className:"mt-3 flex flex-wrap items-center gap-1.5",children:xt.map(f=>{const _=y===f.id;return n.jsx("button",{type:"button",onClick:()=>b==null?void 0:b(f.id),className:pe("rounded-full border px-2.5 py-1 text-caption font-semibold transition-colors",_?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":"border-white/[0.1] bg-white/[0.03] text-secondary hover:bg-white/[0.08] hover:text-primary"),children:f.label},`empty-time-${f.id}`)})}),n.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[(Ie||d||h)&&n.jsx("button",{type:"button",onClick:()=>{Ie&&j(),d&&(g==null||g()),h&&(S==null||S())},className:"rounded-full border border-strong bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-primary transition hover:bg-white/[0.08]",children:"Clear filters"}),ge&&n.jsx("button",{type:"button",onClick:()=>void Q("play",ge),disabled:Pe!==null,className:"rounded-full border border-[#BFFF00]/28 bg-[#BFFF00]/12 px-3 py-1.5 text-caption font-semibold text-[#D8FFA1] transition hover:bg-[#BFFF00]/18 disabled:opacity-45",children:Pe==="play"?"Starting...":"Start next session"}),!ge&&Fe&&n.jsx("button",{type:"button",onClick:Fe,className:"rounded-full border border-[#BFFF00]/28 bg-[#BFFF00]/12 px-3 py-1.5 text-caption font-semibold text-[#D8FFA1] transition hover:bg-[#BFFF00]/18",children:"Browse initiatives"})]}),Te&&n.jsx("p",{className:"mt-2 text-caption text-amber-200/80",children:Te})]})}),n.jsx(ip,{completedCount:pn.completed,decisionsCount:pn.decisions,blockerCount:pn.blocked,visible:_n,onDismiss:()=>{ps(!1),gt.current=Date.now()}}),bt.length>0&&n.jsxs("div",{className:"space-y-4",children:[gs.map(f=>{const _=k?f.clusters.slice(0,4):f.clusters;return n.jsxs("section",{children:[n.jsx("h3",{className:"mb-2.5 border-b border-subtle pb-1.5 text-caption font-semibold tracking-[0.01em] text-muted",children:f.label}),vs?n.jsx(pt,{mode:"popLayout",children:n.jsx("div",{className:"space-y-2",children:_.map((I,T)=>{const ye=ie.has(I.key),ve=I.allItems.slice(1),Xe=ve.length,vt=Math.min(Xe,ue[I.key]??dr),en=ve.slice(0,vt);if(I.count===1)return Ln(I.representative,T);const yt=`cluster:${I.key}`;return n.jsxs("div",{children:[Ln(I.representative,T,yt),n.jsxs("button",{type:"button",onClick:ut=>{ut.stopPropagation(),kn(I.key)},className:"mt-1 ml-8 inline-flex items-center gap-1.5 rounded-full border border-white/[0.1] bg-white/[0.03] px-2.5 py-1 text-micro text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:[n.jsxs("span",{className:"font-semibold",children:["×",I.count]}),n.jsx("span",{className:"text-muted",children:"·"}),n.jsx("span",{children:ye?"hide":`and ${I.count-1} similar`}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:pe("transition-transform",ye?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),ye&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[en.map((ut,Kt)=>Ln(ut,T+Kt+1)),vt<Xe&&n.jsxs("button",{type:"button",onClick:ut=>{ut.stopPropagation(),xs(I.key,Xe)},className:"rounded-full border border-strong bg-white/[0.03] px-2.5 py-1 text-micro text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:["Load more (",Xe-vt," remaining)"]})]})]},I.key)})})}):n.jsx("div",{className:"space-y-2",children:_.map((I,T)=>{const ye=ie.has(I.key),ve=I.allItems.slice(1),Xe=ve.length,vt=Math.min(Xe,ue[I.key]??dr),en=ve.slice(0,vt);if(I.count===1)return Ln(I.representative,T);const yt=`cluster:${I.key}`;return n.jsxs("div",{children:[Ln(I.representative,T,yt),n.jsxs("button",{type:"button",onClick:ut=>{ut.stopPropagation(),kn(I.key)},className:"mt-1 ml-8 inline-flex items-center gap-1.5 rounded-full border border-white/[0.1] bg-white/[0.03] px-2.5 py-1 text-micro text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:[n.jsxs("span",{className:"font-semibold",children:["×",I.count]}),n.jsx("span",{className:"text-muted",children:"·"}),n.jsx("span",{children:ye?"hide":`and ${I.count-1} similar`}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:pe("transition-transform",ye?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),ye&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[en.map((ut,Kt)=>Ln(ut,T+Kt+1)),vt<Xe&&n.jsxs("button",{type:"button",onClick:ut=>{ut.stopPropagation(),xs(I.key,Xe)},className:"rounded-full border border-strong bg-white/[0.03] px-2.5 py-1 text-micro text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:["Load more (",Xe-vt," remaining)"]})]})]},I.key)})}),k&&f.clusters.length>_.length&&n.jsxs("p",{className:"mt-1.5 text-caption text-muted",children:["+",f.clusters.length-_.length," more"]})]},f.key)}),n.jsx("div",{ref:Rt,className:"pointer-events-none h-px","aria-hidden":!0}),n.jsx("div",{className:pe("flex items-center justify-center py-6 transition-opacity duration-500 ease-out",x?"opacity-100":v?"opacity-0":"opacity-0 pointer-events-none"),children:n.jsx("div",{className:"flex items-center gap-2.5",children:n.jsxs("div",{className:"flex gap-1","aria-label":"Loading older events",children:[n.jsx("span",{className:"h-1 w-1 rounded-full bg-[#BFFF00]/70 animate-[pulse_1.4s_ease-in-out_infinite]"}),n.jsx("span",{className:"h-1 w-1 rounded-full bg-[#BFFF00]/50 animate-[pulse_1.4s_ease-in-out_0.2s_infinite]"}),n.jsx("span",{className:"h-1 w-1 rounded-full bg-[#BFFF00]/30 animate-[pulse_1.4s_ease-in-out_0.4s_infinite]"})]})})}),!v&&!x&&bt.length>0&&n.jsx("p",{className:"pb-4 text-center text-micro tracking-wide text-muted/50",children:kt>0?`${bt.length} of ${ns} events`:"You’ve reached the beginning"})]})]})]}),n.jsx(Ep,{}),n.jsx(lp,{open:L!==null,onClose:N,children:L&&n.jsxs("div",{className:"relative flex h-[100dvh] w-full min-h-0 flex-col sm:h-[86vh] sm:max-h-[86vh]",children:[n.jsx("div",{className:"absolute inset-x-0 top-0 h-20 bg-gradient-to-b from-lime/10 via-cyan/5 to-transparent"}),n.jsxs("div",{className:"relative z-10 flex items-center justify-between border-b border-subtle px-5 py-3 sm:px-6",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("span",{className:"h-2.5 w-2.5 flex-shrink-0 rounded-full",style:{backgroundColor:Fi(L.userState),boxShadow:`0 0 12px ${Fi(L.userState)}55`}}),n.jsxs("span",{className:"text-caption text-secondary",children:[Li(L.userState)," · ",Qt+1,"/",bt.length]}),De&&n.jsx(gn,{tone:"neutral",className:"text-micro font-semibold tracking-[0.02em]",children:De})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[L.runId&&W&&n.jsx("button",{type:"button",onClick:()=>{W(L.runId),N()},className:"rounded-full border border-lime/25 bg-lime/10 px-3 py-1 text-caption font-semibold text-lime transition hover:bg-lime/20",children:"Focus session"}),n.jsx("button",{type:"button",onClick:()=>Ze(-1),className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-primary transition hover:bg-white/[0.1]","aria-label":"Previous activity item",children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m15 18-6-6 6-6"})})}),n.jsx("button",{type:"button",onClick:()=>Ze(1),className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-primary transition hover:bg-white/[0.1]","aria-label":"Next activity item",children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m9 18 6-6-6-6"})})}),n.jsxs("div",{className:"relative",children:[n.jsx("button",{type:"button",onClick:()=>Re(f=>!f),className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-secondary transition hover:bg-white/[0.1] hover:text-primary","aria-label":"More actions",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",children:[n.jsx("circle",{cx:"12",cy:"5",r:"1.5"}),n.jsx("circle",{cx:"12",cy:"12",r:"1.5"}),n.jsx("circle",{cx:"12",cy:"19",r:"1.5"})]})}),tt&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-30",onClick:()=>Re(!1)}),n.jsxs("div",{className:"absolute right-0 top-full z-40 mt-1 min-w-[160px] rounded-lg border border-strong bg-[#0d0f16] py-1 shadow-xl",children:[L.runId&&n.jsx("button",{type:"button",onClick:()=>{ze("Run id",L.runId??""),Re(!1)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-caption text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:"Copy run ID"}),Js.agentId&&n.jsx("button",{type:"button",onClick:()=>{ze("Agent id",Js.agentId??""),Re(!1)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-caption text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:"Copy agent ID"}),n.jsx("button",{type:"button",onClick:()=>{ze("Event id",L.item.id),Re(!1)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-caption text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:"Copy event ID"})]})]})]}),n.jsx("button",{type:"button",onClick:N,className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-secondary transition hover:bg-white/[0.1] hover:text-primary","aria-label":"Close activity detail",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6L6 18"}),n.jsx("path",{d:"M6 6l12 12"})]})})]})]}),n.jsx("div",{className:"relative min-h-0 flex-1 overflow-x-hidden overflow-y-auto px-5 pb-5 pt-4 sm:px-6",children:n.jsx(pt,{mode:"wait",custom:Je,children:n.jsx(be.section,{custom:Je,initial:{opacity:0,x:Je*44,scale:.985},animate:{opacity:1,x:0,scale:1},exit:{opacity:0,x:Je*-32,scale:.985},transition:{duration:.28,ease:[.16,1,.3,1]},className:"min-h-full w-full overscroll-contain",children:n.jsxs("div",{className:"space-y-6 pb-1",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-title font-semibold tracking-[-0.02em] text-white whitespace-pre-wrap break-words",children:H||To(L.item,nt)||lt(L.item.title||ti(L.item.type))}),n.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-2 text-body text-secondary",children:[new Date(L.item.timestamp).toLocaleString()," · ",It(L.item.timestamp),U==="llm"&&n.jsx("span",{className:"text-muted",children:"· AI title"})]}),n.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2 text-caption",children:[(()=>{const f=(ce==null?void 0:ce.workstreamId)??ur(L.item)??(L.runId?an.get(L.runId)??null:null),_=f?vn.get(f)??lt(f):null,T=[(ce==null?void 0:ce.initiativeTitle)??(L.item.initiativeId?ts.get(L.item.initiativeId)??null:null),_].filter(Boolean).join(" > ");return T?n.jsx(gn,{tone:"muted",className:"max-w-full",children:n.jsx("span",{className:"truncate",children:T})}):null})(),n.jsx(gn,{tone:"neutral",className:"font-semibold tracking-[0.02em]",children:Li(L.userState)}),n.jsxs(gn,{tone:"muted",children:[n.jsx(Ot,{name:(Rn==null?void 0:Rn.label)??(Ke==null?void 0:Ke.primaryLabel)??"OrgX",hint:Rn?Ri(Rn):(Ke==null?void 0:Ke.primaryLabel)??"OrgX",size:"xs"}),n.jsx("span",{children:(Rn==null?void 0:Rn.label)??(Ke==null?void 0:Ke.primaryLabel)??"OrgX"})]}),A&&n.jsx(gn,{tone:"lime",children:"Sync replay"})]})]}),n.jsx(up,{item:L.item}),zn&&n.jsxs("div",{className:"rounded-xl border border-cyan-400/25 bg-gradient-to-b from-cyan-500/[0.10] to-cyan-500/[0.04]",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 px-4 pt-3.5 pb-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#67e8f9",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"flex-shrink-0",children:[n.jsx("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),n.jsx("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"})]}),n.jsx("span",{className:"text-micro font-semibold uppercase tracking-wider text-cyan-200/80",children:zn.source==="metadata"?"Artifact":lt(zn.source)})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("div",{className:"inline-flex rounded-full border border-cyan-400/20 bg-black/30 p-0.5 text-caption",children:[n.jsx("button",{type:"button",onClick:()=>ot("structured"),"aria-pressed":ft==="structured",className:`rounded-full px-2.5 py-0.5 transition-colors ${ft==="structured"?"bg-cyan-500/[0.25] text-cyan-100":"text-cyan-300/50 hover:text-cyan-200"}`,children:"Structured"}),n.jsx("button",{type:"button",onClick:()=>ot("json"),"aria-pressed":ft==="json",className:`rounded-full px-2.5 py-0.5 transition-colors ${ft==="json"?"bg-cyan-500/[0.25] text-cyan-100":"text-cyan-300/50 hover:text-cyan-200"}`,children:"JSON"})]}),Ds&&n.jsx("button",{type:"button",onClick:()=>Ee(Ds),className:"rounded-full border border-cyan-400/25 bg-cyan-500/[0.12] px-2.5 py-0.5 text-caption font-semibold text-cyan-100 transition hover:bg-cyan-500/[0.2]",children:"Open full artifact"})]})]}),n.jsx("div",{className:"max-h-[320px] overflow-y-auto px-4 pb-4",children:n.jsx("div",{className:"rounded-lg border border-white/[0.06] bg-black/20 p-3.5",children:ft==="structured"?Il(zn.value):n.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap font-mono text-caption leading-relaxed text-primary",children:JSON.stringify(zn.value,null,2)})})})]}),Et&&n.jsxs("div",{className:pe("rounded-xl border px-3.5 py-3",Et.tone==="critical"&&"border-red-400/28 bg-red-500/[0.09]",Et.tone==="warning"&&"border-amber-400/28 bg-amber-500/[0.09]",Et.tone==="positive"&&"border-lime/28 bg-lime/[0.08]",Et.tone==="neutral"&&"border-cyan-400/22 bg-cyan-500/[0.07]"),children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-white/78",children:Et.label}),n.jsx("p",{className:"mt-1 text-body text-primary",children:Et.summary}),Et.hint&&n.jsx("p",{className:"mt-1 text-caption text-secondary",children:Et.hint}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[L.runId&&W&&n.jsx("button",{type:"button",onClick:()=>{W(L.runId),N()},className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption font-semibold text-primary transition hover:bg-white/[0.1]",children:"Open work session"}),ln&&n.jsx("button",{type:"button",onClick:()=>{Y==null||Y(Fs[0]??null),N()},className:"rounded-full border border-amber-300/30 bg-amber-400/[0.10] px-3 py-1 text-caption font-semibold text-amber-100 transition hover:bg-amber-400/[0.16]",children:Fs.length>0?"Resolve decision":"Resolve decisions"}),Ds&&!zn&&n.jsx("button",{type:"button",onClick:()=>Ee(Ds),className:"rounded-full border border-cyan-300/25 bg-cyan-500/[0.1] px-3 py-1 text-caption font-semibold text-cyan-100 transition hover:bg-cyan-500/[0.16]",children:"Open artifact"}),Zs&&n.jsx("a",{href:Zs,target:"_blank",rel:"noopener noreferrer",className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption font-semibold text-primary transition hover:bg-white/[0.1]",children:"Review evidence"}),E&&n.jsx("button",{type:"button",onClick:()=>void Ne(),disabled:st,className:pe("rounded-full border px-3 py-1 text-caption font-semibold transition disabled:opacity-50",E.isBlockedFlow?"border-amber-300/30 bg-amber-500/[0.12] text-amber-100 hover:bg-amber-500/[0.18]":"border-lime/30 bg-lime/[0.12] text-[#D8FFA1] hover:bg-lime/[0.18]"),children:st?"Scheduling...":E.actionLabel})]}),E&&n.jsx("p",{className:"mt-2 text-caption text-secondary",children:Pt??E.helperText})]}),wt&&n.jsxs("div",{className:"mt-3 rounded-xl border border-amber-300/26 bg-amber-500/[0.08] px-3.5 py-3",children:[n.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-amber-100/85",children:"Spawn guard"}),n.jsx(gn,{tone:wt.isRateLimited?"muted":"red",children:wt.isRateLimited?"Rate limited":"Blocked"})]}),n.jsx("p",{className:"mt-1 text-caption text-amber-100/80",children:"Dispatch was stopped before launch. Adjust limits or retry after the window resets."}),n.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2",children:[n.jsxs("div",{className:"rounded-lg border border-white/[0.10] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro font-semibold tracking-[0.02em] text-secondary",children:"Domain window"}),n.jsx("div",{className:"mt-1 text-body font-semibold tabular-nums text-primary",children:wt.domainCurrent!==null&&wt.domainMax!==null?`${wt.domainCurrent}/${wt.domainMax} per hour`:"Not provided"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.10] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro font-semibold tracking-[0.02em] text-secondary",children:"Global window"}),n.jsx("div",{className:"mt-1 text-body font-semibold tabular-nums text-primary",children:wt.totalCurrent!==null&&wt.totalMax!==null?`${wt.totalCurrent}/${wt.totalMax} per hour`:"Not provided"})]})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-caption text-secondary",children:[wt.domain&&n.jsxs(gn,{tone:"muted",children:["Domain: ",lt(wt.domain)]}),wt.modelTier&&n.jsxs(gn,{tone:"muted",children:["Tier: ",lt(wt.modelTier)]}),Qs&&n.jsxs(gn,{tone:"muted",children:["Retry: ",Qs]}),!Qs&&wt.retryInMs!==null&&n.jsxs(gn,{tone:"muted",children:["Retry in ~",Math.max(1,Math.round(wt.retryInMs/1e3)),"s"]})]}),wt.blockedReason&&n.jsx("p",{className:"mt-2 rounded-lg border border-white/[0.10] bg-black/20 px-3 py-2 text-caption text-primary",children:Lt(wt.blockedReason)??wt.blockedReason}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[G&&n.jsx("button",{type:"button",onClick:G,className:"rounded-full border border-amber-300/32 bg-amber-500/[0.14] px-3 py-1 text-caption font-semibold text-amber-100 transition hover:bg-amber-500/[0.2]",children:"Edit limits"}),E&&n.jsx("button",{type:"button",onClick:()=>void Ne(),disabled:st,className:"rounded-full border border-lime/30 bg-lime/[0.12] px-3 py-1 text-caption font-semibold text-[#D8FFA1] transition hover:bg-lime/[0.18] disabled:opacity-50",children:st?"Scheduling...":"Retry now"})]})]}),br.length>0&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Results"}),n.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 text-caption sm:grid-cols-3",children:br.map(f=>n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:f.label}),n.jsx("div",{className:`mt-0.5 break-words tabular-nums ${f.tone==="critical"?"text-red-300":"text-primary"}`,children:f.value})]},f.label))})]}),Ke&&!ce&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Delegation"}),n.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 text-body text-secondary",children:[n.jsx("span",{className:"flex items-center gap-1.5",children:Ke.requester?n.jsxs(n.Fragment,{children:[n.jsx(Ot,{name:Ke.requester.label,hint:Ri(Ke.requester),size:"xs"}),n.jsx("span",{className:"text-primary",children:Ke.requester.label})]}):n.jsx("span",{children:pr("System / unknown")})}),n.jsx("span",{className:"text-white/[0.15]",children:"→"}),n.jsx("span",{className:"text-primary",children:Ke.mode==="handoff"?"Delegated handoff":Ke.mode==="requested"?"Dispatch requested":Ke.mode==="single"?"Direct execution":"System event"}),n.jsx("span",{className:"text-white/[0.15]",children:"→"}),n.jsx("span",{className:"flex items-center gap-1.5",children:Ke.executor?n.jsxs(n.Fragment,{children:[n.jsx(Ot,{name:Ke.executor.label,hint:Ri(Ke.executor),size:"xs"}),n.jsx("span",{className:"text-primary",children:Ke.executor.label})]}):n.jsx("span",{children:pr("Not assigned")})})]}),Ke.subtitle&&n.jsx("p",{className:"mt-1 text-caption text-muted",children:Ke.subtitle})]}),ce&&n.jsxs("div",{className:"space-y-5",children:[n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("p",{className:"px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Session"}),n.jsx("span",{className:"rounded-full border border-lime/30 bg-lime/[0.08] px-2 py-0.5 text-micro font-semibold text-lime/85",children:tr(ce.event)??lt(ce.event)})]}),Un&&n.jsxs("p",{className:"mt-1 px-1 text-caption text-muted",children:["Based on related activity (",lt(Un.relation),")."]})]}),Ut&&n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:vr?"Terminal state":"Progress"}),n.jsx("p",{className:"text-body font-semibold tabular-nums",style:{color:wr},children:vr?(Et==null?void 0:Et.label)??"Stopped":`${Ut.pct}%`})]}),n.jsx("div",{className:"mt-1.5 h-1.5 overflow-hidden rounded-full bg-white/[0.10]",children:n.jsx("div",{className:"h-full rounded-full transition-[width] duration-300",style:{width:`${Math.max(4,Ut.pct)}%`,backgroundColor:wr}})}),n.jsx("p",{className:"mt-1 text-micro text-muted",children:Ut.label})]}),n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"People"}),n.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3 sm:grid-cols-4",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Requester"}),n.jsxs("div",{className:"mt-0.5 flex items-center gap-1.5 text-body text-primary",children:[n.jsx(Ot,{name:on.primary,hint:on.secondary??on.primary,size:"xs"}),n.jsx("span",{children:on.primary})]}),on.secondary&&n.jsxs("p",{className:"mt-0.5 text-micro text-muted",children:["via ",on.secondary]})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Executor"}),n.jsxs("div",{className:"mt-0.5 flex items-center gap-1.5 text-body text-primary",children:[n.jsx(Ot,{name:Ls,hint:Ls,size:"xs"}),n.jsx("span",{children:Ls})]})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Dispatcher"}),n.jsx("div",{className:"mt-0.5 text-body text-primary",children:ce.dispatcherClient?lt(ce.dispatcherClient):"OrgX"})]}),(ce.domain||ce.requiredSkills.length>0)&&n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Policy"}),n.jsxs("div",{className:"mt-0.5 text-body text-primary",children:[ce.domain??"",ce.requiredSkills.length>0?`${ce.domain?" · ":""}${ce.requiredSkills.join(", ")}`:""]})]})]})]}),P&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Scope"}),n.jsxs("div",{className:"grid grid-cols-1 gap-x-6 gap-y-2 sm:grid-cols-2",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 py-1",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Initiative"}),n.jsx("p",{className:"mt-0.5 text-body text-primary",children:P.initiativeTitle??(P.initiativeId?as(P.initiativeId):"—")})]}),P.initiativeStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:lt(P.initiativeStatus)})]}),n.jsxs("div",{className:"flex items-center justify-between gap-2 py-1",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Workstream"}),n.jsx("p",{className:"mt-0.5 text-body text-primary",children:P.workstreamTitle??(P.workstreamId?as(P.workstreamId):"—")})]}),P.workstreamStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:lt(P.workstreamStatus)})]})]}),P.initiativeWorkstreamPct!==null&&n.jsxs("div",{className:"mt-3",children:[n.jsxs("div",{className:"mb-1 flex items-center justify-between text-micro text-muted",children:[n.jsx("span",{children:"Workstreams complete"}),n.jsxs("span",{className:"tabular-nums",children:[P.doneInitiativeWorkstreams??0,"/",P.totalInitiativeWorkstreams??0]})]}),n.jsx("div",{className:"h-1.5 overflow-hidden rounded-full bg-white/[0.10]",children:n.jsx("div",{className:"h-full rounded-full bg-[#BFFF00]/80",style:{width:`${Math.max(4,P.initiativeWorkstreamPct)}%`}})})]})]}),((P==null?void 0:P.taskTitle)||(P==null?void 0:P.milestoneTitle)||(P==null?void 0:P.phase)||(P==null?void 0:P.nextStep)||(P==null?void 0:P.parsedStatus)||(P==null?void 0:P.stopReason))&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Current step"}),n.jsxs("div",{className:"space-y-1 text-caption",children:[(P==null?void 0:P.taskTitle)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Task"})," ",n.jsx("span",{className:"text-primary",children:P.taskTitle})]}),(P==null?void 0:P.milestoneTitle)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Milestone"})," ",n.jsx("span",{className:"text-primary",children:P.milestoneTitle})]}),(P==null?void 0:P.phase)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Phase"})," ",n.jsx("span",{className:"text-primary",children:tr(P.phase)??lt(P.phase)})]}),(P==null?void 0:P.nextStep)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Next step"})," ",n.jsx("span",{className:"text-primary",children:P.nextStep})]}),(P==null?void 0:P.parsedStatus)&&P.parsedStatus!==(P==null?void 0:P.phase)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Status"})," ",n.jsx("span",{className:"text-primary",children:tr(P.parsedStatus)??lt(P.parsedStatus)})]}),(P==null?void 0:P.stopReason)&&P.stopReason!==(P==null?void 0:P.phase)&&P.stopReason!==(P==null?void 0:P.parsedStatus)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Stop reason"})," ",n.jsx("span",{className:"text-primary",children:tr(P.stopReason)??lt(P.stopReason)})]})]})]}),ce.error&&n.jsx("div",{className:"rounded-lg border border-red-400/20 bg-red-500/10 px-4 py-3 text-body text-red-100/80",children:ce.error})]}),m&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Summary"}),Ge==="missing"&&!A&&n.jsx("p",{className:"mb-1 text-caption text-amber-200/75",children:"Full local turn transcript was unavailable; showing the event summary payload."}),n.jsx(Yr,{mode:"block",text:m,className:"text-body leading-relaxed text-primary"})]}),Lt(L.item.description)&&Lt(L.item.description)!==m&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Details"}),n.jsx(Yr,{mode:"block",text:Lt(L.item.description)??"",className:"text-body leading-relaxed text-secondary"})]}),qn&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Narrative"}),n.jsxs("div",{className:"space-y-1.5 text-caption",children:[n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Intent"})," ",n.jsx("span",{className:"text-primary",children:qn.intent})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Dispatch"})," ",n.jsx("span",{className:"text-primary",children:qn.dispatch})]}),qn.highlights.length>0&&n.jsxs("div",{children:[n.jsx("span",{className:"text-muted",children:"Highlights"}),n.jsx("ul",{className:"mt-1 list-disc space-y-0.5 pl-4 text-primary",children:qn.highlights.slice(0,3).map((f,_)=>n.jsx("li",{children:f},`${qn.sliceRunId}:highlight:${_}`))})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Outcome"})," ",n.jsx("span",{className:"text-primary",children:qn.outcome.summary})]})]})]}),In.length>0&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Evidence"}),n.jsx("div",{className:"space-y-2",children:In.filter((f,_,I)=>I.findIndex(T=>T.path===f.path)===_).map((f,_)=>{const I=$i(f.path);return n.jsxs("div",{className:"flex items-center justify-between gap-3 py-1",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-micro text-muted",children:lt(f.key)}),n.jsx("p",{className:"mt-0.5 truncate font-mono text-caption text-primary",children:_s(f.path)})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[I&&n.jsx("a",{href:I,target:"_blank",rel:"noopener noreferrer",className:"rounded-full border border-strong bg-white/[0.04] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.1]",children:"Open"}),n.jsx("button",{type:"button",onClick:()=>void ze(`${lt(f.key)} path`,f.path),className:"rounded-full border border-strong bg-white/[0.04] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.1]",children:"Copy"})]})]},`${f.key}:${f.path}:${_}`)})})]}),St&&n.jsxs("div",{children:[n.jsxs("div",{className:"mb-2 flex flex-wrap items-center justify-between gap-2 px-1",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-wider text-muted",children:"CLI output"}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[Wn&&n.jsx(gn,{tone:"lime",children:"Live"}),n.jsx("button",{type:"button",onClick:Ue,className:"rounded-full border border-strong bg-white/[0.04] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.1]",children:"Refresh"}),Ys&&n.jsx("a",{href:Ys,target:"_blank",rel:"noopener noreferrer",className:"rounded-full border border-strong bg-white/[0.04] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.1]",children:"Open file"})]})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-black/25",children:[mt.status==="loading"&&n.jsx("p",{className:"px-3 py-2 text-caption text-secondary",children:"Loading CLI output…"}),mt.status==="error"&&n.jsx("p",{className:"px-3 py-2 text-caption text-amber-200/80",children:mt.error??"Unable to load CLI output."}),(mt.status==="ready"||mt.status==="error")&&n.jsx("pre",{className:"max-h-[260px] overflow-auto px-3 py-2 whitespace-pre-wrap break-words font-mono text-caption leading-relaxed text-primary",children:mt.text.trim().length>0?mt.text:"No output lines captured yet."}),(mt.status==="ready"||mt.status==="error")&&n.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-t border-white/[0.08] px-3 py-1.5 text-micro text-muted",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsxs("span",{children:["Path: ",_s(mt.path??St)]}),mt.lineCount>0&&n.jsxs("span",{children:[mt.lineCount," line",mt.lineCount===1?"":"s"]}),mt.truncated&&n.jsx("span",{children:"Showing latest tail window"}),mt.updatedAt&&n.jsxs("span",{children:["Updated ",It(mt.updatedAt)??mt.updatedAt]})]}),n.jsx("div",{className:"flex items-center gap-1.5",children:n.jsx("button",{type:"button",onClick:()=>void ze("CLI output",mt.text||mt.path||St),className:"rounded-full border border-strong bg-white/[0.04] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.1]",children:"Copy"})})]})]})]}),L&&Di(L.item)&&!zn&&n.jsxs("button",{type:"button",onClick:()=>{const f=Di(L.item);f&&Ee(f)},className:"flex w-full items-center gap-2.5 rounded-xl border border-cyan-400/25 bg-cyan-500/[0.08] px-3.5 py-2.5 text-left transition-colors hover:bg-cyan-500/[0.14]",children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:F.cyan,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"flex-shrink-0",children:[n.jsx("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),n.jsx("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"})]}),n.jsx("span",{className:"text-body font-medium",style:{color:F.cyan},children:"View registered artifact"})]}),(at||(ce==null?void 0:ce.logPath)||ss)&&n.jsx("div",{className:"border-t border-white/[0.06]"}),(at||(ce==null?void 0:ce.logPath)||(ce==null?void 0:ce.outputPath)||(P==null?void 0:P.initiativeId)||(P==null?void 0:P.workstreamId))&&n.jsxs("details",{className:"group",children:[n.jsxs("summary",{className:"flex cursor-pointer items-center gap-1.5 px-1 text-micro font-semibold uppercase tracking-wider text-muted select-none",children:[n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"transition-transform group-open:rotate-90",children:n.jsx("path",{d:"m9 18 6-6-6-6"})}),"Technical"]}),n.jsxs("div",{className:"mt-3 space-y-3 text-caption",children:[at&&n.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 sm:grid-cols-3",children:[at.domain&&n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:"Domain"}),n.jsx("div",{className:"mt-0.5 text-primary",children:lt(at.domain)})]}),(at.provider||at.model)&&n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:"Model"}),n.jsxs("div",{className:"mt-0.5 text-primary",children:[at.provider?`${lt(at.provider)} · `:"",at.model?gr(at.model):"—"]})]}),at.modelTier&&n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:"Model tier"}),n.jsx("div",{className:"mt-0.5 text-primary",children:lt(at.modelTier)})]}),at.pluginVersion&&n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:"Plugin"}),n.jsxs("div",{className:"mt-0.5 text-primary",children:["v",at.pluginVersion]})]})]}),(at==null?void 0:at.skillPack)&&n.jsxs("div",{className:"flex flex-wrap items-center gap-2 py-1",children:[n.jsx("span",{className:"text-micro text-muted",children:"Skill pack"}),n.jsxs("span",{className:"text-primary",children:[at.skillPack.name??"—",at.skillPack.version?`@${at.skillPack.version}`:"",at.skillPack.source?` · ${at.skillPack.source}`:""]}),at.skillPack.checksum&&n.jsxs("button",{type:"button",onClick:()=>{var f;return void ze("Skill pack checksum",((f=at.skillPack)==null?void 0:f.checksum)??"")},className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:["sha ",at.skillPack.checksum.slice(0,12)]})]}),at&&at.requiredSkills.length>0&&n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 py-1",children:[n.jsx("span",{className:"text-micro text-muted",children:"Skills"}),at.requiredSkills.map(f=>n.jsx("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-micro text-secondary",children:f},f))]}),(at==null?void 0:at.kickoffContextHash)&&n.jsxs("div",{className:"flex items-center justify-between gap-2 py-1",children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-micro text-muted",children:"Kickoff context"})," ",n.jsxs("span",{className:"font-mono text-muted",children:[at.kickoffContextSource?`${at.kickoffContextSource} · `:"",at.kickoffContextHash.slice(0,16)]})]}),n.jsx("button",{type:"button",onClick:()=>void ze("Kickoff context hash",at.kickoffContextHash??""),className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:"Copy"})]}),((ce==null?void 0:ce.logPath)||(ce==null?void 0:ce.outputPath))&&n.jsxs("div",{className:"space-y-1 border-t border-white/[0.06] pt-3",children:[(ce==null?void 0:ce.logPath)&&n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("p",{className:"min-w-0 truncate font-mono text-muted",children:["log: ",_s(ce.logPath)]}),n.jsx("button",{type:"button",onClick:()=>void ze("Log path",(ce==null?void 0:ce.logPath)??""),className:"flex-shrink-0 rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:"Copy"})]}),(ce==null?void 0:ce.outputPath)&&n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("p",{className:"min-w-0 truncate font-mono text-muted",children:["output: ",_s(ce.outputPath)]}),n.jsx("button",{type:"button",onClick:()=>void ze("Output path",(ce==null?void 0:ce.outputPath)??""),className:"flex-shrink-0 rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:"Copy"})]})]}),((P==null?void 0:P.initiativeId)||(P==null?void 0:P.workstreamId))&&n.jsxs("div",{className:"space-y-1 border-t border-white/[0.06] pt-3",children:[(P==null?void 0:P.initiativeId)&&n.jsxs("p",{className:"break-all font-mono text-muted",children:["initiative: ",as(P.initiativeId)]}),(P==null?void 0:P.workstreamId)&&n.jsxs("p",{className:"break-all font-mono text-muted",children:["workstream: ",as(P.workstreamId)]})]})]})]}),ss&&n.jsxs("details",{className:"group",children:[n.jsxs("summary",{className:"flex cursor-pointer items-center gap-1.5 px-1 text-micro font-semibold uppercase tracking-wider text-muted select-none",children:[n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"transition-transform group-open:rotate-90",children:n.jsx("path",{d:"m9 18 6-6-6-6"})}),"Raw metadata"]}),n.jsx("pre",{className:"mt-2 overflow-x-auto whitespace-pre-wrap font-mono text-caption leading-relaxed text-muted",children:ss})]})]})},L.item.id)})}),n.jsx("div",{className:"border-t border-subtle px-5 py-2.5 text-caption text-muted sm:px-6",children:"Keyboard: ← previous · → next · Esc close"})]})})]})})}),vf=o.lazy(async()=>({default:(await qt(()=>import("./DW_rKUic.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8]))).MissionControlView})),kf=o.lazy(async()=>({default:(await qt(()=>import("./DbNoijHm.js"),__vite__mapDeps([9,1,2,3,4,10,7]))).SessionInspector})),jf=o.lazy(async()=>({default:(await qt(()=>import("./CZZTvkQZ.js"),__vite__mapDeps([11,1,2,3,4,8,7,10]))).DecisionQueue})),Nf=o.lazy(()=>qt(()=>import("./CL_wXqR7.js"),__vite__mapDeps([12,1,2,3,4,7])).then(e=>({default:e.TriageQueue}))),If=o.lazy(()=>qt(()=>import("./ic2FaMnh.js"),__vite__mapDeps([13,1,2,3,4,7])).then(e=>({default:e.TriageDetailModal}))),Af=o.lazy(async()=>({default:(await qt(()=>import("./BXWDRGm-.js").then(t=>t.a),__vite__mapDeps([5,1,2,3,4,6,7]))).NextUpPanel})),Sf=o.lazy(async()=>({default:(await qt(()=>import("./CGGR2GZh.js"),__vite__mapDeps([14,1,2,3,4,7]))).SettingsModal})),_f=o.lazy(async()=>({default:(await qt(()=>import("./DjcdE6jC.js"),__vite__mapDeps([15,1,2,3,4,7]))).BulkSessionsModal})),Cf=o.lazy(async()=>({default:(await qt(()=>import("./PAUiij_z.js"),__vite__mapDeps([16,1,2,3,4,11,8,7,10]))).BulkDecisionsModal})),Mf=o.lazy(async()=>({default:(await qt(()=>import("./tS9mbYZi.js"),__vite__mapDeps([17,1,2,3,4,7]))).BulkOutboxModal})),Tf=o.lazy(async()=>({default:(await qt(()=>import("./DG6y9wJI.js"),__vite__mapDeps([18,1,2,3,4,7]))).BulkHandoffsModal})),Ef=o.lazy(async()=>({default:(await qt(()=>import("./CPFiTmlw.js"),__vite__mapDeps([19,1,2,3,4,6,7]))).ArtifactViewerModal})),Rf=o.lazy(async()=>({default:(await qt(()=>import("./FZYuCDnt.js"),__vite__mapDeps([20,1,2,3,4,8,7]))).SliceDetailModal})),Df=o.lazy(async()=>({default:(await qt(()=>import("./CE38zU4U.js"),__vite__mapDeps([21,1,2,3,4,7]))).RealtimeOrchestratorModal})),Eo={connected:"Live",reconnecting:"Reconnecting",disconnected:"Offline"},Lf={connected:F.lime,reconnecting:F.amber,disconnected:F.red},Bi="orgx.demo_mode",qi="orgx.dev_mode",zi="orgx.show_synthetic_entities",na="orgx.selected_workspace_id",Ro={blocked:0,pending:1,queued:2,running:3,failed:4,cancelled:5,completed:6,archived:7},Do=new Set(["running","active","queued","pending","in_progress","working","planning"]),Ff=/^\s*configure\s+engineering\s+agent(?:\s*[.!?])?\s*$/i;function un(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function $f(e){const t=un(e);if(!t)return"unknown";try{return new Date(t).toLocaleString()}catch{return"unknown"}}function Pf(e,t=220){const s=e.split("|").map(a=>a.trim()).filter(Boolean).map(a=>a.replace(/^[^:]+:\s*/,"").trim()),i=Array.from(new Set(s.length>0?s:[e.trim()])).slice(0,2).join(" ");return i.length<=t?i:`${i.slice(0,t-1).trimEnd()}…`}function Of(e){const t=e.trim().toLowerCase();return t.includes("timed out")||t.includes("timeout")||t.includes("request cancelled")||t.includes("signal is aborted")?{title:"Live sync delayed",message:"OrgX Live is responding slowly. Initiatives and Next Up may look empty until sync recovers.",action:"refresh"}:t.includes("unauthorized")||t.includes("forbidden")||t.includes("api key")||t.includes("auth")?{title:"OrgX auth required",message:"Reconnect your OrgX API key in Settings to restore live initiatives, activity, and Next Up.",action:"settings"}:t.includes("unknown api endpoint")||t.includes("missing required live routes")||t.includes("runtime is missing required live routes")?{title:"Plugin update required",message:"This runtime is missing required live routes. Restart the plugin and update to the latest build.",action:"settings"}:{title:"Live stream degraded",message:Pf(e),action:"settings"}}function Ui(e){if(e.runId&&e.runId.trim().length>0)return e.runId.trim();if(!e.metadata||typeof e.metadata!="object"||Array.isArray(e.metadata))return null;const t=e.metadata,s=["runId","run_id","sessionId","session_id","agentRunId"];for(const r of s){const i=t[r];if(typeof i=="string"&&i.trim().length>0)return i.trim()}return null}function Bf(e){const t=e.sliceRunId;if(typeof t=="string"&&t.trim().length>0)return t.trim();if(!e.metadata||typeof e.metadata!="object"||Array.isArray(e.metadata))return null;const s=e.metadata,r=["sliceRunId","slice_run_id","sliceId","slice_id","sliceRun","slice_run"];for(const i of r){const a=s[i];if(typeof a=="string"&&a.trim().length>0)return a.trim()}return null}function Lo(e){return!e.metadata||typeof e.metadata!="object"||Array.isArray(e.metadata)?null:e.metadata}function Fo(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r=="string"&&r.trim().length>0)return r.trim()}return null}function Wi(e,t){const s=Ro[e.status]??99,r=Ro[t.status]??99;return s!==r?s-r:un(e.updatedAt??e.lastEventAt??e.startedAt)-un(t.updatedAt??t.lastEventAt??t.startedAt)}function $o(e){return!Array.isArray(e)||e.length===0?null:e.find(t=>t.queueState!=="blocked"&&t.queueState!=="running")??e.find(t=>t.queueState!=="blocked")??null}function qf(e){const t=e.toLowerCase();return t==="blocked"||t==="failed"?"blocked":t==="running"||t==="active"||t==="in_progress"?"working":t==="pending"||t==="queued"?"waiting":t==="completed"||t==="done"?"done":"idle"}function zf(e){if(Es(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function Uf(e){if(Es(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function Wf(e){const t=e.metadata;return t!=null&&typeof t=="object"&&t.mock===!0}function Hf(e){return Ff.test(e)}function Or(e,t){for(const s of t){const r=e[s];if(typeof r!="string")continue;const i=r.trim();if(i.length>0)return i}return null}function Vf(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function Kf(e){const t=e.title.trim();return t.length>0?t:e.isDefault?"Default workspace":"Untitled workspace"}function Gf(e){const t=e.get("workspace_id")??e.get("workspaceId")??e.get("command_center_id")??e.get("commandCenterId")??e.get("project_id")??e.get("projectId")??e.get("center");return!t||t.trim().length===0?null:t.trim()}function Xf(e,t){us(e,t)}function Qf(e){e.delete("workspace_id"),e.delete("workspaceId"),e.delete("command_center_id"),e.delete("commandCenterId"),e.delete("project_id"),e.delete("projectId"),e.delete("center")}function Jf(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search),t=Gf(e);if(t)return t}catch{}try{const e=window.localStorage.getItem(na);if(e&&e.trim().length>0)return e.trim()}catch{}return null}function Yf(){const e=ed();return e.showGate?n.jsx(Jd,{state:e.state,isLoading:e.isLoading,isStarting:e.isStarting,isSubmittingManual:e.isSubmittingManual,onRefresh:e.refreshStatus,onStartPairing:e.startPairing,onSubmitManualKey:e.submitManualKey,onBackToPairing:e.backToPairing,onUseManualKey:e.setManualMode,onSkip:e.skipGate}):n.jsx(Xu,{children:n.jsx(sh,{onboarding:e})})}function Zf(e){const t=e.toLowerCase();return/market|email|campaign|content|brand/.test(t)?"Marketing":/product|feature|ux|discovery/.test(t)?"Product":/engineer|infra|platform|api|backend|frontend|dev/.test(t)?"Engineering":"Program"}function eh(e){return e==="Marketing"?["Brief","Draft","Review","Ship"]:e==="Engineering"?["Spec","Dev","QA","Deploy"]:e==="Product"?["Brief","Define","Build","Ship"]:["Plan","Build","Review","Ship"]}function Po(e){const t=(e??"").trim().toLowerCase();return t?t==="critical"||t==="p0"||t==="urgent"?0:t==="high"||t==="p1"?1:t==="medium"||t==="normal"||t==="p2"?2:t==="low"||t==="p3"?3:4:4}function Oo(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function th(){return n.jsx("span",{className:"inline-flex h-6 w-6 items-center justify-center rounded-lg border border-strong bg-white/[0.04] p-0.5",children:n.jsx("img",{src:ii,alt:"OrgX",className:"h-full w-full rounded-md object-contain"})})}function nh(){const{state:e}=dl();return e.artifactId?n.jsx(o.Suspense,{fallback:null,children:n.jsx(Ef,{})}):null}function sh({onboarding:e}){const[t,s]=o.useState(()=>{if(typeof window>"u")return!1;if(new URLSearchParams(window.location.search).get("demo")==="1")return!0;try{return window.localStorage.getItem(Bi)==="1"}catch{return!1}}),[r,i]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(zi)==="1"}catch{return!1}}),[a,c]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(qi)==="1"}catch{return!1}}),[l,d]=o.useState(()=>{if(new URLSearchParams(window.location.search).get("view")==="mission-control")return"mission-control";try{if(localStorage.getItem("orgx-dashboard-view")==="mission-control")return"mission-control"}catch{}return"activity"}),[u,h]=o.useState(()=>Jf()),y=o.useCallback(m=>{d(m);try{localStorage.setItem("orgx-dashboard-view",m)}catch{}},[]),{data:b=[]}=ds({queryKey:["workspace-options",t?"demo":"live"],queryFn:async()=>{if(t)return[];const m=await fetch("/orgx/api/entities?type=command_center&limit=50");if(!m.ok)return[];const A=await m.json().catch(()=>null),E=Array.isArray(A==null?void 0:A.data)?A.data:[],N=[];for(const Q of E){if(!Q||typeof Q!="object"||Array.isArray(Q))continue;const Ne=Or(Q,["id"]);if(!Ne)continue;const ze=Or(Q,["status","priority"]);if(!Vf(ze))continue;const Ue=Or(Q,["title","name"])??(Ne.length>10?`${Ne.slice(0,8)}…`:Ne),Ze=Q.is_default===!0,dt=Kf({title:Ue,isDefault:Ze}),Nt=Or(Q,["created_at"]);N.push({id:Ne,title:dt,status:ze,isDefault:Ze,createdAt:Nt})}return N.sort((Q,Ne)=>{if(Q.isDefault!==Ne.isDefault)return Q.isDefault?-1:1;const ze=un(Q.createdAt)-un(Ne.createdAt);return ze!==0?ze:Q.title.localeCompare(Ne.title)}),N},staleTime:6e4}),p=o.useMemo(()=>{var m;return u?((m=b.find(A=>A.id===u))==null?void 0:m.title)??`Workspace ${u.slice(0,8)}`:"All workspaces"},[u,b]),w=o.useMemo(()=>!u||b.some(m=>m.id===u)?b:[{id:u,title:p,status:null,isDefault:!1,createdAt:null},...b],[u,p,b]);o.useEffect(()=>{u&&b.length!==0&&(b.some(m=>m.id===u)||h(null))},[u,b]),t||e.state.hasApiKey&&e.state.connectionVerified;const v=o.useMemo(()=>l==="mission-control"?{maxSessions:240,maxActivityItems:120,maxHandoffs:60,maxDecisions:80,batchWindowMs:140}:{maxSessions:320,maxActivityItems:80,maxHandoffs:80,maxDecisions:80,batchWindowMs:120},[l]),{data:x,isLoading:C,error:j,refetch:g,approveDecision:S,rejectDecision:W,approveAllDecisions:Y,bulkDecisionAction:K,decisionMutation:me}=Sc({useMock:t,enabled:!0,enableDecisions:!0,projectId:u,...v}),ge=t||r,Z=o.useMemo(()=>ge?x.sessions.nodes:x.sessions.nodes.filter(m=>!zf(m)),[x.sessions.nodes,ge]),ae=o.useMemo(()=>x.activity.filter(m=>!(!ge&&Uf(m)||!a&&Wf(m))),[x.activity,ge,a]),ke=x.connection==="connected"||x.decisions.length>0,[Fe,G]=o.useState(null),[Se,Ae]=o.useState(!1),[xe,re]=o.useState(null),[le,Ee]=o.useState(null),[ee,q]=o.useState(null),[J,V]=o.useState(null),[k,z]=o.useState("live"),[O,oe]=o.useState({startIso:null,endIso:null}),ie=o.useRef(new Set),[Me,ue]=o.useState(null),[R,$]=o.useState(null),[X,te]=o.useState(null),[Le,qe]=o.useState(null),_e=o.useRef(null),M=o.useCallback(m=>{_e.current&&clearTimeout(_e.current),qe(m),_e.current=setTimeout(()=>qe(null),4e3)},[]),[B,ne]=o.useState(!1),[fe,De]=o.useState(!1),[et,tt]=o.useState([]),Re=o.useRef(null),Je=o.useRef(null),[We,ft]=o.useState({open:!1,tab:"orgx",focusAgentDomain:null}),[ot,nt]=o.useState(!1),[we,Ge]=o.useState(null),[je,H]=o.useState("agents"),[Oe,U]=o.useState("initiatives"),[se,Ce]=o.useState("next_up"),$e=o.useCallback(m=>{if(H(m),m==="initiatives"){U("initiatives"),Ce("next_up");return}m==="decisions"&&(U("initiatives"),Ce("in_progress"),Be("needs_attention"))},[]),[Pe,Be]=o.useState("all"),Te=o.useMemo(()=>Array.isArray(x.sliceRuns)?x.sliceRuns:[],[x.sliceRuns]),st=o.useMemo(()=>al({sessions:Z,sliceRuns:Te}),[Te,Z]).length,Ve=o.useMemo(()=>ol(Te),[Te]),Pt=Ve.length+(ke?x.decisions.length:0),[Qe,Mt]=o.useState(null),Yt=o.useCallback(m=>{const A=Te.find(E=>E.initiativeId===m.initiativeId&&E.workstreamId===m.workstreamId)??null;Mt({source:"queue",item:m,linkedSliceRun:A})},[Te]),mt=o.useCallback((m,A)=>{Mt({source:"in_progress",row:m,sliceRun:A})},[]),rn=o.useCallback(m=>{Mt({source:"needs_input",sliceRun:m})},[]),_n=o.useCallback(async(m,A)=>{const E=m.runId??m.sliceRunId;if(!E){M("Cannot accept — no run ID found on this slice.");return}try{const N=A?`Accepted: ${A}`:"Accepted from dashboard",Q=`/orgx/api/runs/${encodeURIComponent(E)}/actions/complete`,Ne=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:N})});if(!Ne.ok){const ze=await Ne.json().catch(()=>null),Ue=(ze==null?void 0:ze.error)??(ze==null?void 0:ze.message)??`Failed to accept slice (${Ne.status})`;M(Ue);return}M("Slice accepted and marked complete."),g()}catch{M("Failed to accept slice — network error.")}},[g,M]),ps=o.useCallback(async(m,A)=>{const E=m.runId??m.sliceRunId;if(!E||!A.trim()){M("Cannot post feedback — missing run ID or note.");return}try{const N=await fetch(`/orgx/api/entities/run/${encodeURIComponent(E)}/comments`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:A.trim(),commentType:"review_feedback",severity:"warn",tags:["changes_requested"]})});if(!N.ok){const Q=await N.json().catch(()=>null);M((Q==null?void 0:Q.error)??(Q==null?void 0:Q.message)??`Failed to post feedback (${N.status})`);return}M("Changes requested — feedback posted.")}catch{M("Failed to post feedback — network error.")}},[M]),gt=gd({projectId:u,authToken:null,embedMode:!1,enabled:!0,snapshotVersion:x.snapshotVersion}),Wt=yd({authToken:null,embedMode:!1}),{model:Cn,actions:Qn}=Id({enabled:!0,workspaceId:u,authToken:null,embedMode:!1}),Rt=o.useMemo(()=>Cn.items.filter(m=>m.kind==="failure_diagnostic"),[Cn.items]),$n=o.useMemo(()=>({...Cn,items:Rt,total:Rt.length}),[Rt,Cn]),[jt,Dt]=o.useState(null),[Ct,Mn]=o.useState(0),Pn=o.useCallback(m=>{Dt(m);const A=Rt.findIndex(E=>E.id===m.id);Mn(A>=0?A:0)},[Rt]),Rs=o.useCallback(m=>{if(Rt.length===0)return;const A=(Ct+m+Rt.length)%Rt.length;Mn(A),Dt(Rt[A]??null)},[Ct,Rt]),fs=gt,Zt=o.useMemo(()=>gt.items.find(m=>m.autoIntentEnabled===!0&&(m.autoRuntimeState==="running"||m.autoRuntimeState==="stopping"))??null,[gt.items]),Xt=!!Zt;o.useEffect(()=>{if(!(typeof window>"u"))try{t?window.localStorage.setItem(Bi,"1"):window.localStorage.removeItem(Bi)}catch{}},[t]),o.useEffect(()=>{if(!(typeof window>"u"))try{r?window.localStorage.setItem(zi,"1"):window.localStorage.removeItem(zi)}catch{}},[r]),o.useEffect(()=>{if(!(typeof window>"u"))try{a?window.localStorage.setItem(qi,"1"):window.localStorage.removeItem(qi)}catch{}},[a]),o.useEffect(()=>{if(!(typeof window>"u")){try{u?window.localStorage.setItem(na,u):window.localStorage.removeItem(na)}catch{}try{const m=new URL(window.location.href);u?Xf(m.searchParams,u):Qf(m.searchParams),m.searchParams.delete("initiative"),m.searchParams.delete("initiative_id"),m.searchParams.delete("project"),window.history.replaceState(null,"",`${m.pathname}${m.search}${m.hash}`)}catch{}}},[u]);const Ht=o.useCallback((m,A)=>{ft(E=>({open:!0,tab:m??E.tab,focusAgentDomain:(A==null?void 0:A.focusAgentDomain)??null}))},[]),Jn=o.useCallback(m=>{if(s(m),!(typeof window>"u"))try{const A=new URL(window.location.href);m?A.searchParams.set("demo","1"):A.searchParams.delete("demo"),window.history.replaceState(null,"",`${A.pathname}${A.search}${A.hash}`)}catch{}},[]),pn=o.useCallback(()=>{Ht("orgx")},[Ht]),Yn=o.useCallback(()=>{qt(()=>import("./DW_rKUic.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8]))},[]),{data:Zn}=ll(l==="mission-control",u),{data:Tn}=Gu(l==="mission-control",u),{data:es=[]}=ds({queryKey:["initiative-tombstones"],queryFn:async()=>[],initialData:[],staleTime:Number.POSITIVE_INFINITY}),[Ft,wn]=o.useState(null),[an,ts]=o.useState(""),[vn,D]=o.useState(!1),he=o.useCallback((m,A)=>{wn({type:m,initiativeId:A}),ts(""),D(!1)},[]),de=o.useCallback(()=>{wn(null),ts(""),D(!1)},[]),Ie=o.useCallback(()=>{Ee(null)},[]),xt=o.useCallback(()=>{q(null),V(null)},[]),Ye=o.useCallback(()=>{te(null)},[]);o.useEffect(()=>{var E;const m=((E=Z[0])==null?void 0:E.id)??null;if(!m){Fe!==null&&G(null);return}if(Fe===null){G(m);return}Z.some(N=>N.id===Fe)||G(m)},[Z,Fe]),o.useEffect(()=>{if(!le)return;Z.some(A=>A.id===le)||Ee(null)},[le,Z]);const rt=o.useCallback(m=>{qt(()=>import("./DbNoijHm.js"),__vite__mapDeps([9,1,2,3,4,10,7])),G(m),Ae(!0),re(null),Ee(m),q(null),V(null)},[]),hs=o.useCallback(m=>{qt(()=>import("./DbNoijHm.js"),__vite__mapDeps([9,1,2,3,4,10,7])),G(m.id),Ae(!0),Ee(m.id),q(m.workstreamId??null),V(m.title),re({workstreamId:m.workstreamId??null,text:`Intervention requested for "${m.title}". `}),M(`Opened intervention composer for ${m.title}.`)},[]),bt=o.useCallback(m=>{const A=m.trim();if(!A)return;const E=Z.find(N=>N.runId===A||N.id===A)??null;E&&(rt(E.id),M(`Focused session: ${E.title}`))},[Z,rt]),ns=o.useCallback(m=>{var N;const A=(N=m.id)==null?void 0:N.trim();if(!A)return;const E=Ui(m);if(E){const Q=Z.find(Ne=>Ne.runId===E||Ne.id===E)??null;Q&&(G(Q.id),Ee(Q.id))}y("activity"),H("activity"),Ae(!1),ue(A),M("Opened activity detail from session timeline.")},[Z,y]),kt=o.useMemo(()=>Z.find(m=>m.id===le)??null,[le,Z]),fn=o.useMemo(()=>{var E,N;const m=((E=kt==null?void 0:kt.runId)==null?void 0:E.trim())??"",A=((N=kt==null?void 0:kt.id)==null?void 0:N.trim())??"";return!m||!A?[]:m===A?[m]:[m,A]},[kt==null?void 0:kt.id,kt==null?void 0:kt.runId]),On=o.useMemo(()=>{const m=new Set;for(const A of fn){const E=A.trim();E.length>0&&m.add(E)}return m},[fn]),gs=o.useMemo(()=>{const m=new Map;for(const A of Z){const E=A.workstreamId??null;A.runId&&m.set(A.runId,E),A.id&&m.set(A.id,E)}return m},[Z]),kn=o.useMemo(()=>{const m=fn.length>0?fn.join("|"):"*",A=(ee==null?void 0:ee.trim())||"*",E=(X==null?void 0:X.trim())||"*";return`${m}::${A}::${E}`},[ee,X,fn]),xs=o.useCallback(m=>{ie.current.add(kn),z(m)},[kn]);o.useEffect(()=>{if(ie.current.has(kn)||C)return;const m=Date.now(),A=ae.filter(Q=>{const Ne=Ui(Q);if(On.size>0&&(!Ne||!On.has(Ne)))return!1;if(ee){const ze=Lo(Q);if((Fo(ze,["workstreamId","workstream_id"])??(Ne?gs.get(Ne)??null:null))!==ee)return!1}if(X){const ze=Lo(Q);if((Fo(ze,["agentName","agent_name"])??Q.agentName)!==X)return!1}return!0});if(A.length===0)return;const N=["live","24h","7d","all"].find(Q=>{const Ne=yr(Q,m);return A.some(ze=>{const Ue=un(ze.timestamp);return Ue?Ne===null||Ue>=Ne:!1})})??"all";ie.current.add(kn),N!==k&&z(N)},[ee,ae,kn,k,gs,X,C,On]);const Bn=Pc({seed:ae,timeFilterId:k,customSinceIso:k==="custom"?O.startIso:null,customUntilIso:k==="custom"?O.endIso:null,runId:(kt==null?void 0:kt.runId)??null,projectId:u,pageSize:50,demoMode:t}),Tt=o.useMemo(()=>Z.find(m=>m.id===Fe)??null,[Z,Fe]),jn=o.useMemo(()=>Z.filter(m=>Do.has(m.status)).length,[Z]),Nn=o.useMemo(()=>Te.length>0?Ve.length:Z.filter(m=>{const A=zt(m.status),E=zt(m.phase??""),N=zt(m.state??"");return A==="completed"||A==="cancelled"||A==="archived"?!1:A==="blocked"||A==="failed"||E==="blocked"||N==="error"?!0:Do.has(A)||A==="handoff"||A==="review"?!1:m.blockers.length>0}).length,[Te.length,Ve.length,Z]);o.useMemo(()=>Z.filter(m=>m.status==="failed").length,[Z]);const ys=o.useMemo(()=>Z.filter(m=>m.status==="completed").length,[Z]);o.useMemo(()=>{const m=(ke?x.decisions.length:0)+Nn;return[{id:"active",label:"Running",value:jn,color:jn>0?F.lime:F.textMuted,icon:"active"},{id:"attention",label:"Needs attention",value:m,color:m>0?F.amber:F.textMuted,icon:"decision"},{id:"completed",label:"Done today",value:ys,color:F.teal,icon:"session"}]},[jn,Nn,ys,x.decisions.length,Z,ke]),o.useMemo(()=>x.decisions.length>0?Math.max(0,...x.decisions.map(m=>m.waitingMinutes)):0,[x.decisions]);const En=o.useMemo(()=>j?Of(j):null,[j]),Qt=o.useMemo(()=>{const m=[];if(En){const A=En.action==="refresh"&&typeof g=="function";m.push({id:`stream-error:${j}`,kind:"error",icon:"notification",title:En.title,message:En.message,actionLabel:A?"Refresh":"Settings",onAction:A?()=>void g():()=>Ht("orgx")})}return x.connection!=="connected"&&m.push({id:`connection:${x.connection}`,kind:x.connection==="disconnected"?"error":"info",icon:"notification",title:x.connection==="disconnected"?"Connection lost":"Reconnecting",message:x.connection==="disconnected"?"Live connection is offline. Initiatives and Next Up may stay stale until reconnect.":"Live connection is recovering. Fresh updates will resume automatically.",actionLabel:"Reconnect",onAction:pn}),Le&&m.push({id:`ops:${Le}`,kind:"info",icon:/decision/i.test(Le)?"decision":"workstream",title:"Update",message:Le}),m},[x.connection,x.outbox.lastReplayError,x.outbox.pendingTotal,x.outbox.replayStatus,j,En,pn,g,Ht,Le]);o.useEffect(()=>{const m=new Set(Qt.map(A=>A.id));tt(A=>A.filter(E=>m.has(E)))},[Qt]);const L=o.useMemo(()=>Qt.filter(m=>!et.includes(m.id)),[et,Qt]),Xs=ke?x.decisions.length:0,qn=jn+Nn+Xs,zn=o.useCallback(m=>{tt(A=>A.includes(m)?A:A.concat(m))},[]),Ds=o.useCallback(()=>{tt(Qt.map(m=>m.id))},[Qt]);o.useEffect(()=>{if(!fe)return;const m=E=>{var Q,Ne;const N=E.target;N&&((Q=Je.current)!=null&&Q.contains(N)||(Ne=Re.current)!=null&&Ne.contains(N)||De(!1))},A=E=>{E.key==="Escape"&&De(!1)};return document.addEventListener("mousedown",m),document.addEventListener("touchstart",m),document.addEventListener("keydown",A),()=>{document.removeEventListener("mousedown",m),document.removeEventListener("touchstart",m),document.removeEventListener("keydown",A)}},[fe]);const Vt=o.useMemo(()=>{var E;const m=new Map;for(const N of Z){const Q=N.initiativeId??N.groupId??"unscoped",Ne=N.groupLabel&&N.groupLabel.trim().length>0?N.groupLabel:N.initiativeId??"Unscoped Initiative",ze=Zf(Ne),Ue=m.get(Q)??{id:Q,name:Ne,category:ze,progressTotal:0,progressCount:0,statusCounts:{},activeAgents:new Set,allAgents:new Set,workstreams:new Map,latestEpoch:0};if(N.progress!==null&&(Ue.progressTotal+=N.progress,Ue.progressCount+=1),Ue.statusCounts[N.status]=(Ue.statusCounts[N.status]??0)+1,N.agentName&&(Ue.allAgents.add(N.agentName),["running","queued","pending","blocked"].includes(N.status)&&Ue.activeAgents.add(N.agentName)),N.workstreamId){const Ze=x.sessions.groups.find(Nt=>Nt.id===N.workstreamId),dt=((E=Ze==null?void 0:Ze.label)==null?void 0:E.trim())||N.workstreamId;Ue.workstreams.set(N.workstreamId,dt)}Ue.latestEpoch=Math.max(Ue.latestEpoch,un(N.updatedAt??N.lastEventAt??N.startedAt)),m.set(Q,Ue)}const A=[];for(const N of m.values()){const Q=N.progressCount>0?Math.round(N.progressTotal/N.progressCount):N.statusCounts.completed?100:N.statusCounts.running?55:0,Ne=N.category,ze=eh(Ne),Ue=Math.round(Math.max(0,Math.min(100,Q))/100*(ze.length-1)),Ze=(N.statusCounts.blocked??0)>0,dt=(N.statusCounts.completed??0)>0&&(N.statusCounts.running??0)===0&&(N.statusCounts.queued??0)===0&&(N.statusCounts.pending??0)===0&&(N.statusCounts.blocked??0)===0&&(N.statusCounts.paused??0)===0,Nt=!dt&&!Ze&&(N.statusCounts.paused??0)>0&&(N.statusCounts.running??0)===0&&(N.statusCounts.queued??0)===0&&(N.statusCounts.pending??0)===0,li=ze.map((ws,vs)=>{let Ln="upcoming";return(dt||vs<Ue)&&(Ln="completed"),vs===Ue&&!dt&&(Ln=Ze?"warning":"current"),{name:ws,status:Ln}});A.push({id:N.id,name:N.name,status:dt?"completed":Ze?"blocked":Nt?"paused":"active",rawStatus:dt?"completed":Ze?"blocked":Nt?"paused":"active",category:Ne,health:Math.max(0,Math.min(100,Q)),phases:li,currentPhase:dt?ze.length-1:Ue,daysRemaining:0,targetDate:null,createdAt:N.latestEpoch>0?new Date(N.latestEpoch).toISOString():null,updatedAt:N.latestEpoch>0?new Date(N.latestEpoch).toISOString():null,activeAgents:N.activeAgents.size,totalAgents:N.allAgents.size,avatars:Array.from(N.activeAgents).slice(0,3),description:`${N.workstreams.size} workstreams are active right now.`,workstreams:Array.from(N.workstreams.entries()).map(([ws,vs])=>({id:ws,name:vs,status:"active"}))})}return A.sort((N,Q)=>{const Ne=N.status==="blocked"?0:N.status==="active"?1:2,ze=Q.status==="blocked"?0:Q.status==="active"?1:2;return Ne!==ze?Ne-ze:Q.health-N.health})},[Z,x.sessions.groups]),Un=o.useMemo(()=>{const m=(N,Q)=>{var Ne,ze;return{...N,...Q,health:Q.health>0?Q.health:N.health,activeAgents:Math.max(N.activeAgents,Q.activeAgents),totalAgents:Math.max(N.totalAgents,Q.totalAgents),avatars:(Ne=N.avatars)!=null&&Ne.length?N.avatars:Q.avatars,workstreams:(ze=N.workstreams)!=null&&ze.length?N.workstreams:Q.workstreams,description:N.description??Q.description,rawStatus:Q.rawStatus??N.rawStatus??null,targetDate:Q.targetDate??N.targetDate??null,createdAt:Q.createdAt??N.createdAt??null,updatedAt:Q.updatedAt??N.updatedAt??null}},A=new Map;for(const N of Vt)A.set(N.id,N);for(const N of[...Tn??[],...Zn??[]]){if(!ge&&Es(N.id)){A.delete(N.id);continue}const Q=N.rawStatus??N.status;if(!Oo(Q)){A.delete(N.id);continue}const Ne=A.get(N.id);A.set(N.id,Ne?m(Ne,N):N)}const E=new Set(es);return Array.from(A.values()).filter(N=>!E.has(N.id)).filter(N=>Oo(N.rawStatus??N.status)).sort((N,Q)=>{const Ne=Nt=>Nt==="blocked"?0:Nt==="active"?1:Nt==="paused"?2:3,ze=Ne(N.status)-Ne(Q.status);if(ze!==0)return ze;const Ue=Po(N.priority)-Po(Q.priority);if(Ue!==0)return Ue;const Ze=un(Q.updatedAt)-un(N.updatedAt);if(Ze!==0)return Ze;const dt=Q.health-N.health;return dt!==0?dt:N.name.localeCompare(Q.name)})},[Vt,Zn,ge,Tn,es]),Ke=o.useMemo(()=>{if(!kt)return null;const m=kt.agentName,A=kt.title;if(m){const E=ae.find(N=>{var Q;return N.runId===kt.runId&&((Q=N.summary)==null?void 0:Q.trim())});if(E!=null&&E.summary){const N=E.summary.trim().length>40?E.summary.trim().slice(0,40)+"…":E.summary.trim();return`${m}: ${N}`}return m}if(A){const E=A.replace(/^(telegram|slack|discord|whatsapp|email|sms):/,"").trim();if(E.length>0)return E}return A??null},[ae,kt]),Rn=o.useMemo(()=>{const m=new Map;for(const A of Z){const E=(A.agentId??"").trim()||`name:${(A.agentName??"").trim()}`,N=(A.agentName??"").trim()||(A.agentId??"").trim();if(!N)continue;const Q=A.updatedAt??A.lastEventAt??A.startedAt??new Date().toISOString(),Ne=un(Q),ze=Ne?Math.max(0,Math.floor((Date.now()-Ne)/6e4)):0,Ue=m.get(E),Ze={id:E,name:N,role:"Agent",status:qf(A.status),task:A.title??null,progress:A.progress??null,lastActive:Q,lastActiveMinutes:ze};(!Ue||un(Ze.lastActive)>un(Ue.lastActive))&&m.set(E,Ze)}return Array.from(m.values())},[Z]),ce=o.useCallback(async()=>{if(Z.length===0){M("No sessions available to continue.");return}const m=[...Z].sort(Wi)[0];if(G(m.id),Ee(m.id),q(null),V(null),["blocked","pending","queued"].includes(m.status))try{await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/actions/resume`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"continue_from_dashboard"})})}catch{}M(`Focused highest priority session: ${m.title}`),await g()},[Z,g]),Dn=o.useCallback(async(m,A)=>{const E=await m.json().catch(()=>null),N=typeof(E==null?void 0:E.error)=="string"&&E.error.trim()||typeof(E==null?void 0:E.message)=="string"&&E.message.trim()||`${A} (${m.status})`;return/unknown api endpoint/i.test(N)?`${A}. This route is unavailable in the running plugin build.`:bn(N)},[]),on=o.useCallback((m,A)=>!m||m.trim().length===0?A:bn(m.trim())||A,[]),Ls=o.useCallback(async()=>{const m=$o(gt.items);if(!m){M("No startable Next Up workstream is available."),y("mission-control");return}await gt.playWorkstream({initiativeId:m.initiativeId,workstreamId:m.workstreamId,agentId:m.runnerAgentId}),Ee(null),q(m.workstreamId),V(m.workstreamTitle),te(null),M(`Dispatched Next Up: ${m.workstreamTitle}`),await Promise.all([gt.refetch(),g()])},[g,gt,y]),bs=o.useCallback(async()=>{const m=$o(gt.items);if(!m){M("No startable initiative is ready for Autopilot yet."),y("mission-control");return}await Wt.move({initiativeId:m.initiativeId,workstreamId:m.workstreamId,placement:"top"}),await gt.startWorkstreamAutoContinue({initiativeId:m.initiativeId,workstreamId:m.workstreamId,agentId:m.runnerAgentId,scope:"initiative"}),Ee(null),q(m.workstreamId),V(m.workstreamTitle),te(null),M(`Autopilot started for ${m.initiativeTitle}; queued from ${m.workstreamTitle}.`),await Promise.all([gt.refetch(),g()])},[g,Wt,gt,y]),Ut=o.useCallback(async()=>{ne(!0);try{if(!Zt){await bs();return}await gt.stopInitiativeAutoContinue({initiativeId:Zt.initiativeId}),M(`Autopilot stopped for ${Zt.initiativeTitle}.`),await Promise.all([gt.refetch(),g()])}finally{ne(!1)}},[Zt,g,gt,bs]),P=o.useCallback(async m=>{const A=(m.initiativeId??"").trim(),E=(m.workstreamId??"").trim();if(!A||!E)throw new Error("Missing initiative/workstream metadata for this session.");const N=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:A,workstreamId:E,agentId:m.agentId??void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})});if(!N.ok)throw new Error(await Dn(N,"Failed to dispatch workstream from In Progress"));Ee(null),q(E),V(m.title),M(`Dispatched ${m.title}.`),await Promise.all([gt.refetch(),g()])},[Dn,g,gt]),Et=o.useCallback(async m=>{const A=(m.initiativeId??"").trim(),E=(m.workstreamId??"").trim();if(!A||!E)throw new Error("Missing initiative/workstream metadata for this session.");const N=await fetch("/orgx/api/mission-control/next-up/triage/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:A,workstreamId:E,placement:"bottom",resetToTodo:!1})});if(!N.ok){const Q=await Dn(N,"Failed to pause workstream from In Progress");if(!/running plugin build/i.test(Q))throw new Error(Q);const Ne=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:A})});if(!Ne.ok)throw new Error(await Dn(Ne,"Failed to pause workstream using legacy fallback"))}M(`Paused ${m.title} and sent it to the bottom of queue.`),await Promise.all([gt.refetch(),g()])},[Dn,g,gt]),br=o.useCallback(async m=>{const A=(m.workstreamId??"").trim();if(!A)throw new Error("This session is missing a workstream id for intervention notes.");const E=m.text.trim();if(Hf(E)){Ht("agents",{focusAgentDomain:"engineering"}),M("Opened agent settings for engineering runtime configuration.");return}const N=await fetch(`/orgx/api/entities/workstream/${encodeURIComponent(A)}/comments`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:E,commentType:"intervention",severity:"info",tags:["intervention","in_progress"]})});if(!N.ok)throw new Error(await Dn(N,"Failed to submit intervention"));M(`Intervention sent for ${m.session.title}.`),await g()},[Ht,Dn,g]),Fs=o.useCallback(async m=>{if(G(m.id),Ee(m.id),q(null),V(null),!["running","completed","archived"].includes(m.status))try{await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/actions/resume`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"dispatch_from_dashboard"})})}catch{}M(`Dispatch requested: ${m.title}`),await g()},[g]),ln=o.useCallback(async(m,A,E={})=>{const N=await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/actions/${A}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)});if(!N.ok){const Q=await N.json().catch(()=>null);throw new Error((Q==null?void 0:Q.error)??`${A} failed (${N.status})`)}},[]),wr=o.useCallback(async m=>{var Q;const A=await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/checkpoints`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"dashboard_manual_checkpoint"})});if(!A.ok){const Ne=await A.json().catch(()=>null);throw new Error((Ne==null?void 0:Ne.error)??`Checkpoint creation failed (${A.status})`)}const E=await A.json().catch(()=>null),N=E&&"data"in E&&((Q=E.data)==null?void 0:Q.id)||E&&"id"in E&&E.id||null;M(N?`Checkpoint created: ${N.slice(0,8)}`:"Checkpoint created."),await g()},[g]),vr=o.useCallback(async m=>{await ln(m,"pause",{reason:"pause_from_dashboard"}),M(`Pause requested: ${m.title}`),await g()},[g,ln]),at=o.useCallback(async m=>{await ln(m,"resume",{reason:"resume_from_dashboard"}),M(`Resume requested: ${m.title}`),await g()},[g,ln]),kr=o.useCallback(async m=>{await ln(m,"cancel",{reason:"restart_from_in_progress"}),await P(m),M(`Restarted ${m.title}.`),await g()},[P,g,ln]),wt=o.useCallback(async m=>{await ln(m,"cancel",{reason:"cancel_from_dashboard"}),M(`Cancel requested: ${m.title}`),await g()},[g,ln]),Qs=o.useCallback(async m=>{var ze;const A=await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/checkpoints`,{method:"GET"});if(!A.ok){const Ue=await A.json().catch(()=>null);throw new Error((Ue==null?void 0:Ue.error)??`Checkpoint list failed (${A.status})`)}const E=await A.json().catch(()=>null),Ne=(ze=(Array.isArray(E)?E:Array.isArray(E==null?void 0:E.data)?E.data:[]).map(Ue=>({id:typeof Ue.id=="string"?Ue.id:"",createdAt:typeof Ue.createdAt=="string"?Ue.createdAt:typeof Ue.created_at=="string"?Ue.created_at:""})).filter(Ue=>Ue.id.length>0).sort((Ue,Ze)=>Date.parse(Ze.createdAt)-Date.parse(Ue.createdAt))[0])==null?void 0:ze.id;if(!Ne)throw new Error("No checkpoint available for rollback.");await ln(m,"rollback",{checkpointId:Ne,reason:"rollback_from_dashboard"}),M(`Rollback requested for ${m.title}.`),await g()},[g,ln]),Js=o.useCallback(async()=>{var E;if(!Ft||an.trim().length===0||vn)return;D(!0);const m=Ft.type,A=an.trim();try{const N={type:m,title:A,status:"active"};if(m==="workstream"){const Ne=Ft.initiativeId??(Tt==null?void 0:Tt.initiativeId)??((E=Vt[0])==null?void 0:E.id)??null;if(!Ne){M("Select an initiative first to start a workstream."),D(!1);return}N.initiative_id=Ne,N.parentId=Ne}const Q=await fetch("/orgx/api/entities",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(N)});if(!Q.ok){const Ne=await Q.json().catch(()=>null);throw new Error((Ne==null?void 0:Ne.error)??`Failed to create ${m}.`)}M(`Created ${m}: ${A}`),de(),await g()}catch(N){M(on(N instanceof Error?N.message:"",`Failed to create ${m}.`)),D(!1)}},[de,vn,Ft,an,Vt,g,Tt==null?void 0:Tt.initiativeId]),ss=o.useCallback(()=>{he("initiative")},[he]),In=o.useCallback(m=>{he("workstream",m)},[he]);o.useCallback(()=>{var m;return In((Tt==null?void 0:Tt.initiativeId)??((m=Vt[0])==null?void 0:m.id)??null)},[Vt,Tt==null?void 0:Tt.initiativeId,In]);const St=o.useCallback(m=>{const A=[...Z].filter(E=>(E.initiativeId??E.groupId)===m.id).sort(Wi)[0];A&&(G(A.id),Ee(A.id),q(null),V(null),M(`Focused initiative: ${m.name}`))},[Z]),Ys=o.useCallback(m=>{const A=Vt.find(E=>E.id===m)??Un.find(E=>E.id===m)??null;A&&St(A)},[St,Vt,Un]),Wn=o.useCallback(m=>{const A=(m??"").trim();y("activity"),U("initiatives"),H("initiatives"),Ce("in_progress"),Be("needs_attention"),$(A.length>0?A:null),M(A.length>0?"Reviewing pending decision.":"Review needs attention.")},[y]),Zs=o.useCallback(m=>{const A=new Set,E=(m.runId??"").trim();E.length>0&&A.add(E),A.add(m.sliceRunId);const N=new Map;for(const Ze of ae){const dt=Ui(Ze),Nt=Bf(Ze);(dt&&A.has(dt)||Nt&&Nt===m.sliceRunId)&&N.set(Ze.id,Ze)}const Q=Array.from(N.values()),Ne=Ze=>{const dt=Ze.type.trim().toLowerCase();let Nt=0;return(dt==="decision_requested"||dt==="blocker_created")&&(Nt+=80),(dt==="run_failed"||dt==="autopilot_stopped")&&(Nt+=70),(dt.includes("slice_completed")||dt.includes("completed"))&&(Nt+=60),dt.includes("artifact")&&(Nt+=55),(dt.includes("progress")||dt.includes("update"))&&(Nt+=35),Nt+=Math.floor(un(Ze.timestamp)/1e3),Nt};Q.sort((Ze,dt)=>Ne(dt)-Ne(Ze));const ze=Q[0]??null;y("activity"),H("activity"),U("initiatives");const Ue=(E?Z.find(Ze=>Ze.runId===E||Ze.id===E)??null:null)??(m.initiativeId&&m.workstreamId?Z.find(Ze=>Ze.initiativeId===m.initiativeId&&Ze.workstreamId===m.workstreamId)??null:null);if(Ue?(G(Ue.id),Ee(Ue.id),q(null),V(null)):m.workstreamId&&(Ee(null),q(m.workstreamId),V(m.workstreamTitle??"Work slice")),ze!=null&&ze.id){ue(ze.id),M(`Reviewing activity for ${m.workstreamTitle??"work slice"}.`);return}if(m.primaryAction==="resolve_decision"){Wn();return}if(E.length>0){bt(E),M("Opened the related work session. Timeline details were unavailable.");return}M("No activity details were found for this slice yet.")},[ae,bt,Wn,Z,y]);return o.useCallback(m=>{const A=new Set(m),E=[...Z].filter(N=>A.has(N.status)).sort(Wi)[0];if(!E){M("No matching sessions for that metric right now.");return}rt(E.id),H("activity")},[Z,rt]),o.useCallback(m=>{l==="activity"&&(m==="sessions"||m==="active"||m==="blocked"||m==="failed"||m==="decisions"||m==="outbox"||m==="handoffs")&&Ge(m)},[l]),C?n.jsxs("div",{className:"flex min-h-screen flex-col lg:h-screen",style:{backgroundColor:F.background},children:[n.jsxs("div",{className:"border-b border-subtle px-4 py-2.5 sm:px-6",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"shimmer-skeleton h-6 w-6 rounded-lg"}),n.jsx("div",{className:"shimmer-skeleton h-5 w-28 rounded-md"}),n.jsx("div",{className:"shimmer-skeleton h-5 w-14 rounded-full"})]}),n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:Array.from({length:4}).map((m,A)=>n.jsx("div",{className:"shimmer-skeleton h-7 w-24 rounded-full"},A))})]}),n.jsxs("div",{className:"grid flex-1 grid-cols-1 gap-4 p-4 sm:p-5 lg:grid-cols-12",children:[n.jsx("div",{className:"shimmer-skeleton min-h-[240px] rounded-2xl lg:col-span-3"}),n.jsx("div",{className:"shimmer-skeleton min-h-[240px] rounded-2xl lg:col-span-6"}),n.jsxs("div",{className:"flex flex-col gap-4 lg:col-span-3",children:[n.jsx("div",{className:"shimmer-skeleton h-40 rounded-2xl"}),n.jsx("div",{className:"shimmer-skeleton h-48 rounded-2xl"}),n.jsx("div",{className:"shimmer-skeleton flex-1 rounded-2xl",style:{minHeight:160}})]})]})]}):n.jsxs("div",{className:"relative flex min-h-screen flex-col pb-[92px] lg:h-screen lg:min-h-0 lg:overflow-hidden lg:pb-0",style:{backgroundColor:F.background},children:[typeof window<"u"&&window.location.port==="5173"&&n.jsx("div",{className:"absolute left-1/2 top-4 z-30 -translate-x-1/2",children:n.jsxs("div",{className:"rounded-full border border-strong bg-white/[0.06] px-4 py-2 text-caption text-primary shadow-[0_10px_30px_rgba(0,0,0,0.35)] backdrop-blur",children:["Dev preview on 5173. Installed plugin runs on OpenClaw port"," ",n.jsx("a",{href:"http://127.0.0.1:18789/orgx/live/",className:"text-white underline underline-offset-4 hover:text-secondary",children:"18789"}),"."]})}),n.jsxs("header",{className:"relative z-[180] border-b border-subtle px-4 py-1.5 sm:px-6",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2.5 lg:grid lg:grid-cols-[1fr_auto_1fr]",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[n.jsx(th,{}),n.jsxs("h1",{className:"text-title font-semibold tracking-tight text-white sm:text-[17px]",children:["OrgX",n.jsx("span",{className:"ml-1.5 text-secondary",children:"Live"})]}),n.jsx(Yd,{color:Lf[x.connection],pulse:x.connection==="connected",title:[`Status: ${Eo[x.connection]??x.connection}`,x.connection==="connected"?"Meaning: receiving live updates.":x.connection==="reconnecting"?"Meaning: retrying live stream (data may be stale).":"Meaning: offline (data is stale).",`Last snapshot: ${$f(x.lastSnapshotAt)}`,En?`Details: ${En.message}`:null].filter(Boolean).join(`
213
+ `),children:Eo[x.connection]??"Unknown"}),(jn>0||Nn>0)&&n.jsx(ao,{className:"hidden md:flex",running:jn,blocked:Nn,decisionsCount:ke?x.decisions.length:0,completedToday:ys,onDecisionsClick:()=>{y("activity"),U("initiatives"),H("initiatives"),Ce("in_progress"),Be("needs_attention")},onBlockedClick:()=>{Te.length>0?(y("mission-control"),Ce("in_progress"),Be("needs_attention")):Ge("blocked")},onNewInitiative:ss})]}),n.jsx("div",{className:"hidden items-center justify-center lg:flex",children:n.jsxs("div",{className:"flex rounded-full border border-white/[0.1] bg-white/[0.03] p-0.5",role:"group","aria-label":"Dashboard view",children:[n.jsx("button",{type:"button",onClick:()=>y("activity"),"aria-pressed":l==="activity",className:`rounded-full px-3 py-1 text-body font-medium transition-all ${l==="activity"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Activity"}),n.jsx("button",{type:"button",onClick:()=>y("mission-control"),onMouseEnter:Yn,onFocus:Yn,"aria-pressed":l==="mission-control",className:`rounded-full px-3 py-1 text-body font-medium transition-all ${l==="mission-control"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Mission Control"})]})}),n.jsxs("div",{className:"relative isolate flex items-center justify-end gap-1.5 sm:gap-2",children:[n.jsxs("div",{className:"relative hidden md:block",children:[n.jsx("label",{htmlFor:"workspace-switcher",className:"sr-only",children:"Workspace scope"}),n.jsxs("select",{id:"workspace-switcher",value:u??"__all__",onChange:m=>{const A=m.target.value;h(A==="__all__"?null:A)},className:"control-pill h-8 min-w-[170px] appearance-none justify-start bg-white/[0.03] pl-3 pr-8 text-caption font-semibold text-primary",title:`Workspace scope: ${p}`,children:[n.jsx("option",{value:"__all__",children:"All workspaces"}),w.map(m=>n.jsx("option",{value:m.id,children:m.title},m.id))]}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-secondary",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),x.lastActivity&&n.jsxs("span",{className:"hidden text-body text-secondary xl:inline",children:["Last activity: ",x.lastActivity]}),t&&n.jsx("button",{type:"button",onClick:()=>{Jn(!1),pn()},className:"hidden rounded-full border border-amber-200/25 bg-amber-200/10 px-3 py-1.5 text-caption font-semibold text-amber-100 transition-colors hover:bg-amber-200/15 sm:inline",title:"Exit demo mode",children:"Exit demo"}),n.jsxs("button",{type:"button",ref:Re,onClick:()=>De(m=>!m),title:"Notifications","aria-haspopup":"dialog","aria-expanded":fe,"aria-controls":"header-notifications-panel",className:"relative inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.1] bg-white/[0.03] text-primary transition-colors hover:bg-white/[0.08]",children:[n.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M15 17h5l-1.4-1.4a2 2 0 0 1-.6-1.4V11a6 6 0 1 0-12 0v3.2c0 .53-.21 1.04-.59 1.42L4 17h5"}),n.jsx("path",{d:"M9 17a3 3 0 0 0 6 0"})]}),L.length>0&&n.jsx("span",{className:"absolute -right-1 -top-1 inline-flex min-h-[16px] min-w-[16px] items-center justify-center rounded-full bg-red-500 px-1 text-micro font-semibold text-white",children:L.length})]}),n.jsx("button",{type:"button",onClick:()=>nt(!0),title:"Realtime orchestrator",className:"relative inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.1] bg-white/[0.03] text-primary transition-colors hover:bg-white/[0.08]",children:n.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 18a2.5 2.5 0 0 0 2.5-2.5v-7a2.5 2.5 0 1 0-5 0v7A2.5 2.5 0 0 0 12 18z"}),n.jsx("path",{d:"M6 12.5v2a6 6 0 0 0 12 0v-2"}),n.jsx("path",{d:"M12 20.5v2"})]})}),n.jsx("button",{type:"button",onClick:()=>Ht("orgx"),title:"Settings",className:"relative inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.1] bg-white/[0.03] text-primary transition-colors hover:bg-white/[0.08]",children:n.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 15.5a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7z"}),n.jsx("path",{d:"M19.4 15a1.8 1.8 0 0 0 .36 2l.05.05a2.2 2.2 0 0 1-1.56 3.76 2.2 2.2 0 0 1-1.56-.64l-.05-.05a1.8 1.8 0 0 0-2-.36 1.8 1.8 0 0 0-1.1 1.63V22a2.2 2.2 0 0 1-4.4 0v-.07a1.8 1.8 0 0 0-1.1-1.63 1.8 1.8 0 0 0-2 .36l-.05.05a2.2 2.2 0 1 1-3.12-3.12l.05-.05a1.8 1.8 0 0 0 .36-2 1.8 1.8 0 0 0-1.63-1.1H2a2.2 2.2 0 0 1 0-4.4h.07a1.8 1.8 0 0 0 1.63-1.1 1.8 1.8 0 0 0-.36-2l-.05-.05a2.2 2.2 0 1 1 3.12-3.12l.05.05a1.8 1.8 0 0 0 2 .36 1.8 1.8 0 0 0 1.1-1.63V2a2.2 2.2 0 0 1 4.4 0v.07a1.8 1.8 0 0 0 1.1 1.63 1.8 1.8 0 0 0 2-.36l.05-.05a2.2 2.2 0 0 1 3.12 3.12l-.05.05a1.8 1.8 0 0 0-.36 2 1.8 1.8 0 0 0 1.63 1.1H22a2.2 2.2 0 0 1 0 4.4h-.07a1.8 1.8 0 0 0-1.63 1.1z"})]})}),n.jsxs("button",{type:"button",onClick:g,className:"group inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.1] bg-white/[0.03] text-body text-primary transition-colors hover:bg-white/[0.08] sm:w-auto sm:gap-1.5 sm:px-3",title:"Refresh data",children:[n.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"transition-transform group-hover:rotate-45",children:[n.jsx("path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}),n.jsx("path",{d:"M21 3v5h-5"})]}),n.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]}),fe&&n.jsxs("div",{id:"header-notifications-panel",ref:Je,role:"dialog","aria-label":"Notifications",className:"absolute right-0 top-[calc(100%+8px)] z-[320] w-[min(92vw,380px)] rounded-2xl border border-strong bg-[#070a11]/95 p-2 shadow-[0_20px_50px_rgba(0,0,0,0.45)] backdrop-blur",children:[n.jsxs("div",{className:"mb-1.5 flex items-center justify-between px-2 py-1",children:[n.jsx("p",{className:"text-body font-semibold uppercase tracking-[0.12em] text-secondary",children:"Notifications"}),n.jsxs("div",{className:"flex items-center gap-2",children:[L.length>0&&n.jsx("button",{type:"button",onClick:Ds,className:"text-caption text-secondary transition-colors hover:text-primary",children:"Dismiss all"}),n.jsx("button",{type:"button",onClick:()=>De(!1),className:"rounded-md px-1.5 py-0.5 text-caption text-secondary transition-colors hover:bg-white/[0.08] hover:text-primary","aria-label":"Close notifications",children:"Close"})]})]}),n.jsx("div",{className:"mb-1.5 px-1.5",children:n.jsx(ao,{className:"max-w-full overflow-hidden",running:jn,blocked:Nn,decisionsCount:Xs,completedToday:ys,onDecisionsClick:()=>{y("activity"),H("initiatives"),U("initiatives"),Ce("in_progress"),Be("needs_attention"),De(!1)},onBlockedClick:()=>{Te.length>0?(y("mission-control"),Ce("in_progress"),Be("needs_attention")):Ge("blocked"),De(!1)}})}),L.length===0?n.jsx("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-3 text-body text-secondary",children:qn>0?"No new notification banners. Active work is summarized above.":"Everything looks clear."}):n.jsx("div",{className:"space-y-1.5",children:L.map(m=>n.jsx("div",{className:"rounded-xl border px-3 py-2",style:{borderColor:m.kind==="error"?"rgba(239,68,68,0.35)":"rgba(255,255,255,0.1)",backgroundColor:m.kind==="error"?"rgba(239,68,68,0.08)":"rgba(255,255,255,0.02)"},children:n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("p",{className:"inline-flex items-center gap-1.5 text-body font-semibold",style:{color:m.kind==="error"?"#fecaca":"#e2e8f0"},children:[n.jsx(yn,{type:m.icon,size:12,className:"opacity-90"}),n.jsx("span",{className:"truncate",children:m.title})]}),n.jsx("p",{className:"mt-0.5 text-body leading-snug text-secondary",children:m.message}),m.onAction&&n.jsx("button",{type:"button",onClick:()=>{var A;(A=m.onAction)==null||A.call(m),De(!1)},className:"mt-1.5 rounded-md border border-strong bg-white/[0.05] px-2.5 py-1 text-caption font-medium text-primary transition-colors hover:bg-white/[0.1] hover:text-white",children:m.actionLabel??"View"})]}),n.jsx("button",{type:"button",onClick:()=>zn(m.id),className:"shrink-0 rounded-md px-1.5 py-0.5 text-caption text-secondary transition-colors hover:bg-white/[0.08] hover:text-primary",title:"Dismiss",children:"Dismiss"})]})},m.id))})]})]})]}),n.jsxs("div",{className:"mt-2 flex items-center justify-center gap-2 lg:hidden",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("label",{htmlFor:"workspace-switcher-mobile",className:"sr-only",children:"Workspace scope"}),n.jsxs("div",{className:"relative",children:[n.jsxs("select",{id:"workspace-switcher-mobile",value:u??"__all__",onChange:m=>{const A=m.target.value;h(A==="__all__"?null:A)},className:"control-pill h-8 w-full appearance-none justify-start bg-white/[0.03] pl-3 pr-8 text-caption font-semibold text-primary",title:`Workspace scope: ${p}`,children:[n.jsx("option",{value:"__all__",children:"All workspaces"}),w.map(m=>n.jsx("option",{value:m.id,children:m.title},m.id))]}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-secondary",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]})]}),n.jsxs("div",{className:"flex w-full max-w-[248px] rounded-full border border-white/[0.1] bg-white/[0.03] p-0.5",role:"group","aria-label":"Dashboard view",children:[n.jsx("button",{type:"button",onClick:()=>y("activity"),"aria-pressed":l==="activity",className:`flex-1 rounded-full px-3 py-1.5 text-body font-medium transition-all ${l==="activity"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Activity"}),n.jsx("button",{type:"button",onClick:()=>y("mission-control"),"aria-pressed":l==="mission-control",className:`flex-1 rounded-full px-3 py-1.5 text-body font-medium transition-all ${l==="mission-control"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Mission Control"})]})]})]}),l==="mission-control"?n.jsx("div",{className:"relative z-0 flex-1 min-h-0 flex flex-col overflow-hidden",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"flex flex-1 items-center justify-center text-body text-secondary",children:"Loading Mission Control…"}),children:n.jsx(vf,{initiatives:Un,activities:ae,agents:Rn,runtimeInstances:x.runtimeInstances??[],workspaceInitiativeId:u,isLoading:C,authToken:null,embedMode:!1,connection:x.connection,lastSnapshotAt:x.lastSnapshotAt,error:j,hasApiKey:e.state.hasApiKey,onOpenSettings:()=>Ht("orgx"),onRefresh:g,onCreateInitiative:ss,onPlayNextUp:Ls,onStartAutopilot:bs,nextUpQueueModel:gt,nextUpActionsModel:Wt,snapshotVersion:x.snapshotVersion})})}):n.jsxs("main",{className:"relative z-0 grid min-h-0 flex-1 grid-cols-1 gap-4 overflow-y-auto p-4 pb-20 sm:p-5 sm:pb-20 lg:grid-cols-12 lg:overflow-hidden lg:pb-5",children:[n.jsx("section",{className:`min-h-0 lg:col-span-3 lg:flex lg:flex-col lg:[&>section]:h-full ${je!=="agents"?"hidden lg:flex":""}`,children:n.jsx(Dm,{sessions:x.sessions,activity:ae,runtimeInstances:x.runtimeInstances??[],showSyntheticEntities:t||r,selectedSessionId:Fe,onSelectSession:rt,onAgentFilter:te,agentFilter:X,timeFilterId:k,onReconnect:pn,onLaunched:g,connectionStatus:x.connection})}),n.jsx("section",{className:`min-h-0 lg:col-span-6 lg:flex lg:flex-col lg:[&>section]:h-full ${je!=="activity"?"hidden lg:flex":""}`,children:n.jsx(wf,{activity:Bn.items,sessions:Z,sliceRuns:Te,initiatives:Vt,timelineNarrative:x.timelineNarrative??[],workspaceId:u,chatSnapshot:x.chat,selectedRunIds:fn,selectedSessionLabel:Ke,selectedWorkstreamId:ee,selectedWorkstreamLabel:J,agentFilter:X,timeFilterId:k,onTimeFilterChange:xs,customTimeRange:O,onCustomTimeRangeChange:oe,hasMore:Bn.hasMore,isLoadingMore:Bn.isLoadingMore,onLoadMore:Bn.loadMore,onClearSelection:Ie,onClearWorkstreamFilter:xt,onClearAgentFilter:Ye,onFocusRunId:bt,onOpenDecision:Wn,requestedActivityItemId:Me,onActivityItemRequestHandled:()=>ue(null),onPlayNextUp:Ls,onStartAutopilot:bs,onPauseWorkstream:Et,onCreateInitiative:ss,onOpenMissionControl:()=>y("mission-control"),onOpenSettings:()=>Ht("orgx"),onRefreshData:g,isLoading:C})}),n.jsx("section",{className:`flex min-h-0 flex-col gap-3 lg:col-span-3 lg:gap-3 ${je!=="decisions"&&je!=="initiatives"?"hidden lg:flex":""}`,children:n.jsx("div",{className:`min-h-0 ${Oe==="initiatives"?"flex-1":"flex-shrink-0"} `,children:Oe==="initiatives"?n.jsxs(Hs,{className:"flex h-full min-h-0 flex-col card-enter",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-subtle px-4 pt-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-4 overflow-x-auto",children:[n.jsxs("button",{type:"button",role:"tab","aria-selected":se==="in_progress",onClick:m=>{m.stopPropagation(),Ce("in_progress")},className:pe("relative inline-flex items-center gap-1.5 pb-2 text-caption font-semibold transition-colors",se==="in_progress"?"text-white":"text-secondary hover:text-bright"),children:[n.jsx("span",{children:"In Progress"}),n.jsx("span",{className:"text-micro tabular-nums text-muted",children:st}),n.jsx("span",{className:pe("pointer-events-none absolute -bottom-px left-0 right-0 h-[2px] rounded-full bg-[#BFFF00] transition-opacity",se==="in_progress"?"opacity-100":"opacity-0")})]}),n.jsxs("button",{type:"button",role:"tab","aria-selected":se==="next_up",onClick:m=>{m.stopPropagation(),Ce("next_up")},className:pe("relative inline-flex items-center gap-1.5 pb-2 text-caption font-semibold transition-colors",se==="next_up"?"text-white":"text-secondary hover:text-bright"),children:[n.jsx("span",{children:"Next Up"}),n.jsx("span",{className:"text-micro tabular-nums text-muted",children:fs.total}),n.jsx("span",{className:pe("pointer-events-none absolute -bottom-px left-0 right-0 h-[2px] rounded-full bg-[#BFFF00] transition-opacity",se==="next_up"?"opacity-100":"opacity-0")})]})]}),n.jsxs("button",{type:"button",onClick:()=>{Ut().catch(m=>{M(on(m instanceof Error?m.message:"","Autopilot action failed."))})},disabled:B,className:"control-pill inline-flex h-8 items-center gap-1.5 px-2.5 text-caption font-semibold disabled:opacity-45","data-tone":"teal","data-state":Xt?"active":"idle",title:Xt?"Stop autopilot":"Start autopilot","aria-label":Xt?"Stop autopilot":"Start autopilot",children:[n.jsx("svg",{viewBox:"0 0 20 20",fill:"none",className:pe("h-3.5 w-3.5",Xt?"animate-pulse":""),"aria-hidden":!0,children:n.jsx("path",{d:"M6.1 13.25C4.25 13.25 2.8 11.8 2.8 10s1.45-3.25 3.3-3.25c3.15 0 4.35 6.5 8.05 6.5 1.85 0 3.3-1.45 3.3-3.25s-1.45-3.25-3.3-3.25c-3.7 0-4.9 6.5-8.05 6.5Z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),n.jsx("span",{className:"text-micro uppercase tracking-[0.12em]",children:"Auto"}),n.jsx("span",{className:pe("rounded-full px-1.5 py-0.5 text-[10px] font-semibold",Xt?"bg-[#BFFF00]/18 text-[#E3FFAE]":"bg-white/[0.08] text-secondary"),children:Xt?"On":"Off"})]})]}),se==="in_progress"?n.jsxs("div",{className:"flex items-center gap-1.5 border-b border-subtle px-4 py-2",children:[n.jsxs("button",{type:"button",onClick:()=>Be("all"),className:pe("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",Pe==="all"?"bg-white/[0.09] text-primary":"text-secondary hover:bg-white/[0.06] hover:text-bright"),children:[n.jsx("span",{children:"All active"}),n.jsx("span",{className:"tabular-nums opacity-75",children:st})]}),n.jsxs("button",{type:"button",onClick:()=>Be("needs_attention"),className:pe("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",Pe==="needs_attention"?"bg-[#F5B700]/14 text-[#FFE7A8]":"text-secondary hover:bg-white/[0.06] hover:text-bright"),children:[n.jsx("span",{children:"Needs attention"}),n.jsx("span",{className:"tabular-nums opacity-80",children:Pt})]})]}):null,n.jsx("div",{className:"min-h-0 flex-1",children:se==="in_progress"?Pe==="needs_attention"?n.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-2 overflow-y-auto p-2",children:[$n.items.length>0&&n.jsx("div",{className:"min-h-[180px] max-h-[34%]",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading triage…"}),children:n.jsx(Nf,{model:$n,actions:Qn,onOpenDetail:Pn})})}),ke?n.jsxs("section",{className:pe("overflow-hidden rounded-xl border border-subtle bg-white/[0.02]",Ve.length===0?"flex-1 min-h-[220px]":"min-h-[220px] max-h-[50%]"),children:[n.jsxs("div",{className:"border-b border-subtle px-3 py-2.5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Decision queue"}),n.jsx("span",{className:"rounded-full bg-white/[0.08] px-1.5 py-0.5 text-[10px] font-semibold tabular-nums text-white/55",children:x.decisions.length})]}),n.jsx("p",{className:"mt-1 text-caption text-white/35",children:"Resolve blockers and approvals to keep dispatch moving."})]}),n.jsx("div",{className:"min-h-0 p-2",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"h-full min-h-[160px] rounded-lg border border-subtle bg-white/[0.02] p-4 text-body text-secondary",children:"Loading decisions…"}),children:n.jsx(jf,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",decisions:x.decisions,focusDecisionId:R,onFocusDecisionHandled:()=>$(null),onApproveDecision:S,onRejectDecision:W,onApproveAll:Y,onBulkDecisionAction:K,mutationState:me})})})]}):n.jsx(Hs,{className:"border border-subtle bg-white/[0.02] px-4 py-3 text-body text-secondary",children:"OrgX is not connected. Decision actions are hidden until connectivity returns."}),n.jsxs("section",{className:pe("flex min-h-[180px] flex-1 flex-col overflow-hidden rounded-xl border border-subtle bg-white/[0.02]"),children:[n.jsxs("div",{className:"border-b border-subtle px-3 py-2.5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-[0.14em] text-white/45",children:ke?"Blocked & review-required slices":"Needs attention"}),n.jsx("span",{className:"rounded-full bg-white/[0.08] px-1.5 py-0.5 text-[10px] font-semibold tabular-nums text-white/55",children:Ve.length})]}),n.jsx("p",{className:"mt-1 text-caption text-white/35",children:"Retry, approve, or manually intervene on execution slices."})]}),n.jsx("div",{className:"min-h-0 flex-1 p-2",children:n.jsx(Pu,{className:pe("h-full min-h-0"),title:ke?"Blocked & review-required slices":"Needs attention",showHeader:!1,panelStyle:"flat",sliceRuns:Te,initiatives:Vt,onOpenDecisions:()=>Wn(),onFocusRunId:bt,onReviewActivity:Zs,onOpenSliceDetail:rn,onAcceptSlice:_n})})]})]}):n.jsx(_u,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",sessions:Z,sliceRuns:Te,initiatives:Vt,needsAttentionCount:Pt,onSwitchToNeedsAttention:()=>Be("needs_attention"),onOpenSession:rt,onFocusRunId:bt,onPlayWorkstream:P,onPauseWorkstream:Et,onResumeWorkstream:P,onRestartSession:kr,onIntervene:hs,onOpenSliceDetail:mt}):n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading queue…"}),children:n.jsx(Af,{projectId:u,title:"Next Up",showHeader:!1,panelStyle:"flat",className:"h-full",compact:!1,selectionEnabled:!0,showQueueSettings:!0,queueModel:gt,queueActions:Wt,snapshotVersion:x.snapshotVersion,onOpenInitiative:Ys,onOpenSliceDetail:Yt})})},`${se}:${Pe}`)]}):n.jsx(Hs,{className:"card-enter",children:n.jsxs("button",{onClick:()=>U("initiatives"),className:"flex w-full items-center justify-between px-4 py-3 text-left transition-colors hover:bg-white/[0.03]",children:[n.jsx("div",{className:"flex items-center gap-2",children:n.jsx("h2",{className:"text-heading font-semibold text-white",children:"Initiatives"})}),n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"-rotate-90 text-muted",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]})})})})]}),n.jsx(pt,{children:Se&&Tt&&n.jsxs(n.Fragment,{children:[n.jsx(be.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed bottom-0 left-0 right-0 top-[64px] z-[240] hidden bg-black/40 backdrop-blur-sm lg:block",onClick:()=>Ae(!1)},"session-drawer-backdrop"),n.jsxs(be.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:400,damping:35},className:"fixed bottom-0 right-0 top-[64px] z-[250] hidden w-[480px] flex-col lg:flex",style:{backgroundColor:F.cardBg},children:[n.jsxs("div",{className:"flex items-center justify-between border-b border-subtle px-4 py-3",children:[n.jsx("h3",{className:"text-body font-semibold text-primary",children:"Session Detail"}),n.jsx("button",{type:"button",onClick:()=>Ae(!1),"aria-label":"Close session inspector",className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.03] text-primary transition-colors hover:bg-white/[0.08] hover:text-white",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6L6 18"}),n.jsx("path",{d:"M6 6l12 12"})]})})]}),n.jsx("div",{className:"flex-1 min-h-0",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading session detail…"}),children:n.jsx(kf,{session:Tt,activity:ae,initiatives:Vt,sliceRuns:Te,initialInterventionDraft:xe,onSubmitIntervention:br,onOpenActivityItem:ns,onContinueHighestPriority:ce,onDispatchSession:Fs,onPauseSession:vr,onResumeSession:at,onCancelSession:wt,onCreateCheckpoint:wr,onRollbackSession:Qs,onStartInitiative:ss,onStartWorkstream:In})})})]},"session-drawer-panel")]})}),l==="activity"?n.jsx(eu,{activeTab:je,onTabChange:$e,pendingDecisionCount:ke?x.decisions.length:0}):null,n.jsx(ai,{open:Ft!==null,onClose:de,maxWidth:"max-w-sm",fitContent:!0,children:n.jsxs("div",{className:"flex w-full flex-col",children:[n.jsxs("div",{className:"px-5 pt-5 pb-1",children:[n.jsx("h3",{className:"text-heading font-semibold text-white",children:(Ft==null?void 0:Ft.type)==="workstream"?"New Workstream":"New Initiative"}),n.jsx("p",{className:"mt-1 text-body leading-relaxed text-secondary",children:(Ft==null?void 0:Ft.type)==="workstream"?"Create a new workstream under the selected initiative.":"Create a new initiative to organize your work."})]}),n.jsxs("div",{className:"px-5 py-4",children:[n.jsx("label",{className:"mb-1.5 block text-caption uppercase tracking-[0.1em] text-secondary",children:"Name"}),n.jsx("input",{value:an,onChange:m=>ts(m.target.value),onKeyDown:m=>{m.key==="Enter"&&Js()},autoFocus:!0,"data-modal-autofocus":"true",placeholder:(Ft==null?void 0:Ft.type)==="workstream"?"e.g. User Onboarding Flow":"e.g. Q1 Product Launch",className:"w-full rounded-lg border border-strong bg-black/30 px-3 py-2.5 text-body text-white placeholder:text-muted focus:outline-none focus:ring-1 focus:ring-[#BFFF00]/40"})]}),n.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-subtle px-5 py-3",children:[n.jsx("button",{onClick:de,className:"rounded-md px-3 py-1.5 text-body text-secondary transition-colors hover:text-white",children:"Cancel"}),n.jsx("button",{onClick:Js,disabled:an.trim().length===0||vn,className:"rounded-md border border-lime/25 bg-lime/10 px-4 py-1.5 text-body font-semibold text-lime transition-colors hover:bg-lime/20 disabled:opacity-45",children:vn?"Creating…":"Create"})]})]})}),We.open&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Sf,{open:We.open,onClose:()=>ft(m=>({...m,open:!1,focusAgentDomain:null})),activeTab:We.tab,onChangeTab:m=>ft(A=>({...A,tab:m})),agentBehaviorInitialDomain:We.focusAgentDomain,demoMode:t,onToggleDemoMode:m=>{Jn(m),m||pn()},devMode:a,onToggleDevMode:c,showSyntheticEntities:r,onToggleShowSyntheticEntities:i,workspaceOptions:w,selectedWorkspaceId:u,onSelectWorkspace:h,onboarding:e,authToken:null,embedMode:!1})}),ot&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Df,{open:ot,selectedWorkspaceId:u,onClose:()=>nt(!1)})}),(we==="sessions"||we==="active"||we==="blocked"||we==="failed")&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(_f,{open:we==="sessions"||we==="active"||we==="blocked"||we==="failed",onClose:()=>Ge(null),mode:we==="active"||we==="blocked"||we==="failed"?we:"sessions",sessions:Z,onOpenSession:m=>{rt(m.id),Ge(null)},onRunAction:async(m,A)=>{await ln(m,A,{reason:`bulk_${A}_from_header`})},onRefetch:async()=>g(),onSetNotice:m=>M(m)})}),we==="decisions"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Cf,{open:we==="decisions",onClose:()=>Ge(null),decisions:ke?x.decisions:[],onApproveDecision:S,onRejectDecision:W,onApproveAll:Y,onBulkDecisionAction:K})}),we==="outbox"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Mf,{open:we==="outbox",onClose:()=>Ge(null),outbox:x.outbox,onOpenSettings:()=>{Ge(null),Ht("orgx")},onRefresh:()=>{g()}})}),we==="handoffs"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Tf,{open:we==="handoffs",onClose:()=>Ge(null),handoffs:x.handoffs})}),n.jsx(nh,{}),jt&&n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",children:n.jsx("div",{className:"relative w-full max-w-lg max-h-[80vh] overflow-hidden rounded-xl border border-subtle bg-[#0E0F11] shadow-2xl",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-8 text-center text-secondary",children:"Loading…"}),children:n.jsx(If,{item:jt,actions:Qn,onClose:()=>Dt(null),onNavigate:Rs,currentIndex:Ct,totalCount:Rt.length,decisions:ke?x.decisions:void 0,onApproveDecision:S,onRejectDecision:W})})})}),Qe&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Rf,{target:Qe,onClose:()=>Mt(null),onPlayWorkstream:async(m,A,E)=>{const N=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,workstreamId:A,agentId:E??void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})});if(!N.ok){const Q=await N.json().catch(()=>null);M(on((Q==null?void 0:Q.error)??(Q==null?void 0:Q.message)??null,`Failed to dispatch workstream (${N.status})`));return}M("Dispatched workstream."),g()},onStartAutoContinue:async(m,A,E)=>{await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,workstreamId:A,placement:"top"})});const N=await fetch("/orgx/api/mission-control/auto-continue/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,agentId:E??void 0,ignoreSpawnGuardRateLimit:!0})});if(!N.ok){const Q=await N.json().catch(()=>null);M(on((Q==null?void 0:Q.error)??(Q==null?void 0:Q.message)??null,`Failed to start auto-continue (${N.status})`));return}M("Auto-continue started."),g()},onMoveWorkstream:async(m,A,E)=>{const N=await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,workstreamId:A,placement:E})});if(!N.ok){const Q=await N.json().catch(()=>null);M(on((Q==null?void 0:Q.error)??(Q==null?void 0:Q.message)??null,`Move failed (${N.status})`));return}M(`Moved workstream to ${E}.`),g()},onRemoveFromQueue:async(m,A)=>{const E=await fetch("/orgx/api/mission-control/next-up/remove",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,workstreamId:A})});if(!E.ok){const N=await E.json().catch(()=>null);M(on((N==null?void 0:N.error)??(N==null?void 0:N.message)??null,`Remove failed (${E.status})`));return}M("Removed workstream from queue."),g()},onOpenSession:rt,onFocusRunId:bt,onOpenInitiative:Ys,onReviewActivity:Zs,onOpenDecisions:()=>Wn(),onAcceptSlice:_n,onRejectSlice:ps})})]})}typeof window<"u"&&window.addEventListener("vite:preloadError",e=>{e.preventDefault(),window.location.reload()});Kc();const rh=new $l({defaultOptions:{queries:{staleTime:3e4,retry:1,refetchOnWindowFocus:!1,refetchOnReconnect:!0}}});Ll.createRoot(document.getElementById("root")).render(n.jsx(o.StrictMode,{children:n.jsx(Fl,{client:rh,children:n.jsx(Yf,{})})}));export{ou as $,Ot as A,gd as B,fh as C,rs as D,yn as E,os as F,Hm as G,mh as H,yh as I,_s as J,It as K,Vs as L,Yr as M,nd as N,Pd as O,Hs as P,Od as Q,Gt as R,Wd as S,gh as T,td as U,Kd as V,Gl as W,ph as X,yu as Y,xh as Z,gn as _,qu as a,uh as a0,tr as a1,Gr as a2,_t as b,Rc as c,F as d,lm as e,vh as f,As as g,bn as h,$t as i,Nh as j,dl as k,jh as l,hh as m,zt as n,wh as o,bh as p,Gn as q,ai as r,kh as s,zu as t,yd as u,us as v,pe as w,Bt as x,ms as y,as as z};