@runfusion/fusion 0.77.0-beta.2 → 0.77.0-beta.4

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 (173) hide show
  1. package/dist/bin.js +12324 -8618
  2. package/dist/child-process-worker.js +8252 -6106
  3. package/dist/client/.vite/manifest.json +294 -267
  4. package/dist/client/assets/{AgentDetailView-Dew3af1O.js → AgentDetailView-CH6GtXl9.js} +3 -3
  5. package/dist/client/assets/{AgentPermissionPolicyEditor-CxPQffiY.js → AgentPermissionPolicyEditor-YTEpMhUx.js} +1 -1
  6. package/dist/client/assets/{AgentsView-Cr4LDGdt.js → AgentsView-XOHHDo4a.js} +4 -4
  7. package/dist/client/assets/ChatView-gH7QX3TI.js +13 -0
  8. package/dist/client/assets/{CommandCenter-DCC90LOP.js → CommandCenter-BsH-R15f.js} +3 -3
  9. package/dist/client/assets/{DevServerView-B5b520w6.js → DevServerView-CKOa-lkc.js} +1 -1
  10. package/dist/client/assets/{DirectoryPicker-1JvRd5mC.js → DirectoryPicker-DHUYTE-j.js} +1 -1
  11. package/dist/client/assets/DocumentsView-BPzrxeP-.js +1 -0
  12. package/dist/client/assets/{EvalsView-a3LhgRSo.js → EvalsView-DojCiv47.js} +1 -1
  13. package/dist/client/assets/{ExperimentalAgentOnboardingModal-vdVa8h7F.js → ExperimentalAgentOnboardingModal-DuurZ8qe.js} +1 -1
  14. package/dist/client/assets/{GoalsView-Dz2o91fd.js → GoalsView-DDWPXcG1.js} +1 -1
  15. package/dist/client/assets/{InsightsView-De3R_46d.js → InsightsView-CgkMOD1A.js} +3 -3
  16. package/dist/client/assets/MemoryView-Cj49_z7O.js +3 -0
  17. package/dist/client/assets/{PiExtensionsManager-C9JABO_4.js → PiExtensionsManager-B_rRJiOd.js} +1 -1
  18. package/dist/client/assets/PluginManager-Dxwi88oY.js +1 -0
  19. package/dist/client/assets/{PullRequestView-DT8vTeVi.js → PullRequestView-z-5v2hQT.js} +2 -2
  20. package/dist/client/assets/ReportModal-DmOPEYWp.js +21 -0
  21. package/dist/client/assets/ReportModal-lzN_xrnM.css +1 -0
  22. package/dist/client/assets/{ResearchView-cNsjYu8F.js → ResearchView-D90Jbzbx.js} +2 -2
  23. package/dist/client/assets/{SecretsView-BAmf7KyS.js → SecretsView-CSyjZl5L.js} +1 -1
  24. package/dist/client/assets/SessionTerminal-Bwb8nGmU.js +2 -0
  25. package/dist/client/assets/SettingsModal-BAzmMjr9.js +21 -0
  26. package/dist/client/assets/SettingsModal-C5ic1ls7.css +1 -0
  27. package/dist/client/assets/{SettingsModal-C_9RiEI7.js → SettingsModal-CJof1Ett.js} +1 -1
  28. package/dist/client/assets/{SettingsTextareaRow-D8RHSj8b.js → SettingsTextareaRow-BYchnHfW.js} +1 -1
  29. package/dist/client/assets/SetupWizardModal-NqV-erVf.js +2 -0
  30. package/dist/client/assets/{SkillsView-DyeCwYit.js → SkillsView-BUrkIJ-p.js} +1 -1
  31. package/dist/client/assets/{WorkflowNodeEditor-C5Jc9w_A.js → WorkflowNodeEditor-DcPk2A1Z.js} +1 -1
  32. package/dist/client/assets/{agent-import-generation-SCPNeF25.js → agent-import-generation-X16OLfrL.js} +1 -1
  33. package/dist/client/assets/{agentsOrgChartLayout-CqKtNCjy.js → agentsOrgChartLayout-BhPIXckU.js} +1 -1
  34. package/dist/client/assets/app-B-TfWH9b.js +5 -0
  35. package/dist/client/assets/app-B2RDV_-t.js +13 -0
  36. package/dist/client/assets/app-CDo0mF2S.js +5 -0
  37. package/dist/client/assets/app-Cc18kAQS.js +13 -0
  38. package/dist/client/assets/app-DFF79EUn.js +13 -0
  39. package/dist/client/assets/app-DSeFHxgj.js +13 -0
  40. package/dist/client/assets/app-Ducr0y6r.js +13 -0
  41. package/dist/client/assets/{architectureDiagram-3BPJPVTR-Cz2HYn0b.js → architectureDiagram-3BPJPVTR-WArMtdqy.js} +1 -1
  42. package/dist/client/assets/{blockDiagram-GPEHLZMM-IimJVscG.js → blockDiagram-GPEHLZMM-emScogdV.js} +1 -1
  43. package/dist/client/assets/{c4Diagram-AAUBKEIU-C-xii7zn.js → c4Diagram-AAUBKEIU-CBY7-E0T.js} +1 -1
  44. package/dist/client/assets/channel-CP2ySYs0.js +1 -0
  45. package/dist/client/assets/{chunk-2J33WTMH-DQ-9Xccu.js → chunk-2J33WTMH-Bcai1sOm.js} +1 -1
  46. package/dist/client/assets/{chunk-4BX2VUAB-DmdAX9Bx.js → chunk-4BX2VUAB-hjiKRusj.js} +1 -1
  47. package/dist/client/assets/{chunk-55IACEB6-IF2bk5IL.js → chunk-55IACEB6-DpO9nIb0.js} +1 -1
  48. package/dist/client/assets/{chunk-727SXJPM-AeYpIzVu.js → chunk-727SXJPM-B9JanA0o.js} +1 -1
  49. package/dist/client/assets/{chunk-AQP2D5EJ-DV942DD9.js → chunk-AQP2D5EJ-D6zdnEUE.js} +1 -1
  50. package/dist/client/assets/{chunk-FMBD7UC4-Bt_riVlZ.js → chunk-FMBD7UC4-CRkrJ51d.js} +1 -1
  51. package/dist/client/assets/{chunk-ND2GUHAM-CbyjNbXR.js → chunk-ND2GUHAM-BLQsKt7a.js} +1 -1
  52. package/dist/client/assets/{chunk-QZHKN3VN-DqiRniYQ.js → chunk-QZHKN3VN-MCOlJ723.js} +1 -1
  53. package/dist/client/assets/classDiagram-4FO5ZUOK-DKkOBtzM.js +1 -0
  54. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-DKkOBtzM.js +1 -0
  55. package/dist/client/assets/{cose-bilkent-S5V4N54A-UCvthviL.js → cose-bilkent-S5V4N54A-Cv1XmKKG.js} +1 -1
  56. package/dist/client/assets/{dagre-BM42HDAG-DnMlT1Oi.js → dagre-BM42HDAG-flnNS_RW.js} +1 -1
  57. package/dist/client/assets/{dashboard-view-C9D0aoRW.js → dashboard-view-CC1aH-lp.js} +1 -1
  58. package/dist/client/assets/{dashboard-view-myjM9tr8.js → dashboard-view-CrV-rL9Q.js} +1 -1
  59. package/dist/client/assets/{dashboard-view-JysoyDRX.js → dashboard-view-DEAYb_TZ.js} +1 -1
  60. package/dist/client/assets/{dashboard-view-Cz0sp2Wl.js → dashboard-view-Dz7kqcJc.js} +1 -1
  61. package/dist/client/assets/{diagram-2AECGRRQ-BYFiqXGw.js → diagram-2AECGRRQ-Z3S7b_6_.js} +1 -1
  62. package/dist/client/assets/{diagram-5GNKFQAL-DZU3pSYq.js → diagram-5GNKFQAL-BAZHdMFq.js} +1 -1
  63. package/dist/client/assets/{diagram-KO2AKTUF-0ybdKuMm.js → diagram-KO2AKTUF-C2y3S8F0.js} +1 -1
  64. package/dist/client/assets/{diagram-LMA3HP47-Rxbgnbsp.js → diagram-LMA3HP47-Bfz0_IvT.js} +1 -1
  65. package/dist/client/assets/{diagram-OG6HWLK6-BAU_hTeV.js → diagram-OG6HWLK6-BBmSQsTI.js} +1 -1
  66. package/dist/client/assets/{erDiagram-TEJ5UH35-zr8HrwTt.js → erDiagram-TEJ5UH35-DnpdQi66.js} +1 -1
  67. package/dist/client/assets/{flowDiagram-I6XJVG4X-CrTw0iFw.js → flowDiagram-I6XJVG4X-IybTR_zf.js} +1 -1
  68. package/dist/client/assets/{folder-open-DnAlsXXn.js → folder-open-Dntm63x4.js} +1 -1
  69. package/dist/client/assets/{ganttDiagram-6RSMTGT7-CCORsxxz.js → ganttDiagram-6RSMTGT7-DEQOe2E9.js} +1 -1
  70. package/dist/client/assets/{gitGraphDiagram-PVQCEYII-C07wWSjj.js → gitGraphDiagram-PVQCEYII-BOKc-h63.js} +1 -1
  71. package/dist/client/assets/index-DXpztECA.css +1 -0
  72. package/dist/client/assets/index-I32FijPT.js +2821 -0
  73. package/dist/client/assets/{infoDiagram-5YYISTIA-hAeccD_4.js → infoDiagram-5YYISTIA-LqaYIdbj.js} +1 -1
  74. package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-WLCzv-NH.js → ishikawaDiagram-YF4QCWOH-a8qd512s.js} +1 -1
  75. package/dist/client/assets/{journeyDiagram-JHISSGLW-ClnasNhy.js → journeyDiagram-JHISSGLW-BgoNyeiy.js} +1 -1
  76. package/dist/client/assets/{kanban-definition-UN3LZRKU-CAuARhUz.js → kanban-definition-UN3LZRKU-Bqwow7D3.js} +1 -1
  77. package/dist/client/assets/{mermaid.core-Bh02RvfX.js → mermaid.core-B2zD934i.js} +4 -4
  78. package/dist/client/assets/{mindmap-definition-RKZ34NQL-KNTlbW4V.js → mindmap-definition-RKZ34NQL-CCTOigWu.js} +1 -1
  79. package/dist/client/assets/{pieDiagram-4H26LBE5-BouAfBEw.js → pieDiagram-4H26LBE5-Bq5DtXKR.js} +1 -1
  80. package/dist/client/assets/pixelify-sans-cyrillic-400-normal-DfOZNMlW.woff +0 -0
  81. package/dist/client/assets/pixelify-sans-latin-400-normal-DLrIX9QE.woff2 +0 -0
  82. package/dist/client/assets/pixelify-sans-latin-400-normal-JapMNN6Z.woff +0 -0
  83. package/dist/client/assets/pixelify-sans-latin-ext-400-normal-BkfTUL4s.woff +0 -0
  84. package/dist/client/assets/pixelify-sans-latin-ext-400-normal-DdH6zlBQ.woff2 +0 -0
  85. package/dist/client/assets/{puzzle-CC8Ur3Cy.js → puzzle-VhTPiCit.js} +1 -1
  86. package/dist/client/assets/{quadrantDiagram-W4KKPZXB-wTdkCUJU.js → quadrantDiagram-W4KKPZXB-CGMP3nUx.js} +1 -1
  87. package/dist/client/assets/{requirementDiagram-4Y6WPE33-BnjY4Tc_.js → requirementDiagram-4Y6WPE33-Ckeu_szu.js} +1 -1
  88. package/dist/client/assets/{sankeyDiagram-5OEKKPKP-C-QsS08u.js → sankeyDiagram-5OEKKPKP-SWbBDD4d.js} +1 -1
  89. package/dist/client/assets/{sequenceDiagram-3UESZ5HK-DD36MILE.js → sequenceDiagram-3UESZ5HK-CiJrmL_G.js} +1 -1
  90. package/dist/client/assets/{shield-alert-DcXc56Fy.js → shield-alert-BBDlP6A5.js} +1 -1
  91. package/dist/client/assets/{standing-instructions-template-BF5y1BLz.js → standing-instructions-template-viu_kgDX.js} +2 -2
  92. package/dist/client/assets/{stateDiagram-AJRCARHV-WTq1wQr1.js → stateDiagram-AJRCARHV-DTCzK5Gt.js} +1 -1
  93. package/dist/client/assets/{stateDiagram-v2-BHNVJYJU-eILJdjII.js → stateDiagram-v2-BHNVJYJU-BIGAwFTT.js} +1 -1
  94. package/dist/client/assets/{timeline-definition-PNZ67QCA-PRNwI0NR.js → timeline-definition-PNZ67QCA-BQZEFEug.js} +1 -1
  95. package/dist/client/assets/{upload-qH_64O-B.js → upload-D5w3Ehwp.js} +1 -1
  96. package/dist/client/assets/{useDiscoveredSkillsCache-C-GPCNaO.js → useDiscoveredSkillsCache-D6zMSIaS.js} +1 -1
  97. package/dist/client/assets/{users-D2UesRE4.js → users-Bohihi_o.js} +1 -1
  98. package/dist/client/assets/{vennDiagram-CIIHVFJN-CG2Z4T4O.js → vennDiagram-CIIHVFJN-DnHguEv8.js} +1 -1
  99. package/dist/client/assets/{wardley-L42UT6IY-gO_fGvF9.js → wardley-L42UT6IY-BOqYltGN.js} +1 -1
  100. package/dist/client/assets/{wardleyDiagram-YWT4CUSO-BkyNpjUb.js → wardleyDiagram-YWT4CUSO-Re0Ery2M.js} +1 -1
  101. package/dist/client/assets/{xychartDiagram-2RQKCTM6-CMlZsiPq.js → xychartDiagram-2RQKCTM6-CnVq21b2.js} +1 -1
  102. package/dist/client/index.html +4 -4
  103. package/dist/client/theme-data.css +183 -1
  104. package/dist/client/version.json +1 -1
  105. package/dist/droid-cli/package.json +1 -1
  106. package/dist/extension.js +9275 -6726
  107. package/dist/pi-claude-cli/package.json +1 -1
  108. package/dist/pi-claude-cli/src/__tests__/event-bridge.test.ts +29 -1
  109. package/dist/pi-claude-cli/src/event-bridge.ts +10 -4
  110. package/dist/plugin-sdk/index.d.ts +25 -3
  111. package/dist/plugin-sdk/index.js +10 -1
  112. package/dist/plugins/fusion-plugin-acp-runtime/bundled.js +12 -2
  113. package/dist/plugins/fusion-plugin-acp-runtime/package.json +1 -1
  114. package/dist/plugins/fusion-plugin-claude-runtime/bundled.js +12 -2
  115. package/dist/plugins/fusion-plugin-claude-runtime/package.json +1 -1
  116. package/dist/plugins/fusion-plugin-cli-printing-press/bundled.js +10 -1
  117. package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
  118. package/dist/plugins/fusion-plugin-compound-engineering/bundled.js +10 -1
  119. package/dist/plugins/fusion-plugin-compound-engineering/package.json +1 -1
  120. package/dist/plugins/fusion-plugin-cursor-runtime/bundled.js +10 -1
  121. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
  122. package/dist/plugins/fusion-plugin-dependency-graph/bundled.js +10 -1
  123. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  124. package/dist/plugins/fusion-plugin-droid-runtime/bundled.js +12 -2
  125. package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
  126. package/dist/plugins/fusion-plugin-grok-runtime/bundled.js +12 -2
  127. package/dist/plugins/fusion-plugin-grok-runtime/package.json +1 -1
  128. package/dist/plugins/fusion-plugin-hermes-runtime/bundled.js +10 -1
  129. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  130. package/dist/plugins/fusion-plugin-linear-import/bundled.js +10 -1
  131. package/dist/plugins/fusion-plugin-linear-import/package.json +1 -1
  132. package/dist/plugins/fusion-plugin-omp-runtime/bundled.js +12 -2
  133. package/dist/plugins/fusion-plugin-omp-runtime/package.json +1 -1
  134. package/dist/plugins/fusion-plugin-openclaw-runtime/bundled.js +10 -1
  135. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  136. package/dist/plugins/fusion-plugin-paperclip-runtime/bundled.js +10 -1
  137. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  138. package/dist/plugins/fusion-plugin-quality/bundled.js +10 -1
  139. package/dist/plugins/fusion-plugin-quality/package.json +1 -1
  140. package/dist/plugins/fusion-plugin-reports/bundled.js +10 -1
  141. package/dist/plugins/fusion-plugin-reports/package.json +1 -1
  142. package/dist/plugins/fusion-plugin-roadmap/bundled.js +10 -1
  143. package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
  144. package/dist/plugins/fusion-plugin-todos/bundled.js +10 -1
  145. package/dist/plugins/fusion-plugin-todos/package.json +1 -1
  146. package/dist/plugins/fusion-plugin-whatsapp-chat/bundled.js +10 -1
  147. package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
  148. package/package.json +1 -1
  149. package/skill/fusion/SKILL.md +1 -1
  150. package/skill/fusion/references/extension-tools.md +17 -0
  151. package/skill/fusion/references/fusion-capabilities.md +2 -0
  152. package/dist/client/assets/ChatView-cNYtYx05.js +0 -13
  153. package/dist/client/assets/DocumentsView-ksK9f7xt.js +0 -1
  154. package/dist/client/assets/MemoryView-Cagk2wZG.js +0 -3
  155. package/dist/client/assets/PluginManager-D2csmdQa.js +0 -1
  156. package/dist/client/assets/ReportModal-M3uh98sc.css +0 -1
  157. package/dist/client/assets/ReportModal-YMP6V4vu.js +0 -21
  158. package/dist/client/assets/SessionTerminal-BjGcxq22.js +0 -2
  159. package/dist/client/assets/SettingsModal-C0FY8MPW.css +0 -1
  160. package/dist/client/assets/SettingsModal-DLfy2e_5.js +0 -21
  161. package/dist/client/assets/SetupWizardModal-DRJ96pHQ.js +0 -2
  162. package/dist/client/assets/app-BgpuMvTU.js +0 -13
  163. package/dist/client/assets/app-BlexHhbW.js +0 -13
  164. package/dist/client/assets/app-BsuUOR0P.js +0 -13
  165. package/dist/client/assets/app-DQVOujmO.js +0 -13
  166. package/dist/client/assets/app-DjyTRx1N.js +0 -5
  167. package/dist/client/assets/app-Dniggype.js +0 -13
  168. package/dist/client/assets/app-EV-lyZ0T.js +0 -5
  169. package/dist/client/assets/channel-D-UHgx8G.js +0 -1
  170. package/dist/client/assets/classDiagram-4FO5ZUOK-Do-8MdAc.js +0 -1
  171. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-Do-8MdAc.js +0 -1
  172. package/dist/client/assets/index-B_z7OKl4.js +0 -2818
  173. package/dist/client/assets/index-DPo-IAb2.css +0 -1
@@ -1,4 +1,4 @@
1
- import{r as f,j as s,g as mn,a as aj,b as Jl,c as ij}from"./vendor-react-SZ_qB27O.js";import{c as Vt,h6 as sj,dZ as Nh,L as Ql,l as Mi,h7 as Ii,a as fr,w as mr,aX as vn,h8 as ec,h9 as oj,a$ as Zr,as as el,ae as Ph,a3 as La,F as tn,b2 as lj,b4 as cj,P as zn,b0 as uj,ha as Ah,bV as Di,bh as qa,ag as tc,hb as $u,R as Gt,az as dj,hc as fj,aM as mj,aT as Ri,hd as Oh,ei as vj,aY as Eh,da as _h,bL as hj,aK as rc,bX as pj,he as yj,ar as gj,fw as bj,hf as xj,aj as Th,hg as jj,hh as wj,cV as Fu,hi as Bu,fI as Cj,gM as Ps,hj as zu,hk as ga,hl as kj,hm as Sj,hn as Nj,ho as Pj,gN as Aj,hp as Oj,hq as Ej,hr as _j,gJ as Tj,hs as Mj,G as Ij,aN as Dj,gO as Mh,ht as Rj,c3 as Lj,B as $j,hu as Fj,au as Bj,hv as As,hw as zj,hx as Kj,hy as Vj,hz as Uj,hA as qj,hB as Wj,hC as nc,hD as ac,hE as Ku,c_ as Wa,hF as Vu,hG as tl,hH as Ih,hI as rl,bi as Dh,bW as Rh,bY as Lh,dl as Hj,d6 as Gj,K as ic,C as sc,hJ as Xj,hK as Yj,D as Zj,eZ as Uu,X as $a,E as Jj,y as Qj,b1 as qu,aI as e0,hL as Wu,hM as t0,hN as r0,hO as n0,hP as a0,eg as i0,hQ as Os,hR as s0,hS as o0,hT as l0}from"./index-B_z7OKl4.js";import{u as se}from"./vendor-i18n-Duky4gdQ.js";import{a as $h,b as Fh,p as c0,w as u0}from"./vendor-reactflow-BlIeoTu4.js";import{w as Bh,n as zh,a as Me,A as oc,G as d0,H as f0,l as Kh,t as Li,b as _t,p as nl,s as Ha,c as Vh,q as m0,r as v0,u as h0,v as p0,x as y0,y as g0,z as b0,C as x0,D as j0,k as w0,E as C0,F as k0}from"./step-yuy0qJer.js";import{b as S0,p as N0}from"./band-CquvqAHh.js";import{d as Ga,n as P0,e as A0,f as al,g as Br,h as lc,a as cc,i as Hu,j as Ht,c as O0,k as $i,l as E0,m as _0}from"./linear-Dyk9wory.js";import{i as pr,a as Qt}from"./init-Dmth1JHB.js";import{m as Gu,a as Xu,p as T0,q as M0,u as I0,s as D0,r as R0,v as L0,w as $0,x as F0,y as B0,z as z0,A as K0,B as V0,t as U0}from"./time-2wBVBf9F.js";import{f as q0,b as W0}from"./defaultLocale-DX6XiGOO.js";import{i as H0,o as G0}from"./ordinal-DILIJJjt.js";import{g as X0,i as il,r as Y0}from"./agentsOrgChartLayout-CqKtNCjy.js";import{U as uc}from"./upload-qH_64O-B.js";import{S as Z0}from"./shield-alert-DcXc56Fy.js";import{b as J0}from"./agent-import-generation-SCPNeF25.js";import{r as Q0,B as ew,R as tw,b as rw,a as nw}from"./ReportModal-YMP6V4vu.js";import{PluginManager as aw}from"./PluginManager-D2csmdQa.js";import{v as iw}from"./projectDetection-G3XuxD2X.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-xterm-BNq00GSj.js";import"./DirectoryPicker-1JvRd5mC.js";import"./folder-open-DnAlsXXn.js";/**
1
+ import{r as f,j as s,g as mn,a as aj,b as Jl,c as ij}from"./vendor-react-SZ_qB27O.js";import{c as Vt,hi as sj,dX as Nh,L as Ql,l as Mi,hj as Ii,a as fr,w as mr,aZ as vn,hk as ec,hl as oj,b1 as Zr,as as el,ae as Ph,a3 as La,F as tn,b4 as lj,b6 as cj,P as zn,b2 as uj,hm as Ah,bX as Di,bj as qa,ag as tc,hn as $u,R as Gt,az as dj,ho as fj,aM as mj,aV as Ri,hp as Oh,eo as vj,a_ as Eh,dc as _h,bN as hj,aK as rc,bZ as pj,hq as yj,ar as gj,fD as bj,hr as xj,aj as Th,hs as jj,ht as wj,cX as Fu,hu as Bu,fP as Cj,gY as Ps,hv as zu,hw as ga,hx as kj,hy as Sj,hz as Nj,hA as Pj,gZ as Aj,hB as Oj,hC as Ej,hD as _j,gV as Tj,hE as Mj,G as Ij,aN as Dj,g_ as Mh,hF as Rj,c5 as Lj,B as $j,hG as Fj,au as Bj,hH as As,hI as zj,hJ as Kj,hK as Vj,hL as Uj,hM as qj,hN as Wj,hO as nc,hP as ac,hQ as Ku,d0 as Wa,hR as Vu,hS as tl,hT as Ih,hU as rl,bk as Dh,bY as Rh,b_ as Lh,dn as Hj,d8 as Gj,K as ic,C as sc,hV as Xj,hW as Yj,D as Zj,f4 as Uu,X as $a,E as Jj,y as Qj,b3 as qu,aI as e0,hX as Wu,hY as t0,hZ as r0,h_ as n0,h$ as a0,em as i0,i0 as Os,i1 as s0,i2 as o0,i3 as l0}from"./index-I32FijPT.js";import{u as se}from"./vendor-i18n-Duky4gdQ.js";import{a as $h,b as Fh,p as c0,w as u0}from"./vendor-reactflow-BlIeoTu4.js";import{w as Bh,n as zh,a as Me,A as oc,G as d0,H as f0,l as Kh,t as Li,b as _t,p as nl,s as Ha,c as Vh,q as m0,r as v0,u as h0,v as p0,x as y0,y as g0,z as b0,C as x0,D as j0,k as w0,E as C0,F as k0}from"./step-yuy0qJer.js";import{b as S0,p as N0}from"./band-CquvqAHh.js";import{d as Ga,n as P0,e as A0,f as al,g as Br,h as lc,a as cc,i as Hu,j as Ht,c as O0,k as $i,l as E0,m as _0}from"./linear-Dyk9wory.js";import{i as pr,a as Qt}from"./init-Dmth1JHB.js";import{m as Gu,a as Xu,p as T0,q as M0,u as I0,s as D0,r as R0,v as L0,w as $0,x as F0,y as B0,z as z0,A as K0,B as V0,t as U0}from"./time-2wBVBf9F.js";import{f as q0,b as W0}from"./defaultLocale-DX6XiGOO.js";import{i as H0,o as G0}from"./ordinal-DILIJJjt.js";import{g as X0,i as il,r as Y0}from"./agentsOrgChartLayout-BhPIXckU.js";import{U as uc}from"./upload-D5w3Ehwp.js";import{S as Z0}from"./shield-alert-BBDlP6A5.js";import{b as J0}from"./agent-import-generation-X16OLfrL.js";import{r as Q0,B as ew,R as tw,b as rw,a as nw}from"./ReportModal-DmOPEYWp.js";import{PluginManager as aw}from"./PluginManager-Dxwi88oY.js";import{v as iw}from"./projectDetection-G3XuxD2X.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-xterm-BNq00GSj.js";import"./DirectoryPicker-DHUYTE-j.js";import"./folder-open-Dntm63x4.js";/**
2
2
  * @license lucide-react v1.7.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -96,7 +96,7 @@ import{r as f,j as s,g as mn,a as aj,b as Jl,c as ij}from"./vendor-react-SZ_qB27
96
96
  * This source code is licensed under the MIT license found in the
97
97
  * LICENSE file in the root directory of this source tree.
98
98
  */var gv;function KT(){if(gv)return he;gv=1;var e=60103,t=60106,r=60107,n=60108,a=60114,i=60109,o=60110,l=60112,c=60113,d=60120,u=60115,m=60116,h=60121,v=60122,p=60117,b=60129,y=60131;if(typeof Symbol=="function"&&Symbol.for){var g=Symbol.for;e=g("react.element"),t=g("react.portal"),r=g("react.fragment"),n=g("react.strict_mode"),a=g("react.profiler"),i=g("react.provider"),o=g("react.context"),l=g("react.forward_ref"),c=g("react.suspense"),d=g("react.suspense_list"),u=g("react.memo"),m=g("react.lazy"),h=g("react.block"),v=g("react.server.block"),p=g("react.fundamental"),b=g("react.debug_trace_mode"),y=g("react.legacy_hidden")}function j(I){if(typeof I=="object"&&I!==null){var z=I.$$typeof;switch(z){case e:switch(I=I.type,I){case r:case a:case n:case c:case d:return I;default:switch(I=I&&I.$$typeof,I){case o:case l:case m:case u:case i:return I;default:return z}}case t:return z}}}var x=i,C=e,w=l,P=r,A=m,S=u,N=t,E=a,T=n,O=c;return he.ContextConsumer=o,he.ContextProvider=x,he.Element=C,he.ForwardRef=w,he.Fragment=P,he.Lazy=A,he.Memo=S,he.Portal=N,he.Profiler=E,he.StrictMode=T,he.Suspense=O,he.isAsyncMode=function(){return!1},he.isConcurrentMode=function(){return!1},he.isContextConsumer=function(I){return j(I)===o},he.isContextProvider=function(I){return j(I)===i},he.isElement=function(I){return typeof I=="object"&&I!==null&&I.$$typeof===e},he.isForwardRef=function(I){return j(I)===l},he.isFragment=function(I){return j(I)===r},he.isLazy=function(I){return j(I)===m},he.isMemo=function(I){return j(I)===u},he.isPortal=function(I){return j(I)===t},he.isProfiler=function(I){return j(I)===a},he.isStrictMode=function(I){return j(I)===n},he.isSuspense=function(I){return j(I)===c},he.isValidElementType=function(I){return typeof I=="string"||typeof I=="function"||I===r||I===a||I===b||I===n||I===c||I===d||I===y||typeof I=="object"&&I!==null&&(I.$$typeof===m||I.$$typeof===u||I.$$typeof===i||I.$$typeof===o||I.$$typeof===l||I.$$typeof===p||I.$$typeof===h||I[0]===v)},he.typeOf=j,he}var bv;function VT(){return bv||(bv=1,$o.exports=KT()),$o.exports}var UT=VT(),xv=e=>typeof e=="string"?e:e?e.displayName||e.name||"Component":"",jv=null,Fo=null,Bb=e=>{if(e===jv&&Array.isArray(Fo))return Fo;var t=[];return f.Children.forEach(e,r=>{ze(r)||(UT.isFragment(r)?t=t.concat(Bb(r.props.children)):t.push(r))}),Fo=t,jv=e,t};function zb(e,t){var r=[],n=[];return Array.isArray(t)?n=t.map(a=>xv(a)):n=[xv(t)],Bb(e).forEach(a=>{var i=Mr(a,"type.displayName")||Mr(a,"type.name");i&&n.indexOf(i)!==-1&&r.push(a)}),r}var Kb=e=>e&&typeof e=="object"&&"clipDot"in e?!!e.clipDot:!0,Bo={},wv;function qT(){return wv||(wv=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(r){if(typeof r!="object"||r==null)return!1;if(Object.getPrototypeOf(r)===null)return!0;if(Object.prototype.toString.call(r)!=="[object Object]"){const a=r[Symbol.toStringTag];return a==null||!Object.getOwnPropertyDescriptor(r,Symbol.toStringTag)?.writable?!1:r.toString()===`[object ${a}]`}let n=r;for(;Object.getPrototypeOf(n)!==null;)n=Object.getPrototypeOf(n);return Object.getPrototypeOf(r)===n}e.isPlainObject=t})(Bo)),Bo}var zo,Cv;function WT(){return Cv||(Cv=1,zo=qT().isPlainObject),zo}var HT=WT();const GT=mn(HT);var kv,Sv,Nv,Pv,Av;function Ov(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Ev(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Ov(Object(r),!0).forEach(function(n){XT(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Ov(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function XT(e,t,r){return(t=YT(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function YT(e){var t=ZT(e,"string");return typeof t=="symbol"?t:t+""}function ZT(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function wi(){return wi=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},wi.apply(null,arguments)}function On(e,t){return t||(t=e.slice(0)),Object.freeze(Object.defineProperties(e,{raw:{value:Object.freeze(t)}}))}var _v=(e,t,r,n,a)=>{var i=r-n,o;return o=_e(kv||(kv=On(["M ",",",""])),e,t),o+=_e(Sv||(Sv=On(["L ",",",""])),e+r,t),o+=_e(Nv||(Nv=On(["L ",",",""])),e+r-i/2,t+a),o+=_e(Pv||(Pv=On(["L ",",",""])),e+r-i/2-n,t+a),o+=_e(Av||(Av=On(["L ",","," Z"])),e,t),o},JT={x:0,y:0,upperWidth:0,lowerWidth:0,height:0,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},QT=e=>{var t=Ke(e,JT),{x:r,y:n,upperWidth:a,lowerWidth:i,height:o,className:l}=t,{animationEasing:c,animationDuration:d,animationBegin:u,isUpdateAnimationActive:m}=t,h=f.useRef(null),[v,p]=f.useState(-1),b=f.useRef(a),y=f.useRef(i),g=f.useRef(o),j=f.useRef(r),x=f.useRef(n),C=os(e,"trapezoid-");if(f.useEffect(()=>{if(h.current&&h.current.getTotalLength)try{var z=h.current.getTotalLength();z&&p(z)}catch{}},[]),r!==+r||n!==+n||a!==+a||i!==+i||o!==+o||a===0&&i===0||o===0)return null;var w=ve("recharts-trapezoid",l);if(!m)return f.createElement("g",null,f.createElement("path",wi({},st(t),{className:w,d:_v(r,n,a,i,o)})));var P=b.current,A=y.current,S=g.current,N=j.current,E=x.current,T="0px ".concat(v===-1?1:v,"px"),O="".concat(v,"px ").concat(v,"px"),I=My(["strokeDasharray"],d,c);return f.createElement(ss,{animationId:C,key:C,canBegin:v>0,duration:d,easing:c,isActive:m,begin:u},z=>{var D=tt(P,a,z),V=tt(A,i,z),B=tt(S,o,z),W=tt(N,r,z),K=tt(E,n,z);h.current&&(b.current=D,y.current=V,g.current=B,j.current=W,x.current=K);var te=z>0?{transition:I,strokeDasharray:O}:{strokeDasharray:T};return f.createElement("path",wi({},st(t),{className:w,d:_v(W,K,D,V,B),ref:h,style:Ev(Ev({},te),t.style)}))})},eM=["option","shapeType","activeClassName","inActiveClassName"];function tM(e,t){if(e==null)return{};var r,n,a=rM(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function rM(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}function Tv(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Ci(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Tv(Object(r),!0).forEach(function(n){nM(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Tv(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function nM(e,t,r){return(t=aM(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function aM(e){var t=iM(e,"string");return typeof t=="symbol"?t:t+""}function iM(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function sM(e,t){return Ci(Ci({},t),e)}function oM(e,t){return e==="symbols"}function Mv(e){var{shapeType:t,elementProps:r}=e;switch(t){case"rectangle":return f.createElement(Ly,r);case"trapezoid":return f.createElement(QT,r);case"sector":return f.createElement(zy,r);case"symbols":if(oM(t))return f.createElement(Cc,r);break;case"curve":return f.createElement(Bc,r);default:return null}}function lM(e){return f.isValidElement(e)?e.props:e}function Vb(e){var{option:t,shapeType:r,activeClassName:n="recharts-active-shape",inActiveClassName:a="recharts-shape"}=e,i=tM(e,eM),o;if(f.isValidElement(t))o=f.cloneElement(t,Ci(Ci({},i),lM(t)));else if(typeof t=="function")o=t(i,i.index);else if(GT(t)&&typeof t!="boolean"){var l=sM(t,i);o=f.createElement(Mv,{shapeType:r,elementProps:l})}else{var c=i;o=f.createElement(Mv,{shapeType:r,elementProps:c})}return i.isActive?f.createElement(ot,{className:n},o):f.createElement(ot,{className:a},o)}var cM=(e,t,r)=>{var n=pe();return(a,i)=>o=>{e?.(a,i,o),n(qg({activeIndex:String(i),activeDataKey:t,activeCoordinate:a.tooltipPosition,activeGraphicalItemId:r}))}},uM=e=>{var t=pe();return(r,n)=>a=>{e?.(r,n,a),t(fE())}},dM=(e,t,r)=>{var n=pe();return(a,i)=>o=>{e?.(a,i,o),n(mE({activeIndex:String(i),activeDataKey:t,activeCoordinate:a.tooltipPosition,activeGraphicalItemId:r}))}};function Ub(e){var{tooltipEntrySettings:t}=e,r=pe(),n=dt(),a=f.useRef(null);return f.useLayoutEffect(()=>{n||(a.current===null?r(lE(t)):a.current!==t&&r(cE({prev:a.current,next:t})),a.current=t)},[t,r,n]),f.useLayoutEffect(()=>()=>{a.current&&(r(uE(a.current)),a.current=null)},[r]),null}function fM(e){var{legendPayload:t}=e,r=pe(),n=dt(),a=f.useRef(null);return f.useLayoutEffect(()=>{n||(a.current===null?r(Ay(t)):a.current!==t&&r(Oy({prev:a.current,next:t})),a.current=t)},[r,n,t]),f.useLayoutEffect(()=>()=>{a.current&&(r(Ey(a.current)),a.current=null)},[r]),null}function mM(e){var{legendPayload:t}=e,r=pe(),n=Z(xe),a=f.useRef(null);return f.useLayoutEffect(()=>{n!=="centric"&&n!=="radial"||(a.current===null?r(Ay(t)):a.current!==t&&r(Oy({prev:a.current,next:t})),a.current=t)},[r,n,t]),f.useLayoutEffect(()=>()=>{a.current&&(r(Ey(a.current)),a.current=null)},[r]),null}var Ko,vM=()=>{var[e]=f.useState(()=>Kn("uid-"));return e},hM=(Ko=ij.useId)!==null&&Ko!==void 0?Ko:vM;function pM(e,t){var r=hM();return t||(e?"".concat(e,"-").concat(r):r)}var yM=f.createContext(void 0),qb=e=>{var{id:t,type:r,children:n}=e,a=pM("recharts-".concat(r),t);return f.createElement(yM.Provider,{value:a},n(a))},gM={cartesianItems:[],polarItems:[]},Wb=at({name:"graphicalItems",initialState:gM,reducers:{addCartesianGraphicalItem:{reducer(e,t){e.cartesianItems.push(t.payload)},prepare:je()},replaceCartesianGraphicalItem:{reducer(e,t){var{prev:r,next:n}=t.payload,a=Ct(e).cartesianItems.indexOf(r);a>-1&&(e.cartesianItems[a]=n)},prepare:je()},removeCartesianGraphicalItem:{reducer(e,t){var r=Ct(e).cartesianItems.indexOf(t.payload);r>-1&&e.cartesianItems.splice(r,1)},prepare:je()},addPolarGraphicalItem:{reducer(e,t){e.polarItems.push(t.payload)},prepare:je()},removePolarGraphicalItem:{reducer(e,t){var r=Ct(e).polarItems.indexOf(t.payload);r>-1&&e.polarItems.splice(r,1)},prepare:je()},replacePolarGraphicalItem:{reducer(e,t){var{prev:r,next:n}=t.payload,a=Ct(e).polarItems.indexOf(r);a>-1&&(e.polarItems[a]=n)},prepare:je()}}}),{addCartesianGraphicalItem:bM,replaceCartesianGraphicalItem:xM,removeCartesianGraphicalItem:jM,addPolarGraphicalItem:wM,removePolarGraphicalItem:CM,replacePolarGraphicalItem:kM}=Wb.actions,SM=Wb.reducer,NM=e=>{var t=pe(),r=f.useRef(null);return f.useLayoutEffect(()=>{r.current===null?t(bM(e)):r.current!==e&&t(xM({prev:r.current,next:e})),r.current=e},[t,e]),f.useLayoutEffect(()=>()=>{r.current&&(t(jM(r.current)),r.current=null)},[t]),null},PM=f.memo(NM),AM=e=>{var t=pe(),r=f.useRef(null);return f.useLayoutEffect(()=>{r.current===null?t(wM(e)):r.current!==e&&t(kM({prev:r.current,next:e})),r.current=e},[t,e]),f.useLayoutEffect(()=>()=>{r.current&&(t(CM(r.current)),r.current=null)},[t]),null},OM=f.memo(AM),EM=["key"],_M=["onMouseEnter","onClick","onMouseLeave"],TM=["id"],MM=["id"];function hr(){return hr=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},hr.apply(null,arguments)}function ws(e,t){if(e==null)return{};var r,n,a=IM(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function IM(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}function Iv(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function ke(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Iv(Object(r),!0).forEach(function(n){DM(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Iv(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function DM(e,t,r){return(t=RM(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function RM(e){var t=LM(e,"string");return typeof t=="symbol"?t:t+""}function LM(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function $M(e){var t=f.useMemo(()=>zb(e.children,gs),[e.children]),r=Z(n=>BT(n,e.id,t));return r==null?null:f.createElement(mM,{legendPayload:r})}function FM(e){if(!(e==null||typeof e=="boolean"||typeof e=="function")){if(f.isValidElement(e)){var t,r=(t=e.props)===null||t===void 0?void 0:t.fill;return typeof r=="string"?r:void 0}var{fill:n}=e;return typeof n=="string"?n:void 0}}var BM=f.memo(e=>{var{dataKey:t,nameKey:r,sectors:n,stroke:a,strokeWidth:i,fill:o,name:l,hide:c,tooltipType:d,id:u,activeShape:m}=e,h=FM(m),v=n.map(b=>{var y=b.tooltipPayload;return h==null||y==null?y:y.map(g=>ke(ke({},g),{},{color:h,fill:h}))}),p={dataDefinedOnItem:v,getPosition:b=>{var y;return(y=n[Number(b)])===null||y===void 0?void 0:y.tooltipPosition},settings:{stroke:a,strokeWidth:i,fill:o,dataKey:t,nameKey:r,name:Zi(l,t),hide:c,type:d,color:o,unit:"",graphicalItemId:u}};return f.createElement(Ub,{tooltipEntrySettings:p})}),zM=(e,t)=>e>t?"start":e<t?"end":"middle",KM=(e,t,r)=>ht(typeof t=="function"?t(e):t,r,r*.8),VM=(e,t,r)=>{var{top:n,left:a,width:i,height:o}=t,l=$y(i,o),c=a+ht(e.cx,i,i/2),d=n+ht(e.cy,o,o/2),u=ht(e.innerRadius,l,0),m=KM(r,e.outerRadius,l),h=e.maxRadius||Math.sqrt(i*i+o*o)/2;return{cx:c,cy:d,innerRadius:u,outerRadius:m,maxRadius:h}},UM=(e,t)=>{var r=rt(t-e),n=Math.min(Math.abs(t-e),360);return r*n},qM=(e,t)=>{if(f.isValidElement(e))return f.cloneElement(e,t);if(typeof e=="function")return e(t);var r=ve("recharts-pie-label-line",typeof e!="boolean"?e.className:""),{key:n}=t,a=ws(t,EM);return f.createElement(Bc,hr({},a,{type:"linear",className:r}))},WM=(e,t,r)=>{if(f.isValidElement(e))return f.cloneElement(e,t);var n=r;if(typeof e=="function"&&(n=e(t),f.isValidElement(n)))return n;var a=ve("recharts-pie-label-text",$b(e));return f.createElement(bs,hr({},t,{alignmentBaseline:"middle",className:a}),n)};function HM(e){var{sectors:t,props:r,showLabels:n}=e,{label:a,labelLine:i,dataKey:o}=r;if(!n||!a||!t)return null;var l=kt(r),c=an(a),d=an(i),u=typeof a=="object"&&"offsetRadius"in a&&typeof a.offsetRadius=="number"&&a.offsetRadius||20,m=t.map((h,v)=>{var p=(h.startAngle+h.endAngle)/2,b=Ie(h.cx,h.cy,h.outerRadius+u,p),y=ke(ke(ke(ke({},l),h),{},{stroke:"none"},c),{},{index:v,textAnchor:zM(b.x,h.cx)},b),g=ke(ke(ke(ke({},l),h),{},{fill:"none",stroke:h.fill},d),{},{index:v,points:[Ie(h.cx,h.cy,h.outerRadius,p),b],key:"line"});return f.createElement(Tt,{zIndex:Ze.label,key:"label-".concat(h.startAngle,"-").concat(h.endAngle,"-").concat(h.midAngle,"-").concat(v)},f.createElement(ot,null,i&&qM(i,g),WM(a,y,ge(h,o))))});return f.createElement(ot,{className:"recharts-pie-labels"},m)}function GM(e){var{sectors:t,props:r,showLabels:n}=e,{label:a}=r;return typeof a=="object"&&a!=null&&"position"in a?f.createElement(Mb,{label:a}):f.createElement(HM,{sectors:t,props:r,showLabels:n})}function XM(e){var{sectors:t,activeShape:r,inactiveShape:n,allOtherPieProps:a,shape:i,id:o}=e,l=Z(fn),c=Z(ob),d=Z(lb),{onMouseEnter:u,onClick:m,onMouseLeave:h}=a,v=ws(a,_M),p=cM(u,a.dataKey,o),b=uM(h),y=dM(m,a.dataKey,o);return t==null||t.length===0?null:f.createElement(f.Fragment,null,t.map((g,j)=>{if(g?.startAngle===0&&g?.endAngle===0&&t.length!==1)return null;var x=d==null||d===o,C=String(j)===l&&(c==null||a.dataKey===c)&&x,w=l?n:null,P=r&&C?r:w,A=ke(ke({},g),{},{stroke:g.stroke,tabIndex:-1,[vy]:j,[hy]:o});return f.createElement(ot,hr({key:"sector-".concat(g?.startAngle,"-").concat(g?.endAngle,"-").concat(g.midAngle,"-").concat(j),tabIndex:-1,className:"recharts-pie-sector"},Sc(v,g,j),{onMouseEnter:p(g,j),onMouseLeave:b(g,j),onClick:y(g,j)}),f.createElement(Vb,hr({option:i??P,index:j,shapeType:"sector",isActive:C},A)))}))}function YM(e){var t,{pieSettings:r,displayedData:n,cells:a,offset:i}=e,{cornerRadius:o,startAngle:l,endAngle:c,dataKey:d,nameKey:u,tooltipType:m}=r,h=Math.abs(r.minAngle),v=UM(l,c),p=Math.abs(v),b=n.length<=1?0:(t=r.paddingAngle)!==null&&t!==void 0?t:0,y=n.filter(S=>ge(S,d,0)!==0).length,g=(p>=360?y:y-1)*b,j=n.reduce((S,N)=>{var E=ge(N,d,0);return S+(ee(E)?E:0)},0),x=h>0&&j>0&&n.some(S=>{var N=ge(S,d,0),E=(ee(N)?N:0)/j;return N!==0&&E*p<h}),C=x?h:0,w=p-y*C-g,P;if(j>0){var A;P=n.map((S,N)=>{var E=ge(S,d,0),T=ge(S,u,N),O=VM(r,i,S),I=(ee(E)?E:0)/j,z,D=ke(ke({},S),a&&a[N]&&a[N].props),V=D!=null&&"fill"in D&&typeof D.fill=="string"?D.fill:r.fill;N?z=A.endAngle+rt(v)*b*(E!==0?1:0):z=l;var B=z+rt(v)*((E!==0?C:0)+I*w),W=(z+B)/2,K=(O.innerRadius+O.outerRadius)/2,te=[{name:T,value:E,payload:D,dataKey:d,type:m,color:V,fill:V,graphicalItemId:r.id}],G=Ie(O.cx,O.cy,K,W);return A=ke(ke(ke(ke({},r.presentationProps),{},{percent:I,cornerRadius:typeof o=="string"?parseFloat(o):o,name:T,tooltipPayload:te,midAngle:W,middleRadius:K,tooltipPosition:G},D),O),{},{value:E,dataKey:d,startAngle:z,endAngle:B,payload:D,paddingAngle:E!==0?rt(v)*b:0}),A})}return P}function ZM(e){var{showLabels:t,sectors:r,children:n}=e,a=f.useMemo(()=>!t||!r?[]:r.map(i=>({value:i.value,payload:i.payload,clockWise:!1,parentViewBox:void 0,viewBox:{cx:i.cx,cy:i.cy,innerRadius:i.innerRadius,outerRadius:i.outerRadius,startAngle:i.startAngle,endAngle:i.endAngle,clockWise:!1},fill:i.fill})),[r,t]);return f.createElement(CT,{value:t?a:void 0},n)}function JM(e){var{props:t,previousSectorsRef:r,id:n}=e,{sectors:a,isAnimationActive:i,animationBegin:o,animationDuration:l,animationEasing:c,activeShape:d,inactiveShape:u,onAnimationStart:m,onAnimationEnd:h}=t,v=os(t,"recharts-pie-"),p=r.current,[b,y]=f.useState(!1),g=f.useCallback(()=>{typeof h=="function"&&h(),y(!1)},[h]),j=f.useCallback(()=>{typeof m=="function"&&m(),y(!0)},[m]);return f.createElement(ZM,{showLabels:!b,sectors:a},f.createElement(ss,{animationId:v,begin:o,duration:l,isActive:i,easing:c,onAnimationStart:j,onAnimationEnd:g,key:v},x=>{var C,w=[],P=a&&a[0],A=(C=P?.startAngle)!==null&&C!==void 0?C:0;return a?.forEach((S,N)=>{var E=p&&p[N],T=N>0?Mr(S,"paddingAngle",0):0;if(E){var O=tt(E.endAngle-E.startAngle,S.endAngle-S.startAngle,x),I=ke(ke({},S),{},{startAngle:A+T,endAngle:A+O+T});w.push(I),A=I.endAngle}else{var{endAngle:z,startAngle:D}=S,V=tt(0,z-D,x),B=ke(ke({},S),{},{startAngle:A+T,endAngle:A+V+T});w.push(B),A=B.endAngle}}),r.current=w,f.createElement(ot,null,f.createElement(XM,{sectors:w,activeShape:d,inactiveShape:u,allOtherPieProps:t,shape:t.shape,id:n}))}),f.createElement(GM,{showLabels:!b,sectors:a,props:t}),t.children)}var QM={animationBegin:400,animationDuration:1500,animationEasing:"ease",cx:"50%",cy:"50%",dataKey:"value",endAngle:360,fill:"#808080",hide:!1,innerRadius:0,isAnimationActive:"auto",label:!1,labelLine:!0,legendType:"rect",minAngle:0,nameKey:"name",outerRadius:"80%",paddingAngle:0,rootTabIndex:0,startAngle:0,stroke:"#fff",zIndex:Ze.area};function eI(e){var{id:t}=e,r=ws(e,TM),{hide:n,className:a,rootTabIndex:i}=e,o=f.useMemo(()=>zb(e.children,gs),[e.children]),l=Z(u=>zT(u,t,o)),c=f.useRef(null),d=ve("recharts-pie",a);return n||l==null?(c.current=null,f.createElement(ot,{tabIndex:i,className:d})):f.createElement(Tt,{zIndex:e.zIndex},f.createElement(BM,{dataKey:e.dataKey,nameKey:e.nameKey,sectors:l,stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,name:e.name,hide:e.hide,tooltipType:e.tooltipType,id:t,activeShape:e.activeShape}),f.createElement(ot,{tabIndex:i,className:d},f.createElement(JM,{props:ke(ke({},r),{},{sectors:l}),previousSectorsRef:c,id:t})))}function tI(e){var t=Ke(e,QM),{id:r}=t,n=ws(t,MM),a=kt(n);return f.createElement(qb,{id:r,type:"pie"},i=>f.createElement(f.Fragment,null,f.createElement(OM,{type:"pie",id:i,data:n.data,dataKey:n.dataKey,hide:n.hide,angleAxisId:0,radiusAxisId:0,name:n.name,nameKey:n.nameKey,tooltipType:n.tooltipType,legendType:n.legendType,fill:n.fill,cx:n.cx,cy:n.cy,startAngle:n.startAngle,endAngle:n.endAngle,paddingAngle:n.paddingAngle,minAngle:n.minAngle,innerRadius:n.innerRadius,outerRadius:n.outerRadius,cornerRadius:n.cornerRadius,presentationProps:a,maxRadius:t.maxRadius}),f.createElement($M,hr({},n,{id:i})),f.createElement(eI,hr({},n,{id:i}))))}var Hb=tI;Hb.displayName="Pie";var rI=["points"];function Dv(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Vo(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Dv(Object(r),!0).forEach(function(n){nI(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Dv(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function nI(e,t,r){return(t=aI(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function aI(e){var t=iI(e,"string");return typeof t=="symbol"?t:t+""}function iI(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function ki(){return ki=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ki.apply(null,arguments)}function sI(e,t){if(e==null)return{};var r,n,a=oI(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function oI(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}function lI(e){var{option:t,dotProps:r,className:n}=e;if(f.isValidElement(t))return f.cloneElement(t,r);if(typeof t=="function")return t(r);var a=ve(n,typeof t!="boolean"?t.className:""),i=r??{},{points:o}=i,l=sI(i,rI);return f.createElement(Ib,ki({},l,{className:a}))}function cI(e,t){return e==null?!1:t?!0:e.length===1}function uI(e){var{points:t,dot:r,className:n,dotClassName:a,dataKey:i,baseProps:o,needClip:l,clipPathId:c,zIndex:d=Ze.scatter}=e;if(!cI(t,r))return null;var u=Kb(r),m=fC(r),h=t.map((p,b)=>{var y,g,j=Vo(Vo(Vo({r:3},o),m),{},{index:b,cx:(y=p.x)!==null&&y!==void 0?y:void 0,cy:(g=p.y)!==null&&g!==void 0?g:void 0,dataKey:i,value:p.value,payload:p.payload,points:t});return f.createElement(lI,{key:"dot-".concat(b),option:r,dotProps:j,className:a})}),v={};return l&&c!=null&&(v.clipPath="url(#clipPath-".concat(u?"":"dots-").concat(c,")")),f.createElement(Tt,{zIndex:d},f.createElement(ot,ki({className:n},v),h))}function Rv(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Lv(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Rv(Object(r),!0).forEach(function(n){dI(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Rv(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function dI(e,t,r){return(t=fI(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function fI(e){var t=mI(e,"string");return typeof t=="symbol"?t:t+""}function mI(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var vI={xAxis:{},yAxis:{},zAxis:{}},Gb=at({name:"cartesianAxis",initialState:vI,reducers:{addXAxis:{reducer(e,t){e.xAxis[t.payload.id]=t.payload},prepare:je()},replaceXAxis:{reducer(e,t){var{prev:r,next:n}=t.payload;e.xAxis[r.id]!==void 0&&(r.id!==n.id&&delete e.xAxis[r.id],e.xAxis[n.id]=n)},prepare:je()},removeXAxis:{reducer(e,t){delete e.xAxis[t.payload.id]},prepare:je()},addYAxis:{reducer(e,t){e.yAxis[t.payload.id]=t.payload},prepare:je()},replaceYAxis:{reducer(e,t){var{prev:r,next:n}=t.payload;e.yAxis[r.id]!==void 0&&(r.id!==n.id&&delete e.yAxis[r.id],e.yAxis[n.id]=n)},prepare:je()},removeYAxis:{reducer(e,t){delete e.yAxis[t.payload.id]},prepare:je()},addZAxis:{reducer(e,t){e.zAxis[t.payload.id]=t.payload},prepare:je()},replaceZAxis:{reducer(e,t){var{prev:r,next:n}=t.payload;e.zAxis[r.id]!==void 0&&(r.id!==n.id&&delete e.zAxis[r.id],e.zAxis[n.id]=n)},prepare:je()},removeZAxis:{reducer(e,t){delete e.zAxis[t.payload.id]},prepare:je()},updateYAxisWidth(e,t){var{id:r,width:n}=t.payload,a=e.yAxis[r];if(a){var i,o=a.widthHistory||[];if(o.length===3&&o[0]===o[2]&&n===o[1]&&n!==a.width&&Math.abs(n-((i=o[0])!==null&&i!==void 0?i:0))<=1)return;var l=[...o,n].slice(-3);e.yAxis[r]=Lv(Lv({},a),{},{width:n,widthHistory:l})}}}}),{addXAxis:hI,replaceXAxis:pI,removeXAxis:yI,addYAxis:gI,replaceYAxis:bI,removeYAxis:xI,addZAxis:CB,replaceZAxis:kB,removeZAxis:SB,updateYAxisWidth:jI}=Gb.actions,wI=Gb.reducer,CI=_([qe],e=>({top:e.top,bottom:e.bottom,left:e.left,right:e.right})),kI=_([CI,tr,rr],(e,t,r)=>{if(!(!e||t==null||r==null))return{x:e.left,y:e.top,width:Math.max(0,t-e.left-e.right),height:Math.max(0,r-e.top-e.bottom)}}),Ou=()=>Z(kI),SI=()=>Z(o1);function $v(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Uo(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?$v(Object(r),!0).forEach(function(n){NI(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):$v(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function NI(e,t,r){return(t=PI(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function PI(e){var t=AI(e,"string");return typeof t=="symbol"?t:t+""}function AI(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var OI=e=>{var{point:t,childIndex:r,mainColor:n,activeDot:a,dataKey:i,clipPath:o}=e;if(a===!1||t.x==null||t.y==null)return null;var l={index:r,dataKey:i,cx:t.x,cy:t.y,r:4,fill:n??"none",strokeWidth:2,stroke:"#fff",payload:t.payload,value:t.value},c=Uo(Uo(Uo({},l),an(a)),kc(a)),d;return f.isValidElement(a)?d=f.cloneElement(a,c):typeof a=="function"?d=a(c):d=f.createElement(Ib,c),f.createElement(ot,{className:"recharts-active-dot",clipPath:o},d)};function EI(e){var{points:t,mainColor:r,activeDot:n,itemDataKey:a,clipPath:i,zIndex:o=Ze.activeDot}=e,l=Z(fn),c=SI();if(t==null||c==null)return null;var d=t.find(u=>c.includes(u.payload));return ze(d)?null:f.createElement(Tt,{zIndex:o},f.createElement(OI,{point:d,childIndex:Number(l),mainColor:r,dataKey:a,activeDot:n,clipPath:i}))}var Xb=e=>{var{chartData:t}=e,r=pe(),n=dt();return f.useEffect(()=>n?()=>{}:(r(Ym(t)),()=>{r(Ym(void 0))}),[t,r,n]),null},Fv={x:0,y:0,width:0,height:0,padding:{top:0,right:0,bottom:0,left:0}},Yb=at({name:"brush",initialState:Fv,reducers:{setBrushSettings(e,t){return t.payload==null?Fv:t.payload}}}),{setBrushSettings:NB}=Yb.actions,_I=Yb.reducer;function TI(e){return(e%180+180)%180}var MI=function(t){var{width:r,height:n}=t,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=TI(a),o=i*Math.PI/180,l=Math.atan(n/r),c=o>l&&o<Math.PI-l?n/Math.sin(o):r/Math.cos(o);return Math.abs(c)},II={dots:[],areas:[],lines:[]},Zb=at({name:"referenceElements",initialState:II,reducers:{addDot:(e,t)=>{e.dots.push(t.payload)},removeDot:(e,t)=>{var r=Ct(e).dots.findIndex(n=>n===t.payload);r!==-1&&e.dots.splice(r,1)},addArea:(e,t)=>{e.areas.push(t.payload)},removeArea:(e,t)=>{var r=Ct(e).areas.findIndex(n=>n===t.payload);r!==-1&&e.areas.splice(r,1)},addLine:(e,t)=>{e.lines.push(t.payload)},removeLine:(e,t)=>{var r=Ct(e).lines.findIndex(n=>n===t.payload);r!==-1&&e.lines.splice(r,1)}}}),{addDot:PB,removeDot:AB,addArea:OB,removeArea:EB,addLine:_B,removeLine:TB}=Zb.actions,DI=Zb.reducer,RI=f.createContext(void 0),LI=e=>{var{children:t}=e,[r]=f.useState("".concat(Kn("recharts"),"-clip")),n=Ou();if(n==null)return null;var{x:a,y:i,width:o,height:l}=n;return f.createElement(RI.Provider,{value:r},f.createElement("defs",null,f.createElement("clipPath",{id:r},f.createElement("rect",{x:a,y:i,height:l,width:o}))),t)};function Jb(e,t){if(t<1)return[];if(t===1)return e;for(var r=[],n=0;n<e.length;n+=t){var a=e[n];a!==void 0&&r.push(a)}return r}function $I(e,t,r){var n={width:e.width+t.width,height:e.height+t.height};return MI(n,r)}function FI(e,t,r){var n=r==="width",{x:a,y:i,width:o,height:l}=e;return t===1?{start:n?a:i,end:n?a+o:i+l}:{start:n?a+o:i+l,end:n?a:i}}function Jn(e,t,r,n,a){if(e*t<e*n||e*t>e*a)return!1;var i=r();return e*(t-e*i/2-n)>=0&&e*(t+e*i/2-a)<=0}function BI(e,t){return Jb(e,t+1)}function zI(e,t,r,n,a){for(var i=(n||[]).slice(),{start:o,end:l}=t,c=0,d=1,u=o,m=function(){var p=n?.[c];if(p===void 0)return{v:Jb(n,d)};var b=c,y,g=()=>(y===void 0&&(y=r(p,b)),y),j=p.coordinate,x=c===0||Jn(e,j,g,u,l);x||(c=0,u=o,d+=1),x&&(u=j+e*(g()/2+a),c+=d)},h;d<=i.length;)if(h=m(),h)return h.v;return[]}function KI(e,t,r,n,a){var i=(n||[]).slice(),o=i.length;if(o===0)return[];for(var{start:l,end:c}=t,d=1;d<=o;d++){for(var u=(o-1)%d,m=l,h=!0,v=function(){var C=n[b];if(C==null)return 0;var w=b,P,A=()=>(P===void 0&&(P=r(C,w)),P),S=C.coordinate,N=b===u||Jn(e,S,A,m,c);if(!N)return h=!1,1;N&&(m=S+e*(A()/2+a))},p,b=u;b<o&&(p=v(),!(p!==0&&p===1));b+=d);if(h){for(var y=[],g=u;g<o;g+=d){var j=n[g];j!=null&&y.push(j)}return y}}return[]}function Bv(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Qe(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Bv(Object(r),!0).forEach(function(n){VI(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Bv(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function VI(e,t,r){return(t=UI(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function UI(e){var t=qI(e,"string");return typeof t=="symbol"?t:t+""}function qI(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function WI(e,t,r,n,a){for(var i=(n||[]).slice(),o=i.length,{start:l}=t,{end:c}=t,d=function(h){var v=i[h];if(v==null)return 1;var p=v,b,y=()=>(b===void 0&&(b=r(v,h)),b);if(h===o-1){var g=e*(p.coordinate+e*y()/2-c);i[h]=p=Qe(Qe({},p),{},{tickCoord:g>0?p.coordinate-g*e:p.coordinate})}else i[h]=p=Qe(Qe({},p),{},{tickCoord:p.coordinate});if(p.tickCoord!=null){var j=Jn(e,p.tickCoord,y,l,c);j&&(c=p.tickCoord-e*(y()/2+a),i[h]=Qe(Qe({},p),{},{isShow:!0}))}},u=o-1;u>=0;u--)d(u);return i}function HI(e,t,r,n,a,i){var o=(n||[]).slice(),l=o.length,{start:c,end:d}=t;if(i){var u=n[l-1];if(u!=null){var m=r(u,l-1),h=e*(u.coordinate+e*m/2-d);if(o[l-1]=u=Qe(Qe({},u),{},{tickCoord:h>0?u.coordinate-h*e:u.coordinate}),u.tickCoord!=null){var v=Jn(e,u.tickCoord,()=>m,c,d);v&&(d=u.tickCoord-e*(m/2+a),o[l-1]=Qe(Qe({},u),{},{isShow:!0}))}}}for(var p=i?l-1:l,b=function(j){var x=o[j];if(x==null)return 1;var C=x,w,P=()=>(w===void 0&&(w=r(x,j)),w);if(j===0){var A=e*(C.coordinate-e*P()/2-c);o[j]=C=Qe(Qe({},C),{},{tickCoord:A<0?C.coordinate-A*e:C.coordinate})}else o[j]=C=Qe(Qe({},C),{},{tickCoord:C.coordinate});if(C.tickCoord!=null){var S=Jn(e,C.tickCoord,P,c,d);S&&(c=C.tickCoord+e*(P()/2+a),o[j]=Qe(Qe({},C),{},{isShow:!0}))}},y=0;y<p;y++)b(y);return o}function Eu(e,t,r){var{tick:n,ticks:a,viewBox:i,minTickGap:o,orientation:l,interval:c,tickFormatter:d,unit:u,angle:m}=e;if(!a||!a.length||!n)return[];if(ee(c)||la.isSsr){var h;return(h=BI(a,ee(c)?c:0))!==null&&h!==void 0?h:[]}var v=[],p=l==="top"||l==="bottom"?"width":"height",b=u&&p==="width"?Bn(u,{fontSize:t,letterSpacing:r}):{width:0,height:0},y=(w,P)=>{var A=typeof d=="function"?d(w.value,P):w.value;return p==="width"?$I(Bn(A,{fontSize:t,letterSpacing:r}),b,m):Bn(A,{fontSize:t,letterSpacing:r})[p]},g=a[0],j=a[1],x=a.length>=2&&g!=null&&j!=null?rt(j.coordinate-g.coordinate):1,C=FI(i,x,p);return c==="equidistantPreserveStart"?zI(x,C,y,a,o):c==="equidistantPreserveEnd"?KI(x,C,y,a,o):(c==="preserveStart"||c==="preserveStartEnd"?v=HI(x,C,y,a,o,c==="preserveStartEnd"):v=WI(x,C,y,a,o),v.filter(w=>w.isShow))}var GI=e=>{var{ticks:t,label:r,labelGapWithTick:n=5,tickSize:a=0,tickMargin:i=0}=e,o=0;if(t){Array.from(t).forEach(u=>{if(u){var m=u.getBoundingClientRect();m.width>o&&(o=m.width)}});var l=r?r.getBoundingClientRect().width:0,c=a+i,d=o+c+l+(r?n:0);return Math.round(d)}return 0},XI={xAxis:{},yAxis:{}},Qb=at({name:"renderedTicks",initialState:XI,reducers:{setRenderedTicks:(e,t)=>{var{axisType:r,axisId:n,ticks:a}=t.payload;e[r][n]=a},removeRenderedTicks:(e,t)=>{var{axisType:r,axisId:n}=t.payload;delete e[r][n]}}}),{setRenderedTicks:YI,removeRenderedTicks:ZI}=Qb.actions,JI=Qb.reducer,QI=["axisLine","width","height","className","hide","ticks","axisType","axisId"];function eD(e,t){if(e==null)return{};var r,n,a=tD(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function tD(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}function Fr(){return Fr=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Fr.apply(null,arguments)}function zv(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Ee(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?zv(Object(r),!0).forEach(function(n){rD(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):zv(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function rD(e,t,r){return(t=nD(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function nD(e){var t=aD(e,"string");return typeof t=="symbol"?t:t+""}function aD(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Yt={x:0,y:0,width:0,height:0,viewBox:{x:0,y:0,width:0,height:0},orientation:"bottom",ticks:[],stroke:"#666",tickLine:!0,axisLine:!0,tick:!0,mirror:!1,minTickGap:5,tickSize:6,tickMargin:2,interval:"preserveEnd",zIndex:Ze.axis};function iD(e){var{x:t,y:r,width:n,height:a,orientation:i,mirror:o,axisLine:l,otherSvgProps:c}=e;if(!l)return null;var d=Ee(Ee(Ee({},c),kt(l)),{},{fill:"none"});if(i==="top"||i==="bottom"){var u=+(i==="top"&&!o||i==="bottom"&&o);d=Ee(Ee({},d),{},{x1:t,y1:r+u*a,x2:t+n,y2:r+u*a})}else{var m=+(i==="left"&&!o||i==="right"&&o);d=Ee(Ee({},d),{},{x1:t+m*n,y1:r,x2:t+m*n,y2:r+a})}return f.createElement("line",Fr({},d,{className:ve("recharts-cartesian-axis-line",Mr(l,"className"))}))}function sD(e,t,r,n,a,i,o,l,c){var d,u,m,h,v,p,b=l?-1:1,y=e.tickSize||o,g=ee(e.tickCoord)?e.tickCoord:e.coordinate;switch(i){case"top":d=u=e.coordinate,h=r+ +!l*a,m=h-b*y,p=m-b*c,v=g;break;case"left":m=h=e.coordinate,u=t+ +!l*n,d=u-b*y,v=d-b*c,p=g;break;case"right":m=h=e.coordinate,u=t+ +l*n,d=u+b*y,v=d+b*c,p=g;break;default:d=u=e.coordinate,h=r+ +l*a,m=h+b*y,p=m+b*c,v=g;break}return{line:{x1:d,y1:m,x2:u,y2:h},tick:{x:v,y:p}}}function oD(e,t){switch(e){case"left":return t?"start":"end";case"right":return t?"end":"start";default:return"middle"}}function lD(e,t){switch(e){case"left":case"right":return"middle";case"top":return t?"start":"end";default:return t?"end":"start"}}function cD(e){var{option:t,tickProps:r,value:n}=e,a,i=ve(r.className,"recharts-cartesian-axis-tick-value");if(f.isValidElement(t))a=f.cloneElement(t,Ee(Ee({},r),{},{className:i}));else if(typeof t=="function")a=t(Ee(Ee({},r),{},{className:i}));else{var o="recharts-cartesian-axis-tick-value";typeof t!="boolean"&&(o=ve(o,$b(t))),a=f.createElement(bs,Fr({},r,{className:o}),n)}return a}function uD(e){var{ticks:t,axisType:r,axisId:n}=e,a=pe();return f.useEffect(()=>{if(n==null||r==null)return ta;var i=t.map(o=>({value:o.value,coordinate:o.coordinate,offset:o.offset,index:o.index}));return a(YI({ticks:i,axisId:n,axisType:r})),()=>{a(ZI({axisId:n,axisType:r}))}},[a,t,n,r]),null}var dD=f.forwardRef((e,t)=>{var{ticks:r=[],tick:n,tickLine:a,stroke:i,tickFormatter:o,unit:l,padding:c,tickTextProps:d,orientation:u,mirror:m,x:h,y:v,width:p,height:b,tickSize:y,tickMargin:g,fontSize:j,letterSpacing:x,getTicksConfig:C,events:w,axisType:P,axisId:A}=e,S=Eu(Ee(Ee({},C),{},{ticks:r}),j,x),N=kt(C),E=an(n),T=Sb(N.textAnchor)?N.textAnchor:oD(u,m),O=lD(u,m),I={};typeof a=="object"&&(I=a);var z=Ee(Ee({},N),{},{fill:"none"},I),D=S.map(W=>Ee({entry:W},sD(W,h,v,p,b,u,y,m,g))),V=D.map(W=>{var{entry:K,line:te}=W;return f.createElement(ot,{className:"recharts-cartesian-axis-tick",key:"tick-".concat(K.value,"-").concat(K.coordinate,"-").concat(K.tickCoord)},a&&f.createElement("line",Fr({},z,te,{className:ve("recharts-cartesian-axis-tick-line",Mr(a,"className"))})))}),B=D.map((W,K)=>{var te,G,{entry:M,tick:q}=W,H=Ee(Ee(Ee(Ee({verticalAnchor:O},N),{},{textAnchor:T,stroke:"none",fill:i},q),{},{index:K,payload:M,visibleTicksCount:S.length,tickFormatter:o,padding:c},d),{},{angle:(te=(G=d?.angle)!==null&&G!==void 0?G:N.angle)!==null&&te!==void 0?te:0}),re=Ee(Ee({},H),E);return f.createElement(ot,Fr({className:"recharts-cartesian-axis-tick-label",key:"tick-label-".concat(M.value,"-").concat(M.coordinate,"-").concat(M.tickCoord)},Sc(w,M,K)),n&&f.createElement(cD,{option:n,tickProps:re,value:"".concat(typeof o=="function"?o(M.value,K):M.value).concat(l||"")}))});return f.createElement("g",{className:"recharts-cartesian-axis-ticks recharts-".concat(P,"-ticks")},f.createElement(uD,{ticks:S,axisId:A,axisType:P}),B.length>0&&f.createElement(Tt,{zIndex:Ze.label},f.createElement("g",{className:"recharts-cartesian-axis-tick-labels recharts-".concat(P,"-tick-labels"),ref:t},B)),V.length>0&&f.createElement("g",{className:"recharts-cartesian-axis-tick-lines recharts-".concat(P,"-tick-lines")},V))}),fD=f.forwardRef((e,t)=>{var{axisLine:r,width:n,height:a,className:i,hide:o,ticks:l,axisType:c,axisId:d}=e,u=eD(e,QI),[m,h]=f.useState(""),[v,p]=f.useState(""),b=f.useRef(null);f.useImperativeHandle(t,()=>({getCalculatedWidth:()=>{var g;return GI({ticks:b.current,label:(g=e.labelRef)===null||g===void 0?void 0:g.current,labelGapWithTick:5,tickSize:e.tickSize,tickMargin:e.tickMargin})}}));var y=f.useCallback(g=>{if(g){var j=g.getElementsByClassName("recharts-cartesian-axis-tick-value");b.current=j;var x=j[0];if(x){var C=window.getComputedStyle(x),w=C.fontSize,P=C.letterSpacing;(w!==m||P!==v)&&(h(w),p(P))}}},[m,v]);return o||n!=null&&n<=0||a!=null&&a<=0?null:f.createElement(Tt,{zIndex:e.zIndex},f.createElement(ot,{className:ve("recharts-cartesian-axis",i)},f.createElement(iD,{x:e.x,y:e.y,width:n,height:a,orientation:e.orientation,mirror:e.mirror,axisLine:r,otherSvgProps:kt(e)}),f.createElement(dD,{ref:y,axisType:c,events:u,fontSize:m,getTicksConfig:e,height:e.height,letterSpacing:v,mirror:e.mirror,orientation:e.orientation,padding:e.padding,stroke:e.stroke,tick:e.tick,tickFormatter:e.tickFormatter,tickLine:e.tickLine,tickMargin:e.tickMargin,tickSize:e.tickSize,tickTextProps:e.tickTextProps,ticks:l,unit:e.unit,width:e.width,x:e.x,y:e.y,axisId:d}),f.createElement(oT,{x:e.x,y:e.y,width:e.width,height:e.height,lowerWidth:e.width,upperWidth:e.width},f.createElement(yT,{label:e.label,labelRef:e.labelRef}),e.children)))}),_u=f.forwardRef((e,t)=>{var r=Ke(e,Yt);return f.createElement(fD,Fr({},r,{ref:t}))});_u.displayName="CartesianAxis";var mD=["x1","y1","x2","y2","key"],vD=["offset"],hD=["xAxisId","yAxisId"],pD=["xAxisId","yAxisId"];function Kv(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function et(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Kv(Object(r),!0).forEach(function(n){yD(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Kv(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function yD(e,t,r){return(t=gD(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function gD(e){var t=bD(e,"string");return typeof t=="symbol"?t:t+""}function bD(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Ar(){return Ar=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Ar.apply(null,arguments)}function Si(e,t){if(e==null)return{};var r,n,a=xD(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function xD(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}var jD=e=>{var{fill:t}=e;if(!t||t==="none")return null;var{fillOpacity:r,x:n,y:a,width:i,height:o,ry:l}=e;return f.createElement("rect",{x:n,y:a,ry:l,width:i,height:o,stroke:"none",fill:t,fillOpacity:r,className:"recharts-cartesian-grid-bg"})};function ex(e){var{option:t,lineItemProps:r}=e,n;if(f.isValidElement(t))n=f.cloneElement(t,r);else if(typeof t=="function")n=t(r);else{var a,{x1:i,y1:o,x2:l,y2:c,key:d}=r,u=Si(r,mD),m=(a=kt(u))!==null&&a!==void 0?a:{},{offset:h}=m,v=Si(m,vD);n=f.createElement("line",Ar({},v,{x1:i,y1:o,x2:l,y2:c,fill:"none",key:d}))}return n}function wD(e){var{x:t,width:r,horizontal:n=!0,horizontalPoints:a}=e;if(!n||!a||!a.length)return null;var{xAxisId:i,yAxisId:o}=e,l=Si(e,hD),c=a.map((d,u)=>{var m=et(et({},l),{},{x1:t,y1:d,x2:t+r,y2:d,key:"line-".concat(u),index:u});return f.createElement(ex,{key:"line-".concat(u),option:n,lineItemProps:m})});return f.createElement("g",{className:"recharts-cartesian-grid-horizontal"},c)}function CD(e){var{y:t,height:r,vertical:n=!0,verticalPoints:a}=e;if(!n||!a||!a.length)return null;var{xAxisId:i,yAxisId:o}=e,l=Si(e,pD),c=a.map((d,u)=>{var m=et(et({},l),{},{x1:d,y1:t,x2:d,y2:t+r,key:"line-".concat(u),index:u});return f.createElement(ex,{option:n,lineItemProps:m,key:"line-".concat(u)})});return f.createElement("g",{className:"recharts-cartesian-grid-vertical"},c)}function kD(e){var{horizontalFill:t,fillOpacity:r,x:n,y:a,width:i,height:o,horizontalPoints:l,horizontal:c=!0}=e;if(!c||!t||!t.length||l==null)return null;var d=l.map(m=>Math.round(m+a-a)).sort((m,h)=>m-h);a!==d[0]&&d.unshift(0);var u=d.map((m,h)=>{var v=d[h+1],p=v==null,b=p?a+o-m:v-m;if(b<=0)return null;var y=h%t.length;return f.createElement("rect",{key:"react-".concat(h),y:m,x:n,height:b,width:i,stroke:"none",fill:t[y],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return f.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},u)}function SD(e){var{vertical:t=!0,verticalFill:r,fillOpacity:n,x:a,y:i,width:o,height:l,verticalPoints:c}=e;if(!t||!r||!r.length)return null;var d=c.map(m=>Math.round(m+a-a)).sort((m,h)=>m-h);a!==d[0]&&d.unshift(0);var u=d.map((m,h)=>{var v=d[h+1],p=v==null,b=p?a+o-m:v-m;if(b<=0)return null;var y=h%r.length;return f.createElement("rect",{key:"react-".concat(h),x:m,y:i,width:b,height:l,stroke:"none",fill:r[y],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return f.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},u)}var ND=(e,t)=>{var{xAxis:r,width:n,height:a,offset:i}=e;return dy(Eu(et(et(et({},Yt),r),{},{ticks:fy(r),viewBox:{x:0,y:0,width:n,height:a}})),i.left,i.left+i.width,t)},PD=(e,t)=>{var{yAxis:r,width:n,height:a,offset:i}=e;return dy(Eu(et(et(et({},Yt),r),{},{ticks:fy(r),viewBox:{x:0,y:0,width:n,height:a}})),i.top,i.top+i.height,t)},AD={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[],xAxisId:0,yAxisId:0,syncWithTicks:!1,zIndex:Ze.grid};function tx(e){var t=Dc(),r=Rc(),n=gy(),a=et(et({},Ke(e,AD)),{},{x:ee(e.x)?e.x:n.left,y:ee(e.y)?e.y:n.top,width:ee(e.width)?e.width:n.width,height:ee(e.height)?e.height:n.height}),{xAxisId:i,yAxisId:o,x:l,y:c,width:d,height:u,syncWithTicks:m,horizontalValues:h,verticalValues:v}=a,p=dt(),b=Z(N=>Lm(N,"xAxis",i,p)),y=Z(N=>Lm(N,"yAxis",o,p));if(!on(d)||!on(u)||!ee(l)||!ee(c))return null;var g=a.verticalCoordinatesGenerator||ND,j=a.horizontalCoordinatesGenerator||PD,{horizontalPoints:x,verticalPoints:C}=a;if((!x||!x.length)&&typeof j=="function"){var w=h&&h.length,P=j({yAxis:y?et(et({},y),{},{ticks:w?h:y.ticks}):void 0,width:t??d,height:r??u,offset:n},w?!0:m);kf(Array.isArray(P),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(typeof P,"]")),Array.isArray(P)&&(x=P)}if((!C||!C.length)&&typeof g=="function"){var A=v&&v.length,S=g({xAxis:b?et(et({},b),{},{ticks:A?v:b.ticks}):void 0,width:t??d,height:r??u,offset:n},A?!0:m);kf(Array.isArray(S),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(typeof S,"]")),Array.isArray(S)&&(C=S)}return f.createElement(Tt,{zIndex:a.zIndex},f.createElement("g",{className:"recharts-cartesian-grid"},f.createElement(jD,{fill:a.fill,fillOpacity:a.fillOpacity,x:a.x,y:a.y,width:a.width,height:a.height,ry:a.ry}),f.createElement(kD,Ar({},a,{horizontalPoints:x})),f.createElement(SD,Ar({},a,{verticalPoints:C})),f.createElement(wD,Ar({},a,{offset:n,horizontalPoints:x,xAxis:b,yAxis:y})),f.createElement(CD,Ar({},a,{offset:n,verticalPoints:C,xAxis:b,yAxis:y}))))}tx.displayName="CartesianGrid";var OD={},rx=at({name:"errorBars",initialState:OD,reducers:{addErrorBar:(e,t)=>{var{itemId:r,errorBar:n}=t.payload;e[r]||(e[r]=[]),e[r].push(n)},replaceErrorBar:(e,t)=>{var{itemId:r,prev:n,next:a}=t.payload;e[r]&&(e[r]=e[r].map(i=>i.dataKey===n.dataKey&&i.direction===n.direction?a:i))},removeErrorBar:(e,t)=>{var{itemId:r,errorBar:n}=t.payload;e[r]&&(e[r]=e[r].filter(a=>a.dataKey!==n.dataKey||a.direction!==n.direction))}}}),{addErrorBar:MB,replaceErrorBar:IB,removeErrorBar:DB}=rx.actions,ED=rx.reducer,_D=["children"];function TD(e,t){if(e==null)return{};var r,n,a=MD(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function MD(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}var ID={data:[],xAxisId:"xAxis-0",yAxisId:"yAxis-0",dataPointFormatter:()=>({x:0,y:0,value:0}),errorBarOffset:0},DD=f.createContext(ID);function RD(e){var{children:t}=e,r=TD(e,_D);return f.createElement(DD.Provider,{value:r},t)}function nx(e,t){var r,n,a=Z(d=>nr(d,e)),i=Z(d=>ar(d,t)),o=(r=a?.allowDataOverflow)!==null&&r!==void 0?r:$e.allowDataOverflow,l=(n=i?.allowDataOverflow)!==null&&n!==void 0?n:Fe.allowDataOverflow,c=o||l;return{needClip:c,needClipX:o,needClipY:l}}function LD(e){var{xAxisId:t,yAxisId:r,clipPathId:n}=e,a=Ou(),{needClipX:i,needClipY:o,needClip:l}=nx(t,r);if(!l||!a)return null;var{x:c,y:d,width:u,height:m}=a;return f.createElement("clipPath",{id:"clipPath-".concat(n)},f.createElement("rect",{x:i?c:c-u/2,y:o?d:d-m/2,width:i?u:u*2,height:o?m:m*2}))}var ax=(e,t,r,n)=>Fg(e,"xAxis",t,n),ix=(e,t,r,n)=>$g(e,"xAxis",t,n),sx=(e,t,r,n)=>Fg(e,"yAxis",r,n),ox=(e,t,r,n)=>$g(e,"yAxis",r,n),$D=_([xe,ax,sx,ix,ox],(e,t,r,n,a)=>er(e,"xAxis")?si(t,n,!1):si(r,a,!1)),FD=(e,t,r,n,a)=>a;function BD(e){return e.type==="line"}var zD=_([pg,FD],(e,t)=>e.filter(BD).find(r=>r.id===t)),KD=_([xe,ax,sx,ix,ox,zD,$D,ca],(e,t,r,n,a,i,o,l)=>{var{chartData:c,dataStartIndex:d,dataEndIndex:u}=l;if(!(i==null||t==null||r==null||n==null||a==null||n.length===0||a.length===0||o==null||e!=="horizontal"&&e!=="vertical")){var{dataKey:m,data:h}=i,v;if(h!=null&&h.length>0?v=h:v=c?.slice(d,u+1),v!=null)return cR({layout:e,xAxis:t,yAxis:r,xAxisTicks:n,yAxisTicks:a,dataKey:m,bandSize:o,displayedData:v})}});function VD(e){var t=an(e),r=3,n=2;if(t!=null){var{r:a,strokeWidth:i}=t,o=Number(a),l=Number(i);return(Number.isNaN(o)||o<0)&&(o=r),(Number.isNaN(l)||l<0)&&(l=n),{r:o,strokeWidth:l}}return{r,strokeWidth:n}}var UD=["id"],qD=["type","layout","connectNulls","needClip","shape"],WD=["activeDot","animateNewValues","animationBegin","animationDuration","animationEasing","connectNulls","dot","hide","isAnimationActive","label","legendType","xAxisId","yAxisId","id"];function Qn(){return Qn=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Qn.apply(null,arguments)}function Vv(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Lt(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Vv(Object(r),!0).forEach(function(n){HD(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Vv(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function HD(e,t,r){return(t=GD(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function GD(e){var t=XD(e,"string");return typeof t=="symbol"?t:t+""}function XD(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Tu(e,t){if(e==null)return{};var r,n,a=YD(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function YD(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}var ZD=e=>{var{dataKey:t,name:r,stroke:n,legendType:a,hide:i}=e;return[{inactive:i,dataKey:t,type:a,color:n,value:Zi(r,t),payload:e}]},JD=f.memo(e=>{var{dataKey:t,data:r,stroke:n,strokeWidth:a,fill:i,name:o,hide:l,unit:c,tooltipType:d,id:u}=e,m={dataDefinedOnItem:r,getPosition:ta,settings:{stroke:n,strokeWidth:a,fill:i,dataKey:t,nameKey:void 0,name:Zi(o,t),hide:l,type:d,color:n,unit:c,graphicalItemId:u}};return f.createElement(Ub,{tooltipEntrySettings:m})}),lx=(e,t)=>"".concat(t,"px ").concat(e,"px");function QD(e,t){for(var r=e.length%2!==0?[...e,0]:e,n=[],a=0;a<t;++a)n.push(...r);return n}var eR=(e,t,r)=>{var n=r.reduce((h,v)=>h+v,0);if(!n)return lx(t,e);for(var a=Math.floor(e/n),i=e%n,o=[],l=0,c=0;l<r.length;c+=(d=r[l])!==null&&d!==void 0?d:0,++l){var d,u=r[l];if(u!=null&&c+u>i){o=[...r.slice(0,l),i-c];break}}var m=o.length%2===0?[0,t]:[t];return[...QD(r,a),...o,...m].map(h=>"".concat(h,"px")).join(", ")};function tR(e){var{clipPathId:t,points:r,props:n}=e,{dot:a,dataKey:i,needClip:o}=n,{id:l}=n,c=Tu(n,UD),d=kt(c);return f.createElement(uI,{points:r,dot:a,className:"recharts-line-dots",dotClassName:"recharts-line-dot",dataKey:i,baseProps:d,needClip:o,clipPathId:t})}function rR(e){var{showLabels:t,children:r,points:n}=e,a=f.useMemo(()=>n?.map(i=>{var o,l,c={x:(o=i.x)!==null&&o!==void 0?o:0,y:(l=i.y)!==null&&l!==void 0?l:0,width:0,lowerWidth:0,upperWidth:0,height:0};return Lt(Lt({},c),{},{value:i.value,payload:i.payload,viewBox:c,parentViewBox:void 0,fill:void 0})}),[n]);return f.createElement(wT,{value:t?a:void 0},r)}function Uv(e){var{clipPathId:t,pathRef:r,points:n,strokeDasharray:a,props:i}=e,{type:o,layout:l,connectNulls:c,needClip:d,shape:u}=i,m=Tu(i,qD),h=Lt(Lt({},st(m)),{},{fill:"none",className:"recharts-line-curve",clipPath:d?"url(#clipPath-".concat(t,")"):void 0,points:n,type:o,layout:l,connectNulls:c,strokeDasharray:a??i.strokeDasharray});return f.createElement(f.Fragment,null,n?.length>1&&f.createElement(Vb,Qn({shapeType:"curve",option:u},h,{pathRef:r})),f.createElement(tR,{points:n,clipPathId:t,props:i}))}function nR(e){try{return e&&e.getTotalLength&&e.getTotalLength()||0}catch{return 0}}function aR(e){var{clipPathId:t,props:r,pathRef:n,previousPointsRef:a,longestAnimatedLengthRef:i}=e,{points:o,strokeDasharray:l,isAnimationActive:c,animationBegin:d,animationDuration:u,animationEasing:m,animateNewValues:h,width:v,height:p,onAnimationEnd:b,onAnimationStart:y}=r,g=a.current,j=os(o,"recharts-line-"),x=f.useRef(j),[C,w]=f.useState(!1),P=!C,A=f.useCallback(()=>{typeof b=="function"&&b(),w(!1)},[b]),S=f.useCallback(()=>{typeof y=="function"&&y(),w(!0)},[y]),N=nR(n.current),E=f.useRef(0);x.current!==j&&(E.current=i.current,x.current=j);var T=E.current;return f.createElement(rR,{points:o,showLabels:P},r.children,f.createElement(ss,{animationId:j,begin:d,duration:u,isActive:c,easing:m,onAnimationEnd:A,onAnimationStart:S,key:j},O=>{var I=tt(T,N+T,O),z=Math.min(I,N),D;if(c)if(l){var V="".concat(l).split(/[,\s]+/gim).map(K=>parseFloat(K));D=eR(z,N,V)}else D=lx(N,z);else D=l==null?void 0:String(l);if(O>0&&N>0&&(a.current=o,i.current=Math.max(i.current,z)),g){var B=g.length/o.length,W=O===1?o:o.map((K,te)=>{var G=Math.floor(te*B);if(g[G]){var M=g[G];return Lt(Lt({},K),{},{x:tt(M.x,K.x,O),y:tt(M.y,K.y,O)})}return h?Lt(Lt({},K),{},{x:tt(v*2,K.x,O),y:tt(p/2,K.y,O)}):Lt(Lt({},K),{},{x:K.x,y:K.y})});return a.current=W,f.createElement(Uv,{props:r,points:W,clipPathId:t,pathRef:n,strokeDasharray:D})}return f.createElement(Uv,{props:r,points:o,clipPathId:t,pathRef:n,strokeDasharray:D})}),f.createElement(Mb,{label:r.label}))}function iR(e){var{clipPathId:t,props:r}=e,n=f.useRef(null),a=f.useRef(0),i=f.useRef(null);return f.createElement(aR,{props:r,clipPathId:t,previousPointsRef:n,longestAnimatedLengthRef:a,pathRef:i})}var sR=(e,t)=>{var r,n;return{x:(r=e.x)!==null&&r!==void 0?r:void 0,y:(n=e.y)!==null&&n!==void 0?n:void 0,value:e.value,errorVal:ge(e.payload,t)}};class oR extends f.Component{render(){var{hide:t,dot:r,points:n,className:a,xAxisId:i,yAxisId:o,top:l,left:c,width:d,height:u,id:m,needClip:h,zIndex:v}=this.props;if(t)return null;var p=ve("recharts-line",a),b=m,{r:y,strokeWidth:g}=VD(r),j=Kb(r),x=y*2+g,C=h?"url(#clipPath-".concat(j?"":"dots-").concat(b,")"):void 0;return f.createElement(Tt,{zIndex:v},f.createElement(ot,{className:p},h&&f.createElement("defs",null,f.createElement(LD,{clipPathId:b,xAxisId:i,yAxisId:o}),!j&&f.createElement("clipPath",{id:"clipPath-dots-".concat(b)},f.createElement("rect",{x:c-x/2,y:l-x/2,width:d+x,height:u+x}))),f.createElement(RD,{xAxisId:i,yAxisId:o,data:n,dataPointFormatter:sR,errorBarOffset:0},f.createElement(iR,{props:this.props,clipPathId:b}))),f.createElement(EI,{activeDot:this.props.activeDot,points:n,mainColor:this.props.stroke,itemDataKey:this.props.dataKey,clipPath:C}))}}var cx={activeDot:!0,animateNewValues:!0,animationBegin:0,animationDuration:1500,animationEasing:"ease",connectNulls:!1,dot:!0,fill:"#fff",hide:!1,isAnimationActive:"auto",label:!1,legendType:"line",stroke:"#3182bd",strokeWidth:1,xAxisId:0,yAxisId:0,zIndex:Ze.line,type:"linear"};function lR(e){var t=Ke(e,cx),{activeDot:r,animateNewValues:n,animationBegin:a,animationDuration:i,animationEasing:o,connectNulls:l,dot:c,hide:d,isAnimationActive:u,label:m,legendType:h,xAxisId:v,yAxisId:p,id:b}=t,y=Tu(t,WD),{needClip:g}=nx(v,p),j=Ou(),x=hn(),C=dt(),w=Z(E=>KD(E,v,p,C,b));if(x!=="horizontal"&&x!=="vertical"||w==null||j==null)return null;var{height:P,width:A,x:S,y:N}=j;return f.createElement(oR,Qn({},y,{id:b,connectNulls:l,dot:c,activeDot:r,animateNewValues:n,animationBegin:a,animationDuration:i,animationEasing:o,isAnimationActive:u,hide:d,label:m,legendType:h,xAxisId:v,yAxisId:p,points:w,layout:x,height:P,width:A,left:S,top:N,needClip:g}))}function cR(e){var{layout:t,xAxis:r,yAxis:n,xAxisTicks:a,yAxisTicks:i,dataKey:o,bandSize:l,displayedData:c}=e;return c.map((d,u)=>{var m=ge(d,o);if(t==="horizontal"){var h=bf({axis:r,ticks:a,bandSize:l,entry:d,index:u}),v=ze(m)?null:n.scale.map(m);return{x:h,y:v??null,value:m,payload:d}}var p=ze(m)?null:r.scale.map(m),b=bf({axis:n,ticks:i,bandSize:l,entry:d,index:u});return p==null||b==null?null:{x:p,y:b,value:m,payload:d}}).filter(Boolean)}function uR(e){var t=Ke(e,cx),r=dt();return f.createElement(qb,{id:t.id,type:"line"},n=>f.createElement(f.Fragment,null,f.createElement(fM,{legendPayload:ZD(t)}),f.createElement(JD,{dataKey:t.dataKey,data:t.data,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,name:t.name,hide:t.hide,unit:t.unit,tooltipType:t.tooltipType,id:n}),f.createElement(PM,{type:"line",id:n,data:t.data,xAxisId:t.xAxisId,yAxisId:t.yAxisId,zAxisId:0,dataKey:t.dataKey,hide:t.hide,isPanorama:r}),f.createElement(lR,Qn({},t,{id:n}))))}var ux=f.memo(uR,oa);ux.displayName="Line";var dR=["domain","range"],fR=["domain","range"];function qv(e,t){if(e==null)return{};var r,n,a=mR(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function mR(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}function Wv(e,t){return e===t?!0:Array.isArray(e)&&e.length===2&&Array.isArray(t)&&t.length===2?e[0]===t[0]&&e[1]===t[1]:!1}function dx(e,t){if(e===t)return!0;var{domain:r,range:n}=e,a=qv(e,dR),{domain:i,range:o}=t,l=qv(t,fR);return!Wv(r,i)||!Wv(n,o)?!1:oa(a,l)}var vR=["type"],hR=["dangerouslySetInnerHTML","ticks","scale"],pR=["id","scale"];function zl(){return zl=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},zl.apply(null,arguments)}function Hv(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Gv(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Hv(Object(r),!0).forEach(function(n){yR(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Hv(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function yR(e,t,r){return(t=gR(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function gR(e){var t=bR(e,"string");return typeof t=="symbol"?t:t+""}function bR(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Kl(e,t){if(e==null)return{};var r,n,a=xR(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function xR(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}function jR(e){var t=pe(),r=f.useRef(null),n=by(),{type:a}=e,i=Kl(e,vR),o=us(n,"xAxis",a),l=f.useMemo(()=>{if(o!=null)return Gv(Gv({},i),{},{type:o})},[i,o]);return f.useLayoutEffect(()=>{l!=null&&(r.current===null?t(hI(l)):r.current!==l&&t(pI({prev:r.current,next:l})),r.current=l)},[l,t]),f.useLayoutEffect(()=>()=>{r.current&&(t(yI(r.current)),r.current=null)},[t]),null}var wR=e=>{var{xAxisId:t,className:r}=e,n=Z(py),a=dt(),i="xAxis",o=Z(g=>Lg(g,i,t,a)),l=Z(g=>VO(g,t)),c=Z(g=>XO(g,t)),d=Z(g=>mg(g,t));if(l==null||c==null||d==null)return null;var{dangerouslySetInnerHTML:u,ticks:m,scale:h}=e,v=Kl(e,hR),{id:p,scale:b}=d,y=Kl(d,pR);return f.createElement(_u,zl({},v,y,{x:c.x,y:c.y,width:l.width,height:l.height,className:ve("recharts-".concat(i," ").concat(i),r),viewBox:n,ticks:o,axisType:i,axisId:t}))},CR={allowDataOverflow:$e.allowDataOverflow,allowDecimals:$e.allowDecimals,allowDuplicatedCategory:$e.allowDuplicatedCategory,angle:$e.angle,axisLine:Yt.axisLine,height:$e.height,hide:!1,includeHidden:$e.includeHidden,interval:$e.interval,label:!1,minTickGap:$e.minTickGap,mirror:$e.mirror,orientation:$e.orientation,padding:$e.padding,reversed:$e.reversed,scale:$e.scale,tick:$e.tick,tickCount:$e.tickCount,tickLine:Yt.tickLine,tickSize:Yt.tickSize,type:$e.type,niceTicks:$e.niceTicks,xAxisId:0},kR=e=>{var t=Ke(e,CR);return f.createElement(f.Fragment,null,f.createElement(jR,{allowDataOverflow:t.allowDataOverflow,allowDecimals:t.allowDecimals,allowDuplicatedCategory:t.allowDuplicatedCategory,angle:t.angle,dataKey:t.dataKey,domain:t.domain,height:t.height,hide:t.hide,id:t.xAxisId,includeHidden:t.includeHidden,interval:t.interval,minTickGap:t.minTickGap,mirror:t.mirror,name:t.name,orientation:t.orientation,padding:t.padding,reversed:t.reversed,scale:t.scale,tick:t.tick,tickCount:t.tickCount,tickFormatter:t.tickFormatter,ticks:t.ticks,type:t.type,unit:t.unit,niceTicks:t.niceTicks}),f.createElement(wR,t))},fx=f.memo(kR,dx);fx.displayName="XAxis";var SR=["type"],NR=["dangerouslySetInnerHTML","ticks","scale"],PR=["id","scale"];function Vl(){return Vl=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Vl.apply(null,arguments)}function Xv(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function Yv(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Xv(Object(r),!0).forEach(function(n){AR(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Xv(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function AR(e,t,r){return(t=OR(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function OR(e){var t=ER(e,"string");return typeof t=="symbol"?t:t+""}function ER(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Ul(e,t){if(e==null)return{};var r,n,a=_R(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function _R(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}function TR(e){var t=pe(),r=f.useRef(null),n=by(),{type:a}=e,i=Ul(e,SR),o=us(n,"yAxis",a),l=f.useMemo(()=>{if(o!=null)return Yv(Yv({},i),{},{type:o})},[o,i]);return f.useLayoutEffect(()=>{l!=null&&(r.current===null?t(gI(l)):r.current!==l&&t(bI({prev:r.current,next:l})),r.current=l)},[l,t]),f.useLayoutEffect(()=>()=>{r.current&&(t(xI(r.current)),r.current=null)},[t]),null}function MR(e){var{yAxisId:t,className:r,width:n,label:a}=e,i=f.useRef(null),o=f.useRef(null),l=Z(py),c=dt(),d=pe(),u="yAxis",m=Z(P=>JO(P,t)),h=Z(P=>ZO(P,t)),v=Z(P=>Lg(P,u,t,c)),p=Z(P=>vg(P,t));if(f.useLayoutEffect(()=>{if(!(n!=="auto"||!m||Nu(a)||f.isValidElement(a)||p==null)){var P=i.current;if(P){var A=P.getCalculatedWidth();Math.round(m.width)!==Math.round(A)&&d(jI({id:t,width:A}))}}},[v,m,d,a,t,n,p]),m==null||h==null||p==null)return null;var{dangerouslySetInnerHTML:b,ticks:y,scale:g}=e,j=Ul(e,NR),{id:x,scale:C}=p,w=Ul(p,PR);return f.createElement(_u,Vl({},j,w,{ref:i,labelRef:o,x:h.x,y:h.y,tickTextProps:n==="auto"?{width:void 0}:{width:n},width:m.width,height:m.height,className:ve("recharts-".concat(u," ").concat(u),r),viewBox:l,ticks:v,axisType:u,axisId:t}))}var IR={allowDataOverflow:Fe.allowDataOverflow,allowDecimals:Fe.allowDecimals,allowDuplicatedCategory:Fe.allowDuplicatedCategory,angle:Fe.angle,axisLine:Yt.axisLine,hide:!1,includeHidden:Fe.includeHidden,interval:Fe.interval,label:!1,minTickGap:Fe.minTickGap,mirror:Fe.mirror,orientation:Fe.orientation,padding:Fe.padding,reversed:Fe.reversed,scale:Fe.scale,tick:Fe.tick,tickCount:Fe.tickCount,tickLine:Yt.tickLine,tickSize:Yt.tickSize,type:Fe.type,niceTicks:Fe.niceTicks,width:Fe.width,yAxisId:0},DR=e=>{var t=Ke(e,IR);return f.createElement(f.Fragment,null,f.createElement(TR,{interval:t.interval,id:t.yAxisId,scale:t.scale,type:t.type,domain:t.domain,allowDataOverflow:t.allowDataOverflow,dataKey:t.dataKey,allowDuplicatedCategory:t.allowDuplicatedCategory,allowDecimals:t.allowDecimals,tickCount:t.tickCount,padding:t.padding,includeHidden:t.includeHidden,reversed:t.reversed,ticks:t.ticks,width:t.width,orientation:t.orientation,mirror:t.mirror,hide:t.hide,unit:t.unit,name:t.name,angle:t.angle,minTickGap:t.minTickGap,tick:t.tick,tickFormatter:t.tickFormatter,niceTicks:t.niceTicks}),f.createElement(MR,t))},mx=f.memo(DR,dx);mx.displayName="YAxis";var RR=(e,t)=>t,Mu=_([RR,xe,sg,We,nb,ir,x1,qe],P1);function LR(e){return"getBBox"in e.currentTarget&&typeof e.currentTarget.getBBox=="function"}function Iu(e){var t=e.currentTarget.getBoundingClientRect(),r,n;if(LR(e)){var a=e.currentTarget.getBBox();r=a.width>0?t.width/a.width:1,n=a.height>0?t.height/a.height:1}else{var i=e.currentTarget;r=i.offsetWidth>0?t.width/i.offsetWidth:1,n=i.offsetHeight>0?t.height/i.offsetHeight:1}var o=(l,c)=>({relativeX:Math.round((l-t.left)/r),relativeY:Math.round((c-t.top)/n)});return"touches"in e?Array.from(e.touches).map(l=>o(l.clientX,l.clientY)):o(e.clientX,e.clientY)}var vx=yt("mouseClick"),hx=na();hx.startListening({actionCreator:vx,effect:(e,t)=>{var r=e.payload,n=Mu(t.getState(),Iu(r));n?.activeIndex!=null&&t.dispatch(vE({activeIndex:n.activeIndex,activeDataKey:void 0,activeCoordinate:n.activeCoordinate}))}});var ql=yt("mouseMove"),px=na(),Hr=null,jr=null,qo=null;px.startListening({actionCreator:ql,effect:(e,t)=>{var r=e.payload,n=t.getState(),{throttleDelay:a,throttledEvents:i}=n.eventSettings,o=i==="all"||i?.includes("mousemove");Hr!==null&&(cancelAnimationFrame(Hr),Hr=null),jr!==null&&(typeof a!="number"||!o)&&(clearTimeout(jr),jr=null),qo=Iu(r);var l=()=>{var c=t.getState(),d=va(c,c.tooltip.settings.shared);if(!qo){Hr=null,jr=null;return}if(d==="axis"){var u=Mu(c,qo);u?.activeIndex!=null?t.dispatch(Hg({activeIndex:u.activeIndex,activeDataKey:void 0,activeCoordinate:u.activeCoordinate})):t.dispatch(Wg())}Hr=null,jr=null};if(!o){l();return}a==="raf"?Hr=requestAnimationFrame(l):typeof a=="number"&&jr===null&&(jr=setTimeout(l,a))}});function $R(e,t){return t instanceof HTMLElement?"HTMLElement <".concat(t.tagName,' class="').concat(t.className,'">'):t===window?"global.window":e==="children"&&typeof t=="object"&&t!==null?"<<CHILDREN>>":t}var Zv={accessibilityLayer:!0,barCategoryGap:"10%",barGap:4,barSize:void 0,className:void 0,maxBarSize:void 0,stackOffset:"none",syncId:void 0,syncMethod:"index",baseValue:void 0,reverseStackOrder:!1},yx=at({name:"rootProps",initialState:Zv,reducers:{updateOptions:(e,t)=>{var r;e.accessibilityLayer=t.payload.accessibilityLayer,e.barCategoryGap=t.payload.barCategoryGap,e.barGap=(r=t.payload.barGap)!==null&&r!==void 0?r:Zv.barGap,e.barSize=t.payload.barSize,e.maxBarSize=t.payload.maxBarSize,e.stackOffset=t.payload.stackOffset,e.syncId=t.payload.syncId,e.syncMethod=t.payload.syncMethod,e.className=t.payload.className,e.baseValue=t.payload.baseValue,e.reverseStackOrder=t.payload.reverseStackOrder}}}),FR=yx.reducer,{updateOptions:BR}=yx.actions,zR=null,KR={updatePolarOptions:(e,t)=>e===null?t.payload:(e.startAngle=t.payload.startAngle,e.endAngle=t.payload.endAngle,e.cx=t.payload.cx,e.cy=t.payload.cy,e.innerRadius=t.payload.innerRadius,e.outerRadius=t.payload.outerRadius,e)},gx=at({name:"polarOptions",initialState:zR,reducers:KR}),{updatePolarOptions:VR}=gx.actions,UR=gx.reducer,bx=yt("keyDown"),xx=yt("focus"),jx=yt("blur"),Cs=na(),Gr=null,wr=null,Ea=null;Cs.startListening({actionCreator:bx,effect:(e,t)=>{Ea=e.payload,Gr!==null&&(cancelAnimationFrame(Gr),Gr=null);var r=t.getState(),{throttleDelay:n,throttledEvents:a}=r.eventSettings,i=a==="all"||a.includes("keydown");wr!==null&&(typeof n!="number"||!i)&&(clearTimeout(wr),wr=null);var o=()=>{try{var l=t.getState(),c=l.rootProps.accessibilityLayer!==!1;if(!c)return;var{keyboardInteraction:d}=l.tooltip,u=Ea;if(u!=="ArrowRight"&&u!=="ArrowLeft"&&u!=="Enter")return;var m=Fn(d,$r(l),un(l),dn(l)),h=m==null?-1:Number(m),v=!Number.isFinite(h)||h<0,p=ir(l),b=$r(l),y=va(l,l.tooltip.settings.shared);if(u==="Enter"){if(v)return;var g=xi(l,y,"hover",String(d.index));t.dispatch(bi({active:!d.active,activeIndex:d.index,activeCoordinate:g}));return}var j=nE(l),x=j==="left-to-right"?1:-1,C=u==="ArrowRight"?1:-1,w;if(v){var P=un(l),A=dn(l),S=C*x,N=z=>({active:!1,index:String(z),dataKey:void 0,graphicalItemId:void 0,coordinate:void 0});if(w=-1,S>0){for(var E=0;E<b.length;E++)if(Fn(N(E),b,P,A)!=null){w=E;break}}else for(var T=b.length-1;T>=0;T--)if(Fn(N(T),b,P,A)!=null){w=T;break}if(w<0)return}else{w=h+C*x;var O=p?.length||b.length;if(O===0||w>=O||w<0)return}var I=xi(l,y,"hover",String(w));t.dispatch(bi({active:!0,activeIndex:w.toString(),activeCoordinate:I}))}finally{Gr=null,wr=null}};if(!i){o();return}n==="raf"?Gr=requestAnimationFrame(o):typeof n=="number"&&wr===null&&(o(),Ea=null,wr=setTimeout(()=>{Ea?o():(wr=null,Gr=null)},n))}});Cs.startListening({actionCreator:xx,effect:(e,t)=>{var r=t.getState(),n=r.rootProps.accessibilityLayer!==!1;if(n){var{keyboardInteraction:a}=r.tooltip;if(!a.active&&a.index==null){var i="0",o=va(r,r.tooltip.settings.shared),l=xi(r,o,"hover",String(i));t.dispatch(bi({active:!0,activeIndex:i,activeCoordinate:l}))}}}});Cs.startListening({actionCreator:jx,effect:(e,t)=>{var r=t.getState(),n=r.rootProps.accessibilityLayer!==!1;if(n){var{keyboardInteraction:a}=r.tooltip;a.active&&t.dispatch(bi({active:!1,activeIndex:a.index,activeCoordinate:a.coordinate}))}}});function wx(e){e.persist();var{currentTarget:t}=e;return new Proxy(e,{get:(r,n)=>{if(n==="currentTarget")return t;var a=Reflect.get(r,n);return typeof a=="function"?a.bind(r):a}})}var jt=yt("externalEvent"),Cx=na(),_a=new Map,En=new Map,Wo=new Map;Cx.startListening({actionCreator:jt,effect:(e,t)=>{var{handler:r,reactEvent:n}=e.payload;if(r!=null){var a=n.type,i=wx(n);Wo.set(a,{handler:r,reactEvent:i});var o=_a.get(a);o!==void 0&&(cancelAnimationFrame(o),_a.delete(a));var l=t.getState(),{throttleDelay:c,throttledEvents:d}=l.eventSettings,u=d,m=u==="all"||u?.includes(a),h=En.get(a);h!==void 0&&(typeof c!="number"||!m)&&(clearTimeout(h),En.delete(a));var v=()=>{var y=Wo.get(a);try{if(!y)return;var{handler:g,reactEvent:j}=y,x=t.getState(),C={activeCoordinate:a1(x),activeDataKey:ob(x),activeIndex:fn(x),activeLabel:sb(x),activeTooltipIndex:fn(x),isTooltipActive:i1(x)};g&&g(C,j)}finally{_a.delete(a),En.delete(a),Wo.delete(a)}};if(!m){v();return}if(c==="raf"){var p=requestAnimationFrame(v);_a.set(a,p)}else if(typeof c=="number"){if(!En.has(a)){v();var b=setTimeout(v,c);En.set(a,b)}}else v()}}});var qR=_([wn],e=>e.tooltipItemPayloads),WR=_([qR,(e,t)=>t,(e,t,r)=>r],(e,t,r)=>{if(t!=null){var n=e.find(i=>i.settings.graphicalItemId===r);if(n!=null){var{getPosition:a}=n;if(a!=null)return a(t)}}}),kx=yt("touchMove"),Sx=na(),Cr=null,or=null,Jv=null,_n=null;Sx.startListening({actionCreator:kx,effect:(e,t)=>{var r=e.payload;if(!(r.touches==null||r.touches.length===0)){_n=wx(r);var n=t.getState(),{throttleDelay:a,throttledEvents:i}=n.eventSettings,o=i==="all"||i.includes("touchmove");Cr!==null&&(cancelAnimationFrame(Cr),Cr=null),or!==null&&(typeof a!="number"||!o)&&(clearTimeout(or),or=null),Jv=Array.from(r.touches).map(c=>Iu({clientX:c.clientX,clientY:c.clientY,currentTarget:r.currentTarget}));var l=()=>{if(_n!=null){var c=t.getState(),d=va(c,c.tooltip.settings.shared);if(d==="axis"){var u,m=(u=Jv)===null||u===void 0?void 0:u[0];if(m==null){Cr=null,or=null;return}var h=Mu(c,m);h?.activeIndex!=null&&t.dispatch(Hg({activeIndex:h.activeIndex,activeDataKey:void 0,activeCoordinate:h.activeCoordinate}))}else if(d==="item"){var v,p=_n.touches[0];if(document.elementFromPoint==null||p==null)return;var b=document.elementFromPoint(p.clientX,p.clientY);if(!b||!b.getAttribute)return;var y=b.getAttribute(vy),g=(v=b.getAttribute(hy))!==null&&v!==void 0?v:void 0,j=zr(c).find(w=>w.id===g);if(y==null||j==null||g==null)return;var{dataKey:x}=j,C=WR(c,y,g);t.dispatch(qg({activeDataKey:x,activeIndex:y,activeCoordinate:C,activeGraphicalItemId:g}))}Cr=null,or=null}};if(!o){l();return}a==="raf"?Cr=requestAnimationFrame(l):typeof a=="number"&&or===null&&(l(),_n=null,or=setTimeout(()=>{_n?l():(or=null,Cr=null)},a))}}});var Du={throttleDelay:"raf",throttledEvents:["mousemove","touchmove","pointermove","scroll","wheel"]},Nx=at({name:"eventSettings",initialState:Du,reducers:{setEventSettings:(e,t)=>{t.payload.throttleDelay!=null&&(e.throttleDelay=t.payload.throttleDelay),t.payload.throttledEvents!=null&&(e.throttledEvents=t.payload.throttledEvents)}}}),{setEventSettings:HR}=Nx.actions,GR=Nx.reducer,XR=Rp({brush:_I,cartesianAxis:wI,chartData:n_,errorBars:ED,eventSettings:GR,graphicalItems:SM,layout:FS,legend:AN,options:J1,polarAxis:IT,polarOptions:UR,referenceElements:DI,renderedTicks:JI,rootProps:FR,tooltip:hE,zIndex:B1}),YR=function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Chart";return uS({reducer:XR,preloadedState:t,middleware:n=>{var a;return n({serializableCheck:!1,immutableCheck:!["commonjs","es6","production"].includes((a="es6")!==null&&a!==void 0?a:"")}).concat([hx.middleware,px.middleware,Cs.middleware,Cx.middleware,Sx.middleware])},enhancers:n=>{var a=n;return typeof n=="function"&&(a=n()),a.concat(Zp({type:"raf"}))},devTools:{serialize:{replacer:$R},name:"recharts-".concat(r)}})};function Px(e){var{preloadedState:t,children:r,reduxStoreName:n}=e,a=dt(),i=f.useRef(null);if(a)return r;i.current==null&&(i.current=YR(t,n));var o=Pc;return f.createElement(WN,{context:o,store:i.current},r)}function ZR(e){var{layout:t,margin:r}=e,n=pe(),a=dt();return f.useEffect(()=>{a||(n(RS(t)),n(DS(r)))},[n,a,t,r]),null}var Ax=f.memo(ZR,oa);function Ox(e){var t=pe();return f.useEffect(()=>{t(BR(e))},[t,e]),null}var JR=e=>{var t=pe();return f.useEffect(()=>{t(HR(e))},[t,e]),null},Ex=f.memo(JR,oa);function Qv(e){var{zIndex:t,isPanorama:r}=e,n=f.useRef(null),a=pe();return f.useLayoutEffect(()=>(n.current&&a($1({zIndex:t,element:n.current,isPanorama:r})),()=>{a(F1({zIndex:t,isPanorama:r}))}),[a,t,r]),f.createElement("g",{tabIndex:-1,ref:n,className:"recharts-zIndex-layer_".concat(t)})}function eh(e){var{children:t,isPanorama:r}=e,n=Z(O1);if(!n||n.length===0)return t;var a=n.filter(o=>o<0),i=n.filter(o=>o>0);return f.createElement(f.Fragment,null,a.map(o=>f.createElement(Qv,{key:o,zIndex:o,isPanorama:r})),t,i.map(o=>f.createElement(Qv,{key:o,zIndex:o,isPanorama:r})))}var QR=["children"];function eL(e,t){if(e==null)return{};var r,n,a=tL(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function tL(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}function Ni(){return Ni=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Ni.apply(null,arguments)}var rL={width:"100%",height:"100%",display:"block"},nL=f.forwardRef((e,t)=>{var r=Dc(),n=Rc(),a=Ty();if(!on(r)||!on(n))return null;var{children:i,otherAttributes:o,title:l,desc:c}=e,d,u;return o!=null&&(typeof o.tabIndex=="number"?d=o.tabIndex:d=a?0:void 0,typeof o.role=="string"?u=o.role:u=a?"application":void 0),f.createElement(bc,Ni({},o,{title:l,desc:c,role:u,tabIndex:d,width:r,height:n,style:rL,ref:t}),i)}),aL=e=>{var{children:t}=e,r=Z(ts);if(!r)return null;var{width:n,height:a,y:i,x:o}=r;return f.createElement(bc,{width:n,height:a,x:o,y:i},t)},th=f.forwardRef((e,t)=>{var{children:r}=e,n=eL(e,QR),a=dt();return a?f.createElement(aL,null,f.createElement(eh,{isPanorama:!0},r)):f.createElement(nL,Ni({ref:t},n),f.createElement(eh,{isPanorama:!1},r))});function iL(){var e=pe(),[t,r]=f.useState(null),n=Z(QS);return f.useEffect(()=>{if(t!=null){var a=t.getBoundingClientRect(),i=a.width/t.offsetWidth;me(i)&&i!==n&&e($S(i))}},[t,e,n]),r}function rh(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function sL(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?rh(Object(r),!0).forEach(function(n){oL(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):rh(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function oL(e,t,r){return(t=lL(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function lL(e){var t=cL(e,"string");return typeof t=="symbol"?t:t+""}function cL(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function vr(){return vr=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},vr.apply(null,arguments)}var uL=()=>(f_(),null);function Pi(e){if(typeof e=="number")return e;if(typeof e=="string"){var t=parseFloat(e);if(!Number.isNaN(t))return t}return 0}var dL=f.forwardRef((e,t)=>{var r,n,a=f.useRef(null),[i,o]=f.useState({containerWidth:Pi((r=e.style)===null||r===void 0?void 0:r.width),containerHeight:Pi((n=e.style)===null||n===void 0?void 0:n.height)}),l=f.useCallback((d,u)=>{o(m=>{var h=Math.round(d),v=Math.round(u);return m.containerWidth===h&&m.containerHeight===v?m:{containerWidth:h,containerHeight:v}})},[]),c=f.useCallback(d=>{if(typeof t=="function"&&t(d),a.current!=null&&(a.current.disconnect(),a.current=null),d!=null&&typeof ResizeObserver<"u"){var{width:u,height:m}=d.getBoundingClientRect();l(u,m);var h=p=>{var b=p[0];if(b!=null){var{width:y,height:g}=b.contentRect;l(y,g)}},v=new ResizeObserver(h);v.observe(d),a.current=v}},[t,l]);return f.useEffect(()=>()=>{var d=a.current;d?.disconnect()},[l]),f.createElement(f.Fragment,null,f.createElement(ia,{width:i.containerWidth,height:i.containerHeight}),f.createElement("div",vr({ref:c},e)))}),fL=f.forwardRef((e,t)=>{var{width:r,height:n}=e,[a,i]=f.useState({containerWidth:Pi(r),containerHeight:Pi(n)}),o=f.useCallback((c,d)=>{i(u=>{var m=Math.round(c),h=Math.round(d);return u.containerWidth===m&&u.containerHeight===h?u:{containerWidth:m,containerHeight:h}})},[]),l=f.useCallback(c=>{if(typeof t=="function"&&t(c),c!=null){var{width:d,height:u}=c.getBoundingClientRect();o(d,u)}},[t,o]);return f.createElement(f.Fragment,null,f.createElement(ia,{width:a.containerWidth,height:a.containerHeight}),f.createElement("div",vr({ref:l},e)))}),mL=f.forwardRef((e,t)=>{var{width:r,height:n}=e;return f.createElement(f.Fragment,null,f.createElement(ia,{width:r,height:n}),f.createElement("div",vr({ref:t},e)))}),vL=f.forwardRef((e,t)=>{var{width:r,height:n}=e;return typeof r=="string"||typeof n=="string"?f.createElement(fL,vr({},e,{ref:t})):typeof r=="number"&&typeof n=="number"?f.createElement(mL,vr({},e,{width:r,height:n,ref:t})):f.createElement(f.Fragment,null,f.createElement(ia,{width:r,height:n}),f.createElement("div",vr({ref:t},e)))});function hL(e){return e?dL:vL}var pL=f.forwardRef((e,t)=>{var{children:r,className:n,height:a,onClick:i,onContextMenu:o,onDoubleClick:l,onMouseDown:c,onMouseEnter:d,onMouseLeave:u,onMouseMove:m,onMouseUp:h,onTouchEnd:v,onTouchMove:p,onTouchStart:b,style:y,width:g,responsive:j,dispatchTouchEvents:x=!0}=e,C=f.useRef(null),w=pe(),[P,A]=f.useState(null),[S,N]=f.useState(null),E=iL(),T=yy(),O=T?.width>0?T.width:g,I=T?.height>0?T.height:a,z=f.useCallback(J=>{E(J),typeof t=="function"&&t(J),A(J),N(J),J!=null&&(C.current=J)},[E,t,A,N]),D=f.useCallback(J=>{w(vx(J)),w(jt({handler:i,reactEvent:J}))},[w,i]),V=f.useCallback(J=>{w(ql(J)),w(jt({handler:d,reactEvent:J}))},[w,d]),B=f.useCallback(J=>{w(Wg()),w(jt({handler:u,reactEvent:J}))},[w,u]),W=f.useCallback(J=>{w(ql(J)),w(jt({handler:m,reactEvent:J}))},[w,m]),K=f.useCallback(()=>{w(xx())},[w]),te=f.useCallback(()=>{w(jx())},[w]),G=f.useCallback(J=>{w(bx(J.key))},[w]),M=f.useCallback(J=>{w(jt({handler:o,reactEvent:J}))},[w,o]),q=f.useCallback(J=>{w(jt({handler:l,reactEvent:J}))},[w,l]),H=f.useCallback(J=>{w(jt({handler:c,reactEvent:J}))},[w,c]),re=f.useCallback(J=>{w(jt({handler:h,reactEvent:J}))},[w,h]),ae=f.useCallback(J=>{w(jt({handler:b,reactEvent:J}))},[w,b]),ye=f.useCallback(J=>{x&&w(kx(J)),w(jt({handler:p,reactEvent:J}))},[w,x,p]),oe=f.useCallback(J=>{w(jt({handler:v,reactEvent:J}))},[w,v]),He=hL(j);return f.createElement(hb.Provider,{value:P},f.createElement(mp.Provider,{value:S},f.createElement(He,{width:O??y?.width,height:I??y?.height,className:ve("recharts-wrapper",n),style:sL({position:"relative",cursor:"default",width:O,height:I},y),onClick:D,onContextMenu:M,onDoubleClick:q,onFocus:K,onBlur:te,onKeyDown:G,onMouseDown:H,onMouseEnter:V,onMouseLeave:B,onMouseMove:W,onMouseUp:re,onTouchEnd:oe,onTouchMove:ye,onTouchStart:ae,ref:z},f.createElement(uL,null),r)))}),yL=["width","height","responsive","children","className","style","compact","title","desc"];function gL(e,t){if(e==null)return{};var r,n,a=bL(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function bL(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}var _x=f.forwardRef((e,t)=>{var{width:r,height:n,responsive:a,children:i,className:o,style:l,compact:c,title:d,desc:u}=e,m=gL(e,yL),h=kt(m);return c?f.createElement(f.Fragment,null,f.createElement(ia,{width:r,height:n}),f.createElement(th,{otherAttributes:h,title:d,desc:u},i)):f.createElement(pL,{className:o,style:l,width:r,height:n,responsive:a??!1,onClick:e.onClick,onMouseLeave:e.onMouseLeave,onMouseEnter:e.onMouseEnter,onMouseMove:e.onMouseMove,onMouseDown:e.onMouseDown,onMouseUp:e.onMouseUp,onContextMenu:e.onContextMenu,onDoubleClick:e.onDoubleClick,onTouchStart:e.onTouchStart,onTouchMove:e.onTouchMove,onTouchEnd:e.onTouchEnd},f.createElement(th,{otherAttributes:h,title:d,desc:u,ref:t},f.createElement(LI,null,i)))});function Wl(){return Wl=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Wl.apply(null,arguments)}function nh(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function xL(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?nh(Object(r),!0).forEach(function(n){jL(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):nh(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function jL(e,t,r){return(t=wL(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function wL(e){var t=CL(e,"string");return typeof t=="symbol"?t:t+""}function CL(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var kL={top:5,right:5,bottom:5,left:5},SL=xL({accessibilityLayer:!0,barCategoryGap:"10%",barGap:4,layout:"horizontal",margin:kL,responsive:!1,reverseStackOrder:!1,stackOffset:"none",syncMethod:"index"},Du),NL=f.forwardRef(function(t,r){var n,a=Ke(t.categoricalChartProps,SL),{chartName:i,defaultTooltipEventType:o,validateTooltipEventTypes:l,tooltipPayloadSearcher:c,categoricalChartProps:d}=t,u={chartName:i,defaultTooltipEventType:o,validateTooltipEventTypes:l,tooltipPayloadSearcher:c,eventEmitter:void 0};return f.createElement(Px,{preloadedState:{options:u},reduxStoreName:(n=d.id)!==null&&n!==void 0?n:i},f.createElement(Xb,{chartData:d.data}),f.createElement(Ax,{layout:a.layout,margin:a.margin}),f.createElement(Ex,{throttleDelay:a.throttleDelay,throttledEvents:a.throttledEvents}),f.createElement(Ox,{baseValue:a.baseValue,accessibilityLayer:a.accessibilityLayer,barCategoryGap:a.barCategoryGap,maxBarSize:a.maxBarSize,stackOffset:a.stackOffset,barGap:a.barGap,barSize:a.barSize,syncId:a.syncId,syncMethod:a.syncMethod,className:a.className,reverseStackOrder:a.reverseStackOrder}),f.createElement(_x,Wl({},a,{ref:r})))}),PL=["axis"],AL=f.forwardRef((e,t)=>f.createElement(NL,{chartName:"LineChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:PL,tooltipPayloadSearcher:pb,categoricalChartProps:e,ref:t}));function OL(e){var t=pe();return f.useEffect(()=>{t(VR(e))},[t,e]),null}var EL=["layout"];function Hl(){return Hl=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Hl.apply(null,arguments)}function _L(e,t){if(e==null)return{};var r,n,a=TL(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)===-1&&{}.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function TL(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}function ah(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function ML(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?ah(Object(r),!0).forEach(function(n){IL(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ah(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function IL(e,t,r){return(t=DL(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function DL(e){var t=RL(e,"string");return typeof t=="symbol"?t:t+""}function RL(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var LL={top:5,right:5,bottom:5,left:5},Tx=ML({accessibilityLayer:!0,stackOffset:"none",barCategoryGap:"10%",barGap:4,margin:LL,reverseStackOrder:!1,syncMethod:"index",layout:"radial",responsive:!1,cx:"50%",cy:"50%",innerRadius:0,outerRadius:"80%"},Du),$L=f.forwardRef(function(t,r){var n,a=Ke(t.categoricalChartProps,Tx),{layout:i}=a,o=_L(a,EL),{chartName:l,defaultTooltipEventType:c,validateTooltipEventTypes:d,tooltipPayloadSearcher:u}=t,m={chartName:l,defaultTooltipEventType:c,validateTooltipEventTypes:d,tooltipPayloadSearcher:u,eventEmitter:void 0};return f.createElement(Px,{preloadedState:{options:m},reduxStoreName:(n=a.id)!==null&&n!==void 0?n:l},f.createElement(Xb,{chartData:a.data}),f.createElement(Ax,{layout:i,margin:a.margin}),f.createElement(Ex,{throttleDelay:a.throttleDelay,throttledEvents:a.throttledEvents}),f.createElement(Ox,{baseValue:void 0,accessibilityLayer:a.accessibilityLayer,barCategoryGap:a.barCategoryGap,maxBarSize:a.maxBarSize,stackOffset:a.stackOffset,barGap:a.barGap,barSize:a.barSize,syncId:a.syncId,syncMethod:a.syncMethod,className:a.className,reverseStackOrder:a.reverseStackOrder}),f.createElement(OL,{cx:a.cx,cy:a.cy,startAngle:a.startAngle,endAngle:a.endAngle,innerRadius:a.innerRadius,outerRadius:a.outerRadius}),f.createElement(_x,Hl({},o,{ref:r})))});function ih(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function sh(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?ih(Object(r),!0).forEach(function(n){FL(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ih(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function FL(e,t,r){return(t=BL(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function BL(e){var t=zL(e,"string");return typeof t=="symbol"?t:t+""}function zL(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var KL=["item"],VL=sh(sh({},Tx),{},{layout:"centric",startAngle:0,endAngle:360}),UL=f.forwardRef((e,t)=>{var r=Ke(e,VL);return f.createElement($L,{chartName:"PieChart",defaultTooltipEventType:"item",validateTooltipEventTypes:KL,tooltipPayloadSearcher:pb,categoricalChartProps:r,ref:t})});const Ai="currentColor",qL=["--accent","--todo","--in-progress","--in-review","--triage","--color-success","--color-warning","--color-error"];function kr(e,t=Ai){if(typeof document>"u"||typeof getComputedStyle!="function")return t;const r=getComputedStyle(document.documentElement).getPropertyValue(e).trim();return r.length>0?r:t}function Ru(){const e=kr("--text"),t=kr("--text-muted",e),r=kr("--accent"),n=kr("--surface-1",""),a=kr("--surface-2",n),i=kr("--border-subtle",""),o=qL.map(l=>kr(l)).filter(l=>l.length>0);return{stroke:r,fill:a,grid:i,tick:t,tooltipBackground:n,tooltipBorder:i,tooltipText:e,legendText:t,palette:o.length>0?o:[Ai]}}function Mx(e,t=Ru()){if(t.palette.length===0)return Ai;const r=Number.isFinite(e)&&e>=0?Math.floor(e):0;return t.palette[r%t.palette.length]??Ai}const WL={width:320,height:220},Ix=120,Dx=120;function HL(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function GL(e){return e.map(t=>({label:t.label,value:Number.isFinite(t.value)&&t.value>0?t.value:0})).filter(t=>t.value>0)}function oh(e,t){return e!==void 0||t!==void 0?{width:e,height:t}:void 0}function lh(e){return typeof e=="number"||typeof e=="string"&&/^\d+(?:\.\d+)?%$/.test(e)?e:"100%"}function Oi(e,t){return Number.isFinite(e)&&e>=t?e:null}function XL(e,t,r){return{width:typeof t=="number"&&t>0?t:e.width,height:typeof r=="number"&&r>0?r:e.height}}function YL(e,t){return Math.abs(e.width-t.width)<.5&&Math.abs(e.height-t.height)<.5}function ZL(e){const t=e.getBoundingClientRect(),r=Oi(t.width,Ix),n=Oi(t.height,Dx);return r===null||n===null?null:{width:r,height:n}}function JL(){const e=f.useRef(null),[t,r]=f.useState(WL);return f.useLayoutEffect(()=>{const n=e.current;if(!n)return;const a=o=>{o&&r(l=>YL(l,o)?l:o)};if(a(ZL(n)),typeof ResizeObserver>"u")return;const i=new ResizeObserver(o=>{const l=o[0];if(!l)return;const c=Oi(l.contentRect.width,Ix),d=Oi(l.contentRect.height,Dx);a(c===null||d===null?null:{width:c,height:d})});return i.observe(n),()=>i.disconnect()},[]),{ref:e,dimensions:t}}function Mt({data:e,ariaLabel:t,width:r,height:n,emptyLabel:a="No chart data"}){const i=Ru(),{ref:o,dimensions:l}=JL(),c=XL(l,r,n),d=GL(e);return d.length===0?s.jsx("div",{className:"cc-recharts-empty",role:"img","aria-label":t,style:oh(r,n),children:a}):s.jsx("div",{ref:o,className:"cc-recharts-chart",role:"img","aria-label":t,style:oh(r,n),"data-responsive-width":lh(r),"data-responsive-height":lh(n),children:s.jsxs(UL,{width:c.width,height:c.height,children:[s.jsx(Hb,{data:d,dataKey:"value",nameKey:"label",isAnimationActive:!HL(),children:d.map((u,m)=>s.jsx(gs,{fill:Mx(m,i),stroke:i.tooltipBorder},u.label))}),s.jsx(bb,{contentStyle:{background:i.tooltipBackground,borderColor:i.tooltipBorder,color:i.tooltipText},itemStyle:{color:i.tooltipText},labelStyle:{color:i.tooltipText}}),s.jsx(Fc,{wrapperStyle:{color:i.legendText}})]})})}const QL={width:360,height:220},Rx=120,Lx=120;function e$(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function t$(e){return Number.isFinite(e)&&e>0?e:0}function r$(e){const t=e.reduce((r,n)=>n>r?n:r,0);return t<=0?e.map(()=>0):e.map(r=>r/t*100)}function n$(e,t){return e.map((r,n)=>{const a=r.values.map(t$);return{label:r.label,dataKey:`series${n}`,values:a,plotKey:t==="series"?`series${n}Normalized`:`series${n}`,plotValues:t==="series"?r$(a):a}}).filter(r=>r.values.length>0)}function a$(e){const t=e.reduce((r,n)=>Math.max(r,n.values.length),0);return Array.from({length:t},(r,n)=>{const a={index:n+1};for(const i of e)a[i.dataKey]=i.values[n]??0,a[i.plotKey]=i.plotValues[n]??0;return a})}function ch(e,t){return e!==void 0||t!==void 0?{width:e,height:t}:void 0}function uh(e){return typeof e=="number"||typeof e=="string"&&/^\d+(?:\.\d+)?%$/.test(e)?e:"100%"}function Ei(e,t){return Number.isFinite(e)&&e>=t?e:null}function i$(e,t,r){return{width:typeof t=="number"&&t>0?t:e.width,height:typeof r=="number"&&r>0?r:e.height}}function s$(e,t){return Math.abs(e.width-t.width)<.5&&Math.abs(e.height-t.height)<.5}function o$(e){const t=e.getBoundingClientRect(),r=Ei(t.width,Rx),n=Ei(t.height,Lx);return r===null||n===null?null:{width:r,height:n}}function l$(){const e=f.useRef(null),[t,r]=f.useState(QL);return f.useLayoutEffect(()=>{const n=e.current;if(!n)return;const a=o=>{o&&r(l=>s$(l,o)?l:o)};if(a(o$(n)),typeof ResizeObserver>"u")return;const i=new ResizeObserver(o=>{const l=o[0];if(!l)return;const c=Ei(l.contentRect.width,Rx),d=Ei(l.contentRect.height,Lx);a(c===null||d===null?null:{width:c,height:d})});return i.observe(n),()=>i.disconnect()},[]),{ref:e,dimensions:t}}function br({series:e,ariaLabel:t,width:r,height:n,emptyLabel:a="No chart data",xAxisLabels:i,valueFormatter:o,scaleMode:l="shared"}){const c=Ru(),{ref:d,dimensions:u}=l$(),m=i$(u,r,n),h=n$(e,l),v=a$(h),p=y=>{const g=typeof y=="number"?y:Number(y);return Number.isFinite(g)?i?.[g-1]??String(y):String(y)},b=y=>{const g=typeof y=="number"?y:Number(y);return o&&Number.isFinite(g)?o(g):String(y)};return h.length===0||v.length===0?s.jsx("div",{className:"cc-recharts-empty",role:"img","aria-label":t,style:ch(r,n),children:a}):s.jsx("div",{ref:d,className:"cc-recharts-chart",role:"img","aria-label":t,style:ch(r,n),"data-scale-mode":l,"data-responsive-width":uh(r),"data-responsive-height":uh(n),children:s.jsxs(AL,{width:m.width,height:m.height,data:v,children:[s.jsx(tx,{stroke:c.grid}),s.jsx(fx,{dataKey:"index",stroke:c.tick,tick:{fill:c.tick},tickFormatter:i?p:void 0}),s.jsx(mx,{stroke:c.tick,tick:{fill:c.tick},domain:l==="series"?[0,100]:void 0,tickFormatter:l==="series"?y=>`${y}%`:o}),s.jsx(bb,{contentStyle:{background:c.tooltipBackground,borderColor:c.tooltipBorder,color:c.tooltipText},itemStyle:{color:c.tooltipText},labelStyle:{color:c.tooltipText},formatter:o?y=>b(y):void 0,labelFormatter:i?p:void 0}),s.jsx(Fc,{wrapperStyle:{color:c.legendText}}),h.map((y,g)=>s.jsx(ux,{type:"monotone",dataKey:y.plotKey,name:y.label,stroke:Mx(g,c),isAnimationActive:!e$()},y.dataKey))]})})}function ft({testId:e,isLoading:t,error:r,isEmpty:n,emptyMessage:a,children:i}){const{t:o}=se("app");return t?s.jsxs("div",{className:"cc-loading-inline","data-testid":`cc-area-${e}-loading`,children:[s.jsx(Ql,{size:18,className:"spin"}),s.jsx("span",{children:o("commandCenter.area.loading","Loading…")})]}):r!==null?s.jsxs("div",{className:"cc-area-error","data-testid":`cc-area-${e}-error`,role:"alert",children:[s.jsx(Mi,{size:22}),s.jsx("p",{children:r})]}):n?s.jsxs("div",{className:"cc-area-empty","data-testid":`cc-area-${e}-empty`,children:[s.jsx(Ii,{size:24}),s.jsx("p",{children:a??o("commandCenter.area.empty","No data for the selected range.")})]}):s.jsx("div",{className:"cc-area","data-testid":`cc-area-${e}`,children:i})}function c$(e,t){if(t==="")return e;const r=t.slice(1);return`${e}${e.includes("?")?"&":"?"}${r}`}function Je(e,t,r={}){const[n,a]=f.useState(null),i=f.useRef(null),[o,l]=f.useState(!0),[c,d]=f.useState(null),u=sC(t),m=cp(t),{projectId:h}=r,v=f.useCallback(async()=>{if(m){l(!1);return}i.current!==null||l(!0),d(null);try{const y=await fr(mr(c$(e,u),h));i.current=y,a(y)}catch(y){d(y instanceof Error?y.message:"Failed to load analytics")}finally{l(!1)}},[e,u,m,h]);f.useEffect(()=>{v()},[v]),vn(v,r.pollMs??0,{enabled:!m&&r.pollMs!==void 0});const p=f.useCallback(()=>{v()},[v]);return{data:n,isLoading:o,error:c!==null&&n===null?c:null,reload:p}}const u$=15e3,d$=["hour","day","week"];function dh(e){return e.usd??-1}function fh(e){return e.key??"unknown"}function mh(e,t){return e.key??t}function $x(e){return ec(e.key??"")}function f$({group:e,unknownLabel:t}){const r=e.key??t;return s.jsxs("span",{className:"cc-model-label",children:[s.jsx(Nh,{provider:$x(e),size:"sm"}),s.jsx("span",{className:"cc-model-label-text",children:r})]})}function m$(e,t,r){const n=[...e];return n.sort((a,i)=>{let o=0;return t==="key"?o=(a.key??"").localeCompare(i.key??""):t==="totalTokens"?o=a.totalTokens-i.totalTokens:o=dh(a.cost)-dh(i.cost),o===0&&(o=(a.key??"").localeCompare(i.key??"")),o*r}),n}function v$({range:e,projectId:t}){const{t:r}=se("app"),[n,a]=f.useState("day"),i=`/command-center/tokens?groupBy=model&granularity=${n}`,{data:o,isLoading:l,error:c}=Je(i,e,{pollMs:u$,projectId:t}),d=f.useMemo(()=>o?.groups??[],[o?.groups]),u=f.useMemo(()=>o?.series??[],[o?.series]),[m,h]=f.useState("totalTokens"),[v,p]=f.useState(-1),b=f.useMemo(()=>d.map(O=>O.key??"∅").join(" "),[d]),y=f.useRef(null);f.useEffect(()=>{if(y.current===null){y.current=b;return}y.current!==b&&(y.current=b,h("totalTokens"),p(-1))},[b]);const g=f.useMemo(()=>m$(d,m,v),[d,m,v]),j=f.useMemo(()=>[...d].sort((O,I)=>I.totalTokens-O.totalTokens||(O.key??"").localeCompare(I.key??"")),[d]),x=f.useMemo(()=>j.map(O=>({label:mh(O,r("commandCenter.tokens.unknownModel","(unknown)")),value:O.totalTokens,valueLabel:U(O.totalTokens),iconProvider:$x(O)})),[j,r]),C=f.useMemo(()=>j.map(O=>({label:mh(O,r("commandCenter.tokens.unknownModel","(unknown)")),value:O.totalTokens})),[j,r]),w=f.useMemo(()=>[{label:r("commandCenter.tokens.input","Input"),values:u.map(O=>O.inputTokens)},{label:r("commandCenter.tokens.output","Output"),values:u.map(O=>O.outputTokens)},{label:r("commandCenter.tokens.cached","Cached"),values:u.map(O=>O.cachedTokens)},{label:r("commandCenter.tokens.total","Total"),values:u.map(O=>O.totalTokens)}],[u,r]);function P(O){O===m?p(I=>I===1?-1:1):(h(O),p(O==="key"?1:-1))}function A(O){return O!==m?null:s.jsx("span",{className:"cc-sort-caret",children:v===1?"▲":"▼"})}const S=o?.totals,N=f.useMemo(()=>u.map(O=>O.bucket).join(" "),[u]),E=S?.totalTokens??0,T=!o||E===0;return s.jsxs(ft,{testId:"tokens",isLoading:l,error:c,isEmpty:T,children:[s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.tokens.totalsTitle","Totals")}),s.jsxs("div",{className:"cc-stat-grid",children:[s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-tokens-total",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.tokens.totalTokens","Total tokens")}),s.jsx("div",{className:"cc-stat-value cc-token-count-live",children:U(E)},E)]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-tokens-cost",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.tokens.cost","Estimated cost")}),s.jsx("div",{className:"cc-stat-value",children:o?Tr(o.cost.usd,o.cost.unavailable):"—"}),o?.cost.stale?s.jsx("span",{className:"cc-stat-sub",children:r("commandCenter.tokens.stalePricing","pricing may be stale")}):null]}),s.jsxs("div",{className:"card cc-stat-card",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.tokens.tasks","Tasks")}),s.jsx("div",{className:"cc-stat-value",children:U(S?.nTasks??0)})]}),s.jsxs("div",{className:"card cc-stat-card",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.tokens.chatMessages","Chat turns")}),s.jsx("div",{className:"cc-stat-value",children:U(S?.nChatMessages??0)})]})]})]}),s.jsxs("div",{className:"cc-area-section",children:[s.jsxs("div",{className:"cc-area-section-header",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.tokens.overTimeChart","Tokens over time")}),s.jsx("div",{className:"cc-token-granularity",role:"group","aria-label":r("commandCenter.tokens.granularity","Token chart granularity"),children:d$.map(O=>s.jsx("button",{type:"button",className:`btn ${O===n?"active":""}`,"aria-pressed":O===n,"data-testid":`cc-token-granularity-${O}`,onClick:()=>a(O),children:r(`commandCenter.tokens.granularity.${O}`,O)},O))})]}),s.jsx(lC,{points:u,ariaLabel:r("commandCenter.tokens.overTimeChart","Tokens over time")},N)]}),u.length>0?s.jsxs("div",{className:"cc-area-section","data-testid":"cc-tokens-line",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.tokens.rechartsLine","Tokens trend")}),s.jsx(br,{series:w,ariaLabel:r("commandCenter.tokens.rechartsLine","Tokens trend")})]}):null,s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.tokens.byModelChart","Tokens by model")}),s.jsx(nt,{data:x,ariaLabel:r("commandCenter.tokens.byModelChart","Tokens by model")})]}),C.length>0?s.jsxs("div",{className:"cc-area-section","data-testid":"cc-tokens-pie",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.tokens.pieChart","Token share by model")}),s.jsx(Mt,{data:C,ariaLabel:r("commandCenter.tokens.pieChart","Token share by model")})]}):null,s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.tokens.tableTitle","Per-model breakdown")}),s.jsx("div",{className:"cc-table-wrap",children:s.jsxs("table",{className:"cc-table","data-testid":"cc-tokens-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsxs("th",{className:"cc-sortable",onClick:()=>P("key"),"data-testid":"cc-tokens-sort-key",children:[r("commandCenter.tokens.model","Model"),A("key")]}),s.jsx("th",{children:r("commandCenter.tokens.input","Input")}),s.jsx("th",{children:r("commandCenter.tokens.output","Output")}),s.jsx("th",{children:r("commandCenter.tokens.cached","Cached")}),s.jsxs("th",{className:"cc-sortable",onClick:()=>P("totalTokens"),"data-testid":"cc-tokens-sort-total",children:[r("commandCenter.tokens.total","Total"),A("totalTokens")]}),s.jsxs("th",{className:"cc-sortable",onClick:()=>P("cost"),"data-testid":"cc-tokens-sort-cost",children:[r("commandCenter.tokens.costCol","Cost"),A("cost")]})]})}),s.jsx("tbody",{children:g.map(O=>s.jsxs("tr",{"data-testid":`cc-tokens-row-${fh(O)}`,children:[s.jsx("td",{children:s.jsx(f$,{group:O,unknownLabel:r("commandCenter.tokens.unknownModel","(unknown)")})}),s.jsx("td",{children:U(O.inputTokens)}),s.jsx("td",{children:U(O.outputTokens)}),s.jsx("td",{children:U(O.cachedTokens)}),s.jsx("td",{children:U(O.totalTokens)}),s.jsx("td",{children:s.jsx("span",{className:O.cost.usd===null?"cc-unavailable":void 0,title:O.cost.unavailable?r("commandCenter.tokens.costUnavailable","No pricing for some or all usage"):void 0,children:Tr(O.cost.usd,O.cost.unavailable)})})]},fh(O)))})]})})]})]})}function h$({range:e,projectId:t}){const{t:r}=se("app"),{data:n,isLoading:a,error:i}=Je("/command-center/tools",e,{projectId:t}),o=f.useMemo(()=>[...n?.byCategory??[]].sort((m,h)=>h.count-m.count||m.category.localeCompare(h.category)),[n?.byCategory]),l=f.useMemo(()=>o.map(m=>({label:m.category,value:m.count,valueLabel:U(m.count)})),[o]),c=f.useMemo(()=>o.map(m=>({label:m.category,value:m.count})),[o]),d=!n||n.toolCalls===0,u=n?n.fullyAutonomous?r("commandCenter.tools.ratioAutonomous","{{ratio}} calls/session (fully autonomous)",{ratio:n.autonomyRatio.toFixed(1)}):`${n.autonomyRatio.toFixed(1)}:1`:"—";return s.jsxs(ft,{testId:"tools",isLoading:a,error:i,isEmpty:d,children:[s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.tools.summaryTitle","Summary")}),s.jsxs("div",{className:"cc-stat-grid",children:[s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-tools-autonomy",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.tools.autonomyRatio","Autonomy ratio")}),s.jsx("div",{className:"cc-stat-value",children:u}),s.jsx("span",{className:"cc-stat-sub",children:r("commandCenter.tools.autonomyHint","tool calls per human intervention")})]}),s.jsxs("div",{className:"card cc-stat-card",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.tools.toolCalls","Tool calls")}),s.jsx("div",{className:"cc-stat-value",children:U(n?.toolCalls??0)})]}),s.jsxs("div",{className:"card cc-stat-card",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.tools.interventions","Interventions")}),s.jsx("div",{className:"cc-stat-value",children:U(n?.interventions.total??0)}),s.jsx("span",{className:"cc-stat-sub",children:r("commandCenter.tools.interventionBreakdown","{{approvals}} approvals · {{steers}} steers",{approvals:U(n?.interventions.approvals??0),steers:U(n?.interventions.userSteers??0)})})]}),s.jsxs("div",{className:"card cc-stat-card",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.tools.sessions","Sessions")}),s.jsx("div",{className:"cc-stat-value",children:U(n?.sessions??0)})]})]})]}),s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.tools.categoriesTitle","Tool categories")}),s.jsx(nt,{data:l,ariaLabel:r("commandCenter.tools.categoriesTitle","Tool categories")})]}),c.length>0?s.jsxs("div",{className:"cc-area-section","data-testid":"cc-tools-pie",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.tools.pieChart","Tool category share")}),s.jsx(Mt,{data:c,ariaLabel:r("commandCenter.tools.pieChart","Tool category share")})]}):null]})}const p$=250,y$=100,Gl=1.8,en=3,g$={width:p$,height:y$};function b$(e,t){if(!Number.isFinite(e)||e<=0)return 0;const r=Number.isFinite(t)&&t>0?t:1;return Math.max(0,Math.min(100,e/r*100))}function vh(e){return Number.isFinite(e)?e:0}function x$(e,t){return!Number.isFinite(e)||!Number.isFinite(t)||e<=0||t<=0?null:{width:Math.max(e,en*2+Gl*2),height:Math.max(t,en*2+Gl*2)}}function j$(e,t,r,n,a){const i=Math.max(0,a.width-en*2),o=Math.max(0,a.height-en*2),l=r<=1?a.width/2:en+t/(r-1)*i,c=b$(e,n);return{x:vh(l),y:vh(en+o*(1-c/100))}}function w$(e,t,r){return e.map((n,a)=>j$(n,a,e.length,t,r))}function C$(e){return e.map(t=>`${t.x},${t.y}`).join(" ")}function k$(e,t){return Number.isFinite(t)&&t!==void 0&&t>0?t:e.reduce((r,n)=>{const a=n.values.reduce((i,o)=>Number.isFinite(o)&&o>i?o:i,0);return a>r?a:r},0)}function hh(e){return x$(e.width,e.height)}function S$(e,t){return Math.abs(e.width-t.width)<.5&&Math.abs(e.height-t.height)<.5}function Ta({series:e,ariaLabel:t,max:r}){const n=f.useRef(null),[a,i]=f.useState(g$),o=k$(e,r);return f.useLayoutEffect(()=>{const l=n.current;if(!l)return;const c=u=>{u&&i(m=>S$(m,u)?m:u)};if(c(hh(l.getBoundingClientRect())),typeof ResizeObserver>"u")return;const d=new ResizeObserver(u=>{const m=u[0];m&&c(hh(m.contentRect))});return d.observe(l),()=>d.disconnect()},[]),s.jsx("svg",{ref:n,className:"cc-line-chart",role:"img","aria-label":t,viewBox:`0 0 ${a.width} ${a.height}`,preserveAspectRatio:"none",children:e.map((l,c)=>{const d=w$(l.values,o,a),u=C$(d);return s.jsxs("g",{className:"cc-line-chart-series","aria-label":l.label,children:[d.length>1?s.jsx("polyline",{className:"cc-line-chart-path",points:u,pathLength:a.width,vectorEffect:"non-scaling-stroke","aria-hidden":"true"}):null,d.map((m,h)=>s.jsx("circle",{className:"cc-line-chart-point",cx:m.x,cy:m.y,r:Gl,vectorEffect:"non-scaling-stroke","aria-hidden":"true"},h))]},c)})})}function N$(e,t){if(!Number.isFinite(e)||e<=0)return 0;const r=Number.isFinite(t)&&t>0?t:1;return Math.max(0,Math.min(100,e/r*100))}function Ot({values:e,ariaLabel:t,max:r}){const n=r??e.reduce((a,i)=>i>a?i:a,0);return s.jsx("div",{className:"cc-sparkline",role:"img","aria-label":t,children:e.map((a,i)=>{const o=N$(a,n);return s.jsx("div",{className:"cc-sparkline-bar",style:{height:`${o}%`},"aria-hidden":"true"},i)})})}const P$=15e3;function A$({range:e,projectId:t}){const{t:r}=se("app"),{data:n,isLoading:a,error:i,reload:o}=Je("/command-center/activity",e,{projectId:t}),l=f.useMemo(()=>n?.daily??[],[n?.daily]),c=f.useMemo(()=>l.map(x=>x.messages),[l]),d=f.useMemo(()=>l.map(x=>x.activeAgents),[l]),u=f.useMemo(()=>l.map(x=>x.activeNodes),[l]),m=f.useMemo(()=>l.map(x=>x.agentRuns),[l]),h=f.useMemo(()=>l.map(x=>x.messages+x.activeAgents+x.activeNodes),[l]),v=f.useMemo(()=>[{label:r("commandCenter.activity.messages","Messages"),values:c},{label:r("commandCenter.activity.activeAgents","Active agents"),values:d},{label:r("commandCenter.activity.agentRuns","Agent runs"),values:m}],[m,d,c,r]),p=cp(e),b=a&&n===null;vn(o,P$,{enabled:!p});const y=n?.agentRuns??{total:0,active:0,completed:0,failed:0},g=f.useMemo(()=>[{label:r("commandCenter.activity.agentRunsActive","Active"),value:y.active},{label:r("commandCenter.activity.agentRunsCompleted","Completed"),value:y.completed},{label:r("commandCenter.activity.agentRunsFailed","Failed"),value:y.failed}].filter(x=>x.value>0),[y.active,y.completed,y.failed,r]),j=!n||n.sessions===0&&n.messages===0&&n.activeNodes===0&&n.activeAgents===0&&y.total===0;return s.jsxs(ft,{testId:"activity",isLoading:b,error:i,isEmpty:j,children:[s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.activity.summaryTitle","Summary")}),s.jsxs("div",{className:"cc-stat-grid",children:[s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-activity-sessions",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.activity.sessions","Sessions")}),s.jsx("div",{className:"cc-stat-value",children:U(n?.sessions??0)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-activity-messages",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.activity.messages","Messages")}),s.jsx("div",{className:"cc-stat-value",children:U(n?.messages??0)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-activity-nodes",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.activity.activeNodes","Active nodes")}),s.jsx("div",{className:"cc-stat-value",children:U(n?.activeNodes??0)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-activity-agents",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.activity.activeAgents","Active agents")}),s.jsx("div",{className:"cc-stat-value",children:U(n?.activeAgents??0)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-activity-agent-runs",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.activity.agentRuns","Agent runs")}),s.jsx("div",{className:"cc-stat-value",children:U(y.total)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-activity-agent-runs-active",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.activity.agentRunsActive","Active")}),s.jsx("div",{className:"cc-stat-value",children:U(y.active)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-activity-agent-runs-completed",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.activity.agentRunsCompleted","Completed")}),s.jsx("div",{className:"cc-stat-value",children:U(y.completed)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-activity-agent-runs-failed",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.activity.agentRunsFailed","Failed")}),s.jsx("div",{className:"cc-stat-value",children:U(y.failed)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-activity-stickiness",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.activity.stickiness","Stickiness")}),s.jsx("div",{className:"cc-stat-value",children:n?`${Math.round(n.stickiness*100)}%`:"—"}),s.jsx("span",{className:"cc-stat-sub",children:r("commandCenter.activity.stickinessHint","DAU / MAU")})]})]})]}),l.length>0?s.jsxs("div",{className:"cc-area-section","data-testid":"cc-activity-line",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.activity.rechartsLine","Activity trend")}),s.jsx(br,{series:v,ariaLabel:r("commandCenter.activity.rechartsLine","Activity trend"),scaleMode:"series"})]}):null,g.length>0?s.jsxs("div",{className:"cc-area-section","data-testid":"cc-activity-pie",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.activity.agentRunOutcomeShare","Agent run outcome share")}),s.jsx(Mt,{data:g,ariaLabel:r("commandCenter.activity.agentRunOutcomeShare","Agent run outcome share")})]}):null,s.jsxs("div",{className:"cc-area-section","data-testid":"cc-activity-line-messages",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.activity.messagesPerDay","Messages / day")}),s.jsx(Ta,{series:[{label:r("commandCenter.activity.messages","Messages"),values:c}],ariaLabel:r("commandCenter.activity.messagesPerDay","Messages / day")})]}),s.jsxs("div",{className:"cc-area-section","data-testid":"cc-activity-line-agents",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.activity.agentsPerDay","Active agents / day")}),s.jsx(Ta,{series:[{label:r("commandCenter.activity.activeAgents","Active agents"),values:d}],ariaLabel:r("commandCenter.activity.agentsPerDay","Active agents / day")})]}),s.jsxs("div",{className:"cc-area-section","data-testid":"cc-activity-line-nodes",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.activity.nodesPerDay","Active nodes / day")}),s.jsx(Ta,{series:[{label:r("commandCenter.activity.activeNodes","Active nodes"),values:u}],ariaLabel:r("commandCenter.activity.nodesPerDay","Active nodes / day")})]}),s.jsxs("div",{className:"cc-area-section","data-testid":"cc-activity-agent-runs-sparkline",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.activity.agentRunsPerDay","Agent runs / day")}),s.jsx(Ot,{values:m,ariaLabel:r("commandCenter.activity.agentRunsPerDay","Agent runs / day")})]}),s.jsxs("div",{className:"cc-area-section","data-testid":"cc-activity-line-throughput",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.activity.throughputPerDay","Throughput / day")}),s.jsx(Ta,{series:[{label:r("commandCenter.activity.throughput","Throughput"),values:h}],ariaLabel:r("commandCenter.activity.throughputPerDay","Throughput / day")})]})]})}const O$={"task:created":{label:"Created",icon:zn,color:"var(--todo)"},"task:moved":{label:"Moved",icon:Uh,color:"var(--in-progress)"},"task:updated":{label:"Updated",icon:La,color:"var(--text-muted)"},"task:merge-worktree-reacquired":{label:"Merge Worktree Reacquired",icon:La,color:"var(--color-info)"},"task:deleted":{label:"Deleted",icon:cj,color:"var(--color-error)"},"task:merged":{label:"Merged",icon:lj,color:"var(--color-success)"},"task:failed":{label:"Failed",icon:Zr,color:"var(--color-error)"},"task:duplicate-warning-overridden":{label:"Duplicate Override",icon:Zr,color:"var(--color-warning)"},"task:auto-archived-ghost-bug":{label:"Auto-Archived (Ghost Bug)",icon:Zr,color:"var(--color-warning)"},"task:auto-archived-duplicate":{label:"Auto-Archived (Duplicate)",icon:tn,color:"var(--text-muted)"},"task:auto-archived-deterministic-duplicate":{label:"Auto-Archived (Deterministic Duplicate)",icon:tn,color:"var(--text-muted)"},"task:auto-archived-near-duplicate":{label:"Auto-Archived (Near-Duplicate)",icon:tn,color:"var(--text-muted)"},"task:near-duplicate-flagged":{label:"Near-Duplicate Flagged",icon:Zr,color:"var(--color-warning)"},"settings:updated":{label:"Settings",icon:La,color:"var(--text-muted)"},"project:isolation-transition":{label:"Isolation",icon:Ph,color:"var(--color-info)"}};function E$(e){const t=oj(e);if(!t){const r=new Date(e);return Number.isFinite(r.getTime())?"Just now":r.toLocaleDateString()}switch(t.bucket){case"just-now":return"Just now";case"minutes":return`${t.count}m ago`;case"hours":return`${t.count}h ago`;case"days":return`${t.count}d ago`;case"weeks":case"older":return t.date.toLocaleDateString()}}function _$(e){return new Date(e).toLocaleString()}function Fx({config:e,details:t,timestamp:r,headerSuffix:n}){const a=e.icon;return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"activity-feed-icon",style:{color:e.color},children:s.jsx(a,{size:16})}),s.jsxs("div",{className:"activity-feed-content",children:[s.jsxs("div",{className:"activity-feed-header",children:[s.jsx("span",{className:"activity-feed-type",children:e.label}),n]}),s.jsx("div",{className:"activity-feed-details",children:t}),s.jsx("div",{className:"activity-feed-meta",children:s.jsx("span",{className:"activity-feed-time",title:_$(r),children:E$(r)})})]})]})}function T$({entry:e,projectName:t}){const r=O$[e.type];return s.jsx("div",{className:"activity-feed-item","data-type":e.type,children:s.jsx(Fx,{config:r,timestamp:e.timestamp,headerSuffix:t?s.jsxs("span",{className:"activity-feed-project-badge",children:[s.jsx(Ph,{size:10}),t]}):void 0,details:s.jsxs(s.Fragment,{children:[e.taskId&&s.jsx("span",{className:"activity-feed-task-id",children:e.taskId}),e.taskTitle&&s.jsx("span",{className:"activity-feed-task-title",title:e.taskTitle,children:e.taskTitle}),s.jsx("span",{className:"activity-feed-description",children:e.details})]})})})}function M$(e,t){if(e.isLoading!==t.isLoading||e.error!==t.error||e.entries.length!==t.entries.length)return!1;for(let r=0;r<e.entries.length;r++){const n=e.entries[r],a=t.entries[r];if(n.id!==a.id||n.timestamp!==a.timestamp||n.type!==a.type||n.details!==a.details||n.taskId!==a.taskId||n.taskTitle!==a.taskTitle)return!1}return!0}function I$({entries:e,isLoading:t=!1,error:r=null,projectNames:n={},emptyMessage:a}){const{t:i}=se("app"),o=a??i("activityFeed.noRecentActivity","No recent activity"),l=f.useCallback(d=>n[d]||d,[n]),c=f.useMemo(()=>{const d=[];let u=null;for(const m of e){const h=new Date(m.timestamp).toLocaleDateString();(!u||u.date!==h)&&(u={date:h,entries:[]},d.push(u)),u.entries.push(m)}return d},[e]);return t?s.jsx("div",{className:"activity-feed activity-feed-loading",children:s.jsx("div",{className:"activity-feed-skeleton",children:[1,2,3].map(d=>s.jsxs("div",{className:"activity-feed-skeleton-item",children:[s.jsx("div",{className:"activity-feed-skeleton-icon"}),s.jsxs("div",{className:"activity-feed-skeleton-content",children:[s.jsx("div",{className:"activity-feed-skeleton-line"}),s.jsx("div",{className:"activity-feed-skeleton-line short"})]})]},d))})}):r?s.jsx("div",{className:"activity-feed activity-feed-error",children:s.jsxs("div",{className:"activity-feed-error-message",children:[s.jsx(Zr,{size:24}),s.jsx("p",{children:r})]})}):e.length===0?s.jsx("div",{className:"activity-feed activity-feed-empty",children:s.jsxs("div",{className:"activity-feed-empty-state",children:[s.jsx(el,{size:32}),s.jsx("p",{children:o}),s.jsx("span",{className:"activity-feed-empty-hint",children:i("activityFeed.emptyHint","Activity will appear here when tasks are created, moved, or completed")})]})}):s.jsx("div",{className:"activity-feed",children:c.map(d=>s.jsxs("div",{className:"activity-feed-group",children:[s.jsxs("div",{className:"activity-feed-group-header",children:[s.jsx("span",{className:"activity-feed-group-date",children:d.date}),s.jsx("span",{className:"activity-feed-group-count",children:i("activityFeed.eventCount",{count:d.entries.length,defaultValue_one:"{{count}} event",defaultValue_other:"{{count}} events"})})]}),s.jsx("div",{className:"activity-feed-list",children:d.entries.map(u=>s.jsx(T$,{entry:u,projectName:l(u.projectId)},u.id))})]},d.date))})}f.memo(I$,M$);const Lu={"task:started":{label:"Task started",icon:Di,color:"var(--in-progress)"},"task:handed-off":{label:"Task handed off",icon:Uh,color:"var(--in-progress)"},"task:completed":{label:"Task completed",icon:el,color:"var(--color-success)"},"agent:state-changed":{label:"Agent state changed",icon:Ah,color:"var(--text-muted)"},"workflow:gate-passed":{label:"Workflow gate passed",icon:el,color:"var(--color-success)"},"workflow:gate-failed":{label:"Workflow gate failed",icon:Zr,color:"var(--color-error)"},"approval:requested":{label:"Approval requested",icon:uj,color:"var(--color-warning)"}},D$={label:"Activity",icon:Ah,color:"var(--text-muted)"},R$=50,L$=3;function $$(e,t){const r=BigInt(e.seq),n=BigInt(t.seq);return r===n?0:r>n?-1:1}function Bx(e,t){const r=new Map;for(const n of e)r.set(n.eventId,n);for(const n of t)r.set(n.eventId,n);return[...r.values()].sort($$)}function F$(e,t){return t===null||BigInt(e)<BigInt(t)}function B$(e){return e===null?{}:{before:e}}function z$(e){return typeof e=="object"&&e!==null&&e.truncated===!0}function K$(e){const{requestedCursor:t,existing:r,page:n,consecutiveNoProgress:a}=e,i=Bx(r,n.events),o=i.length-r.length;if(n.nextCursor===null)return{merged:i,nextCursor:null,hasMore:!1,reason:"end-of-history",consecutiveNoProgress:0};const l=a+1,c=F$(n.nextCursor,t);return(o===0||!c)&&l>=L$?{merged:i,nextCursor:t,hasMore:!1,reason:"attempt-cap",consecutiveNoProgress:l}:o===0?{merged:i,nextCursor:n.nextCursor,hasMore:!0,reason:"no-progress",consecutiveNoProgress:l}:c?{merged:i,nextCursor:n.nextCursor,hasMore:!0,reason:null,consecutiveNoProgress:0}:{merged:i,nextCursor:t,hasMore:!0,reason:"cursor-rewind",consecutiveNoProgress:l}}const V$=5;function U$(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid agent activity response");const t=e;if(!Array.isArray(t.events)||t.nextCursor!==null&&(typeof t.nextCursor!="string"||!/^\d+$/.test(t.nextCursor)))throw new Error("Invalid agent activity response");return{events:t.events.filter(zx),nextCursor:t.nextCursor}}function zx(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e,r=n=>n===null||typeof n=="string";return typeof t.seq=="string"&&/^\d+$/.test(t.seq)&&typeof t.eventId=="string"&&typeof t.projectId=="string"&&typeof t.agentId=="string"&&typeof t.type=="string"&&typeof t.summary=="string"&&typeof t.occurredAt=="string"&&r(t.taskId)&&r(t.fromAgentId)&&r(t.toAgentId)&&(t.metadata===null||typeof t.metadata=="object"&&!Array.isArray(t.metadata))}function q$({projectId:e,filters:t,range:r}){const[n,a]=f.useState([]),i=f.useRef([]),[o,l]=f.useState(!0),[c,d]=f.useState(!1),[u,m]=f.useState(null),[h,v]=f.useState(null),[p,b]=f.useState(!1),[y,g]=f.useState(null),j=f.useRef(0),x=f.useRef(null),C=f.useRef(0),w=f.useRef(0),P=f.useRef(t);P.current=t;const A=JSON.stringify([e,t.agentId,t.taskId,t.type]),S=`${r?.from??""}|${r?.to??""}|${r?.preset??""}`,N=f.useCallback(z=>{i.current=z,a(z)},[]),E=f.useCallback(async(z,D)=>{const V=j.current;if(!e){N([]),l(!1);return}if(!(!D&&(z===null||x.current===z))){D?(l(!0),m(null)):(x.current=z,d(!0));try{const B=await X0({projectId:e,limit:R$,...P.current,...B$(z)}),W=U$(B);if(V!==j.current)return;const K=K$({requestedCursor:z,existing:i.current,page:W,consecutiveNoProgress:C.current});N(K.merged),v(K.nextCursor),b(K.hasMore),g(K.reason),C.current=K.consecutiveNoProgress}catch(B){V===j.current&&m(B instanceof Error?B.message:"Failed to load agent activity")}finally{V===j.current&&(l(!1),d(!1),x.current=null)}}},[N,A,e]),T=f.useCallback(()=>{j.current+=1,x.current=null,C.current=0,w.current=0,v(null),b(!1),g(null),N([]),E(null,!0)},[N,E]);f.useEffect(()=>{T()},[A,T]);const O=f.useCallback(()=>{!p||h===null||E(h,!1)},[p,h,E]);f.useEffect(()=>qa("/api/events",{events:{"agent:activity":D=>{let V;try{V=JSON.parse(D.data)}catch{return}if(z$(V)){T();return}if(!zx(V))return;const B=V,W=P.current;B.projectId!==e||!B.eventId||!B.seq||W.agentId&&B.agentId!==W.agentId||W.taskId&&B.taskId!==W.taskId||W.type&&B.type!==W.type||N(Bx(i.current,[B]))}},onReconnect:T}),[N,e,T]);const I=f.useMemo(()=>{if(!r||!r.from&&!r.to)return n;const z=r.from?Date.parse(r.from):-1/0,D=r.to?Date.parse(r.to):1/0;return Number.isNaN(z)||Number.isNaN(D)?n:n.filter(V=>{const B=Date.parse(V.occurredAt);return Number.isFinite(B)&&B>=z&&B<=D})},[n,r]);return f.useEffect(()=>{w.current=0},[S]),f.useEffect(()=>{if(!r?.from||!p||h===null||w.current>=V$)return;const z=Date.parse(r.from),D=n.at(-1);!Number.isFinite(z)||!D||Date.parse(D.occurredAt)<=z||(w.current+=1,O())},[n,p,O,h,r?.from,S]),{events:n,visibleEvents:I,isLoading:o,isLoadingOlder:c,error:u,hasMore:p,exhaustedReason:y,loadOlder:O,reload:T}}const W$=100,Ho=100,H$=Object.keys(Lu).filter(e=>!il(e));function G$({projectId:e,range:t,onOpenAgent:r,onOpenTask:n}){const{t:a}=se("app"),[i,o]=f.useState("live"),[l,c]=f.useState({}),[d,u]=f.useState(Ho),m=q$({projectId:e,filters:l,range:t});f.useEffect(()=>{u(Ho)},[l.agentId,l.taskId,l.type,t.from,t.to]);const h=f.useMemo(()=>[...new Set(m.events.map(b=>b.agentId).filter(Boolean))].sort(),[m.events]),v=m.visibleEvents.filter(b=>!il(b.type)),p=i==="live"?m.events.filter(b=>!il(b.type)).slice(0,W$):v.slice(0,d);return s.jsxs("section",{className:"cc-agent-activity",children:[s.jsxs("div",{className:"cc-agent-activity-mode",role:"group","aria-label":a("commandCenter.agentActivity.mode","Activity mode"),children:[s.jsx("button",{type:"button",className:"btn btn-sm","aria-pressed":i==="live",onClick:()=>o("live"),children:a("commandCenter.agentActivity.live","Live")}),s.jsx("button",{type:"button",className:"btn btn-sm","aria-pressed":i==="timeline",onClick:()=>o("timeline"),children:a("commandCenter.agentActivity.timeline","Timeline")})]}),i==="timeline"?s.jsxs("div",{className:"cc-agent-activity-filters",children:[s.jsxs("select",{className:"input","aria-label":a("commandCenter.agentActivity.agentFilter","Filter by agent"),value:l.agentId??"",onChange:b=>c(y=>({...y,agentId:b.target.value||void 0})),children:[s.jsx("option",{value:"",children:a("commandCenter.agentActivity.allAgents","All agents")}),h.map(b=>s.jsx("option",{value:b,children:b},b))]}),s.jsx("input",{className:"input","aria-label":a("commandCenter.agentActivity.taskFilter","Filter by task"),value:l.taskId??"",placeholder:a("commandCenter.agentActivity.taskFilter","Filter by task"),onChange:b=>c(y=>({...y,taskId:b.target.value||void 0}))}),s.jsxs("select",{className:"input","aria-label":a("commandCenter.agentActivity.typeFilter","Filter by event type"),value:l.type??"",onChange:b=>c(y=>({...y,type:b.target.value||void 0})),children:[s.jsx("option",{value:"",children:a("commandCenter.agentActivity.allTypes","All event types")}),H$.map(b=>s.jsx("option",{value:b,children:Lu[b].label},b))]}),s.jsx("span",{className:"cc-agent-activity-range-note",children:a("commandCenter.agentActivity.rangeNote","Time range filters loaded events; it is not sent to the server.")})]}):null,s.jsxs(ft,{testId:"agent-activity",isLoading:m.isLoading,error:m.error,isEmpty:!p.length&&!m.hasMore,emptyMessage:a("commandCenter.agentActivity.empty","No agent activity yet."),children:[p.length?s.jsx("div",{className:"cc-agent-activity-list",children:p.map(b=>s.jsx(X$,{event:b,onOpenAgent:r,onOpenTask:n},b.eventId))}):s.jsx("div",{className:"cc-area-empty","data-testid":"cc-area-agent-activity-empty",children:s.jsx("p",{children:a("commandCenter.agentActivity.empty","No agent activity yet.")})}),i==="timeline"&&d<v.length?s.jsx("button",{type:"button",className:"btn",onClick:()=>u(b=>b+Ho),children:a("commandCenter.agentActivity.showMore","Show more loaded activity")}):null,i==="timeline"&&m.hasMore?s.jsx("button",{type:"button",className:"btn",onClick:m.loadOlder,disabled:m.isLoadingOlder,children:m.isLoadingOlder?a("commandCenter.agentActivity.loadingOlder","Loading…"):a("commandCenter.agentActivity.loadOlder","Load older")}):null,i==="timeline"&&!m.hasMore&&m.exhaustedReason?s.jsx("p",{className:"cc-agent-activity-end",children:a("commandCenter.agentActivity.end","End of activity history")}):null]})]})}function X$({event:e,onOpenAgent:t,onOpenTask:r}){const{t:n}=se("app"),a=Lu[e.type]??D$,i={...a,label:n(`commandCenter.agentActivity.eventTypes.${e.type}`,a.label)},o=n("commandCenter.agentActivity.openTask","Open task {{taskId}}",{taskId:e.taskId}),l=n("commandCenter.agentActivity.openAgent","Open agent {{agentId}}",{agentId:e.agentId}),c=s.jsx(Fx,{config:i,timestamp:e.occurredAt,details:s.jsx("span",{className:"activity-feed-description",children:e.summary})});return e.taskId&&r?s.jsxs("div",{className:"cc-agent-activity-target",children:[s.jsx("button",{type:"button",className:"cc-agent-activity-row","aria-label":o,onClick:()=>r(e.taskId),children:c}),t?s.jsx("button",{type:"button",className:"btn btn-sm","aria-label":l,onClick:()=>t(e.agentId),children:e.agentId}):null]}):e.agentId&&t?s.jsx("button",{type:"button",className:"cc-agent-activity-row","aria-label":l,onClick:()=>t(e.agentId),children:c}):s.jsx("div",{className:"cc-agent-activity-row",children:c})}function Y$({range:e,projectId:t}){const{t:r}=se("app"),{confirm:n}=tc(),{data:a,isLoading:i,error:o}=Je("/command-center/productivity",e,{projectId:t}),[l,c]=f.useState(!1),[d,u]=f.useState(null),[m,h]=f.useState(null),v=f.useCallback(async()=>{if(!l){c(!0),h(null),u(null);try{const D=await $u({dryRun:!0});u(D)}catch(D){h(D instanceof Error?D.message:r("commandCenter.productivity.backfillFailed","Failed to backfill historical LOC stats"))}finally{c(!1)}}},[l,r]),p=f.useCallback(async()=>{if(!(l||!await n({title:r("commandCenter.productivity.backfillConfirmTitle","Apply LOC backfill?"),message:r("commandCenter.productivity.backfillConfirmMessage","This will persist diff stats to task_commit_associations for historical commit associations. Review the dry-run counts before applying."),confirmLabel:r("commandCenter.productivity.backfillApply","Apply backfill"),cancelLabel:r("common.cancel","Cancel"),danger:!0}))){c(!0),h(null);try{const V=await $u({dryRun:!1});u(V)}catch(V){h(V instanceof Error?V.message:r("commandCenter.productivity.backfillFailed","Failed to backfill historical LOC stats"))}finally{c(!1)}}},[n,l,r]),b=f.useMemo(()=>(a?.byLanguage??[]).slice(0,12).map(D=>({label:D.language,value:D.count,valueLabel:U(D.count)})),[a?.byLanguage]),y=f.useMemo(()=>(a?.byLanguage??[]).slice(0,12).map(D=>({label:D.language,value:D.count})),[a?.byLanguage]),g=a?.taskDuration??{completedTasks:0,averageMs:null,medianMs:null,p90Ms:null,totalMs:null,unavailable:!0},j=f.useMemo(()=>(a?.taskDurationTrend??[]).filter(D=>!D.unavailable&&D.completedTasks>0&&D.averageMs!==null&&D.medianMs!==null&&Number.isFinite(D.averageMs)&&Number.isFinite(D.medianMs)),[a?.taskDurationTrend]),x=f.useMemo(()=>[{label:r("commandCenter.productivity.averageDuration","Average"),values:j.map(D=>D.averageMs??0)},{label:r("commandCenter.productivity.medianDuration","Median"),values:j.map(D=>D.medianMs??0)}],[r,j]),C=f.useMemo(()=>j.map(D=>D.bucket),[j]),w=j.length>0,P=a?.loc??{value:null,unavailable:!0},A=a?.hoursSaved??{value:null,unavailable:!0},S=!a||a.modifiedFiles===0&&a.commits===0&&a.pullRequests===0&&g.completedTasks===0,N=!a||P.unavailable||P.value===null,E=!a||A.unavailable||A.value===null,T=!a||g.unavailable,O=r("commandCenter.productivity.durationUnavailable","Task duration is unavailable until completed tasks have active execution time recorded"),I=m?"cc-productivity-backfill-status--error":l?"cc-productivity-backfill-status--warning":"",z=(D,V)=>T||D===null?s.jsx("span",{className:"cc-unavailable",title:O,"data-testid":V,children:"—"}):ad(D);return s.jsxs(ft,{testId:"productivity",isLoading:i,error:o,isEmpty:S,children:[s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.productivity.outcomesTitle","Outcomes")}),s.jsxs("div",{className:"cc-stat-grid",children:[s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-productivity-commits",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.productivity.commits","Commits")}),s.jsx("div",{className:"cc-stat-value",children:U(a?.commits??0)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-productivity-prs",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.productivity.pullRequests","Pull requests")}),s.jsx("div",{className:"cc-stat-value",children:U(a?.pullRequests??0)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-productivity-hours-saved",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.productivity.hoursSaved","Human hours saved")}),s.jsx("div",{className:"cc-stat-value",children:E?s.jsx("span",{className:"cc-unavailable",title:r("commandCenter.productivity.hoursSavedUnavailable","Estimated human hours saved is unavailable until commit diff stats exist"),"data-testid":"cc-productivity-hours-saved-unavailable",children:"—"}):U(A.value??0)}),s.jsx("span",{className:"cc-stat-sub",children:r("commandCenter.productivity.hoursSavedEstimate","estimate from lines changed")})]})]})]}),s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.productivity.volumeTitle","Volume (proxy)")}),s.jsxs("div",{className:"cc-stat-grid",children:[s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-productivity-files",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.productivity.modifiedFiles","Files modified")}),s.jsx("div",{className:"cc-stat-value",children:U(a?.modifiedFiles??0)}),s.jsx("span",{className:"cc-stat-sub",children:r("commandCenter.productivity.volumeHint","volume, not outcome")})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-productivity-loc",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.productivity.loc","Lines changed")}),s.jsx("div",{className:"cc-stat-value",children:N?s.jsx("span",{className:"cc-unavailable",title:r("commandCenter.productivity.locUnavailable","LOC is unavailable until commit diff stats are recorded"),"data-testid":"cc-productivity-loc-unavailable",children:"—"}):U(P.value??0)}),s.jsx("span",{className:"cc-stat-sub",children:r("commandCenter.productivity.volumeHint","volume, not outcome")}),s.jsxs("div",{className:"cc-productivity-backfill-actions",children:[s.jsxs("button",{type:"button",className:"btn","data-testid":"cc-productivity-backfill-button",onClick:()=>void v(),disabled:l,children:[s.jsx(Gt,{className:l?"spin":void 0}),s.jsx("span",{children:l?r("commandCenter.productivity.backfillBusy","Checking historical LOC…"):r("commandCenter.productivity.backfillButton","Preview LOC backfill")})]}),d?.dryRun?s.jsx("button",{type:"button",className:"btn","data-testid":"cc-productivity-backfill-apply-button",onClick:()=>void p(),disabled:l,children:r("commandCenter.productivity.backfillApply","Apply backfill")}):null]}),l||d||m?s.jsxs("div",{className:`cc-productivity-backfill-status ${I}`.trim(),"data-testid":"cc-productivity-backfill-result",role:"status",children:[l?s.jsx("span",{children:r("commandCenter.productivity.backfillPending","LOC backfill check is running.")}):null,m?s.jsx("span",{children:m}):null,d?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:r("commandCenter.productivity.backfillResult","Backfill report")}),s.jsx("span",{children:d.dryRun?r("commandCenter.productivity.backfillPreviewLabel","Dry-run preview"):r("commandCenter.productivity.backfillAppliedLabel","Applied")}),s.jsxs("span",{children:[r("commandCenter.productivity.backfillScannedRows","Scanned rows"),": ",d.scannedRows]}),s.jsxs("span",{children:[r("commandCenter.productivity.backfillDistinctCommits","Distinct commits"),": ",d.distinctCommits]}),s.jsxs("span",{children:[r("commandCenter.productivity.backfillUpdatedRows","Updated rows"),": ",d.updatedRows]}),s.jsxs("span",{children:[r("commandCenter.productivity.backfillSkippedUnavailableCommits","Skipped unavailable commits"),": ",d.skippedUnavailableCommits]}),s.jsxs("span",{children:[r("commandCenter.productivity.backfillSkippedInvalidShas","Skipped invalid SHAs"),": ",d.skippedInvalidShas]})]}):null]}):null]})]})]}),s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.productivity.durationTitle","Task duration")}),s.jsxs("div",{className:"cc-stat-grid",children:[s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-productivity-duration-completed",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.productivity.completedTasks","Completed tasks")}),s.jsx("div",{className:"cc-stat-value",children:U(g.completedTasks)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-productivity-duration-avg",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.productivity.averageDuration","Average")}),s.jsx("div",{className:"cc-stat-value",children:z(g.averageMs,"cc-productivity-duration-avg-unavailable")})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-productivity-duration-median",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.productivity.medianDuration","Median")}),s.jsx("div",{className:"cc-stat-value",children:z(g.medianMs,"cc-productivity-duration-median-unavailable")})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-productivity-duration-p90",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.productivity.p90Duration","P90")}),s.jsx("div",{className:"cc-stat-value",children:z(g.p90Ms,"cc-productivity-duration-p90-unavailable")})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-productivity-duration-total",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.productivity.totalDuration","Total active")}),s.jsx("div",{className:"cc-stat-value",children:z(g.totalMs,"cc-productivity-duration-total-unavailable")})]})]})]}),w?s.jsxs("div",{className:"cc-area-section","data-testid":"cc-productivity-duration-trend",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.productivity.durationTrendTitle","Task duration over time")}),s.jsx(br,{series:x,ariaLabel:r("commandCenter.productivity.durationTrendTitle","Task duration over time"),xAxisLabels:C,valueFormatter:ad})]}):null,s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.productivity.byLanguage","Files by language")}),s.jsx(nt,{data:b,ariaLabel:r("commandCenter.productivity.byLanguage","Files by language")})]}),y.length>0?s.jsxs("div",{className:"cc-area-section","data-testid":"cc-productivity-pie",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.productivity.languagePie","Language share")}),s.jsx(Mt,{data:y,ariaLabel:r("commandCenter.productivity.languagePie","Language share")})]}):null]})}function Z$({projectId:e,addToast:t=()=>{}}){const{t:r}=se("app"),{artifacts:n,loading:a,error:i}=dj({projectId:e}),[o,l]=f.useState(()=>typeof window<"u"&&window.matchMedia?.("(max-width: 768px)").matches===!0),c=f.useMemo(()=>n.filter(u=>!!u.taskId&&fj(u)),[n]),d=f.useMemo(()=>c.map(({taskId:u,taskTitle:m,...h})=>h),[c]);return f.useEffect(()=>{const u=typeof window>"u"?void 0:window.matchMedia?.("(max-width: 768px)");if(!u)return;const m=()=>l(u.matches);return m(),u.addEventListener("change",m),()=>u.removeEventListener("change",m)},[]),s.jsx(ft,{testId:"review-artifacts",isLoading:a,error:i,isEmpty:c.length===0,emptyMessage:r("commandCenter.reviewArtifacts.empty","No review artifacts are available yet."),children:s.jsxs("section",{"aria-label":r("commandCenter.reviewArtifacts.title","Review artifacts"),children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.reviewArtifacts.title","Review artifacts")}),s.jsx(mj,{artifacts:d,projectId:e,isMobile:o,addToast:t,onOpenTask:()=>{}})]})})}function J$(e){const t=URL.createObjectURL(new Blob([JSON.stringify(e,null,2)],{type:"application/json"})),r=document.createElement("a");r.href=t,r.download="fusion-org-bundle.json",r.click(),URL.revokeObjectURL(t)}function Q$({projectId:e,onSettingsRefresh:t}){const{t:r}=se("app"),{confirm:n}=tc(),[a,i]=f.useState("idle"),[o,l]=f.useState("idle"),[c,d]=f.useState(""),[u,m]=f.useState(null),[h,v]=f.useState(null),[p,b]=f.useState(null),y=f.useRef(0),g=async()=>{i("working");try{const P=await fr(mr("/org/export",e),{method:"POST"});J$(P.bundle),i("success")}catch{i("error")}},j=()=>{try{const P=JSON.parse(c);if(!P||typeof P!="object"||Array.isArray(P))throw new Error("invalid");return P}catch{return m(r("commandCenter.portability.import.invalid","Paste a valid org bundle JSON document")),l("error"),null}},x=async()=>{const P=j();if(!P)return;const A=y.current;l("previewing"),m(null);try{const S=await fr(mr("/org/import",e),{method:"POST",body:JSON.stringify({bundle:P,dryRun:!0})});if(y.current!==A)return;v(S.result),b(P),l("previewed")}catch(S){if(y.current!==A)return;m(S instanceof Error?S.message:r("commandCenter.portability.import.error","Unable to preview import")),l("error")}},C=async()=>{if(!(!p||!await n({title:r("commandCenter.portability.import.confirmTitle","Import organization bundle?"),message:r("commandCenter.portability.import.confirmMessage","This applies the previewed configuration to this project."),confirmLabel:r("commandCenter.portability.import.confirmApply","Import bundle"),cancelLabel:r("actions.cancel","Cancel")}))){l("importing");try{await fr(mr("/org/import",e),{method:"POST",body:JSON.stringify({bundle:p,dryRun:!1})}),await t(),l("success")}catch(A){m(A instanceof Error?A.message:r("commandCenter.portability.import.error","Unable to import bundle")),l("error")}}},w=a==="working"?r("commandCenter.portability.export.working","Exporting…"):r("commandCenter.portability.export.action","Export org bundle");return s.jsx(s.Fragment,{children:s.jsxs("section",{className:"card cc-controls-card cc-portability-card","data-testid":"cc-controls-org-portability",children:[s.jsxs("div",{className:"cc-controls-card-header",children:[s.jsxs("div",{children:[s.jsx("h3",{children:r("commandCenter.portability.title","Org export / import")}),s.jsx("p",{children:r("commandCenter.portability.description","Download or preview a secret-scrubbed organization bundle.")})]}),s.jsx("span",{className:`cc-controls-save-state cc-controls-save-state--${a}`,"aria-live":"polite",children:a==="success"?r("commandCenter.portability.export.success","Export ready"):a==="error"?r("commandCenter.portability.export.error","Export failed"):r("commandCenter.controls.status.ready","Ready")})]}),s.jsxs("div",{className:"cc-portability-actions",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary cc-controls-action",onClick:()=>void g(),disabled:a==="working",children:[s.jsx(Ri,{size:16,"aria-hidden":"true"}),w]}),s.jsx("label",{className:"cc-portability-import-label",htmlFor:"cc-org-bundle",children:r("commandCenter.portability.import.label","Org bundle JSON")}),s.jsx("textarea",{id:"cc-org-bundle",className:"input cc-portability-import-input",value:c,onChange:P=>{y.current+=1,d(P.target.value),v(null),b(null),m(null),l("idle")},placeholder:r("commandCenter.portability.import.placeholder","Paste a secret-scrubbed org bundle")}),s.jsxs("div",{className:"cc-portability-actions",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary cc-controls-action",onClick:()=>void x(),disabled:!c||o==="previewing",children:[s.jsx(uc,{size:16,"aria-hidden":"true"}),o==="previewing"?r("commandCenter.portability.import.previewing","Previewing…"):r("commandCenter.portability.import.preview","Preview import")]}),s.jsx("button",{type:"button",className:"btn cc-controls-action",onClick:()=>void C(),disabled:o!=="previewed"&&o!=="success",children:o==="importing"?r("commandCenter.portability.import.importing","Importing…"):r("commandCenter.portability.import.apply","Apply import")})]})]}),h?s.jsx("p",{className:"cc-controls-muted","data-testid":"cc-org-import-preview",children:r("commandCenter.portability.import.previewReady","Preview ready. Confirm to apply this bundle.")}):null,u?s.jsx("p",{className:"cc-controls-error",role:"alert",children:u}):null]})})}const e2=15e3,t2=1e4,r2=4,Go=[.1,.25,.5,1,2,3,5,10];function ph(e){return e.usd??-1}function _i(e,t){return e.agentName??e.agentId??t}function n2(e){switch(e){case"running":return"status-dot status-dot--connecting";case"active":case"idle":return"status-dot status-dot--online";case"error":case"failed":return"status-dot status-dot--error";case"starting":case"pending":return"status-dot status-dot--pending";default:return"status-dot status-dot--pending"}}function a2(e,t,r,n){const a=[...e];return a.sort((i,o)=>{let l=0;return t==="agent"?l=_i(i,n).localeCompare(_i(o,n)):t==="tokens"?l=i.tokens.totalTokens-o.tokens.totalTokens:t==="cost"?l=ph(i.cost)-ph(o.cost):t==="filesChanged"?l=i.filesChanged-o.filesChanged:t==="tasksCompleted"?l=i.tasksCompleted-o.tasksCompleted:l=i.tasksInProgress-o.tasksInProgress,l===0&&(l=i.agentId.localeCompare(o.agentId)),l*r}),a}function yh(e,t,r){return[...e].sort((n,a)=>t(a)-t(n)||n.agentId.localeCompare(a.agentId)).slice(0,12).map(n=>{const a=t(n);return{label:_i(n,r),value:a,valueLabel:U(a)}})}function i2(e,t){if(!e)return t;const r=new Date(e);return Number.isNaN(r.getTime())?t:r.toLocaleString()}function s2({paused:e,label:t}){return s.jsxs("span",{className:"cc-team-status-pill",children:[s.jsx("span",{className:`status-dot ${e?"status-dot--pending":"status-dot--online"}`,"aria-hidden":"true"}),s.jsx("span",{children:t})]})}function Kx({node:e}){const t=e.children.length>0;return s.jsxs("li",{className:"cc-team-org-item",children:[s.jsx("div",{className:"cc-team-org-card",children:s.jsxs("div",{className:"cc-team-org-card-header",children:[s.jsx("span",{className:"cc-team-org-avatar",children:s.jsx(gj,{agent:e.agent,size:20})}),s.jsx("span",{className:"cc-team-org-name",children:e.agent.name}),s.jsx("span",{className:"cc-team-org-badge",children:e.agent.state})]})}),t?s.jsx("ul",{className:"cc-team-org-children",children:e.children.map(r=>s.jsx(Kx,{node:r},r.agent.id))}):null]})}function o2({range:e,projectId:t,addToast:r}){const{t:n}=se("app"),{globalPaused:a,enginePaused:i,toggleEnginePause:o,refresh:l}=Oh(t),[c,d]=f.useState(1),[u,m]=f.useState(!1),[h,v]=f.useState({status:"loading",data:null,error:null}),[p,b]=f.useState({status:"loading",data:null,error:null}),y=f.useRef(null),g=f.useRef(!0);f.useEffect(()=>(g.current=!0,()=>{g.current=!1,y.current&&clearTimeout(y.current)}),[]);const j=f.useRef(null),x=f.useRef(null),C=f.useRef(!1),[w,P]=f.useState(!1),[A,S]=f.useState(0),{data:N,isLoading:E,error:T}=Je("/command-center/team",e,{pollMs:e2,projectId:t});f.useEffect(()=>{let k=!1;return v({status:"loading",data:null,error:null}),(async()=>{try{const $=await vj(t);k||v({status:"loaded",data:$,error:null})}catch($){k||v({status:"error",data:null,error:$ instanceof Error?$.message:n("commandCenter.controls.orgChart.error","Unable to load org chart")})}})(),()=>{k=!0}},[t,n]),f.useEffect(()=>{const k=j.current;if(!k)return;const $=()=>{S(k.clientWidth)};$();const de=typeof ResizeObserver<"u"?new ResizeObserver($):null;return de?.observe(k),window.addEventListener("resize",$),()=>{de?.disconnect(),window.removeEventListener("resize",$)}},[h.status]),f.useEffect(()=>{let k=!1,$;const de=async()=>{try{const Le=await yj(t);k||b({status:"loaded",data:Le,error:null})}catch(Le){k||b({status:"error",data:null,error:Le instanceof Error?Le.message:n("commandCenter.controls.status.error","Unable to load live scheduler status")})}finally{k||($=setTimeout(de,t2))}};return b({status:"loading",data:null,error:null}),de(),()=>{k=!0,$&&clearTimeout($)}},[t,n]),f.useEffect(()=>{let k=!1;return Eh(t).then($=>{k||d($.heartbeatMultiplier??1)}).catch(()=>{}),()=>{k=!0}},[t]);const O=f.useCallback(k=>{const $=Number.isFinite(k)&&k>0?k:1;d($),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{y.current=null,g.current&&m(!0),(async()=>{try{await _h({heartbeatMultiplier:$},t),g.current&&r?.(n("agents.heartbeatSpeedSet","Heartbeat speed set to ×{{value}}",{value:$.toFixed(1)}),"success")}catch(de){g.current&&r?.(n("agents.heartbeatSpeedSaveFailed","Failed to save heartbeat multiplier: {{error}}",{error:hj(de)}),"error")}finally{g.current&&m(!1)}})()},300)},[t,r,n]),I=f.useMemo(()=>N?.agents??[],[N?.agents]),z=n("commandCenter.team.unknownAgent","(unknown agent)"),D=n("commandCenter.team.unknownRole","Unknown role"),V=n("commandCenter.team.noChartData","No non-zero values for this chart yet."),[B,W]=f.useState("tokens"),[K,te]=f.useState(-1),G=f.useMemo(()=>I.map(k=>k.agentId).join(" "),[I]),M=f.useRef(null);f.useEffect(()=>{if(M.current===null){M.current=G;return}M.current!==G&&(M.current=G,W("tokens"),te(-1))},[G]);const q=f.useMemo(()=>a2(I,B,K,z),[I,K,B,z]),H=f.useMemo(()=>yh(I,k=>k.tokens.totalTokens,z),[I,z]),re=f.useMemo(()=>H.map(k=>({label:k.label,value:k.value})),[H]),ae=f.useMemo(()=>yh(I,k=>k.tasksCompleted,z),[I,z]),ye=H.some(k=>k.value>0),oe=ae.some(k=>k.value>0),He=f.useMemo(()=>I.flatMap(k=>[k.tokens.totalTokens,k.filesChanged,k.tasksCompleted]),[I]);function J(k){k===B?te($=>$===1?-1:1):(W(k),te(k==="agent"?1:-1))}function Ce(k){return k!==B?null:s.jsx("span",{className:"cc-sort-caret",children:K===1?"▲":"▼"})}const Re=f.useCallback(k=>{const $=x.current;!$||$.pointerId!==k.pointerId||(k.currentTarget.hasPointerCapture?.(k.pointerId)&&k.currentTarget.releasePointerCapture?.(k.pointerId),x.current=null,P(!1))},[]),L=f.useCallback(k=>{if(k.pointerType==="touch"||k.button!==0)return;const $=k.currentTarget;C.current=!1,x.current={pointerId:k.pointerId,startX:k.clientX,startY:k.clientY,startScrollLeft:$.scrollLeft,startScrollTop:$.scrollTop,isPanning:!1},$.setPointerCapture?.(k.pointerId)},[]),Y=f.useCallback(k=>{const $=x.current;if(!$||$.pointerId!==k.pointerId)return;const de=k.clientX-$.startX,Le=k.clientY-$.startY;if(!$.isPanning&&Math.hypot(de,Le)<r2)return;$.isPanning||($.isPanning=!0,C.current=!0,P(!0)),k.preventDefault();const Nt=k.currentTarget;Nt.scrollLeft=$.startScrollLeft-de,Nt.scrollTop=$.startScrollTop-Le},[]),ne=f.useCallback(k=>{C.current&&(C.current=!1,k.preventDefault(),k.stopPropagation())},[]),Ne=f.useMemo(()=>h.status!=="loaded"||A<=0&&h.data.length>1?"vertical":Y0({tree:h.data,availableWidth:A,preference:"auto"}),[A,h]),Q=p.data?.globalPause??a,le=p.data?.enginePaused??i,Oe=i2(p.data?.lastActivityAt,n("commandCenter.controls.status.noActivity","No recent activity"));return s.jsxs("div",{className:"cc-team-area",children:[s.jsxs("div",{className:"cc-team-ops-grid","data-testid":"cc-team-ops",children:[s.jsxs("section",{className:"card cc-team-ops-card cc-team-ops-card--org","data-testid":"cc-team-org-chart",children:[s.jsx("div",{className:"cc-team-ops-card-header",children:s.jsx("div",{children:s.jsx("h3",{children:n("commandCenter.controls.orgChart.title","Agent org chart")})})}),s.jsx("div",{className:`cc-team-org-scroll${w?" is-dragging":""}`,"data-layout":Ne,ref:j,"aria-live":"polite",onPointerDown:L,onPointerMove:Y,onPointerUp:Re,onPointerCancel:Re,onPointerLeave:Re,onClickCapture:ne,children:h.status==="loading"?s.jsx("p",{className:"cc-team-muted",children:s.jsx(rc,{label:n("commandCenter.controls.orgChart.loading","Loading org chart…")})}):h.status==="error"?s.jsx("p",{className:"cc-team-error",role:"alert",children:h.error}):h.data.length===0?s.jsx("p",{className:"cc-team-muted",children:n("commandCenter.controls.orgChart.empty","No agents are reporting in yet.")}):s.jsx("ul",{className:"cc-team-org-roots",children:h.data.map(k=>s.jsx(Kx,{node:k},k.agent.id))})})]}),s.jsxs("section",{className:"card cc-team-ops-card cc-team-ops-card--heartbeat","data-testid":"cc-team-heartbeat",children:[s.jsxs("div",{className:"cc-team-ops-card-header",children:[s.jsxs("div",{children:[s.jsx("h3",{children:n("commandCenter.controls.heartbeat.title","Heartbeat control")}),s.jsx("p",{children:n("commandCenter.controls.heartbeat.description","Pause or resume the scheduling heartbeat.")})]}),s.jsx(s2,{paused:le,label:le?n("commandCenter.controls.status.paused","Paused"):n("commandCenter.controls.status.running","Running")})]}),s.jsxs("dl",{className:"cc-team-facts",children:[s.jsxs("div",{children:[s.jsx("dt",{children:n("commandCenter.controls.status.lastActivity","Last activity")}),s.jsx("dd",{children:p.status==="loading"?n("commandCenter.controls.status.loading","Loading…"):Oe})]}),s.jsxs("div",{children:[s.jsx("dt",{children:n("commandCenter.controls.status.maxConcurrent","Max concurrent")}),s.jsx("dd",{children:p.data?.maxConcurrent??"—"})]})]}),p.status==="error"?s.jsx("p",{className:"cc-team-error",role:"alert",children:p.error}):null,s.jsxs("button",{type:"button",className:"btn btn-secondary cc-team-action",onClick:()=>void o(),disabled:Q,children:[le?s.jsx(Di,{size:16,"aria-hidden":"true"}):s.jsx(pj,{size:16,"aria-hidden":"true"}),s.jsx("span",{children:le?n("commandCenter.controls.heartbeat.resume","Resume heartbeat"):n("commandCenter.controls.heartbeat.pause","Pause heartbeat")})]}),Q?s.jsx("p",{className:"cc-team-muted",children:n("commandCenter.controls.heartbeat.disabledByStop","Start the AI engine before resuming the heartbeat.")}):null,s.jsxs("div",{className:"cc-team-heartbeat-multiplier heartbeat-multiplier-group",children:[s.jsxs("div",{className:"heartbeat-multiplier-controls",children:[s.jsx("label",{htmlFor:"ccHeartbeatMultiplier",className:"heartbeat-multiplier-label",children:n("agents.heartbeatSpeed","Heartbeat Speed")}),s.jsx("input",{id:"ccHeartbeatMultiplier",className:"heartbeat-multiplier-slider touch-target",type:"range",min:.1,max:10,step:.1,value:c,onChange:k=>{const $=Number(k.target.value);O(Number.isFinite($)&&$>0?$:1)},disabled:u}),s.jsxs("span",{className:"heartbeat-multiplier-value",children:["×",c.toFixed(1)]}),s.jsx("select",{className:"heartbeat-multiplier-preset",value:String(Go.reduce((k,$)=>Math.abs($-c)<Math.abs(k-c)?$:k,Go[0])),onChange:k=>{const $=Number(k.target.value);O(Number.isFinite($)&&$>0?$:1)},disabled:u,"aria-label":n("agents.heartbeatSpeedPreset","Heartbeat speed preset"),children:Go.map(k=>s.jsxs("option",{value:String(k),children:["×",k]},k))})]}),s.jsx("small",{className:"text-secondary",children:n("agents.heartbeatSpeedHint","Scales all agent heartbeat intervals. ×0.5 = twice as fast, ×2.0 = twice as slow. Default: ×1.0")})]})]})]}),s.jsx(Q$,{projectId:t,onSettingsRefresh:l}),s.jsxs(ft,{testId:"team",isLoading:E,error:T,isEmpty:!N||N.agents.length===0,emptyMessage:n("commandCenter.team.empty","No agents have reported team analytics yet."),children:[s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:n("commandCenter.team.totalsTitle","Team totals")}),s.jsxs("div",{className:"cc-stat-grid",children:[s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-team-total-tokens",children:[s.jsx("div",{className:"cc-stat-label",children:n("commandCenter.team.totalTokens","Total tokens")}),s.jsx("div",{className:"cc-stat-value",children:U(N?.totals.tokens.totalTokens??0)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-team-total-cost",children:[s.jsx("div",{className:"cc-stat-label",children:n("commandCenter.team.totalCost","Estimated cost")}),s.jsx("div",{className:"cc-stat-value",children:N?Tr(N.totals.cost.usd,N.totals.cost.unavailable):"—"})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-team-total-files",children:[s.jsx("div",{className:"cc-stat-label",children:n("commandCenter.team.filesChanged","Files changed")}),s.jsx("div",{className:"cc-stat-value",children:U(N?.totals.filesChanged??0)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-team-total-completed",children:[s.jsx("div",{className:"cc-stat-label",children:n("commandCenter.team.tasksCompleted","Tasks done")}),s.jsx("div",{className:"cc-stat-value",children:U(N?.totals.tasksCompleted??0)})]})]})]}),s.jsxs("div",{className:"cc-area-section cc-team-chart-grid",children:[ye?s.jsxs("div",{className:"cc-team-chart-panel","data-testid":"cc-team-pie",children:[s.jsx("h3",{className:"cc-area-section-title",children:n("commandCenter.team.tokenShareByAgent","Token share by agent")}),s.jsx(Mt,{data:re,ariaLabel:n("commandCenter.team.tokenShareByAgent","Token share by agent")})]}):null,s.jsxs("div",{className:"cc-team-chart-panel","data-testid":"cc-team-tokens-chart",children:[s.jsx("h3",{className:"cc-area-section-title",children:n("commandCenter.team.tokensByAgent","Tokens by agent")}),ye?s.jsx(nt,{data:H,ariaLabel:n("commandCenter.team.tokensByAgent","Tokens by agent")}):s.jsx("p",{className:"cc-muted-hint",children:V})]}),s.jsxs("div",{className:"cc-team-chart-panel","data-testid":"cc-team-completed-chart",children:[s.jsx("h3",{className:"cc-area-section-title",children:n("commandCenter.team.completedByAgent","Tasks done by agent")}),oe?s.jsx(nt,{data:ae,ariaLabel:n("commandCenter.team.completedByAgent","Tasks done by agent")}):s.jsx("p",{className:"cc-muted-hint",children:V})]}),s.jsxs("div",{className:"cc-team-chart-panel cc-team-spark-panel","data-testid":"cc-team-spread-chart",children:[s.jsx("h3",{className:"cc-area-section-title",children:n("commandCenter.team.spread","Team spread")}),s.jsx(Ot,{values:He,ariaLabel:n("commandCenter.team.spread","Team spread")})]})]}),s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:n("commandCenter.team.tableTitle","Per-agent breakdown")}),s.jsx("div",{className:"cc-table-wrap",children:s.jsxs("table",{className:"cc-table","data-testid":"cc-team-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsxs("th",{className:"cc-sortable",onClick:()=>J("agent"),"data-testid":"cc-team-sort-agent",children:[n("commandCenter.team.agent","Agent"),Ce("agent")]}),s.jsxs("th",{className:"cc-sortable",onClick:()=>J("tokens"),"data-testid":"cc-team-sort-tokens",children:[n("commandCenter.team.tokens","Tokens"),Ce("tokens")]}),s.jsxs("th",{className:"cc-sortable",onClick:()=>J("cost"),"data-testid":"cc-team-sort-cost",children:[n("commandCenter.team.cost","Cost"),Ce("cost")]}),s.jsxs("th",{className:"cc-sortable",onClick:()=>J("filesChanged"),"data-testid":"cc-team-sort-files",children:[n("commandCenter.team.files","Files changed"),Ce("filesChanged")]}),s.jsxs("th",{className:"cc-sortable",onClick:()=>J("tasksCompleted"),"data-testid":"cc-team-sort-completed",children:[n("commandCenter.team.done","Tasks done"),Ce("tasksCompleted")]}),s.jsxs("th",{className:"cc-sortable",onClick:()=>J("tasksInProgress"),"data-testid":"cc-team-sort-progress",children:[n("commandCenter.team.inProgress","In progress"),Ce("tasksInProgress")]})]})}),s.jsx("tbody",{children:q.map(k=>s.jsxs("tr",{"data-testid":`cc-team-row-${k.agentId}`,children:[s.jsx("td",{children:s.jsxs("span",{className:"cc-team-agent-cell",children:[s.jsx("span",{className:n2(k.state),"aria-label":n("commandCenter.team.state","Agent state: {{state}}",{state:k.state??n("commandCenter.team.unknownState","unknown")})}),s.jsxs("span",{children:[s.jsx("span",{className:"cc-team-agent-name",children:_i(k,z)}),s.jsx("span",{className:"cc-team-agent-role",children:k.role??D})]})]})}),s.jsx("td",{children:U(k.tokens.totalTokens)}),s.jsx("td",{children:Tr(k.cost.usd,k.cost.unavailable)}),s.jsx("td",{children:U(k.filesChanged)}),s.jsx("td",{children:U(k.tasksCompleted)}),s.jsx("td",{children:U(k.tasksInProgress)})]},k.agentId))})]})})]})]})]})}function Vx(e,t){return e.workflowName||e.workflowId||t}function l2(e,t,r,n){const a=[...e];return a.sort((i,o)=>{let l=0;return l=i.tokens.totalTokens-o.tokens.totalTokens,l===0&&(l=i.workflowId.localeCompare(o.workflowId)),l*r}),a}function gh(e,t,r){return[...e].sort((n,a)=>t(a)-t(n)||n.workflowId.localeCompare(a.workflowId)).slice(0,12).map(n=>{const a=t(n);return{label:Vx(n,r),value:a,valueLabel:U(a)}})}function c2({range:e,projectId:t}){const{t:r}=se("app"),{data:n,isLoading:a,error:i}=Je("/command-center/workflows",e,{projectId:t}),o=r("commandCenter.workflows.unknownWorkflow","(unknown workflow)"),l=r("commandCenter.workflows.noChartData","No non-zero values for this chart yet."),c=n?.workflows??[],d=l2(c,"tokens",-1),u=gh(c,p=>p.tokens.totalTokens,o),m=gh(c,p=>p.tasksCompleted,o),h=u.some(p=>p.value>0),v=m.some(p=>p.value>0);return s.jsxs(ft,{testId:"workflows",isLoading:a,error:i,isEmpty:!n||n.workflows.length===0,emptyMessage:r("commandCenter.workflows.empty","No workflow analytics have been recorded for this range yet."),children:[s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.workflows.totalsTitle","Workflow totals")}),s.jsxs("div",{className:"cc-stat-grid",children:[s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-workflows-total-tokens",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.workflows.totalTokens","Total tokens")}),s.jsx("div",{className:"cc-stat-value",children:U(n?.totals.tokens.totalTokens??0)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-workflows-total-cost",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.workflows.totalCost","Estimated cost")}),s.jsx("div",{className:"cc-stat-value",children:n?Tr(n.totals.cost.usd,n.totals.cost.unavailable):"—"})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-workflows-total-files",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.workflows.filesChanged","Files changed")}),s.jsx("div",{className:"cc-stat-value",children:U(n?.totals.filesChanged??0)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-workflows-total-completed",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.workflows.tasksCompleted","Tasks done")}),s.jsx("div",{className:"cc-stat-value",children:U(n?.totals.tasksCompleted??0)})]})]})]}),s.jsxs("div",{className:"cc-area-section cc-team-chart-grid",children:[s.jsxs("div",{className:"cc-team-chart-panel","data-testid":"cc-workflows-tokens-chart",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.workflows.tokensByWorkflow","Tokens by workflow")}),h?s.jsx(nt,{data:u,ariaLabel:r("commandCenter.workflows.tokensByWorkflow","Tokens by workflow")}):s.jsx("p",{className:"cc-muted-hint",children:l})]}),s.jsxs("div",{className:"cc-team-chart-panel","data-testid":"cc-workflows-completed-chart",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.workflows.completedByWorkflow","Tasks done by workflow")}),v?s.jsx(nt,{data:m,ariaLabel:r("commandCenter.workflows.completedByWorkflow","Tasks done by workflow")}):s.jsx("p",{className:"cc-muted-hint",children:l})]})]}),s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.workflows.tableTitle","Per-workflow breakdown")}),s.jsx("div",{className:"cc-table-wrap",children:s.jsxs("table",{className:"cc-table","data-testid":"cc-workflows-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:r("commandCenter.workflows.workflow","Workflow")}),s.jsx("th",{children:r("commandCenter.workflows.tokens","Tokens")}),s.jsx("th",{children:r("commandCenter.workflows.cost","Cost")}),s.jsx("th",{children:r("commandCenter.workflows.files","Files changed")}),s.jsx("th",{children:r("commandCenter.workflows.done","Tasks done")}),s.jsx("th",{children:r("commandCenter.workflows.inProgress","In progress")}),s.jsx("th",{children:r("commandCenter.workflows.inReview","In review")})]})}),s.jsx("tbody",{children:d.map(p=>s.jsxs("tr",{"data-testid":`cc-workflows-row-${p.workflowId}`,children:[s.jsx("td",{children:s.jsxs("span",{className:"cc-team-agent-cell",children:[s.jsx(bj,{workflowId:p.workflowId,icon:p.workflowIcon,decorative:!0}),s.jsxs("span",{children:[s.jsx("span",{className:"cc-team-agent-name",children:Vx(p,o)}),s.jsx("span",{className:"cc-team-agent-role",children:p.workflowId})]})]})}),s.jsx("td",{children:U(p.tokens.totalTokens)}),s.jsx("td",{children:Tr(p.cost.usd,p.cost.unavailable)}),s.jsx("td",{children:U(p.filesChanged)}),s.jsx("td",{children:U(p.tasksCompleted)}),s.jsx("td",{children:U(p.tasksInProgress)}),s.jsx("td",{children:U(p.tasksInReview)})]},p.workflowId))})]})})]})]})}function u2({range:e,projectId:t}){const{t:r}=se("app"),{data:n,isLoading:a,error:i}=Je("/command-center/tokens?groupBy=model&granularity=day",e,{projectId:t}),{data:o,isLoading:l}=Je("/command-center/plugin-activations",e,{projectId:t}),c=f.useMemo(()=>(n?.groups??[]).filter(j=>(j.key??"").trim().length>0),[n?.groups]),d=c.length,u=f.useMemo(()=>[...c].sort((j,x)=>x.nTasks-j.nTasks||(j.key??"").localeCompare(x.key??"")).slice(0,12).map(j=>({label:j.key??r("commandCenter.tokens.unknownModel","(unknown)"),value:j.nTasks,valueLabel:U(j.nTasks),iconProvider:ec(j.key??"")})),[c,r]),m=f.useMemo(()=>u.map(j=>({label:j.label,value:j.value})),[u]),h=f.useMemo(()=>[{label:r("commandCenter.ecosystem.tokenTrendSeries","Tokens"),values:(n?.series??[]).map(j=>j.totalTokens)},{label:r("commandCenter.ecosystem.taskTrendSeries","Tasks"),values:(n?.series??[]).map(j=>j.nTasks)}],[n?.series,r]),v=m.some(j=>j.value>0),p=(n?.series??[]).length>0,b=o?.unavailable===!1,y=(!n||d===0)&&!b,g=a||l&&!n;return s.jsxs(ft,{testId:"ecosystem",isLoading:g,error:i,isEmpty:y,emptyMessage:r("commandCenter.ecosystem.empty","No models or plugins active in the selected range."),children:[s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.ecosystem.breadthTitle","Ecosystem breadth")}),s.jsxs("div",{className:"cc-stat-grid",children:[s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-ecosystem-unique-models",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.ecosystem.uniqueModels","Active models")}),s.jsx("div",{className:"cc-stat-value",children:U(d)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-ecosystem-plugins",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.ecosystem.plugins","Plugin activations")}),s.jsx("div",{className:"cc-stat-value",children:b?s.jsx("span",{"data-testid":"cc-ecosystem-plugins-value",children:U(o?.activations??0)}):s.jsx("span",{className:"cc-unavailable",title:r("commandCenter.ecosystem.pluginsUnavailable","Plugin-activation metrics are not yet recorded"),"data-testid":"cc-ecosystem-plugins-unavailable",children:"—"})})]})]})]}),v?s.jsxs("div",{className:"cc-area-section","data-testid":"cc-ecosystem-pie",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.ecosystem.modelShareTitle","Task share by model")}),s.jsx(Mt,{data:m,ariaLabel:r("commandCenter.ecosystem.modelShareTitle","Task share by model")})]}):null,p?s.jsxs("div",{className:"cc-area-section","data-testid":"cc-ecosystem-line",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.ecosystem.trendTitle","Ecosystem trend")}),s.jsx(br,{series:h,ariaLabel:r("commandCenter.ecosystem.trendTitle","Ecosystem trend")})]}):null,s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.ecosystem.perModelTitle","Tasks per model")}),s.jsx(nt,{data:u,ariaLabel:r("commandCenter.ecosystem.perModelTitle","Tasks per model")})]})]})}const bh=100,d2=1e3;function f2(e,t){const r=new Date(e);return Number.isNaN(r.getTime())?t:r.toLocaleString()}function m2({range:e,projectId:t}){const{t:r}=se("app"),{data:n,isLoading:a,error:i}=Je("/command-center/github",e,{projectId:t}),[o,l]=f.useState(!1),[c,d]=f.useState(null),[u,m]=f.useState(null),h=f.useCallback(async()=>{if(!o){l(!0),d(null),m(null);try{let D=0;const V={scanned:0,filled:0,skipped:0,errors:0};for(let B=0;B<d2;B+=1){const W=await xj({offset:D,limit:bh});if(V.scanned+=W.scanned,V.filled+=W.filled,V.skipped+=W.skipped,V.errors+=W.errors,!W.hasMore){d(V);return}D+=bh}d(V),m(r("commandCenter.github.backfillMaxBatches","Backfill stopped after the safety limit; rerun after checking server logs."))}catch(D){m(D instanceof Error?D.message:r("commandCenter.github.backfillFailed","Failed to backfill GitHub source issue close times"))}finally{l(!1)}}},[o,r]),v=f.useMemo(()=>n?.daily??[],[n?.daily]),p=f.useMemo(()=>n?.byRepo??[],[n?.byRepo]),b=f.useMemo(()=>n?.resolved??[],[n?.resolved]),y=f.useMemo(()=>v.map(D=>D.filed),[v]),g=f.useMemo(()=>v.map(D=>D.fixed),[v]),j=f.useMemo(()=>Math.max(0,...y,...g),[y,g]),x=f.useMemo(()=>p.slice(0,12).map(D=>({label:D.repo,value:D.filed+D.fixed,valueLabel:r("commandCenter.github.repoValue","{{filed}} filed / {{fixed}} fixed",{filed:U(D.filed),fixed:U(D.fixed)})})),[p,r]),C=f.useMemo(()=>[{label:r("commandCenter.github.filed","Filed by Fusion"),value:n?.filed??0},{label:r("commandCenter.github.fixed","Fixed by Fusion"),value:n?.fixed??0}],[n?.filed,n?.fixed,r]),w=f.useMemo(()=>[{label:r("commandCenter.github.filedTrend","Filed"),values:y},{label:r("commandCenter.github.fixedTrend","Fixed"),values:g}],[y,g,r]),P=n?.filed??0,A=n?.fixed??0,S=n?.net??P-A,N=!n||P===0&&A===0,E=v.length>0,T=P+A>0,O=x.length>0,I=b.length>0,z=u||(c?.errors??0)>0?"cc-github-backfill-status--error":o?"cc-github-backfill-status--warning":"";return s.jsxs(ft,{testId:"github",isLoading:a,error:i,isEmpty:!1,emptyMessage:r("commandCenter.github.empty","No GitHub issue activity in the selected range."),children:[s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.github.totalsTitle","GitHub issue flow")}),N?s.jsx("span",{className:"cc-stat-sub",children:r("commandCenter.github.empty","No GitHub issue activity in the selected range.")}):null,s.jsxs("div",{className:"cc-stat-grid",children:[s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-github-filed",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.github.filed","Filed by Fusion")}),s.jsx("div",{className:"cc-stat-value",children:U(P)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-github-fixed",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.github.fixed","Fixed by Fusion")}),s.jsx("div",{className:"cc-stat-value",children:U(A)}),s.jsx("span",{className:"cc-stat-sub",children:r("commandCenter.github.fixedApproximation","Uses done tasks updated in range")}),s.jsx("div",{className:"cc-github-backfill-actions",children:s.jsxs("button",{type:"button",className:"btn","data-testid":"cc-github-backfill-button",onClick:()=>void h(),disabled:o,children:[s.jsx(Gt,{className:o?"spin":void 0}),s.jsx("span",{children:o?r("commandCenter.github.backfillBusy","Backfilling close times…"):r("commandCenter.github.backfillButton","Backfill exact close times")})]})}),o||c||u?s.jsxs("div",{className:`cc-github-backfill-status ${z}`.trim(),"data-testid":"cc-github-backfill-result",role:"status",children:[o?s.jsx("span",{children:r("commandCenter.github.backfillPending","Backfill is running in paginated batches.")}):null,u?s.jsx("span",{children:u}):null,c?s.jsx("span",{children:c.scanned===0&&c.filled===0?r("commandCenter.github.backfillNothing","Nothing to backfill. Scanned {{scanned}}, filled {{filled}}, skipped {{skipped}}, errors {{errors}}.",c):r("commandCenter.github.backfillResult","Backfill complete. Scanned {{scanned}}, filled {{filled}}, skipped {{skipped}}, errors {{errors}}.",c)}):null]}):null]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-github-net",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.github.net","Net")}),s.jsx("div",{className:"cc-stat-value",children:U(S)})]})]})]}),T?s.jsxs("div",{className:"cc-area-section","data-testid":"cc-github-pie",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.github.issueFlowShare","Filed vs fixed share")}),s.jsx(Mt,{data:C,ariaLabel:r("commandCenter.github.issueFlowShare","Filed vs fixed share")})]}):null,E?s.jsxs("div",{className:"cc-area-section","data-testid":"cc-github-line",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.github.dailyLine","Filed vs fixed line")}),s.jsx(br,{series:w,ariaLabel:r("commandCenter.github.dailyLine","Filed vs fixed line")})]}):null,E?s.jsxs("div",{className:"cc-area-section","data-testid":"cc-github-daily-trend",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.github.dailyTrend","Filed vs fixed trend")}),s.jsxs("div",{className:"cc-stat-grid",children:[s.jsxs("div",{className:"card cc-stat-card",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.github.filedTrend","Filed")}),s.jsx(Ot,{values:y,max:j,ariaLabel:r("commandCenter.github.filedTrend","Filed")})]}),s.jsxs("div",{className:"card cc-stat-card",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.github.fixedTrend","Fixed")}),s.jsx(Ot,{values:g,max:j,ariaLabel:r("commandCenter.github.fixedTrend","Fixed")})]})]})]}):null,O?s.jsxs("div",{className:"cc-area-section","data-testid":"cc-github-by-repo",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.github.byRepo","By repository")}),s.jsx(nt,{data:x,ariaLabel:r("commandCenter.github.byRepo","By repository")})]}):null,I?s.jsxs("div",{className:"cc-area-section","data-testid":"cc-github-resolved",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.github.resolvedTitle","Resolved issues")}),s.jsx("div",{className:"cc-table-wrap cc-github-resolved-table-wrap","data-testid":"cc-github-resolved-table-wrap",children:s.jsxs("table",{className:"cc-table cc-github-resolved-table","data-testid":"cc-github-resolved-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{scope:"col",children:r("commandCenter.github.resolvedIssue","Issue")}),s.jsx("th",{scope:"col",children:r("commandCenter.github.resolvedTask","Resolving task")}),s.jsx("th",{scope:"col",children:r("commandCenter.github.resolvedAt","Resolved at")})]})}),s.jsx("tbody",{children:b.map(D=>{const V=D.issueNumber===null?D.repo:`${D.repo}#${D.issueNumber}`,B=f2(D.resolvedAt,r("commandCenter.github.resolvedAtUnknown","Unknown")),W=!!D.taskTitle;return s.jsxs("tr",{children:[s.jsx("td",{className:"cc-github-resolved-issue-cell",children:D.url?s.jsx("a",{className:"cc-github-resolved-issue-link",href:D.url,target:"_blank",rel:"noopener noreferrer","aria-label":r("commandCenter.github.openResolvedIssue","Open GitHub issue {{issue}}",{issue:V}),children:V}):s.jsx("span",{className:"cc-github-resolved-issue-ref",children:V})}),s.jsx("td",{className:"cc-github-resolved-task-cell",children:s.jsxs("span",{className:"cc-github-resolved-task",children:[s.jsx("span",{className:"cc-github-resolved-task-title",children:D.taskTitle||D.taskId}),W?s.jsx("span",{className:"cc-stat-sub cc-github-resolved-task-id",children:D.taskId}):null]})}),s.jsx("td",{className:"cc-github-resolved-date-cell",children:s.jsxs("span",{className:"cc-github-resolved-date",children:[s.jsx("span",{children:B}),D.resolvedAtExact?null:s.jsx("span",{className:"cc-stat-sub cc-github-resolved-date-approx",children:r("commandCenter.github.resolvedApprox","approx")})]})})]},D.taskId)})})]})})]}):null]})}function v2(e,t){const r=new Date(e);return Number.isNaN(r.getTime())?t:r.toLocaleString()}function h2({range:e,projectId:t}){const{t:r}=se("app"),{data:n,isLoading:a,error:i}=Je("/command-center/gitlab",e,{projectId:t}),o=f.useMemo(()=>n?.daily??[],[n?.daily]),l=f.useMemo(()=>n?.byProject??[],[n?.byProject]),c=f.useMemo(()=>n?.resolved??[],[n?.resolved]),d=f.useMemo(()=>o.map(g=>g.filed),[o]),u=f.useMemo(()=>o.map(g=>g.fixed),[o]),m=f.useMemo(()=>Math.max(0,...d,...u),[d,u]),h=f.useMemo(()=>l.slice(0,12).map(g=>({label:g.project,value:g.filed+g.fixed,valueLabel:r("commandCenter.gitlab.projectValue","{{filed}} filed / {{fixed}} fixed",{filed:U(g.filed),fixed:U(g.fixed)})})),[l,r]),v=n?.filed??0,p=n?.fixed??0,b=n?.net??v-p,y=!n||v===0&&p===0;return s.jsxs(ft,{testId:"gitlab",isLoading:a,error:i,isEmpty:!1,emptyMessage:r("commandCenter.gitlab.empty","No GitLab issue or merge request activity in the selected range."),children:[s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.gitlab.totalsTitle","GitLab issue and MR flow")}),y?s.jsx("span",{className:"cc-stat-sub",children:r("commandCenter.gitlab.empty","No GitLab issue or merge request activity in the selected range.")}):null,s.jsxs("div",{className:"cc-stat-grid",children:[s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-gitlab-filed",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.gitlab.filed","Filed by Fusion")}),s.jsx("div",{className:"cc-stat-value",children:U(v)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-gitlab-fixed",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.gitlab.fixed","Fixed by Fusion")}),s.jsx("div",{className:"cc-stat-value",children:U(p)}),s.jsx("span",{className:"cc-stat-sub",children:r("commandCenter.gitlab.fixedApproximation","Uses persisted GitLab close times when available")})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-gitlab-net",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.gitlab.net","Net")}),s.jsx("div",{className:"cc-stat-value",children:U(b)})]})]})]}),s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.gitlab.dailyTitle","Daily GitLab flow")}),o.length>0?s.jsxs("div",{className:"cc-chart-grid",children:[s.jsxs("div",{className:"card cc-chart-card",children:[s.jsx("h4",{children:r("commandCenter.gitlab.filedTrend","Filed")}),s.jsx(Ot,{values:d,max:m})]}),s.jsxs("div",{className:"card cc-chart-card",children:[s.jsx("h4",{children:r("commandCenter.gitlab.fixedTrend","Fixed")}),s.jsx(Ot,{values:u,max:m})]})]}):s.jsx("span",{className:"cc-stat-sub",children:r("commandCenter.gitlab.noDaily","No daily GitLab trend data yet.")})]}),s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.gitlab.projectsTitle","Projects and groups")}),h.length>0?s.jsx(nt,{data:h}):s.jsx("span",{className:"cc-stat-sub",children:r("commandCenter.gitlab.noProjects","No GitLab project activity yet.")})]}),s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.gitlab.resolvedTitle","Resolved GitLab source items")}),c.length>0?s.jsx("div",{className:"cc-resolved-list","data-testid":"cc-gitlab-resolved-list",children:c.slice(0,12).map(g=>{const x=`${g.issueNumber===null?g.project:`${g.project}#${g.issueNumber}`} · ${g.taskId}`;return s.jsxs("div",{className:"card cc-resolved-item",children:[s.jsxs("div",{children:[g.url?s.jsx("a",{href:g.url,target:"_blank",rel:"noopener noreferrer",children:x}):s.jsx("strong",{children:x}),s.jsx("div",{className:"cc-stat-sub",children:g.taskTitle})]}),s.jsxs("span",{className:"cc-stat-sub",children:[v2(g.resolvedAt,g.resolvedAt),g.resolvedAtExact?"":` ${r("commandCenter.gitlab.approximate","(approx.)")}`]})]},`${g.taskId}:${g.resolvedAt}`)})}):s.jsx("span",{className:"cc-stat-sub",children:r("commandCenter.gitlab.noResolved","No resolved GitLab source items in range.")})]})]})}function p2({range:e,projectId:t}){const{t:r}=se("app"),{data:n,isLoading:a}=Je("/command-center/signals",e,{projectId:t}),{data:i,isLoading:o}=Je("/command-center/signals/connectors",e,{projectId:t}),l=f.useMemo(()=>(n?.bySource??[]).map(y=>({label:y.source,value:y.count,valueLabel:U(y.count)})),[n?.bySource]),c=f.useMemo(()=>(n?.bySeverity??[]).map(y=>({label:y.severity,value:y.count,valueLabel:U(y.count)})),[n?.bySeverity]),d=f.useMemo(()=>[{label:r("commandCenter.signals.open","Open"),value:n?.open??0},{label:r("commandCenter.signals.resolved","Resolved"),value:n?.resolved??0}],[n?.open,n?.resolved,r]),u=!n||n.totalSignals===0,h=(Array.isArray(i?.connectors)?i.connectors.filter(y=>y.configured).map(y=>y.provider):void 0)??n?.connectors?.configured??[],p=h.length>0||n?.connectors?.anyConfigured===!0?r("commandCenter.signals.emptyAwaitingSignals","Connector configured, awaiting signals in this range. Configured providers: {{providers}}.",{providers:h.length>0?h.join(", "):r("commandCenter.signals.providersUnknown","unknown")}):r("commandCenter.signals.emptyNoConnectorConfigured","No signal connector configured. Connect GitLab, Sentry, Datadog, PagerDuty, or a generic webhook to see incident metrics here."),b=!u&&d.some(y=>y.value>0);return s.jsxs(ft,{testId:"signals",isLoading:a||o,error:null,isEmpty:u,emptyMessage:p,children:[s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.signals.summaryTitle","Summary")}),s.jsxs("div",{className:"cc-stat-grid",children:[s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-signals-total",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.signals.total","Total signals")}),s.jsx("div",{className:"cc-stat-value",children:U(n?.totalSignals??0)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-signals-open",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.signals.open","Open")}),s.jsx("div",{className:"cc-stat-value",children:U(n?.open??0)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-signals-resolved",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.signals.resolved","Resolved")}),s.jsx("div",{className:"cc-stat-value",children:U(n?.resolved??0)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-signals-mttr",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.signals.mttr","MTTR")}),s.jsx("div",{className:"cc-stat-value",children:n&&n.mttr.value!==null&&!n.mttr.unavailable?r("commandCenter.signals.mttrValue","{{min}} min",{min:Math.round(n.mttr.value)}):s.jsx("span",{className:"cc-unavailable",title:r("commandCenter.signals.mttrUnavailable","MTTR is unavailable until incident data is recorded"),children:"—"})})]})]})]}),b?s.jsxs("div",{className:"cc-area-section","data-testid":"cc-signals-pie",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.signals.statusShare","Signal status share")}),s.jsx(Mt,{data:d,ariaLabel:r("commandCenter.signals.statusShare","Signal status share")})]}):null,s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.signals.bySource","By source")}),s.jsx(nt,{data:l,ariaLabel:r("commandCenter.signals.bySource","By source")})]}),s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.signals.bySeverity","By severity")}),s.jsx(nt,{data:c,ariaLabel:r("commandCenter.signals.bySeverity","By severity")})]})]})}function Ux(e){return e===null||!Number.isFinite(e)||e<=0?0:Math.max(0,Math.min(1,e))}function y2(e){if(e===null)return"—";const t=Ux(e);return`${Math.round(t*100)}%`}function Ua({value:e,label:t,ariaLabel:r}){const n=Ux(e),a=y2(e),i={"--cc-radial-value":`${n*100}%`};return s.jsxs("div",{className:"cc-radial-gauge",role:"img","aria-label":r,style:i,children:[s.jsx("div",{className:"cc-radial-gauge-ring","aria-hidden":"true",children:s.jsx("div",{className:"cc-radial-gauge-core",children:s.jsx("span",{className:"cc-radial-gauge-value",children:a})})}),s.jsx("span",{className:"cc-radial-gauge-label",children:t})]})}const g2=5e3,b2=30,x2=["triage","todo","in-progress","in-review","done"],j2=["idle","active","running","error"];function xh(e,t){return!Number.isFinite(e)||!Number.isFinite(t)||t<=0?"—":`${(e/t*100).toFixed(1)}%`}function w2(e,t){if(t<=0)return"normal";const r=e/t;return r>=.85?"critical":r>=.65?"warning":"normal"}function C2(e,t){if(t<=0)return"normal";const r=e/t;return r>=.5?"critical":r>=.25?"warning":"normal"}function k2(e,t){if(t<=0)return"normal";const r=e/t;return r>=.9?"critical":r>=.75?"warning":"normal"}function S2(e,t){if(e===null||!Number.isFinite(e)||e<0)return"normal";const r=t>0?e/t:e;return r>=80?"critical":r>=50?"warning":"normal"}function Ma(e){return e==="critical"?"cc-system-value--critical":e==="warning"?"cc-system-value--warning":""}function N2(e,t){if(!e)return t;const r=new Date(e);return Number.isNaN(r.getTime())?t:r.toLocaleString()}function Ti(e,t){return!Number.isFinite(e)||!Number.isFinite(t)||t<=0?0:Math.max(0,Math.min(1,e/t))}function $n(e){return e==null||!Number.isFinite(e)?0:Math.max(0,Math.min(100,e))}function P2(e){const t=e.systemStats,r=t.systemTotalMem-t.systemFreeMem;return{cpuPercent:$n(t.cpuPercent),usedSystemMemPercent:Ti(r,t.systemTotalMem)*100,heapUsedPercent:Ti(t.heapUsed,t.heapLimit)*100}}function A2({projectId:e}){const{t}=se("app"),[r,n]=f.useState(null),[a,i]=f.useState([]),[o,l]=f.useState(!0),[c,d]=f.useState(null),[u,m]=f.useState(!0),[h,v]=f.useState(90),[p,b]=f.useState(!1),[y,g]=f.useState(!1),[j,x]=f.useState(null),[C,w]=f.useState(null),[P,A]=f.useState(null),[S,N]=f.useState(null),{nodes:E}=Th(),T=f.useMemo(()=>E.find(k=>k.type==="local")?.id,[E]),O=S??T??null,I=E.find(k=>k.id===O)??null,z=E.length>1,D=I?.name??t("systemStats.localNodeFallback","Local node"),V=f.useCallback(k=>{const $=[];return k.type==="local"&&$.push(t("systemStats.thisNodeSuffix","this node")),k.status&&k.status!=="online"&&$.push(t("systemStats.nodeStatusSuffix","{{status}}",{status:k.status})),$.length>0?`${k.name} (${$.join(" · ")})`:k.name},[E,t]),B=f.useCallback(async k=>{l(!0);try{const $=O&&O!==T?await jj(O,e):await wj(e);n($),i(de=>[...de,P2($)].slice(-b2)),d(null),A(Date.now()),k?.preserveKillResult||x(null)}catch($){d($ instanceof Error?$.message:t("systemStats.errorLoadStats","Failed to load system stats"))}finally{l(!1)}},[O,T,e,t]);f.useEffect(()=>{B()},[B]);const W=f.useCallback(()=>{B()},[B]);vn(W,g2),f.useEffect(()=>{N(k=>k&&E.some($=>$.id===k)?k:null)},[E]),f.useEffect(()=>{i([]),d(null),x(null),g(!1)},[O]),f.useEffect(()=>{let k=!1;return(async()=>{try{const de=await Cj();if(k)return;m(de.vitestAutoKillEnabled??!0),v(de.vitestKillThresholdPct??90),w(null)}catch(de){k||w(de instanceof Error?de.message:t("systemStats.errorLoadVitestSettings","Failed to load vitest settings"))}})(),()=>{k=!0}},[t]);const K=f.useCallback(async k=>{m(k);try{await Fu({vitestAutoKillEnabled:k}),w(null)}catch($){w($ instanceof Error?$.message:t("systemStats.errorSaveVitestSettings","Failed to save vitest settings"))}},[t]),te=f.useCallback(async k=>{const $=Math.min(99,Math.max(50,Number.isFinite(k)?Math.round(k):90));v($);try{await Fu({vitestKillThresholdPct:$}),w(null)}catch(de){w(de instanceof Error?de.message:t("systemStats.errorSaveVitestSettings","Failed to save vitest settings"))}},[t]),G=f.useCallback(async()=>{if(!p){if(!y){g(!0);return}b(!0);try{const k=O&&O!==T?await Bu(e,O,T):await Bu(e);x(k),g(!1),await B({preserveKillResult:!0})}catch(k){d(k instanceof Error?k.message:t("systemStats.errorKillVitest","Failed to kill vitest processes"))}finally{b(!1)}}},[y,O,p,B,T,e,t]),M=r?.systemStats,q=r?.taskStats,H=M?M.systemTotalMem-M.systemFreeMem:0,re=M?Ti(H,M.systemTotalMem):0,ae=M?Ti(M.heapUsed,M.heapLimit):0,ye=M?.cpuPercent===null||M?.cpuPercent===void 0?null:$n(M.cpuPercent)/100,oe=M?.cpuPercent===null||M?.cpuPercent===void 0?t("systemStats.cpuSampling","Sampling…"):`${M.cpuPercent.toFixed(1)}%`,He=P?t("systemStats.updatedAt","Updated {{time}}",{time:new Date(P).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}):t("systemStats.waitingFirstUpdate","Waiting for first update"),J=f.useMemo(()=>{const k=q?.byColumn??{};return(Object.keys(k).length>0?Object.keys(k):x2).map(de=>({label:de,value:k[de]??0,valueLabel:U(k[de]??0)}))},[q?.byColumn]),Ce=f.useMemo(()=>J.map(k=>({label:k.label,value:k.value})),[J]),Re=f.useMemo(()=>[{label:t("commandCenter.system.cpuSeries","CPU"),values:a.map(k=>$n(k.cpuPercent))},{label:t("commandCenter.system.memorySeries","Memory"),values:a.map(k=>$n(k.usedSystemMemPercent))},{label:t("commandCenter.system.heapSeries","Heap"),values:a.map(k=>$n(k.heapUsedPercent))}],[a,t]),L=Ce.some(k=>k.value>0),Y=a.length>0,ne=f.useMemo(()=>{const k=q?.agents;return j2.map($=>({label:t(`systemStats.agent${$[0].toUpperCase()}${$.slice(1)}`,$),value:k?.[$]??0,valueLabel:U(k?.[$]??0)}))},[q?.agents,t]),Ne=f.useMemo(()=>{const k=M?Ma(w2(M.heapUsed,M.heapLimit)):"",$=M?Ma(C2(M.rss,M.systemTotalMem)):"",de=M?Ma(k2(H,M.systemTotalMem)):"",Le=M?Ma(S2(M.cpuPercent,M.cpuCount)):"";return[{label:t("systemStats.rowAppCpu","App CPU"),value:oe,detail:M?.cpuPercent===null?t("systemStats.cpuFirstSamplePending","First sample pending"):t("systemStats.cpuProcessUsage","process usage"),className:Le},{label:t("systemStats.rowRss","RSS"),value:M?ct(M.rss):"—",detail:M?xh(M.rss,M.systemTotalMem):"—",className:$},{label:t("systemStats.rowHeapUsed","Heap Used"),value:M?ct(M.heapUsed):"—",detail:M?t("systemStats.rowHeapUsedDetail","of {{total}}",{total:ct(M.heapTotal)}):"—",className:k},{label:t("systemStats.rowHeapLimit","Heap Limit"),value:M?ct(M.heapLimit):"—",detail:t("systemStats.rowHeapLimitDetail","V8 limit")},{label:t("systemStats.rowExternal","External"),value:M?ct(M.external):"—"},{label:t("systemStats.rowArrayBuffers","Array Buffers"),value:M?ct(M.arrayBuffers):"—"},{label:t("systemStats.rowLoadAvg","Load Avg"),value:M?.loadAvg.map(Nt=>Nt.toFixed(2)).join(" ")??"—"},{label:t("systemStats.rowCores","Cores"),value:M?.cpuCount??"—"},{label:t("systemStats.rowPlatform","Platform"),value:M?.platform??"—"},{label:t("systemStats.rowNode","Node"),value:M?.nodeVersion??"—"},{label:t("systemStats.rowPid","PID"),value:M?.pid??"—"},{label:t("systemStats.rowMemoryUsed","Memory Used"),value:M?ct(H):"—",detail:M?`${xh(H,M.systemTotalMem)} of ${ct(M.systemTotalMem)}`:"—",className:de},{label:t("systemStats.rowMemoryFree","Memory Free"),value:M?ct(M.systemFreeMem):"—"}]},[oe,M,t,H]),Q=r?.vitestProcessCount,le=N2(r?.vitestLastAutoKillAt,t("systemStats.notYet","Not yet")),Oe=o&&!!r;return s.jsxs(ft,{testId:"system",isLoading:o&&!r,error:r?null:c,isEmpty:!1,children:[s.jsxs("div",{className:"cc-area-section",children:[s.jsxs("div",{className:"cc-area-section-header",children:[s.jsx("h3",{className:"cc-area-section-title",children:t("commandCenter.system.healthTitle","Live system health")}),s.jsxs("div",{className:"cc-system-refresh","aria-live":"polite",children:[z?s.jsxs("label",{className:"cc-system-node-selector",htmlFor:"cc-system-node-select",children:[s.jsx("span",{children:t("systemStats.nodeSelectorLabel","Node")}),s.jsx("select",{id:"cc-system-node-select",className:"input","data-testid":"cc-system-node-select","aria-label":t("systemStats.nodeSelectorAriaLabel","Select system stats node"),value:O??"",onChange:k=>{i([]),x(null),g(!1),N(k.target.value||null)},children:E.map(k=>s.jsx("option",{value:k.id,children:V(k)},k.id))})]}):null,s.jsx("span",{children:t("systemStats.viewingNode","Viewing {{node}}",{node:D})}),s.jsx("span",{children:t("systemStats.autoRefresh","Auto-refresh · 5s")}),s.jsx("span",{children:He}),s.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void B(),title:t("systemStats.refreshTitle","Refresh"),"aria-label":t("systemStats.refreshAriaLabel","Refresh system stats"),children:s.jsx(Gt,{size:16,className:Oe?"spin":void 0})})]})]}),c&&r?s.jsx("p",{className:"cc-system-note cc-system-note--error",role:"status",children:t("systemStats.footerRefreshFailed","Latest refresh failed: {{error}}",{error:c})}):null,s.jsxs("div",{className:"cc-stat-grid cc-system-gauges",children:[s.jsxs("div",{className:"card cc-stat-card cc-stat-card--gauge","data-testid":"cc-system-cpu-gauge",children:[s.jsx(Ua,{value:ye,label:t("systemStats.rowAppCpu","App CPU"),ariaLabel:t("commandCenter.system.cpuGauge","App CPU usage")}),s.jsx("span",{className:"cc-stat-sub",children:oe})]}),s.jsxs("div",{className:"card cc-stat-card cc-stat-card--gauge","data-testid":"cc-system-mem-gauge",children:[s.jsx(Ua,{value:re,label:t("systemStats.rowMemoryUsed","Memory Used"),ariaLabel:t("commandCenter.system.memoryGauge","System memory used")}),s.jsx("span",{className:"cc-stat-sub",children:M?`${ct(H)} / ${ct(M.systemTotalMem)}`:"—"})]}),s.jsxs("div",{className:"card cc-stat-card cc-stat-card--gauge","data-testid":"cc-system-heap-gauge",children:[s.jsx(Ua,{value:ae,label:t("systemStats.rowHeapUsed","Heap Used"),ariaLabel:t("commandCenter.system.heapGauge","Heap used")}),s.jsx("span",{className:"cc-stat-sub",children:M?`${ct(M.heapUsed)} / ${ct(M.heapLimit)}`:"—"})]})]})]}),s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:t("commandCenter.system.trendsTitle","Live trends")}),Y?s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-system-line",children:[s.jsx("div",{className:"cc-stat-label",children:t("commandCenter.system.resourceTrend","Resource trend")}),s.jsx(br,{series:Re,ariaLabel:t("commandCenter.system.resourceTrend","Resource trend")})]}):null,s.jsxs("div",{className:"cc-stat-grid",children:[s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-system-cpu-trend",children:[s.jsx("div",{className:"cc-stat-label",children:t("commandCenter.system.cpuTrend","CPU over time")}),s.jsx(Ot,{values:a.map(k=>k.cpuPercent),max:100,ariaLabel:t("commandCenter.system.cpuTrend","CPU over time")})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-system-memory-trend",children:[s.jsx("div",{className:"cc-stat-label",children:t("commandCenter.system.memoryTrend","Memory over time")}),s.jsx(Ot,{values:a.map(k=>k.usedSystemMemPercent),max:100,ariaLabel:t("commandCenter.system.memoryTrend","Memory over time")})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-system-heap-trend",children:[s.jsx("div",{className:"cc-stat-label",children:t("commandCenter.system.heapTrend","Heap over time")}),s.jsx(Ot,{values:a.map(k=>k.heapUsedPercent),max:100,ariaLabel:t("commandCenter.system.heapTrend","Heap over time")})]})]})]}),s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:t("commandCenter.system.workloadTitle","Workload")}),s.jsxs("div",{className:"cc-system-chart-grid",children:[L?s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-system-pie",children:[s.jsx("div",{className:"cc-stat-label",children:t("commandCenter.system.taskShare","Task distribution")}),s.jsx(Mt,{data:Ce,ariaLabel:t("commandCenter.system.taskShare","Task distribution")})]}):null,s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-system-tasks-bar",children:[s.jsx("div",{className:"cc-stat-label",children:t("systemStats.sectionTasks","Tasks")}),s.jsx(nt,{data:J,ariaLabel:t("systemStats.sectionTasksAriaLabel","Task stats")})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-system-agents-bar",children:[s.jsx("div",{className:"cc-stat-label",children:t("systemStats.sectionAgents","Agents")}),s.jsx(nt,{data:ne,ariaLabel:t("systemStats.sectionAgentsAriaLabel","Agent stats")})]})]})]}),s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:t("commandCenter.system.detailsTitle","Runtime details")}),s.jsx("div",{className:"cc-stat-grid","data-testid":"cc-system-details-grid",children:Ne.map(k=>s.jsxs("div",{className:"card cc-stat-card",children:[s.jsx("div",{className:"cc-stat-label",children:k.label}),s.jsx("div",{className:`cc-stat-value ${k.className??""}`.trim(),children:k.value}),k.detail?s.jsx("span",{className:"cc-stat-sub",children:k.detail}):null]},k.label))})]}),s.jsxs("div",{className:"cc-area-section","data-testid":"cc-system-vitest-controls",children:[s.jsxs("h3",{className:"cc-area-section-title cc-system-section-title-with-icon",children:[s.jsx(Z0,{}),s.jsx("span",{children:t("systemStats.sectionVitest","Vitest Controls")})]}),s.jsxs("div",{className:"cc-stat-grid",children:[s.jsxs("div",{className:"card cc-stat-card",children:[s.jsx("div",{className:"cc-stat-label",children:t("systemStats.vitestProcesses","Vitest Processes")}),s.jsx("div",{className:"cc-stat-value",children:Q??"—"})]}),s.jsxs("div",{className:"card cc-stat-card",children:[s.jsx("div",{className:"cc-stat-label",children:t("systemStats.lastAutoKill","Last auto-kill: {{time}}",{time:""}).trim()}),s.jsx("div",{className:"cc-stat-value",children:le})]})]}),s.jsxs("div",{className:"card cc-system-vitest-card",children:[s.jsxs("button",{type:"button",className:"btn btn-danger","data-testid":"cc-system-kill-vitest",onClick:()=>void G(),disabled:p||Q===0,children:[s.jsx(xw,{}),s.jsx("span",{children:y?t("systemStats.confirmKill","Confirm Kill?"):t("systemStats.killVitest","Kill Vitest Processes")})]}),s.jsxs("label",{className:"cc-system-toggle-row",children:[s.jsx("input",{type:"checkbox",checked:u,onChange:k=>{K(k.target.checked)}}),s.jsx("span",{children:t("systemStats.autoKillLabel","Auto-kill vitest on memory pressure")})]}),s.jsxs("div",{className:"cc-system-threshold-row",children:[s.jsx("label",{htmlFor:"cc-system-vitest-threshold-number",children:t("systemStats.killThresholdLabel","Kill threshold (%)")}),s.jsxs("div",{className:"cc-system-threshold-controls",children:[s.jsx("input",{id:"cc-system-vitest-threshold-range",type:"range",min:50,max:99,value:h,"aria-label":t("systemStats.killThresholdSliderAriaLabel","Kill threshold slider (%)"),onChange:k=>{const $=Number.parseInt(k.target.value,10);te(Number.isNaN($)?90:$)}}),s.jsx("input",{id:"cc-system-vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":t("systemStats.killThresholdInputAriaLabel","Kill threshold (%)"),onChange:k=>{const $=Number.parseInt(k.target.value,10);te(Number.isNaN($)?90:$)},onBlur:()=>{te(h)}})]})]}),j?s.jsx("p",{className:`cc-system-note ${j.killed>0?"cc-system-note--success":"cc-system-note--error"}`,children:t("systemStats.killedProcesses","Killed {{count}} processes",{count:j.killed})}):null,C?s.jsx("p",{className:"cc-system-note cc-system-note--error",children:C}):null]})]})]})}const Tn=500,O2=1500,E2=3e3,_2=9e4,T2=50,M2=3e3;function jh(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=T2}function I2(e){const t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleTimeString()}function D2({projectId:e,addToast:t}){const{t:r}=se("app"),n=f.useCallback((R,ce)=>t?.(R,ce),[t]),[a,i]=f.useState(null),[o,l]=f.useState(null),[c,d]=f.useState(null),[u,m]=f.useState(null),h=typeof window>"u"?void 0:Q0(window.location),[v,p]=f.useState(null),[b,y]=f.useState([]),g=f.useRef(new Set),j=f.useRef(null),x=f.useRef(!0),C=f.useRef(null),[w,P]=f.useState(null),A=f.useRef(null),S=f.useRef(null),N=f.useRef(null),E=f.useRef(new Set),T=f.useRef(!1),O=f.useRef(0),[I,z]=f.useState(!1),[D,V]=f.useState([]),B=f.useRef(null),W=f.useRef(!0),[K,te]=f.useState(null),G=f.useCallback(()=>{const R=j.current;R&&(x.current=jh(R))},[]),M=f.useCallback(()=>{const R=B.current;R&&(W.current=jh(R))},[]),q=f.useCallback(async()=>{try{const R=await Ps();return i(R),l(null),R.activeRebuild&&p(ce=>ce&&ce.id===R.activeRebuild.id?ce:(y([]),g.current=new Set,x.current=!0,R.activeRebuild)),R}catch(R){return l(R instanceof Error?R.message:String(R)),null}},[]);f.useEffect(()=>{let R=!1;return(async()=>{await q();try{const{job:ce}=await zu();if(!R&&ce){p(ce);const Pe=ce.lines??[];g.current=new Set(Pe.map(Ge=>Ge.i)),y(ga(Pe,Tn))}}catch{}})(),()=>{R=!0}},[q]),f.useEffect(()=>{S.current=v},[v]),f.useEffect(()=>{N.current=a},[a]);const H=f.useCallback(R=>{if(E.current.has(R.id)){p(R);return}if(E.current.add(R.id),p(R),R.status==="succeeded"&&R.restartScheduled)A.current=N.current?.pid??null,P("waiting");else if(R.status==="succeeded"){const ce=R.kind==="fn-binary"&&R.scope==="link-local"?r("systemControls.fnLinkLocalSucceeded","Local fn binary built and linked"):R.kind==="fn-binary"&&R.scope==="use-global"?r("systemControls.fnUseGlobalSucceeded","Switched default fn to global npm install"):r("systemControls.rebuildSucceeded","Rebuild finished successfully");n(ce,"success")}else n(r("systemControls.rebuildFailed","Job failed — see output for details"),"error")},[r,n]),re=f.useCallback(async()=>{const R=S.current;if(!R||R.status!=="running"||T.current)return;const ce=Date.now();if(ce-O.current<M2)return;O.current=ce,T.current=!0;const Pe=N.current?.pid;try{let Ge=null;try{({job:Ge}=await zu())}catch{O.current=0;return}if(S.current?.id!==R.id)return;if(Ge&&Ge.id===R.id){const Cn=Ge.lines;Cn&&(g.current=new Set(Cn.map(Ss=>Ss.i)),y(ga(Cn,Tn))),Ge.status!=="running"&&H(Ge);return}const Kr=await Ps().catch(()=>null);if(!Kr||S.current?.id!==R.id)return;if(i(Kr),Pe!==void 0&&Kr.pid!==Pe){p(null),y([]),g.current=new Set,R.restartAfter?(A.current=Kr.pid,P("back")):n(r("systemControls.jobLostToRestart","The server restarted while the job was streaming — its output is gone"),"warning");return}const ya=r("systemControls.jobOutcomeUnknown","Lost the job stream before a result arrived — the outcome is unknown");E.current.add(R.id),p({...R,status:"failed",finishedAt:Date.now(),error:ya}),n(ya,"warning")}finally{T.current=!1}},[H,r,n]);f.useEffect(()=>!v||v.status!=="running"?void 0:qa(`/api/system/jobs/${v.id}/stream`,{events:{line:ce=>{try{const Pe=JSON.parse(ce.data);if(g.current.has(Pe.i))return;g.current.add(Pe.i),y(Ge=>ga([...Ge,Pe],Tn))}catch{}},end:ce=>{try{const Pe=JSON.parse(ce.data);H(Pe)}catch{}}},onReconnect:()=>{re()},onError:()=>{re()}}),[v?.id,v?.status,H,re]),f.useEffect(()=>{const R=j.current;R&&x.current&&(R.scrollTop=R.scrollHeight)},[b]),f.useEffect(()=>{if(w!=="waiting")return;let R=!1;const ce=Date.now(),Pe=setInterval(()=>{(async()=>{if(Date.now()-ce>_2){R||P("timeout");return}try{const Ge=await Ps();if(R)return;(A.current===null||Ge.pid!==A.current)&&(i(Ge),P("back"))}catch{}})()},O2);return()=>{R=!0,clearInterval(Pe)}},[w]),f.useEffect(()=>{if(w!=="back")return;const R=setTimeout(()=>window.location.reload(),E2);return()=>clearTimeout(R)},[w]),f.useEffect(()=>!I||!a?.logsSupported?void 0:(W.current=!0,V([]),qa("/api/system/logs/stream",{events:{log:ce=>{try{const Pe=JSON.parse(ce.data);V(Ge=>ga([...Ge,Pe],Tn))}catch{}}},onReconnect:()=>V([])})),[I,a?.logsSupported]),f.useEffect(()=>{const R=B.current;R&&W.current&&(R.scrollTop=R.scrollHeight)},[D]);const ae=f.useCallback(async(R,ce)=>{if(!c){d(R);try{await ce()}catch(Pe){n(Pe instanceof Error?Pe.message:String(Pe),"error")}finally{d(null)}}},[c,n]);f.useEffect(()=>{if(!v||v.status!=="running")return;const R=requestAnimationFrame(()=>{C.current?.scrollIntoView({behavior:"smooth",block:"nearest"})});return()=>cancelAnimationFrame(R)},[v?.id,v?.status]);const ye=f.useCallback(R=>{x.current=!0,y([]),p(R)},[]),oe=f.useCallback(R=>ae(`rebuild-${R}`,async()=>{const ce=await kj(R,a?.restartSupported??!1);ye(ce)}),[ye,a?.restartSupported,ae]),He=f.useCallback(()=>ae("fn-link-local",async()=>{const R=await Sj();ye(R)}),[ye,ae]),J=f.useCallback(()=>ae("fn-use-global",async()=>{const R=await Nj();ye(R)}),[ye,ae]),Ce=f.useCallback(()=>ae("check-updates",async()=>{const R=await Pj();if(te(R),R.error){n(R.error,"error");return}if(R.disabled){n(r("systemControls.updatesDisabled","Update checks are disabled in global settings"),"warning");return}if(R.updateAvailable&&R.latestVersion){n(r("systemControls.updateAvailable","Update available: v{{version}} (current: v{{current}})",{version:R.latestVersion,current:R.currentVersion}),"success");return}n(r("systemControls.upToDate","You're up to date (v{{version}})",{version:R.currentVersion}),"success")}),[ae,r,n]),Re=f.useCallback(()=>ae("restart",async()=>{A.current=a?.pid??null,await Aj("system-panel"),P("waiting")}),[a?.pid,ae]),L=f.useCallback(()=>ae("engine",async()=>{const R=await Oj();n(r("systemControls.engineRestarted","Restarted {{count}} engine(s){{failed}}",{count:R.restarted.length,failed:R.failed.length?` — ${R.failed.length} failed`:""}),R.failed.length?"warning":"success")}),[ae,r,n]),Y=f.useCallback(()=>ae("agents",async()=>{const R=await Ej(e);n(r("systemControls.agentsRestarted","Restarted {{count}} active agent(s){{failed}}",{count:R.restarted.length,failed:R.failed.length?` — ${R.failed.length} failed`:""}),R.failed.length?"warning":"success")}),[e,ae,r,n]),ne=f.useCallback(()=>ae("plugins-reload",async()=>{const R=await _j();n(r("systemControls.pluginsReloaded","Reloaded {{count}} plugin(s){{failed}}",{count:R.reloaded.length,failed:R.failed.length?` — ${R.failed.length} failed`:""}),R.failed.length?"warning":"success")}),[ae,r,n]),Ne=f.useCallback(()=>ae("backup",async()=>{await J0(e),n(r("systemControls.backupCreated","Database backup created"),"success")}),[e,ae,r,n]),Q=f.useCallback(async()=>{const R=await Tj().catch(()=>null),ce=a?.logsSupported?await Mj(100).then(Pe=>Pe.entries).catch(()=>[]):[];return{capturedAt:new Date().toISOString(),version:R?.version,health:R??void 0,system:a??void 0,recentLogs:ce}},[a]),le=f.useCallback(()=>ae("diagnostics",async()=>{const R=await Q();if(await Ij(JSON.stringify(R,null,2))){n(r("systemControls.diagnosticsCopied","Diagnostics copied to clipboard"),"success");return}n(r("systemControls.diagnosticsCopyFailed","Could not copy diagnostics to clipboard"),"error")}),[Q,ae,r,n]),Oe=a&&!a.restartSupported?r("systemControls.restartUnavailable","Needs a supervising parent — restart the dashboard without --no-supervise."):void 0,k=a?.rebuildSupported??!1,$=a?.fnBinaryLinkLocalSupported??a?.rebuildSupported??!1,de=a?.fnBinaryUseGlobalSupported!==!1,Le=v?.status==="running",Nt=f.useMemo(()=>[{key:"rebuild-app",icon:vw,title:r("systemControls.rebuildRestart","Rebuild & restart"),description:r("systemControls.rebuildRestartDesc","Rebuild core, engine, dashboard and changed plugins, then restart the server."),cta:r("systemControls.rebuildRestartCta","Rebuild"),hidden:!k,disabled:Le,run:()=>void oe("app"),testId:"cc-syscontrol-rebuild-app"},{key:"rebuild-full",icon:Dj,title:r("systemControls.fullRebuild","Full rebuild & restart"),description:r("systemControls.fullRebuildDesc","Rebuild the entire workspace (slower), then restart."),cta:r("systemControls.fullRebuildCta","Full rebuild"),hidden:!k,disabled:Le,run:()=>void oe("full"),testId:"cc-syscontrol-rebuild-full"},{key:"fn-link-local",icon:pw,title:r("systemControls.fnLinkLocal","Build & link local fn"),description:r("systemControls.fnLinkLocalDesc","Build the standalone fn binary from this source checkout and install it as your default PATH binary (~/.local)."),cta:r("systemControls.fnLinkLocalCta","Build & link"),hidden:!$,disabled:Le,run:()=>void He(),testId:"cc-syscontrol-fn-link-local"},{key:"fn-use-global",icon:Ri,title:r("systemControls.fnUseGlobal","Use global npm fn"),description:r("systemControls.fnUseGlobalDesc","Remove the local-build shims and reinstall the published runfusion.ai package globally."),cta:r("systemControls.fnUseGlobalCta","Install global"),hidden:!de,disabled:Le,run:()=>void J(),testId:"cc-syscontrol-fn-use-global"},{key:"check-updates",icon:uw,title:r("systemControls.checkUpdates","Check for updates"),description:r("systemControls.checkUpdatesDesc","Query the registry for a newer published Fusion version."),cta:r("systemControls.checkUpdatesCta","Check now"),disabled:!1,run:()=>void Ce(),testId:"cc-syscontrol-check-updates"},{key:"restart",icon:Mh,title:r("systemControls.restartServer","Restart server"),description:r("systemControls.restartServerDesc","Gracefully restart the dashboard and engine process."),cta:r("systemControls.restartServerCta","Restart"),disabled:!a?.restartSupported,note:Oe,run:()=>void Re(),testId:"cc-syscontrol-restart"},{key:"engine",icon:Rj,title:r("systemControls.restartEngine","Restart engine"),description:r("systemControls.restartEngineDesc","Stop and restart all running project engines in place."),cta:r("systemControls.restartEngineCta","Restart engine"),disabled:!a?.engineAvailable,note:a&&!a.engineAvailable?r("systemControls.engineUnavailable","Engine is not running in this process."):void 0,run:()=>void L(),testId:"cc-syscontrol-engine"},{key:"agents",icon:Lj,title:r("systemControls.restartAgents","Restart all agents"),description:r("systemControls.restartAgentsDesc","Stop active runs and bounce every active agent. Paused agents stay paused."),cta:r("systemControls.restartAgentsCta","Restart agents"),disabled:!1,run:()=>void Y(),testId:"cc-syscontrol-agents"},{key:"rebuild-plugins",icon:lw,title:r("systemControls.rebuildPlugins","Rebuild & reload plugins"),description:r("systemControls.rebuildPluginsDesc","Rebuild changed plugin bundles and hot-reload them without a server restart."),cta:r("systemControls.rebuildPluginsCta","Rebuild plugins"),hidden:!k,disabled:Le,run:()=>void oe("plugins"),testId:"cc-syscontrol-rebuild-plugins"},{key:"plugins-reload",icon:Gt,title:r("systemControls.reloadPlugins","Reload plugins"),description:r("systemControls.reloadPluginsDesc","Hot-reload every started plugin from its current build."),cta:r("systemControls.reloadPluginsCta","Reload"),disabled:!a?.pluginReloadSupported,note:a&&!a.pluginReloadSupported?r("systemControls.pluginReloadUnavailable","Plugin runner is unavailable in this mode."):void 0,run:()=>void ne(),testId:"cc-syscontrol-plugins-reload"},{key:"backup",icon:fw,title:r("systemControls.backupDb","Backup database"),description:r("systemControls.backupDbDesc","Create an integrity-checked backup of the database now."),cta:r("systemControls.backupDbCta","Backup now"),disabled:!1,run:()=>void Ne(),testId:"cc-syscontrol-backup"},{key:"diagnostics",icon:$j,title:r("systemControls.copyDiagnostics","Copy diagnostics"),description:r("systemControls.copyDiagnosticsDesc","Copy a JSON bundle with health, runtime info and recent logs."),cta:r("systemControls.copyDiagnosticsCta","Copy"),disabled:!1,run:()=>void le(),testId:"cc-syscontrol-diagnostics"}],[He,J,oe,Y,Ne,Ce,le,L,ne,Re,a,$,de,k,Le,Oe,r]),pa=v?v.status==="running"?r("systemControls.jobRunning","Running…"):v.status==="succeeded"?r("systemControls.jobSucceeded","Succeeded"):r("systemControls.jobFailed","Failed"):null,ks=v?.kind==="fn-binary"&&v.scope==="link-local"?r("systemControls.fnLinkLocalOutput","Local fn build output"):v?.kind==="fn-binary"&&v.scope==="use-global"?r("systemControls.fnUseGlobalOutput","Global npm install output"):r("systemControls.rebuildOutput","Rebuild output");return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"cc-area-section","data-testid":"cc-system-controls",children:[s.jsxs("div",{className:"cc-area-section-header cc-system-controls-header",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("systemControls.title","System controls")}),s.jsx("button",{type:"button",className:"btn-icon","data-testid":"cc-system-refresh",onClick:()=>void q(),title:r("systemControls.refresh","Refresh capabilities"),"aria-label":r("systemControls.refresh","Refresh capabilities"),children:s.jsx(Gt,{size:16})})]}),o?s.jsx("p",{className:"cc-system-note cc-system-note--error",role:"status",children:r("systemControls.infoError","Failed to load system info: {{error}}",{error:o})}):null,w==="waiting"?s.jsxs("div",{className:"cc-syscontrols-banner cc-syscontrols-banner--waiting",role:"status","data-testid":"cc-system-restart-waiting",children:[s.jsx(Gt,{size:16,className:"spin"}),s.jsx("span",{children:r("systemControls.restartWaiting","Restarting server — waiting for it to come back…")})]}):null,w==="back"?s.jsxs("div",{className:"cc-syscontrols-banner cc-syscontrols-banner--back",role:"status","data-testid":"cc-system-restart-back",children:[s.jsx("span",{children:r("systemControls.restartBack","Server is back online — reloading…")}),s.jsx("button",{type:"button",className:"btn",onClick:()=>window.location.reload(),children:r("systemControls.reloadNow","Reload now")})]}):null,w==="timeout"?s.jsxs("div",{className:"cc-syscontrols-banner cc-syscontrols-banner--error",role:"status","data-testid":"cc-system-restart-timeout",children:[s.jsx("span",{children:r("systemControls.restartTimeout","The server did not come back within the expected time. It may still be restarting, or the restart may have stopped it.")}),s.jsx("button",{type:"button",className:"btn",onClick:()=>window.location.reload(),children:r("systemControls.reloadNow","Reload now")})]}):null,K&&!K.error?s.jsx("div",{className:`cc-syscontrols-banner ${K.updateAvailable?"cc-syscontrols-banner--back":""}`,role:"status","data-testid":"cc-system-update-check-result",children:s.jsx("span",{children:K.disabled?r("systemControls.updatesDisabled","Update checks are disabled in global settings"):K.updateAvailable&&K.latestVersion?r("systemControls.updateAvailable","Update available: v{{version}} (current: v{{current}})",{version:K.latestVersion,current:K.currentVersion}):r("systemControls.upToDate","You're up to date (v{{version}})",{version:K.currentVersion})})}):null,s.jsxs("div",{className:"cc-syscontrols-grid",children:[Nt.filter(R=>!("hidden"in R&&R.hidden)).map(R=>s.jsxs("div",{className:"card cc-syscontrol-card","data-testid":R.testId,children:[s.jsxs("div",{className:"cc-syscontrol-head",children:[s.jsx(R.icon,{size:18,className:"cc-syscontrol-icon","aria-hidden":!0}),s.jsx("span",{className:"cc-syscontrol-title",children:R.title})]}),s.jsx("p",{className:"cc-syscontrol-desc",children:R.description}),R.note?s.jsx("p",{className:"cc-syscontrol-note",children:R.note}):null,s.jsx("button",{type:"button",className:"btn cc-syscontrol-cta",disabled:R.disabled||c!==null||w==="waiting",onClick:R.run,children:c===R.key?r("systemControls.working","Working…"):R.cta})]},R.key)),s.jsxs("div",{className:"card cc-syscontrol-card","data-testid":"cc-syscontrol-report-bug",children:[s.jsxs("div",{className:"cc-syscontrol-head",children:[s.jsx(ew,{size:18,className:"cc-syscontrol-icon","aria-hidden":!0}),s.jsx("span",{className:"cc-syscontrol-title",children:r("systemControls.reportBug","Report")})]}),s.jsx("p",{className:"cc-syscontrol-desc",children:r("systemControls.reportBugDesc","Report a bug, send feedback, share an idea, or get help through a guided prompt.")}),s.jsx("div",{className:"cc-syscontrol-cta",children:s.jsx(tw,{onSelect:m})})]})]}),u?s.jsx(rw,{actionType:u,contextRefs:h,onClose:()=>m(null)}):null]}),v?s.jsxs("div",{ref:C,className:"cc-area-section","data-testid":"cc-system-rebuild-output",children:[s.jsxs("div",{className:"cc-area-section-header",children:[s.jsx("h3",{className:"cc-area-section-title",children:ks}),s.jsx("span",{className:`cc-syscontrols-job-status cc-syscontrols-job-status--${v.status}`,children:pa})]}),(b[0]?.i??0)>0?s.jsx("p",{className:"cc-system-note","data-testid":"cc-system-rebuild-output-truncated",children:r("systemControls.jobOutputTruncated","Showing the most recent {{count}} lines — earlier output trimmed",{count:Tn})}):null,s.jsx("pre",{ref:j,className:"cc-syscontrols-output","aria-live":"polite",onScroll:G,children:b.map(R=>`${R.stream==="stderr"?"! ":""}${R.text}`).join(`
99
- `)}),v.status==="failed"&&v.error?s.jsx("p",{className:"cc-system-note cc-system-note--error",children:v.error}):null]}):null,s.jsxs("div",{className:"cc-area-section","data-testid":"cc-system-logs",children:[s.jsxs("div",{className:"cc-area-section-header",children:[s.jsxs("h3",{className:"cc-area-section-title cc-system-section-title-with-icon",children:[s.jsx(gw,{size:16}),s.jsx("span",{children:r("systemControls.serverLogs","Server logs")})]}),s.jsx("button",{type:"button",className:"btn",disabled:a?!a.logsSupported:!1,onClick:()=>z(R=>!R),"data-testid":"cc-system-logs-toggle",children:I?r("systemControls.hideLogs","Hide logs"):r("systemControls.viewLogs","View logs")})]}),a&&!a.logsSupported?s.jsx("p",{className:"cc-system-note",children:r("systemControls.logsUnavailable","Host-process logs are not available in this mode.")}):null,I&&a?.logsSupported?s.jsxs("div",{ref:B,className:"cc-syscontrols-output cc-syscontrols-logs","aria-live":"polite",onScroll:M,children:[D.map((R,ce)=>s.jsxs("div",{className:`cc-syscontrols-log-line cc-syscontrols-log-line--${R.level}`,children:[s.jsx("span",{className:"cc-syscontrols-log-time",children:I2(R.timestamp)}),R.prefix?s.jsxs("span",{className:"cc-syscontrols-log-prefix",children:["[",R.prefix,"]"]}):null,s.jsx("span",{className:"cc-syscontrols-log-message",children:R.message})]},`${R.timestamp}-${ce}`)),D.length===0?s.jsx("div",{className:"cc-syscontrols-log-line",children:r("systemControls.noLogs","No log entries yet.")}):null]}):null]})]})}function R2(e,t){if(!Number.isFinite(e)||e<=0)return 0;const r=Number.isFinite(t)&&t>0?t:1;return Math.max(0,Math.min(100,e/r*100))}function L2(e,t){return t===null?null:!Number.isFinite(t)||t<=0?"—":`${Math.max(0,Math.min(100,e/t*100)).toFixed(0)}%`}function qx({stages:e,ariaLabel:t}){const r=e.reduce((n,a)=>a.value>n?a.value:n,0);return s.jsx("ol",{className:"cc-funnel","aria-label":t,children:e.map((n,a)=>{const i=R2(n.value,r),o=a>0?e[a-1].value:null,l=L2(n.value,o),c=String(Number.isFinite(n.value)?n.value:0);return s.jsxs("li",{className:"cc-funnel-stage",children:[s.jsxs("div",{className:"cc-funnel-header",children:[s.jsx("span",{className:"cc-funnel-label",children:n.label}),l!==null?s.jsx("span",{className:"cc-funnel-conversion",children:l}):null]}),s.jsx("div",{className:"cc-funnel-track",children:s.jsx("div",{className:"cc-funnel-fill",style:{width:`${i}%`},role:"img","aria-label":`${n.label}: ${c}`})}),s.jsx("span",{className:"cc-funnel-value",children:c})]},n.label)})})}function Wx(e){const t=e.trim().toLowerCase();return t==="in-progress"||t==="in progress"||t==="doing"}function $2(e){return(e??[]).reduce((t,r)=>t+(Wx(r.column)?r.count:0),0)}function F2(e){return(e?.activeSessions??0)+(e?.activeRuns??0)}const B2=5e3,z2=3e4,K2=["session:updated","session:completed","run:created","run:updated","run:completed","run:cancelled","run:failed","agent:stateChanged","task:moved","task:updated","task:created","task:deleted"],V2=new Set(["triage","signal","backlog"]),Xo=[{id:"triage",match:e=>V2.has(e)},{id:"todo",match:e=>e==="todo"||e==="to-do"||e==="to do"||e==="ready"},{id:"in-progress",match:Wx},{id:"in-review",match:e=>e==="in-review"||e==="in review"||e==="review"},{id:"done",match:e=>e==="done"||e==="complete"||e==="completed"||e==="shipped"}];function Hx(e){const[t,r]=f.useState(null),[n,a]=f.useState(!0),[i,o]=f.useState(null),[l,c]=f.useState(!1),d=f.useRef(null),u=f.useRef(null),m=f.useRef(Symbol("no-live-snapshot-request")),h=f.useRef(m.current),{capture:v}=Bj(e,"useLiveSnapshot"),p=f.useCallback(()=>{u.current!==null&&(clearInterval(u.current),u.current=null,c(!1))},[]),b=f.useCallback(async()=>{const g=v(),j=g.projectIdAtStart;if(h.current!==j){h.current=j;try{const x=await fr(mr("/command-center/live",j));if(g.isStale())return;d.current=x,r(x),o(null)}catch(x){if(g.isStale())return;o(x instanceof Error?x.message:"Failed to load live snapshot")}finally{if(h.current===j&&(h.current=m.current),!g.isStale()){a(!1);const x=d.current;(typeof document>"u"||document.visibilityState!=="hidden")&&!!x&&(x.activeSessions>0||x.activeRuns>0)?u.current===null&&(u.current=setInterval(()=>{b()},B2),c(!0)):p()}}}},[v,p]);f.useEffect(()=>{d.current=null,r(null),a(!0),o(null),b();const g=qa("/api/events",{events:Object.fromEntries(K2.map(x=>[x,()=>void b()])),onReconnect:()=>void b()}),j=()=>{if(document.visibilityState==="hidden"){p();return}b()};return typeof document<"u"&&document.addEventListener("visibilitychange",j),()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",j),g(),p()}},[b,e,p]);const y=f.useCallback(()=>{b()},[b]);return{snapshot:t,isLoading:n,error:i!==null&&t===null?i:null,polling:l,reload:y}}function U2(e){const t=e.split(/[/\\]/).filter(Boolean);return t.length>0?t[t.length-1]:e}function q2(e,t){const r=Date.parse(t),n=new Map;for(const a of e){if(!a.worktreePath)continue;const i=n.get(a.worktreePath)??{count:0,freshestMs:0},o=Date.parse(a.updatedAt);n.set(a.worktreePath,{count:i.count+1,freshestMs:Number.isFinite(o)?Math.max(i.freshestMs,o):i.freshestMs})}return Array.from(n.entries()).map(([a,i])=>{const o=Number.isFinite(r)&&i.freshestMs>0?r-i.freshestMs:0;return{path:a,label:U2(a),sessionCount:i.count,inactive:o>z2}}).sort((a,i)=>i.sessionCount-a.sessionCount)}function W2(e,t){const r=new Map;for(const i of Xo)r.set(i.id,0);let n=0;for(const i of e){const o=i.column.trim().toLowerCase(),l=Xo.find(c=>c.match(o));l?r.set(l.id,(r.get(l.id)??0)+i.count):n+=i.count}const a=Xo.map(i=>({label:t(`commandCenter.missionControl.stage.${i.id}`,i.id),value:r.get(i.id)??0}));return n>0&&a.push({label:t("commandCenter.missionControl.stage.other","Other"),value:n}),a}function H2({projectId:e}={}){const{t}=se("app"),{snapshot:r,isLoading:n,error:a}=Hx(e),i=f.useMemo(()=>r?.sessions??[],[r?.sessions]),o=f.useMemo(()=>r?q2(r.sessions,r.capturedAt):[],[r]),l=f.useMemo(()=>r?W2(r.columns,t):[],[r,t]);if(n&&!r)return s.jsxs("div",{className:"cc-loading-inline","data-testid":"mission-control-loading",children:[s.jsx(Ql,{size:18,className:"spin"}),s.jsx("span",{children:t("commandCenter.missionControl.loading","Loading live activity…")})]});if(a!==null)return s.jsxs("div",{className:"cc-area-error","data-testid":"mission-control-error",role:"alert",children:[s.jsx(Mi,{size:22}),s.jsx("p",{children:a})]});const c=(r?.activeSessions??0)>0||(r?.activeRuns??0)>0;return s.jsxs("div",{className:"cc-mission-control","data-testid":"mission-control",children:[s.jsxs("div",{className:"cc-stat-grid","data-testid":"mission-control-summary",children:[s.jsxs("div",{className:"card cc-stat-card","data-testid":"mission-control-active-sessions",children:[s.jsx("div",{className:"cc-stat-label",children:t("commandCenter.missionControl.activeSessions","Active sessions")}),s.jsx("div",{className:"cc-stat-value",children:r?.activeSessions??0})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"mission-control-active-runs",children:[s.jsx("div",{className:"cc-stat-label",children:t("commandCenter.missionControl.activeRuns","Active runs")}),s.jsx("div",{className:"cc-stat-value",children:r?.activeRuns??0})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"mission-control-active-nodes",children:[s.jsx("div",{className:"cc-stat-label",children:t("commandCenter.missionControl.activeNodes","Active nodes")}),s.jsx("div",{className:"cc-stat-value",children:r?.activeNodes??0})]})]}),c?null:s.jsxs("div",{className:"cc-area-empty","data-testid":"mission-control-idle",children:[s.jsx(Fj,{size:24}),s.jsx("p",{children:t("commandCenter.missionControl.idle","No active sessions. Live updates resume when work starts.")})]}),s.jsxs("div",{className:"cc-mc-columns",children:[s.jsxs("section",{className:"cc-mc-section","data-testid":"mission-control-sessions",children:[s.jsx("h3",{className:"cc-area-section-title",children:t("commandCenter.missionControl.sessionsTitle","Sessions")}),i.length===0?s.jsx("p",{className:"cc-mc-muted","data-testid":"mission-control-sessions-empty",children:t("commandCenter.missionControl.noSessions","No active sessions.")}):s.jsx("ul",{className:"cc-mc-list",children:i.map(d=>s.jsxs("li",{className:"cc-mc-session","data-testid":`mission-control-session-${d.id}`,children:[s.jsx("span",{className:"cc-mc-session-purpose",children:d.purpose||d.adapterId}),s.jsxs("span",{className:"cc-mc-session-meta",children:[s.jsx("span",{className:"cc-mc-badge",children:d.agentState}),d.taskId?s.jsx("span",{className:"cc-mc-task",children:d.taskId}):null]})]},d.id))})]}),s.jsxs("section",{className:"cc-mc-section","data-testid":"mission-control-nodes",children:[s.jsx("h3",{className:"cc-area-section-title",children:t("commandCenter.missionControl.nodesTitle","Nodes")}),o.length===0?s.jsx("p",{className:"cc-mc-muted","data-testid":"mission-control-nodes-empty",children:t("commandCenter.missionControl.noNodes","No active nodes.")}):s.jsx("ul",{className:"cc-mc-list",children:o.map(d=>s.jsxs("li",{className:`cc-mc-node${d.inactive?" inactive":""}`,"data-testid":`mission-control-node-${d.label}`,"data-inactive":d.inactive?"true":"false",children:[s.jsx("span",{className:"cc-mc-node-label",children:d.label}),s.jsxs("span",{className:"cc-mc-node-meta",children:[d.inactive?s.jsx("span",{className:"cc-mc-badge inactive",children:t("commandCenter.missionControl.inactive","inactive")}):null,s.jsx("span",{className:"cc-mc-node-count",children:t("commandCenter.missionControl.sessionCount","{{count}} session",{count:d.sessionCount})})]})]},d.path))})]})]}),s.jsxs("section",{className:"cc-mc-section","data-testid":"mission-control-funnel",children:[s.jsx("h3",{className:"cc-area-section-title",children:t("commandCenter.missionControl.funnelTitle","SDLC funnel (live)")}),s.jsx(qx,{stages:l,ariaLabel:t("commandCenter.missionControl.funnelTitle","SDLC funnel (live)")})]})]})}const G2=500,Mn={maxConcurrent:As.maxConcurrent,maxWorktrees:As.maxWorktrees,worktreeLimitEnabled:!!As.worktreeLimitEnabled},Yr={maxConcurrent:{min:1,max:50},maxWorktrees:{min:1,max:50}},Gx={maxConcurrent:{key:"commandCenter.controls.concurrency.maxConcurrent",defaultValue:"Max concurrent tasks"},maxWorktrees:{key:"commandCenter.controls.concurrency.maxWorktrees",defaultValue:"Max worktrees"}};function Xx(e,t,r){return Math.min(r,Math.max(t,e))}function Yo(e,t){return Math.max(Yr[e].max,t)}function X2(e,t,r,n){return n<=r?0:Xx((Math.min(e,t)-r)/(n-r),0,1)}function Y2(e){return{"--use-pct":`${e*100}%`,"--use-offset":`calc((var(--cc-controls-range-thumb-size) / 2) + ((100% - var(--cc-controls-range-thumb-size)) * ${e}))`}}function Z2(e,t){return Object.keys(Gx).filter(r=>e[r]!==t[r])}function J2({paused:e,label:t}){return s.jsxs("span",{className:"cc-controls-status-pill",children:[s.jsx("span",{className:`status-dot ${e?"status-dot--pending":"status-dot--online"}`,"aria-hidden":"true"}),s.jsx("span",{children:t})]})}function Q2({projectId:e,colorTheme:t,themeMode:r,shadcnCustomColors:n={},resolvedThemeMode:a=r==="light"?"light":"dark",onColorThemeChange:i,onThemeModeChange:o,onShadcnCustomColorsChange:l=()=>{},onChangeView:c}){const{t:d}=se("app"),{confirm:u}=tc(),{globalPaused:m,toggleGlobalPause:h,refresh:v}=Oh(e),[p,b]=f.useState({status:"loading",data:null,error:null}),[y,g]=f.useState(!1),[j,x]=f.useState("idle"),C=f.useRef(Mn),w=f.useRef(null),P=f.useRef(!1),A=zj();f.useEffect(()=>{let B=!1;return g(!1),x("idle"),b({status:"loading",data:null,error:null}),(async()=>{try{const[W,K]=await Promise.all([Kj(e),Eh(e)]);if(!B){const te={maxConcurrent:K.maxConcurrent??W.maxConcurrent??Mn.maxConcurrent,maxWorktrees:K.maxWorktrees??Mn.maxWorktrees,worktreeLimitEnabled:K.worktreeLimitEnabled!==!1};C.current=te,w.current=null,P.current=!1,b({status:"loaded",data:te,error:null})}}catch(W){B||b({status:"error",data:C.current,error:W instanceof Error?W.message:d("commandCenter.controls.concurrency.error","Unable to load concurrency settings")})}})(),()=>{B=!0}},[e,d]),f.useEffect(()=>{if(!y||!p.data||P.current)return;const B=p.data,W=setTimeout(()=>{const K=C.current,te=Z2(B,K);if(te.length===0){g(!1),w.current=null;return}P.current=!0;const G=te.map(q=>{const H=Gx[q];return d("commandCenter.controls.concurrency.confirmChangeSummaryItem","{{setting}} from {{oldValue}} to {{newValue}}",{setting:d(H.key,H.defaultValue),oldValue:K[q],newValue:B[q]})}),M=te.length===1?d("commandCenter.controls.concurrency.confirmMessage","Change {{setting}}?",{setting:G[0]}):d("commandCenter.controls.concurrency.confirmMultipleMessage","Change these concurrency settings: {{settings}}?",{settings:G.join("; ")});u({title:d("commandCenter.controls.concurrency.confirmTitle","Confirm concurrency change"),message:M,confirmLabel:d("commandCenter.controls.concurrency.confirmSave","Save change"),cancelLabel:d("commandCenter.controls.concurrency.confirmCancel","Cancel")}).then(q=>{if(P.current=!1,!q){b({status:"loaded",data:C.current,error:null}),g(!1),w.current=null,x("idle");return}x("saving"),_h(B,e).then(async()=>{await v(),C.current=B,g(!1),w.current=null,x("saved")}).catch(()=>{x("error")})})},G2);return()=>clearTimeout(W)},[u,y,p.data,e,v,d]);const S=(B,W,K,te)=>{const G=Xx(Number(W),K,te);w.current=B,b(M=>({status:"loaded",data:{...M.data??Mn,[B]:G},error:null})),g(!0),x("idle")},N=m,E=p.data??Mn,T=A.status==="loaded",O=A.projectActiveCount(e),I=Yo("maxConcurrent",E.maxConcurrent),z=p.status==="loaded"&&E.worktreeLimitEnabled,D=p.status==="loaded",V=X2(O,E.maxConcurrent,Yr.maxConcurrent.min,I);return s.jsx("section",{className:"cc-controls","data-testid":"command-center-controls","aria-label":d("commandCenter.controls.title","Operator controls"),children:s.jsxs("div",{className:"cc-controls-grid",children:[s.jsxs("section",{className:"card cc-controls-card","data-testid":"cc-controls-engine",children:[s.jsxs("div",{className:"cc-controls-card-header",children:[s.jsxs("div",{children:[s.jsx("h3",{children:d("commandCenter.controls.engine.title","AI engine")}),s.jsx("p",{children:d("commandCenter.controls.engine.description","Stopping the engine halts all AI work.")})]}),s.jsx(J2,{paused:N,label:N?d("commandCenter.controls.status.stopped","Stopped"):d("commandCenter.controls.status.running","Running")})]}),s.jsxs("button",{type:"button",className:"btn btn-secondary cc-controls-action",onClick:()=>void h(),children:[s.jsx(Mh,{size:16,"aria-hidden":"true"}),s.jsx("span",{children:N?d("header.startAiEngine","Start AI Engine"):d("header.stopAiEngine","Stop AI Engine")})]}),c?s.jsxs("div",{className:"cc-overview-engine-nav","data-testid":"command-center-engine-panel",children:[s.jsx("button",{type:"button",className:"btn btn-secondary cc-overview-engine-nav-btn",onClick:()=>c("board"),children:d("commandCenter.controls.engine.viewBoard","View Board")}),s.jsx("button",{type:"button",className:"btn btn-secondary cc-overview-engine-nav-btn",onClick:()=>c("agents"),children:d("commandCenter.controls.engine.viewAgents","View Agents")})]}):null]}),s.jsxs("section",{className:"card cc-controls-card","data-testid":"cc-controls-theme",children:[s.jsx("div",{className:"cc-controls-card-header",children:s.jsxs("div",{children:[s.jsx("h3",{children:d("commandCenter.controls.theme.title","Theme")}),s.jsx("p",{children:d("commandCenter.controls.theme.description","Switch the dashboard theme with live color previews.")})]})}),s.jsx(nw,{colorTheme:t,themeMode:r,shadcnCustomColors:n,resolvedThemeMode:a,onColorThemeChange:i,onThemeModeChange:o,onShadcnCustomColorsChange:l})]}),s.jsxs("section",{className:"card cc-controls-card cc-controls-card--concurrency","data-testid":"cc-controls-concurrency",children:[s.jsxs("div",{className:"cc-controls-card-header",children:[s.jsxs("div",{children:[s.jsx("h3",{children:d("commandCenter.controls.concurrency.title","Concurrency")}),s.jsx("p",{children:d("commandCenter.controls.concurrency.description","Tune live scheduler capacity.")})]}),s.jsx("span",{className:`cc-controls-save-state cc-controls-save-state--${j}`,"aria-live":"polite",children:p.status==="loading"?d("commandCenter.controls.status.loading","Loading…"):j==="saving"?d("commandCenter.controls.status.saving","Saving…"):j==="saved"?d("commandCenter.controls.status.saved","Saved"):j==="error"?d("commandCenter.controls.status.saveError","Save failed"):d("commandCenter.controls.status.ready","Ready")})]}),s.jsxs("div",{className:"cc-controls-sliders",children:[s.jsxs("label",{className:"cc-controls-slider",htmlFor:"cc-max-concurrent",children:[s.jsxs("span",{className:"cc-controls-slider-label",children:[d("commandCenter.controls.concurrency.maxConcurrent","Max concurrent tasks"),s.jsx("strong",{children:E.maxConcurrent})]}),T?s.jsxs(s.Fragment,{children:[s.jsx("small",{className:"cc-controls-slider-caption","data-testid":"cc-project-running",children:d("commandCenter.controls.concurrency.runningProject","{{count}} running (this project)",{count:O})}),s.jsx("small",{className:"cc-controls-slider-caption","data-testid":"cc-global-running",children:d("commandCenter.controls.concurrency.runningGlobal","{{count}} running (all projects)",{count:A.currentlyActive})})]}):null,s.jsxs("span",{className:"cc-controls-range-wrap",children:[s.jsx("input",{id:"cc-max-concurrent",className:"cc-controls-touch-slider",type:"range",min:Yr.maxConcurrent.min,max:I,value:E.maxConcurrent,disabled:!D,onChange:B=>S("maxConcurrent",B.target.value,Yr.maxConcurrent.min,I)}),T?s.jsx("span",{className:"status-dot status-dot--online cc-controls-use-marker",style:Y2(V),"data-testid":"cc-project-use-marker","aria-hidden":"true"}):null]})]}),s.jsxs("label",{className:"cc-controls-slider",htmlFor:"cc-max-worktrees",children:[s.jsxs("span",{className:"cc-controls-slider-label",children:[d("commandCenter.controls.concurrency.maxWorktrees","Max worktrees"),s.jsx("strong",{children:E.maxWorktrees})]}),s.jsx("span",{className:"cc-controls-range-wrap",children:s.jsx("input",{id:"cc-max-worktrees",className:"cc-controls-touch-slider",type:"range",min:Yr.maxWorktrees.min,max:Yo("maxWorktrees",E.maxWorktrees),value:E.maxWorktrees,disabled:!z,onChange:B=>S("maxWorktrees",B.target.value,Yr.maxWorktrees.min,Yo("maxWorktrees",E.maxWorktrees))})}),!E.worktreeLimitEnabled&&p.status==="loaded"?s.jsx("small",{className:"cc-controls-slider-caption",children:d("commandCenter.controls.concurrency.worktreeLimitDisabled","Enable the worktree limit in Settings to edit this capacity.")}):null]})]}),p.status==="error"?s.jsx("p",{className:"cc-controls-error",role:"alert",children:p.error}):null]})]})})}function wh(e){return`${(e*100).toFixed(1)}%`}function Ch(e){return e===null?"—":`${(e/6e4).toFixed(1)}m`}function Ia(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function eF({projectId:e}={}){const{t}=se("app"),[r,n]=f.useState(null),[a,i]=f.useState(!0),[o,l]=f.useState(null),[c,d]=f.useState(!1),[u,m]=f.useState(!1),[h,v]=f.useState(null),p=f.useCallback(async()=>{i(!0),l(null);try{const T=await fr(mr("/health/reliability",e));n(T)}catch(T){l(T instanceof Error?T.message:t("reliability.failedToLoad","Failed to load reliability metrics"))}finally{i(!1)}},[t,e]),b=f.useCallback(async()=>{v(null),await fr(mr("/health/reliability/reset",e),{method:"POST"}),await p(),m(!1)},[p,e]);f.useEffect(()=>{p();const T=setInterval(()=>{p()},6e4);return()=>clearInterval(T)},[p]);const y=r?.headline.inReviewFailureRate7d,g=f.useMemo(()=>y==null?null:Math.max(0,Math.min(1,1-y)),[y]),j=f.useMemo(()=>g===null?"var(--text-muted)":g>=.95?"var(--color-success)":g>=.9?"var(--color-warning)":"var(--color-error)",[g]),x=f.useMemo(()=>(r?.perDay??[]).reduce((T,O)=>T+O.tasksEnteredInReview,0),[r?.perDay]),C=f.useMemo(()=>(r?.perDay??[]).reduce((T,O)=>T+O.tasksBouncedToInProgress,0),[r?.perDay]),w=f.useMemo(()=>r?.perDay?[...c?r.perDay:r.perDay.filter(O=>O.hasSamples!==!1)].sort((O,I)=>O.date.localeCompare(I.date)):[],[r?.perDay,c]),P=f.useMemo(()=>w.some(O=>O.tasksEnteredInReview>0||O.tasksBouncedToInProgress>0)?[{label:t("reliability.flowChart.entered","Entered"),values:w.map(O=>O.tasksEnteredInReview)},{label:t("reliability.flowChart.bounced","Bounced"),values:w.map(O=>O.tasksBouncedToInProgress)}]:[],[w,t]),A=f.useMemo(()=>Object.entries(r?.mergeAttempts.histogram??{}).sort(([T],[O])=>T.localeCompare(O,void 0,{numeric:!0})),[r?.mergeAttempts.histogram]),S=f.useMemo(()=>A.map(([T,O])=>({label:T,value:O})),[A]),N=f.useMemo(()=>A.reduce((T,[,O])=>T+O,0),[A]),E=r?Ia(r.resetAt??new Date(Date.parse(r.generatedAt)-r.windowDays*864e5).toISOString()):"—";return a&&r===null?s.jsxs("div",{className:"reliability-loading","data-testid":"reliability-loading",children:[s.jsx(Ql,{size:24,className:"spin"}),s.jsx("p",{children:t("reliability.loading","Loading reliability data...")})]}):o!==null&&r===null?s.jsxs("div",{className:"reliability-error","data-testid":"reliability-error",role:"alert",children:[s.jsx(Mi,{size:24}),s.jsx("p",{children:o})]}):s.jsxs("section",{className:"reliability-view",children:[s.jsxs("div",{className:"card reliability-card reliability-headline-card",children:[s.jsxs("div",{className:"reliability-section-header",children:[s.jsx("h2",{children:t("reliability.heading","Reliability")}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>m(!0),children:t("reliability.resetStats","Reset stats")})]}),s.jsx("div",{className:"reliability-headline",style:{color:j},children:y==null?t("reliability.insufficientData","Insufficient data — {{reason}}",{reason:r?.headline.reason??"unknown"}):wh(g??0)}),g!==null?s.jsx("div",{className:"reliability-muted",children:t("reliability.successRateLabel","In-review success rate (last 7d)")}):null,r?.resetAt?s.jsx("div",{className:"reliability-muted",children:t("reliability.countingSince","Counting since {{date}}",{date:Ia(r.resetAt)})}):null,s.jsxs("details",{className:"reliability-details",children:[s.jsx("summary",{children:t("reliability.details","Details")}),s.jsxs("div",{className:"reliability-details-content",children:[s.jsx("div",{children:t("reliability.bouncedEntered","{{bounced}} bounced / {{entered}} entered (last {{days}}d)",{bounced:C,entered:x,days:r?.windowDays??7})}),y!=null?s.jsx("div",{children:t("reliability.failureRate","Failure rate: {{rate}}",{rate:wh(y)})}):null,s.jsx("div",{children:t("reliability.window","Window: {{start}} → {{end}}",{start:E,end:Ia(r?.generatedAt)})}),r?.resetAt?s.jsx("div",{children:t("reliability.resetBaseline","Reset baseline: {{date}}",{date:Ia(r.resetAt)})}):null,r?.headline.reason?s.jsx("div",{children:t("reliability.reason","Reason: {{reason}}",{reason:r.headline.reason})}):null]})]})]}),s.jsxs("div",{className:"reliability-grid",children:[s.jsxs("div",{className:"card reliability-card",children:[s.jsxs("div",{className:"reliability-section-header",children:[s.jsx("h3",{children:t("reliability.inReviewFlow","In-review flow")}),s.jsx("button",{className:"btn btn-sm",onClick:()=>d(T=>!T),children:c?t("reliability.hideEmptyDays","Hide empty days"):t("reliability.showEmptyDays","Show empty days")})]}),s.jsxs("div",{className:"reliability-chart-section","data-testid":"reliability-flow-chart",children:[s.jsx("h4",{children:t("reliability.flowChart.heading","Entered vs bounced trend")}),s.jsx(br,{series:P,ariaLabel:t("reliability.flowChart.aria","In-review entered vs bounced per day"),emptyLabel:t("reliability.flowChart.empty","No in-review flow data")})]}),s.jsxs("table",{className:"reliability-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:t("reliability.table.date","Date")}),s.jsx("th",{children:t("reliability.table.entered","Entered")}),s.jsx("th",{children:t("reliability.table.bounced","Bounced")})]})}),s.jsx("tbody",{children:w.map(T=>s.jsxs("tr",{children:[s.jsx("td",{children:T.date}),s.jsx("td",{children:T.tasksEnteredInReview}),s.jsx("td",{children:T.tasksBouncedToInProgress})]},T.date))})]})]}),s.jsxs("div",{className:"card reliability-card",children:[s.jsx("h3",{children:t("reliability.duration.heading","Duration")}),s.jsxs("div",{className:"reliability-stat-row",children:[s.jsx("span",{children:t("reliability.duration.p50","P50")}),s.jsx("strong",{children:Ch(r?.duration.p50Ms??null)})]}),s.jsxs("div",{className:"reliability-stat-row",children:[s.jsx("span",{children:t("reliability.duration.p95","P95")}),s.jsx("strong",{children:Ch(r?.duration.p95Ms??null)})]}),s.jsx("div",{className:"reliability-muted",children:t("reliability.duration.samples","Samples: {{count}}",{count:r?.duration.sampleCount??0})}),s.jsxs("details",{className:"reliability-details",children:[s.jsx("summary",{children:t("reliability.duration.moreStats","More stats")}),s.jsxs("div",{className:"reliability-details-content",children:[s.jsx("div",{children:t("reliability.duration.p50Raw","P50 raw: {{value}} ms",{value:r?.duration.p50Ms??"—"})}),s.jsx("div",{children:t("reliability.duration.p95Raw","P95 raw: {{value}} ms",{value:r?.duration.p95Ms??"—"})}),s.jsx("div",{children:t("reliability.duration.sampleCount","Sample count: {{count}}",{count:r?.duration.sampleCount??0})}),r?.duration.reason?s.jsx("div",{children:t("reliability.duration.reason","Reason: {{reason}}",{reason:r.duration.reason})}):null]})]})]}),s.jsxs("div",{className:"card reliability-card",children:[s.jsx("h3",{children:t("reliability.mergeAttempts.heading","Merge attempts")}),s.jsxs("div",{className:"reliability-stat-row",children:[s.jsx("span",{children:t("reliability.mergeAttempts.mean","Mean")}),s.jsx("strong",{children:r?.mergeAttempts.mean?.toFixed(2)??"—"})]}),s.jsxs("div",{className:"reliability-stat-row",children:[s.jsx("span",{children:t("reliability.mergeAttempts.max","Max")}),s.jsx("strong",{children:r?.mergeAttempts.max??"—"})]}),s.jsxs("div",{className:"reliability-chart-section","data-testid":"reliability-merge-attempts-chart",children:[s.jsx("h4",{children:t("reliability.mergeAttemptsChart.heading","Attempts distribution")}),s.jsx(Mt,{data:S,ariaLabel:t("reliability.mergeAttemptsChart.aria","Merge attempts histogram"),emptyLabel:t("reliability.mergeAttemptsChart.empty","No merge attempt data")})]}),s.jsx("ul",{className:"reliability-histogram",children:A.map(([T,O])=>s.jsxs("li",{children:[s.jsx("span",{children:T}),s.jsx("div",{className:"reliability-histogram-bar-wrap",children:s.jsx("div",{className:"reliability-histogram-bar",style:{width:`${Math.min(O*20,100)}%`}})}),s.jsx("strong",{children:O})]},T))}),s.jsxs("details",{className:"reliability-details",children:[s.jsx("summary",{children:t("reliability.mergeAttempts.moreStats","More stats")}),s.jsxs("div",{className:"reliability-details-content",children:[s.jsx("div",{children:t("reliability.mergeAttempts.tasksCounted","Tasks counted: {{count}}",{count:N})}),s.jsx("div",{children:t("reliability.mergeAttempts.histogramTotal","Histogram total: {{count}}",{count:N})}),r?.mergeAttempts.reason?s.jsx("div",{children:t("reliability.mergeAttempts.reason","Reason: {{reason}}",{reason:r.mergeAttempts.reason})}):null]})]})]})]}),u?s.jsx("div",{className:"modal-overlay open",role:"presentation",children:s.jsxs("div",{className:"modal",role:"dialog","aria-modal":"true","aria-labelledby":"reliability-reset-title",children:[s.jsx("div",{className:"modal-header",children:s.jsx("h2",{id:"reliability-reset-title",children:t("reliability.resetModal.title","Reset reliability stats?")})}),s.jsx("p",{children:t("reliability.resetModal.description","This sets a new baseline for reliability statistics. Historical events older than the reset time are excluded from counts but are not deleted.")}),h?s.jsx("div",{className:"form-error",children:h}):null,s.jsxs("div",{className:"modal-actions",children:[s.jsx("button",{className:"btn",onClick:()=>m(!1),children:t("common.cancel","Cancel")}),s.jsx("button",{className:"btn btn-danger",onClick:()=>{b().catch(T=>{v(T instanceof Error?T.message:t("reliability.resetModal.failedError","Failed to reset reliability stats"))})},children:t("reliability.resetModal.confirm","Confirm reset")})]})]})}):null]})}function Zo(e){const{lastSyncAt:t,remoteReachable:r,diff:n}=e,a=Object.values(n.workflowSettings).reduce((o,l)=>o+l.length,0),i=n.global.length+n.project.length+a;return t===null?{syncState:"never-synced",lastSyncAt:t,diffCount:0}:r?i>0?{syncState:"diff",lastSyncAt:t,diffCount:i}:{syncState:"synced",lastSyncAt:t,diffCount:0}:{syncState:"error",lastSyncAt:t,diffCount:i}}function Xl(e){if(e===null)return"Never synced";const t=new Date(e);if(Number.isNaN(t.getTime()))return"Never synced";const n=Date.now()-t.getTime(),a=Math.floor(n/1e3),i=Math.floor(a/60),o=Math.floor(i/60),l=Math.floor(o/24);return i<1?"Synced just now":i<60?`Synced ${i}m ago`:o<24?`Synced ${o}h ago`:`Synced ${l}d ago`}function tF(e){switch(e){case"synced":return"var(--color-success)";case"pending":return"var(--color-warning)";case"diff":return"var(--color-warning)";case"error":return"var(--color-error)";case"never-synced":return"var(--text-muted)"}}const rF=3e4;function nF(){const{t:e}=se("app"),[t,r]=f.useState({}),[n,a]=f.useState(!1),[i,o]=f.useState({}),[l,c]=f.useState(null),d=f.useRef(new Set),u=f.useRef(!1),m=f.useRef(null),[h,v]=f.useState(!0),p=f.useCallback(async(S,N)=>{try{const E=await Vj(S);r(T=>({...T,[S]:E})),c(null)}catch(E){if(E?.status===409){d.current.delete(S);return}console.error(`Failed to fetch sync status for node ${S}:`,E),c(E instanceof Error?E.message:e("nodeSync.error.failedToFetchStatus","Failed to fetch sync status"))}},[e]),b=f.useCallback(async()=>{const S=Array.from(d.current);if(S.length===0)return;m.current&&m.current.abort(),m.current=new AbortController;const N=!u.current;N&&a(!0),c(null);try{const E=await Promise.allSettled(S.map(O=>p(O,N)));u.current=!0,E.filter(O=>O.status==="rejected").length>0&&c(e("nodeSync.error.someRequestsFailed","Some sync status requests failed"))}catch(E){if(E instanceof Error&&E.name==="AbortError")return;c(E instanceof Error?E.message:e("nodeSync.error.failedToFetchStatus","Failed to fetch sync status")),u.current=!0}finally{a(!1)}},[p,e]),y=f.useCallback(()=>{v(!1)},[]);f.useEffect(()=>(b(),()=>{m.current&&m.current.abort()}),[b]),vn(b,rF,{enabled:h});const g=f.useCallback(S=>{d.current.has(S)||(d.current.add(S),p(S,!u.current))},[p]),j=f.useCallback(S=>{d.current.delete(S),r(N=>{const E={...N};return delete E[S],E}),d.current.size===0&&y()},[y]),x=f.useCallback(async S=>{o(N=>({...N,[S]:!0})),c(null);try{const N=await Uj(S);return p(S,!1),!N.success&&N.error&&c(N.error),N}catch(N){const E=N instanceof Error?N.message:e("nodeSync.error.pushFailed","Push settings failed");throw c(E),N}finally{o(N=>{const E={...N};return delete E[S],E})}},[p,e]),C=f.useCallback(async S=>{o(N=>({...N,[S]:!0})),c(null);try{const N=await qj(S);return p(S,!1),!N.success&&N.error&&c(N.error),N}catch(N){const E=N instanceof Error?N.message:e("nodeSync.error.pullFailed","Pull settings failed");throw c(E),N}finally{o(N=>{const E={...N};return delete E[S],E})}},[p,e]),w=f.useCallback(async S=>{o(N=>({...N,[S]:!0})),c(null);try{return await Wj(S)}catch(N){const E=N instanceof Error?N.message:e("nodeSync.error.authSyncFailed","Auth sync failed");throw c(E),N}finally{o(N=>{const E={...N};return delete E[S],E})}},[e]),P=f.useCallback(S=>t[S]?.authMatch,[t]),A=f.useCallback(S=>t[S]?.authDiff,[t]);return{syncStatusMap:t,loading:n,actionLoading:i,error:l,refresh:b,trackNode:g,untrackNode:j,pushSettings:x,pullSettings:C,syncAuth:w,getAuthSyncState:P,getAuthProviders:A}}const aF=1e4,iF=1e3;function sF(){const{t:e}=se("app"),[t,r]=f.useState([]),[n,a]=f.useState(!0),[i,o]=f.useState(null),l=f.useRef(0),c=f.useRef(t),d=nc();f.useEffect(()=>{c.current=t},[t]);const u=f.useCallback(h=>c.current.length>0&&ac(h,d.wasRecentlyHidden()),[d]),m=f.useCallback(async()=>{try{o(null);const h=await Ku();r(h.nodes)}catch(h){const v=h instanceof Error?h.message:e("mesh.failedToFetchMeshState","Failed to fetch mesh state");u(v)||o(v)}},[u,e]);return f.useEffect(()=>{let h=!1;async function v(){a(!0);try{const b=await Ku();h||(r(b.nodes),o(null))}catch(b){const y=b instanceof Error?b.message:e("mesh.failedToFetchMeshState","Failed to fetch mesh state");!h&&!u(y)&&o(y)}finally{h||a(!1)}}v();const p=()=>{if(document.visibilityState!=="visible")return;const b=Date.now(),y=b-l.current;if(y<iF){Wa({view:"useMeshState",trigger:"visibility",projectId:void 0,replayAttempted:!1,reason:"debounce-skipped",detail:{timeSinceLastRefreshMs:y}});return}l.current=b,Wa({view:"useMeshState",trigger:"visibility",projectId:void 0,replayAttempted:!1,reason:"debounced-refresh"}),m()};return document.addEventListener("visibilitychange",p),()=>{h=!0,document.removeEventListener("visibilitychange",p)}},[m,u,e]),vn(m,aF,{enabled:!n,refreshOnVisible:!1}),{meshState:t,loading:n,error:i,refresh:m}}const oF=1e4,lF=1e3;function cF(){const{t:e}=se("app"),[t,r]=f.useState([]),[n,a]=f.useState(!0),[i,o]=f.useState(null),l=f.useRef(null),c=f.useRef(0),d=f.useRef(t),u=nc();f.useEffect(()=>{d.current=t},[t]);const m=f.useCallback(v=>d.current.length>0&&ac(v,u.wasRecentlyHidden()),[u]),h=f.useCallback(async()=>{try{o(null);const v=await Vu();r(v.engines)}catch(v){const p=v instanceof Error?v.message:e("mesh.failedToFetchEngines","Failed to fetch engine status");m(p)||o(p)}},[m,e]);return f.useEffect(()=>{let v=!1;async function p(){a(!0);try{const y=await Vu();v||(r(y.engines),o(null))}catch(y){const g=y instanceof Error?y.message:e("mesh.failedToFetchEngines","Failed to fetch engine status");!v&&!m(g)&&o(g)}finally{v||a(!1)}}p();const b=()=>{if(document.visibilityState!=="visible")return;const y=Date.now();y-c.current<lF||(c.current=y,h())};return document.addEventListener("visibilitychange",b),()=>{v=!0,document.removeEventListener("visibilitychange",b)}},[h,m,e]),f.useEffect(()=>{if(!n)return l.current=setInterval(()=>{h()},oF),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[n,h]),{engines:t,loading:n,error:i,refresh:h}}function uF(e){return{online:{label:e("nodes.status.online","Online"),color:"var(--color-success)",className:"node-card__status--online"},offline:{label:e("nodes.status.offline","Offline"),color:"var(--color-error)",className:"node-card__status--offline"},connecting:{label:e("nodes.status.connecting","Connecting"),color:"var(--color-warning)",className:"node-card__status--connecting"},error:{label:e("nodes.status.error","Error"),color:"var(--color-error)",className:"node-card__status--error"},creating:{label:e("nodes.status.creating","Creating"),color:"var(--color-warning)",className:"node-card__status--creating"},recreating:{label:e("nodes.status.recreating","Recreating"),color:"var(--color-warning)",className:"node-card__status--recreating"},deleting:{label:e("nodes.status.deleting","Deleting"),color:"var(--color-error)",className:"node-card__status--deleting"},running:{label:e("nodes.status.running","Running"),color:"var(--color-success)",className:"node-card__status--online"},stopped:{label:e("nodes.status.stopped","Stopped"),color:"var(--color-error)",className:"node-card__status--offline"},exited:{label:e("nodes.status.exited","Exited"),color:"var(--color-error)",className:"node-card__status--offline"}}}const dF={match:"var(--color-success)",differs:"var(--color-warning)","not-synced":"var(--text-muted)"};function fF(e,t,r){if(e==="match")return r?r("nodes.auth.match","Auth credentials match"):"Auth credentials match";if(e==="not-synced")return r?r("nodes.auth.notSynced","Auth not synced"):"Auth not synced";if(t&&Object.keys(t).length>0){const n=Object.entries(t).filter(([,a])=>a==="differs").map(([a])=>a);if(n.length>0)return r?r("nodes.auth.differProviders","Auth credentials differ: {{providers}}",{providers:n.join(", ")}):`Auth credentials differ: ${n.join(", ")}`}return r?r("nodes.auth.differ","Auth credentials differ"):"Auth credentials differ"}function mF(e,t=42){return e.length<=t?e:`${e.slice(0,t-3)}...`}function vF(e,t){const r=e.node,n=t.node;if(r.id!==n.id||r.name!==n.name||r.type!==n.type||r.url!==n.url||r.status!==n.status||r.maxConcurrent!==n.maxConcurrent||r.updatedAt!==n.updatedAt||e.isLoading!==t.isLoading)return!1;const a=e.managedDockerNode,i=t.managedDockerNode;if(!!a!=!!i||a&&i&&(a.id!==i.id||a.status!==i.status||a.imageTag!==i.imageTag||a.updatedAt!==i.updatedAt))return!1;const o=e.syncStatus,l=t.syncStatus;if(!(!o&&!l)){if(!o||!l)return!1;if(o.syncState!==l.syncState||o.lastSyncAt!==l.lastSyncAt||o.diffCount!==l.diffCount)return!1}if(e.authSyncState!==t.authSyncState)return!1;const c=e.authSyncProviders,d=t.authSyncProviders;if(c!==d){if(!c||!d)return!1;{const h=Object.keys(c),v=Object.keys(d);if(h.length!==v.length||h.some(p=>c[p]!==d[p]))return!1}}const u=tl(e.projects,r),m=tl(t.projects,n);return u===m}function hF({node:e,projects:t,onHealthCheck:r,onEdit:n,onRemove:a,isLoading:i=!1,syncStatus:o,authSyncState:l,authSyncProviders:c,managedDockerNode:d}){const{t:u}=se("app"),[m,h]=f.useState(!1),v=uF(u),p=v[e.status]??v.offline,b=d?v[d.status]??v.error:null,y=d?.hostConfig.type==="remote"?u("nodes.dockerHost.remote","Remote: {{host}}",{host:d.hostConfig.host??"unknown"}):u("nodes.dockerHost.local","Local Docker"),g=f.useMemo(()=>tl(t,e),[t,e]),j=f.useCallback(()=>{n(e)},[n,e]),x=f.useCallback(A=>{A.stopPropagation(),r(e.id)},[r,e.id]),C=f.useCallback(A=>{A.stopPropagation(),n(e)},[n,e]),w=f.useCallback(A=>{if(A.stopPropagation(),!m){h(!0);return}a(e.id),h(!1)},[m,a,e.id]),P=f.useCallback(A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),n(e))},[n,e]);return s.jsxs("article",{className:`node-card ${i?"node-card--loading":""}`,"data-node-id":e.id,role:"button",tabIndex:0,onClick:j,onKeyDown:P,children:[s.jsx("header",{className:"node-card__header",children:s.jsxs("div",{className:"node-card__title-wrap",children:[s.jsx("div",{className:"node-card__icon",children:s.jsx(Ih,{size:18})}),s.jsxs("div",{children:[s.jsx("h3",{className:"node-card__name",title:e.name,children:e.name}),s.jsxs("div",{className:"node-card__meta-row",children:[s.jsx("span",{className:"node-card__type-badge",children:e.type==="local"?u("nodes.type.local","Local"):u("nodes.type.remote","Remote")}),d&&s.jsxs("span",{className:"node-card__docker-badge",title:u("nodes.dockerBadge","Managed Docker node"),children:[s.jsx(rl,{size:12,"aria-hidden":!0}),u("nodes.dockerLabel","Docker")]}),s.jsxs("span",{className:`node-card__status ${p.className}`,style:{color:p.color},"data-status":e.status,children:[s.jsx("span",{className:"node-card__status-indicator",style:{backgroundColor:p.color},"aria-hidden":!0}),p.label]}),d&&b&&s.jsxs("span",{className:`node-card__status ${b.className}`,style:{color:b.color},"data-status":d.status,children:[s.jsx("span",{className:"node-card__status-indicator",style:{backgroundColor:b.color},"aria-hidden":!0}),b.label]}),e.type==="remote"&&l&&s.jsx("span",{className:`node-card__auth-indicator node-card__auth-indicator--${l}`,title:fF(l,c,u),"aria-label":u("nodes.authSync.label","Auth sync: {{status}}",{status:l==="match"?u("nodes.authSync.match","credentials match"):l==="differs"?u("nodes.authSync.differ","credentials differ"):u("nodes.authSync.notSynced","not synced")}),style:{color:dF[l]},children:s.jsx(Dh,{size:14})})]})]})]})}),s.jsxs("div",{className:"node-card__body",children:[e.type==="remote"&&e.url&&s.jsx("div",{className:"node-card__url",title:e.url,children:mF(e.url)}),d&&s.jsxs("div",{className:"node-card__docker-meta",children:[s.jsxs("span",{title:`${d.imageName}:${d.imageTag}`,children:[d.imageName,":",d.imageTag]}),s.jsx("span",{title:y,children:y})]}),s.jsxs("div",{className:"node-card__metrics",children:[s.jsxs("div",{className:"node-card__metric",children:[s.jsx("span",{className:"node-card__metric-label",children:u("nodes.metrics.projects","Projects")}),s.jsx("span",{className:"node-card__metric-value",children:g})]}),s.jsxs("div",{className:"node-card__metric",children:[s.jsx("span",{className:"node-card__metric-label",children:u("nodes.metrics.concurrency","Concurrency")}),s.jsx("span",{className:"node-card__metric-value",children:e.maxConcurrent})]})]}),e.type==="remote"&&o&&s.jsxs("div",{className:"node-card__sync","data-sync-state":o.syncState,"data-testid":"node-card-sync",children:[s.jsx("span",{className:"node-card__sync-dot",style:{backgroundColor:tF(o.syncState)},"aria-hidden":!0}),s.jsx("span",{className:"node-card__sync-time",children:Xl(o.lastSyncAt)})]})]}),s.jsxs("footer",{className:"node-card__actions",children:[s.jsxs("button",{className:"btn btn-sm node-card__action",type:"button",onClick:x,disabled:i,"aria-label":u("nodes.actions.health.ariaLabel","Run node health check"),title:u("nodes.actions.health.title","Health Check"),children:[s.jsx(Rh,{size:14}),s.jsx("span",{children:u("nodes.actions.health.label","Health")})]}),s.jsxs("button",{className:"btn btn-sm node-card__action",type:"button",onClick:C,disabled:i,"aria-label":u("nodes.actions.edit.ariaLabel","Edit node"),title:u("nodes.actions.edit.title","Edit"),children:[s.jsx(La,{size:14}),s.jsx("span",{children:u("nodes.actions.edit.label","Edit")})]}),d&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{className:"btn btn-sm node-card__action",type:"button",disabled:!0,"aria-label":u("nodes.actions.start.ariaLabel","Start node container"),title:u("nodes.actions.start.title","Available after FN-3113"),children:[s.jsx(Di,{size:14}),s.jsx("span",{children:u("nodes.actions.start.label","Start")})]}),s.jsxs("button",{className:"btn btn-sm node-card__action",type:"button",disabled:!0,"aria-label":u("nodes.actions.stop.ariaLabel","Stop node container"),title:u("nodes.actions.stop.title","Available after FN-3113"),children:[s.jsx(Lh,{size:14}),s.jsx("span",{children:u("nodes.actions.stop.label","Stop")})]}),s.jsxs("button",{className:"btn btn-sm node-card__action",type:"button",disabled:!0,"aria-label":u("nodes.actions.restart.ariaLabel","Restart node container"),title:u("nodes.actions.restart.title","Available after FN-3113"),children:[s.jsx(Hj,{size:14}),s.jsx("span",{children:u("nodes.actions.restart.label","Restart")})]})]}),s.jsxs("button",{className:`btn btn-sm node-card__action node-card__action--remove ${m?"btn-danger is-armed":""}`,type:"button",onClick:w,disabled:i,"aria-label":m?u("nodes.actions.remove.ariaLabelConfirm","Confirm remove node"):u("nodes.actions.remove.ariaLabel","Remove node"),title:m?u("nodes.actions.remove.titleConfirm","Confirm remove"):u("nodes.actions.remove.title","Remove"),children:[s.jsx(tn,{size:14}),s.jsx("span",{children:m?u("nodes.actions.remove.labelConfirm","Confirm"):u("nodes.actions.remove.label","Remove")})]})]})]})}const pF=f.memo(hF,vF),In={online:"var(--success, var(--color-success))",offline:"var(--text-dim)",connecting:"var(--color-warning)",error:"var(--color-error)"},Da=28,yF=12,gF=300,bF=120;function xF({nodes:e,engines:t,className:r}){const{t:n}=se("app"),a=f.useMemo(()=>e.find(v=>v.nodeType==="local")??e[0],[e]),i=f.useMemo(()=>e.filter(v=>v.nodeId!==a?.nodeId),[e,a?.nodeId]),o=f.useMemo(()=>(t??[]).reduce((v,p)=>v+(p.inFlightTasks??0),0),[t]),l=f.useMemo(()=>(t??[]).reduce((v,p)=>v+(p.activeAgents??0),0),[t]),c=f.useMemo(()=>gF+Math.max(0,i.length-4)*20,[i.length]),d=c/2,u=c/2,m=f.useMemo(()=>{const v=new Map;if(a&&v.set(a.nodeId,{x:d,y:u,node:a}),i.length>0){const p=Math.min(bF,c/2-Da-10),b=2*Math.PI/i.length,y=-Math.PI/2;i.forEach((g,j)=>{const x=y+j*b;v.set(g.nodeId,{node:g,x:d+p*Math.cos(x),y:u+p*Math.sin(x)})})}return v},[d,u,a,i,c]),h=f.useMemo(()=>{const v=new Set,p=[];for(const b of e){const y=m.get(b.nodeId);if(y)for(const g of b.knownPeers){const j=m.get(g.peerNodeId);if(!j)continue;const x=[b.nodeId,g.peerNodeId].sort().join("::");v.has(x)||(v.add(x),p.push({key:x,from:y,to:j}))}}return p},[m,e]);return e.length===0?s.jsx("div",{className:`mesh-topology mesh-topology--empty ${r??""}`,children:s.jsx("div",{className:"mesh-topology__empty-state",children:s.jsx("p",{children:n("mesh.noNodes","No nodes to display")})})}):s.jsxs("div",{className:`mesh-topology ${r??""}`,children:[s.jsxs("svg",{className:"mesh-topology__svg",viewBox:`0 0 ${c} ${c}`,preserveAspectRatio:"xMidYMid meet","aria-label":n("mesh.ariaLabel","Node mesh topology visualization"),children:[h.map(v=>s.jsx("line",{className:"mesh-topology__link mesh-topology__peer-line",x1:v.from.x,y1:v.from.y,x2:v.to.x,y2:v.to.y},v.key)),Array.from(m.values()).map(({node:v,x:p,y:b})=>s.jsxs("g",{className:"mesh-topology__node",transform:`translate(${p}, ${b})`,children:[s.jsx("circle",{className:"mesh-topology__node-circle",r:Da,fill:In[v.status],"aria-label":`${v.nodeName} (${v.status})`}),s.jsx("text",{className:"mesh-topology__node-label",y:Da+yF,textAnchor:"middle",children:v.nodeName.length>12?`${v.nodeName.slice(0,10)}…`:v.nodeName}),s.jsxs("g",{className:"mesh-topology__node-type",transform:`translate(0 ${-Da-10})`,children:[s.jsx("circle",{className:"mesh-topology__node-type-badge",r:"8"}),s.jsx("text",{className:"mesh-topology__node-type-text",textAnchor:"middle",dominantBaseline:"middle",children:v.nodeType==="local"?"L":"R"})]})]},v.nodeId))]}),(t??[]).length>0&&s.jsxs("div",{className:"mesh-topology__engines","aria-label":n("mesh.enginesAriaLabel","Active engine connections"),children:[s.jsxs("div",{className:"mesh-topology__engines-summary",children:[s.jsx("span",{className:"mesh-topology__engines-count",children:n("mesh.enginesConnected",{count:(t??[]).length,defaultValue:"{{count}} engine(s) connected to shared PG"})}),s.jsx("span",{className:"mesh-topology__engines-metric",children:n("mesh.inFlightTasks",{count:o,defaultValue:"{{count}} in-flight"})}),s.jsx("span",{className:"mesh-topology__engines-metric",children:n("mesh.activeAgents",{count:l,defaultValue:"{{count}} agents"})})]}),s.jsx("ul",{className:"mesh-topology__engines-list",children:(t??[]).map(v=>s.jsxs("li",{className:"mesh-topology__engine-item",children:[s.jsx("span",{className:"mesh-topology__engine-name",children:v.projectName??v.projectId}),s.jsx("span",{className:"mesh-topology__engine-status","data-runtime-status":v.runtimeStatus,children:v.runtimeStatus}),s.jsxs("span",{className:"mesh-topology__engine-tasks",children:[v.inFlightTasks," tasks"]})]},v.projectId))})]}),s.jsxs("div",{className:"mesh-topology__legend",children:[s.jsxs("div",{className:"mesh-topology__legend-item",children:[s.jsx("span",{className:"mesh-topology__legend-dot",style:{background:In.online}}),s.jsx("span",{children:n("mesh.online","Online")})]}),s.jsxs("div",{className:"mesh-topology__legend-item",children:[s.jsx("span",{className:"mesh-topology__legend-dot",style:{background:In.offline}}),s.jsx("span",{children:n("mesh.offline","Offline")})]}),s.jsxs("div",{className:"mesh-topology__legend-item",children:[s.jsx("span",{className:"mesh-topology__legend-dot",style:{background:In.connecting}}),s.jsx("span",{children:n("mesh.connecting","Connecting")})]}),s.jsxs("div",{className:"mesh-topology__legend-item",children:[s.jsx("span",{className:"mesh-topology__legend-dot",style:{background:In.error}}),s.jsx("span",{children:n("mesh.error","Error")})]})]}),h.length===0&&s.jsx("p",{className:"mesh-topology__notice",children:n("mesh.noPeers","Peer-to-peer discovery data unavailable.")})]})}const jF=f.memo(xF),Yl=1,Zl=10;function wF(e,t){const r={projectMappings:{}};e.name.trim()||(r.name=t("nodes.nameRequired","Name is required")),e.type==="remote"&&!e.url?.trim()&&(r.url=t("nodes.urlRequired","URL is required for remote nodes")),(!Number.isFinite(e.maxConcurrent)||e.maxConcurrent<Yl||e.maxConcurrent>Zl)&&(r.maxConcurrent=t("nodes.concurrencyRange","Concurrency must be between {{min}} and {{max}}",{min:Yl,max:Zl}));for(const n of e.projectMappings){const a=iw(n.path);a.valid||(r.projectMappings[n.projectId]=a.error??t("nodes.pathInvalid","Path is invalid"))}return r}function CF({isOpen:e,onClose:t,onSubmit:r,onDiscoverRemoteProjects:n,addToast:a,projects:i}){const{t:o}=se("app");Gj(e);const[l,c]=f.useState(""),[d,u]=f.useState("local"),[m,h]=f.useState(""),[v,p]=f.useState(""),[b,y]=f.useState(2),[g,j]=f.useState("auto-generate"),[x,C]=f.useState({}),[w,P]=f.useState({projectMappings:{}}),[A,S]=f.useState(!1),[N,E]=f.useState("idle"),[T,O]=f.useState(null),[I,z]=f.useState([]),D=f.useCallback(()=>{c(""),u("local"),h(""),p(""),y(2),j("auto-generate"),C({}),P({projectMappings:{}}),S(!1),E("idle"),O(null),z([])},[]),V=f.useCallback(()=>{A||(D(),t())},[A,t,D]);f.useEffect(()=>{if(!e){D();return}const M=q=>{q.key==="Escape"&&(q.preventDefault(),V())};return document.addEventListener("keydown",M),()=>{document.removeEventListener("keydown",M)}},[V,e,D]);const B=f.useMemo(()=>({name:l.trim(),type:d,url:d==="remote"&&m.trim()||void 0,apiKey:d==="remote"&&g==="provide"&&v||void 0,maxConcurrent:b,apiKeyMode:g,projectMappings:Object.entries(x).map(([M,q])=>({projectId:M,path:q.trim()}))}),[v,g,b,l,x,d,m]),W=f.useCallback(async()=>{if(A||N==="loading")return;const M=m.trim();if(!M){P(q=>({...q,url:o("nodes.urlRequired","URL is required for remote nodes")}));return}E("loading"),O(null);try{const q=await n({url:M,apiKey:g==="provide"&&v.trim().length>0?v:void 0});z(q.projects),E("success"),C(H=>{if(Object.keys(H).length===0)return H;const re={...H};for(const ae of i){if(!(ae.id in re))continue;const ye=q.projects.filter(oe=>oe.name===ae.name);ye.length===1&&(re[ae.id]=ye[0].path)}return re})}catch(q){E("error"),z([]),O(q instanceof Error?q.message:o("nodes.discoveryFailed","Failed to discover remote projects"))}},[v,g,N,A,n,i,o,m]);f.useEffect(()=>{if(d!=="remote"){E("idle"),O(null),z([]);return}E("idle"),O(null),z([])},[v,g,d,m]);const K=f.useCallback(async()=>{if(A)return;const M=wF(B,o);if(P(M),!(M.name||M.url||M.maxConcurrent||Object.keys(M.projectMappings).length>0)){if(B.type==="remote"&&N!=="success"){O(o("nodes.discoverBeforeAdding","Discover remote projects before adding this node."));return}S(!0);try{await r(B),a(o("nodes.registered",'Node "{{name}}" registered',{name:B.name}),"success"),V()}catch(q){const H=q instanceof Error?q.message:o("nodes.registerFailed","Failed to register node");a(H,"error")}finally{S(!1)}}},[a,V,N,B,A,r,o]),te=M=>{C(q=>{if(M.id in q){const{[M.id]:H,...re}=q;return re}if(d==="remote"&&N==="success"){const H=I.filter(re=>re.name===M.name);return H.length===1?{...q,[M.id]:H[0].path}:{...q,[M.id]:""}}return{...q,[M.id]:M.path}})},G=(M,q)=>{C(H=>({...H,[M]:q}))};return e?s.jsx(ic,{windowKey:"add-node",title:o("nodes.addNode","Add Node"),ariaLabel:o("nodes.addNode","Add Node"),onClose:V,hideHeader:!0,dragHandleSelector:".modal-header",className:"floating-window--add-node",defaultSize:{width:720,height:560},minSize:{width:360,height:280},persistGeometryKey:"floating-window:add-node",suspendGeometryPersistenceOnMobile:!0,suspendGeometryPersistenceOnShortViewport:!0,closeOnOutsidePointerDown:!0,children:s.jsxs("div",{className:"modal modal-md add-node-modal",children:[s.jsxs("div",{className:"modal-header",children:[s.jsx("h3",{children:o("nodes.addNode","Add Node")}),s.jsx("button",{className:"modal-close",onClick:V,disabled:A,"aria-label":o("nodes.closeNodeModal","Close add node modal"),children:"×"})]}),s.jsxs("div",{className:"modal-body add-node-modal__body",children:[s.jsx("p",{className:"add-node-modal__description",children:o("nodes.description","Register an existing Fusion node by providing its connection details and concurrency settings.")}),s.jsxs("label",{className:"add-node-modal__field",children:[s.jsx("span",{children:o("nodes.name","Name")}),s.jsx("input",{className:"input",type:"text",value:l,onChange:M=>c(M.target.value),placeholder:o("nodes.namePlaceholder","Build Machine"),disabled:A,"aria-invalid":!!w.name,autoFocus:!0}),w.name&&s.jsx("span",{className:"form-error add-node-modal__error",children:w.name})]}),s.jsxs("div",{className:"add-node-modal__type-toggle",children:[s.jsx("button",{type:"button",className:`add-node-modal__type-btn ${d==="local"?"active":""}`,"data-type":"local",onClick:()=>u("local"),disabled:A,"aria-pressed":d==="local",children:o("nodes.local","Local")}),s.jsx("button",{type:"button",className:`add-node-modal__type-btn ${d==="remote"?"active":""}`,"data-type":"remote",onClick:()=>u("remote"),disabled:A,"aria-pressed":d==="remote",children:o("nodes.remote","Remote")})]}),d==="remote"&&s.jsxs("div",{className:"add-node-modal__remote-fields","data-testid":"remote-fields-container","data-visible":!0,children:[s.jsxs("label",{className:"add-node-modal__field",children:[s.jsx("span",{children:o("nodes.reachableUrl","Reachable URL / Hostname")}),s.jsx("input",{className:"input",type:"text",value:m,onChange:M=>h(M.target.value),placeholder:"https://node.example.com",disabled:A,"aria-invalid":!!w.url}),w.url&&s.jsx("span",{className:"form-error add-node-modal__error",children:w.url})]}),s.jsxs("label",{className:"add-node-modal__field",children:[s.jsx("span",{children:o("nodes.apiKeyMode","API Key Mode")}),s.jsxs("select",{className:"select",value:g,onChange:M=>j(M.target.value),disabled:A,children:[s.jsx("option",{value:"auto-generate",children:o("nodes.autoGenerate","Auto-generate")}),s.jsx("option",{value:"provide",children:o("nodes.provideManually","Provide key manually")})]})]}),g==="provide"&&s.jsxs("label",{className:"add-node-modal__field",children:[s.jsx("span",{children:o("nodes.apiKey","API Key")}),s.jsx("input",{className:"input",type:"password",value:v,onChange:M=>p(M.target.value),placeholder:o("nodes.apiKeyPlaceholder","Enter node API key"),disabled:A})]}),s.jsxs("div",{className:"add-node-modal__discovery-actions",children:[s.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void W(),disabled:A||N==="loading",children:N==="loading"?o("nodes.discovering","Discovering..."):o("nodes.discoverRemoteProjects","Discover Remote Projects")}),N==="success"&&s.jsx("span",{className:"add-node-modal__discovery-state","data-state":"success",children:I.length>0?o("nodes.discoveredCount","Discovered {{count}} remote project{{plural}}",{count:I.length,plural:I.length===1?"":"s"}):o("nodes.noProjectsDiscovered","No projects discovered on remote node.")}),N==="error"&&T&&s.jsx("span",{className:"form-error add-node-modal__error",children:T}),N==="idle"&&s.jsx("span",{className:"add-node-modal__hint",children:o("nodes.discoverBeforeAdding","Discover remote projects before adding this node.")})]}),N==="success"&&I.length>0&&s.jsx("div",{className:"add-node-modal__discovered-list","aria-label":o("nodes.discoveredRemoteProjectsLabel","Discovered remote projects"),children:I.map(M=>s.jsxs("div",{className:"card add-node-modal__discovered-card",children:[s.jsxs("div",{className:"add-node-modal__discovered-row",children:[s.jsx("strong",{children:M.name}),s.jsx("span",{className:"card-status-badge card-status-badge--in-review",children:M.status})]}),s.jsx("div",{className:"add-node-modal__hint",children:M.path})]},`${M.id}-${M.path}`))})]}),s.jsxs("label",{className:"add-node-modal__field",children:[s.jsx("span",{children:o("nodes.maxConcurrent","Max Concurrent")}),s.jsx("input",{className:"input",type:"number",min:Yl,max:Zl,value:b,onChange:M=>y(Number(M.target.value)),disabled:A,"aria-invalid":!!w.maxConcurrent}),s.jsx("span",{className:"add-node-modal__hint",children:o("nodes.maxConcurrentHint","Max simultaneous task agents (1–10)")}),w.maxConcurrent&&s.jsx("span",{className:"form-error add-node-modal__error",children:w.maxConcurrent})]}),s.jsxs("section",{className:"add-node-modal__projects","aria-label":o("nodes.projectPathMappingsLabel","Project path mappings"),children:[s.jsx("h4",{className:"add-node-modal__projects-title",children:o("nodes.attachProjects","Attach Existing Projects")}),s.jsx("p",{className:"add-node-modal__hint",children:o("nodes.attachProjectsHint","Select existing projects to run on this node and provide the node-specific absolute path for each one.")}),i.length===0?s.jsx("p",{className:"add-node-modal__hint",children:o("nodes.noProjects","No projects are currently registered.")}):s.jsx("div",{className:"add-node-modal__project-list",children:i.map(M=>{const q=M.id in x,H=w.projectMappings[M.id];return s.jsxs("div",{className:"card add-node-modal__project-card",children:[s.jsxs("label",{className:"checkbox-label add-node-modal__project-toggle",children:[s.jsx("input",{type:"checkbox",checked:q,onChange:()=>te(M),disabled:A}),s.jsx("span",{children:M.name})]}),q&&s.jsxs("label",{className:"add-node-modal__field",children:[s.jsx("span",{children:o("nodes.pathOnNode","Path on this node")}),d==="remote"&&N==="success"&&s.jsx("span",{className:"add-node-modal__hint",children:(()=>{const re=I.filter(ae=>ae.name===M.name);return re.length===1?o("nodes.pathDiscovered","Remote-authoritative path discovered: {{path}}",{path:re[0].path}):re.length>1?o("nodes.multipleMatches","Multiple remote projects matched this name. Enter the correct path manually."):o("nodes.noMatch","No exact remote name match. Enter this path manually.")})()}),s.jsx("input",{className:"input",type:"text",value:x[M.id]??"",onChange:re=>G(M.id,re.target.value),disabled:A,placeholder:"/absolute/path/to/project","aria-invalid":!!H}),H&&s.jsx("span",{className:"form-error add-node-modal__error",children:H})]})]},M.id)})})]})]}),s.jsxs("div",{className:"modal-actions",children:[s.jsx("button",{className:"btn btn-sm",onClick:V,disabled:A,children:o("common.cancel","Cancel")}),s.jsx("button",{className:"btn btn-primary btn-sm","data-testid":"add-node-submit",onClick:K,disabled:A,children:A?o("nodes.adding","Adding..."):o("nodes.addNode","Add Node")})]})]})}):null}function kF(){const[e,t]=f.useState([]),[r,n]=f.useState(!1),[a,i]=f.useState(null),[o,l]=f.useState(!1),[c,d]=f.useState(null),[u,m]=f.useState(!1),h=f.useCallback(async()=>{n(!0),i(null);try{const b=await fetch("/api/docker/contexts");if(!b.ok)throw new Error(`Failed to load Docker contexts (${b.status})`);const y=await b.json();return t(y),y}catch(b){const y=b instanceof Error?b.message:String(b);throw i(y),b}finally{n(!1)}},[]),v=f.useCallback(async b=>{l(!0);try{const y=await fetch("/api/docker/test-connection",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hostConfig:b})});if(!y.ok)throw new Error(`Failed to test Docker connection (${y.status})`);const g=await y.json();return d(g),g}finally{l(!1)}},[]),p=f.useCallback(async()=>{m(!0);try{const b=await fetch("/api/docker/local-available");if(!b.ok)throw new Error(`Failed to check local Docker availability (${b.status})`);return await b.json()}finally{m(!1)}},[]);return{contexts:e,isLoadingContexts:r,contextsError:a,loadContexts:h,isTestingConnection:o,lastTestResult:c,testConnection:v,isCheckingLocal:u,checkLocalDocker:p}}function SF({value:e,onChange:t}){const{t:r}=se("app"),[n,a]=f.useState(!!(e?.tlsCaPath||e?.tlsCertPath||e?.tlsKeyPath||e?.tlsVerify));f.useEffect(()=>{n||t({tlsVerify:void 0,tlsCaPath:void 0,tlsCertPath:void 0,tlsKeyPath:void 0})},[n,t]);const i=f.useMemo(()=>({tlsVerify:e?.tlsVerify??!0,tlsCaPath:e?.tlsCaPath??"",tlsCertPath:e?.tlsCertPath??"",tlsKeyPath:e?.tlsKeyPath??""}),[e]);return s.jsxs("div",{className:"docker-tls-config",children:[s.jsxs("label",{className:"checkbox-label",children:[s.jsx("input",{type:"checkbox",checked:n,onChange:o=>a(o.target.checked)}),r("docker.useTls","Use TLS")]}),n&&s.jsxs("div",{className:"docker-tls-config__fields",children:[s.jsxs("div",{className:"docker-tls-config__field",children:[s.jsx("label",{htmlFor:"docker-tls-ca-path",children:r("docker.caPath","CA Certificate Path")}),s.jsx("input",{id:"docker-tls-ca-path",className:"input",value:i.tlsCaPath,onChange:o=>t({...i,tlsCaPath:o.target.value}),placeholder:"/etc/docker/ca.pem"})]}),s.jsxs("div",{className:"docker-tls-config__field",children:[s.jsx("label",{htmlFor:"docker-tls-cert-path",children:r("docker.certPath","Client Certificate Path")}),s.jsx("input",{id:"docker-tls-cert-path",className:"input",value:i.tlsCertPath,onChange:o=>t({...i,tlsCertPath:o.target.value}),placeholder:"/etc/docker/cert.pem"})]}),s.jsxs("div",{className:"docker-tls-config__field",children:[s.jsx("label",{htmlFor:"docker-tls-key-path",children:r("docker.keyPath","Client Key Path")}),s.jsx("input",{id:"docker-tls-key-path",className:"input",value:i.tlsKeyPath,onChange:o=>t({...i,tlsKeyPath:o.target.value}),placeholder:"/etc/docker/key.pem"})]}),s.jsxs("label",{className:"checkbox-label",children:[s.jsx("input",{type:"checkbox",checked:i.tlsVerify,onChange:o=>t({...i,tlsVerify:o.target.checked})}),r("docker.verifyTls","Verify TLS Certificate")]})]})]})}function NF({value:e,onChange:t,onError:r}){const{t:n}=se("app"),a=e?.context?"context":e?.host?"host":"local",[i,o]=f.useState(a),[l,c]=f.useState(e?.context??""),[d,u]=f.useState(e?.host??""),[m,h]=f.useState(null),{contexts:v,isLoadingContexts:p,contextsError:b,loadContexts:y,testConnection:g,isTestingConnection:j,lastTestResult:x,checkLocalDocker:C,isCheckingLocal:w}=kF(),P=f.useMemo(()=>({tlsVerify:e?.tlsVerify,tlsCaPath:e?.tlsCaPath,tlsCertPath:e?.tlsCertPath,tlsKeyPath:e?.tlsKeyPath}),[e]);f.useEffect(()=>{if(i==="local"){t({});return}if(i==="context"){y().catch(S=>r?.(S instanceof Error?S.message:String(S))),t(l?{context:l}:{});return}t({host:d,...P})},[i]);const A=f.useCallback(S=>{i==="host"&&t({host:d,...S})},[d,i,t]);return s.jsxs("div",{className:"docker-target-selector",children:[s.jsxs("div",{className:"docker-target-selector__modes",role:"group","aria-label":n("docker.targetMode","Docker target mode"),children:[s.jsx("button",{type:"button",className:`btn btn-sm ${i==="local"?"docker-target-selector__mode-active":""}`,onClick:()=>{o("local"),C().then(S=>{if(S.available){const N=S.version?` (${S.version})`:"";h(n("docker.available","Docker is available{{version}}",{version:N}))}else{const N=S.error?`: ${S.error}`:"";h(n("docker.notFound","Docker not found{{error}}",{error:N}))}}).catch(S=>{const N=S instanceof Error?S.message:String(S);h(n("docker.notFoundError","Docker not found: {{message}}",{message:N})),r?.(N)})},children:n("docker.local","Local Docker")}),s.jsx("button",{type:"button",className:`btn btn-sm ${i==="context"?"docker-target-selector__mode-active":""}`,onClick:()=>o("context"),children:n("docker.context","Docker Context")}),s.jsx("button",{type:"button",className:`btn btn-sm ${i==="host"?"docker-target-selector__mode-active":""}`,onClick:()=>o("host"),children:n("docker.remote","Remote Host")})]}),i==="local"&&m&&s.jsx("div",{className:"docker-target-selector__status",children:m}),i==="context"&&s.jsxs("div",{className:"docker-target-selector__panel",children:[s.jsxs("div",{className:"docker-target-selector__context-row",children:[s.jsxs("select",{className:"select",value:l,onChange:S=>{const N=S.target.value;c(N),t(N?{context:N}:{})},children:[s.jsx("option",{value:"",children:n("docker.selectContext","Select context")}),v.map(S=>s.jsxs("option",{value:S.name,children:[S.name,S.isCurrentContext?" (current)":"",S.dockerHost?` — ${S.dockerHost}`:""]},S.name))]}),s.jsx("button",{type:"button",className:"btn btn-sm btn-icon",onClick:()=>void y(),disabled:p,"aria-label":n("docker.refreshContexts","Refresh contexts"),children:s.jsx(Gt,{size:14})})]}),b&&s.jsx("div",{className:"docker-target-selector__error",children:b})]}),i==="host"&&s.jsxs("div",{className:"docker-target-selector__panel",children:[s.jsxs("div",{className:"docker-target-selector__field",children:[s.jsx("label",{htmlFor:"docker-target-selector-host",children:n("docker.host","Docker Host")}),s.jsx("input",{id:"docker-target-selector-host",className:"input",placeholder:n("docker.hostPlaceholder","tcp://host:2376"),value:d,onChange:S=>{const N=S.target.value;u(N),t({host:N,...P})}})]}),s.jsx(SF,{value:P,onChange:A})]}),s.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void g(i==="local"?void 0:i==="context"?{context:l}:{host:d,...P}),disabled:j||w,children:j?n("docker.testing","Testing..."):n("docker.testConnection","Test Connection")}),x&&s.jsx("div",{className:x.success?"docker-target-selector__success":"docker-target-selector__error",children:x.success?n("docker.connected","Connected{{version}}",{version:x.dockerVersion?` (Docker ${x.dockerVersion})`:""}):x.error??n("docker.connectionFailed","Connection failed")})]})}const Jo="http://localhost:4040",kh={readWrite:"rw",readOnly:"ro"};function PF({isOpen:e,onClose:t,onSubmit:r,addToast:n}){const{t:a}=se("app"),[i,o]=f.useState(""),[l,c]=f.useState({}),[d,u]=f.useState(Jo),[m,h]=f.useState("auto"),[v,p]=f.useState(""),[b,y]=f.useState(!1),[g,j]=f.useState(!1),[x,C]=f.useState(!0),[w,P]=f.useState(4096),[A,S]=f.useState(2),[N,E]=f.useState(!1),[T,O]=f.useState("runfusion/fusion"),[I,z]=f.useState("latest"),[D,V]=f.useState([]),[B,W]=f.useState([]),[K,te]=f.useState({}),[G,M]=f.useState(!1),q=f.useCallback(()=>{o(""),c({}),u(Jo),h("auto"),p(""),y(!1),j(!1),C(!0),P(4096),S(2),E(!1),O("runfusion/fusion"),z("latest"),V([]),W([]),te({}),M(!1)},[]),H=f.useCallback(()=>{G||(q(),t())},[t,q,G]);f.useEffect(()=>{if(!e){q();return}const L=Y=>{Y.key==="Escape"&&(Y.preventDefault(),H())};return document.addEventListener("keydown",L),()=>document.removeEventListener("keydown",L)},[H,e,q]);const re=f.useMemo(()=>({nodeId:null,name:i.trim(),imageName:T.trim()||"runfusion/fusion",imageTag:I.trim()||"latest",hostConfig:{context:l.context?.trim()||void 0,host:l.host?.trim()||void 0,tlsVerify:l.tlsVerify,tlsCaPath:l.tlsCaPath?.trim()||void 0,tlsCertPath:l.tlsCertPath?.trim()||void 0,tlsKeyPath:l.tlsKeyPath?.trim()||void 0},envVars:Object.fromEntries(D.map(L=>[L.key.trim(),L.value]).filter(([L])=>!!L)),volumeMounts:B.map(L=>({hostPath:L.hostPath.trim(),containerPath:L.containerPath.trim(),mode:L.mode})).filter(L=>L.hostPath&&L.containerPath),resourceSizing:{memoryMB:w,cpus:A},extraClis:[b?"claude-cli":null,g?"droid-cli":null].filter(Boolean),persistentStorage:x,reachableUrl:d.trim()||null,apiKey:m==="manual"&&v.trim()||null}),[v,m,A,l,D,T,I,b,g,w,B,i,x,d]),ae=f.useCallback(()=>{V(L=>[...L,{key:"",value:""}])},[]),ye=f.useCallback((L,Y)=>{V(ne=>ne.map((Ne,Q)=>Q===L?Y:Ne))},[]),oe=f.useCallback(L=>{V(Y=>Y.filter((ne,Ne)=>Ne!==L))},[]),He=f.useCallback(()=>{W(L=>[...L,{hostPath:"",containerPath:"",mode:"rw"}])},[]),J=f.useCallback((L,Y)=>{W(ne=>ne.map((Ne,Q)=>Q===L?Y:Ne))},[]),Ce=f.useCallback(L=>{W(Y=>Y.filter((ne,Ne)=>Ne!==L))},[]),Re=f.useCallback(async()=>{if(G)return;const L={};if((!re.name||re.name.length>64)&&(L.name=a("docker.errors.nameRequired","Name is required and must be 64 characters or fewer")),re.reachableUrl||(L.reachableUrl=a("docker.errors.urlRequired","URL is required")),w<512&&(L.memoryMB=a("docker.errors.memoryMinimum","Memory must be at least 512 MB")),A<.5&&(L.cpus=a("docker.errors.cpusMinimum","CPUs must be at least 0.5")),te(L),!(Object.keys(L).length>0)){M(!0);try{await r(re),H()}catch{}finally{M(!1)}}},[H,A,re,w,r,G,a]);return e?s.jsx(ic,{windowKey:"docker-node-onboarding",modal:!0,title:a("docker.titles.provisionNode","Provision Docker Node"),ariaLabel:a("docker.ariaLabels.modal","Docker node onboarding"),onClose:()=>{G||H()},hideHeader:!0,dragHandleSelector:".docker-onboarding .modal-header",className:"floating-window--docker-node-onboarding",defaultSize:{width:720,height:640},minSize:{width:420,height:320},persistGeometryKey:"floating-window:docker-node-onboarding",suspendGeometryPersistenceOnMobile:!0,suspendGeometryPersistenceOnShortViewport:!0,closeOnOutsidePointerDown:!0,children:s.jsxs("div",{className:"modal docker-onboarding",children:[s.jsxs("div",{className:"modal-header",children:[s.jsx("h3",{children:a("docker.titles.provisionNode","Provision Docker Node")}),s.jsx("button",{className:"modal-close",onClick:H,disabled:G,"aria-label":a("docker.ariaLabels.closeModal","Close onboarding modal"),children:"×"})]}),s.jsxs("div",{className:"modal-body docker-onboarding__body",children:[s.jsxs("section",{className:"docker-onboarding__section",children:[s.jsx("h4",{className:"docker-onboarding__section-title",children:a("docker.sections.requiredSettings","Required Settings")}),s.jsxs("label",{className:"docker-onboarding__field",children:[s.jsx("span",{children:a("docker.labels.nodeName","Node Name")}),s.jsx("input",{className:"input",value:i,onChange:L=>o(L.target.value),disabled:G,placeholder:a("docker.placeholders.nodeName","my-docker-node"),autoFocus:!0})]}),K.name&&s.jsx("div",{className:"form-error",children:K.name}),s.jsx(NF,{value:l,onChange:c}),s.jsxs("label",{className:"docker-onboarding__field",children:[s.jsx("span",{children:a("docker.labels.reachableUrl","Reachable URL")}),s.jsx("input",{className:"input",value:d,onChange:L=>u(L.target.value),disabled:G,placeholder:Jo})]}),K.reachableUrl&&s.jsx("div",{className:"form-error",children:K.reachableUrl}),s.jsxs("div",{className:"docker-onboarding__radio-group",children:[s.jsxs("label",{className:"checkbox-label",children:[s.jsx("input",{type:"radio",checked:m==="auto",onChange:()=>h("auto"),disabled:G}),a("docker.options.autoGenerate","Auto-generate")]}),s.jsxs("label",{className:"checkbox-label",children:[s.jsx("input",{type:"radio",checked:m==="manual",onChange:()=>h("manual"),disabled:G}),a("docker.options.provideManually","Provide manually")]})]}),m==="manual"&&s.jsxs("label",{className:"docker-onboarding__field",children:[s.jsx("span",{children:a("docker.labels.apiKey","API Key")}),s.jsx("input",{className:"input",type:"password",value:v,onChange:L=>p(L.target.value),disabled:G,placeholder:a("docker.placeholders.apiKey","Enter API key")})]}),s.jsxs("div",{className:"docker-onboarding__checkbox-group",children:[s.jsxs("label",{className:"checkbox-label",children:[s.jsx("input",{type:"checkbox",checked:b,onChange:L=>y(L.target.checked),disabled:G}),a("docker.options.claudeCli","Claude CLI")]}),s.jsxs("label",{className:"checkbox-label",children:[s.jsx("input",{type:"checkbox",checked:g,onChange:L=>j(L.target.checked),disabled:G}),a("docker.options.droidCli","Droid CLI")]}),s.jsxs("label",{className:"checkbox-label",children:[s.jsx("input",{type:"checkbox",checked:x,onChange:L=>C(L.target.checked),disabled:G}),a("docker.options.persistentStorage","Keep data across container recreations")]})]}),s.jsxs("div",{className:"docker-onboarding__inline-fields",children:[s.jsxs("label",{className:"docker-onboarding__field",children:[s.jsx("span",{children:a("docker.labels.memory","Memory (MB)")}),s.jsx("input",{className:"input",type:"number",min:512,value:w,onChange:L=>P(Number(L.target.value)),disabled:G})]}),s.jsxs("label",{className:"docker-onboarding__field",children:[s.jsx("span",{children:a("docker.labels.cpus","CPUs")}),s.jsx("input",{className:"input",type:"number",min:.5,step:.5,value:A,onChange:L=>S(Number(L.target.value)),disabled:G})]})]}),K.memoryMB&&s.jsx("div",{className:"form-error",children:K.memoryMB}),K.cpus&&s.jsx("div",{className:"form-error",children:K.cpus})]}),s.jsxs("section",{className:"docker-onboarding__section",children:[s.jsxs("button",{type:"button",className:`docker-onboarding__advanced-toggle ${N?"is-expanded":""}`,onClick:()=>E(L=>!L),disabled:G,children:[s.jsx("span",{children:a("docker.sections.advanced","Advanced")}),s.jsx(sc,{})]}),s.jsx("div",{className:`docker-onboarding__advanced-content ${N?"is-expanded":""}`,children:s.jsxs("div",{children:[s.jsxs("div",{className:"docker-onboarding__inline-fields",children:[s.jsxs("label",{className:"docker-onboarding__field",children:[s.jsx("span",{children:a("docker.labels.image","Image")}),s.jsx("input",{className:"input",value:T,onChange:L=>O(L.target.value),disabled:G,placeholder:a("docker.placeholders.image","runfusion/fusion")})]}),s.jsxs("label",{className:"docker-onboarding__field",children:[s.jsx("span",{children:a("docker.labels.tag","Tag")}),s.jsx("input",{className:"input",value:I,onChange:L=>z(L.target.value),disabled:G,placeholder:a("docker.placeholders.tag","latest")})]})]}),s.jsxs("div",{className:"docker-onboarding__kv-list",children:[s.jsx("h5",{children:a("docker.sections.environmentVariables","Environment Variables")}),D.map((L,Y)=>s.jsxs("div",{className:"docker-onboarding__kv-row docker-onboarding__kv-row--env",children:[s.jsx("input",{className:"input",placeholder:a("docker.placeholders.envVarKey","KEY"),value:L.key,disabled:G,onChange:ne=>ye(Y,{key:ne.target.value,value:L.value})}),s.jsx("input",{className:"input",placeholder:a("docker.placeholders.envVarValue","Value"),value:L.value,disabled:G,onChange:ne=>ye(Y,{key:L.key,value:ne.target.value})}),s.jsx("button",{type:"button",className:"btn btn-icon","aria-label":a("docker.ariaLabels.removeVariable","Remove environment variable"),onClick:()=>oe(Y),disabled:G,children:s.jsx(tn,{size:14})})]},`env-${Y}`)),s.jsxs("button",{type:"button",className:"btn btn-sm docker-onboarding__kv-add",onClick:ae,disabled:G,children:[s.jsx(zn,{size:14}),a("docker.actions.addVariable","Add variable")]})]}),s.jsxs("div",{className:"docker-onboarding__kv-list",children:[s.jsx("h5",{children:a("docker.sections.volumeMounts","Volume Mounts")}),B.map((L,Y)=>s.jsxs("div",{className:"docker-onboarding__kv-row docker-onboarding__kv-row--mount",children:[s.jsx("input",{className:"input",placeholder:a("docker.placeholders.hostPath","Host path"),value:L.hostPath,disabled:G,onChange:ne=>J(Y,{hostPath:ne.target.value,containerPath:L.containerPath,mode:L.mode})}),s.jsx("input",{className:"input",placeholder:a("docker.placeholders.containerPath","Container path"),value:L.containerPath,disabled:G,onChange:ne=>J(Y,{hostPath:L.hostPath,containerPath:ne.target.value,mode:L.mode})}),s.jsxs("select",{className:"select",value:L.mode,disabled:G,onChange:ne=>J(Y,{hostPath:L.hostPath,containerPath:L.containerPath,mode:ne.target.value==="ro"?"ro":"rw"}),children:[s.jsx("option",{value:"rw",children:kh.readWrite}),s.jsx("option",{value:"ro",children:kh.readOnly})]}),s.jsx("button",{type:"button",className:"btn btn-icon","aria-label":a("docker.ariaLabels.removeMount","Remove volume mount"),onClick:()=>Ce(Y),disabled:G,children:s.jsx(tn,{size:14})})]},`mount-${Y}`)),s.jsxs("button",{type:"button",className:"btn btn-sm docker-onboarding__kv-add",onClick:He,disabled:G,children:[s.jsx(zn,{size:14}),a("docker.actions.addMount","Add mount")]})]})]})})]})]}),s.jsxs("div",{className:"modal-actions",children:[s.jsx("button",{className:"btn",onClick:H,disabled:G,children:a("docker.actions.cancel","Cancel")}),s.jsx("button",{className:"btn btn-primary",onClick:()=>void Re(),disabled:G,children:G?a("docker.states.creating","Creating..."):a("docker.actions.createNode","Create Docker Node")})]})]})}):null}function AF({nodeId:e,entries:t,loading:r=!1,singleNode:n=!1}){const{t:a}=se("app"),[i,o]=f.useState(!1),[l,c]=f.useState("all"),[d,u]=f.useState("all"),m=f.useCallback(()=>{o(g=>!g)},[]),h=f.useMemo(()=>{const g=new Set;for(const j of t)g.add(j.nodeName);return Array.from(g).sort()},[t]),v=f.useMemo(()=>{let g=[...t];return l!=="all"&&(g=g.filter(j=>j.direction===l)),!n&&d!=="all"&&(g=g.filter(j=>j.nodeName===d)),g.sort((j,x)=>{const C=new Date(j.timestamp).getTime();return new Date(x.timestamp).getTime()-C}),g},[t,l,d,n]),p=f.useCallback(g=>new Date(g).toLocaleString(),[]),b=f.useCallback(g=>{switch(g){case"success":return"settings-sync-log__badge--success";case"conflict":return"settings-sync-log__badge--conflict";case"error":return"settings-sync-log__badge--error";default:return""}},[]),y=f.useCallback(g=>{switch(g){case"success":return a("syncLog.resultSuccess","Success");case"conflict":return a("syncLog.resultConflict","Conflict");case"error":return a("syncLog.resultError","Error");default:return g}},[a]);return s.jsxs("div",{className:"settings-sync-log",children:[s.jsxs("button",{className:"settings-sync-log__header",type:"button",onClick:m,"aria-expanded":i,"data-testid":"settings-sync-log-header",children:[s.jsx(sc,{size:16,className:`settings-sync-log__chevron ${i?"settings-sync-log__chevron--expanded":""}`}),s.jsx("span",{children:a("syncLog.entryCount",{count:t.length,defaultValue_one:"{{count}} entry",defaultValue_other:"{{count}} entries"})})]}),i&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"settings-sync-log__filters",children:[s.jsxs("label",{children:[a("syncLog.filterDirection","Direction:"),s.jsxs("select",{value:l,onChange:g=>c(g.target.value),children:[s.jsx("option",{value:"all",children:a("syncLog.filterAll","All")}),s.jsx("option",{value:"push",children:a("syncLog.filterPush","Push")}),s.jsx("option",{value:"pull",children:a("syncLog.filterPull","Pull")})]})]}),!n&&s.jsxs("label",{children:[a("syncLog.filterNode","Node:"),s.jsxs("select",{value:d,onChange:g=>u(g.target.value),children:[s.jsx("option",{value:"all",children:a("syncLog.filterAllNodes","All Nodes")}),h.map(g=>s.jsx("option",{value:g,children:g},g))]})]})]}),r&&t.length===0?s.jsx("div",{className:"settings-sync-log__empty",children:s.jsx(rc,{label:a("syncLog.loading","Loading...")})}):v.length===0?s.jsx("div",{className:"settings-sync-log__empty",children:a("syncLog.noHistory","No sync history available")}):s.jsx("div",{className:"settings-sync-log__list",children:v.map(g=>s.jsxs("div",{className:"settings-sync-log__entry",children:[s.jsx("span",{className:"settings-sync-log__entry-timestamp",children:p(g.timestamp)}),s.jsx("span",{className:"settings-sync-log__entry-direction",children:g.direction==="push"?s.jsx(uc,{size:14,"data-testid":"upload-icon"}):s.jsx(Ri,{size:14,"data-testid":"download-icon"})}),s.jsx("span",{className:`settings-sync-log__entry-result ${b(g.result)}`,children:y(g.result)}),!n&&s.jsx("span",{className:"settings-sync-log__entry-node",children:g.nodeName}),g.details&&s.jsx("span",{className:"settings-sync-log__entry-details",title:g.details,children:Xj(g.details??"")})]},g.id))})]})]})}function OF(e,t){const r=typeof e=="string"?e:JSON.stringify(e,null,2),n=typeof t=="string"?t:JSON.stringify(t,null,2);if(r===n)return r;const a=r.split(`
99
+ `)}),v.status==="failed"&&v.error?s.jsx("p",{className:"cc-system-note cc-system-note--error",children:v.error}):null]}):null,s.jsxs("div",{className:"cc-area-section","data-testid":"cc-system-logs",children:[s.jsxs("div",{className:"cc-area-section-header",children:[s.jsxs("h3",{className:"cc-area-section-title cc-system-section-title-with-icon",children:[s.jsx(gw,{size:16}),s.jsx("span",{children:r("systemControls.serverLogs","Server logs")})]}),s.jsx("button",{type:"button",className:"btn",disabled:a?!a.logsSupported:!1,onClick:()=>z(R=>!R),"data-testid":"cc-system-logs-toggle",children:I?r("systemControls.hideLogs","Hide logs"):r("systemControls.viewLogs","View logs")})]}),a&&!a.logsSupported?s.jsx("p",{className:"cc-system-note",children:r("systemControls.logsUnavailable","Host-process logs are not available in this mode.")}):null,I&&a?.logsSupported?s.jsxs("div",{ref:B,className:"cc-syscontrols-output cc-syscontrols-logs","aria-live":"polite",onScroll:M,children:[D.map((R,ce)=>s.jsxs("div",{className:`cc-syscontrols-log-line cc-syscontrols-log-line--${R.level}`,children:[s.jsx("span",{className:"cc-syscontrols-log-time",children:I2(R.timestamp)}),R.prefix?s.jsxs("span",{className:"cc-syscontrols-log-prefix",children:["[",R.prefix,"]"]}):null,s.jsx("span",{className:"cc-syscontrols-log-message",children:R.message})]},`${R.timestamp}-${ce}`)),D.length===0?s.jsx("div",{className:"cc-syscontrols-log-line",children:r("systemControls.noLogs","No log entries yet.")}):null]}):null]})]})}function R2(e,t){if(!Number.isFinite(e)||e<=0)return 0;const r=Number.isFinite(t)&&t>0?t:1;return Math.max(0,Math.min(100,e/r*100))}function L2(e,t){return t===null?null:!Number.isFinite(t)||t<=0?"—":`${Math.max(0,Math.min(100,e/t*100)).toFixed(0)}%`}function qx({stages:e,ariaLabel:t}){const r=e.reduce((n,a)=>a.value>n?a.value:n,0);return s.jsx("ol",{className:"cc-funnel","aria-label":t,children:e.map((n,a)=>{const i=R2(n.value,r),o=a>0?e[a-1].value:null,l=L2(n.value,o),c=String(Number.isFinite(n.value)?n.value:0);return s.jsxs("li",{className:"cc-funnel-stage",children:[s.jsxs("div",{className:"cc-funnel-header",children:[s.jsx("span",{className:"cc-funnel-label",children:n.label}),l!==null?s.jsx("span",{className:"cc-funnel-conversion",children:l}):null]}),s.jsx("div",{className:"cc-funnel-track",children:s.jsx("div",{className:"cc-funnel-fill",style:{width:`${i}%`},role:"img","aria-label":`${n.label}: ${c}`})}),s.jsx("span",{className:"cc-funnel-value",children:c})]},n.label)})})}function Wx(e){const t=e.trim().toLowerCase();return t==="in-progress"||t==="in progress"||t==="doing"}function $2(e){return(e??[]).reduce((t,r)=>t+(Wx(r.column)?r.count:0),0)}function F2(e){return(e?.activeSessions??0)+(e?.activeRuns??0)}const B2=5e3,z2=3e4,K2=["session:updated","session:completed","run:created","run:updated","run:completed","run:cancelled","run:failed","agent:stateChanged","task:moved","task:updated","task:created","task:deleted"],V2=new Set(["triage","signal","backlog"]),Xo=[{id:"triage",match:e=>V2.has(e)},{id:"todo",match:e=>e==="todo"||e==="to-do"||e==="to do"||e==="ready"},{id:"in-progress",match:Wx},{id:"in-review",match:e=>e==="in-review"||e==="in review"||e==="review"},{id:"done",match:e=>e==="done"||e==="complete"||e==="completed"||e==="shipped"}];function Hx(e){const[t,r]=f.useState(null),[n,a]=f.useState(!0),[i,o]=f.useState(null),[l,c]=f.useState(!1),d=f.useRef(null),u=f.useRef(null),m=f.useRef(Symbol("no-live-snapshot-request")),h=f.useRef(m.current),{capture:v}=Bj(e,"useLiveSnapshot"),p=f.useCallback(()=>{u.current!==null&&(clearInterval(u.current),u.current=null,c(!1))},[]),b=f.useCallback(async()=>{const g=v(),j=g.projectIdAtStart;if(h.current!==j){h.current=j;try{const x=await fr(mr("/command-center/live",j));if(g.isStale())return;d.current=x,r(x),o(null)}catch(x){if(g.isStale())return;o(x instanceof Error?x.message:"Failed to load live snapshot")}finally{if(h.current===j&&(h.current=m.current),!g.isStale()){a(!1);const x=d.current;(typeof document>"u"||document.visibilityState!=="hidden")&&!!x&&(x.activeSessions>0||x.activeRuns>0)?u.current===null&&(u.current=setInterval(()=>{b()},B2),c(!0)):p()}}}},[v,p]);f.useEffect(()=>{d.current=null,r(null),a(!0),o(null),b();const g=qa("/api/events",{events:Object.fromEntries(K2.map(x=>[x,()=>void b()])),onReconnect:()=>void b()}),j=()=>{if(document.visibilityState==="hidden"){p();return}b()};return typeof document<"u"&&document.addEventListener("visibilitychange",j),()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",j),g(),p()}},[b,e,p]);const y=f.useCallback(()=>{b()},[b]);return{snapshot:t,isLoading:n,error:i!==null&&t===null?i:null,polling:l,reload:y}}function U2(e){const t=e.split(/[/\\]/).filter(Boolean);return t.length>0?t[t.length-1]:e}function q2(e,t){const r=Date.parse(t),n=new Map;for(const a of e){if(!a.worktreePath)continue;const i=n.get(a.worktreePath)??{count:0,freshestMs:0},o=Date.parse(a.updatedAt);n.set(a.worktreePath,{count:i.count+1,freshestMs:Number.isFinite(o)?Math.max(i.freshestMs,o):i.freshestMs})}return Array.from(n.entries()).map(([a,i])=>{const o=Number.isFinite(r)&&i.freshestMs>0?r-i.freshestMs:0;return{path:a,label:U2(a),sessionCount:i.count,inactive:o>z2}}).sort((a,i)=>i.sessionCount-a.sessionCount)}function W2(e,t){const r=new Map;for(const i of Xo)r.set(i.id,0);let n=0;for(const i of e){const o=i.column.trim().toLowerCase(),l=Xo.find(c=>c.match(o));l?r.set(l.id,(r.get(l.id)??0)+i.count):n+=i.count}const a=Xo.map(i=>({label:t(`commandCenter.missionControl.stage.${i.id}`,i.id),value:r.get(i.id)??0}));return n>0&&a.push({label:t("commandCenter.missionControl.stage.other","Other"),value:n}),a}function H2({projectId:e}={}){const{t}=se("app"),{snapshot:r,isLoading:n,error:a}=Hx(e),i=f.useMemo(()=>r?.sessions??[],[r?.sessions]),o=f.useMemo(()=>r?q2(r.sessions,r.capturedAt):[],[r]),l=f.useMemo(()=>r?W2(r.columns,t):[],[r,t]);if(n&&!r)return s.jsxs("div",{className:"cc-loading-inline","data-testid":"mission-control-loading",children:[s.jsx(Ql,{size:18,className:"spin"}),s.jsx("span",{children:t("commandCenter.missionControl.loading","Loading live activity…")})]});if(a!==null)return s.jsxs("div",{className:"cc-area-error","data-testid":"mission-control-error",role:"alert",children:[s.jsx(Mi,{size:22}),s.jsx("p",{children:a})]});const c=(r?.activeSessions??0)>0||(r?.activeRuns??0)>0;return s.jsxs("div",{className:"cc-mission-control","data-testid":"mission-control",children:[s.jsxs("div",{className:"cc-stat-grid","data-testid":"mission-control-summary",children:[s.jsxs("div",{className:"card cc-stat-card","data-testid":"mission-control-active-sessions",children:[s.jsx("div",{className:"cc-stat-label",children:t("commandCenter.missionControl.activeSessions","Active sessions")}),s.jsx("div",{className:"cc-stat-value",children:r?.activeSessions??0})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"mission-control-active-runs",children:[s.jsx("div",{className:"cc-stat-label",children:t("commandCenter.missionControl.activeRuns","Active runs")}),s.jsx("div",{className:"cc-stat-value",children:r?.activeRuns??0})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"mission-control-active-nodes",children:[s.jsx("div",{className:"cc-stat-label",children:t("commandCenter.missionControl.activeNodes","Active nodes")}),s.jsx("div",{className:"cc-stat-value",children:r?.activeNodes??0})]})]}),c?null:s.jsxs("div",{className:"cc-area-empty","data-testid":"mission-control-idle",children:[s.jsx(Fj,{size:24}),s.jsx("p",{children:t("commandCenter.missionControl.idle","No active sessions. Live updates resume when work starts.")})]}),s.jsxs("div",{className:"cc-mc-columns",children:[s.jsxs("section",{className:"cc-mc-section","data-testid":"mission-control-sessions",children:[s.jsx("h3",{className:"cc-area-section-title",children:t("commandCenter.missionControl.sessionsTitle","Sessions")}),i.length===0?s.jsx("p",{className:"cc-mc-muted","data-testid":"mission-control-sessions-empty",children:t("commandCenter.missionControl.noSessions","No active sessions.")}):s.jsx("ul",{className:"cc-mc-list",children:i.map(d=>s.jsxs("li",{className:"cc-mc-session","data-testid":`mission-control-session-${d.id}`,children:[s.jsx("span",{className:"cc-mc-session-purpose",children:d.purpose||d.adapterId}),s.jsxs("span",{className:"cc-mc-session-meta",children:[s.jsx("span",{className:"cc-mc-badge",children:d.agentState}),d.taskId?s.jsx("span",{className:"cc-mc-task",children:d.taskId}):null]})]},d.id))})]}),s.jsxs("section",{className:"cc-mc-section","data-testid":"mission-control-nodes",children:[s.jsx("h3",{className:"cc-area-section-title",children:t("commandCenter.missionControl.nodesTitle","Nodes")}),o.length===0?s.jsx("p",{className:"cc-mc-muted","data-testid":"mission-control-nodes-empty",children:t("commandCenter.missionControl.noNodes","No active nodes.")}):s.jsx("ul",{className:"cc-mc-list",children:o.map(d=>s.jsxs("li",{className:`cc-mc-node${d.inactive?" inactive":""}`,"data-testid":`mission-control-node-${d.label}`,"data-inactive":d.inactive?"true":"false",children:[s.jsx("span",{className:"cc-mc-node-label",children:d.label}),s.jsxs("span",{className:"cc-mc-node-meta",children:[d.inactive?s.jsx("span",{className:"cc-mc-badge inactive",children:t("commandCenter.missionControl.inactive","inactive")}):null,s.jsx("span",{className:"cc-mc-node-count",children:t("commandCenter.missionControl.sessionCount","{{count}} session",{count:d.sessionCount})})]})]},d.path))})]})]}),s.jsxs("section",{className:"cc-mc-section","data-testid":"mission-control-funnel",children:[s.jsx("h3",{className:"cc-area-section-title",children:t("commandCenter.missionControl.funnelTitle","SDLC funnel (live)")}),s.jsx(qx,{stages:l,ariaLabel:t("commandCenter.missionControl.funnelTitle","SDLC funnel (live)")})]})]})}const G2=500,Mn={maxConcurrent:As.maxConcurrent,maxWorktrees:As.maxWorktrees,worktreeLimitEnabled:!!As.worktreeLimitEnabled},Yr={maxConcurrent:{min:1,max:50},maxWorktrees:{min:1,max:50}},Gx={maxConcurrent:{key:"commandCenter.controls.concurrency.maxConcurrent",defaultValue:"Max concurrent tasks"},maxWorktrees:{key:"commandCenter.controls.concurrency.maxWorktrees",defaultValue:"Max worktrees"}};function Xx(e,t,r){return Math.min(r,Math.max(t,e))}function Yo(e,t){return Math.max(Yr[e].max,t)}function X2(e,t,r,n){return n<=r?0:Xx((Math.min(e,t)-r)/(n-r),0,1)}function Y2(e){return{"--use-pct":`${e*100}%`,"--use-offset":`calc((var(--cc-controls-range-thumb-size) / 2) + ((100% - var(--cc-controls-range-thumb-size)) * ${e}))`}}function Z2(e,t){return Object.keys(Gx).filter(r=>e[r]!==t[r])}function J2({paused:e,label:t}){return s.jsxs("span",{className:"cc-controls-status-pill",children:[s.jsx("span",{className:`status-dot ${e?"status-dot--pending":"status-dot--online"}`,"aria-hidden":"true"}),s.jsx("span",{children:t})]})}function Q2({projectId:e,colorTheme:t,themeMode:r,shadcnCustomColors:n={},resolvedThemeMode:a=r==="light"?"light":"dark",onColorThemeChange:i,onThemeModeChange:o,onShadcnCustomColorsChange:l=()=>{},onChangeView:c}){const{t:d}=se("app"),{confirm:u}=tc(),{globalPaused:m,toggleGlobalPause:h,refresh:v}=Oh(e),[p,b]=f.useState({status:"loading",data:null,error:null}),[y,g]=f.useState(!1),[j,x]=f.useState("idle"),C=f.useRef(Mn),w=f.useRef(null),P=f.useRef(!1),A=zj();f.useEffect(()=>{let B=!1;return g(!1),x("idle"),b({status:"loading",data:null,error:null}),(async()=>{try{const[W,K]=await Promise.all([Kj(e),Eh(e)]);if(!B){const te={maxConcurrent:K.maxConcurrent??W.maxConcurrent??Mn.maxConcurrent,maxWorktrees:K.maxWorktrees??Mn.maxWorktrees,worktreeLimitEnabled:K.worktreeLimitEnabled!==!1};C.current=te,w.current=null,P.current=!1,b({status:"loaded",data:te,error:null})}}catch(W){B||b({status:"error",data:C.current,error:W instanceof Error?W.message:d("commandCenter.controls.concurrency.error","Unable to load concurrency settings")})}})(),()=>{B=!0}},[e,d]),f.useEffect(()=>{if(!y||!p.data||P.current)return;const B=p.data,W=setTimeout(()=>{const K=C.current,te=Z2(B,K);if(te.length===0){g(!1),w.current=null;return}P.current=!0;const G=te.map(q=>{const H=Gx[q];return d("commandCenter.controls.concurrency.confirmChangeSummaryItem","{{setting}} from {{oldValue}} to {{newValue}}",{setting:d(H.key,H.defaultValue),oldValue:K[q],newValue:B[q]})}),M=te.length===1?d("commandCenter.controls.concurrency.confirmMessage","Change {{setting}}?",{setting:G[0]}):d("commandCenter.controls.concurrency.confirmMultipleMessage","Change these concurrency settings: {{settings}}?",{settings:G.join("; ")});u({title:d("commandCenter.controls.concurrency.confirmTitle","Confirm concurrency change"),message:M,confirmLabel:d("commandCenter.controls.concurrency.confirmSave","Save change"),cancelLabel:d("commandCenter.controls.concurrency.confirmCancel","Cancel")}).then(q=>{if(P.current=!1,!q){b({status:"loaded",data:C.current,error:null}),g(!1),w.current=null,x("idle");return}x("saving"),_h(B,e).then(async()=>{await v(),C.current=B,g(!1),w.current=null,x("saved")}).catch(()=>{x("error")})})},G2);return()=>clearTimeout(W)},[u,y,p.data,e,v,d]);const S=(B,W,K,te)=>{const G=Xx(Number(W),K,te);w.current=B,b(M=>({status:"loaded",data:{...M.data??Mn,[B]:G},error:null})),g(!0),x("idle")},N=m,E=p.data??Mn,T=A.status==="loaded",O=A.projectActiveCount(e),I=Yo("maxConcurrent",E.maxConcurrent),z=p.status==="loaded"&&E.worktreeLimitEnabled,D=p.status==="loaded",V=X2(O,E.maxConcurrent,Yr.maxConcurrent.min,I);return s.jsx("section",{className:"cc-controls","data-testid":"command-center-controls","aria-label":d("commandCenter.controls.title","Operator controls"),children:s.jsxs("div",{className:"cc-controls-grid",children:[s.jsxs("section",{className:"card cc-controls-card","data-testid":"cc-controls-engine",children:[s.jsxs("div",{className:"cc-controls-card-header",children:[s.jsxs("div",{children:[s.jsx("h3",{children:d("commandCenter.controls.engine.title","AI engine")}),s.jsx("p",{children:d("commandCenter.controls.engine.description","Stopping the engine halts all AI work.")})]}),s.jsx(J2,{paused:N,label:N?d("commandCenter.controls.status.stopped","Stopped"):d("commandCenter.controls.status.running","Running")})]}),s.jsxs("button",{type:"button",className:"btn btn-secondary cc-controls-action",onClick:()=>void h(),children:[s.jsx(Mh,{size:16,"aria-hidden":"true"}),s.jsx("span",{children:N?d("header.startAiEngine","Start AI Engine"):d("header.stopAiEngine","Stop AI Engine")})]}),c?s.jsxs("div",{className:"cc-overview-engine-nav","data-testid":"command-center-engine-panel",children:[s.jsx("button",{type:"button",className:"btn btn-secondary cc-overview-engine-nav-btn",onClick:()=>c("board"),children:d("commandCenter.controls.engine.viewBoard","View Board")}),s.jsx("button",{type:"button",className:"btn btn-secondary cc-overview-engine-nav-btn",onClick:()=>c("agents"),children:d("commandCenter.controls.engine.viewAgents","View Agents")})]}):null]}),s.jsxs("section",{className:"card cc-controls-card","data-testid":"cc-controls-theme",children:[s.jsx("div",{className:"cc-controls-card-header",children:s.jsxs("div",{children:[s.jsx("h3",{children:d("commandCenter.controls.theme.title","Theme")}),s.jsx("p",{children:d("commandCenter.controls.theme.description","Switch the dashboard theme with live color previews.")})]})}),s.jsx(nw,{colorTheme:t,themeMode:r,shadcnCustomColors:n,resolvedThemeMode:a,onColorThemeChange:i,onThemeModeChange:o,onShadcnCustomColorsChange:l})]}),s.jsxs("section",{className:"card cc-controls-card cc-controls-card--concurrency","data-testid":"cc-controls-concurrency",children:[s.jsxs("div",{className:"cc-controls-card-header",children:[s.jsxs("div",{children:[s.jsx("h3",{children:d("commandCenter.controls.concurrency.title","Concurrency")}),s.jsx("p",{children:d("commandCenter.controls.concurrency.description","Tune live scheduler capacity.")})]}),s.jsx("span",{className:`cc-controls-save-state cc-controls-save-state--${j}`,"aria-live":"polite",children:p.status==="loading"?d("commandCenter.controls.status.loading","Loading…"):j==="saving"?d("commandCenter.controls.status.saving","Saving…"):j==="saved"?d("commandCenter.controls.status.saved","Saved"):j==="error"?d("commandCenter.controls.status.saveError","Save failed"):d("commandCenter.controls.status.ready","Ready")})]}),s.jsxs("div",{className:"cc-controls-sliders",children:[s.jsxs("label",{className:"cc-controls-slider",htmlFor:"cc-max-concurrent",children:[s.jsxs("span",{className:"cc-controls-slider-label",children:[d("commandCenter.controls.concurrency.maxConcurrent","Max concurrent tasks"),s.jsx("strong",{children:E.maxConcurrent})]}),T?s.jsxs(s.Fragment,{children:[s.jsx("small",{className:"cc-controls-slider-caption","data-testid":"cc-project-running",children:d("commandCenter.controls.concurrency.runningProject","{{count}} running (this project)",{count:O})}),s.jsx("small",{className:"cc-controls-slider-caption","data-testid":"cc-global-running",children:d("commandCenter.controls.concurrency.runningGlobal","{{count}} running (all projects)",{count:A.currentlyActive})})]}):null,s.jsxs("span",{className:"cc-controls-range-wrap",children:[s.jsx("input",{id:"cc-max-concurrent",className:"cc-controls-touch-slider",type:"range",min:Yr.maxConcurrent.min,max:I,value:E.maxConcurrent,disabled:!D,onChange:B=>S("maxConcurrent",B.target.value,Yr.maxConcurrent.min,I)}),T?s.jsx("span",{className:"status-dot status-dot--online cc-controls-use-marker",style:Y2(V),"data-testid":"cc-project-use-marker","aria-hidden":"true"}):null]})]}),s.jsxs("label",{className:"cc-controls-slider",htmlFor:"cc-max-worktrees",children:[s.jsxs("span",{className:"cc-controls-slider-label",children:[d("commandCenter.controls.concurrency.maxWorktrees","Max worktrees"),s.jsx("strong",{children:E.maxWorktrees})]}),s.jsx("span",{className:"cc-controls-range-wrap",children:s.jsx("input",{id:"cc-max-worktrees",className:"cc-controls-touch-slider",type:"range",min:Yr.maxWorktrees.min,max:Yo("maxWorktrees",E.maxWorktrees),value:E.maxWorktrees,disabled:!z,onChange:B=>S("maxWorktrees",B.target.value,Yr.maxWorktrees.min,Yo("maxWorktrees",E.maxWorktrees))})}),!E.worktreeLimitEnabled&&p.status==="loaded"?s.jsx("small",{className:"cc-controls-slider-caption",children:d("commandCenter.controls.concurrency.worktreeLimitDisabled","Enable the worktree limit in Settings to edit this capacity.")}):null]})]}),p.status==="error"?s.jsx("p",{className:"cc-controls-error",role:"alert",children:p.error}):null]})]})})}function wh(e){return`${(e*100).toFixed(1)}%`}function Ch(e){return e===null?"—":`${(e/6e4).toFixed(1)}m`}function Ia(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function eF({projectId:e}={}){const{t}=se("app"),[r,n]=f.useState(null),[a,i]=f.useState(!0),[o,l]=f.useState(null),[c,d]=f.useState(!1),[u,m]=f.useState(!1),[h,v]=f.useState(null),p=f.useCallback(async()=>{i(!0),l(null);try{const T=await fr(mr("/health/reliability",e));n(T)}catch(T){l(T instanceof Error?T.message:t("reliability.failedToLoad","Failed to load reliability metrics"))}finally{i(!1)}},[t,e]),b=f.useCallback(async()=>{v(null),await fr(mr("/health/reliability/reset",e),{method:"POST"}),await p(),m(!1)},[p,e]);f.useEffect(()=>{p();const T=setInterval(()=>{p()},6e4);return()=>clearInterval(T)},[p]);const y=r?.headline.inReviewFailureRate7d,g=f.useMemo(()=>y==null?null:Math.max(0,Math.min(1,1-y)),[y]),j=f.useMemo(()=>g===null?"var(--text-muted)":g>=.95?"var(--color-success)":g>=.9?"var(--color-warning)":"var(--color-error)",[g]),x=f.useMemo(()=>(r?.perDay??[]).reduce((T,O)=>T+O.tasksEnteredInReview,0),[r?.perDay]),C=f.useMemo(()=>(r?.perDay??[]).reduce((T,O)=>T+O.tasksBouncedToInProgress,0),[r?.perDay]),w=f.useMemo(()=>r?.perDay?[...c?r.perDay:r.perDay.filter(O=>O.hasSamples!==!1)].sort((O,I)=>O.date.localeCompare(I.date)):[],[r?.perDay,c]),P=f.useMemo(()=>w.some(O=>O.tasksEnteredInReview>0||O.tasksBouncedToInProgress>0)?[{label:t("reliability.flowChart.entered","Entered"),values:w.map(O=>O.tasksEnteredInReview)},{label:t("reliability.flowChart.bounced","Bounced"),values:w.map(O=>O.tasksBouncedToInProgress)}]:[],[w,t]),A=f.useMemo(()=>Object.entries(r?.mergeAttempts.histogram??{}).sort(([T],[O])=>T.localeCompare(O,void 0,{numeric:!0})),[r?.mergeAttempts.histogram]),S=f.useMemo(()=>A.map(([T,O])=>({label:T,value:O})),[A]),N=f.useMemo(()=>A.reduce((T,[,O])=>T+O,0),[A]),E=r?Ia(r.resetAt??new Date(Date.parse(r.generatedAt)-r.windowDays*864e5).toISOString()):"—";return a&&r===null?s.jsxs("div",{className:"reliability-loading","data-testid":"reliability-loading",children:[s.jsx(Ql,{size:24,className:"spin"}),s.jsx("p",{children:t("reliability.loading","Loading reliability data...")})]}):o!==null&&r===null?s.jsxs("div",{className:"reliability-error","data-testid":"reliability-error",role:"alert",children:[s.jsx(Mi,{size:24}),s.jsx("p",{children:o})]}):s.jsxs("section",{className:"reliability-view",children:[s.jsxs("div",{className:"card reliability-card reliability-headline-card",children:[s.jsxs("div",{className:"reliability-section-header",children:[s.jsx("h2",{children:t("reliability.heading","Reliability")}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>m(!0),children:t("reliability.resetStats","Reset stats")})]}),s.jsx("div",{className:"reliability-headline",style:{color:j},children:y==null?t("reliability.insufficientData","Insufficient data — {{reason}}",{reason:r?.headline.reason??"unknown"}):wh(g??0)}),g!==null?s.jsx("div",{className:"reliability-muted",children:t("reliability.successRateLabel","In-review success rate (last 7d)")}):null,r?.resetAt?s.jsx("div",{className:"reliability-muted",children:t("reliability.countingSince","Counting since {{date}}",{date:Ia(r.resetAt)})}):null,s.jsxs("details",{className:"reliability-details",children:[s.jsx("summary",{children:t("reliability.details","Details")}),s.jsxs("div",{className:"reliability-details-content",children:[s.jsx("div",{children:t("reliability.bouncedEntered","{{bounced}} bounced / {{entered}} entered (last {{days}}d)",{bounced:C,entered:x,days:r?.windowDays??7})}),y!=null?s.jsx("div",{children:t("reliability.failureRate","Failure rate: {{rate}}",{rate:wh(y)})}):null,s.jsx("div",{children:t("reliability.window","Window: {{start}} → {{end}}",{start:E,end:Ia(r?.generatedAt)})}),r?.resetAt?s.jsx("div",{children:t("reliability.resetBaseline","Reset baseline: {{date}}",{date:Ia(r.resetAt)})}):null,r?.headline.reason?s.jsx("div",{children:t("reliability.reason","Reason: {{reason}}",{reason:r.headline.reason})}):null]})]})]}),s.jsxs("div",{className:"reliability-grid",children:[s.jsxs("div",{className:"card reliability-card",children:[s.jsxs("div",{className:"reliability-section-header",children:[s.jsx("h3",{children:t("reliability.inReviewFlow","In-review flow")}),s.jsx("button",{className:"btn btn-sm",onClick:()=>d(T=>!T),children:c?t("reliability.hideEmptyDays","Hide empty days"):t("reliability.showEmptyDays","Show empty days")})]}),s.jsxs("div",{className:"reliability-chart-section","data-testid":"reliability-flow-chart",children:[s.jsx("h4",{children:t("reliability.flowChart.heading","Entered vs bounced trend")}),s.jsx(br,{series:P,ariaLabel:t("reliability.flowChart.aria","In-review entered vs bounced per day"),emptyLabel:t("reliability.flowChart.empty","No in-review flow data")})]}),s.jsxs("table",{className:"reliability-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:t("reliability.table.date","Date")}),s.jsx("th",{children:t("reliability.table.entered","Entered")}),s.jsx("th",{children:t("reliability.table.bounced","Bounced")})]})}),s.jsx("tbody",{children:w.map(T=>s.jsxs("tr",{children:[s.jsx("td",{children:T.date}),s.jsx("td",{children:T.tasksEnteredInReview}),s.jsx("td",{children:T.tasksBouncedToInProgress})]},T.date))})]})]}),s.jsxs("div",{className:"card reliability-card",children:[s.jsx("h3",{children:t("reliability.duration.heading","Duration")}),s.jsxs("div",{className:"reliability-stat-row",children:[s.jsx("span",{children:t("reliability.duration.p50","P50")}),s.jsx("strong",{children:Ch(r?.duration.p50Ms??null)})]}),s.jsxs("div",{className:"reliability-stat-row",children:[s.jsx("span",{children:t("reliability.duration.p95","P95")}),s.jsx("strong",{children:Ch(r?.duration.p95Ms??null)})]}),s.jsx("div",{className:"reliability-muted",children:t("reliability.duration.samples","Samples: {{count}}",{count:r?.duration.sampleCount??0})}),s.jsxs("details",{className:"reliability-details",children:[s.jsx("summary",{children:t("reliability.duration.moreStats","More stats")}),s.jsxs("div",{className:"reliability-details-content",children:[s.jsx("div",{children:t("reliability.duration.p50Raw","P50 raw: {{value}} ms",{value:r?.duration.p50Ms??"—"})}),s.jsx("div",{children:t("reliability.duration.p95Raw","P95 raw: {{value}} ms",{value:r?.duration.p95Ms??"—"})}),s.jsx("div",{children:t("reliability.duration.sampleCount","Sample count: {{count}}",{count:r?.duration.sampleCount??0})}),r?.duration.reason?s.jsx("div",{children:t("reliability.duration.reason","Reason: {{reason}}",{reason:r.duration.reason})}):null]})]})]}),s.jsxs("div",{className:"card reliability-card",children:[s.jsx("h3",{children:t("reliability.mergeAttempts.heading","Merge attempts")}),s.jsxs("div",{className:"reliability-stat-row",children:[s.jsx("span",{children:t("reliability.mergeAttempts.mean","Mean")}),s.jsx("strong",{children:r?.mergeAttempts.mean?.toFixed(2)??"—"})]}),s.jsxs("div",{className:"reliability-stat-row",children:[s.jsx("span",{children:t("reliability.mergeAttempts.max","Max")}),s.jsx("strong",{children:r?.mergeAttempts.max??"—"})]}),s.jsxs("div",{className:"reliability-chart-section","data-testid":"reliability-merge-attempts-chart",children:[s.jsx("h4",{children:t("reliability.mergeAttemptsChart.heading","Attempts distribution")}),s.jsx(Mt,{data:S,ariaLabel:t("reliability.mergeAttemptsChart.aria","Merge attempts histogram"),emptyLabel:t("reliability.mergeAttemptsChart.empty","No merge attempt data")})]}),s.jsx("ul",{className:"reliability-histogram",children:A.map(([T,O])=>s.jsxs("li",{children:[s.jsx("span",{children:T}),s.jsx("div",{className:"reliability-histogram-bar-wrap",children:s.jsx("div",{className:"reliability-histogram-bar",style:{width:`${Math.min(O*20,100)}%`}})}),s.jsx("strong",{children:O})]},T))}),s.jsxs("details",{className:"reliability-details",children:[s.jsx("summary",{children:t("reliability.mergeAttempts.moreStats","More stats")}),s.jsxs("div",{className:"reliability-details-content",children:[s.jsx("div",{children:t("reliability.mergeAttempts.tasksCounted","Tasks counted: {{count}}",{count:N})}),s.jsx("div",{children:t("reliability.mergeAttempts.histogramTotal","Histogram total: {{count}}",{count:N})}),r?.mergeAttempts.reason?s.jsx("div",{children:t("reliability.mergeAttempts.reason","Reason: {{reason}}",{reason:r.mergeAttempts.reason})}):null]})]})]})]}),u?s.jsx("div",{className:"modal-overlay open",role:"presentation",children:s.jsxs("div",{className:"modal",role:"dialog","aria-modal":"true","aria-labelledby":"reliability-reset-title",children:[s.jsx("div",{className:"modal-header",children:s.jsx("h2",{id:"reliability-reset-title",children:t("reliability.resetModal.title","Reset reliability stats?")})}),s.jsx("p",{children:t("reliability.resetModal.description","This sets a new baseline for reliability statistics. Historical events older than the reset time are excluded from counts but are not deleted.")}),h?s.jsx("div",{className:"form-error",children:h}):null,s.jsxs("div",{className:"modal-actions",children:[s.jsx("button",{className:"btn",onClick:()=>m(!1),children:t("common.cancel","Cancel")}),s.jsx("button",{className:"btn btn-danger",onClick:()=>{b().catch(T=>{v(T instanceof Error?T.message:t("reliability.resetModal.failedError","Failed to reset reliability stats"))})},children:t("reliability.resetModal.confirm","Confirm reset")})]})]})}):null]})}function Zo(e){const{lastSyncAt:t,remoteReachable:r,diff:n}=e,a=Object.values(n.workflowSettings).reduce((o,l)=>o+l.length,0),i=n.global.length+n.project.length+a;return t===null?{syncState:"never-synced",lastSyncAt:t,diffCount:0}:r?i>0?{syncState:"diff",lastSyncAt:t,diffCount:i}:{syncState:"synced",lastSyncAt:t,diffCount:0}:{syncState:"error",lastSyncAt:t,diffCount:i}}function Xl(e){if(e===null)return"Never synced";const t=new Date(e);if(Number.isNaN(t.getTime()))return"Never synced";const n=Date.now()-t.getTime(),a=Math.floor(n/1e3),i=Math.floor(a/60),o=Math.floor(i/60),l=Math.floor(o/24);return i<1?"Synced just now":i<60?`Synced ${i}m ago`:o<24?`Synced ${o}h ago`:`Synced ${l}d ago`}function tF(e){switch(e){case"synced":return"var(--color-success)";case"pending":return"var(--color-warning)";case"diff":return"var(--color-warning)";case"error":return"var(--color-error)";case"never-synced":return"var(--text-muted)"}}const rF=3e4;function nF(){const{t:e}=se("app"),[t,r]=f.useState({}),[n,a]=f.useState(!1),[i,o]=f.useState({}),[l,c]=f.useState(null),d=f.useRef(new Set),u=f.useRef(!1),m=f.useRef(null),[h,v]=f.useState(!0),p=f.useCallback(async(S,N)=>{try{const E=await Vj(S);r(T=>({...T,[S]:E})),c(null)}catch(E){if(E?.status===409){d.current.delete(S);return}console.error(`Failed to fetch sync status for node ${S}:`,E),c(E instanceof Error?E.message:e("nodeSync.error.failedToFetchStatus","Failed to fetch sync status"))}},[e]),b=f.useCallback(async()=>{const S=Array.from(d.current);if(S.length===0)return;m.current&&m.current.abort(),m.current=new AbortController;const N=!u.current;N&&a(!0),c(null);try{const E=await Promise.allSettled(S.map(O=>p(O,N)));u.current=!0,E.filter(O=>O.status==="rejected").length>0&&c(e("nodeSync.error.someRequestsFailed","Some sync status requests failed"))}catch(E){if(E instanceof Error&&E.name==="AbortError")return;c(E instanceof Error?E.message:e("nodeSync.error.failedToFetchStatus","Failed to fetch sync status")),u.current=!0}finally{a(!1)}},[p,e]),y=f.useCallback(()=>{v(!1)},[]);f.useEffect(()=>(b(),()=>{m.current&&m.current.abort()}),[b]),vn(b,rF,{enabled:h});const g=f.useCallback(S=>{d.current.has(S)||(d.current.add(S),p(S,!u.current))},[p]),j=f.useCallback(S=>{d.current.delete(S),r(N=>{const E={...N};return delete E[S],E}),d.current.size===0&&y()},[y]),x=f.useCallback(async S=>{o(N=>({...N,[S]:!0})),c(null);try{const N=await Uj(S);return p(S,!1),!N.success&&N.error&&c(N.error),N}catch(N){const E=N instanceof Error?N.message:e("nodeSync.error.pushFailed","Push settings failed");throw c(E),N}finally{o(N=>{const E={...N};return delete E[S],E})}},[p,e]),C=f.useCallback(async S=>{o(N=>({...N,[S]:!0})),c(null);try{const N=await qj(S);return p(S,!1),!N.success&&N.error&&c(N.error),N}catch(N){const E=N instanceof Error?N.message:e("nodeSync.error.pullFailed","Pull settings failed");throw c(E),N}finally{o(N=>{const E={...N};return delete E[S],E})}},[p,e]),w=f.useCallback(async S=>{o(N=>({...N,[S]:!0})),c(null);try{return await Wj(S)}catch(N){const E=N instanceof Error?N.message:e("nodeSync.error.authSyncFailed","Auth sync failed");throw c(E),N}finally{o(N=>{const E={...N};return delete E[S],E})}},[e]),P=f.useCallback(S=>t[S]?.authMatch,[t]),A=f.useCallback(S=>t[S]?.authDiff,[t]);return{syncStatusMap:t,loading:n,actionLoading:i,error:l,refresh:b,trackNode:g,untrackNode:j,pushSettings:x,pullSettings:C,syncAuth:w,getAuthSyncState:P,getAuthProviders:A}}const aF=1e4,iF=1e3;function sF(){const{t:e}=se("app"),[t,r]=f.useState([]),[n,a]=f.useState(!0),[i,o]=f.useState(null),l=f.useRef(0),c=f.useRef(t),d=nc();f.useEffect(()=>{c.current=t},[t]);const u=f.useCallback(h=>c.current.length>0&&ac(h,d.wasRecentlyHidden()),[d]),m=f.useCallback(async()=>{try{o(null);const h=await Ku();r(h.nodes)}catch(h){const v=h instanceof Error?h.message:e("mesh.failedToFetchMeshState","Failed to fetch mesh state");u(v)||o(v)}},[u,e]);return f.useEffect(()=>{let h=!1;async function v(){a(!0);try{const b=await Ku();h||(r(b.nodes),o(null))}catch(b){const y=b instanceof Error?b.message:e("mesh.failedToFetchMeshState","Failed to fetch mesh state");!h&&!u(y)&&o(y)}finally{h||a(!1)}}v();const p=()=>{if(document.visibilityState!=="visible")return;const b=Date.now(),y=b-l.current;if(y<iF){Wa({view:"useMeshState",trigger:"visibility",projectId:void 0,replayAttempted:!1,reason:"debounce-skipped",detail:{timeSinceLastRefreshMs:y}});return}l.current=b,Wa({view:"useMeshState",trigger:"visibility",projectId:void 0,replayAttempted:!1,reason:"debounced-refresh"}),m()};return document.addEventListener("visibilitychange",p),()=>{h=!0,document.removeEventListener("visibilitychange",p)}},[m,u,e]),vn(m,aF,{enabled:!n,refreshOnVisible:!1}),{meshState:t,loading:n,error:i,refresh:m}}const oF=1e4,lF=1e3;function cF(){const{t:e}=se("app"),[t,r]=f.useState([]),[n,a]=f.useState(!0),[i,o]=f.useState(null),l=f.useRef(null),c=f.useRef(0),d=f.useRef(t),u=nc();f.useEffect(()=>{d.current=t},[t]);const m=f.useCallback(v=>d.current.length>0&&ac(v,u.wasRecentlyHidden()),[u]),h=f.useCallback(async()=>{try{o(null);const v=await Vu();r(v.engines)}catch(v){const p=v instanceof Error?v.message:e("mesh.failedToFetchEngines","Failed to fetch engine status");m(p)||o(p)}},[m,e]);return f.useEffect(()=>{let v=!1;async function p(){a(!0);try{const y=await Vu();v||(r(y.engines),o(null))}catch(y){const g=y instanceof Error?y.message:e("mesh.failedToFetchEngines","Failed to fetch engine status");!v&&!m(g)&&o(g)}finally{v||a(!1)}}p();const b=()=>{if(document.visibilityState!=="visible")return;const y=Date.now();y-c.current<lF||(c.current=y,h())};return document.addEventListener("visibilitychange",b),()=>{v=!0,document.removeEventListener("visibilitychange",b)}},[h,m,e]),f.useEffect(()=>{if(!n)return l.current=setInterval(()=>{h()},oF),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[n,h]),{engines:t,loading:n,error:i,refresh:h}}function uF(e){return{online:{label:e("nodes.status.online","Online"),color:"var(--color-success)",className:"node-card__status--online"},offline:{label:e("nodes.status.offline","Offline"),color:"var(--color-error)",className:"node-card__status--offline"},connecting:{label:e("nodes.status.connecting","Connecting"),color:"var(--color-warning)",className:"node-card__status--connecting"},error:{label:e("nodes.status.error","Error"),color:"var(--color-error)",className:"node-card__status--error"},creating:{label:e("nodes.status.creating","Creating"),color:"var(--color-warning)",className:"node-card__status--creating"},recreating:{label:e("nodes.status.recreating","Recreating"),color:"var(--color-warning)",className:"node-card__status--recreating"},deleting:{label:e("nodes.status.deleting","Deleting"),color:"var(--color-error)",className:"node-card__status--deleting"},running:{label:e("nodes.status.running","Running"),color:"var(--color-success)",className:"node-card__status--online"},stopped:{label:e("nodes.status.stopped","Stopped"),color:"var(--color-error)",className:"node-card__status--offline"},exited:{label:e("nodes.status.exited","Exited"),color:"var(--color-error)",className:"node-card__status--offline"}}}const dF={match:"var(--color-success)",differs:"var(--color-warning)","not-synced":"var(--text-muted)"};function fF(e,t,r){if(e==="match")return r?r("nodes.auth.match","Auth credentials match"):"Auth credentials match";if(e==="not-synced")return r?r("nodes.auth.notSynced","Auth not synced"):"Auth not synced";if(t&&Object.keys(t).length>0){const n=Object.entries(t).filter(([,a])=>a==="differs").map(([a])=>a);if(n.length>0)return r?r("nodes.auth.differProviders","Auth credentials differ: {{providers}}",{providers:n.join(", ")}):`Auth credentials differ: ${n.join(", ")}`}return r?r("nodes.auth.differ","Auth credentials differ"):"Auth credentials differ"}function mF(e,t=42){return e.length<=t?e:`${e.slice(0,t-3)}...`}function vF(e,t){const r=e.node,n=t.node;if(r.id!==n.id||r.name!==n.name||r.type!==n.type||r.url!==n.url||r.status!==n.status||r.maxConcurrent!==n.maxConcurrent||r.updatedAt!==n.updatedAt||e.isLoading!==t.isLoading)return!1;const a=e.managedDockerNode,i=t.managedDockerNode;if(!!a!=!!i||a&&i&&(a.id!==i.id||a.status!==i.status||a.imageTag!==i.imageTag||a.updatedAt!==i.updatedAt))return!1;const o=e.syncStatus,l=t.syncStatus;if(!(!o&&!l)){if(!o||!l)return!1;if(o.syncState!==l.syncState||o.lastSyncAt!==l.lastSyncAt||o.diffCount!==l.diffCount)return!1}if(e.authSyncState!==t.authSyncState)return!1;const c=e.authSyncProviders,d=t.authSyncProviders;if(c!==d){if(!c||!d)return!1;{const h=Object.keys(c),v=Object.keys(d);if(h.length!==v.length||h.some(p=>c[p]!==d[p]))return!1}}const u=tl(e.projects,r),m=tl(t.projects,n);return u===m}function hF({node:e,projects:t,onHealthCheck:r,onEdit:n,onRemove:a,isLoading:i=!1,syncStatus:o,authSyncState:l,authSyncProviders:c,managedDockerNode:d}){const{t:u}=se("app"),[m,h]=f.useState(!1),v=uF(u),p=v[e.status]??v.offline,b=d?v[d.status]??v.error:null,y=d?.hostConfig.type==="remote"?u("nodes.dockerHost.remote","Remote: {{host}}",{host:d.hostConfig.host??"unknown"}):u("nodes.dockerHost.local","Local Docker"),g=f.useMemo(()=>tl(t,e),[t,e]),j=f.useCallback(()=>{n(e)},[n,e]),x=f.useCallback(A=>{A.stopPropagation(),r(e.id)},[r,e.id]),C=f.useCallback(A=>{A.stopPropagation(),n(e)},[n,e]),w=f.useCallback(A=>{if(A.stopPropagation(),!m){h(!0);return}a(e.id),h(!1)},[m,a,e.id]),P=f.useCallback(A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),n(e))},[n,e]);return s.jsxs("article",{className:`node-card ${i?"node-card--loading":""}`,"data-node-id":e.id,role:"button",tabIndex:0,onClick:j,onKeyDown:P,children:[s.jsx("header",{className:"node-card__header",children:s.jsxs("div",{className:"node-card__title-wrap",children:[s.jsx("div",{className:"node-card__icon",children:s.jsx(Ih,{size:18})}),s.jsxs("div",{children:[s.jsx("h3",{className:"node-card__name",title:e.name,children:e.name}),s.jsxs("div",{className:"node-card__meta-row",children:[s.jsx("span",{className:"node-card__type-badge",children:e.type==="local"?u("nodes.type.local","Local"):u("nodes.type.remote","Remote")}),d&&s.jsxs("span",{className:"node-card__docker-badge",title:u("nodes.dockerBadge","Managed Docker node"),children:[s.jsx(rl,{size:12,"aria-hidden":!0}),u("nodes.dockerLabel","Docker")]}),s.jsxs("span",{className:`node-card__status ${p.className}`,style:{color:p.color},"data-status":e.status,children:[s.jsx("span",{className:"node-card__status-indicator",style:{backgroundColor:p.color},"aria-hidden":!0}),p.label]}),d&&b&&s.jsxs("span",{className:`node-card__status ${b.className}`,style:{color:b.color},"data-status":d.status,children:[s.jsx("span",{className:"node-card__status-indicator",style:{backgroundColor:b.color},"aria-hidden":!0}),b.label]}),e.type==="remote"&&l&&s.jsx("span",{className:`node-card__auth-indicator node-card__auth-indicator--${l}`,title:fF(l,c,u),"aria-label":u("nodes.authSync.label","Auth sync: {{status}}",{status:l==="match"?u("nodes.authSync.match","credentials match"):l==="differs"?u("nodes.authSync.differ","credentials differ"):u("nodes.authSync.notSynced","not synced")}),style:{color:dF[l]},children:s.jsx(Dh,{size:14})})]})]})]})}),s.jsxs("div",{className:"node-card__body",children:[e.type==="remote"&&e.url&&s.jsx("div",{className:"node-card__url",title:e.url,children:mF(e.url)}),d&&s.jsxs("div",{className:"node-card__docker-meta",children:[s.jsxs("span",{title:`${d.imageName}:${d.imageTag}`,children:[d.imageName,":",d.imageTag]}),s.jsx("span",{title:y,children:y})]}),s.jsxs("div",{className:"node-card__metrics",children:[s.jsxs("div",{className:"node-card__metric",children:[s.jsx("span",{className:"node-card__metric-label",children:u("nodes.metrics.projects","Projects")}),s.jsx("span",{className:"node-card__metric-value",children:g})]}),s.jsxs("div",{className:"node-card__metric",children:[s.jsx("span",{className:"node-card__metric-label",children:u("nodes.metrics.concurrency","Concurrency")}),s.jsx("span",{className:"node-card__metric-value",children:e.maxConcurrent})]})]}),e.type==="remote"&&o&&s.jsxs("div",{className:"node-card__sync","data-sync-state":o.syncState,"data-testid":"node-card-sync",children:[s.jsx("span",{className:"node-card__sync-dot",style:{backgroundColor:tF(o.syncState)},"aria-hidden":!0}),s.jsx("span",{className:"node-card__sync-time",children:Xl(o.lastSyncAt)})]})]}),s.jsxs("footer",{className:"node-card__actions",children:[s.jsxs("button",{className:"btn btn-sm node-card__action",type:"button",onClick:x,disabled:i,"aria-label":u("nodes.actions.health.ariaLabel","Run node health check"),title:u("nodes.actions.health.title","Health Check"),children:[s.jsx(Rh,{size:14}),s.jsx("span",{children:u("nodes.actions.health.label","Health")})]}),s.jsxs("button",{className:"btn btn-sm node-card__action",type:"button",onClick:C,disabled:i,"aria-label":u("nodes.actions.edit.ariaLabel","Edit node"),title:u("nodes.actions.edit.title","Edit"),children:[s.jsx(La,{size:14}),s.jsx("span",{children:u("nodes.actions.edit.label","Edit")})]}),d&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{className:"btn btn-sm node-card__action",type:"button",disabled:!0,"aria-label":u("nodes.actions.start.ariaLabel","Start node container"),title:u("nodes.actions.start.title","Available after FN-3113"),children:[s.jsx(Di,{size:14}),s.jsx("span",{children:u("nodes.actions.start.label","Start")})]}),s.jsxs("button",{className:"btn btn-sm node-card__action",type:"button",disabled:!0,"aria-label":u("nodes.actions.stop.ariaLabel","Stop node container"),title:u("nodes.actions.stop.title","Available after FN-3113"),children:[s.jsx(Lh,{size:14}),s.jsx("span",{children:u("nodes.actions.stop.label","Stop")})]}),s.jsxs("button",{className:"btn btn-sm node-card__action",type:"button",disabled:!0,"aria-label":u("nodes.actions.restart.ariaLabel","Restart node container"),title:u("nodes.actions.restart.title","Available after FN-3113"),children:[s.jsx(Hj,{size:14}),s.jsx("span",{children:u("nodes.actions.restart.label","Restart")})]})]}),s.jsxs("button",{className:`btn btn-sm node-card__action node-card__action--remove ${m?"btn-danger is-armed":""}`,type:"button",onClick:w,disabled:i,"aria-label":m?u("nodes.actions.remove.ariaLabelConfirm","Confirm remove node"):u("nodes.actions.remove.ariaLabel","Remove node"),title:m?u("nodes.actions.remove.titleConfirm","Confirm remove"):u("nodes.actions.remove.title","Remove"),children:[s.jsx(tn,{size:14}),s.jsx("span",{children:m?u("nodes.actions.remove.labelConfirm","Confirm"):u("nodes.actions.remove.label","Remove")})]})]})]})}const pF=f.memo(hF,vF),In={online:"var(--success, var(--color-success))",offline:"var(--text-dim)",connecting:"var(--color-warning)",error:"var(--color-error)"},Da=28,yF=12,gF=300,bF=120;function xF({nodes:e,engines:t,className:r}){const{t:n}=se("app"),a=f.useMemo(()=>e.find(v=>v.nodeType==="local")??e[0],[e]),i=f.useMemo(()=>e.filter(v=>v.nodeId!==a?.nodeId),[e,a?.nodeId]),o=f.useMemo(()=>(t??[]).reduce((v,p)=>v+(p.inFlightTasks??0),0),[t]),l=f.useMemo(()=>(t??[]).reduce((v,p)=>v+(p.activeAgents??0),0),[t]),c=f.useMemo(()=>gF+Math.max(0,i.length-4)*20,[i.length]),d=c/2,u=c/2,m=f.useMemo(()=>{const v=new Map;if(a&&v.set(a.nodeId,{x:d,y:u,node:a}),i.length>0){const p=Math.min(bF,c/2-Da-10),b=2*Math.PI/i.length,y=-Math.PI/2;i.forEach((g,j)=>{const x=y+j*b;v.set(g.nodeId,{node:g,x:d+p*Math.cos(x),y:u+p*Math.sin(x)})})}return v},[d,u,a,i,c]),h=f.useMemo(()=>{const v=new Set,p=[];for(const b of e){const y=m.get(b.nodeId);if(y)for(const g of b.knownPeers){const j=m.get(g.peerNodeId);if(!j)continue;const x=[b.nodeId,g.peerNodeId].sort().join("::");v.has(x)||(v.add(x),p.push({key:x,from:y,to:j}))}}return p},[m,e]);return e.length===0?s.jsx("div",{className:`mesh-topology mesh-topology--empty ${r??""}`,children:s.jsx("div",{className:"mesh-topology__empty-state",children:s.jsx("p",{children:n("mesh.noNodes","No nodes to display")})})}):s.jsxs("div",{className:`mesh-topology ${r??""}`,children:[s.jsxs("svg",{className:"mesh-topology__svg",viewBox:`0 0 ${c} ${c}`,preserveAspectRatio:"xMidYMid meet","aria-label":n("mesh.ariaLabel","Node mesh topology visualization"),children:[h.map(v=>s.jsx("line",{className:"mesh-topology__link mesh-topology__peer-line",x1:v.from.x,y1:v.from.y,x2:v.to.x,y2:v.to.y},v.key)),Array.from(m.values()).map(({node:v,x:p,y:b})=>s.jsxs("g",{className:"mesh-topology__node",transform:`translate(${p}, ${b})`,children:[s.jsx("circle",{className:"mesh-topology__node-circle",r:Da,fill:In[v.status],"aria-label":`${v.nodeName} (${v.status})`}),s.jsx("text",{className:"mesh-topology__node-label",y:Da+yF,textAnchor:"middle",children:v.nodeName.length>12?`${v.nodeName.slice(0,10)}…`:v.nodeName}),s.jsxs("g",{className:"mesh-topology__node-type",transform:`translate(0 ${-Da-10})`,children:[s.jsx("circle",{className:"mesh-topology__node-type-badge",r:"8"}),s.jsx("text",{className:"mesh-topology__node-type-text",textAnchor:"middle",dominantBaseline:"middle",children:v.nodeType==="local"?"L":"R"})]})]},v.nodeId))]}),(t??[]).length>0&&s.jsxs("div",{className:"mesh-topology__engines","aria-label":n("mesh.enginesAriaLabel","Active engine connections"),children:[s.jsxs("div",{className:"mesh-topology__engines-summary",children:[s.jsx("span",{className:"mesh-topology__engines-count",children:n("mesh.enginesConnected",{count:(t??[]).length,defaultValue:"{{count}} engine(s) connected to shared PG"})}),s.jsx("span",{className:"mesh-topology__engines-metric",children:n("mesh.inFlightTasks",{count:o,defaultValue:"{{count}} in-flight"})}),s.jsx("span",{className:"mesh-topology__engines-metric",children:n("mesh.activeAgents",{count:l,defaultValue:"{{count}} agents"})})]}),s.jsx("ul",{className:"mesh-topology__engines-list",children:(t??[]).map(v=>s.jsxs("li",{className:"mesh-topology__engine-item",children:[s.jsx("span",{className:"mesh-topology__engine-name",children:v.projectName??v.projectId}),s.jsx("span",{className:"mesh-topology__engine-status","data-runtime-status":v.runtimeStatus,children:v.runtimeStatus}),s.jsx("span",{className:"mesh-topology__engine-tasks",children:n("mesh.taskCount","{{count}} tasks",{count:v.inFlightTasks})})]},v.projectId))})]}),s.jsxs("div",{className:"mesh-topology__legend",children:[s.jsxs("div",{className:"mesh-topology__legend-item",children:[s.jsx("span",{className:"mesh-topology__legend-dot",style:{background:In.online}}),s.jsx("span",{children:n("mesh.online","Online")})]}),s.jsxs("div",{className:"mesh-topology__legend-item",children:[s.jsx("span",{className:"mesh-topology__legend-dot",style:{background:In.offline}}),s.jsx("span",{children:n("mesh.offline","Offline")})]}),s.jsxs("div",{className:"mesh-topology__legend-item",children:[s.jsx("span",{className:"mesh-topology__legend-dot",style:{background:In.connecting}}),s.jsx("span",{children:n("mesh.connecting","Connecting")})]}),s.jsxs("div",{className:"mesh-topology__legend-item",children:[s.jsx("span",{className:"mesh-topology__legend-dot",style:{background:In.error}}),s.jsx("span",{children:n("mesh.error","Error")})]})]}),h.length===0&&s.jsx("p",{className:"mesh-topology__notice",children:n("mesh.noPeers","Peer-to-peer discovery data unavailable.")})]})}const jF=f.memo(xF),Yl=1,Zl=10;function wF(e,t){const r={projectMappings:{}};e.name.trim()||(r.name=t("nodes.nameRequired","Name is required")),e.type==="remote"&&!e.url?.trim()&&(r.url=t("nodes.urlRequired","URL is required for remote nodes")),(!Number.isFinite(e.maxConcurrent)||e.maxConcurrent<Yl||e.maxConcurrent>Zl)&&(r.maxConcurrent=t("nodes.concurrencyRange","Concurrency must be between {{min}} and {{max}}",{min:Yl,max:Zl}));for(const n of e.projectMappings){const a=iw(n.path);a.valid||(r.projectMappings[n.projectId]=a.error??t("nodes.pathInvalid","Path is invalid"))}return r}function CF({isOpen:e,onClose:t,onSubmit:r,onDiscoverRemoteProjects:n,addToast:a,projects:i}){const{t:o}=se("app");Gj(e);const[l,c]=f.useState(""),[d,u]=f.useState("local"),[m,h]=f.useState(""),[v,p]=f.useState(""),[b,y]=f.useState(2),[g,j]=f.useState("auto-generate"),[x,C]=f.useState({}),[w,P]=f.useState({projectMappings:{}}),[A,S]=f.useState(!1),[N,E]=f.useState("idle"),[T,O]=f.useState(null),[I,z]=f.useState([]),D=f.useCallback(()=>{c(""),u("local"),h(""),p(""),y(2),j("auto-generate"),C({}),P({projectMappings:{}}),S(!1),E("idle"),O(null),z([])},[]),V=f.useCallback(()=>{A||(D(),t())},[A,t,D]);f.useEffect(()=>{if(!e){D();return}const M=q=>{q.key==="Escape"&&(q.preventDefault(),V())};return document.addEventListener("keydown",M),()=>{document.removeEventListener("keydown",M)}},[V,e,D]);const B=f.useMemo(()=>({name:l.trim(),type:d,url:d==="remote"&&m.trim()||void 0,apiKey:d==="remote"&&g==="provide"&&v||void 0,maxConcurrent:b,apiKeyMode:g,projectMappings:Object.entries(x).map(([M,q])=>({projectId:M,path:q.trim()}))}),[v,g,b,l,x,d,m]),W=f.useCallback(async()=>{if(A||N==="loading")return;const M=m.trim();if(!M){P(q=>({...q,url:o("nodes.urlRequired","URL is required for remote nodes")}));return}E("loading"),O(null);try{const q=await n({url:M,apiKey:g==="provide"&&v.trim().length>0?v:void 0});z(q.projects),E("success"),C(H=>{if(Object.keys(H).length===0)return H;const re={...H};for(const ae of i){if(!(ae.id in re))continue;const ye=q.projects.filter(oe=>oe.name===ae.name);ye.length===1&&(re[ae.id]=ye[0].path)}return re})}catch(q){E("error"),z([]),O(q instanceof Error?q.message:o("nodes.discoveryFailed","Failed to discover remote projects"))}},[v,g,N,A,n,i,o,m]);f.useEffect(()=>{if(d!=="remote"){E("idle"),O(null),z([]);return}E("idle"),O(null),z([])},[v,g,d,m]);const K=f.useCallback(async()=>{if(A)return;const M=wF(B,o);if(P(M),!(M.name||M.url||M.maxConcurrent||Object.keys(M.projectMappings).length>0)){if(B.type==="remote"&&N!=="success"){O(o("nodes.discoverBeforeAdding","Discover remote projects before adding this node."));return}S(!0);try{await r(B),a(o("nodes.registered",'Node "{{name}}" registered',{name:B.name}),"success"),V()}catch(q){const H=q instanceof Error?q.message:o("nodes.registerFailed","Failed to register node");a(H,"error")}finally{S(!1)}}},[a,V,N,B,A,r,o]),te=M=>{C(q=>{if(M.id in q){const{[M.id]:H,...re}=q;return re}if(d==="remote"&&N==="success"){const H=I.filter(re=>re.name===M.name);return H.length===1?{...q,[M.id]:H[0].path}:{...q,[M.id]:""}}return{...q,[M.id]:M.path}})},G=(M,q)=>{C(H=>({...H,[M]:q}))};return e?s.jsx(ic,{windowKey:"add-node",title:o("nodes.addNode","Add Node"),ariaLabel:o("nodes.addNode","Add Node"),onClose:V,hideHeader:!0,dragHandleSelector:".modal-header",className:"floating-window--add-node",defaultSize:{width:720,height:560},minSize:{width:360,height:280},persistGeometryKey:"floating-window:add-node",suspendGeometryPersistenceOnMobile:!0,suspendGeometryPersistenceOnShortViewport:!0,closeOnOutsidePointerDown:!0,children:s.jsxs("div",{className:"modal modal-md add-node-modal",children:[s.jsxs("div",{className:"modal-header",children:[s.jsx("h3",{children:o("nodes.addNode","Add Node")}),s.jsx("button",{className:"modal-close",onClick:V,disabled:A,"aria-label":o("nodes.closeNodeModal","Close add node modal"),children:"×"})]}),s.jsxs("div",{className:"modal-body add-node-modal__body",children:[s.jsx("p",{className:"add-node-modal__description",children:o("nodes.description","Register an existing Fusion node by providing its connection details and concurrency settings.")}),s.jsxs("label",{className:"add-node-modal__field",children:[s.jsx("span",{children:o("nodes.name","Name")}),s.jsx("input",{className:"input",type:"text",value:l,onChange:M=>c(M.target.value),placeholder:o("nodes.namePlaceholder","Build Machine"),disabled:A,"aria-invalid":!!w.name,autoFocus:!0}),w.name&&s.jsx("span",{className:"form-error add-node-modal__error",children:w.name})]}),s.jsxs("div",{className:"add-node-modal__type-toggle",children:[s.jsx("button",{type:"button",className:`add-node-modal__type-btn ${d==="local"?"active":""}`,"data-type":"local",onClick:()=>u("local"),disabled:A,"aria-pressed":d==="local",children:o("nodes.local","Local")}),s.jsx("button",{type:"button",className:`add-node-modal__type-btn ${d==="remote"?"active":""}`,"data-type":"remote",onClick:()=>u("remote"),disabled:A,"aria-pressed":d==="remote",children:o("nodes.remote","Remote")})]}),d==="remote"&&s.jsxs("div",{className:"add-node-modal__remote-fields","data-testid":"remote-fields-container","data-visible":!0,children:[s.jsxs("label",{className:"add-node-modal__field",children:[s.jsx("span",{children:o("nodes.reachableUrl","Reachable URL / Hostname")}),s.jsx("input",{className:"input",type:"text",value:m,onChange:M=>h(M.target.value),placeholder:"https://node.example.com",disabled:A,"aria-invalid":!!w.url}),w.url&&s.jsx("span",{className:"form-error add-node-modal__error",children:w.url})]}),s.jsxs("label",{className:"add-node-modal__field",children:[s.jsx("span",{children:o("nodes.apiKeyMode","API Key Mode")}),s.jsxs("select",{className:"select",value:g,onChange:M=>j(M.target.value),disabled:A,children:[s.jsx("option",{value:"auto-generate",children:o("nodes.autoGenerate","Auto-generate")}),s.jsx("option",{value:"provide",children:o("nodes.provideManually","Provide key manually")})]})]}),g==="provide"&&s.jsxs("label",{className:"add-node-modal__field",children:[s.jsx("span",{children:o("nodes.apiKey","API Key")}),s.jsx("input",{className:"input",type:"password",value:v,onChange:M=>p(M.target.value),placeholder:o("nodes.apiKeyPlaceholder","Enter node API key"),disabled:A})]}),s.jsxs("div",{className:"add-node-modal__discovery-actions",children:[s.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void W(),disabled:A||N==="loading",children:N==="loading"?o("nodes.discovering","Discovering..."):o("nodes.discoverRemoteProjects","Discover Remote Projects")}),N==="success"&&s.jsx("span",{className:"add-node-modal__discovery-state","data-state":"success",children:I.length>0?o("nodes.discoveredCount","Discovered {{count}} remote project{{plural}}",{count:I.length,plural:I.length===1?"":"s"}):o("nodes.noProjectsDiscovered","No projects discovered on remote node.")}),N==="error"&&T&&s.jsx("span",{className:"form-error add-node-modal__error",children:T}),N==="idle"&&s.jsx("span",{className:"add-node-modal__hint",children:o("nodes.discoverBeforeAdding","Discover remote projects before adding this node.")})]}),N==="success"&&I.length>0&&s.jsx("div",{className:"add-node-modal__discovered-list","aria-label":o("nodes.discoveredRemoteProjectsLabel","Discovered remote projects"),children:I.map(M=>s.jsxs("div",{className:"card add-node-modal__discovered-card",children:[s.jsxs("div",{className:"add-node-modal__discovered-row",children:[s.jsx("strong",{children:M.name}),s.jsx("span",{className:"card-status-badge card-status-badge--in-review",children:M.status})]}),s.jsx("div",{className:"add-node-modal__hint",children:M.path})]},`${M.id}-${M.path}`))})]}),s.jsxs("label",{className:"add-node-modal__field",children:[s.jsx("span",{children:o("nodes.maxConcurrent","Max Concurrent")}),s.jsx("input",{className:"input",type:"number",min:Yl,max:Zl,value:b,onChange:M=>y(Number(M.target.value)),disabled:A,"aria-invalid":!!w.maxConcurrent}),s.jsx("span",{className:"add-node-modal__hint",children:o("nodes.maxConcurrentHint","Max simultaneous task agents (1–10)")}),w.maxConcurrent&&s.jsx("span",{className:"form-error add-node-modal__error",children:w.maxConcurrent})]}),s.jsxs("section",{className:"add-node-modal__projects","aria-label":o("nodes.projectPathMappingsLabel","Project path mappings"),children:[s.jsx("h4",{className:"add-node-modal__projects-title",children:o("nodes.attachProjects","Attach Existing Projects")}),s.jsx("p",{className:"add-node-modal__hint",children:o("nodes.attachProjectsHint","Select existing projects to run on this node and provide the node-specific absolute path for each one.")}),i.length===0?s.jsx("p",{className:"add-node-modal__hint",children:o("nodes.noProjects","No projects are currently registered.")}):s.jsx("div",{className:"add-node-modal__project-list",children:i.map(M=>{const q=M.id in x,H=w.projectMappings[M.id];return s.jsxs("div",{className:"card add-node-modal__project-card",children:[s.jsxs("label",{className:"checkbox-label add-node-modal__project-toggle",children:[s.jsx("input",{type:"checkbox",checked:q,onChange:()=>te(M),disabled:A}),s.jsx("span",{children:M.name})]}),q&&s.jsxs("label",{className:"add-node-modal__field",children:[s.jsx("span",{children:o("nodes.pathOnNode","Path on this node")}),d==="remote"&&N==="success"&&s.jsx("span",{className:"add-node-modal__hint",children:(()=>{const re=I.filter(ae=>ae.name===M.name);return re.length===1?o("nodes.pathDiscovered","Remote-authoritative path discovered: {{path}}",{path:re[0].path}):re.length>1?o("nodes.multipleMatches","Multiple remote projects matched this name. Enter the correct path manually."):o("nodes.noMatch","No exact remote name match. Enter this path manually.")})()}),s.jsx("input",{className:"input",type:"text",value:x[M.id]??"",onChange:re=>G(M.id,re.target.value),disabled:A,placeholder:"/absolute/path/to/project","aria-invalid":!!H}),H&&s.jsx("span",{className:"form-error add-node-modal__error",children:H})]})]},M.id)})})]})]}),s.jsxs("div",{className:"modal-actions",children:[s.jsx("button",{className:"btn btn-sm",onClick:V,disabled:A,children:o("common.cancel","Cancel")}),s.jsx("button",{className:"btn btn-primary btn-sm","data-testid":"add-node-submit",onClick:K,disabled:A,children:A?o("nodes.adding","Adding..."):o("nodes.addNode","Add Node")})]})]})}):null}function kF(){const[e,t]=f.useState([]),[r,n]=f.useState(!1),[a,i]=f.useState(null),[o,l]=f.useState(!1),[c,d]=f.useState(null),[u,m]=f.useState(!1),h=f.useCallback(async()=>{n(!0),i(null);try{const b=await fetch("/api/docker/contexts");if(!b.ok)throw new Error(`Failed to load Docker contexts (${b.status})`);const y=await b.json();return t(y),y}catch(b){const y=b instanceof Error?b.message:String(b);throw i(y),b}finally{n(!1)}},[]),v=f.useCallback(async b=>{l(!0);try{const y=await fetch("/api/docker/test-connection",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hostConfig:b})});if(!y.ok)throw new Error(`Failed to test Docker connection (${y.status})`);const g=await y.json();return d(g),g}finally{l(!1)}},[]),p=f.useCallback(async()=>{m(!0);try{const b=await fetch("/api/docker/local-available");if(!b.ok)throw new Error(`Failed to check local Docker availability (${b.status})`);return await b.json()}finally{m(!1)}},[]);return{contexts:e,isLoadingContexts:r,contextsError:a,loadContexts:h,isTestingConnection:o,lastTestResult:c,testConnection:v,isCheckingLocal:u,checkLocalDocker:p}}function SF({value:e,onChange:t}){const{t:r}=se("app"),[n,a]=f.useState(!!(e?.tlsCaPath||e?.tlsCertPath||e?.tlsKeyPath||e?.tlsVerify));f.useEffect(()=>{n||t({tlsVerify:void 0,tlsCaPath:void 0,tlsCertPath:void 0,tlsKeyPath:void 0})},[n,t]);const i=f.useMemo(()=>({tlsVerify:e?.tlsVerify??!0,tlsCaPath:e?.tlsCaPath??"",tlsCertPath:e?.tlsCertPath??"",tlsKeyPath:e?.tlsKeyPath??""}),[e]);return s.jsxs("div",{className:"docker-tls-config",children:[s.jsxs("label",{className:"checkbox-label",children:[s.jsx("input",{type:"checkbox",checked:n,onChange:o=>a(o.target.checked)}),r("docker.useTls","Use TLS")]}),n&&s.jsxs("div",{className:"docker-tls-config__fields",children:[s.jsxs("div",{className:"docker-tls-config__field",children:[s.jsx("label",{htmlFor:"docker-tls-ca-path",children:r("docker.caPath","CA Certificate Path")}),s.jsx("input",{id:"docker-tls-ca-path",className:"input",value:i.tlsCaPath,onChange:o=>t({...i,tlsCaPath:o.target.value}),placeholder:"/etc/docker/ca.pem"})]}),s.jsxs("div",{className:"docker-tls-config__field",children:[s.jsx("label",{htmlFor:"docker-tls-cert-path",children:r("docker.certPath","Client Certificate Path")}),s.jsx("input",{id:"docker-tls-cert-path",className:"input",value:i.tlsCertPath,onChange:o=>t({...i,tlsCertPath:o.target.value}),placeholder:"/etc/docker/cert.pem"})]}),s.jsxs("div",{className:"docker-tls-config__field",children:[s.jsx("label",{htmlFor:"docker-tls-key-path",children:r("docker.keyPath","Client Key Path")}),s.jsx("input",{id:"docker-tls-key-path",className:"input",value:i.tlsKeyPath,onChange:o=>t({...i,tlsKeyPath:o.target.value}),placeholder:"/etc/docker/key.pem"})]}),s.jsxs("label",{className:"checkbox-label",children:[s.jsx("input",{type:"checkbox",checked:i.tlsVerify,onChange:o=>t({...i,tlsVerify:o.target.checked})}),r("docker.verifyTls","Verify TLS Certificate")]})]})]})}function NF({value:e,onChange:t,onError:r}){const{t:n}=se("app"),a=e?.context?"context":e?.host?"host":"local",[i,o]=f.useState(a),[l,c]=f.useState(e?.context??""),[d,u]=f.useState(e?.host??""),[m,h]=f.useState(null),{contexts:v,isLoadingContexts:p,contextsError:b,loadContexts:y,testConnection:g,isTestingConnection:j,lastTestResult:x,checkLocalDocker:C,isCheckingLocal:w}=kF(),P=f.useMemo(()=>({tlsVerify:e?.tlsVerify,tlsCaPath:e?.tlsCaPath,tlsCertPath:e?.tlsCertPath,tlsKeyPath:e?.tlsKeyPath}),[e]);f.useEffect(()=>{if(i==="local"){t({});return}if(i==="context"){y().catch(S=>r?.(S instanceof Error?S.message:String(S))),t(l?{context:l}:{});return}t({host:d,...P})},[i]);const A=f.useCallback(S=>{i==="host"&&t({host:d,...S})},[d,i,t]);return s.jsxs("div",{className:"docker-target-selector",children:[s.jsxs("div",{className:"docker-target-selector__modes",role:"group","aria-label":n("docker.targetMode","Docker target mode"),children:[s.jsx("button",{type:"button",className:`btn btn-sm ${i==="local"?"docker-target-selector__mode-active":""}`,onClick:()=>{o("local"),C().then(S=>{if(S.available){const N=S.version?` (${S.version})`:"";h(n("docker.available","Docker is available{{version}}",{version:N}))}else{const N=S.error?`: ${S.error}`:"";h(n("docker.notFound","Docker not found{{error}}",{error:N}))}}).catch(S=>{const N=S instanceof Error?S.message:String(S);h(n("docker.notFoundError","Docker not found: {{message}}",{message:N})),r?.(N)})},children:n("docker.local","Local Docker")}),s.jsx("button",{type:"button",className:`btn btn-sm ${i==="context"?"docker-target-selector__mode-active":""}`,onClick:()=>o("context"),children:n("docker.context","Docker Context")}),s.jsx("button",{type:"button",className:`btn btn-sm ${i==="host"?"docker-target-selector__mode-active":""}`,onClick:()=>o("host"),children:n("docker.remote","Remote Host")})]}),i==="local"&&m&&s.jsx("div",{className:"docker-target-selector__status",children:m}),i==="context"&&s.jsxs("div",{className:"docker-target-selector__panel",children:[s.jsxs("div",{className:"docker-target-selector__context-row",children:[s.jsxs("select",{className:"select",value:l,onChange:S=>{const N=S.target.value;c(N),t(N?{context:N}:{})},children:[s.jsx("option",{value:"",children:n("docker.selectContext","Select context")}),v.map(S=>s.jsxs("option",{value:S.name,children:[S.name,S.isCurrentContext?" (current)":"",S.dockerHost?` — ${S.dockerHost}`:""]},S.name))]}),s.jsx("button",{type:"button",className:"btn btn-sm btn-icon",onClick:()=>void y(),disabled:p,"aria-label":n("docker.refreshContexts","Refresh contexts"),children:s.jsx(Gt,{size:14})})]}),b&&s.jsx("div",{className:"docker-target-selector__error",children:b})]}),i==="host"&&s.jsxs("div",{className:"docker-target-selector__panel",children:[s.jsxs("div",{className:"docker-target-selector__field",children:[s.jsx("label",{htmlFor:"docker-target-selector-host",children:n("docker.host","Docker Host")}),s.jsx("input",{id:"docker-target-selector-host",className:"input",placeholder:n("docker.hostPlaceholder","tcp://host:2376"),value:d,onChange:S=>{const N=S.target.value;u(N),t({host:N,...P})}})]}),s.jsx(SF,{value:P,onChange:A})]}),s.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void g(i==="local"?void 0:i==="context"?{context:l}:{host:d,...P}),disabled:j||w,children:j?n("docker.testing","Testing..."):n("docker.testConnection","Test Connection")}),x&&s.jsx("div",{className:x.success?"docker-target-selector__success":"docker-target-selector__error",children:x.success?n("docker.connected","Connected{{version}}",{version:x.dockerVersion?` (Docker ${x.dockerVersion})`:""}):x.error??n("docker.connectionFailed","Connection failed")})]})}const Jo="http://localhost:4040",kh={readWrite:"rw",readOnly:"ro"};function PF({isOpen:e,onClose:t,onSubmit:r,addToast:n}){const{t:a}=se("app"),[i,o]=f.useState(""),[l,c]=f.useState({}),[d,u]=f.useState(Jo),[m,h]=f.useState("auto"),[v,p]=f.useState(""),[b,y]=f.useState(!1),[g,j]=f.useState(!1),[x,C]=f.useState(!0),[w,P]=f.useState(4096),[A,S]=f.useState(2),[N,E]=f.useState(!1),[T,O]=f.useState("runfusion/fusion"),[I,z]=f.useState("latest"),[D,V]=f.useState([]),[B,W]=f.useState([]),[K,te]=f.useState({}),[G,M]=f.useState(!1),q=f.useCallback(()=>{o(""),c({}),u(Jo),h("auto"),p(""),y(!1),j(!1),C(!0),P(4096),S(2),E(!1),O("runfusion/fusion"),z("latest"),V([]),W([]),te({}),M(!1)},[]),H=f.useCallback(()=>{G||(q(),t())},[t,q,G]);f.useEffect(()=>{if(!e){q();return}const L=Y=>{Y.key==="Escape"&&(Y.preventDefault(),H())};return document.addEventListener("keydown",L),()=>document.removeEventListener("keydown",L)},[H,e,q]);const re=f.useMemo(()=>({nodeId:null,name:i.trim(),imageName:T.trim()||"runfusion/fusion",imageTag:I.trim()||"latest",hostConfig:{context:l.context?.trim()||void 0,host:l.host?.trim()||void 0,tlsVerify:l.tlsVerify,tlsCaPath:l.tlsCaPath?.trim()||void 0,tlsCertPath:l.tlsCertPath?.trim()||void 0,tlsKeyPath:l.tlsKeyPath?.trim()||void 0},envVars:Object.fromEntries(D.map(L=>[L.key.trim(),L.value]).filter(([L])=>!!L)),volumeMounts:B.map(L=>({hostPath:L.hostPath.trim(),containerPath:L.containerPath.trim(),mode:L.mode})).filter(L=>L.hostPath&&L.containerPath),resourceSizing:{memoryMB:w,cpus:A},extraClis:[b?"claude-cli":null,g?"droid-cli":null].filter(Boolean),persistentStorage:x,reachableUrl:d.trim()||null,apiKey:m==="manual"&&v.trim()||null}),[v,m,A,l,D,T,I,b,g,w,B,i,x,d]),ae=f.useCallback(()=>{V(L=>[...L,{key:"",value:""}])},[]),ye=f.useCallback((L,Y)=>{V(ne=>ne.map((Ne,Q)=>Q===L?Y:Ne))},[]),oe=f.useCallback(L=>{V(Y=>Y.filter((ne,Ne)=>Ne!==L))},[]),He=f.useCallback(()=>{W(L=>[...L,{hostPath:"",containerPath:"",mode:"rw"}])},[]),J=f.useCallback((L,Y)=>{W(ne=>ne.map((Ne,Q)=>Q===L?Y:Ne))},[]),Ce=f.useCallback(L=>{W(Y=>Y.filter((ne,Ne)=>Ne!==L))},[]),Re=f.useCallback(async()=>{if(G)return;const L={};if((!re.name||re.name.length>64)&&(L.name=a("docker.errors.nameRequired","Name is required and must be 64 characters or fewer")),re.reachableUrl||(L.reachableUrl=a("docker.errors.urlRequired","URL is required")),w<512&&(L.memoryMB=a("docker.errors.memoryMinimum","Memory must be at least 512 MB")),A<.5&&(L.cpus=a("docker.errors.cpusMinimum","CPUs must be at least 0.5")),te(L),!(Object.keys(L).length>0)){M(!0);try{await r(re),H()}catch{}finally{M(!1)}}},[H,A,re,w,r,G,a]);return e?s.jsx(ic,{windowKey:"docker-node-onboarding",modal:!0,title:a("docker.titles.provisionNode","Provision Docker Node"),ariaLabel:a("docker.ariaLabels.modal","Docker node onboarding"),onClose:()=>{G||H()},hideHeader:!0,dragHandleSelector:".docker-onboarding .modal-header",className:"floating-window--docker-node-onboarding",defaultSize:{width:720,height:640},minSize:{width:420,height:320},persistGeometryKey:"floating-window:docker-node-onboarding",suspendGeometryPersistenceOnMobile:!0,suspendGeometryPersistenceOnShortViewport:!0,closeOnOutsidePointerDown:!0,children:s.jsxs("div",{className:"modal docker-onboarding",children:[s.jsxs("div",{className:"modal-header",children:[s.jsx("h3",{children:a("docker.titles.provisionNode","Provision Docker Node")}),s.jsx("button",{className:"modal-close",onClick:H,disabled:G,"aria-label":a("docker.ariaLabels.closeModal","Close onboarding modal"),children:"×"})]}),s.jsxs("div",{className:"modal-body docker-onboarding__body",children:[s.jsxs("section",{className:"docker-onboarding__section",children:[s.jsx("h4",{className:"docker-onboarding__section-title",children:a("docker.sections.requiredSettings","Required Settings")}),s.jsxs("label",{className:"docker-onboarding__field",children:[s.jsx("span",{children:a("docker.labels.nodeName","Node Name")}),s.jsx("input",{className:"input",value:i,onChange:L=>o(L.target.value),disabled:G,placeholder:a("docker.placeholders.nodeName","my-docker-node"),autoFocus:!0})]}),K.name&&s.jsx("div",{className:"form-error",children:K.name}),s.jsx(NF,{value:l,onChange:c}),s.jsxs("label",{className:"docker-onboarding__field",children:[s.jsx("span",{children:a("docker.labels.reachableUrl","Reachable URL")}),s.jsx("input",{className:"input",value:d,onChange:L=>u(L.target.value),disabled:G,placeholder:Jo})]}),K.reachableUrl&&s.jsx("div",{className:"form-error",children:K.reachableUrl}),s.jsxs("div",{className:"docker-onboarding__radio-group",children:[s.jsxs("label",{className:"checkbox-label",children:[s.jsx("input",{type:"radio",checked:m==="auto",onChange:()=>h("auto"),disabled:G}),a("docker.options.autoGenerate","Auto-generate")]}),s.jsxs("label",{className:"checkbox-label",children:[s.jsx("input",{type:"radio",checked:m==="manual",onChange:()=>h("manual"),disabled:G}),a("docker.options.provideManually","Provide manually")]})]}),m==="manual"&&s.jsxs("label",{className:"docker-onboarding__field",children:[s.jsx("span",{children:a("docker.labels.apiKey","API Key")}),s.jsx("input",{className:"input",type:"password",value:v,onChange:L=>p(L.target.value),disabled:G,placeholder:a("docker.placeholders.apiKey","Enter API key")})]}),s.jsxs("div",{className:"docker-onboarding__checkbox-group",children:[s.jsxs("label",{className:"checkbox-label",children:[s.jsx("input",{type:"checkbox",checked:b,onChange:L=>y(L.target.checked),disabled:G}),a("docker.options.claudeCli","Claude CLI")]}),s.jsxs("label",{className:"checkbox-label",children:[s.jsx("input",{type:"checkbox",checked:g,onChange:L=>j(L.target.checked),disabled:G}),a("docker.options.droidCli","Droid CLI")]}),s.jsxs("label",{className:"checkbox-label",children:[s.jsx("input",{type:"checkbox",checked:x,onChange:L=>C(L.target.checked),disabled:G}),a("docker.options.persistentStorage","Keep data across container recreations")]})]}),s.jsxs("div",{className:"docker-onboarding__inline-fields",children:[s.jsxs("label",{className:"docker-onboarding__field",children:[s.jsx("span",{children:a("docker.labels.memory","Memory (MB)")}),s.jsx("input",{className:"input",type:"number",min:512,value:w,onChange:L=>P(Number(L.target.value)),disabled:G})]}),s.jsxs("label",{className:"docker-onboarding__field",children:[s.jsx("span",{children:a("docker.labels.cpus","CPUs")}),s.jsx("input",{className:"input",type:"number",min:.5,step:.5,value:A,onChange:L=>S(Number(L.target.value)),disabled:G})]})]}),K.memoryMB&&s.jsx("div",{className:"form-error",children:K.memoryMB}),K.cpus&&s.jsx("div",{className:"form-error",children:K.cpus})]}),s.jsxs("section",{className:"docker-onboarding__section",children:[s.jsxs("button",{type:"button",className:`docker-onboarding__advanced-toggle ${N?"is-expanded":""}`,onClick:()=>E(L=>!L),disabled:G,children:[s.jsx("span",{children:a("docker.sections.advanced","Advanced")}),s.jsx(sc,{})]}),s.jsx("div",{className:`docker-onboarding__advanced-content ${N?"is-expanded":""}`,children:s.jsxs("div",{children:[s.jsxs("div",{className:"docker-onboarding__inline-fields",children:[s.jsxs("label",{className:"docker-onboarding__field",children:[s.jsx("span",{children:a("docker.labels.image","Image")}),s.jsx("input",{className:"input",value:T,onChange:L=>O(L.target.value),disabled:G,placeholder:a("docker.placeholders.image","runfusion/fusion")})]}),s.jsxs("label",{className:"docker-onboarding__field",children:[s.jsx("span",{children:a("docker.labels.tag","Tag")}),s.jsx("input",{className:"input",value:I,onChange:L=>z(L.target.value),disabled:G,placeholder:a("docker.placeholders.tag","latest")})]})]}),s.jsxs("div",{className:"docker-onboarding__kv-list",children:[s.jsx("h5",{children:a("docker.sections.environmentVariables","Environment Variables")}),D.map((L,Y)=>s.jsxs("div",{className:"docker-onboarding__kv-row docker-onboarding__kv-row--env",children:[s.jsx("input",{className:"input",placeholder:a("docker.placeholders.envVarKey","KEY"),value:L.key,disabled:G,onChange:ne=>ye(Y,{key:ne.target.value,value:L.value})}),s.jsx("input",{className:"input",placeholder:a("docker.placeholders.envVarValue","Value"),value:L.value,disabled:G,onChange:ne=>ye(Y,{key:L.key,value:ne.target.value})}),s.jsx("button",{type:"button",className:"btn btn-icon","aria-label":a("docker.ariaLabels.removeVariable","Remove environment variable"),onClick:()=>oe(Y),disabled:G,children:s.jsx(tn,{size:14})})]},`env-${Y}`)),s.jsxs("button",{type:"button",className:"btn btn-sm docker-onboarding__kv-add",onClick:ae,disabled:G,children:[s.jsx(zn,{size:14}),a("docker.actions.addVariable","Add variable")]})]}),s.jsxs("div",{className:"docker-onboarding__kv-list",children:[s.jsx("h5",{children:a("docker.sections.volumeMounts","Volume Mounts")}),B.map((L,Y)=>s.jsxs("div",{className:"docker-onboarding__kv-row docker-onboarding__kv-row--mount",children:[s.jsx("input",{className:"input",placeholder:a("docker.placeholders.hostPath","Host path"),value:L.hostPath,disabled:G,onChange:ne=>J(Y,{hostPath:ne.target.value,containerPath:L.containerPath,mode:L.mode})}),s.jsx("input",{className:"input",placeholder:a("docker.placeholders.containerPath","Container path"),value:L.containerPath,disabled:G,onChange:ne=>J(Y,{hostPath:L.hostPath,containerPath:ne.target.value,mode:L.mode})}),s.jsxs("select",{className:"select",value:L.mode,disabled:G,onChange:ne=>J(Y,{hostPath:L.hostPath,containerPath:L.containerPath,mode:ne.target.value==="ro"?"ro":"rw"}),children:[s.jsx("option",{value:"rw",children:kh.readWrite}),s.jsx("option",{value:"ro",children:kh.readOnly})]}),s.jsx("button",{type:"button",className:"btn btn-icon","aria-label":a("docker.ariaLabels.removeMount","Remove volume mount"),onClick:()=>Ce(Y),disabled:G,children:s.jsx(tn,{size:14})})]},`mount-${Y}`)),s.jsxs("button",{type:"button",className:"btn btn-sm docker-onboarding__kv-add",onClick:He,disabled:G,children:[s.jsx(zn,{size:14}),a("docker.actions.addMount","Add mount")]})]})]})})]})]}),s.jsxs("div",{className:"modal-actions",children:[s.jsx("button",{className:"btn",onClick:H,disabled:G,children:a("docker.actions.cancel","Cancel")}),s.jsx("button",{className:"btn btn-primary",onClick:()=>void Re(),disabled:G,children:G?a("docker.states.creating","Creating..."):a("docker.actions.createNode","Create Docker Node")})]})]})}):null}function AF({nodeId:e,entries:t,loading:r=!1,singleNode:n=!1}){const{t:a}=se("app"),[i,o]=f.useState(!1),[l,c]=f.useState("all"),[d,u]=f.useState("all"),m=f.useCallback(()=>{o(g=>!g)},[]),h=f.useMemo(()=>{const g=new Set;for(const j of t)g.add(j.nodeName);return Array.from(g).sort()},[t]),v=f.useMemo(()=>{let g=[...t];return l!=="all"&&(g=g.filter(j=>j.direction===l)),!n&&d!=="all"&&(g=g.filter(j=>j.nodeName===d)),g.sort((j,x)=>{const C=new Date(j.timestamp).getTime();return new Date(x.timestamp).getTime()-C}),g},[t,l,d,n]),p=f.useCallback(g=>new Date(g).toLocaleString(),[]),b=f.useCallback(g=>{switch(g){case"success":return"settings-sync-log__badge--success";case"conflict":return"settings-sync-log__badge--conflict";case"error":return"settings-sync-log__badge--error";default:return""}},[]),y=f.useCallback(g=>{switch(g){case"success":return a("syncLog.resultSuccess","Success");case"conflict":return a("syncLog.resultConflict","Conflict");case"error":return a("syncLog.resultError","Error");default:return g}},[a]);return s.jsxs("div",{className:"settings-sync-log",children:[s.jsxs("button",{className:"settings-sync-log__header",type:"button",onClick:m,"aria-expanded":i,"data-testid":"settings-sync-log-header",children:[s.jsx(sc,{size:16,className:`settings-sync-log__chevron ${i?"settings-sync-log__chevron--expanded":""}`}),s.jsx("span",{children:a("syncLog.entryCount",{count:t.length,defaultValue_one:"{{count}} entry",defaultValue_other:"{{count}} entries"})})]}),i&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"settings-sync-log__filters",children:[s.jsxs("label",{children:[a("syncLog.filterDirection","Direction:"),s.jsxs("select",{value:l,onChange:g=>c(g.target.value),children:[s.jsx("option",{value:"all",children:a("syncLog.filterAll","All")}),s.jsx("option",{value:"push",children:a("syncLog.filterPush","Push")}),s.jsx("option",{value:"pull",children:a("syncLog.filterPull","Pull")})]})]}),!n&&s.jsxs("label",{children:[a("syncLog.filterNode","Node:"),s.jsxs("select",{value:d,onChange:g=>u(g.target.value),children:[s.jsx("option",{value:"all",children:a("syncLog.filterAllNodes","All Nodes")}),h.map(g=>s.jsx("option",{value:g,children:g},g))]})]})]}),r&&t.length===0?s.jsx("div",{className:"settings-sync-log__empty",children:s.jsx(rc,{label:a("syncLog.loading","Loading...")})}):v.length===0?s.jsx("div",{className:"settings-sync-log__empty",children:a("syncLog.noHistory","No sync history available")}):s.jsx("div",{className:"settings-sync-log__list",children:v.map(g=>s.jsxs("div",{className:"settings-sync-log__entry",children:[s.jsx("span",{className:"settings-sync-log__entry-timestamp",children:p(g.timestamp)}),s.jsx("span",{className:"settings-sync-log__entry-direction",children:g.direction==="push"?s.jsx(uc,{size:14,"data-testid":"upload-icon"}):s.jsx(Ri,{size:14,"data-testid":"download-icon"})}),s.jsx("span",{className:`settings-sync-log__entry-result ${b(g.result)}`,children:y(g.result)}),!n&&s.jsx("span",{className:"settings-sync-log__entry-node",children:g.nodeName}),g.details&&s.jsx("span",{className:"settings-sync-log__entry-details",title:g.details,children:Xj(g.details??"")})]},g.id))})]})]})}function OF(e,t){const r=typeof e=="string"?e:JSON.stringify(e,null,2),n=typeof t=="string"?t:JSON.stringify(t,null,2);if(r===n)return r;const a=r.split(`
100
100
  `),i=n.split(`
101
101
  `),o=[],l=Math.max(a.length,i.length);for(let c=0;c<l;c++){const d=a[c],u=i[c];d!==void 0&&d!==u&&o.push(`- ${d}`),u!==void 0&&u!==d&&o.push(`+ ${u}`),d!==void 0&&d===u&&o.push(` ${d}`)}return o.join(`
102
- `)}function EF({isOpen:e,onClose:t,onResolve:r,conflicts:n,localNodeName:a,remoteNodeName:i,addToast:o}){const{t:l}=se("app"),[c,d]=f.useState({}),[u,m]=f.useState(!1);f.useEffect(()=>{const g={};for(const j of n)c[j.key]||(g[j.key]={resolution:"local"});Object.keys(g).length>0&&d(j=>({...j,...g}))},[n,c]),f.useEffect(()=>{if(!e)return;const g=j=>{j.key==="Escape"&&(j.preventDefault(),t())};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[e,t]);const h=f.useCallback((g,j)=>{d(x=>{const C=x[g]??{};return j==="manual"?{...x,[g]:{resolution:"manual",manualValue:C.manualValue??JSON.stringify(n.find(w=>w.key===g)?.localValue??null,null,2)}}:{...x,[g]:{resolution:j}}})},[n]),v=f.useCallback((g,j)=>{d(x=>({...x,[g]:{...x[g],resolution:"manual",manualValue:j}}))},[]),p=f.useCallback(g=>{const j={};for(const x of n)j[x.key]={resolution:g};d(j)},[n]),b=f.useCallback(async()=>{m(!0);try{const g=n.map(j=>{const x=c[j.key]??{resolution:"local"};let C;switch(x.resolution){case"remote":C=j.remoteValue;break;case"manual":try{C=JSON.parse(x.manualValue??"null")}catch{C=x.manualValue??null}break;case"local":default:C=j.localValue;break}return{key:j.key,value:C}});await r(g),o(l("settings.resolvedSuccess","Settings conflicts resolved successfully"),"success"),t()}catch(g){const j=g instanceof Error?g.message:l("settings.resolveFailed","Failed to resolve conflicts");o(j,"error")}finally{m(!1)}},[o,n,t,r,c]),y=f.useMemo(()=>{const g={};for(const j of n)g[j.key]=OF(j.localValue,j.remoteValue);return g},[n]);return!e||n.length===0?null:s.jsx("div",{className:"modal-overlay open",onClick:t,children:s.jsxs("div",{className:"modal modal-lg settings-sync-conflict-modal",onClick:g=>g.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":l("settings.conflictModalTitle","Resolve Settings Conflicts"),children:[s.jsxs("div",{className:"modal-header",children:[s.jsx("h3",{children:l("settings.conflictModalTitle","Resolve Settings Conflicts")}),s.jsx("button",{className:"modal-close",onClick:t,"aria-label":l("settings.closeModal","Close conflict modal"),children:"×"})]}),s.jsxs("div",{className:"modal-body",children:[s.jsx("div",{className:"settings-sync-conflict-modal__conflict-list",children:n.map(g=>{const j=c[g.key]??{resolution:"local"},x=y[g.key];return s.jsxs("div",{className:"settings-sync-conflict-modal__conflict-item",children:[s.jsx("div",{className:"settings-sync-conflict-modal__key",children:g.key}),s.jsxs("div",{className:"settings-sync-conflict-modal__diff-panel",children:[s.jsxs("div",{className:"settings-sync-conflict-modal__diff-side",children:[s.jsx("div",{className:"settings-sync-conflict-modal__diff-label",children:a}),s.jsx("div",{className:"settings-sync-conflict-modal__diff-content",children:s.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap"},children:x})})]}),s.jsxs("div",{className:"settings-sync-conflict-modal__diff-side",children:[s.jsx("div",{className:"settings-sync-conflict-modal__diff-label",children:i}),s.jsx("div",{className:"settings-sync-conflict-modal__diff-content",children:s.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap"},children:x})})]})]}),s.jsxs("div",{className:"settings-sync-conflict-modal__resolution",children:[s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:`resolution-${g.key}`,checked:j.resolution==="local",onChange:()=>h(g.key,"local")}),l("settings.keepLocal","Keep Local")]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:`resolution-${g.key}`,checked:j.resolution==="remote",onChange:()=>h(g.key,"remote")}),l("settings.keepRemote","Keep Remote")]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:`resolution-${g.key}`,checked:j.resolution==="manual",onChange:()=>h(g.key,"manual")}),l("settings.mergeManually","Merge Manually")]})]}),j.resolution==="manual"&&s.jsx("textarea",{className:"settings-sync-conflict-modal__manual-input",value:j.manualValue??"",onChange:C=>v(g.key,C.target.value),placeholder:l("settings.jsonPlaceholder","Enter JSON value...")})]},g.key)})}),s.jsxs("div",{className:"settings-sync-conflict-modal__bulk-actions",children:[s.jsx("button",{className:"btn btn-sm",onClick:()=>p("local"),type:"button",children:l("settings.resolveAllLocal","Resolve All: Keep Local")}),s.jsx("button",{className:"btn btn-sm",onClick:()=>p("remote"),type:"button",children:l("settings.resolveAllRemote","Resolve All: Keep Remote")})]})]}),s.jsxs("div",{className:"modal-actions settings-sync-conflict-modal__footer",children:[s.jsx("button",{className:"btn btn-sm",onClick:t,children:l("actions.cancel","Cancel")}),s.jsx("button",{className:"btn btn-primary btn-sm",onClick:b,disabled:u,children:u?l("settings.resolving","Resolving..."):l("actions.confirm","Confirm")})]})]})})}const Ra={readWrite:"rw",readOnly:"ro",volume:"volume",bind:"bind"},Yx=/(KEY|TOKEN|SECRET|PASSWORD)/i;function Qo(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?"—":t.toLocaleString()}function _F(e){if(!e)return"—";const t=new Date(e),r=Date.now();if(Number.isNaN(t.getTime())||t.getTime()>r)return"—";const n=Math.floor((r-t.getTime())/1e3);if(n<60)return`${n}s`;const a=Math.floor(n/60);if(a<60)return`${a}m`;const i=Math.floor(a/60);return i<24?`${i}h ${a%60}m`:`${Math.floor(i/24)}d ${i%24}h`}function TF(e){switch(e){case"synced":return"node-detail-modal__sync-dot--synced";case"diff":return"node-detail-modal__sync-dot--diff";case"error":return"node-detail-modal__sync-dot--error";case"pending":return"node-detail-modal__sync-dot--pending";case"never-synced":default:return"node-detail-modal__sync-dot--never"}}function MF(e){return e==="running"?"success":e==="creating"||e==="recreating"||e==="restarting"?"warning":"error"}function IF(e){return e?`${e.charAt(0).toUpperCase()}${e.slice(1)}`:"Unknown"}function DF(e){if(!e)return"—";try{const t=new URL(e);return t.port?t.port:t.protocol==="https:"?"443":t.protocol==="http:"?"80":"—"}catch{return"—"}}function RF(e,t){return Yx.test(e)?"••••••••":t}function LF({isOpen:e,onClose:t,node:r,projects:n,onUpdate:a,onHealthCheck:i,addToast:o,syncStatus:l,onPushSettings:c,onPullSettings:d,onSyncAuth:u,syncHistory:m=[],onResolveConflicts:h,managedDockerNode:v,containerStatus:p,onFetchContainerStatus:b,onFetchLogs:y,onUpdateDockerConfig:g,onFetchDockerConfigDiff:j}){const{t:x}=se("app"),C=f.useRef(!0),[w,P]=f.useState(!1),[A,S]=f.useState(""),[N,E]=f.useState(""),[T,O]=f.useState(""),[I,z]=f.useState(2),[D,V]=f.useState(!1),[B,W]=f.useState(!1),[K,te]=f.useState(!1),[G,M]=f.useState(!1),[q,H]=f.useState(null),[re,ae]=f.useState(!1),[ye]=f.useState([]),[oe,He]=f.useState(p),[J,Ce]=f.useState(!1),[Re,L]=f.useState(!1),[Y,ne]=f.useState(""),[Ne,Q]=f.useState(!1),[le,Oe]=f.useState(!1),[k,$]=f.useState(r?.dockerConfig??null),[de,Le]=f.useState({}),[Nt,pa]=f.useState(!1),[ks,R]=f.useState(!1);f.useEffect(()=>(C.current=!0,()=>{C.current=!1}),[]),f.useEffect(()=>{He(p)},[p]),f.useEffect(()=>{if(!r||!e){P(!1),L(!1),ne("");return}S(r.name),E(r.url??""),O(r.apiKey??""),z(r.maxConcurrent),P(!1),$(r.dockerConfig??null),Oe(!1),Le({})},[e,r]),f.useEffect(()=>{if(!e)return;const F=ie=>{ie.key==="Escape"&&(ie.preventDefault(),t())};return document.addEventListener("keydown",F),()=>document.removeEventListener("keydown",F)},[e,t]);const ce=f.useMemo(()=>r?Yj(n,r):[],[r,n]),Pe=f.useMemo(()=>v?v.hostConfig.type==="remote"?v.hostConfig.host??"—":x("nodes.localDocker","Local Docker"):"—",[v,x]),Ge=f.useMemo(()=>!v?.resourceSizing?.cpuLimit&&!v?.resourceSizing?.memoryLimit?x("nodes.dockerResourceDefault","Default"):`${v.resourceSizing?.cpuLimit??x("nodes.dockerDefaultCpu","Default CPU")} / ${v.resourceSizing?.memoryLimit??x("nodes.dockerDefaultMemory","Default memory")}`,[v,x]),Kr=f.useCallback(async()=>{if(r)try{if(await i(r.id),!C.current)return;o(x("nodes.healthCheckSuccess","Health check completed for {{name}}",{name:r.name}),"success")}catch(F){if(!C.current)return;const ie=F instanceof Error?F.message:x("nodes.healthCheckFailed","Health check failed");o(ie,"error")}},[o,r,i]),ya=f.useCallback(async()=>{if(!(!r||!c)){H(null),W(!0);try{if(await c(r.id),!C.current)return;o(x("nodes.pushSettingsSuccess","Settings pushed successfully"),"success")}catch(F){if(!C.current)return;const ie=F instanceof Error?F.message:x("nodes.pushSettingsFailed","Push settings failed");H(ie),o(ie,"error")}finally{C.current&&W(!1)}}},[o,r,c]),Cn=f.useCallback(async()=>{if(!(!r||!d)){H(null),te(!0);try{if(await d(r.id),!C.current)return;o(x("nodes.pullSettingsSuccess","Settings pulled successfully"),"success")}catch(F){if(!C.current)return;const ie=F instanceof Error?F.message:x("nodes.pullSettingsFailed","Pull settings failed");H(ie),o(ie,"error")}finally{C.current&&te(!1)}}},[o,r,d]),Ss=f.useCallback(async()=>{if(!(!r||!u)){H(null),M(!0);try{if(await u(r.id),!C.current)return;o(x("nodes.syncAuthSuccess","Auth credentials synced successfully"),"success")}catch(F){if(!C.current)return;const ie=F instanceof Error?F.message:x("nodes.syncAuthFailed","Auth sync failed");H(ie),o(ie,"error")}finally{C.current&&M(!1)}}},[o,r,u]),Zx=f.useCallback(()=>{H(null)},[]),Jx=f.useCallback(async()=>{if(!(!v||!b)){Ce(!0);try{const F=await b(v.id);if(!C.current)return;He(F)}catch(F){const ie=F instanceof Error?F.message:x("nodes.fetchContainerStatusFailed","Failed to fetch container status");o(ie,"error")}finally{C.current&&Ce(!1)}}},[o,v,b]),Qx=f.useCallback(async()=>{if(!(!v||!y)){L(!0),Q(!0);try{const F=await y(v.id);if(!C.current)return;ne(F)}catch(F){if(!C.current)return;ne("");const ie=F instanceof Error?F.message:x("nodes.fetchContainerLogsFailed","Failed to fetch container logs");o(ie,"error")}finally{C.current&&Q(!1)}}},[o,v,y]),ej=f.useCallback(async()=>{if(!r||D)return;const F=A.trim();if(!F){o(x("nodes.nameRequired","Name is required"),"error");return}if(r.type==="remote"&&!N.trim()){o(x("nodes.urlRequired","URL is required for remote nodes"),"error");return}if(!Number.isFinite(I)||I<1){o(x("nodes.concurrencyMin","Concurrency must be at least 1"),"error");return}V(!0);try{await a(r.id,{name:F,url:r.type==="remote"&&N.trim()||void 0,apiKey:r.type==="remote"&&T||void 0,maxConcurrent:I}),o(x("nodes.updateSuccess","Updated {{name}}",{name:F}),"success"),P(!1)}catch(ie){const it=ie instanceof Error?ie.message:x("nodes.updateFailed","Failed to update node");o(it,"error")}finally{V(!1)}},[o,T,D,I,A,r,a,N]);f.useEffect(()=>{!r?.dockerConfig||!j||!e||j(r.id).then(F=>{C.current&&R(F.needsRecreate)}).catch(()=>{C.current&&R(!1)})},[e,r,j]);const tj=f.useCallback(async()=>{if(!(!r||!k||!g||Nt)){pa(!0);try{const F=await g(r.id,{image:k.image,volumeMounts:k.volumeMounts,environment:k.environment,resources:k.resources,host:k.host,extraClis:k.extraClis,persistence:k.persistence,containerName:k.containerName});if(!C.current)return;$(F),o(x("nodes.dockerConfigSaveSuccess","Docker config saved"),"success")}catch(F){if(!C.current)return;const ie=F instanceof Error?F.message:x("nodes.dockerConfigSaveFailed","Failed to save Docker config");o(ie,"error")}finally{C.current&&pa(!1)}}},[o,k,Nt,r,g]),rj=f.useCallback(()=>{r&&(S(r.name),E(r.url??""),O(r.apiKey??""),z(r.maxConcurrent),P(!1))},[r]);if(!e||!r)return null;const sr=oe?.status??v?.status,nj=MF(sr);return s.jsxs(ic,{windowKey:"node-detail",title:x("nodes.modalTitle","Node Details"),ariaLabel:x("nodes.modalAriaLabel","Node details for {{name}}",{name:r.name}),onClose:t,hideHeader:!0,dragHandleSelector:".modal-header",className:"floating-window--node-detail",defaultSize:{width:720,height:560},minSize:{width:360,height:280},persistGeometryKey:"floating-window:node-detail",suspendGeometryPersistenceOnMobile:!0,suspendGeometryPersistenceOnShortViewport:!0,closeOnOutsidePointerDown:!0,children:[s.jsxs("div",{className:"modal modal-lg node-detail-modal",children:[s.jsxs("div",{className:"modal-header",children:[s.jsx("h3",{children:x("nodes.modalTitle","Node Details")}),s.jsx("button",{className:"modal-close",onClick:t,"aria-label":x("nodes.closeModalAriaLabel","Close node detail modal"),children:"×"})]}),s.jsxs("div",{className:"modal-body node-detail-modal__body",children:[s.jsxs("section",{className:"node-detail-modal__section",children:[s.jsxs("div",{className:"node-detail-modal__section-header",children:[s.jsx("h4",{children:x("nodes.sectionOverview","Overview")}),!w&&s.jsxs("button",{className:"btn btn-sm",onClick:()=>P(!0),children:[s.jsx(Zj,{size:14}),x("nodes.editButton","Edit")]})]}),s.jsxs("div",{className:"node-detail-modal__grid",children:[s.jsxs("label",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.fieldName","Name")}),w?s.jsx("input",{className:"input",value:A,onChange:F=>S(F.target.value),disabled:D}):s.jsx("strong",{children:r.name})]}),s.jsxs("div",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.fieldType","Type")}),s.jsx("strong",{children:r.type==="local"?x("nodes.typeLocal","Local"):x("nodes.typeRemote","Remote")})]}),s.jsxs("div",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.fieldStatus","Status")}),s.jsx("strong",{children:r.status})]}),s.jsxs("label",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.fieldMaxConcurrent","Max Concurrent")}),w?s.jsx("input",{className:"input",type:"number",min:1,max:10,value:I,onChange:F=>z(Number(F.target.value)),disabled:D}):s.jsx("strong",{children:r.maxConcurrent})]}),r.type==="remote"&&s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"node-detail-modal__field node-detail-modal__field--full",children:[s.jsx("span",{children:x("nodes.fieldUrl","URL")}),w?s.jsx("input",{className:"input",value:N,onChange:F=>E(F.target.value),disabled:D}):s.jsx("strong",{children:r.url??"—"})]}),s.jsxs("label",{className:"node-detail-modal__field node-detail-modal__field--full",children:[s.jsx("span",{children:x("nodes.fieldApiKey","API Key")}),w?s.jsx("input",{className:"input",type:"password",value:T,onChange:F=>O(F.target.value),placeholder:x("nodes.apiKeyPlaceholder","Leave blank to keep unchanged"),disabled:D}):s.jsx("strong",{children:r.apiKey?"••••••••":x("nodes.apiKeyNotConfigured","Not configured")})]})]}),s.jsxs("div",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.fieldCreated","Created")}),s.jsx("strong",{children:Qo(r.createdAt)})]}),s.jsxs("div",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.fieldUpdated","Updated")}),s.jsx("strong",{children:Qo(r.updatedAt)})]})]}),w&&s.jsxs("div",{className:"node-detail-modal__edit-actions",children:[s.jsxs("button",{className:"btn btn-primary btn-sm",onClick:ej,disabled:D,children:[s.jsx(Uu,{size:14}),D?x("nodes.saving","Saving..."):x("nodes.saveButton","Save")]}),s.jsxs("button",{className:"btn btn-sm",onClick:rj,disabled:D,children:[s.jsx($a,{size:14}),x("nodes.cancelButton","Cancel")]})]})]}),s.jsxs("section",{className:"node-detail-modal__section",children:[s.jsxs("h4",{children:[r.type==="local"?x("nodes.sectionProjects","Projects"):x("nodes.sectionAssignedProjects","Assigned Projects")," (",ce.length,")"]}),ce.length===0?s.jsx("p",{className:"node-detail-modal__empty",children:r.type==="local"?x("nodes.noProjectsRunning","No projects are running on this node."):x("nodes.noProjectsAssigned","No projects are assigned to this node.")}):s.jsx("ul",{className:"node-detail-modal__project-list",children:ce.map(F=>s.jsxs("li",{className:"node-detail-modal__project-item",children:[s.jsx("span",{children:F.name}),s.jsx("code",{children:F.id})]},F.id))})]}),s.jsxs("section",{className:"node-detail-modal__section",children:[s.jsx("h4",{children:x("nodes.sectionHealth","Health")}),s.jsxs("div",{className:"node-detail-modal__health-row",children:[s.jsxs("span",{children:[x("nodes.healthStatus","Status:")," ",s.jsx("strong",{children:r.status})]}),s.jsxs("span",{children:[x("nodes.healthLastCheck","Last check:")," ",s.jsx("strong",{children:Qo(r.updatedAt)})]})]})]}),k&&s.jsxs("section",{className:"node-detail-modal__section node-detail-modal__docker-config",children:[s.jsxs("button",{className:"btn btn-sm node-detail-modal__docker-toggle",onClick:()=>Oe(F=>!F),"aria-expanded":le,children:[s.jsx(sc,{size:14,className:le?"node-detail-modal__docker-toggle-icon--expanded":""}),x("nodes.dockerConfiguration","Docker Configuration")]}),le&&s.jsxs("div",{className:"node-detail-modal__docker-config-content",children:[s.jsx("div",{className:"node-detail-modal__grid",children:s.jsxs("label",{className:"node-detail-modal__field node-detail-modal__field--full",children:[s.jsx("span",{children:x("nodes.dockerFieldImage","Image")}),s.jsx("input",{className:"input",value:k.image,onChange:F=>$({...k,image:F.target.value})})]})}),s.jsxs("details",{children:[s.jsx("summary",{children:x("nodes.dockerVolumeMounts","Volume Mounts")}),s.jsxs("div",{className:"node-detail-modal__docker-list",children:[k.volumeMounts.map((F,ie)=>s.jsxs("div",{className:"node-detail-modal__docker-row",children:[s.jsx("input",{className:"input",value:F.hostPath,placeholder:x("nodes.dockerHostPath","Host path"),onChange:it=>{const fe=[...k.volumeMounts];fe[ie]={...fe[ie],hostPath:it.target.value},$({...k,volumeMounts:fe})}}),s.jsx("input",{className:"input",value:F.containerPath,placeholder:x("nodes.dockerContainerPath","Container path"),onChange:it=>{const fe=[...k.volumeMounts];fe[ie]={...fe[ie],containerPath:it.target.value},$({...k,volumeMounts:fe})}}),s.jsxs("select",{className:"input",value:F.mode??"rw",onChange:it=>{const fe=[...k.volumeMounts];fe[ie]={...fe[ie],mode:it.target.value},$({...k,volumeMounts:fe})},children:[s.jsx("option",{value:"rw",children:Ra.readWrite}),s.jsx("option",{value:"ro",children:Ra.readOnly})]}),s.jsxs("select",{className:"input",value:F.type??"volume",onChange:it=>{const fe=[...k.volumeMounts];fe[ie]={...fe[ie],type:it.target.value},$({...k,volumeMounts:fe})},children:[s.jsx("option",{value:"volume",children:Ra.volume}),s.jsx("option",{value:"bind",children:Ra.bind})]}),s.jsx("button",{className:"btn btn-sm",onClick:()=>$({...k,volumeMounts:k.volumeMounts.filter((it,fe)=>fe!==ie)}),children:x("nodes.removeButton","Remove")})]},`${F.hostPath}-${F.containerPath}-${ie}`)),s.jsx("button",{className:"btn btn-sm",onClick:()=>$({...k,volumeMounts:[...k.volumeMounts,{hostPath:"",containerPath:"",mode:"rw",type:"volume"}]}),children:x("nodes.addMountButton","Add Mount")})]})]}),s.jsxs("details",{children:[s.jsx("summary",{children:x("nodes.dockerEnvVars","Environment Variables")}),s.jsxs("div",{className:"node-detail-modal__docker-list",children:[Object.entries(k.environment).map(([F,ie])=>{const it=Yx.test(F)&&!de[F];return s.jsxs("div",{className:"node-detail-modal__docker-row",children:[s.jsx("input",{className:"input",value:F,onChange:fe=>{const Ns={...k.environment};delete Ns[F],Ns[fe.target.value]=ie,$({...k,environment:Ns})}}),s.jsx("input",{className:"input",value:it?"***":String(ie),onChange:fe=>$({...k,environment:{...k.environment,[F]:fe.target.value}})}),s.jsx("button",{className:"btn btn-sm",onClick:()=>Le(fe=>({...fe,[F]:!fe[F]})),children:de[F]?s.jsx(Jj,{size:14}):s.jsx(Qj,{size:14})}),s.jsx("button",{className:"btn btn-sm",onClick:()=>{const fe={...k.environment};delete fe[F],$({...k,environment:fe})},children:x("nodes.removeButton","Remove")})]},F)}),s.jsx("button",{className:"btn btn-sm",onClick:()=>{const F=`NEW_VAR_${Object.keys(k.environment).length+1}`;$({...k,environment:{...k.environment,[F]:""}})},children:x("nodes.addVariableButton","Add Variable")})]})]}),s.jsxs("details",{children:[s.jsx("summary",{children:x("nodes.dockerResources","Resources")}),s.jsxs("div",{className:"node-detail-modal__docker-stack",children:[s.jsx("input",{className:"input",type:"number",placeholder:x("nodes.dockerMemoryBytes","Memory bytes (2 GB = 2147483648)"),value:k.resources?.memoryBytes??"",onChange:F=>$({...k,resources:{...k.resources,memoryBytes:F.target.value?Number(F.target.value):void 0}})}),s.jsx("input",{className:"input",type:"number",placeholder:x("nodes.dockerCpuCount","CPU count"),value:k.resources?.cpuCount??"",onChange:F=>$({...k,resources:{...k.resources,cpuCount:F.target.value?Number(F.target.value):void 0}})}),s.jsx("input",{className:"input",type:"number",placeholder:x("nodes.dockerPidsLimit","PIDs limit"),value:k.resources?.pidsLimit??"",onChange:F=>$({...k,resources:{...k.resources,pidsLimit:F.target.value?Number(F.target.value):void 0}})})]})]}),s.jsxs("details",{children:[s.jsx("summary",{children:x("nodes.dockerHostConfig","Host Config")}),s.jsxs("div",{className:"node-detail-modal__docker-stack",children:[s.jsx("input",{className:"input",placeholder:x("nodes.dockerContextName","Context name"),value:k.host?.contextName??"",onChange:F=>$({...k,host:{...k.host,contextName:F.target.value}})}),s.jsx("input",{className:"input",placeholder:x("nodes.dockerHostUrl","Docker host URL"),value:k.host?.dockerHost??"",onChange:F=>$({...k,host:{...k.host,dockerHost:F.target.value}})}),s.jsx("input",{className:"input",placeholder:x("nodes.dockerTlsCaCert","TLS CA cert path"),value:k.host?.tlsCaCert??"",onChange:F=>$({...k,host:{...k.host,tlsCaCert:F.target.value}})}),s.jsx("input",{className:"input",placeholder:x("nodes.dockerTlsCert","TLS cert path"),value:k.host?.tlsCert??"",onChange:F=>$({...k,host:{...k.host,tlsCert:F.target.value}})}),s.jsx("input",{className:"input",placeholder:x("nodes.dockerTlsKey","TLS key path"),value:k.host?.tlsKey??"",onChange:F=>$({...k,host:{...k.host,tlsKey:F.target.value}})}),s.jsxs("label",{className:"node-detail-modal__checkbox",children:[s.jsx("input",{type:"checkbox",checked:k.host?.tlsVerify??!0,onChange:F=>$({...k,host:{...k.host,tlsVerify:F.target.checked}})}),x("nodes.dockerTlsVerify","TLS verify")]})]})]}),s.jsxs("details",{children:[s.jsx("summary",{children:x("nodes.dockerExtraClis","Extra CLIs")}),s.jsxs("div",{className:"node-detail-modal__docker-list",children:[(k.extraClis??[]).map((F,ie)=>s.jsxs("div",{className:"node-detail-modal__docker-row",children:[s.jsx("input",{className:"input",value:F,onChange:it=>{const fe=[...k.extraClis??[]];fe[ie]=it.target.value,$({...k,extraClis:fe})}}),s.jsx("button",{className:"btn btn-sm",onClick:()=>$({...k,extraClis:(k.extraClis??[]).filter((it,fe)=>fe!==ie)}),children:x("nodes.removeButton","Remove")})]},`${F}-${ie}`)),s.jsx("button",{className:"btn btn-sm",onClick:()=>$({...k,extraClis:[...k.extraClis??[],""]}),children:x("nodes.addCliButton","Add CLI")})]})]}),s.jsxs("details",{children:[s.jsx("summary",{children:x("nodes.dockerPersistence","Persistence")}),s.jsxs("div",{className:"node-detail-modal__docker-stack",children:[s.jsx("input",{className:"input",placeholder:x("nodes.dockerVolumeName","Volume name"),value:k.persistence?.volumeName??"",onChange:F=>$({...k,persistence:{...k.persistence,volumeName:F.target.value}})}),s.jsxs("label",{className:"node-detail-modal__checkbox",children:[s.jsx("input",{type:"checkbox",checked:k.persistence?.retainOnDelete??!1,onChange:F=>$({...k,persistence:{...k.persistence,retainOnDelete:F.target.checked}})}),x("nodes.dockerRetainOnDelete","Retain on delete")]})]})]}),s.jsxs("div",{className:"node-detail-modal__docker-meta",children:[s.jsx("span",{children:x("nodes.dockerConfigMeta","Config v{{version}} • Updated {{updated}}",{version:k.configVersion,updated:Xl(k.lastUpdated??r.updatedAt)})}),ks&&s.jsx("span",{className:"node-detail-modal__docker-recreate",children:x("nodes.dockerNeedsRecreate","Needs Recreate")})]}),s.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void tj(),disabled:Nt,children:[s.jsx(Uu,{size:14}),Nt?x("nodes.saving","Saving..."):x("nodes.saveDockerConfig","Save Docker Config")]})]})]}),v&&s.jsxs("section",{className:"node-detail-modal__section docker-management",children:[s.jsx("h4",{children:x("nodes.sectionDockerManagement","Docker Management")}),s.jsxs("div",{className:"docker-management__status-card",children:[s.jsxs("div",{className:"docker-management__status-row",children:[s.jsx("span",{className:`docker-management__status-dot docker-management__status-dot--${nj}`,"aria-hidden":!0}),s.jsx("strong",{children:sr?IF(sr):x("nodes.dockerStatusUnknown","Unknown")}),(sr==="creating"||sr==="recreating"||sr==="restarting")&&s.jsx(qu,{size:14,className:"spin","aria-hidden":!0})]}),s.jsxs("div",{className:"docker-management__status-meta",children:[sr==="running"&&s.jsxs("span",{children:[x("nodes.dockerUptime","Uptime:")," ",_F(oe?.startedAt)]}),sr!=="running"&&oe?.exitCode!==void 0&&s.jsxs("span",{children:[x("nodes.dockerExitCode","Exit code:")," ",oe.exitCode]}),(oe?.error||v.errorMessage)&&s.jsx("span",{children:oe?.error??v.errorMessage})]}),s.jsx("button",{className:"btn btn-sm",onClick:()=>void Jx(),disabled:!b||J,children:J?x("nodes.refreshing","Refreshing..."):x("nodes.refreshStatus","Refresh Status")})]}),s.jsxs("div",{className:"node-detail-modal__grid docker-management__info-grid",children:[s.jsxs("div",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.dockerFieldImage","Image")}),s.jsx("strong",{children:s.jsxs("code",{children:[v.imageName,":",v.imageTag]})})]}),s.jsxs("div",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.dockerContainerId","Container ID")}),s.jsx("strong",{children:s.jsx("code",{children:v.containerId?v.containerId.slice(0,12):"—"})})]}),s.jsxs("div",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.dockerHostLabel","Host")}),s.jsx("strong",{children:Pe})]}),s.jsxs("div",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.dockerPersistentStorage","Persistent Storage")}),s.jsx("strong",{children:v.persistentStorage?x("nodes.yes","Yes"):x("nodes.no","No")})]}),s.jsxs("div",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.dockerPort","Port")}),s.jsx("strong",{children:DF(v.reachableUrl)})]}),s.jsxs("div",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.dockerResourceSizing","Resource Sizing")}),s.jsx("strong",{children:Ge})]})]}),s.jsxs("div",{className:"docker-management__actions",children:[s.jsxs("button",{className:"btn btn-sm",disabled:!0,title:x("nodes.availableSoon","Available after FN-3113"),children:[s.jsx(Di,{size:14}),x("nodes.startButton","Start")]}),s.jsxs("button",{className:"btn btn-sm",disabled:!0,title:x("nodes.availableSoon","Available after FN-3113"),children:[s.jsx(Lh,{size:14}),x("nodes.stopButton","Stop")]}),s.jsxs("button",{className:"btn btn-sm",disabled:!0,title:x("nodes.availableSoon","Available after FN-3113"),children:[s.jsx(qu,{size:14}),x("nodes.restartButton","Restart")]}),s.jsxs("button",{className:"btn btn-sm",onClick:()=>void Qx(),disabled:!y,children:[s.jsx(e0,{size:14}),x("nodes.viewLogsButton","View Logs")]})]}),Re&&s.jsxs("div",{className:"docker-management__log-viewer",children:[s.jsxs("div",{className:"docker-management__log-viewer-header",children:[s.jsx("strong",{children:x("nodes.containerLogs","Container Logs")}),s.jsx("button",{className:"btn-icon",onClick:()=>L(!1),"aria-label":x("nodes.closeLogsAriaLabel","Close logs"),children:s.jsx($a,{size:14})})]}),Ne?s.jsx("p",{children:x("nodes.fetchingLogs","Fetching logs...")}):s.jsx("pre",{children:Y.trim()||x("nodes.noLogsAvailable","No logs available")})]}),s.jsxs("details",{children:[s.jsx("summary",{children:x("nodes.dockerEnvVars","Environment Variables")}),s.jsx("dl",{className:"docker-management__env-list",children:Object.entries(v.envVars).map(([F,ie])=>s.jsxs("div",{children:[s.jsx("dt",{children:F}),s.jsx("dd",{children:RF(F,ie)})]},F))})]}),s.jsxs("details",{children:[s.jsx("summary",{children:x("nodes.dockerVolumeMounts","Volume Mounts")}),s.jsx("ul",{className:"docker-management__mounts-list",children:v.volumeMounts.map(F=>s.jsxs("li",{children:[s.jsxs("span",{children:[F.hostPath," → ",F.containerPath]}),F.readOnly&&s.jsx("span",{className:"node-card__type-badge",children:x("nodes.readOnly","Read-only")})]},`${F.hostPath}:${F.containerPath}`))})]})]}),r.type==="remote"&&s.jsxs("section",{className:"node-detail-modal__section",children:[s.jsx("h4",{children:x("nodes.sectionSettingsSync","Settings Sync")}),l&&s.jsxs("div",{className:"node-detail-modal__sync-status",children:[s.jsx("span",{className:`node-detail-modal__sync-dot ${TF(l.syncState)}`,"aria-hidden":!0}),s.jsxs("span",{children:[x("nodes.syncLastSync","Last sync:")," ",s.jsx("strong",{children:l.lastSyncAt?Xl(l.lastSyncAt):x("nodes.syncNeverSynced","Never synced")})]}),l.diffCount>0&&s.jsxs("span",{className:"node-detail-modal__sync-diff",children:[x("nodes.syncDifferences","Differences:")," ",s.jsx("strong",{children:l.diffCount})]})]}),s.jsxs("div",{className:"node-detail-modal__sync-actions",children:[s.jsxs("button",{className:"btn btn-sm",onClick:ya,disabled:B||!c,children:[s.jsx(uc,{size:14}),B?x("nodes.pushing","Pushing..."):x("nodes.pushSettings","Push Settings")]}),s.jsxs("button",{className:"btn btn-sm",onClick:Cn,disabled:K||!d,children:[s.jsx(Ri,{size:14}),K?x("nodes.pulling","Pulling..."):x("nodes.pullSettings","Pull Settings")]}),s.jsxs("button",{className:"btn btn-sm",onClick:Ss,disabled:G||!u,children:[s.jsx(Dh,{size:14}),G?x("nodes.syncing","Syncing..."):x("nodes.syncAuth","Sync Auth")]})]}),q&&s.jsxs("div",{className:"node-detail-modal__sync-error",children:[s.jsx("span",{children:q}),s.jsx("button",{className:"node-detail-modal__sync-error-dismiss",onClick:Zx,"aria-label":x("nodes.dismissError","Dismiss error"),children:s.jsx($a,{size:14})})]})]}),r.type==="remote"&&s.jsxs("section",{className:"node-detail-modal__section",children:[s.jsx("h4",{children:x("nodes.sectionSyncHistory","Sync History")}),s.jsx(AF,{nodeId:r.id,entries:m,singleNode:!0})]})]}),s.jsxs("div",{className:"modal-actions node-detail-modal__actions",children:[s.jsxs("button",{className:"btn btn-sm",onClick:Kr,children:[s.jsx(Rh,{size:14}),x("nodes.healthCheckButton","Health Check")]}),s.jsx("button",{className:"btn btn-sm",onClick:t,children:x("nodes.closeButton","Close")})]})]}),r.type==="remote"&&s.jsx(EF,{isOpen:re,onClose:()=>ae(!1),onResolve:h??(async()=>{}),conflicts:ye,localNodeName:x("nodes.localNodeName","Local"),remoteNodeName:r.name,addToast:o})]})}const $F=15e3,FF=1e3;function BF(){const[e,t]=f.useState([]),[r,n]=f.useState(!0),[a,i]=f.useState(null),o=f.useRef(null),l=f.useRef(0),c=f.useRef(e),d=nc();f.useEffect(()=>{c.current=e},[e]);const u=f.useCallback(b=>c.current.length>0&&ac(b,d.wasRecentlyHidden()),[d]),m=f.useCallback(async()=>{try{i(null);const b=await Wu();t(b)}catch(b){const y=b instanceof Error?b.message:"Failed to fetch managed Docker nodes";u(y)||i(y)}},[u]);f.useEffect(()=>{let b=!1;async function y(){n(!0);try{const j=await Wu();b||(t(j),i(null))}catch(j){const x=j instanceof Error?j.message:"Failed to fetch managed Docker nodes";!b&&!u(x)&&i(x)}finally{b||n(!1)}}y();const g=()=>{if(document.visibilityState!=="visible")return;const j=Date.now(),x=j-l.current;if(x<FF){Wa({view:"useManagedDockerNodes",trigger:"visibility",projectId:void 0,replayAttempted:!1,reason:"debounce-skipped",detail:{timeSinceLastRefreshMs:x}});return}l.current=j,Wa({view:"useManagedDockerNodes",trigger:"visibility",projectId:void 0,replayAttempted:!1,reason:"debounced-refresh"}),m()};return document.addEventListener("visibilitychange",g),()=>{b=!0,document.removeEventListener("visibilitychange",g)}},[m,u]),f.useEffect(()=>{if(!r)return o.current=setInterval(()=>{m()},$F),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[r,m]);const h=f.useCallback(async b=>t0(b),[]),v=f.useCallback(async(b,y)=>(await r0(b,y)).logs,[]),p=f.useCallback(async b=>{const y=await n0(b),g={...y,nodeId:y.nodeId??void 0,containerId:y.containerId??void 0,status:y.status,hostConfig:{type:y.hostConfig.host||y.hostConfig.context?"remote":"local",host:y.hostConfig.host,context:y.hostConfig.context},reachableUrl:y.reachableUrl??void 0,volumeMounts:y.volumeMounts.map(j=>({hostPath:j.hostPath,containerPath:j.containerPath,readOnly:j.mode==="ro"?!0:void 0})),persistentStorage:y.persistentStorage,resourceSizing:{cpuLimit:y.resourceSizing.cpus!==void 0?String(y.resourceSizing.cpus):void 0,memoryLimit:y.resourceSizing.memoryMB!==void 0?`${y.resourceSizing.memoryMB}MB`:void 0},errorMessage:y.errorMessage??void 0};return t(j=>[...j,g]),g},[]);return{dockerNodes:e,loading:r,error:a,refresh:m,getContainerStatus:h,getLogs:v,create:p}}function zF({addToast:e,onClose:t}){const{t:r}=se("app"),{nodes:n,loading:a,error:i,refresh:o,register:l,update:c,unregister:d,healthCheck:u,patchDockerConfig:m,fetchDockerDiff:h,discoverRemoteProjects:v}=Th(),{projects:p,refresh:b}=a0(),{meshState:y,loading:g,error:j}=sF(),{engines:x,loading:C,error:w}=cF(),{syncStatusMap:P,pushSettings:A,pullSettings:S,syncAuth:N,trackNode:E,getAuthSyncState:T,getAuthProviders:O}=nF(),{dockerNodes:I,loading:z,refresh:D,getContainerStatus:V,getLogs:B,create:W}=BF(),[K,te]=f.useState(!1),[G,M]=f.useState(!1),[q,H]=f.useState(null);f.useEffect(()=>{const L=n.filter(Y=>Y.type==="remote");for(const Y of L)E(Y.id)},[n,E]),f.useEffect(()=>{if(!q)return;const L=n.find(Y=>Y.id===q.id)??null;H(L)},[n,q]);const re=f.useMemo(()=>{const L=n.length,Y=n.filter(Oe=>Oe.status==="online").length,ne=n.filter(Oe=>Oe.status==="offline"||Oe.status==="error").length,Ne=n.filter(Oe=>Oe.type==="remote").length,Q=n.filter(Oe=>Oe.type==="remote"&&P[Oe.id]&&Zo(P[Oe.id]).syncState==="synced").length,le=I.length;return{total:L,online:Y,offline:ne,remote:Ne,synced:Q,docker:le}},[I.length,n,P]),ae=f.useCallback(async L=>{await l(L),await b()},[b,l]),ye=f.useCallback(async L=>{try{await W(L),e(r("nodes.dockerNodeCreated",'Docker node "{{name}}" created',{name:L.name}),"success"),M(!1)}catch(Y){const ne=Y instanceof Error?Y.message:r("nodes.failedCreateDocker","Failed to create Docker node");throw e(ne,"error"),Y}},[e,W,r]),oe=f.useMemo(()=>{const L=new Map;for(const Y of I)Y.nodeId&&L.set(Y.nodeId,Y);return L},[I]),He=f.useCallback(async()=>{try{await Promise.all([o(),D()])}catch{e(r("nodes.failedRefresh","Failed to refresh nodes"),"error")}},[e,o,D,r]),J=f.useCallback(async L=>{try{await u(L),e(r("nodes.healthCheckComplete","Node health check complete"),"success")}catch(Y){const ne=Y instanceof Error?Y.message:r("nodes.healthCheckFailed","Health check failed");e(ne,"error")}},[e,u,r]),Ce=f.useCallback(async L=>{try{await d(L),e(r("nodes.removed","Node removed"),"success"),q?.id===L&&H(null)}catch(Y){const ne=Y instanceof Error?Y.message:r("nodes.failedRemove","Failed to remove node");e(ne,"error")}},[e,q?.id,d,r]),Re=f.useCallback(async(L,Y)=>{await c(L,Y)},[c]);return s.jsxs("div",{className:"nodes-view","data-testid":"nodes-view",children:[s.jsxs("div",{className:"nodes-view-header",children:[s.jsxs("div",{className:"nodes-view-title",children:[s.jsxs("h2",{children:[s.jsx(Ih,{size:20}),r("nodes.heading","Nodes")]}),s.jsx("span",{className:"nodes-view-count",children:r("nodes.registeredCount","{{count}} registered",{count:n.length})})]}),s.jsxs("div",{className:"nodes-view-actions",children:[t?s.jsx("button",{className:"btn-icon nodes-view-close",onClick:t,"aria-label":r("nodes.closeAriaLabel","Close nodes view"),children:s.jsx($a,{size:16})}):null,s.jsxs("button",{className:"btn btn-sm",onClick:()=>void He(),disabled:a||z,children:[s.jsx(Gt,{size:14,className:a?"spin":""}),r("nodes.refresh","Refresh")]}),s.jsxs("button",{className:"btn btn-sm",onClick:()=>te(!0),children:[s.jsx(zn,{size:14}),r("nodes.addNode","Add Node")]}),s.jsxs("button",{className:"btn btn-sm",onClick:()=>M(!0),title:r("nodes.addDockerNodeTitle","Add a managed Docker node"),children:[s.jsx(rl,{size:14}),r("nodes.addDockerNode","Add Docker Node")]})]})]}),s.jsxs("div",{className:"nodes-view-stats",children:[s.jsxs("div",{className:"nodes-view-stat","data-testid":"nodes-stat-total",children:[s.jsx("span",{children:r("nodes.total","Total")}),s.jsx("strong",{children:re.total})]}),s.jsxs("div",{className:"nodes-view-stat nodes-view-stat--online","data-testid":"nodes-stat-online",children:[s.jsxs("span",{children:[s.jsx(kw,{size:14})," ",r("nodes.online","Online")]}),s.jsx("strong",{children:re.online})]}),s.jsxs("div",{className:"nodes-view-stat nodes-view-stat--offline","data-testid":"nodes-stat-offline",children:[s.jsxs("span",{children:[s.jsx(ww,{size:14})," ",r("nodes.offline","Offline")]}),s.jsx("strong",{children:re.offline})]}),s.jsxs("div",{className:"nodes-view-stat","data-testid":"nodes-stat-remote",children:[s.jsxs("span",{children:[s.jsx(i0,{size:14})," ",r("nodes.remote","Remote")]}),s.jsx("strong",{children:re.remote})]}),s.jsxs("div",{className:"nodes-view-stat nodes-view-stat--synced","data-testid":"nodes-stat-synced",children:[s.jsxs("span",{children:[s.jsx(Gt,{size:14})," ",r("nodes.synced","Synced")]}),s.jsx("strong",{children:re.synced})]}),s.jsxs("div",{className:"nodes-view-stat","data-testid":"nodes-stat-docker",children:[s.jsxs("span",{children:[s.jsx(rl,{size:14})," ",r("nodes.docker","Docker")]}),s.jsx("strong",{children:re.docker})]})]}),(i||j||w)&&s.jsx("div",{className:"nodes-view-error",children:i??j??w}),!g&&y.length>0&&s.jsxs("section",{className:"nodes-view-topology","aria-label":r("nodes.meshTopologyAriaLabel","Mesh Topology"),children:[s.jsx("h3",{className:"nodes-view-section-title",children:r("nodes.meshTopology","Mesh Topology")}),s.jsx(jF,{nodes:y,engines:C?void 0:x})]}),a?s.jsx("div",{className:"nodes-view-grid",children:Array.from({length:4}).map((L,Y)=>s.jsx("div",{className:"node-card node-card--loading","aria-hidden":!0},Y))}):n.length===0?s.jsxs("div",{className:"nodes-view-empty",children:[s.jsx("p",{children:r("nodes.noRegistered","No nodes are registered yet.")}),s.jsxs("button",{className:"btn btn-primary",onClick:()=>te(!0),children:[s.jsx(zn,{size:14}),r("nodes.addFirstNode","Add First Node")]})]}):s.jsx("div",{className:"nodes-view-grid",children:n.map(L=>{const Y=L.type==="remote"&&P[L.id]?Zo(P[L.id]):void 0;return s.jsx(pF,{node:L,projects:p,onHealthCheck:ne=>{J(ne)},onEdit:ne=>H(ne),onRemove:ne=>{Ce(ne)},isLoading:a,syncStatus:Y,authSyncState:L.type==="remote"?T(L.id):void 0,authSyncProviders:L.type==="remote"?O(L.id):void 0,managedDockerNode:oe.get(L.id)},L.id)})}),s.jsx(CF,{isOpen:K,onClose:()=>te(!1),onSubmit:ae,onDiscoverRemoteProjects:v,addToast:e,projects:p}),s.jsx(PF,{isOpen:G,onClose:()=>M(!1),onSubmit:ye,addToast:e}),s.jsx(LF,{isOpen:q!==null,onClose:()=>H(null),node:q,projects:p,onUpdate:Re,onHealthCheck:J,addToast:e,syncStatus:q?.type==="remote"&&q&&P[q.id]?Zo(P[q.id]):void 0,onPushSettings:A,onPullSettings:S,onSyncAuth:N,managedDockerNode:q?oe.get(q.id):void 0,onFetchContainerStatus:V,onFetchLogs:B,onUpdateDockerConfig:m,onFetchDockerConfigDiff:h})]})}function KF(){const{t:e}=se("app");return t=>{switch(t){case"triage":return e("commandCenter.funnel.stage.triage","Planning");case"todo":return e("commandCenter.funnel.stage.todo","Todo");case"in-progress":return e("commandCenter.funnel.stage.inProgress","In progress");case"in-review":return e("commandCenter.funnel.stage.inReview","In review");case"done":return e("commandCenter.funnel.stage.done","Done");case"other":return e("commandCenter.funnel.stage.other","Other");default:return t}}}function VF(e){return Number.isFinite(e)?e.toFixed(2):"—"}function UF({range:e,projectId:t}){const{t:r}=se("app"),n=KF(),{data:a,isLoading:i,error:o}=Je("/command-center/activity",e,{projectId:t}),l=a?.funnel??null,c=f.useMemo(()=>(l?.stages??[]).map(u=>({label:n(u.stage),value:u.entered})),[l?.stages,n]),d=!l||l.stages.every(u=>u.entered===0);return s.jsxs(ft,{testId:"funnel",isLoading:i,error:o,isEmpty:d,emptyMessage:r("commandCenter.funnel.empty","No task transitions in the selected range."),children:[s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.funnel.title","SDLC funnel")}),s.jsx(qx,{stages:c,ariaLabel:r("commandCenter.funnel.ariaLabel","Tasks per workflow stage")})]}),s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.funnel.throughputTitle","Throughput")}),s.jsxs("div",{className:"cc-stat-grid",children:[s.jsxs("div",{className:"card cc-stat-card cc-stat-card--gauge","data-testid":"cc-funnel-completion-rate",children:[s.jsx(Ua,{value:l?.completionRate??null,label:r("commandCenter.funnel.completionRate","Completion rate"),ariaLabel:r("commandCenter.funnel.completionRateAria","Completion rate for in-range planning entrants")}),s.jsx("span",{className:"cc-stat-sub",children:r("commandCenter.funnel.completionRateHint","Done ÷ entered (in range)")})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-funnel-throughput",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.funnel.throughputPerDay","Tasks done / day")}),s.jsx("div",{className:"cc-stat-value",children:VF(l?.throughputPerDay??0)}),s.jsx("span",{className:"cc-stat-sub",children:r("commandCenter.funnel.rangeDays","{{count}} day range",{count:l?.rangeDays??0})})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-funnel-done",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.funnel.doneInRange","Reached done")}),s.jsx("div",{className:"cc-stat-value",children:U(l?.doneInRange??0)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-funnel-entered",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.funnel.enteredInRange","Entered planning")}),s.jsx("div",{className:"cc-stat-value",children:U(l?.enteredInRange??0)})]})]})]})]})}const qF=8;function WF(e){const{t}=se("app");return[{id:"overview",label:t("commandCenter.tabs.overview","Overview")},{id:"tokens",label:t("commandCenter.tabs.tokens","Tokens")},{id:"tools",label:t("commandCenter.tabs.tools","Tools")},{id:"activity",label:t("commandCenter.tabs.activity","Activity")},{id:"agent-activity",label:t("commandCenter.tabs.agentActivity","Agent Activity")},{id:"productivity",label:t("commandCenter.tabs.productivity","Productivity")},{id:"review-artifacts",label:t("commandCenter.tabs.reviewArtifacts","Review artifacts")},{id:"team",label:t("commandCenter.tabs.team","Team")},{id:"workflows",label:t("commandCenter.tabs.workflows","Workflows")},{id:"ecosystem",label:t("commandCenter.tabs.ecosystem","Ecosystem")},{id:"github",label:t("commandCenter.tabs.github","GitHub")},{id:"gitlab",label:t("commandCenter.tabs.gitlab","GitLab")},{id:"signals",label:t("commandCenter.tabs.signals","Signals")},{id:"system",label:t("commandCenter.tabs.system","System")},{id:"plugins",label:t("commandCenter.tabs.plugins","Plugins")},...e?[{id:"nodes",label:t("commandCenter.tabs.nodes","Nodes")}]:[],{id:"reliability",label:t("commandCenter.tabs.reliability","Reliability")},{id:"mission-control",label:t("commandCenter.tabs.missionControl","Mission Control")}]}const Sh=15e3;function HF({range:e,projectId:t,colorTheme:r="default",themeMode:n="system",shadcnCustomColors:a={},resolvedThemeMode:i=n==="light"?"light":"dark",onColorThemeChange:o=()=>{},onThemeModeChange:l=()=>{},onShadcnCustomColorsChange:c=()=>{},onChangeView:d}){const{t:u}=se("app"),m=Je("/command-center/tokens?groupBy=model",e,{pollMs:Sh,projectId:t}),h=Je("/command-center/tools",e,{projectId:t}),v=Je("/command-center/activity",e,{projectId:t}),p=Je("/command-center/signals",e,{projectId:t}),{snapshot:b,isLoading:y}=Hx(t),[g,j]=f.useState(null),[x,C]=f.useState([]),w=f.useRef(0),P=f.useCallback(()=>{const Q=w.current,le=()=>w.current!==Q;fr(mr("/command-center/verification-requests",t)).then(Oe=>{le()||C(Oe.requests)}).catch(()=>{le()||C([])})},[t]);f.useEffect(()=>(P(),()=>{w.current+=1}),[P]),vn(P,Sh),f.useEffect(()=>{let Q=!1;return j(null),t?(o0(t).then(le=>{Q||j(le)},()=>{Q||j(null)}),()=>{Q=!0}):()=>{Q=!0}},[t]);const A=m.data?.totals?.totalTokens??0,S=h.data?.toolCalls??0,N=v.data?.activeNodes??0,E=v.data?.activeAgents??0,T=F2(b),O=v.data?.sessions??0,I=v.data?.agentRuns?.total??0,z=v.data?.funnel?.doneInRange??0,D=$2(b?.columns),V=m.data?.groups?.length??0,B=f.useMemo(()=>[...m.data?.groups??[]].sort((Q,le)=>le.totalTokens-Q.totalTokens||(Q.key??"").localeCompare(le.key??"")).slice(0,qF).map(Q=>({label:Q.key??u("commandCenter.tokens.unknownModel","(unknown)"),value:Q.totalTokens,valueLabel:U(Q.totalTokens),iconProvider:ec(Q.key??"")})),[m.data?.groups,u]),W=f.useMemo(()=>[...h.data?.byCategory??[]].sort((Q,le)=>le.count-Q.count||Q.category.localeCompare(le.category)).map(Q=>({label:Q.category,value:Q.count,valueLabel:U(Q.count)})),[h.data?.byCategory]),K=f.useMemo(()=>B.map(Q=>({label:Q.label,value:Q.value})),[B]),te=f.useMemo(()=>(v.data?.daily??[]).map(Q=>Q.messages+Q.activeAgents+(Q.agentRuns??0)),[v.data?.daily]),G=f.useMemo(()=>[{label:u("commandCenter.activity.messages","Messages"),values:(v.data?.daily??[]).map(Q=>Q.messages)},{label:u("commandCenter.activity.activeAgents","Active agents"),values:(v.data?.daily??[]).map(Q=>Q.activeAgents)},{label:u("commandCenter.activity.agentRuns","Agent runs"),values:(v.data?.daily??[]).map(Q=>Q.agentRuns)}],[v.data?.daily,u]),M=te.length>0?te:[O,v.data?.messages??0,E,N,z],q=B.length>0||W.length>0||te.length>0,H=O>0||(v.data?.messages??0)>0||N>0||E>0||I>0||z>0,re=A>0||S>0||H,ye=!(m.data!==null&&h.data!==null&&v.data!==null)&&(m.isLoading||h.isLoading||v.isLoading),oe=m.error??h.error??v.error,He=m.data?Tr(m.data.cost?.usd??null,m.data.cost?.unavailable??!0):"—",J=h.data?h.data.fullyAutonomous?u("commandCenter.tools.ratioAutonomous","{{ratio}} calls/session (fully autonomous)",{ratio:h.data.autonomyRatio.toFixed(1)}):`${h.data.autonomyRatio.toFixed(1)}:1`:"—",Ce=[{id:"codebaseTokens",testId:"cc-overview-codebase-tokens",label:u("commandCenter.overview.codebaseTokens","Codebase tokens"),value:g?U(g.tokenEstimate):"—",subLabel:g?.truncated?u("commandCenter.overview.metricsPartial","Approx. (partial)"):g?u("commandCenter.overview.codebaseTokensHint","Local estimate calibrated to cl100k_base"):void 0},{id:"diskSize",testId:"cc-overview-disk-size",label:u("commandCenter.overview.diskSize","Disk size"),value:g?ct(g.diskBytes):"—",subLabel:g?.truncated?u("commandCenter.overview.metricsPartial","Approx. (partial)"):g?u("commandCenter.overview.diskSizeHint","Apparent local size"):void 0}],Re=Q=>s.jsx("div",{className:"cc-stat-grid",children:Q.map(le=>s.jsxs("div",{className:"card cc-stat-card","data-testid":le.testId??`command-center-stat-${le.id}`,children:[s.jsx("div",{className:"cc-stat-label",children:le.label}),s.jsx("div",{className:`cc-stat-value ${le.id==="tokens"?"cc-token-count-live":""}`,children:le.value},le.value),le.subLabel?s.jsx("span",{className:"cc-stat-sub",children:le.subLabel}):null]},le.id))}),L=[{id:"tokens",label:u("commandCenter.overview.tokensCost","Tokens & cost"),value:U(A),subLabel:He},{id:"autonomy",label:u("commandCenter.overview.autonomy","Autonomy ratio"),value:J},{id:"agentRuns",label:u("commandCenter.overview.agentRuns","Agent runs"),value:U(I)},{id:"tasksDone",label:u("commandCenter.overview.tasksDone","Tasks done"),value:U(z)},{id:"models",label:u("commandCenter.overview.uniqueModels","Unique models"),value:U(V)},{id:"signals",label:u("commandCenter.overview.openSignals","Open signals"),value:p.isLoading?"—":p.data?U(p.data.open??0):"—"}],Y=s.jsx(Q2,{projectId:t,colorTheme:r,themeMode:n,shadcnCustomColors:a,resolvedThemeMode:i,onColorThemeChange:o,onThemeModeChange:l,onShadcnCustomColorsChange:c,onChangeView:d}),ne=s.jsx("div",{className:"cc-overview-throughput","data-testid":"command-center-throughput",children:s.jsx(UF,{range:e,projectId:t})}),Ne=x.length>0?s.jsxs("section",{className:"cc-verification-requests card","data-testid":"command-center-verification-requests",children:[s.jsxs("div",{className:"cc-overview-chart-header",children:[s.jsx("h3",{className:"cc-area-section-title",children:"Task verification"}),s.jsx("p",{children:"Latest executor-owned verification requests"})]}),x.map(Q=>s.jsxs("div",{className:"cc-verification-requests__item",children:[s.jsx("span",{className:"cc-verification-requests__task",children:Q.taskId}),s.jsx(l0,{request:Q,compact:!0})]},Q.requestId))]}):null;return ye?s.jsxs("div",{className:"cc-overview",children:[Y,Re(Ce),s.jsxs("div",{className:"cc-loading","data-testid":"command-center-overview-loading",children:[s.jsx("div",{className:"cc-chart-skeleton"}),s.jsx("p",{children:s.jsx(rc,{label:u("commandCenter.loading","Loading dashboard...")})})]}),Ne,ne]}):oe!==null&&!re?s.jsxs("div",{className:"cc-overview",children:[Y,Re(Ce),s.jsxs("div",{className:"cc-error","data-testid":"command-center-overview-error",role:"alert",children:[s.jsx(Mi,{size:24}),s.jsx("p",{children:oe})]}),Ne,ne]}):re?s.jsxs("div",{className:"cc-overview",children:[Y,Re([...Ce,...L]),s.jsxs("div",{className:"cc-live-strip","data-testid":"command-center-live-strip",children:[s.jsxs("div",{className:"cc-live-strip-heading",children:[s.jsx("span",{className:"status-dot status-dot--connecting","aria-hidden":"true"}),s.jsx("span",{className:"cc-live-strip-label",children:u("commandCenter.overview.liveStrip","Live activity snapshot")})]}),s.jsxs("div",{className:"cc-live-strip-metrics","data-testid":"command-center-live-snapshot",children:[s.jsxs("span",{className:"cc-live-metric","data-testid":"command-center-live-tasks-in-progress",children:[s.jsx("span",{className:"cc-live-metric-value",children:y?"—":U(D)}),s.jsx("span",{className:"cc-live-metric-label",children:u("commandCenter.overview.tasksInProgress","tasks in progress")})]}),s.jsxs("span",{className:"cc-live-metric","data-testid":"command-center-live-agents-working",children:[s.jsx("span",{className:"cc-live-metric-value",children:y?"—":U(T)}),s.jsx("span",{className:"cc-live-metric-label",children:u("commandCenter.overview.agentsWorking","agents working")})]}),s.jsxs("span",{className:"cc-live-metric","data-testid":"command-center-live-tokens",children:[s.jsx("span",{className:"cc-live-metric-value cc-token-count-live",children:U(A)},A),s.jsx("span",{className:"cc-live-metric-label",children:u("commandCenter.overview.liveTokens","tokens")})]}),s.jsxs("span",{className:"cc-live-metric","data-testid":"command-center-live-open-signals",children:[s.jsx("span",{className:"cc-live-metric-value",children:p.isLoading?"—":p.data?U(p.data.open??0):"—"}),s.jsx("span",{className:"cc-live-metric-label",children:u("commandCenter.overview.openSignals","open signals")})]})]}),s.jsxs("div",{className:"cc-live-trend","data-testid":"command-center-throughput-trend",children:[s.jsx("span",{className:"cc-live-trend-label",children:u("commandCenter.overview.throughputTrend","throughput trend")}),s.jsx(Ot,{values:M,ariaLabel:u("commandCenter.overview.throughputTrendAria","Recent activity throughput trend")})]})]}),Ne,q?s.jsxs("section",{className:"cc-overview-charts","data-testid":"command-center-overview-charts",children:[B.length>0?s.jsxs("div",{className:"card cc-overview-chart-card","data-testid":"command-center-overview-chart-tokens",children:[s.jsxs("div",{className:"cc-overview-chart-header",children:[s.jsx("h3",{className:"cc-area-section-title",children:u("commandCenter.overview.tokensByModel","Tokens by model")}),s.jsx("p",{children:u("commandCenter.overview.tokensByModelHint","Top model token consumers in this range")})]}),s.jsx(nt,{data:B,ariaLabel:u("commandCenter.overview.tokensByModel","Tokens by model")})]}):null,K.length>0?s.jsxs("div",{className:"card cc-overview-chart-card","data-testid":"cc-overview-pie",children:[s.jsxs("div",{className:"cc-overview-chart-header",children:[s.jsx("h3",{className:"cc-area-section-title",children:u("commandCenter.overview.tokensByModelPie","Token share by model")}),s.jsx("p",{children:u("commandCenter.overview.tokensByModelPieHint","Top model token share in this range")})]}),s.jsx(Mt,{data:K,ariaLabel:u("commandCenter.overview.tokensByModelPie","Token share by model")})]}):null,W.length>0?s.jsxs("div",{className:"card cc-overview-chart-card","data-testid":"command-center-overview-chart-tools",children:[s.jsxs("div",{className:"cc-overview-chart-header",children:[s.jsx("h3",{className:"cc-area-section-title",children:u("commandCenter.overview.toolCategories","Tool categories")}),s.jsx("p",{children:u("commandCenter.overview.toolCategoriesHint","Autonomous work grouped by tool family")})]}),s.jsx(nt,{data:W,ariaLabel:u("commandCenter.overview.toolCategories","Tool categories")})]}):null,te.length>0?s.jsxs("div",{className:"card cc-overview-chart-card cc-overview-chart-card--trend","data-testid":"cc-overview-line",children:[s.jsxs("div",{className:"cc-overview-chart-header",children:[s.jsx("h3",{className:"cc-area-section-title",children:u("commandCenter.overview.dailyActivityLine","Daily activity line")}),s.jsx("p",{children:u("commandCenter.overview.dailyActivityLineHint","Messages, agents, and runs by day")})]}),s.jsx(br,{series:G,ariaLabel:u("commandCenter.overview.dailyActivityLine","Daily activity line")})]}):null,te.length>0?s.jsxs("div",{className:"card cc-overview-chart-card cc-overview-chart-card--trend","data-testid":"command-center-overview-chart-activity",children:[s.jsxs("div",{className:"cc-overview-chart-header",children:[s.jsx("h3",{className:"cc-area-section-title",children:u("commandCenter.overview.dailyActivity","Daily activity trend")}),s.jsx("p",{children:u("commandCenter.overview.dailyActivityHint","Messages plus active agents per day")})]}),s.jsx(Ot,{values:te,ariaLabel:u("commandCenter.overview.dailyActivityAria","Daily activity trend")})]}):null]}):null,ne]}):s.jsxs("div",{className:"cc-overview",children:[Y,Re(Ce),s.jsxs("div",{className:"cc-empty","data-testid":"command-center-empty",children:[s.jsx(Ii,{size:28}),s.jsx("p",{children:u("commandCenter.empty","No usage data yet. Run some agents to populate the Dashboard.")})]}),Ne,ne]})}function GF({tabId:e}){const{t}=se("app");return s.jsxs("div",{className:"cc-empty","data-testid":`command-center-placeholder-${e}`,children:[s.jsx(Ii,{size:28}),s.jsx("p",{children:t("commandCenter.areaPending","This area renders once metrics data is available.")})]})}function RB({projectId:e,colorTheme:t="default",themeMode:r="system",shadcnCustomColors:n={},resolvedThemeMode:a=r==="light"?"light":"dark",onColorThemeChange:i=()=>{},onThemeModeChange:o=()=>{},onShadcnCustomColorsChange:l=()=>{},addToast:c=()=>{},nodesEnabled:d=!1,onChangeView:u,onOpenAgent:m,onOpenTask:h}={}){const{t:v}=se("app"),p=WF(d),[b,y]=f.useState(()=>Os(e)?.activeTab??"overview"),[g,j]=f.useState(()=>Os(e)?.range??cl(ll((S,N)=>N)[1])),x=f.useRef(e);f.useEffect(()=>{if(x.current===e)return;x.current=e;const S=Os(e);y(S?.activeTab??"overview"),j(S?.range??cl(ll((N,E)=>E)[1]))},[e]),f.useEffect(()=>{x.current===e&&s0({activeTab:b,range:g},e)},[b,e,g]),f.useEffect(()=>{p.some(S=>S.id===b)||y("overview")},[b,p]);const C=f.useRef([]),w=f.useCallback(S=>{const N=(S+p.length)%p.length;y(p[N].id),C.current[N]?.focus()},[p]),P=f.useCallback((S,N)=>{switch(S.key){case"ArrowRight":case"ArrowDown":S.preventDefault(),w(N+1);break;case"ArrowLeft":case"ArrowUp":S.preventDefault(),w(N-1);break;case"Home":S.preventDefault(),w(0);break;case"End":S.preventDefault(),w(p.length-1);break;case"Enter":case" ":S.preventDefault(),y(p[N].id);break}},[w,p]);function A(){switch(b){case"overview":return s.jsx(HF,{range:g,projectId:e,colorTheme:t,themeMode:r,shadcnCustomColors:n,resolvedThemeMode:a,onColorThemeChange:i,onThemeModeChange:o,onShadcnCustomColorsChange:l,onChangeView:u});case"tokens":return s.jsx(v$,{range:g,projectId:e});case"tools":return s.jsx(h$,{range:g,projectId:e});case"activity":return s.jsx(A$,{range:g,projectId:e});case"agent-activity":return s.jsx(G$,{projectId:e,range:g,onOpenAgent:m,onOpenTask:h});case"productivity":return s.jsx(Y$,{range:g,projectId:e});case"review-artifacts":return s.jsx(Z$,{projectId:e,addToast:c});case"team":return s.jsx(o2,{range:g,projectId:e,addToast:c});case"workflows":return s.jsx(c2,{range:g,projectId:e});case"ecosystem":return s.jsx(u2,{range:g,projectId:e});case"github":return s.jsx(m2,{range:g,projectId:e});case"gitlab":return s.jsx(h2,{range:g,projectId:e});case"signals":return s.jsx(p2,{range:g,projectId:e});case"system":return s.jsxs("div",{className:"cc-system-tab","data-testid":"cc-system-tab",children:[s.jsx(D2,{projectId:e,addToast:c}),s.jsx(A2,{})]});case"plugins":return s.jsx(aw,{addToast:c??(()=>{}),projectId:e});case"nodes":return s.jsx(zF,{addToast:c});case"reliability":return s.jsx(eF,{projectId:e});case"mission-control":return s.jsx(H2,{projectId:e});default:return s.jsx(GF,{tabId:b})}}return s.jsxs("section",{className:"command-center","data-testid":"command-center",children:[s.jsxs("header",{className:"cc-header",children:[s.jsxs("h2",{className:"cc-title",children:[s.jsx(Ii,{size:20}),v("commandCenter.heading","Dashboard")]}),s.jsx(aC,{value:g,onChange:j})]}),s.jsx("div",{className:"cc-tablist",role:"tablist","aria-label":v("commandCenter.tablistLabel","Dashboard sections"),children:p.map((S,N)=>{const E=S.id===b;return s.jsx("button",{ref:T=>{C.current[N]=T},role:"tab",id:`cc-tab-${S.id}`,"aria-selected":E,"aria-controls":`cc-tabpanel-${S.id}`,tabIndex:E?0:-1,className:`cc-tab${E?" active":""}`,onClick:()=>y(S.id),onKeyDown:T=>P(T,N),"data-testid":`command-center-tab-${S.id}`,children:S.label},S.id)})}),s.jsx("div",{role:"tabpanel",id:`cc-tabpanel-${b}`,"aria-labelledby":`cc-tab-${b}`,tabIndex:0,className:"cc-tabpanel","data-testid":`command-center-panel-${b}`,children:A()})]})}export{RB as CommandCenter};
102
+ `)}function EF({isOpen:e,onClose:t,onResolve:r,conflicts:n,localNodeName:a,remoteNodeName:i,addToast:o}){const{t:l}=se("app"),[c,d]=f.useState({}),[u,m]=f.useState(!1);f.useEffect(()=>{const g={};for(const j of n)c[j.key]||(g[j.key]={resolution:"local"});Object.keys(g).length>0&&d(j=>({...j,...g}))},[n,c]),f.useEffect(()=>{if(!e)return;const g=j=>{j.key==="Escape"&&(j.preventDefault(),t())};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[e,t]);const h=f.useCallback((g,j)=>{d(x=>{const C=x[g]??{};return j==="manual"?{...x,[g]:{resolution:"manual",manualValue:C.manualValue??JSON.stringify(n.find(w=>w.key===g)?.localValue??null,null,2)}}:{...x,[g]:{resolution:j}}})},[n]),v=f.useCallback((g,j)=>{d(x=>({...x,[g]:{...x[g],resolution:"manual",manualValue:j}}))},[]),p=f.useCallback(g=>{const j={};for(const x of n)j[x.key]={resolution:g};d(j)},[n]),b=f.useCallback(async()=>{m(!0);try{const g=n.map(j=>{const x=c[j.key]??{resolution:"local"};let C;switch(x.resolution){case"remote":C=j.remoteValue;break;case"manual":try{C=JSON.parse(x.manualValue??"null")}catch{C=x.manualValue??null}break;case"local":default:C=j.localValue;break}return{key:j.key,value:C}});await r(g),o(l("settings.resolvedSuccess","Settings conflicts resolved successfully"),"success"),t()}catch(g){const j=g instanceof Error?g.message:l("settings.resolveFailed","Failed to resolve conflicts");o(j,"error")}finally{m(!1)}},[o,n,t,r,c]),y=f.useMemo(()=>{const g={};for(const j of n)g[j.key]=OF(j.localValue,j.remoteValue);return g},[n]);return!e||n.length===0?null:s.jsx("div",{className:"modal-overlay open",onClick:t,children:s.jsxs("div",{className:"modal modal-lg settings-sync-conflict-modal",onClick:g=>g.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":l("settings.conflictModalTitle","Resolve Settings Conflicts"),children:[s.jsxs("div",{className:"modal-header",children:[s.jsx("h3",{children:l("settings.conflictModalTitle","Resolve Settings Conflicts")}),s.jsx("button",{className:"modal-close",onClick:t,"aria-label":l("settings.closeModal","Close conflict modal"),children:"×"})]}),s.jsxs("div",{className:"modal-body",children:[s.jsx("div",{className:"settings-sync-conflict-modal__conflict-list",children:n.map(g=>{const j=c[g.key]??{resolution:"local"},x=y[g.key];return s.jsxs("div",{className:"settings-sync-conflict-modal__conflict-item",children:[s.jsx("div",{className:"settings-sync-conflict-modal__key",children:g.key}),s.jsxs("div",{className:"settings-sync-conflict-modal__diff-panel",children:[s.jsxs("div",{className:"settings-sync-conflict-modal__diff-side",children:[s.jsx("div",{className:"settings-sync-conflict-modal__diff-label",children:a}),s.jsx("div",{className:"settings-sync-conflict-modal__diff-content",children:s.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap"},children:x})})]}),s.jsxs("div",{className:"settings-sync-conflict-modal__diff-side",children:[s.jsx("div",{className:"settings-sync-conflict-modal__diff-label",children:i}),s.jsx("div",{className:"settings-sync-conflict-modal__diff-content",children:s.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap"},children:x})})]})]}),s.jsxs("div",{className:"settings-sync-conflict-modal__resolution",children:[s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:`resolution-${g.key}`,checked:j.resolution==="local",onChange:()=>h(g.key,"local")}),l("settings.keepLocal","Keep Local")]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:`resolution-${g.key}`,checked:j.resolution==="remote",onChange:()=>h(g.key,"remote")}),l("settings.keepRemote","Keep Remote")]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:`resolution-${g.key}`,checked:j.resolution==="manual",onChange:()=>h(g.key,"manual")}),l("settings.mergeManually","Merge Manually")]})]}),j.resolution==="manual"&&s.jsx("textarea",{className:"settings-sync-conflict-modal__manual-input",value:j.manualValue??"",onChange:C=>v(g.key,C.target.value),placeholder:l("settings.jsonPlaceholder","Enter JSON value...")})]},g.key)})}),s.jsxs("div",{className:"settings-sync-conflict-modal__bulk-actions",children:[s.jsx("button",{className:"btn btn-sm",onClick:()=>p("local"),type:"button",children:l("settings.resolveAllLocal","Resolve All: Keep Local")}),s.jsx("button",{className:"btn btn-sm",onClick:()=>p("remote"),type:"button",children:l("settings.resolveAllRemote","Resolve All: Keep Remote")})]})]}),s.jsxs("div",{className:"modal-actions settings-sync-conflict-modal__footer",children:[s.jsx("button",{className:"btn btn-sm",onClick:t,children:l("actions.cancel","Cancel")}),s.jsx("button",{className:"btn btn-primary btn-sm",onClick:b,disabled:u,children:u?l("settings.resolving","Resolving..."):l("actions.confirm","Confirm")})]})]})})}const Ra={readWrite:"rw",readOnly:"ro",volume:"volume",bind:"bind"},Yx=/(KEY|TOKEN|SECRET|PASSWORD)/i;function Qo(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?"—":t.toLocaleString()}function _F(e){if(!e)return"—";const t=new Date(e),r=Date.now();if(Number.isNaN(t.getTime())||t.getTime()>r)return"—";const n=Math.floor((r-t.getTime())/1e3);if(n<60)return`${n}s`;const a=Math.floor(n/60);if(a<60)return`${a}m`;const i=Math.floor(a/60);return i<24?`${i}h ${a%60}m`:`${Math.floor(i/24)}d ${i%24}h`}function TF(e){switch(e){case"synced":return"node-detail-modal__sync-dot--synced";case"diff":return"node-detail-modal__sync-dot--diff";case"error":return"node-detail-modal__sync-dot--error";case"pending":return"node-detail-modal__sync-dot--pending";case"never-synced":default:return"node-detail-modal__sync-dot--never"}}function MF(e){return e==="running"?"success":e==="creating"||e==="recreating"||e==="restarting"?"warning":"error"}function IF(e){return e?`${e.charAt(0).toUpperCase()}${e.slice(1)}`:"Unknown"}function DF(e){if(!e)return"—";try{const t=new URL(e);return t.port?t.port:t.protocol==="https:"?"443":t.protocol==="http:"?"80":"—"}catch{return"—"}}function RF(e,t){return Yx.test(e)?"••••••••":t}function LF({isOpen:e,onClose:t,node:r,projects:n,onUpdate:a,onHealthCheck:i,addToast:o,syncStatus:l,onPushSettings:c,onPullSettings:d,onSyncAuth:u,syncHistory:m=[],onResolveConflicts:h,managedDockerNode:v,containerStatus:p,onFetchContainerStatus:b,onFetchLogs:y,onUpdateDockerConfig:g,onFetchDockerConfigDiff:j}){const{t:x}=se("app"),C=f.useRef(!0),[w,P]=f.useState(!1),[A,S]=f.useState(""),[N,E]=f.useState(""),[T,O]=f.useState(""),[I,z]=f.useState(2),[D,V]=f.useState(!1),[B,W]=f.useState(!1),[K,te]=f.useState(!1),[G,M]=f.useState(!1),[q,H]=f.useState(null),[re,ae]=f.useState(!1),[ye]=f.useState([]),[oe,He]=f.useState(p),[J,Ce]=f.useState(!1),[Re,L]=f.useState(!1),[Y,ne]=f.useState(""),[Ne,Q]=f.useState(!1),[le,Oe]=f.useState(!1),[k,$]=f.useState(r?.dockerConfig??null),[de,Le]=f.useState({}),[Nt,pa]=f.useState(!1),[ks,R]=f.useState(!1);f.useEffect(()=>(C.current=!0,()=>{C.current=!1}),[]),f.useEffect(()=>{He(p)},[p]),f.useEffect(()=>{if(!r||!e){P(!1),L(!1),ne("");return}S(r.name),E(r.url??""),O(r.apiKey??""),z(r.maxConcurrent),P(!1),$(r.dockerConfig??null),Oe(!1),Le({})},[e,r]),f.useEffect(()=>{if(!e)return;const F=ie=>{ie.key==="Escape"&&(ie.preventDefault(),t())};return document.addEventListener("keydown",F),()=>document.removeEventListener("keydown",F)},[e,t]);const ce=f.useMemo(()=>r?Yj(n,r):[],[r,n]),Pe=f.useMemo(()=>v?v.hostConfig.type==="remote"?v.hostConfig.host??"—":x("nodes.localDocker","Local Docker"):"—",[v,x]),Ge=f.useMemo(()=>!v?.resourceSizing?.cpuLimit&&!v?.resourceSizing?.memoryLimit?x("nodes.dockerResourceDefault","Default"):`${v.resourceSizing?.cpuLimit??x("nodes.dockerDefaultCpu","Default CPU")} / ${v.resourceSizing?.memoryLimit??x("nodes.dockerDefaultMemory","Default memory")}`,[v,x]),Kr=f.useCallback(async()=>{if(r)try{if(await i(r.id),!C.current)return;o(x("nodes.healthCheckSuccess","Health check completed for {{name}}",{name:r.name}),"success")}catch(F){if(!C.current)return;const ie=F instanceof Error?F.message:x("nodes.healthCheckFailed","Health check failed");o(ie,"error")}},[o,r,i]),ya=f.useCallback(async()=>{if(!(!r||!c)){H(null),W(!0);try{if(await c(r.id),!C.current)return;o(x("nodes.pushSettingsSuccess","Settings pushed successfully"),"success")}catch(F){if(!C.current)return;const ie=F instanceof Error?F.message:x("nodes.pushSettingsFailed","Push settings failed");H(ie),o(ie,"error")}finally{C.current&&W(!1)}}},[o,r,c]),Cn=f.useCallback(async()=>{if(!(!r||!d)){H(null),te(!0);try{if(await d(r.id),!C.current)return;o(x("nodes.pullSettingsSuccess","Settings pulled successfully"),"success")}catch(F){if(!C.current)return;const ie=F instanceof Error?F.message:x("nodes.pullSettingsFailed","Pull settings failed");H(ie),o(ie,"error")}finally{C.current&&te(!1)}}},[o,r,d]),Ss=f.useCallback(async()=>{if(!(!r||!u)){H(null),M(!0);try{if(await u(r.id),!C.current)return;o(x("nodes.syncAuthSuccess","Auth credentials synced successfully"),"success")}catch(F){if(!C.current)return;const ie=F instanceof Error?F.message:x("nodes.syncAuthFailed","Auth sync failed");H(ie),o(ie,"error")}finally{C.current&&M(!1)}}},[o,r,u]),Zx=f.useCallback(()=>{H(null)},[]),Jx=f.useCallback(async()=>{if(!(!v||!b)){Ce(!0);try{const F=await b(v.id);if(!C.current)return;He(F)}catch(F){const ie=F instanceof Error?F.message:x("nodes.fetchContainerStatusFailed","Failed to fetch container status");o(ie,"error")}finally{C.current&&Ce(!1)}}},[o,v,b]),Qx=f.useCallback(async()=>{if(!(!v||!y)){L(!0),Q(!0);try{const F=await y(v.id);if(!C.current)return;ne(F)}catch(F){if(!C.current)return;ne("");const ie=F instanceof Error?F.message:x("nodes.fetchContainerLogsFailed","Failed to fetch container logs");o(ie,"error")}finally{C.current&&Q(!1)}}},[o,v,y]),ej=f.useCallback(async()=>{if(!r||D)return;const F=A.trim();if(!F){o(x("nodes.nameRequired","Name is required"),"error");return}if(r.type==="remote"&&!N.trim()){o(x("nodes.urlRequired","URL is required for remote nodes"),"error");return}if(!Number.isFinite(I)||I<1){o(x("nodes.concurrencyMin","Concurrency must be at least 1"),"error");return}V(!0);try{await a(r.id,{name:F,url:r.type==="remote"&&N.trim()||void 0,apiKey:r.type==="remote"&&T||void 0,maxConcurrent:I}),o(x("nodes.updateSuccess","Updated {{name}}",{name:F}),"success"),P(!1)}catch(ie){const it=ie instanceof Error?ie.message:x("nodes.updateFailed","Failed to update node");o(it,"error")}finally{V(!1)}},[o,T,D,I,A,r,a,N]);f.useEffect(()=>{!r?.dockerConfig||!j||!e||j(r.id).then(F=>{C.current&&R(F.needsRecreate)}).catch(()=>{C.current&&R(!1)})},[e,r,j]);const tj=f.useCallback(async()=>{if(!(!r||!k||!g||Nt)){pa(!0);try{const F=await g(r.id,{image:k.image,volumeMounts:k.volumeMounts,environment:k.environment,resources:k.resources,host:k.host,extraClis:k.extraClis,persistence:k.persistence,containerName:k.containerName});if(!C.current)return;$(F),o(x("nodes.dockerConfigSaveSuccess","Docker config saved"),"success")}catch(F){if(!C.current)return;const ie=F instanceof Error?F.message:x("nodes.dockerConfigSaveFailed","Failed to save Docker config");o(ie,"error")}finally{C.current&&pa(!1)}}},[o,k,Nt,r,g]),rj=f.useCallback(()=>{r&&(S(r.name),E(r.url??""),O(r.apiKey??""),z(r.maxConcurrent),P(!1))},[r]);if(!e||!r)return null;const sr=oe?.status??v?.status,nj=MF(sr);return s.jsxs(ic,{windowKey:"node-detail",title:x("nodes.modalTitle","Node Details"),ariaLabel:x("nodes.modalAriaLabel","Node details for {{name}}",{name:r.name}),onClose:t,hideHeader:!0,dragHandleSelector:".modal-header",className:"floating-window--node-detail",defaultSize:{width:720,height:560},minSize:{width:360,height:280},persistGeometryKey:"floating-window:node-detail",suspendGeometryPersistenceOnMobile:!0,suspendGeometryPersistenceOnShortViewport:!0,closeOnOutsidePointerDown:!0,children:[s.jsxs("div",{className:"modal modal-lg node-detail-modal",children:[s.jsxs("div",{className:"modal-header",children:[s.jsx("h3",{children:x("nodes.modalTitle","Node Details")}),s.jsx("button",{className:"modal-close",onClick:t,"aria-label":x("nodes.closeModalAriaLabel","Close node detail modal"),children:"×"})]}),s.jsxs("div",{className:"modal-body node-detail-modal__body",children:[s.jsxs("section",{className:"node-detail-modal__section",children:[s.jsxs("div",{className:"node-detail-modal__section-header",children:[s.jsx("h4",{children:x("nodes.sectionOverview","Overview")}),!w&&s.jsxs("button",{className:"btn btn-sm",onClick:()=>P(!0),children:[s.jsx(Zj,{size:14}),x("nodes.editButton","Edit")]})]}),s.jsxs("div",{className:"node-detail-modal__grid",children:[s.jsxs("label",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.fieldName","Name")}),w?s.jsx("input",{className:"input",value:A,onChange:F=>S(F.target.value),disabled:D}):s.jsx("strong",{children:r.name})]}),s.jsxs("div",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.fieldType","Type")}),s.jsx("strong",{children:r.type==="local"?x("nodes.typeLocal","Local"):x("nodes.typeRemote","Remote")})]}),s.jsxs("div",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.fieldStatus","Status")}),s.jsx("strong",{children:r.status})]}),s.jsxs("label",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.fieldMaxConcurrent","Max Concurrent")}),w?s.jsx("input",{className:"input",type:"number",min:1,max:10,value:I,onChange:F=>z(Number(F.target.value)),disabled:D}):s.jsx("strong",{children:r.maxConcurrent})]}),r.type==="remote"&&s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"node-detail-modal__field node-detail-modal__field--full",children:[s.jsx("span",{children:x("nodes.fieldUrl","URL")}),w?s.jsx("input",{className:"input",value:N,onChange:F=>E(F.target.value),disabled:D}):s.jsx("strong",{children:r.url??"—"})]}),s.jsxs("label",{className:"node-detail-modal__field node-detail-modal__field--full",children:[s.jsx("span",{children:x("nodes.fieldApiKey","API Key")}),w?s.jsx("input",{className:"input",type:"password",value:T,onChange:F=>O(F.target.value),placeholder:x("nodes.apiKeyPlaceholder","Leave blank to keep unchanged"),disabled:D}):s.jsx("strong",{children:r.apiKey?"••••••••":x("nodes.apiKeyNotConfigured","Not configured")})]})]}),s.jsxs("div",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.fieldCreated","Created")}),s.jsx("strong",{children:Qo(r.createdAt)})]}),s.jsxs("div",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.fieldUpdated","Updated")}),s.jsx("strong",{children:Qo(r.updatedAt)})]})]}),w&&s.jsxs("div",{className:"node-detail-modal__edit-actions",children:[s.jsxs("button",{className:"btn btn-primary btn-sm",onClick:ej,disabled:D,children:[s.jsx(Uu,{size:14}),D?x("nodes.saving","Saving..."):x("nodes.saveButton","Save")]}),s.jsxs("button",{className:"btn btn-sm",onClick:rj,disabled:D,children:[s.jsx($a,{size:14}),x("nodes.cancelButton","Cancel")]})]})]}),s.jsxs("section",{className:"node-detail-modal__section",children:[s.jsxs("h4",{children:[r.type==="local"?x("nodes.sectionProjects","Projects"):x("nodes.sectionAssignedProjects","Assigned Projects")," (",ce.length,")"]}),ce.length===0?s.jsx("p",{className:"node-detail-modal__empty",children:r.type==="local"?x("nodes.noProjectsRunning","No projects are running on this node."):x("nodes.noProjectsAssigned","No projects are assigned to this node.")}):s.jsx("ul",{className:"node-detail-modal__project-list",children:ce.map(F=>s.jsxs("li",{className:"node-detail-modal__project-item",children:[s.jsx("span",{children:F.name}),s.jsx("code",{children:F.id})]},F.id))})]}),s.jsxs("section",{className:"node-detail-modal__section",children:[s.jsx("h4",{children:x("nodes.sectionHealth","Health")}),s.jsxs("div",{className:"node-detail-modal__health-row",children:[s.jsxs("span",{children:[x("nodes.healthStatus","Status:")," ",s.jsx("strong",{children:r.status})]}),s.jsxs("span",{children:[x("nodes.healthLastCheck","Last check:")," ",s.jsx("strong",{children:Qo(r.updatedAt)})]})]})]}),k&&s.jsxs("section",{className:"node-detail-modal__section node-detail-modal__docker-config",children:[s.jsxs("button",{className:"btn btn-sm node-detail-modal__docker-toggle",onClick:()=>Oe(F=>!F),"aria-expanded":le,children:[s.jsx(sc,{size:14,className:le?"node-detail-modal__docker-toggle-icon--expanded":""}),x("nodes.dockerConfiguration","Docker Configuration")]}),le&&s.jsxs("div",{className:"node-detail-modal__docker-config-content",children:[s.jsx("div",{className:"node-detail-modal__grid",children:s.jsxs("label",{className:"node-detail-modal__field node-detail-modal__field--full",children:[s.jsx("span",{children:x("nodes.dockerFieldImage","Image")}),s.jsx("input",{className:"input",value:k.image,onChange:F=>$({...k,image:F.target.value})})]})}),s.jsxs("details",{children:[s.jsx("summary",{children:x("nodes.dockerVolumeMounts","Volume Mounts")}),s.jsxs("div",{className:"node-detail-modal__docker-list",children:[k.volumeMounts.map((F,ie)=>s.jsxs("div",{className:"node-detail-modal__docker-row",children:[s.jsx("input",{className:"input",value:F.hostPath,placeholder:x("nodes.dockerHostPath","Host path"),onChange:it=>{const fe=[...k.volumeMounts];fe[ie]={...fe[ie],hostPath:it.target.value},$({...k,volumeMounts:fe})}}),s.jsx("input",{className:"input",value:F.containerPath,placeholder:x("nodes.dockerContainerPath","Container path"),onChange:it=>{const fe=[...k.volumeMounts];fe[ie]={...fe[ie],containerPath:it.target.value},$({...k,volumeMounts:fe})}}),s.jsxs("select",{className:"input",value:F.mode??"rw",onChange:it=>{const fe=[...k.volumeMounts];fe[ie]={...fe[ie],mode:it.target.value},$({...k,volumeMounts:fe})},children:[s.jsx("option",{value:"rw",children:Ra.readWrite}),s.jsx("option",{value:"ro",children:Ra.readOnly})]}),s.jsxs("select",{className:"input",value:F.type??"volume",onChange:it=>{const fe=[...k.volumeMounts];fe[ie]={...fe[ie],type:it.target.value},$({...k,volumeMounts:fe})},children:[s.jsx("option",{value:"volume",children:Ra.volume}),s.jsx("option",{value:"bind",children:Ra.bind})]}),s.jsx("button",{className:"btn btn-sm",onClick:()=>$({...k,volumeMounts:k.volumeMounts.filter((it,fe)=>fe!==ie)}),children:x("nodes.removeButton","Remove")})]},`${F.hostPath}-${F.containerPath}-${ie}`)),s.jsx("button",{className:"btn btn-sm",onClick:()=>$({...k,volumeMounts:[...k.volumeMounts,{hostPath:"",containerPath:"",mode:"rw",type:"volume"}]}),children:x("nodes.addMountButton","Add Mount")})]})]}),s.jsxs("details",{children:[s.jsx("summary",{children:x("nodes.dockerEnvVars","Environment Variables")}),s.jsxs("div",{className:"node-detail-modal__docker-list",children:[Object.entries(k.environment).map(([F,ie])=>{const it=Yx.test(F)&&!de[F];return s.jsxs("div",{className:"node-detail-modal__docker-row",children:[s.jsx("input",{className:"input",value:F,onChange:fe=>{const Ns={...k.environment};delete Ns[F],Ns[fe.target.value]=ie,$({...k,environment:Ns})}}),s.jsx("input",{className:"input",value:it?"***":String(ie),onChange:fe=>$({...k,environment:{...k.environment,[F]:fe.target.value}})}),s.jsx("button",{className:"btn btn-sm",onClick:()=>Le(fe=>({...fe,[F]:!fe[F]})),children:de[F]?s.jsx(Jj,{size:14}):s.jsx(Qj,{size:14})}),s.jsx("button",{className:"btn btn-sm",onClick:()=>{const fe={...k.environment};delete fe[F],$({...k,environment:fe})},children:x("nodes.removeButton","Remove")})]},F)}),s.jsx("button",{className:"btn btn-sm",onClick:()=>{const F=`NEW_VAR_${Object.keys(k.environment).length+1}`;$({...k,environment:{...k.environment,[F]:""}})},children:x("nodes.addVariableButton","Add Variable")})]})]}),s.jsxs("details",{children:[s.jsx("summary",{children:x("nodes.dockerResources","Resources")}),s.jsxs("div",{className:"node-detail-modal__docker-stack",children:[s.jsx("input",{className:"input",type:"number",placeholder:x("nodes.dockerMemoryBytes","Memory bytes (2 GB = 2147483648)"),value:k.resources?.memoryBytes??"",onChange:F=>$({...k,resources:{...k.resources,memoryBytes:F.target.value?Number(F.target.value):void 0}})}),s.jsx("input",{className:"input",type:"number",placeholder:x("nodes.dockerCpuCount","CPU count"),value:k.resources?.cpuCount??"",onChange:F=>$({...k,resources:{...k.resources,cpuCount:F.target.value?Number(F.target.value):void 0}})}),s.jsx("input",{className:"input",type:"number",placeholder:x("nodes.dockerPidsLimit","PIDs limit"),value:k.resources?.pidsLimit??"",onChange:F=>$({...k,resources:{...k.resources,pidsLimit:F.target.value?Number(F.target.value):void 0}})})]})]}),s.jsxs("details",{children:[s.jsx("summary",{children:x("nodes.dockerHostConfig","Host Config")}),s.jsxs("div",{className:"node-detail-modal__docker-stack",children:[s.jsx("input",{className:"input",placeholder:x("nodes.dockerContextName","Context name"),value:k.host?.contextName??"",onChange:F=>$({...k,host:{...k.host,contextName:F.target.value}})}),s.jsx("input",{className:"input",placeholder:x("nodes.dockerHostUrl","Docker host URL"),value:k.host?.dockerHost??"",onChange:F=>$({...k,host:{...k.host,dockerHost:F.target.value}})}),s.jsx("input",{className:"input",placeholder:x("nodes.dockerTlsCaCert","TLS CA cert path"),value:k.host?.tlsCaCert??"",onChange:F=>$({...k,host:{...k.host,tlsCaCert:F.target.value}})}),s.jsx("input",{className:"input",placeholder:x("nodes.dockerTlsCert","TLS cert path"),value:k.host?.tlsCert??"",onChange:F=>$({...k,host:{...k.host,tlsCert:F.target.value}})}),s.jsx("input",{className:"input",placeholder:x("nodes.dockerTlsKey","TLS key path"),value:k.host?.tlsKey??"",onChange:F=>$({...k,host:{...k.host,tlsKey:F.target.value}})}),s.jsxs("label",{className:"node-detail-modal__checkbox",children:[s.jsx("input",{type:"checkbox",checked:k.host?.tlsVerify??!0,onChange:F=>$({...k,host:{...k.host,tlsVerify:F.target.checked}})}),x("nodes.dockerTlsVerify","TLS verify")]})]})]}),s.jsxs("details",{children:[s.jsx("summary",{children:x("nodes.dockerExtraClis","Extra CLIs")}),s.jsxs("div",{className:"node-detail-modal__docker-list",children:[(k.extraClis??[]).map((F,ie)=>s.jsxs("div",{className:"node-detail-modal__docker-row",children:[s.jsx("input",{className:"input",value:F,onChange:it=>{const fe=[...k.extraClis??[]];fe[ie]=it.target.value,$({...k,extraClis:fe})}}),s.jsx("button",{className:"btn btn-sm",onClick:()=>$({...k,extraClis:(k.extraClis??[]).filter((it,fe)=>fe!==ie)}),children:x("nodes.removeButton","Remove")})]},`${F}-${ie}`)),s.jsx("button",{className:"btn btn-sm",onClick:()=>$({...k,extraClis:[...k.extraClis??[],""]}),children:x("nodes.addCliButton","Add CLI")})]})]}),s.jsxs("details",{children:[s.jsx("summary",{children:x("nodes.dockerPersistence","Persistence")}),s.jsxs("div",{className:"node-detail-modal__docker-stack",children:[s.jsx("input",{className:"input",placeholder:x("nodes.dockerVolumeName","Volume name"),value:k.persistence?.volumeName??"",onChange:F=>$({...k,persistence:{...k.persistence,volumeName:F.target.value}})}),s.jsxs("label",{className:"node-detail-modal__checkbox",children:[s.jsx("input",{type:"checkbox",checked:k.persistence?.retainOnDelete??!1,onChange:F=>$({...k,persistence:{...k.persistence,retainOnDelete:F.target.checked}})}),x("nodes.dockerRetainOnDelete","Retain on delete")]})]})]}),s.jsxs("div",{className:"node-detail-modal__docker-meta",children:[s.jsx("span",{children:x("nodes.dockerConfigMeta","Config v{{version}} • Updated {{updated}}",{version:k.configVersion,updated:Xl(k.lastUpdated??r.updatedAt)})}),ks&&s.jsx("span",{className:"node-detail-modal__docker-recreate",children:x("nodes.dockerNeedsRecreate","Needs Recreate")})]}),s.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void tj(),disabled:Nt,children:[s.jsx(Uu,{size:14}),Nt?x("nodes.saving","Saving..."):x("nodes.saveDockerConfig","Save Docker Config")]})]})]}),v&&s.jsxs("section",{className:"node-detail-modal__section docker-management",children:[s.jsx("h4",{children:x("nodes.sectionDockerManagement","Docker Management")}),s.jsxs("div",{className:"docker-management__status-card",children:[s.jsxs("div",{className:"docker-management__status-row",children:[s.jsx("span",{className:`docker-management__status-dot docker-management__status-dot--${nj}`,"aria-hidden":!0}),s.jsx("strong",{children:sr?IF(sr):x("nodes.dockerStatusUnknown","Unknown")}),(sr==="creating"||sr==="recreating"||sr==="restarting")&&s.jsx(qu,{size:14,className:"spin","aria-hidden":!0})]}),s.jsxs("div",{className:"docker-management__status-meta",children:[sr==="running"&&s.jsxs("span",{children:[x("nodes.dockerUptime","Uptime:")," ",_F(oe?.startedAt)]}),sr!=="running"&&oe?.exitCode!==void 0&&s.jsxs("span",{children:[x("nodes.dockerExitCode","Exit code:")," ",oe.exitCode]}),(oe?.error||v.errorMessage)&&s.jsx("span",{children:oe?.error??v.errorMessage})]}),s.jsx("button",{className:"btn btn-sm",onClick:()=>void Jx(),disabled:!b||J,children:J?x("nodes.refreshing","Refreshing..."):x("nodes.refreshStatus","Refresh Status")})]}),s.jsxs("div",{className:"node-detail-modal__grid docker-management__info-grid",children:[s.jsxs("div",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.dockerFieldImage","Image")}),s.jsx("strong",{children:s.jsxs("code",{children:[v.imageName,":",v.imageTag]})})]}),s.jsxs("div",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.dockerContainerId","Container ID")}),s.jsx("strong",{children:s.jsx("code",{children:v.containerId?v.containerId.slice(0,12):"—"})})]}),s.jsxs("div",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.dockerHostLabel","Host")}),s.jsx("strong",{children:Pe})]}),s.jsxs("div",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.dockerPersistentStorage","Persistent Storage")}),s.jsx("strong",{children:v.persistentStorage?x("nodes.yes","Yes"):x("nodes.no","No")})]}),s.jsxs("div",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.dockerPort","Port")}),s.jsx("strong",{children:DF(v.reachableUrl)})]}),s.jsxs("div",{className:"node-detail-modal__field",children:[s.jsx("span",{children:x("nodes.dockerResourceSizing","Resource Sizing")}),s.jsx("strong",{children:Ge})]})]}),s.jsxs("div",{className:"docker-management__actions",children:[s.jsxs("button",{className:"btn btn-sm",disabled:!0,title:x("nodes.availableSoon","Available after FN-3113"),children:[s.jsx(Di,{size:14}),x("nodes.startButton","Start")]}),s.jsxs("button",{className:"btn btn-sm",disabled:!0,title:x("nodes.availableSoon","Available after FN-3113"),children:[s.jsx(Lh,{size:14}),x("nodes.stopButton","Stop")]}),s.jsxs("button",{className:"btn btn-sm",disabled:!0,title:x("nodes.availableSoon","Available after FN-3113"),children:[s.jsx(qu,{size:14}),x("nodes.restartButton","Restart")]}),s.jsxs("button",{className:"btn btn-sm",onClick:()=>void Qx(),disabled:!y,children:[s.jsx(e0,{size:14}),x("nodes.viewLogsButton","View Logs")]})]}),Re&&s.jsxs("div",{className:"docker-management__log-viewer",children:[s.jsxs("div",{className:"docker-management__log-viewer-header",children:[s.jsx("strong",{children:x("nodes.containerLogs","Container Logs")}),s.jsx("button",{className:"btn-icon",onClick:()=>L(!1),"aria-label":x("nodes.closeLogsAriaLabel","Close logs"),children:s.jsx($a,{size:14})})]}),Ne?s.jsx("p",{children:x("nodes.fetchingLogs","Fetching logs...")}):s.jsx("pre",{children:Y.trim()||x("nodes.noLogsAvailable","No logs available")})]}),s.jsxs("details",{children:[s.jsx("summary",{children:x("nodes.dockerEnvVars","Environment Variables")}),s.jsx("dl",{className:"docker-management__env-list",children:Object.entries(v.envVars).map(([F,ie])=>s.jsxs("div",{children:[s.jsx("dt",{children:F}),s.jsx("dd",{children:RF(F,ie)})]},F))})]}),s.jsxs("details",{children:[s.jsx("summary",{children:x("nodes.dockerVolumeMounts","Volume Mounts")}),s.jsx("ul",{className:"docker-management__mounts-list",children:v.volumeMounts.map(F=>s.jsxs("li",{children:[s.jsxs("span",{children:[F.hostPath," → ",F.containerPath]}),F.readOnly&&s.jsx("span",{className:"node-card__type-badge",children:x("nodes.readOnly","Read-only")})]},`${F.hostPath}:${F.containerPath}`))})]})]}),r.type==="remote"&&s.jsxs("section",{className:"node-detail-modal__section",children:[s.jsx("h4",{children:x("nodes.sectionSettingsSync","Settings Sync")}),l&&s.jsxs("div",{className:"node-detail-modal__sync-status",children:[s.jsx("span",{className:`node-detail-modal__sync-dot ${TF(l.syncState)}`,"aria-hidden":!0}),s.jsxs("span",{children:[x("nodes.syncLastSync","Last sync:")," ",s.jsx("strong",{children:l.lastSyncAt?Xl(l.lastSyncAt):x("nodes.syncNeverSynced","Never synced")})]}),l.diffCount>0&&s.jsxs("span",{className:"node-detail-modal__sync-diff",children:[x("nodes.syncDifferences","Differences:")," ",s.jsx("strong",{children:l.diffCount})]})]}),s.jsxs("div",{className:"node-detail-modal__sync-actions",children:[s.jsxs("button",{className:"btn btn-sm",onClick:ya,disabled:B||!c,children:[s.jsx(uc,{size:14}),B?x("nodes.pushing","Pushing..."):x("nodes.pushSettings","Push Settings")]}),s.jsxs("button",{className:"btn btn-sm",onClick:Cn,disabled:K||!d,children:[s.jsx(Ri,{size:14}),K?x("nodes.pulling","Pulling..."):x("nodes.pullSettings","Pull Settings")]}),s.jsxs("button",{className:"btn btn-sm",onClick:Ss,disabled:G||!u,children:[s.jsx(Dh,{size:14}),G?x("nodes.syncing","Syncing..."):x("nodes.syncAuth","Sync Auth")]})]}),q&&s.jsxs("div",{className:"node-detail-modal__sync-error",children:[s.jsx("span",{children:q}),s.jsx("button",{className:"node-detail-modal__sync-error-dismiss",onClick:Zx,"aria-label":x("nodes.dismissError","Dismiss error"),children:s.jsx($a,{size:14})})]})]}),r.type==="remote"&&s.jsxs("section",{className:"node-detail-modal__section",children:[s.jsx("h4",{children:x("nodes.sectionSyncHistory","Sync History")}),s.jsx(AF,{nodeId:r.id,entries:m,singleNode:!0})]})]}),s.jsxs("div",{className:"modal-actions node-detail-modal__actions",children:[s.jsxs("button",{className:"btn btn-sm",onClick:Kr,children:[s.jsx(Rh,{size:14}),x("nodes.healthCheckButton","Health Check")]}),s.jsx("button",{className:"btn btn-sm",onClick:t,children:x("nodes.closeButton","Close")})]})]}),r.type==="remote"&&s.jsx(EF,{isOpen:re,onClose:()=>ae(!1),onResolve:h??(async()=>{}),conflicts:ye,localNodeName:x("nodes.localNodeName","Local"),remoteNodeName:r.name,addToast:o})]})}const $F=15e3,FF=1e3;function BF(){const[e,t]=f.useState([]),[r,n]=f.useState(!0),[a,i]=f.useState(null),o=f.useRef(null),l=f.useRef(0),c=f.useRef(e),d=nc();f.useEffect(()=>{c.current=e},[e]);const u=f.useCallback(b=>c.current.length>0&&ac(b,d.wasRecentlyHidden()),[d]),m=f.useCallback(async()=>{try{i(null);const b=await Wu();t(b)}catch(b){const y=b instanceof Error?b.message:"Failed to fetch managed Docker nodes";u(y)||i(y)}},[u]);f.useEffect(()=>{let b=!1;async function y(){n(!0);try{const j=await Wu();b||(t(j),i(null))}catch(j){const x=j instanceof Error?j.message:"Failed to fetch managed Docker nodes";!b&&!u(x)&&i(x)}finally{b||n(!1)}}y();const g=()=>{if(document.visibilityState!=="visible")return;const j=Date.now(),x=j-l.current;if(x<FF){Wa({view:"useManagedDockerNodes",trigger:"visibility",projectId:void 0,replayAttempted:!1,reason:"debounce-skipped",detail:{timeSinceLastRefreshMs:x}});return}l.current=j,Wa({view:"useManagedDockerNodes",trigger:"visibility",projectId:void 0,replayAttempted:!1,reason:"debounced-refresh"}),m()};return document.addEventListener("visibilitychange",g),()=>{b=!0,document.removeEventListener("visibilitychange",g)}},[m,u]),f.useEffect(()=>{if(!r)return o.current=setInterval(()=>{m()},$F),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[r,m]);const h=f.useCallback(async b=>t0(b),[]),v=f.useCallback(async(b,y)=>(await r0(b,y)).logs,[]),p=f.useCallback(async b=>{const y=await n0(b),g={...y,nodeId:y.nodeId??void 0,containerId:y.containerId??void 0,status:y.status,hostConfig:{type:y.hostConfig.host||y.hostConfig.context?"remote":"local",host:y.hostConfig.host,context:y.hostConfig.context},reachableUrl:y.reachableUrl??void 0,volumeMounts:y.volumeMounts.map(j=>({hostPath:j.hostPath,containerPath:j.containerPath,readOnly:j.mode==="ro"?!0:void 0})),persistentStorage:y.persistentStorage,resourceSizing:{cpuLimit:y.resourceSizing.cpus!==void 0?String(y.resourceSizing.cpus):void 0,memoryLimit:y.resourceSizing.memoryMB!==void 0?`${y.resourceSizing.memoryMB}MB`:void 0},errorMessage:y.errorMessage??void 0};return t(j=>[...j,g]),g},[]);return{dockerNodes:e,loading:r,error:a,refresh:m,getContainerStatus:h,getLogs:v,create:p}}function zF({addToast:e,onClose:t}){const{t:r}=se("app"),{nodes:n,loading:a,error:i,refresh:o,register:l,update:c,unregister:d,healthCheck:u,patchDockerConfig:m,fetchDockerDiff:h,discoverRemoteProjects:v}=Th(),{projects:p,refresh:b}=a0(),{meshState:y,loading:g,error:j}=sF(),{engines:x,loading:C,error:w}=cF(),{syncStatusMap:P,pushSettings:A,pullSettings:S,syncAuth:N,trackNode:E,getAuthSyncState:T,getAuthProviders:O}=nF(),{dockerNodes:I,loading:z,refresh:D,getContainerStatus:V,getLogs:B,create:W}=BF(),[K,te]=f.useState(!1),[G,M]=f.useState(!1),[q,H]=f.useState(null);f.useEffect(()=>{const L=n.filter(Y=>Y.type==="remote");for(const Y of L)E(Y.id)},[n,E]),f.useEffect(()=>{if(!q)return;const L=n.find(Y=>Y.id===q.id)??null;H(L)},[n,q]);const re=f.useMemo(()=>{const L=n.length,Y=n.filter(Oe=>Oe.status==="online").length,ne=n.filter(Oe=>Oe.status==="offline"||Oe.status==="error").length,Ne=n.filter(Oe=>Oe.type==="remote").length,Q=n.filter(Oe=>Oe.type==="remote"&&P[Oe.id]&&Zo(P[Oe.id]).syncState==="synced").length,le=I.length;return{total:L,online:Y,offline:ne,remote:Ne,synced:Q,docker:le}},[I.length,n,P]),ae=f.useCallback(async L=>{await l(L),await b()},[b,l]),ye=f.useCallback(async L=>{try{await W(L),e(r("nodes.dockerNodeCreated",'Docker node "{{name}}" created',{name:L.name}),"success"),M(!1)}catch(Y){const ne=Y instanceof Error?Y.message:r("nodes.failedCreateDocker","Failed to create Docker node");throw e(ne,"error"),Y}},[e,W,r]),oe=f.useMemo(()=>{const L=new Map;for(const Y of I)Y.nodeId&&L.set(Y.nodeId,Y);return L},[I]),He=f.useCallback(async()=>{try{await Promise.all([o(),D()])}catch{e(r("nodes.failedRefresh","Failed to refresh nodes"),"error")}},[e,o,D,r]),J=f.useCallback(async L=>{try{await u(L),e(r("nodes.healthCheckComplete","Node health check complete"),"success")}catch(Y){const ne=Y instanceof Error?Y.message:r("nodes.healthCheckFailed","Health check failed");e(ne,"error")}},[e,u,r]),Ce=f.useCallback(async L=>{try{await d(L),e(r("nodes.removed","Node removed"),"success"),q?.id===L&&H(null)}catch(Y){const ne=Y instanceof Error?Y.message:r("nodes.failedRemove","Failed to remove node");e(ne,"error")}},[e,q?.id,d,r]),Re=f.useCallback(async(L,Y)=>{await c(L,Y)},[c]);return s.jsxs("div",{className:"nodes-view","data-testid":"nodes-view",children:[s.jsxs("div",{className:"nodes-view-header",children:[s.jsxs("div",{className:"nodes-view-title",children:[s.jsxs("h2",{children:[s.jsx(Ih,{size:20}),r("nodes.heading","Nodes")]}),s.jsx("span",{className:"nodes-view-count",children:r("nodes.registeredCount","{{count}} registered",{count:n.length})})]}),s.jsxs("div",{className:"nodes-view-actions",children:[t?s.jsx("button",{className:"btn-icon nodes-view-close",onClick:t,"aria-label":r("nodes.closeAriaLabel","Close nodes view"),children:s.jsx($a,{size:16})}):null,s.jsxs("button",{className:"btn btn-sm",onClick:()=>void He(),disabled:a||z,children:[s.jsx(Gt,{size:14,className:a?"spin":""}),r("nodes.refresh","Refresh")]}),s.jsxs("button",{className:"btn btn-sm",onClick:()=>te(!0),children:[s.jsx(zn,{size:14}),r("nodes.addNode","Add Node")]}),s.jsxs("button",{className:"btn btn-sm",onClick:()=>M(!0),title:r("nodes.addDockerNodeTitle","Add a managed Docker node"),children:[s.jsx(rl,{size:14}),r("nodes.addDockerNode","Add Docker Node")]})]})]}),s.jsxs("div",{className:"nodes-view-stats",children:[s.jsxs("div",{className:"nodes-view-stat","data-testid":"nodes-stat-total",children:[s.jsx("span",{children:r("nodes.total","Total")}),s.jsx("strong",{children:re.total})]}),s.jsxs("div",{className:"nodes-view-stat nodes-view-stat--online","data-testid":"nodes-stat-online",children:[s.jsxs("span",{children:[s.jsx(kw,{size:14})," ",r("nodes.online","Online")]}),s.jsx("strong",{children:re.online})]}),s.jsxs("div",{className:"nodes-view-stat nodes-view-stat--offline","data-testid":"nodes-stat-offline",children:[s.jsxs("span",{children:[s.jsx(ww,{size:14})," ",r("nodes.offline","Offline")]}),s.jsx("strong",{children:re.offline})]}),s.jsxs("div",{className:"nodes-view-stat","data-testid":"nodes-stat-remote",children:[s.jsxs("span",{children:[s.jsx(i0,{size:14})," ",r("nodes.remote","Remote")]}),s.jsx("strong",{children:re.remote})]}),s.jsxs("div",{className:"nodes-view-stat nodes-view-stat--synced","data-testid":"nodes-stat-synced",children:[s.jsxs("span",{children:[s.jsx(Gt,{size:14})," ",r("nodes.synced","Synced")]}),s.jsx("strong",{children:re.synced})]}),s.jsxs("div",{className:"nodes-view-stat","data-testid":"nodes-stat-docker",children:[s.jsxs("span",{children:[s.jsx(rl,{size:14})," ",r("nodes.docker","Docker")]}),s.jsx("strong",{children:re.docker})]})]}),(i||j||w)&&s.jsx("div",{className:"nodes-view-error",children:i??j??w}),!g&&y.length>0&&s.jsxs("section",{className:"nodes-view-topology","aria-label":r("nodes.meshTopologyAriaLabel","Mesh Topology"),children:[s.jsx("h3",{className:"nodes-view-section-title",children:r("nodes.meshTopology","Mesh Topology")}),s.jsx(jF,{nodes:y,engines:C?void 0:x})]}),a?s.jsx("div",{className:"nodes-view-grid",children:Array.from({length:4}).map((L,Y)=>s.jsx("div",{className:"node-card node-card--loading","aria-hidden":!0},Y))}):n.length===0?s.jsxs("div",{className:"nodes-view-empty",children:[s.jsx("p",{children:r("nodes.noRegistered","No nodes are registered yet.")}),s.jsxs("button",{className:"btn btn-primary",onClick:()=>te(!0),children:[s.jsx(zn,{size:14}),r("nodes.addFirstNode","Add First Node")]})]}):s.jsx("div",{className:"nodes-view-grid",children:n.map(L=>{const Y=L.type==="remote"&&P[L.id]?Zo(P[L.id]):void 0;return s.jsx(pF,{node:L,projects:p,onHealthCheck:ne=>{J(ne)},onEdit:ne=>H(ne),onRemove:ne=>{Ce(ne)},isLoading:a,syncStatus:Y,authSyncState:L.type==="remote"?T(L.id):void 0,authSyncProviders:L.type==="remote"?O(L.id):void 0,managedDockerNode:oe.get(L.id)},L.id)})}),s.jsx(CF,{isOpen:K,onClose:()=>te(!1),onSubmit:ae,onDiscoverRemoteProjects:v,addToast:e,projects:p}),s.jsx(PF,{isOpen:G,onClose:()=>M(!1),onSubmit:ye,addToast:e}),s.jsx(LF,{isOpen:q!==null,onClose:()=>H(null),node:q,projects:p,onUpdate:Re,onHealthCheck:J,addToast:e,syncStatus:q?.type==="remote"&&q&&P[q.id]?Zo(P[q.id]):void 0,onPushSettings:A,onPullSettings:S,onSyncAuth:N,managedDockerNode:q?oe.get(q.id):void 0,onFetchContainerStatus:V,onFetchLogs:B,onUpdateDockerConfig:m,onFetchDockerConfigDiff:h})]})}function KF(){const{t:e}=se("app");return t=>{switch(t){case"triage":return e("commandCenter.funnel.stage.triage","Planning");case"todo":return e("commandCenter.funnel.stage.todo","Todo");case"in-progress":return e("commandCenter.funnel.stage.inProgress","In progress");case"in-review":return e("commandCenter.funnel.stage.inReview","In review");case"done":return e("commandCenter.funnel.stage.done","Done");case"other":return e("commandCenter.funnel.stage.other","Other");default:return t}}}function VF(e){return Number.isFinite(e)?e.toFixed(2):"—"}function UF({range:e,projectId:t}){const{t:r}=se("app"),n=KF(),{data:a,isLoading:i,error:o}=Je("/command-center/activity",e,{projectId:t}),l=a?.funnel??null,c=f.useMemo(()=>(l?.stages??[]).map(u=>({label:n(u.stage),value:u.entered})),[l?.stages,n]),d=!l||l.stages.every(u=>u.entered===0);return s.jsxs(ft,{testId:"funnel",isLoading:i,error:o,isEmpty:d,emptyMessage:r("commandCenter.funnel.empty","No task transitions in the selected range."),children:[s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.funnel.title","SDLC funnel")}),s.jsx(qx,{stages:c,ariaLabel:r("commandCenter.funnel.ariaLabel","Tasks per workflow stage")})]}),s.jsxs("div",{className:"cc-area-section",children:[s.jsx("h3",{className:"cc-area-section-title",children:r("commandCenter.funnel.throughputTitle","Throughput")}),s.jsxs("div",{className:"cc-stat-grid",children:[s.jsxs("div",{className:"card cc-stat-card cc-stat-card--gauge","data-testid":"cc-funnel-completion-rate",children:[s.jsx(Ua,{value:l?.completionRate??null,label:r("commandCenter.funnel.completionRate","Completion rate"),ariaLabel:r("commandCenter.funnel.completionRateAria","Completion rate for in-range planning entrants")}),s.jsx("span",{className:"cc-stat-sub",children:r("commandCenter.funnel.completionRateHint","Done ÷ entered (in range)")})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-funnel-throughput",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.funnel.throughputPerDay","Tasks done / day")}),s.jsx("div",{className:"cc-stat-value",children:VF(l?.throughputPerDay??0)}),s.jsx("span",{className:"cc-stat-sub",children:r("commandCenter.funnel.rangeDays","{{count}} day range",{count:l?.rangeDays??0})})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-funnel-done",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.funnel.doneInRange","Reached done")}),s.jsx("div",{className:"cc-stat-value",children:U(l?.doneInRange??0)})]}),s.jsxs("div",{className:"card cc-stat-card","data-testid":"cc-funnel-entered",children:[s.jsx("div",{className:"cc-stat-label",children:r("commandCenter.funnel.enteredInRange","Entered planning")}),s.jsx("div",{className:"cc-stat-value",children:U(l?.enteredInRange??0)})]})]})]})]})}const qF=8;function WF(e){const{t}=se("app");return[{id:"overview",label:t("commandCenter.tabs.overview","Overview")},{id:"tokens",label:t("commandCenter.tabs.tokens","Tokens")},{id:"tools",label:t("commandCenter.tabs.tools","Tools")},{id:"activity",label:t("commandCenter.tabs.activity","Activity")},{id:"agent-activity",label:t("commandCenter.tabs.agentActivity","Agent Activity")},{id:"productivity",label:t("commandCenter.tabs.productivity","Productivity")},{id:"review-artifacts",label:t("commandCenter.tabs.reviewArtifacts","Review artifacts")},{id:"team",label:t("commandCenter.tabs.team","Team")},{id:"workflows",label:t("commandCenter.tabs.workflows","Workflows")},{id:"ecosystem",label:t("commandCenter.tabs.ecosystem","Ecosystem")},{id:"github",label:t("commandCenter.tabs.github","GitHub")},{id:"gitlab",label:t("commandCenter.tabs.gitlab","GitLab")},{id:"signals",label:t("commandCenter.tabs.signals","Signals")},{id:"system",label:t("commandCenter.tabs.system","System")},{id:"plugins",label:t("commandCenter.tabs.plugins","Plugins")},...e?[{id:"nodes",label:t("commandCenter.tabs.nodes","Nodes")}]:[],{id:"reliability",label:t("commandCenter.tabs.reliability","Reliability")},{id:"mission-control",label:t("commandCenter.tabs.missionControl","Mission Control")}]}const Sh=15e3;function HF({range:e,projectId:t,colorTheme:r="default",themeMode:n="system",shadcnCustomColors:a={},resolvedThemeMode:i=n==="light"?"light":"dark",onColorThemeChange:o=()=>{},onThemeModeChange:l=()=>{},onShadcnCustomColorsChange:c=()=>{},onChangeView:d}){const{t:u}=se("app"),m=Je("/command-center/tokens?groupBy=model",e,{pollMs:Sh,projectId:t}),h=Je("/command-center/tools",e,{projectId:t}),v=Je("/command-center/activity",e,{projectId:t}),p=Je("/command-center/signals",e,{projectId:t}),{snapshot:b,isLoading:y}=Hx(t),[g,j]=f.useState(null),[x,C]=f.useState([]),w=f.useRef(0),P=f.useCallback(()=>{const Q=w.current,le=()=>w.current!==Q;fr(mr("/command-center/verification-requests",t)).then(Oe=>{le()||C(Oe.requests)}).catch(()=>{le()||C([])})},[t]);f.useEffect(()=>(P(),()=>{w.current+=1}),[P]),vn(P,Sh),f.useEffect(()=>{let Q=!1;return j(null),t?(o0(t).then(le=>{Q||j(le)},()=>{Q||j(null)}),()=>{Q=!0}):()=>{Q=!0}},[t]);const A=m.data?.totals?.totalTokens??0,S=h.data?.toolCalls??0,N=v.data?.activeNodes??0,E=v.data?.activeAgents??0,T=F2(b),O=v.data?.sessions??0,I=v.data?.agentRuns?.total??0,z=v.data?.funnel?.doneInRange??0,D=$2(b?.columns),V=m.data?.groups?.length??0,B=f.useMemo(()=>[...m.data?.groups??[]].sort((Q,le)=>le.totalTokens-Q.totalTokens||(Q.key??"").localeCompare(le.key??"")).slice(0,qF).map(Q=>({label:Q.key??u("commandCenter.tokens.unknownModel","(unknown)"),value:Q.totalTokens,valueLabel:U(Q.totalTokens),iconProvider:ec(Q.key??"")})),[m.data?.groups,u]),W=f.useMemo(()=>[...h.data?.byCategory??[]].sort((Q,le)=>le.count-Q.count||Q.category.localeCompare(le.category)).map(Q=>({label:Q.category,value:Q.count,valueLabel:U(Q.count)})),[h.data?.byCategory]),K=f.useMemo(()=>B.map(Q=>({label:Q.label,value:Q.value})),[B]),te=f.useMemo(()=>(v.data?.daily??[]).map(Q=>Q.messages+Q.activeAgents+(Q.agentRuns??0)),[v.data?.daily]),G=f.useMemo(()=>[{label:u("commandCenter.activity.messages","Messages"),values:(v.data?.daily??[]).map(Q=>Q.messages)},{label:u("commandCenter.activity.activeAgents","Active agents"),values:(v.data?.daily??[]).map(Q=>Q.activeAgents)},{label:u("commandCenter.activity.agentRuns","Agent runs"),values:(v.data?.daily??[]).map(Q=>Q.agentRuns)}],[v.data?.daily,u]),M=te.length>0?te:[O,v.data?.messages??0,E,N,z],q=B.length>0||W.length>0||te.length>0,H=O>0||(v.data?.messages??0)>0||N>0||E>0||I>0||z>0,re=A>0||S>0||H,ye=!(m.data!==null&&h.data!==null&&v.data!==null)&&(m.isLoading||h.isLoading||v.isLoading),oe=m.error??h.error??v.error,He=m.data?Tr(m.data.cost?.usd??null,m.data.cost?.unavailable??!0):"—",J=h.data?h.data.fullyAutonomous?u("commandCenter.tools.ratioAutonomous","{{ratio}} calls/session (fully autonomous)",{ratio:h.data.autonomyRatio.toFixed(1)}):`${h.data.autonomyRatio.toFixed(1)}:1`:"—",Ce=[{id:"codebaseTokens",testId:"cc-overview-codebase-tokens",label:u("commandCenter.overview.codebaseTokens","Codebase tokens"),value:g?U(g.tokenEstimate):"—",subLabel:g?.truncated?u("commandCenter.overview.metricsPartial","Approx. (partial)"):g?u("commandCenter.overview.codebaseTokensHint","Local estimate calibrated to cl100k_base"):void 0},{id:"diskSize",testId:"cc-overview-disk-size",label:u("commandCenter.overview.diskSize","Disk size"),value:g?ct(g.diskBytes):"—",subLabel:g?.truncated?u("commandCenter.overview.metricsPartial","Approx. (partial)"):g?u("commandCenter.overview.diskSizeHint","Apparent local size"):void 0}],Re=Q=>s.jsx("div",{className:"cc-stat-grid",children:Q.map(le=>s.jsxs("div",{className:"card cc-stat-card","data-testid":le.testId??`command-center-stat-${le.id}`,children:[s.jsx("div",{className:"cc-stat-label",children:le.label}),s.jsx("div",{className:`cc-stat-value ${le.id==="tokens"?"cc-token-count-live":""}`,children:le.value},le.value),le.subLabel?s.jsx("span",{className:"cc-stat-sub",children:le.subLabel}):null]},le.id))}),L=[{id:"tokens",label:u("commandCenter.overview.tokensCost","Tokens & cost"),value:U(A),subLabel:He},{id:"autonomy",label:u("commandCenter.overview.autonomy","Autonomy ratio"),value:J},{id:"agentRuns",label:u("commandCenter.overview.agentRuns","Agent runs"),value:U(I)},{id:"tasksDone",label:u("commandCenter.overview.tasksDone","Tasks done"),value:U(z)},{id:"models",label:u("commandCenter.overview.uniqueModels","Unique models"),value:U(V)},{id:"signals",label:u("commandCenter.overview.openSignals","Open signals"),value:p.isLoading?"—":p.data?U(p.data.open??0):"—"}],Y=s.jsx(Q2,{projectId:t,colorTheme:r,themeMode:n,shadcnCustomColors:a,resolvedThemeMode:i,onColorThemeChange:o,onThemeModeChange:l,onShadcnCustomColorsChange:c,onChangeView:d}),ne=s.jsx("div",{className:"cc-overview-throughput","data-testid":"command-center-throughput",children:s.jsx(UF,{range:e,projectId:t})}),Ne=x.length>0?s.jsxs("section",{className:"cc-verification-requests card","data-testid":"command-center-verification-requests",children:[s.jsxs("div",{className:"cc-overview-chart-header",children:[s.jsx("h3",{className:"cc-area-section-title",children:u("commandCenter.taskVerification","Task verification")}),s.jsx("p",{children:u("commandCenter.verificationRequests","Latest executor-owned verification requests")})]}),x.map(Q=>s.jsxs("div",{className:"cc-verification-requests__item",children:[s.jsx("span",{className:"cc-verification-requests__task",children:Q.taskId}),s.jsx(l0,{request:Q,compact:!0})]},Q.requestId))]}):null;return ye?s.jsxs("div",{className:"cc-overview",children:[Y,Re(Ce),s.jsxs("div",{className:"cc-loading","data-testid":"command-center-overview-loading",children:[s.jsx("div",{className:"cc-chart-skeleton"}),s.jsx("p",{children:s.jsx(rc,{label:u("commandCenter.loading","Loading dashboard...")})})]}),Ne,ne]}):oe!==null&&!re?s.jsxs("div",{className:"cc-overview",children:[Y,Re(Ce),s.jsxs("div",{className:"cc-error","data-testid":"command-center-overview-error",role:"alert",children:[s.jsx(Mi,{size:24}),s.jsx("p",{children:oe})]}),Ne,ne]}):re?s.jsxs("div",{className:"cc-overview",children:[Y,Re([...Ce,...L]),s.jsxs("div",{className:"cc-live-strip","data-testid":"command-center-live-strip",children:[s.jsxs("div",{className:"cc-live-strip-heading",children:[s.jsx("span",{className:"status-dot status-dot--connecting","aria-hidden":"true"}),s.jsx("span",{className:"cc-live-strip-label",children:u("commandCenter.overview.liveStrip","Live activity snapshot")})]}),s.jsxs("div",{className:"cc-live-strip-metrics","data-testid":"command-center-live-snapshot",children:[s.jsxs("span",{className:"cc-live-metric","data-testid":"command-center-live-tasks-in-progress",children:[s.jsx("span",{className:"cc-live-metric-value",children:y?"—":U(D)}),s.jsx("span",{className:"cc-live-metric-label",children:u("commandCenter.overview.tasksInProgress","tasks in progress")})]}),s.jsxs("span",{className:"cc-live-metric","data-testid":"command-center-live-agents-working",children:[s.jsx("span",{className:"cc-live-metric-value",children:y?"—":U(T)}),s.jsx("span",{className:"cc-live-metric-label",children:u("commandCenter.overview.agentsWorking","agents working")})]}),s.jsxs("span",{className:"cc-live-metric","data-testid":"command-center-live-tokens",children:[s.jsx("span",{className:"cc-live-metric-value cc-token-count-live",children:U(A)},A),s.jsx("span",{className:"cc-live-metric-label",children:u("commandCenter.overview.liveTokens","tokens")})]}),s.jsxs("span",{className:"cc-live-metric","data-testid":"command-center-live-open-signals",children:[s.jsx("span",{className:"cc-live-metric-value",children:p.isLoading?"—":p.data?U(p.data.open??0):"—"}),s.jsx("span",{className:"cc-live-metric-label",children:u("commandCenter.overview.openSignals","open signals")})]})]}),s.jsxs("div",{className:"cc-live-trend","data-testid":"command-center-throughput-trend",children:[s.jsx("span",{className:"cc-live-trend-label",children:u("commandCenter.overview.throughputTrend","throughput trend")}),s.jsx(Ot,{values:M,ariaLabel:u("commandCenter.overview.throughputTrendAria","Recent activity throughput trend")})]})]}),Ne,q?s.jsxs("section",{className:"cc-overview-charts","data-testid":"command-center-overview-charts",children:[B.length>0?s.jsxs("div",{className:"card cc-overview-chart-card","data-testid":"command-center-overview-chart-tokens",children:[s.jsxs("div",{className:"cc-overview-chart-header",children:[s.jsx("h3",{className:"cc-area-section-title",children:u("commandCenter.overview.tokensByModel","Tokens by model")}),s.jsx("p",{children:u("commandCenter.overview.tokensByModelHint","Top model token consumers in this range")})]}),s.jsx(nt,{data:B,ariaLabel:u("commandCenter.overview.tokensByModel","Tokens by model")})]}):null,K.length>0?s.jsxs("div",{className:"card cc-overview-chart-card","data-testid":"cc-overview-pie",children:[s.jsxs("div",{className:"cc-overview-chart-header",children:[s.jsx("h3",{className:"cc-area-section-title",children:u("commandCenter.overview.tokensByModelPie","Token share by model")}),s.jsx("p",{children:u("commandCenter.overview.tokensByModelPieHint","Top model token share in this range")})]}),s.jsx(Mt,{data:K,ariaLabel:u("commandCenter.overview.tokensByModelPie","Token share by model")})]}):null,W.length>0?s.jsxs("div",{className:"card cc-overview-chart-card","data-testid":"command-center-overview-chart-tools",children:[s.jsxs("div",{className:"cc-overview-chart-header",children:[s.jsx("h3",{className:"cc-area-section-title",children:u("commandCenter.overview.toolCategories","Tool categories")}),s.jsx("p",{children:u("commandCenter.overview.toolCategoriesHint","Autonomous work grouped by tool family")})]}),s.jsx(nt,{data:W,ariaLabel:u("commandCenter.overview.toolCategories","Tool categories")})]}):null,te.length>0?s.jsxs("div",{className:"card cc-overview-chart-card cc-overview-chart-card--trend","data-testid":"cc-overview-line",children:[s.jsxs("div",{className:"cc-overview-chart-header",children:[s.jsx("h3",{className:"cc-area-section-title",children:u("commandCenter.overview.dailyActivityLine","Daily activity line")}),s.jsx("p",{children:u("commandCenter.overview.dailyActivityLineHint","Messages, agents, and runs by day")})]}),s.jsx(br,{series:G,ariaLabel:u("commandCenter.overview.dailyActivityLine","Daily activity line")})]}):null,te.length>0?s.jsxs("div",{className:"card cc-overview-chart-card cc-overview-chart-card--trend","data-testid":"command-center-overview-chart-activity",children:[s.jsxs("div",{className:"cc-overview-chart-header",children:[s.jsx("h3",{className:"cc-area-section-title",children:u("commandCenter.overview.dailyActivity","Daily activity trend")}),s.jsx("p",{children:u("commandCenter.overview.dailyActivityHint","Messages plus active agents per day")})]}),s.jsx(Ot,{values:te,ariaLabel:u("commandCenter.overview.dailyActivityAria","Daily activity trend")})]}):null]}):null,ne]}):s.jsxs("div",{className:"cc-overview",children:[Y,Re(Ce),s.jsxs("div",{className:"cc-empty","data-testid":"command-center-empty",children:[s.jsx(Ii,{size:28}),s.jsx("p",{children:u("commandCenter.empty","No usage data yet. Run some agents to populate the Dashboard.")})]}),Ne,ne]})}function GF({tabId:e}){const{t}=se("app");return s.jsxs("div",{className:"cc-empty","data-testid":`command-center-placeholder-${e}`,children:[s.jsx(Ii,{size:28}),s.jsx("p",{children:t("commandCenter.areaPending","This area renders once metrics data is available.")})]})}function RB({projectId:e,colorTheme:t="default",themeMode:r="system",shadcnCustomColors:n={},resolvedThemeMode:a=r==="light"?"light":"dark",onColorThemeChange:i=()=>{},onThemeModeChange:o=()=>{},onShadcnCustomColorsChange:l=()=>{},addToast:c=()=>{},nodesEnabled:d=!1,onChangeView:u,onOpenAgent:m,onOpenTask:h}={}){const{t:v}=se("app"),p=WF(d),[b,y]=f.useState(()=>Os(e)?.activeTab??"overview"),[g,j]=f.useState(()=>Os(e)?.range??cl(ll((S,N)=>N)[1])),x=f.useRef(e);f.useEffect(()=>{if(x.current===e)return;x.current=e;const S=Os(e);y(S?.activeTab??"overview"),j(S?.range??cl(ll((N,E)=>E)[1]))},[e]),f.useEffect(()=>{x.current===e&&s0({activeTab:b,range:g},e)},[b,e,g]),f.useEffect(()=>{p.some(S=>S.id===b)||y("overview")},[b,p]);const C=f.useRef([]),w=f.useCallback(S=>{const N=(S+p.length)%p.length;y(p[N].id),C.current[N]?.focus()},[p]),P=f.useCallback((S,N)=>{switch(S.key){case"ArrowRight":case"ArrowDown":S.preventDefault(),w(N+1);break;case"ArrowLeft":case"ArrowUp":S.preventDefault(),w(N-1);break;case"Home":S.preventDefault(),w(0);break;case"End":S.preventDefault(),w(p.length-1);break;case"Enter":case" ":S.preventDefault(),y(p[N].id);break}},[w,p]);function A(){switch(b){case"overview":return s.jsx(HF,{range:g,projectId:e,colorTheme:t,themeMode:r,shadcnCustomColors:n,resolvedThemeMode:a,onColorThemeChange:i,onThemeModeChange:o,onShadcnCustomColorsChange:l,onChangeView:u});case"tokens":return s.jsx(v$,{range:g,projectId:e});case"tools":return s.jsx(h$,{range:g,projectId:e});case"activity":return s.jsx(A$,{range:g,projectId:e});case"agent-activity":return s.jsx(G$,{projectId:e,range:g,onOpenAgent:m,onOpenTask:h});case"productivity":return s.jsx(Y$,{range:g,projectId:e});case"review-artifacts":return s.jsx(Z$,{projectId:e,addToast:c});case"team":return s.jsx(o2,{range:g,projectId:e,addToast:c});case"workflows":return s.jsx(c2,{range:g,projectId:e});case"ecosystem":return s.jsx(u2,{range:g,projectId:e});case"github":return s.jsx(m2,{range:g,projectId:e});case"gitlab":return s.jsx(h2,{range:g,projectId:e});case"signals":return s.jsx(p2,{range:g,projectId:e});case"system":return s.jsxs("div",{className:"cc-system-tab","data-testid":"cc-system-tab",children:[s.jsx(D2,{projectId:e,addToast:c}),s.jsx(A2,{})]});case"plugins":return s.jsx(aw,{addToast:c??(()=>{}),projectId:e});case"nodes":return s.jsx(zF,{addToast:c});case"reliability":return s.jsx(eF,{projectId:e});case"mission-control":return s.jsx(H2,{projectId:e});default:return s.jsx(GF,{tabId:b})}}return s.jsxs("section",{className:"command-center","data-testid":"command-center",children:[s.jsxs("header",{className:"cc-header",children:[s.jsxs("h2",{className:"cc-title",children:[s.jsx(Ii,{size:20}),v("commandCenter.heading","Dashboard")]}),s.jsx(aC,{value:g,onChange:j})]}),s.jsx("div",{className:"cc-tablist",role:"tablist","aria-label":v("commandCenter.tablistLabel","Dashboard sections"),children:p.map((S,N)=>{const E=S.id===b;return s.jsx("button",{ref:T=>{C.current[N]=T},role:"tab",id:`cc-tab-${S.id}`,"aria-selected":E,"aria-controls":`cc-tabpanel-${S.id}`,tabIndex:E?0:-1,className:`cc-tab${E?" active":""}`,onClick:()=>y(S.id),onKeyDown:T=>P(T,N),"data-testid":`command-center-tab-${S.id}`,children:S.label},S.id)})}),s.jsx("div",{role:"tabpanel",id:`cc-tabpanel-${b}`,"aria-labelledby":`cc-tab-${b}`,tabIndex:0,className:"cc-tabpanel","data-testid":`command-center-panel-${b}`,children:A()})]})}export{RB as CommandCenter};