@pennyfarthing/core 11.0.0 → 11.1.1

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 (401) hide show
  1. package/README.md +81 -23
  2. package/package.json +1 -1
  3. package/packages/core/dist/cli/utils/010-detect-remove-old-packages.test.d.ts +20 -0
  4. package/packages/core/dist/cli/utils/010-detect-remove-old-packages.test.d.ts.map +1 -0
  5. package/packages/core/dist/cli/utils/010-detect-remove-old-packages.test.js +278 -0
  6. package/packages/core/dist/cli/utils/010-detect-remove-old-packages.test.js.map +1 -0
  7. package/packages/core/dist/cli/utils/constants.d.ts +8 -2
  8. package/packages/core/dist/cli/utils/constants.d.ts.map +1 -1
  9. package/packages/core/dist/cli/utils/constants.js +4 -1
  10. package/packages/core/dist/cli/utils/constants.js.map +1 -1
  11. package/packages/core/dist/cli/utils/constants.test.d.ts +10 -0
  12. package/packages/core/dist/cli/utils/constants.test.d.ts.map +1 -0
  13. package/packages/core/dist/cli/utils/constants.test.js +38 -0
  14. package/packages/core/dist/cli/utils/constants.test.js.map +1 -0
  15. package/packages/core/dist/consultation/consultation-protocol.d.ts +139 -0
  16. package/packages/core/dist/consultation/consultation-protocol.d.ts.map +1 -0
  17. package/packages/core/dist/consultation/consultation-protocol.js +178 -0
  18. package/packages/core/dist/consultation/consultation-protocol.js.map +1 -0
  19. package/packages/core/dist/consultation/consultation-protocol.test.d.ts +20 -0
  20. package/packages/core/dist/consultation/consultation-protocol.test.d.ts.map +1 -0
  21. package/packages/core/dist/consultation/consultation-protocol.test.js +474 -0
  22. package/packages/core/dist/consultation/consultation-protocol.test.js.map +1 -0
  23. package/packages/core/dist/consultation/dialogue-manager.d.ts +75 -0
  24. package/packages/core/dist/consultation/dialogue-manager.d.ts.map +1 -0
  25. package/packages/core/dist/consultation/dialogue-manager.js +334 -0
  26. package/packages/core/dist/consultation/dialogue-manager.js.map +1 -0
  27. package/packages/core/dist/consultation/dialogue-manager.test.d.ts +19 -0
  28. package/packages/core/dist/consultation/dialogue-manager.test.d.ts.map +1 -0
  29. package/packages/core/dist/consultation/dialogue-manager.test.js +444 -0
  30. package/packages/core/dist/consultation/dialogue-manager.test.js.map +1 -0
  31. package/packages/core/dist/public/js/react/react.js +3 -3
  32. package/packages/core/dist/scripts/theme-detail.test.d.ts +10 -0
  33. package/packages/core/dist/scripts/theme-detail.test.js +199 -0
  34. package/packages/core/dist/server/api/git.d.ts +13 -1
  35. package/packages/core/dist/server/api/git.d.ts.map +1 -1
  36. package/packages/core/dist/server/api/git.js +53 -34
  37. package/packages/core/dist/server/api/git.js.map +1 -1
  38. package/packages/core/dist/server/api/health-score.d.ts.map +1 -1
  39. package/packages/core/dist/server/api/health-score.js +25 -1
  40. package/packages/core/dist/server/api/health-score.js.map +1 -1
  41. package/packages/core/dist/server/api/settings.d.ts.map +1 -1
  42. package/packages/core/dist/server/api/settings.js +63 -1
  43. package/packages/core/dist/server/api/settings.js.map +1 -1
  44. package/packages/core/dist/server/api/theme-agents.d.ts.map +1 -1
  45. package/packages/core/dist/server/api/theme-agents.js +61 -0
  46. package/packages/core/dist/server/api/theme-agents.js.map +1 -1
  47. package/packages/core/dist/server/server.d.ts.map +1 -1
  48. package/packages/core/dist/server/server.js +17 -12
  49. package/packages/core/dist/server/server.js.map +1 -1
  50. package/packages/core/dist/shared/skill-search.test.js +2 -2
  51. package/packages/core/dist/workflow/gate-file-validation.d.ts +49 -0
  52. package/packages/core/dist/workflow/gate-file-validation.d.ts.map +1 -0
  53. package/packages/core/dist/workflow/gate-file-validation.js +157 -0
  54. package/packages/core/dist/workflow/gate-file-validation.js.map +1 -0
  55. package/packages/core/dist/workflow/gate-file-validation.test.d.ts +19 -0
  56. package/packages/core/dist/workflow/gate-file-validation.test.d.ts.map +1 -0
  57. package/packages/core/dist/workflow/gate-file-validation.test.js +536 -0
  58. package/packages/core/dist/workflow/gate-file-validation.test.js.map +1 -0
  59. package/packages/core/dist/workflow/gate-schema-validation.test.d.ts +14 -0
  60. package/packages/core/dist/workflow/gate-schema-validation.test.d.ts.map +1 -0
  61. package/packages/core/dist/workflow/gate-schema-validation.test.js +339 -0
  62. package/packages/core/dist/workflow/gate-schema-validation.test.js.map +1 -0
  63. package/packages/core/dist/workflow/handoff.js +2 -2
  64. package/packages/core/dist/workflow/handoff.js.map +1 -1
  65. package/packages/core/dist/workflow/handoff.test.js +16 -0
  66. package/packages/core/dist/workflow/handoff.test.js.map +1 -1
  67. package/packages/core/dist/workflow/workflow-schema.d.ts +4 -2
  68. package/packages/core/dist/workflow/workflow-schema.d.ts.map +1 -1
  69. package/packages/core/dist/workflow/workflow-schema.js +43 -8
  70. package/packages/core/dist/workflow/workflow-schema.js.map +1 -1
  71. package/pennyfarthing-dist/agents/README.md +6 -14
  72. package/pennyfarthing-dist/agents/architect.md +43 -29
  73. package/pennyfarthing-dist/agents/ba.md +30 -29
  74. package/pennyfarthing-dist/agents/dev.md +32 -43
  75. package/pennyfarthing-dist/agents/devops.md +57 -21
  76. package/pennyfarthing-dist/agents/orchestrator.md +3 -10
  77. package/pennyfarthing-dist/agents/pm.md +45 -31
  78. package/pennyfarthing-dist/agents/reviewer.md +20 -66
  79. package/pennyfarthing-dist/agents/sm-setup.md +2 -2
  80. package/pennyfarthing-dist/agents/sm.md +8 -30
  81. package/pennyfarthing-dist/agents/tea.md +25 -41
  82. package/pennyfarthing-dist/agents/tech-writer.md +33 -90
  83. package/pennyfarthing-dist/agents/ux-designer.md +39 -39
  84. package/pennyfarthing-dist/commands/benchmark-control.md +8 -64
  85. package/pennyfarthing-dist/commands/benchmark.md +8 -480
  86. package/pennyfarthing-dist/commands/job-fair.md +8 -97
  87. package/pennyfarthing-dist/commands/pf-benchmark-control.md +70 -0
  88. package/pennyfarthing-dist/commands/pf-benchmark.md +486 -0
  89. package/pennyfarthing-dist/commands/pf-chore.md +4 -4
  90. package/pennyfarthing-dist/commands/pf-ci.md +40 -0
  91. package/pennyfarthing-dist/commands/pf-close-epic.md +9 -27
  92. package/pennyfarthing-dist/commands/pf-continue-session.md +9 -213
  93. package/pennyfarthing-dist/commands/pf-create-branches-from-story.md +11 -353
  94. package/pennyfarthing-dist/commands/pf-docs.md +28 -0
  95. package/pennyfarthing-dist/commands/pf-epic.md +67 -0
  96. package/pennyfarthing-dist/commands/pf-git-cleanup.md +11 -52
  97. package/pennyfarthing-dist/commands/pf-git.md +75 -0
  98. package/pennyfarthing-dist/commands/pf-help.md +110 -128
  99. package/pennyfarthing-dist/commands/pf-job-fair.md +102 -0
  100. package/pennyfarthing-dist/commands/pf-new-work.md +9 -18
  101. package/pennyfarthing-dist/commands/pf-parallel-work.md +6 -66
  102. package/pennyfarthing-dist/commands/pf-release.md +11 -76
  103. package/pennyfarthing-dist/commands/pf-repo-status.md +11 -44
  104. package/pennyfarthing-dist/commands/pf-run-ci.md +8 -111
  105. package/pennyfarthing-dist/commands/pf-session.md +51 -0
  106. package/pennyfarthing-dist/commands/pf-solo.md +447 -0
  107. package/pennyfarthing-dist/commands/pf-sprint-planning.md +8 -104
  108. package/pennyfarthing-dist/commands/pf-standalone.md +1 -1
  109. package/pennyfarthing-dist/commands/pf-start-epic.md +9 -163
  110. package/pennyfarthing-dist/commands/pf-sync-epic-to-jira.md +8 -179
  111. package/pennyfarthing-dist/commands/pf-sync-work-with-sprint.md +8 -368
  112. package/pennyfarthing-dist/commands/pf-update-domain-docs.md +8 -78
  113. package/pennyfarthing-dist/commands/solo.md +8 -442
  114. package/pennyfarthing-dist/guides/agent-behavior.md +13 -13
  115. package/pennyfarthing-dist/guides/agent-coordination.md +7 -7
  116. package/pennyfarthing-dist/guides/agent-tag-taxonomy.md +6 -5
  117. package/pennyfarthing-dist/guides/bikerack.md +128 -0
  118. package/pennyfarthing-dist/guides/brownfield-tools.md +133 -0
  119. package/pennyfarthing-dist/guides/command-tag-taxonomy.md +2 -2
  120. package/pennyfarthing-dist/guides/gate-schema.md +227 -0
  121. package/pennyfarthing-dist/guides/gates.md +120 -0
  122. package/pennyfarthing-dist/guides/handoff-cli.md +116 -0
  123. package/pennyfarthing-dist/guides/hooks.md +86 -4
  124. package/pennyfarthing-dist/guides/output-styles.md +65 -0
  125. package/pennyfarthing-dist/guides/patterns/approval-gates-pattern.md +5 -5
  126. package/pennyfarthing-dist/guides/patterns/tdd-flow-pattern.md +4 -4
  127. package/pennyfarthing-dist/guides/prompt-patterns.md +5 -5
  128. package/pennyfarthing-dist/guides/reflector.md +4 -4
  129. package/pennyfarthing-dist/guides/session-artifacts.md +1 -1
  130. package/pennyfarthing-dist/guides/skill-schema.md +1 -1
  131. package/pennyfarthing-dist/guides/tandem-protocol.md +13 -1
  132. package/pennyfarthing-dist/guides/worktree-mode.md +3 -3
  133. package/pennyfarthing-dist/guides/xml-tags.md +5 -4
  134. package/pennyfarthing-dist/personas/themes/hogans-heroes.yaml +11 -22
  135. package/pennyfarthing-dist/personas/themes/stephen-king.yaml +13 -24
  136. package/pennyfarthing-dist/scripts/core/dialogue-manager.sh +322 -0
  137. package/pennyfarthing-dist/scripts/core/phase-check-start.sh +1 -1
  138. package/pennyfarthing-dist/scripts/hooks/otel-auto-config.sh +19 -14
  139. package/pennyfarthing-dist/scripts/portraits/generate-portraits.py +191 -57
  140. package/pennyfarthing-dist/scripts/portraits/generate-portraits.sh +26 -10
  141. package/pennyfarthing-dist/skills/pf-changelog/SKILL.md +4 -4
  142. package/pennyfarthing-dist/skills/pf-sprint/skill.md +1 -1
  143. package/pennyfarthing-dist/skills/skill-registry.schema.json +4 -0
  144. package/pennyfarthing-dist/skills/skill-registry.yaml +5 -0
  145. package/pennyfarthing-dist/workflows/2party-tdd.yaml +11 -0
  146. package/pennyfarthing-dist/workflows/agent-docs.yaml +2 -0
  147. package/pennyfarthing-dist/workflows/bdd-tandem.yaml +4 -0
  148. package/pennyfarthing-dist/workflows/bdd.yaml +4 -0
  149. package/pennyfarthing-dist/workflows/git-cleanup/steps/step-05-complete.md +1 -1
  150. package/pennyfarthing-dist/workflows/tdd-tandem.yaml +3 -0
  151. package/pennyfarthing-dist/workflows/tdd.yaml +3 -0
  152. package/pennyfarthing-dist/workflows/trivial.yaml +2 -0
  153. package/pennyfarthing_scripts/__pycache__/__init__.cpython-314.pyc +0 -0
  154. package/pennyfarthing_scripts/__pycache__/bellmode_hook.cpython-314.pyc +0 -0
  155. package/pennyfarthing_scripts/__pycache__/cli.cpython-314.pyc +0 -0
  156. package/pennyfarthing_scripts/__pycache__/config.cpython-314.pyc +0 -0
  157. package/pennyfarthing_scripts/__pycache__/context.cpython-314.pyc +0 -0
  158. package/pennyfarthing_scripts/__pycache__/hooks.cpython-314.pyc +0 -0
  159. package/pennyfarthing_scripts/__pycache__/jira_bidirectional_sync.cpython-314.pyc +0 -0
  160. package/pennyfarthing_scripts/__pycache__/jira_epic_creation.cpython-314.pyc +0 -0
  161. package/pennyfarthing_scripts/__pycache__/jira_sync.cpython-314.pyc +0 -0
  162. package/pennyfarthing_scripts/__pycache__/jira_sync_story.cpython-314.pyc +0 -0
  163. package/pennyfarthing_scripts/__pycache__/output.cpython-314.pyc +0 -0
  164. package/pennyfarthing_scripts/__pycache__/patch_mode.cpython-314.pyc +0 -0
  165. package/pennyfarthing_scripts/__pycache__/pretooluse_hook.cpython-314.pyc +0 -0
  166. package/pennyfarthing_scripts/__pycache__/schema_validation_hook.cpython-314.pyc +0 -0
  167. package/pennyfarthing_scripts/__pycache__/session_start_hook.cpython-314.pyc +0 -0
  168. package/pennyfarthing_scripts/__pycache__/workflow.cpython-314.pyc +0 -0
  169. package/pennyfarthing_scripts/bc/__pycache__/__init__.cpython-314.pyc +0 -0
  170. package/pennyfarthing_scripts/bc/__pycache__/cli.cpython-314.pyc +0 -0
  171. package/pennyfarthing_scripts/bc/__pycache__/focus.cpython-314.pyc +0 -0
  172. package/pennyfarthing_scripts/bikerack/__pycache__/__init__.cpython-314.pyc +0 -0
  173. package/pennyfarthing_scripts/bikerack/__pycache__/__main__.cpython-314.pyc +0 -0
  174. package/pennyfarthing_scripts/bikerack/__pycache__/background_panel.cpython-314.pyc +0 -0
  175. package/pennyfarthing_scripts/bikerack/__pycache__/base_panel.cpython-314.pyc +0 -0
  176. package/pennyfarthing_scripts/bikerack/__pycache__/changed_panel.cpython-314.pyc +0 -0
  177. package/pennyfarthing_scripts/bikerack/__pycache__/cli.cpython-314.pyc +0 -0
  178. package/pennyfarthing_scripts/bikerack/__pycache__/debug_panel.cpython-314.pyc +0 -0
  179. package/pennyfarthing_scripts/bikerack/__pycache__/diffs_panel.cpython-314.pyc +0 -0
  180. package/pennyfarthing_scripts/bikerack/__pycache__/git_panel.cpython-314.pyc +0 -0
  181. package/pennyfarthing_scripts/bikerack/__pycache__/launcher.cpython-314.pyc +0 -0
  182. package/pennyfarthing_scripts/bikerack/__pycache__/sprint_panel.cpython-314.pyc +0 -0
  183. package/pennyfarthing_scripts/bikerack/__pycache__/tui.cpython-314.pyc +0 -0
  184. package/pennyfarthing_scripts/bikerack/__pycache__/ws_client.cpython-314.pyc +0 -0
  185. package/pennyfarthing_scripts/bikerack/cli.py +10 -11
  186. package/pennyfarthing_scripts/bikerack/debug_panel.py +218 -0
  187. package/pennyfarthing_scripts/bikerack/diffs_panel.py +203 -27
  188. package/pennyfarthing_scripts/brownfield/__pycache__/__init__.cpython-314.pyc +0 -0
  189. package/pennyfarthing_scripts/brownfield/__pycache__/__main__.cpython-314.pyc +0 -0
  190. package/pennyfarthing_scripts/brownfield/__pycache__/cli.cpython-314.pyc +0 -0
  191. package/pennyfarthing_scripts/brownfield/__pycache__/discover.cpython-314.pyc +0 -0
  192. package/pennyfarthing_scripts/cli.py +114 -0
  193. package/pennyfarthing_scripts/codemarkers/__pycache__/__init__.cpython-314.pyc +0 -0
  194. package/pennyfarthing_scripts/codemarkers/__pycache__/__main__.cpython-314.pyc +0 -0
  195. package/pennyfarthing_scripts/codemarkers/__pycache__/analyze.cpython-314.pyc +0 -0
  196. package/pennyfarthing_scripts/codemarkers/__pycache__/cli.cpython-314.pyc +0 -0
  197. package/pennyfarthing_scripts/codemarkers/__pycache__/formatters.cpython-314.pyc +0 -0
  198. package/pennyfarthing_scripts/codemarkers/__pycache__/models.cpython-314.pyc +0 -0
  199. package/pennyfarthing_scripts/common/__pycache__/__init__.cpython-314.pyc +0 -0
  200. package/pennyfarthing_scripts/common/__pycache__/config.cpython-314.pyc +0 -0
  201. package/pennyfarthing_scripts/common/__pycache__/output.cpython-314.pyc +0 -0
  202. package/pennyfarthing_scripts/common/__pycache__/themes.cpython-314.pyc +0 -0
  203. package/pennyfarthing_scripts/complexity/__pycache__/__init__.cpython-314.pyc +0 -0
  204. package/pennyfarthing_scripts/complexity/__pycache__/__main__.cpython-314.pyc +0 -0
  205. package/pennyfarthing_scripts/complexity/__pycache__/analyze.cpython-314.pyc +0 -0
  206. package/pennyfarthing_scripts/complexity/__pycache__/cli.cpython-314.pyc +0 -0
  207. package/pennyfarthing_scripts/complexity/__pycache__/formatters.cpython-314.pyc +0 -0
  208. package/pennyfarthing_scripts/complexity/__pycache__/models.cpython-314.pyc +0 -0
  209. package/pennyfarthing_scripts/deadcode/__pycache__/__init__.cpython-314.pyc +0 -0
  210. package/pennyfarthing_scripts/deadcode/__pycache__/__main__.cpython-314.pyc +0 -0
  211. package/pennyfarthing_scripts/deadcode/__pycache__/analyze.cpython-314.pyc +0 -0
  212. package/pennyfarthing_scripts/deadcode/__pycache__/cli.cpython-314.pyc +0 -0
  213. package/pennyfarthing_scripts/deadcode/__pycache__/formatters.cpython-314.pyc +0 -0
  214. package/pennyfarthing_scripts/deadcode/__pycache__/models.cpython-314.pyc +0 -0
  215. package/pennyfarthing_scripts/dependencies/__pycache__/__init__.cpython-314.pyc +0 -0
  216. package/pennyfarthing_scripts/dependencies/__pycache__/__main__.cpython-314.pyc +0 -0
  217. package/pennyfarthing_scripts/dependencies/__pycache__/analyze.cpython-314.pyc +0 -0
  218. package/pennyfarthing_scripts/dependencies/__pycache__/cli.cpython-314.pyc +0 -0
  219. package/pennyfarthing_scripts/dependencies/__pycache__/formatters.cpython-314.pyc +0 -0
  220. package/pennyfarthing_scripts/dependencies/__pycache__/models.cpython-314.pyc +0 -0
  221. package/pennyfarthing_scripts/epic/__init__.py +0 -0
  222. package/pennyfarthing_scripts/epic/cli.py +64 -0
  223. package/pennyfarthing_scripts/gate/__init__.py +1 -0
  224. package/pennyfarthing_scripts/gate/__pycache__/__init__.cpython-314.pyc +0 -0
  225. package/pennyfarthing_scripts/gate/__pycache__/cli.cpython-314.pyc +0 -0
  226. package/pennyfarthing_scripts/gate/__pycache__/validate.cpython-314.pyc +0 -0
  227. package/pennyfarthing_scripts/gate/cli.py +56 -0
  228. package/pennyfarthing_scripts/gate/validate.py +266 -0
  229. package/pennyfarthing_scripts/git/__pycache__/__init__.cpython-314.pyc +0 -0
  230. package/pennyfarthing_scripts/git/__pycache__/create_branches.cpython-314.pyc +0 -0
  231. package/pennyfarthing_scripts/git/__pycache__/status_all.cpython-314.pyc +0 -0
  232. package/pennyfarthing_scripts/git_group/__init__.py +0 -0
  233. package/pennyfarthing_scripts/git_group/cli.py +100 -0
  234. package/pennyfarthing_scripts/handoff/__init__.py +1 -0
  235. package/pennyfarthing_scripts/handoff/__pycache__/__init__.cpython-314.pyc +0 -0
  236. package/pennyfarthing_scripts/handoff/__pycache__/cli.cpython-314.pyc +0 -0
  237. package/pennyfarthing_scripts/handoff/__pycache__/complete_phase.cpython-314.pyc +0 -0
  238. package/pennyfarthing_scripts/handoff/__pycache__/gate_file.cpython-314.pyc +0 -0
  239. package/pennyfarthing_scripts/handoff/__pycache__/gate_runner.cpython-314.pyc +0 -0
  240. package/pennyfarthing_scripts/handoff/__pycache__/marker.cpython-314.pyc +0 -0
  241. package/pennyfarthing_scripts/handoff/__pycache__/resolve_gate.cpython-314.pyc +0 -0
  242. package/pennyfarthing_scripts/handoff/cli.py +120 -0
  243. package/pennyfarthing_scripts/handoff/complete_phase.py +155 -0
  244. package/pennyfarthing_scripts/handoff/gate_file.py +105 -0
  245. package/pennyfarthing_scripts/handoff/gate_runner.py +152 -0
  246. package/pennyfarthing_scripts/handoff/marker.py +109 -0
  247. package/pennyfarthing_scripts/handoff/resolve_gate.py +152 -0
  248. package/pennyfarthing_scripts/healthscore/__pycache__/__init__.cpython-314.pyc +0 -0
  249. package/pennyfarthing_scripts/healthscore/__pycache__/__main__.cpython-314.pyc +0 -0
  250. package/pennyfarthing_scripts/healthscore/__pycache__/analyze.cpython-314.pyc +0 -0
  251. package/pennyfarthing_scripts/healthscore/__pycache__/cli.cpython-314.pyc +0 -0
  252. package/pennyfarthing_scripts/healthscore/__pycache__/formatters.cpython-314.pyc +0 -0
  253. package/pennyfarthing_scripts/healthscore/__pycache__/models.cpython-314.pyc +0 -0
  254. package/pennyfarthing_scripts/hotspots/__pycache__/__init__.cpython-314.pyc +0 -0
  255. package/pennyfarthing_scripts/hotspots/__pycache__/__main__.cpython-314.pyc +0 -0
  256. package/pennyfarthing_scripts/hotspots/__pycache__/analyze.cpython-314.pyc +0 -0
  257. package/pennyfarthing_scripts/hotspots/__pycache__/cli.cpython-314.pyc +0 -0
  258. package/pennyfarthing_scripts/hotspots/__pycache__/formatters.cpython-314.pyc +0 -0
  259. package/pennyfarthing_scripts/hotspots/__pycache__/models.cpython-314.pyc +0 -0
  260. package/pennyfarthing_scripts/jira/__pycache__/__init__.cpython-314.pyc +0 -0
  261. package/pennyfarthing_scripts/jira/__pycache__/__main__.cpython-314.pyc +0 -0
  262. package/pennyfarthing_scripts/jira/__pycache__/bidirectional.cpython-314.pyc +0 -0
  263. package/pennyfarthing_scripts/jira/__pycache__/claim.cpython-314.pyc +0 -0
  264. package/pennyfarthing_scripts/jira/__pycache__/cli.cpython-314.pyc +0 -0
  265. package/pennyfarthing_scripts/jira/__pycache__/client.cpython-314.pyc +0 -0
  266. package/pennyfarthing_scripts/jira/__pycache__/create.cpython-314.pyc +0 -0
  267. package/pennyfarthing_scripts/jira/__pycache__/epic.cpython-314.pyc +0 -0
  268. package/pennyfarthing_scripts/jira/__pycache__/operations.cpython-314.pyc +0 -0
  269. package/pennyfarthing_scripts/jira/__pycache__/reconcile.cpython-314.pyc +0 -0
  270. package/pennyfarthing_scripts/jira/__pycache__/story.cpython-314.pyc +0 -0
  271. package/pennyfarthing_scripts/jira/__pycache__/sync.cpython-314.pyc +0 -0
  272. package/pennyfarthing_scripts/launch/__pycache__/__init__.cpython-314.pyc +0 -0
  273. package/pennyfarthing_scripts/launch/__pycache__/cli.cpython-314.pyc +0 -0
  274. package/pennyfarthing_scripts/migration/__pycache__/__init__.cpython-314.pyc +0 -0
  275. package/pennyfarthing_scripts/migration/__pycache__/session.cpython-314.pyc +0 -0
  276. package/pennyfarthing_scripts/migration/__pycache__/skill.cpython-314.pyc +0 -0
  277. package/pennyfarthing_scripts/migration/__pycache__/step.cpython-314.pyc +0 -0
  278. package/pennyfarthing_scripts/migration/__pycache__/validate.cpython-314.pyc +0 -0
  279. package/pennyfarthing_scripts/preflight/__pycache__/__init__.cpython-314.pyc +0 -0
  280. package/pennyfarthing_scripts/preflight/__pycache__/__main__.cpython-314.pyc +0 -0
  281. package/pennyfarthing_scripts/preflight/__pycache__/cli.cpython-314.pyc +0 -0
  282. package/pennyfarthing_scripts/preflight/__pycache__/finish.cpython-314.pyc +0 -0
  283. package/pennyfarthing_scripts/prime/__pycache__/__init__.cpython-314.pyc +0 -0
  284. package/pennyfarthing_scripts/prime/__pycache__/cli.cpython-314.pyc +0 -0
  285. package/pennyfarthing_scripts/prime/__pycache__/loader.cpython-314.pyc +0 -0
  286. package/pennyfarthing_scripts/prime/__pycache__/models.cpython-314.pyc +0 -0
  287. package/pennyfarthing_scripts/prime/__pycache__/persona.cpython-314.pyc +0 -0
  288. package/pennyfarthing_scripts/prime/__pycache__/session.cpython-314.pyc +0 -0
  289. package/pennyfarthing_scripts/prime/__pycache__/tiers.cpython-314.pyc +0 -0
  290. package/pennyfarthing_scripts/prime/__pycache__/version_sentinel.cpython-314.pyc +0 -0
  291. package/pennyfarthing_scripts/prime/__pycache__/workflow.cpython-314.pyc +0 -0
  292. package/pennyfarthing_scripts/prime/workflow.py +39 -0
  293. package/pennyfarthing_scripts/session/__init__.py +0 -0
  294. package/pennyfarthing_scripts/session/cli.py +87 -0
  295. package/pennyfarthing_scripts/sprint/__pycache__/__init__.cpython-314.pyc +0 -0
  296. package/pennyfarthing_scripts/sprint/__pycache__/__main__.cpython-314.pyc +0 -0
  297. package/pennyfarthing_scripts/sprint/__pycache__/archive.cpython-314.pyc +0 -0
  298. package/pennyfarthing_scripts/sprint/__pycache__/archive_epic.cpython-314.pyc +0 -0
  299. package/pennyfarthing_scripts/sprint/__pycache__/cli.cpython-314.pyc +0 -0
  300. package/pennyfarthing_scripts/sprint/__pycache__/epic_add.cpython-314.pyc +0 -0
  301. package/pennyfarthing_scripts/sprint/__pycache__/epic_update.cpython-314.pyc +0 -0
  302. package/pennyfarthing_scripts/sprint/__pycache__/import_epic.cpython-314.pyc +0 -0
  303. package/pennyfarthing_scripts/sprint/__pycache__/loader.cpython-314.pyc +0 -0
  304. package/pennyfarthing_scripts/sprint/__pycache__/status.cpython-314.pyc +0 -0
  305. package/pennyfarthing_scripts/sprint/__pycache__/story_add.cpython-314.pyc +0 -0
  306. package/pennyfarthing_scripts/sprint/__pycache__/story_finish.cpython-314.pyc +0 -0
  307. package/pennyfarthing_scripts/sprint/__pycache__/story_update.cpython-314.pyc +0 -0
  308. package/pennyfarthing_scripts/sprint/__pycache__/validate_cmd.cpython-314.pyc +0 -0
  309. package/pennyfarthing_scripts/sprint/__pycache__/validator.cpython-314.pyc +0 -0
  310. package/pennyfarthing_scripts/sprint/__pycache__/work.cpython-314.pyc +0 -0
  311. package/pennyfarthing_scripts/sprint/__pycache__/yaml_io.cpython-314.pyc +0 -0
  312. package/pennyfarthing_scripts/sprint/story_finish.py +14 -0
  313. package/pennyfarthing_scripts/story/__pycache__/__init__.cpython-314.pyc +0 -0
  314. package/pennyfarthing_scripts/story/__pycache__/__main__.cpython-314.pyc +0 -0
  315. package/pennyfarthing_scripts/story/__pycache__/cli.cpython-314.pyc +0 -0
  316. package/pennyfarthing_scripts/story/__pycache__/create.cpython-314.pyc +0 -0
  317. package/pennyfarthing_scripts/story/__pycache__/size.cpython-314.pyc +0 -0
  318. package/pennyfarthing_scripts/story/__pycache__/template.cpython-314.pyc +0 -0
  319. package/pennyfarthing_scripts/tests/__pycache__/__init__.cpython-314.pyc +0 -0
  320. package/pennyfarthing_scripts/tests/__pycache__/conftest.cpython-314-pytest-9.0.2.pyc +0 -0
  321. package/pennyfarthing_scripts/tests/__pycache__/test_108_2_remove_handoff_fallback.cpython-314-pytest-9.0.2.pyc +0 -0
  322. package/pennyfarthing_scripts/tests/__pycache__/test_archive_epic.cpython-314-pytest-9.0.2.pyc +0 -0
  323. package/pennyfarthing_scripts/tests/__pycache__/test_bc.cpython-314-pytest-9.0.2.pyc +0 -0
  324. package/pennyfarthing_scripts/tests/__pycache__/test_bikerack.cpython-314-pytest-9.0.2.pyc +0 -0
  325. package/pennyfarthing_scripts/tests/__pycache__/test_brownfield.cpython-314-pytest-9.0.2.pyc +0 -0
  326. package/pennyfarthing_scripts/tests/__pycache__/test_cli_modules.cpython-314-pytest-9.0.2.pyc +0 -0
  327. package/pennyfarthing_scripts/tests/__pycache__/test_cli_normalization.cpython-314-pytest-9.0.2.pyc +0 -0
  328. package/pennyfarthing_scripts/tests/__pycache__/test_codemarkers.cpython-314-pytest-9.0.2.pyc +0 -0
  329. package/pennyfarthing_scripts/tests/__pycache__/test_common.cpython-314-pytest-9.0.2.pyc +0 -0
  330. package/pennyfarthing_scripts/tests/__pycache__/test_epic_shard_validation.cpython-314-pytest-9.0.2.pyc +0 -0
  331. package/pennyfarthing_scripts/tests/__pycache__/test_gate_file_resolution.cpython-314-pytest-9.0.2.pyc +0 -0
  332. package/pennyfarthing_scripts/tests/__pycache__/test_gate_runner.cpython-314-pytest-9.0.2.pyc +0 -0
  333. package/pennyfarthing_scripts/tests/__pycache__/test_git_utils.cpython-314-pytest-9.0.2.pyc +0 -0
  334. package/pennyfarthing_scripts/tests/__pycache__/test_handoff_cli.cpython-314-pytest-9.0.2.pyc +0 -0
  335. package/pennyfarthing_scripts/tests/__pycache__/test_handoff_e2e.cpython-314-pytest-9.0.2.pyc +0 -0
  336. package/pennyfarthing_scripts/tests/__pycache__/test_healthscore.cpython-314-pytest-9.0.2.pyc +0 -0
  337. package/pennyfarthing_scripts/tests/__pycache__/test_jira_package.cpython-314-pytest-9.0.2.pyc +0 -0
  338. package/pennyfarthing_scripts/tests/__pycache__/test_package_structure.cpython-314-pytest-9.0.2.pyc +0 -0
  339. package/pennyfarthing_scripts/tests/__pycache__/test_patch_mode.cpython-314-pytest-9.0.2.pyc +0 -0
  340. package/pennyfarthing_scripts/tests/__pycache__/test_prime.cpython-314-pytest-9.0.2.pyc +0 -0
  341. package/pennyfarthing_scripts/tests/__pycache__/test_resolve_gate_file_field.cpython-314-pytest-9.0.2.pyc +0 -0
  342. package/pennyfarthing_scripts/tests/__pycache__/test_sprint_package.cpython-314-pytest-9.0.2.pyc +0 -0
  343. package/pennyfarthing_scripts/tests/__pycache__/test_sprint_panel.cpython-314-pytest-9.0.2.pyc +0 -0
  344. package/pennyfarthing_scripts/tests/__pycache__/test_sprint_validator.cpython-314-pytest-9.0.2.pyc +0 -0
  345. package/pennyfarthing_scripts/tests/__pycache__/test_story_add.cpython-314-pytest-9.0.2.pyc +0 -0
  346. package/pennyfarthing_scripts/tests/__pycache__/test_story_package.cpython-314-pytest-9.0.2.pyc +0 -0
  347. package/pennyfarthing_scripts/tests/__pycache__/test_story_update.cpython-314-pytest-9.0.2.pyc +0 -0
  348. package/pennyfarthing_scripts/tests/__pycache__/test_tiers.cpython-314-pytest-9.0.2.pyc +0 -0
  349. package/pennyfarthing_scripts/tests/__pycache__/test_token_counting.cpython-314-pytest-9.0.2.pyc +0 -0
  350. package/pennyfarthing_scripts/tests/__pycache__/test_topology_loader.cpython-314-pytest-9.0.2.pyc +0 -0
  351. package/pennyfarthing_scripts/tests/__pycache__/test_tui_focus.cpython-314-pytest-9.0.2.pyc +0 -0
  352. package/pennyfarthing_scripts/tests/__pycache__/test_tui_panel_persistence.cpython-314-pytest-9.0.2.pyc +0 -0
  353. package/pennyfarthing_scripts/tests/__pycache__/test_validate_cmd.cpython-314-pytest-9.0.2.pyc +0 -0
  354. package/pennyfarthing_scripts/tests/__pycache__/test_version_sentinel.cpython-314-pytest-9.0.2.pyc +0 -0
  355. package/pennyfarthing_scripts/tests/__pycache__/test_workflow_check.cpython-314-pytest-9.0.2.pyc +0 -0
  356. package/pennyfarthing_scripts/tests/__pycache__/test_yaml_io.cpython-314-pytest-9.0.2.pyc +0 -0
  357. package/pennyfarthing_scripts/tests/test_108_1_gate_migration.py +540 -0
  358. package/pennyfarthing_scripts/tests/test_108_2_remove_handoff_fallback.py +339 -0
  359. package/pennyfarthing_scripts/tests/test_confidence_sm_evaluation.py +253 -0
  360. package/pennyfarthing_scripts/tests/test_confidence_sm_gate.py +315 -0
  361. package/pennyfarthing_scripts/tests/test_gate_file_resolution.py +341 -0
  362. package/pennyfarthing_scripts/tests/test_gate_runner.py +620 -0
  363. package/pennyfarthing_scripts/tests/test_handoff_cli.py +929 -0
  364. package/pennyfarthing_scripts/tests/test_handoff_e2e.py +454 -0
  365. package/pennyfarthing_scripts/tests/test_resolve_gate_file_field.py +464 -0
  366. package/pennyfarthing_scripts/theme/__pycache__/__init__.cpython-314.pyc +0 -0
  367. package/pennyfarthing_scripts/theme/__pycache__/cli.cpython-314.pyc +0 -0
  368. package/pennyfarthing_scripts/validate/__pycache__/__init__.cpython-314.pyc +0 -0
  369. package/pennyfarthing_scripts/validate/__pycache__/cli.cpython-314.pyc +0 -0
  370. package/pennyfarthing_scripts/validate/adapters/__pycache__/__init__.cpython-314.pyc +0 -0
  371. package/pennyfarthing_scripts/validate/adapters/__pycache__/agent.cpython-314.pyc +0 -0
  372. package/pennyfarthing_scripts/validate/adapters/__pycache__/schema.cpython-314.pyc +0 -0
  373. package/pennyfarthing_scripts/validate/adapters/__pycache__/skill_command.cpython-314.pyc +0 -0
  374. package/pennyfarthing_scripts/validate/adapters/__pycache__/sprint.cpython-314.pyc +0 -0
  375. package/pennyfarthing_scripts/validate/adapters/__pycache__/workflow.cpython-314.pyc +0 -0
  376. package/pennyfarthing_scripts/validate/adapters/skill_command.py +200 -0
  377. package/pennyfarthing_scripts/validate/adapters/workflow.py +64 -0
  378. package/pennyfarthing_scripts/validate/cli.py +15 -4
  379. package/packages/core/dist/scripts/benchmark-integration.d.ts +0 -182
  380. package/packages/core/dist/scripts/benchmark-integration.d.ts.map +0 -1
  381. package/packages/core/dist/scripts/benchmark-integration.js +0 -691
  382. package/packages/core/dist/scripts/benchmark-integration.js.map +0 -1
  383. package/packages/core/dist/scripts/job-fair-aggregator.d.ts +0 -150
  384. package/packages/core/dist/scripts/job-fair-aggregator.d.ts.map +0 -1
  385. package/packages/core/dist/scripts/job-fair-aggregator.js +0 -547
  386. package/packages/core/dist/scripts/job-fair-aggregator.js.map +0 -1
  387. package/pennyfarthing-dist/agents/handoff.md +0 -250
  388. package/pennyfarthing-dist/agents/sm-handoff.md +0 -152
  389. package/pennyfarthing-dist/scripts/core/handoff-marker.sh +0 -112
  390. package/pennyfarthing-dist/scripts/hooks/__pycache__/question_reflector_check.cpython-314.pyc +0 -0
  391. package/pennyfarthing_scripts/__pycache__/__init__.cpython-311.pyc +0 -0
  392. package/pennyfarthing_scripts/__pycache__/jira.cpython-314.pyc +0 -0
  393. package/pennyfarthing_scripts/__pycache__/sprint.cpython-314.pyc +0 -0
  394. package/pennyfarthing_scripts/__pycache__/workflow.cpython-311.pyc +0 -0
  395. package/pennyfarthing_scripts/jira/__pycache__/compat.cpython-314.pyc +0 -0
  396. package/pennyfarthing_scripts/jira/__pycache__/mappings.cpython-314.pyc +0 -0
  397. package/pennyfarthing_scripts/jira/__pycache__/models.cpython-314.pyc +0 -0
  398. package/pennyfarthing_scripts/migration/__pycache__/__main__.cpython-314.pyc +0 -0
  399. package/pennyfarthing_scripts/migration/__pycache__/cli.cpython-314.pyc +0 -0
  400. package/pennyfarthing_scripts/prime/__pycache__/__main__.cpython-314.pyc +0 -0
  401. package/pennyfarthing_scripts/tests/__pycache__/test_workflow_cli.cpython-314-pytest-9.0.2.pyc +0 -0
@@ -60,8 +60,8 @@ For more information, see https://radix-ui.com/primitives/docs/components/${e.do
60
60
  `).length:0}function fM(n,e){return n.replace(/\r\n/g,`
61
61
  `).split(`
62
62
  `).slice(0,e).join(`
63
- `)}function mM(n,e){return n==="Read"&&e.file_path?String(e.file_path):n==="Bash"&&e.command?String(e.command):n==="Glob"&&e.pattern||n==="Grep"&&e.pattern?String(e.pattern):n==="Write"&&e.file_path?String(e.file_path):JSON.stringify(e,null,2)}function ES(n){return{Read:"R",Write:"W",Bash:"B",Glob:"G",Grep:"S",Edit:"E",Task:"T",WebFetch:"F",WebSearch:"W",TodoWrite:"D"}[n]||n.charAt(0).toUpperCase()}function Rm({toolUse:n,result:e,className:i}){const[a,r]=m.useState(!0),[c,d]=m.useState(!0),[h,f]=m.useState(!1),[p,y]=m.useState("idle"),b=e?.is_error===!0,x=mM(n.tool_name,n.input),w=Object.keys(n.input).length,E=cM(n.tool_name),_=m.useMemo(()=>Af(n.tool_name,n.input),[n.tool_name,n.input]),C=m.useMemo(()=>e?hM(e.content):0,[e?.content]),D=C>bx,N=D&&!h,k=m.useMemo(()=>e?N?fM(e.content,bx):e.content:"",[e?.content,N]),T=async()=>{if(e)try{await navigator.clipboard.writeText(e.content),y("copied"),setTimeout(()=>y("idle"),2e3)}catch{y("error")}},R=C===1?"1 line":`${C} lines`,z=["tool-call-block",E,b?"tool-error":"",i||""].filter(Boolean).join(" "),O=ES(n.tool_name);return l.jsx(St,{delayDuration:300,children:l.jsxs("div",{"data-testid":"tool-call-block",className:z,children:[l.jsxs("div",{className:"tool-header",children:[l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx($e,{variant:"default",className:"tool-type-badge",children:O})}),l.jsx(Te,{children:n.tool_name})]}),l.jsx("span",{className:"tool-name",children:_}),l.jsx("span",{"data-testid":"tool-duration",className:"tool-duration",children:e?.durationMs!==void 0?_S(e.durationMs):""})]}),l.jsx("div",{className:"tool-result-header",children:l.jsxs(Ce,{variant:"ghost",size:"sm","data-testid":"tool-prompt-toggle",className:"tool-result-toggle",onClick:()=>d(!c),children:[c?"▶":"▼"," Prompt (",w," ",w===1?"param":"params",")"]})}),l.jsx("div",{"data-testid":"tool-prompt-content",className:`tool-result-content ${c?"collapsed":""}`,children:l.jsx("pre",{children:x})}),e&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"tool-result-header",children:[l.jsxs(Ce,{variant:"ghost",size:"sm","data-testid":"tool-result-toggle",className:"tool-result-toggle",onClick:()=>r(!a),children:[a?"▶":"▼"," Result (",R,")"]}),l.jsx(Ce,{variant:"ghost",size:"icon","data-testid":"tool-result-copy",className:`tool-result-copy ${p==="copied"?"copied":""} ${p==="error"?"copy-error":""}`,onClick:T,"aria-label":"Copy result to clipboard",children:p==="copied"?"✓":"📋"})]}),l.jsxs("div",{"data-testid":"tool-result-content",className:`tool-result-content ${a?"collapsed":""} ${N&&!a?"truncated":""} ${b?"error-content":""}`,children:[l.jsx("pre",{children:k}),D&&!a&&N&&l.jsxs(Ce,{variant:"link",size:"sm","data-testid":"tool-result-expand",className:"tool-result-expand",onClick:()=>f(!0),children:["Show all (",C," lines)"]})]})]})]})})}function pM({stack:n,toolResults:e}){const[i,a]=m.useState(!n.isActive),r=m.useRef(n.isActive);m.useEffect(()=>{r.current&&!n.isActive&&a(!1),r.current=n.isActive},[n.isActive]);const c=`${n.count}`,d=m.useMemo(()=>{if(n.isActive&&n.tools.length>0){const E=n.tools[n.tools.length-1];return Af(E.tool_name,E.input)}return null},[n.tools,n.isActive]),h=m.useMemo(()=>{if(n.tools.length===0)return"";const E=n.tools[n.tools.length-1];return Af(E.tool_name,E.input)},[n.tools]),f=m.useMemo(()=>{const E=new Map;return n.tools.forEach(_=>{const C=E.get(_.tool_name)||0;E.set(_.tool_name,C+1)}),E},[n.tools]),p=m.useMemo(()=>n.tools.reduce((E,_)=>{const C=e.get(_.tool_id);return E+(C?.durationMs||0)},0),[n.tools,e]),y=E=>{const _=n.tools[E],C=e.get(_.tool_id);return n.isActive&&E===n.tools.length-1&&!C?"tool-current":"tool-historical"},b=m.useCallback(()=>{a(E=>!E)},[]),x=m.useCallback(E=>{(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),b())},[b]),w=!i||n.isActive;return l.jsxs("div",{"data-testid":"tool-stack","data-collapsible":"true",className:`tool-stack ${i&&!n.isActive?"collapsed":""}`,children:[l.jsxs("div",{"data-testid":"tool-stack-header",className:"tool-stack-header",onClick:b,onKeyDown:x,role:"button",tabIndex:0,"aria-expanded":!i||n.isActive,"aria-label":`Tool stack with ${c}: ${h}`,children:[l.jsx("span",{className:"tool-stack-toggle",children:i&&!n.isActive?"▶":"▼"}),l.jsx("span",{"data-testid":"tool-stack-count",className:"tool-stack-count-badge",children:c}),n.isActive&&d?l.jsx("span",{className:"tool-stack-active-summary",children:d}):l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"tool-stack-badges",children:l.jsx(St,{delayDuration:300,children:Array.from(f.entries()).slice(0,4).map(([E,_])=>l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx($e,{variant:"outline",className:`tool-mini-badge badge-${E.toLowerCase()}`,children:ES(E)})}),l.jsx(Te,{children:`${_} ${E} call${_>1?"s":""}`})]},E))})}),l.jsx("span",{className:"tool-stack-summary",children:h})]}),l.jsx("span",{className:"tool-stack-duration",children:p>0?_S(p):""})]}),w&&l.jsx("div",{className:"tool-stack-content",children:n.tools.map((E,_)=>{const C=e.get(E.tool_id),D=y(_);return l.jsx(Rm,{toolUse:{type:"tool_use",tool_name:E.tool_name,tool_id:E.tool_id,input:E.input,timestamp:E.timestamp},result:C?{type:"tool_result",tool_id:C.tool_id,content:C.content,timestamp:C.timestamp}:void 0,className:D},E.tool_id||`tool-${_}`)})})]})}const Yh=new Map;let xc=null;async function gM(){if(!xc)try{const n=await fetch("/api/theme-agents/full");n.ok&&(xc=await n.json())}catch{}}async function vM(n){const e=`agent:${n}`;if(Yh.has(e))return Yh.get(e);try{if(await gM(),xc?.agents){const i=xc.agents.find(a=>a.role===n);if(i?.helper)return Yh.set(e,i.helper),i.helper}return null}catch{return null}}const xx={"testing-runner":"Running tests",Explore:"Exploring codebase","sm-setup":"Setting up story","sm-finish":"Finishing story",handoff:"Handing off","workflow-status-check":"Checking workflow status","general-purpose":"Processing task",Plan:"Planning implementation",Bash:"Running commands"};function yM(n,e){const i=e?.plural?"are":"is",a=n.description,r=n.subagent_type;if(r&&xx[r]){const c=xx[r],d=c.charAt(0).toLowerCase()+c.slice(1);return a?`${i} ${d}: ${a}`:`${i} ${d}`}return a||"Working..."}function bM(){const[n,e]=m.useState(null),[i,a]=m.useState(!0),[r,c]=m.useState(null);return m.useEffect(()=>{const d=async p=>{try{const y=await vM(p);e(y),a(!1)}catch(y){c(y instanceof Error?y:new Error("Failed to fetch helper")),a(!1)}},h=window.location.protocol==="https:"?"wss:":"ws:",f=new WebSocket(`${h}//${window.location.host}/ws/persona`);return f.onmessage=p=>{try{const y=JSON.parse(p.data);y?.role&&d(y.role)}catch(y){c(y instanceof Error?y:new Error("Failed to parse persona")),a(!1)}},f.onerror=()=>{c(new Error("WebSocket connection failed")),a(!1)},()=>f.close()},[]),{helper:n,isLoading:i,error:r}}function xM({type:n,name:e,messages:i,defaultCollapsed:a=!0,onCollapseChange:r,helperName:c,helperStyle:d,friendlyMessage:h}){const[f,p]=m.useState(a),{helper:y}=bM(),b=m.useMemo(()=>yM({subagent_type:n,description:e},{plural:y?.plural}),[n,e,y?.plural]),x=c??y?.name,w=d??y?.style,E=h??b,_=x||n,C=E||e,D=i.filter(T=>T.type!=="tool_result").length,N=new Map;i.forEach(T=>{T.type==="tool_result"&&T.tool_id&&N.set(T.tool_id,T)});const k=(T,R)=>{if(T.type==="tool_use"&&T.tool_name&&T.tool_id){const z=N.get(T.tool_id);return l.jsx("div",{"data-testid":"message-tool_use",className:"message message-tool_use",children:l.jsx(Rm,{toolUse:{type:"tool_use",tool_name:T.tool_name,tool_id:T.tool_id,input:T.input||{},timestamp:T.timestamp},result:z?{type:"tool_result",tool_id:z.tool_id,content:z.content||"",timestamp:z.timestamp}:void 0})},`tool-wrapper-${T.tool_id}`)}if(T.type==="tool_result")return null;if(T.type==="user"){const z=(T.content||"").slice(0,120).replace(/\n/g," ");return l.jsx("div",{"data-testid":"subagent-prompt",className:"message message-subagent-prompt",children:l.jsxs("div",{className:"message-content",children:[z,(T.content||"").length>120?"...":""]})},`subagent-prompt-${R}`)}return l.jsx(CS,{message:{type:T.type,content:T.content,timestamp:T.timestamp}},`msg-${R}`)};return l.jsxs("div",{"data-testid":"subagent-span","data-collapsible":"true",className:`subagent-span subagent-${n} ${f?"collapsed":""}`,children:[l.jsxs("div",{"data-testid":"subagent-span-header",className:"subagent-header",onClick:()=>{const T=!f;p(T),r?.(T)},children:[l.jsx("span",{className:"subagent-toggle",children:f?"▶":"▼"}),l.jsx(St,{delayDuration:300,children:w?l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{className:"subagent-helper-name",children:_})}),l.jsx(Te,{children:w})]}):l.jsx("span",{className:"subagent-helper-name",children:_})}),l.jsx("span",{className:"subagent-friendly-message",children:C}),l.jsx($e,{variant:"outline","data-testid":"subagent-type-badge",className:"subagent-type-badge",children:n}),l.jsx("span",{className:"subagent-count",children:D})]}),!f&&l.jsx("div",{className:"subagent-content",children:i.map((T,R)=>k(T,R))})]})}const wx=/<!--\s*CYCLIST:(\w+)(?::([^>]+?))?\s*-->/gi,As={HANDOFF:"handoff",CONTEXT_CLEAR:"context_clear",INVOKE:"invoke",QUESTION:"question",CHOICES:"choices",CONTINUE:"continue"},wM=new Set(["handoff","context_clear","invoke","question","choices","continue"]);function SM(n){return n?n.replace(/```[\s\S]*?```/g,""):""}function CM(n){if(!n)return null;const e=SM(n);if(!e.trim())return null;const i=[];wx.lastIndex=0;let a;for(;(a=wx.exec(e))!==null;){const r=a[1].toLowerCase();wM.has(r)&&i.push({type:r,value:a[2]?.trim()??"",source:"structured_marker"})}return i.length>0?i:null}function _M(n,e){if(!n)return e.map(c=>({number:c,text:`Option ${c}`}));const i=n.replace(/```[\s\S]*?```/g,""),a=[/^\s*(\d+)\.\s+(.+)$/gm,/^\s*(\d+)\)\s+(.+)$/gm,/\*\*(\d+)[.)]\*\*\s*(.+)/gm],r=new Map;for(const c of a){c.lastIndex=0;let d;for(;(d=c.exec(i))!==null;){const h=parseInt(d[1],10);if(e.includes(h)&&!r.has(h)){let f=d[2].trim();const p=f.search(/\s+[-—]\s+/);p>0&&p<30&&(f=f.substring(0,p)),r.set(h,f)}}}return e.map(c=>({number:c,text:r.get(c)||`Option ${c}`}))}function EM(n,e){if(!n||n.length===0)return null;const i=n[0];switch(i.type){case As.HANDOFF:return{type:"handoff",value:i.value,responses:[i.value,"Not yet"]};case As.INVOKE:return{type:"invoke",value:i.value,autoExecute:!0};case As.QUESTION:{if(i.value==="yesno")return{type:"yesno",responses:["Yes","No"]};if(i.value?.startsWith("open")){const r=i.value.indexOf(":");if(r!==-1){const c=i.value.substring(r+1).trim();if(c)return{type:"open",responses:[c]}}return{type:"open"}}const a=n.find(r=>r.type===As.CHOICES);return a?Sx(a.value,e):null}case As.CHOICES:return Sx(i.value,e);case As.CONTEXT_CLEAR:return{type:"context_clear",value:i.value};case As.CONTINUE:return{type:"continue",responses:["Continue"]};default:return null}}function Sx(n,e){const i=n.split(",").map(d=>d.trim()),a=i[0],r=/^\d+$/.test(a);let c;if(r){const d=i.map(h=>parseInt(h,10));c=_M(e,d)}else c=i.map((d,h)=>({number:h+1,text:d}));return{type:"choices",choices:c,responses:c.map(d=>d.text)}}function DM(n){return m.useMemo(()=>{if(!n)return null;const e=CM(n);return e?EM(e,n):null},[n])}async function AM(){try{const n=await fetch("/api/settings");if(n.ok)return(await n.json())?.workflow?.relay_mode??!1}catch{}return!1}function NM(n){const{send:e}=dr(),i=m.useCallback(x=>{console.log("[QuickActions] sendMessage called:",x),e(x,[])},[e]),{onAction:a}=n,[r,c]=m.useState(!1),[d,h]=m.useState(!1),f="message"in n?n.message:void 0,p="actions"in n?n.actions:void 0,y=DM(f?.content);m.useEffect(()=>{c(!1)},[f?.timestamp]),m.useEffect(()=>{AM().then(h)},[]),m.useEffect(()=>{const x=()=>{c(!0)};return window.addEventListener("cyclist:user-submit",x),()=>{window.removeEventListener("cyclist:user-submit",x)}},[]),m.useEffect(()=>{if(y?.type==="handoff"&&d&&y.value){const x=setTimeout(()=>{i(y.value),c(!0),a?.(y.value)},100);return()=>clearTimeout(x)}if(y?.type==="invoke"&&y.value){const x=setTimeout(()=>{i(y.value),c(!0),a?.(y.value)},100);return()=>clearTimeout(x)}},[y,d,a]),m.useEffect(()=>{if(y?.type==="open"&&y.responses&&y.responses.length>0){const x=y.responses[0];window.dispatchEvent(new CustomEvent("cyclist:suggest-prompt",{detail:{prompt:x}}))}},[y]);const b=m.useCallback(x=>{console.log("[QuickActions] Button clicked:",x),c(!0),i(x),a?.(x)},[a]);return p&&p.length>0?l.jsx("div",{className:"quick-actions",children:l.jsx("div",{className:"quick-actions-buttons",children:p.map(x=>l.jsx(Ce,{variant:"secondary",size:"sm",type:"button",className:"quick-action-btn",onClick:()=>b(x.command),disabled:r,"aria-label":`${x.label}: ${x.command}`,children:x.label},x.command))})}):!y||y.type==="open"||y.type==="continue"?null:y.type==="invoke"?l.jsx("div",{className:"quick-actions",children:l.jsxs("span",{className:"auto-invoke-status",children:["Invoking ",y.value,"..."]})}):y.type==="handoff"&&d?l.jsx("div",{className:"quick-actions",children:l.jsxs("span",{className:"auto-invoke-status",children:["Handing off to ",y.value,"..."]})}):l.jsxs("div",{className:"quick-actions",children:[y.type==="handoff"&&y.responses&&l.jsx("div",{className:"quick-actions-buttons",children:y.responses.map(x=>l.jsx(Ce,{variant:"secondary",size:"sm",type:"button",className:"quick-action-btn",onClick:()=>b(x),disabled:r,"aria-label":`Continue with ${x}`,children:x},x))}),y.type==="yesno"&&l.jsxs("div",{className:"quick-actions-buttons",children:[l.jsx(Ce,{variant:"secondary",size:"sm",type:"button",className:"quick-action-btn",onClick:()=>b("Yes"),disabled:r,"aria-label":"Answer Yes",children:"Yes"}),l.jsx(Ce,{variant:"secondary",size:"sm",type:"button",className:"quick-action-btn",onClick:()=>b("No"),disabled:r,"aria-label":"Answer No",children:"No"})]}),y.type==="choices"&&y.choices&&l.jsx("div",{className:"quick-actions-buttons",children:y.choices.map(x=>l.jsx(Ce,{variant:"secondary",size:"sm",type:"button",className:"quick-action-btn",onClick:()=>b(x.text),disabled:r,"aria-label":`Choose option ${x.number}: ${x.text}`,children:x.text},x.number))})]})}var jM="Separator",Cx="horizontal",TM=["horizontal","vertical"],DS=m.forwardRef((n,e)=>{const{decorative:i,orientation:a=Cx,...r}=n,c=kM(a)?a:Cx,h=i?{role:"none"}:{"aria-orientation":c==="vertical"?c:void 0,role:"separator"};return l.jsx(In.div,{"data-orientation":c,...h,...r,ref:e})});DS.displayName=jM;function kM(n){return TM.includes(n)}var AS=DS;const Rt=m.forwardRef(({className:n,orientation:e="horizontal",decorative:i=!0,...a},r)=>l.jsx(AS,{ref:r,decorative:i,orientation:e,className:ye("shrink-0 bg-border",e==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",n),...a}));Rt.displayName=AS.displayName;const RM=["<command-message>","<command-name>","Base directory for this skill:","Launching skill:"],OM=[/^```bash\s*\npf agent start\b/,/^pf agent start\b/,/^<purpose>/,/^<when-to-use>/,/^<execution>/,/^<critical>\s*\n/],ql={sm:"Scrum Master",tea:"Test Engineer",dev:"Developer",reviewer:"Reviewer",architect:"Architect",pm:"Product Manager","tech-writer":"Tech Writer","ux-designer":"UX Designer",devops:"DevOps",orchestrator:"Orchestrator",ba:"Business Analyst"};function zM(n){if(!n||typeof n!="string")return!1;if(RM.some(i=>n.includes(i)))return!0;const e=n.trimStart();return OM.some(i=>i.test(e))}function MM(n){if(!n||typeof n!="string")return null;const e=n.match(/<command-name>\/?([^<]+)<\/command-name>/);if(e){const c=e[1].trim();return ql[c]||c}const i=n.match(/<command-message>([^<]+)<\/command-message>/);if(i){const c=i[1].trim();return ql[c]||c}const a=n.match(/pf agent start\s+"([^"]+)"/);if(a){const c=a[1].trim();return ql[c]||c}const r=n.match(/Launching skill:\s*(\S+)/);if(r){const c=r[1].trim();return ql[c]||c}return null}function _x(n){return n.length===0?"stack-empty":`stack-${n[0].tool_id}`}function PM(n){const e=[];let i=[];for(const a of n)if(a.type==="tool_use")i.push({type:"tool_use",tool_name:a.tool_name||"",tool_id:a.tool_id||"",input:a.input||{},timestamp:a.timestamp,isStreaming:a.isStreaming});else{if(a.type==="tool_result")continue;if(i.length>=1){const r=i[i.length-1];e.push({stackId:_x(i),tools:[...i],count:i.length,isActive:r.isStreaming===!0,timestamp:i[0].timestamp})}i=[]}if(i.length>=1){const a=i[i.length-1];e.push({stackId:_x(i),tools:[...i],count:i.length,isActive:a.isStreaming===!0,timestamp:i[0].timestamp})}return e}function Xh(){const n=document.documentElement.getAttribute("data-variant");return n==="light"||n==="dark"?n:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function NS(){const[n,e]=m.useState(Xh);return m.useEffect(()=>{const i=new MutationObserver(()=>{e(Xh())});i.observe(document.documentElement,{attributes:!0,attributeFilter:["data-variant"]});const a=()=>e(Xh());return window.addEventListener("presetChange",a),()=>{i.disconnect(),window.removeEventListener("presetChange",a)}},[]),n}const Ex=2e3;function Om(){const[n,e]=m.useState(null),[i,a]=m.useState(null),[r,c]=m.useState(null),[d,h]=m.useState(!0),[f,p]=m.useState(null),y=m.useRef({context:!1,stats:!1,projectInfo:!1}),b=m.useCallback(()=>{const x=y.current;x.context&&x.stats&&x.projectInfo&&h(!1)},[]);return m.useEffect(()=>{let x=null,w=null,E=!0;const _=()=>{const C=window.location.protocol==="https:"?"wss:":"ws:";x=new WebSocket(`${C}//${window.location.host}/ws/context`),x.onopen=()=>{console.log("[useStatsStrip] Context WebSocket connected")},x.onmessage=D=>{try{const N=JSON.parse(D.data);if(N.type==="init"||N.type==="update"){const k=N.context;k&&e({percent:k.percent??0,used:k.tokens??void 0,total:k.available?(k.tokens??0)+k.available:void 0}),y.current.context||(y.current.context=!0,b())}}catch(N){console.error("[useStatsStrip] Failed to parse context message:",N)}},x.onclose=()=>{E&&(w=setTimeout(_,Ex))},x.onerror=D=>{console.error("[useStatsStrip] Context WebSocket error:",D),x?.close()}};return _(),()=>{E=!1,w&&clearTimeout(w),x?.close()}},[b]),m.useEffect(()=>{let x=null,w=null,E=!0;const _=()=>{const C=window.location.protocol==="https:"?"wss:":"ws:";x=new WebSocket(`${C}//${window.location.host}/ws/stats`),x.onopen=()=>{console.log("[useStatsStrip] Stats WebSocket connected")},x.onmessage=D=>{try{const N=JSON.parse(D.data);a({model:N.model??null}),N.pwd&&c(k=>({pwd:N.pwd,jiraEmail:k?.jiraEmail??null,githubUsername:k?.githubUsername??null})),y.current.stats||(y.current.stats=!0,b())}catch(N){console.error("[useStatsStrip] Failed to parse stats message:",N)}},x.onclose=()=>{E&&(w=setTimeout(_,Ex))},x.onerror=D=>{console.error("[useStatsStrip] Stats WebSocket error:",D),x?.close()}};return _(),()=>{E=!1,w&&clearTimeout(w),x?.close()}},[b]),m.useEffect(()=>{(async()=>{try{const w=await fetch("/api/identity");if(w.ok){const E=await w.json();c(_=>({pwd:_?.pwd??"",jiraEmail:E.jiraEmail??null,githubUsername:E.githubUsername??null}))}}catch(w){console.error("[useStatsStrip] Failed to fetch identity:",w),p(w instanceof Error?w:new Error("Failed to fetch identity"))}finally{y.current.projectInfo=!0,b()}})()},[b]),{context:n,stats:i,projectInfo:r,isLoading:d,error:f}}const LM={pm:"#a78bfa",sm:"#60a5fa",dev:"#4ade80",tea:"#2dd4bf",reviewer:"#f87171",architect:"#fb923c",devops:"#22d3ee","ux-designer":"#f0abfc","tech-writer":"#e5e5e5",orchestrator:"#e879f9",ba:"#a3e635"},IM={pm:"PM",sm:"SM",dev:"DEV",tea:"TEA",reviewer:"REV",architect:"ARC",devops:"OPS","ux-designer":"UX","tech-writer":"TW",orchestrator:"ORC",ba:"BA"};function Dx(n){return new Date(n).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function GM(n){if("isToolStack"in n||"messages"in n)return"agent";const e=n;return e.type==="context_cleared"?"system":e.type==="user"||e.type==="bell_injected"?"user":"agent"}function BM({messages:n}){const e=m.useRef(null),[i,a]=m.useState(!0),{persona:r}=Zc(),c=NS(),{projectInfo:d}=Om(),h=m.useRef(new Map),f=m.useCallback(C=>{a(C)},[]),p=m.useCallback(()=>{e.current?.scrollToBottom("smooth")},[]),y=m.useMemo(()=>{for(let C=n.length-1;C>=0;C--)if(n[C].type==="agent"&&!n[C].isStreaming)return n[C];return null},[n]),{turns:b,toolResults:x,lastAgentItemIndex:w}=m.useMemo(()=>{const C=new Map;for(const B of n)B.type==="tool_result"&&B.tool_id&&C.set(B.tool_id,B);const D=[],N=new Map;let k=!1;for(const B of n)if(B.type!=="tool_result"){if(B.type==="user"&&zM(B.content)){const $=MM(B.content);$&&!k&&(k=!0,D.push({...B,content:$}));continue}if(B.type==="user"&&(k=!1),B.parent_id){let $=N.get(B.parent_id);$||($={parent_id:B.parent_id,type:B.subagent_type||"unknown",name:B.subagent_name||"unnamed",messages:[]},N.set(B.parent_id,$)),$.messages.push(B);continue}D.push(B)}const T=PM(D),R=new Map;for(const B of T)for(const $ of B.tools)R.set($.tool_id,B);const z=[],O=new Set,A=new Set;for(const B of D)if(B.type==="tool_use"&&B.tool_id&&R.has(B.tool_id)){const $=R.get(B.tool_id);O.has($.stackId)||(O.add($.stackId),z.push({isToolStack:!0,stack:$}))}else z.push(B);for(const[,B]of N)A.has(B.parent_id)||(A.add(B.parent_id),z.push(B));let G=-1;for(let B=z.length-1;B>=0;B--){const $=z[B];if(!("isToolStack"in $)&&!("messages"in $)&&$.type==="agent"){G=B;break}}const U=[];for(const B of z){const $=GM(B),ae=U[U.length-1];ae&&ae.speaker===$?ae.items.push(B):U.push({speaker:$,items:[B],timestamp:"timestamp"in B?B.timestamp:Date.now()})}return{turns:U,toolResults:C,lastAgentItemIndex:G}},[n]),E=(C,D,N)=>{if("isToolStack"in C)return l.jsx(pM,{stack:C.stack,toolResults:x},`stack-${C.stack.stackId}`);if("messages"in C&&"parent_id"in C){const T=C,R=h.current.get(T.parent_id)??!0;return l.jsx(xM,{type:T.type,name:T.name,messages:T.messages,defaultCollapsed:R,onCollapseChange:z=>h.current.set(T.parent_id,z)},`subagent-${T.parent_id}`)}const k=C;if(k.type==="tool_use"&&k.tool_name&&k.tool_id){if(k.tool_name==="AskUserQuestion")return null;const T=x.get(k.tool_id);return l.jsx(Rm,{toolUse:{type:"tool_use",tool_name:k.tool_name,tool_id:k.tool_id,input:k.input||{},timestamp:k.timestamp},result:T?{type:"tool_result",tool_id:T.tool_id,content:T.content||"",timestamp:T.timestamp,is_error:T.is_error,durationMs:T.durationMs}:void 0},`tool-${k.tool_id}`)}return l.jsx(CS,{message:k,isLastAgentMessage:D===w,isFirstInTurn:N},`msg-${D}-${k.timestamp}`)};if(n.length===0)return l.jsx("div",{"data-testid":"message-view",className:"message-view",children:l.jsx("div",{className:"message-view-empty",children:l.jsxs("div",{children:[l.jsx("img",{src:c==="dark"?"/images/cyclist-dark.png":"/images/cyclist-light.png",alt:"Cyclist",style:{height:"2.5rem",opacity:.6,display:"block",margin:"0 auto 0.5rem"}}),l.jsxs("div",{children:["Type ",l.jsx("code",{style:{background:"var(--bg-tertiary, #0f0f1a)",padding:"2px 6px",borderRadius:"3px",fontFamily:"var(--font-mono, monospace)"},children:"/sm"})," to start"]})]})})});let _=0;return l.jsxs("div",{"data-testid":"message-view",className:"message-view",role:"log","aria-live":"polite",children:[l.jsx(SS,{ref:e,onScrollChange:f,autoScroll:i,children:b.map((C,D)=>{if(C.speaker==="system")return C.items.forEach(()=>_++),l.jsx("div",{className:"turn-group turn-system",children:l.jsxs("div",{className:"context-cleared-bar",children:[l.jsx(Rt,{className:"context-cleared-line"}),l.jsx("span",{className:"context-cleared-label",children:"Context cleared"}),l.jsx("span",{className:"context-cleared-time",children:Dx(C.timestamp)}),l.jsx(Rt,{className:"context-cleared-line"})]})},`turn-${D}`);let N=!1;const k=r?.character||"Agent",T=r?.role||null,R=T?IM[T]||T:null,z=T?LM[T]||"#e879f9":void 0,O=d?.githubUsername||"You";return l.jsxs("div",{className:`turn-group turn-${C.speaker}`,children:[l.jsxs("div",{className:"turn-label",children:[l.jsx("span",{className:"turn-speaker",children:C.speaker==="user"?O:k}),C.speaker==="agent"&&R&&l.jsx($e,{variant:"default",className:"turn-role-badge",style:{backgroundColor:z},children:R}),l.jsx("span",{className:"turn-timestamp",children:Dx(C.timestamp)})]}),C.items.map(A=>{const G=_++,U=!("isToolStack"in A)&&!("messages"in A)&&A.type!=="tool_use",B=U&&!N;return U&&(N=!0),E(A,G,B)})]},`turn-${D}`)})}),y&&l.jsx(NM,{message:y}),l.jsx("div",{"data-testid":"auto-scroll-indicator","data-active":i.toString(),className:"auto-scroll-indicator",style:{display:"none"}}),l.jsx(Ce,{variant:"ghost",size:"icon","data-testid":"scroll-to-bottom-button",className:"scroll-to-bottom-button",onClick:p,style:{visibility:i?"hidden":"visible"},children:"↓"})]})}const Ax="cyclist-command-history",HM=100;function VM(){const[n,e]=m.useState(()=>{try{const p=localStorage.getItem(Ax);return p?JSON.parse(p):[]}catch{return[]}}),i=m.useRef(-1),a=m.useRef(""),r=m.useCallback(p=>{try{localStorage.setItem(Ax,JSON.stringify(p))}catch{}},[]),c=m.useCallback(p=>{p.trim()&&e(y=>{if(y.length>0&&y[y.length-1]===p)return y;const b=[...y,p];return b.length>HM&&b.shift(),r(b),b})},[r]),d=m.useCallback(p=>{if(n.length===0)return null;if(i.current===-1)a.current=p,i.current=n.length-1;else if(i.current>0)i.current--;else return null;return n[i.current]},[n]),h=m.useCallback(()=>{if(i.current===-1)return null;if(i.current++,i.current>=n.length){i.current=-1;const p=a.current;return a.current="",p}return n[i.current]},[n]),f=m.useCallback(()=>{i.current=-1,a.current=""},[]);return{addToHistory:c,navigateUp:d,navigateDown:h,resetNavigation:f}}const jS=[{name:"/add",description:"Add files to context"},{name:"/benchmark",description:"Compare an agent's performance against a stored baseline"},{name:"/benchmark-control",description:"Create control baseline for a scenario (shortcut for /benchmark control <agent>)"},{name:"/bug",description:"Report a bug"},{name:"/clear",description:"Clear conversation history"},{name:"/compact",description:"Toggle compact mode"},{name:"/config",description:"Show configuration"},{name:"/cost",description:"Show session cost"},{name:"/doctor",description:"Check system health"},{name:"/help",description:"Show available commands"},{name:"/init",description:"Initialize CLAUDE.md"},{name:"/job-fair",description:"Discover which characters in a theme excel at each role"},{name:"/login",description:"Authenticate with Anthropic"},{name:"/logout",description:"Clear authentication"},{name:"/memory",description:"Edit CLAUDE.md memory"},{name:"/model",description:"Switch Claude model"},{name:"/permissions",description:"View/edit permissions"},{name:"/pf-architect",description:"System Architect - Technical design and architecture"},{name:"/pf-ba",description:"Business Analyst - Requirements discovery and stakeholder analysis"},{name:"/pf-brainstorming",description:"Structured problem-solving brainstorm session"},{name:"/pf-check",description:"Run quality gates (lint, type check, tests) before handoff"},{name:"/pf-chore",description:"Quick commit for small changes without full git-cleanup ceremony"},{name:"/pf-close-epic",description:"Close an epic - verify completion, update status, and archive context"},{name:"/pf-continue-session",description:"Resume work from a saved checkpoint after context circuit breaker"},{name:"/pf-create-branches-from-story",description:"Create feature branches in both repos from a story"},{name:"/pf-dev",description:"Developer - Feature implementation and coding"},{name:"/pf-devops",description:"DevOps Engineer - Infrastructure and deployment automation"},{name:"/pf-fix-blocker",description:"Quick alias for /patch - fix blocking issue during story work"},{name:"/pf-git-cleanup",description:"Clean up git repos by organizing changes into proper commits/branches by initiative"},{name:"/pf-health-check",description:"Check Pennyfarthing installation health and apply updates"},{name:"/pf-help",description:"Context-aware help for Pennyfarthing commands, agents, and workflows"},{name:"/pf-new-work",description:"Start the next available story from the sprint backlog"},{name:"/pf-orchestrator",description:"Orchestrator - Coordinator of all agents and meta operations"},{name:"/pf-parallel-work",description:"Start parallel work in a new worktree"},{name:"/pf-party-mode",description:"Creative brainstorming and multi-agent discussion"},{name:"/pf-patch",description:"Interrupt-driven bug fix during active story work"},{name:"/pf-permissions",description:"View and manage runtime permission grants - list, grant, revoke, or show details"},{name:"/pf-pm",description:"Product Manager - Strategic planning and prioritization"},{name:"/pf-prime",description:"Load essential project context at agent activation"},{name:"/pf-release",description:"Interactive stepped release with verification gates"},{name:"/pf-repo-status",description:"Check git status of all project repos"},{name:"/pf-retro",description:"Facilitate a sprint retrospective"},{name:"/pf-reviewer",description:"Code Reviewer - Critical code review and quality enforcement"},{name:"/pf-run-ci",description:"Detect and run CI locally"},{name:"/pf-setup",description:"/setup - Interactive Project Setup"},{name:"/pf-sm",description:"Scrum Master - Story coordination and sprint management"},{name:"/pf-sprint",description:"Sprint status, backlog, and story management - check status, find work, archive completed stories"},{name:"/pf-sprint-planning",description:"Facilitate sprint planning session"},{name:"/pf-standalone",description:"Wrap current changes into a standalone Jira story, branch, PR, and merge"},{name:"/pf-start-epic",description:"Start an epic - move to current sprint and generate tech context"},{name:"/pf-sync-epic-to-jira",description:"Sync Pennyfarthing epic to Jira MSSCI project using jira CLI"},{name:"/pf-sync-work-with-sprint",description:"Sync Pennyfarthing work session with unified sprint status"},{name:"/pf-tea",description:"Test Engineer/Architect - Test strategy and TDD"},{name:"/pf-tech-writer",description:"Technical Writer - Documentation creation and maintenance"},{name:"/pf-theme",description:"Manage persona themes - list, show, set, create, or interactive wizard"},{name:"/pf-update-domain-docs",description:"Update CLAUDE-*.md domain documentation files based on current codebase"},{name:"/pf-ux-designer",description:"UX Designer - User experience design and UI patterns"},{name:"/pf-work",description:"Resume work or start new - smart entry point that picks up where you left off"},{name:"/pf-workflow",description:"List available workflows, show current workflow details, and switch workflows mid-session. Use when checking available workflow types (TDD, trivial, agent-docs), viewing current workflow phase, switching to a different workflow pattern, or managing BikeLane stepped workflows."},{name:"/pr-comments",description:"View PR comments"},{name:"/review",description:"Start code review"},{name:"/solo",description:"Run a single agent on a scenario with absolute rubric scoring"},{name:"/status",description:"Show session status"},{name:"/terminal-setup",description:"Configure terminal"},{name:"/vim",description:"Toggle vim mode"}].sort((n,e)=>n.name.localeCompare(e.name)),TS="cyclist:command-frequency";function kS(){if(typeof localStorage>"u")return{};try{const n=localStorage.getItem(TS);return n?JSON.parse(n):{}}catch{return{}}}function RS(n){if(typeof localStorage>"u")return;const e=kS();e[n]=(e[n]||0)+1,localStorage.setItem(TS,JSON.stringify(e))}function FM(n){const e=n.toLowerCase(),i=kS();return jS.filter(a=>a.name.toLowerCase().startsWith(e)).sort((a,r)=>{const c=i[a.name]||0,d=i[r.name]||0;return d!==c?d-c:a.name.localeCompare(r.name)})}function UM(n){const e=m.useMemo(()=>jS,[n]),[i,a]=m.useState({visible:!1,commands:[],selectedIndex:0,prefix:""}),r=m.useCallback(b=>FM(b),[e,n]),c=m.useCallback(b=>{const x=r(b);a({visible:!0,commands:x,selectedIndex:0,prefix:b})},[r]),d=m.useCallback(()=>{a({visible:!1,commands:[],selectedIndex:0,prefix:""})},[]),h=m.useCallback(b=>{const x=r(b);x.length===0?d():a(w=>({...w,commands:x,selectedIndex:0,prefix:b}))},[r,d]),f=m.useCallback(()=>{a(b=>{if(b.commands.length===0)return b;const x=b.selectedIndex<=0?b.commands.length-1:b.selectedIndex-1;return{...b,selectedIndex:x}})},[]),p=m.useCallback(()=>{a(b=>{if(b.commands.length===0)return b;const x=b.selectedIndex>=b.commands.length-1?0:b.selectedIndex+1;return{...b,selectedIndex:x}})},[]),y=m.useCallback(()=>{if(!i.visible||i.commands.length===0)return null;const b=i.commands[i.selectedIndex];return d(),b?.name&&RS(b.name),b?.name||null},[i,d]);return{state:i,showCompletion:c,hideCompletion:d,updateCompletion:h,navigateUp:f,navigateDown:p,selectCurrent:y,isVisible:i.visible}}function OS(n){const e=n+"CollectionProvider",[i,a]=cn(e),[r,c]=i(e,{collectionRef:{current:null},itemMap:new Map}),d=_=>{const{scope:C,children:D}=_,N=ue.useRef(null),k=ue.useRef(new Map).current;return l.jsx(r,{scope:C,itemMap:k,collectionRef:N,children:D})};d.displayName=e;const h=n+"CollectionSlot",f=Pa(h),p=ue.forwardRef((_,C)=>{const{scope:D,children:N}=_,k=c(h,D),T=Ie(C,k.collectionRef);return l.jsx(f,{ref:T,children:N})});p.displayName=h;const y=n+"CollectionItemSlot",b="data-radix-collection-item",x=Pa(y),w=ue.forwardRef((_,C)=>{const{scope:D,children:N,...k}=_,T=ue.useRef(null),R=Ie(C,T),z=c(y,D);return ue.useEffect(()=>(z.itemMap.set(T,{ref:T,...k}),()=>{z.itemMap.delete(T)})),l.jsx(x,{[b]:"",ref:R,children:N})});w.displayName=y;function E(_){const C=c(n+"CollectionConsumer",_);return ue.useCallback(()=>{const N=C.collectionRef.current;if(!N)return[];const k=Array.from(N.querySelectorAll(`[${b}]`));return Array.from(C.itemMap.values()).sort((z,O)=>k.indexOf(z.ref.current)-k.indexOf(O.ref.current))},[C.collectionRef,C.itemMap])}return[{Provider:d,Slot:p,ItemSlot:w},E,a]}var $M=m.createContext(void 0);function Kc(n){const e=m.useContext($M);return n||e||"ltr"}var Qh="rovingFocusGroup.onEntryFocus",WM={bubbles:!1,cancelable:!0},hr="RovingFocusGroup",[Nf,zS,qM]=OS(hr),[YM,MS]=cn(hr,[qM]),[XM,QM]=YM(hr),PS=m.forwardRef((n,e)=>l.jsx(Nf.Provider,{scope:n.__scopeRovingFocusGroup,children:l.jsx(Nf.Slot,{scope:n.__scopeRovingFocusGroup,children:l.jsx(ZM,{...n,ref:e})})}));PS.displayName=hr;var ZM=m.forwardRef((n,e)=>{const{__scopeRovingFocusGroup:i,orientation:a,loop:r=!1,dir:c,currentTabStopId:d,defaultCurrentTabStopId:h,onCurrentTabStopIdChange:f,onEntryFocus:p,preventScrollOnEntryFocus:y=!1,...b}=n,x=m.useRef(null),w=Ie(e,x),E=Kc(c),[_,C]=_n({prop:d,defaultProp:h??null,onChange:f,caller:hr}),[D,N]=m.useState(!1),k=Gt(p),T=zS(i),R=m.useRef(!1),[z,O]=m.useState(0);return m.useEffect(()=>{const A=x.current;if(A)return A.addEventListener(Qh,k),()=>A.removeEventListener(Qh,k)},[k]),l.jsx(XM,{scope:i,orientation:a,dir:E,loop:r,currentTabStopId:_,onItemFocus:m.useCallback(A=>C(A),[C]),onItemShiftTab:m.useCallback(()=>N(!0),[]),onFocusableItemAdd:m.useCallback(()=>O(A=>A+1),[]),onFocusableItemRemove:m.useCallback(()=>O(A=>A-1),[]),children:l.jsx(je.div,{tabIndex:D||z===0?-1:0,"data-orientation":a,...b,ref:w,style:{outline:"none",...n.style},onMouseDown:we(n.onMouseDown,()=>{R.current=!0}),onFocus:we(n.onFocus,A=>{const G=!R.current;if(A.target===A.currentTarget&&G&&!D){const U=new CustomEvent(Qh,WM);if(A.currentTarget.dispatchEvent(U),!U.defaultPrevented){const B=T().filter(M=>M.focusable),$=B.find(M=>M.active),ae=B.find(M=>M.id===_),W=[$,ae,...B].filter(Boolean).map(M=>M.ref.current);GS(W,y)}}R.current=!1}),onBlur:we(n.onBlur,()=>N(!1))})})}),LS="RovingFocusGroupItem",IS=m.forwardRef((n,e)=>{const{__scopeRovingFocusGroup:i,focusable:a=!0,active:r=!1,tabStopId:c,children:d,...h}=n,f=Mt(),p=c||f,y=QM(LS,i),b=y.currentTabStopId===p,x=zS(i),{onFocusableItemAdd:w,onFocusableItemRemove:E,currentTabStopId:_}=y;return m.useEffect(()=>{if(a)return w(),()=>E()},[a,w,E]),l.jsx(Nf.ItemSlot,{scope:i,id:p,focusable:a,active:r,children:l.jsx(je.span,{tabIndex:b?0:-1,"data-orientation":y.orientation,...h,ref:e,onMouseDown:we(n.onMouseDown,C=>{a?y.onItemFocus(p):C.preventDefault()}),onFocus:we(n.onFocus,()=>y.onItemFocus(p)),onKeyDown:we(n.onKeyDown,C=>{if(C.key==="Tab"&&C.shiftKey){y.onItemShiftTab();return}if(C.target!==C.currentTarget)return;const D=e2(C,y.orientation,y.dir);if(D!==void 0){if(C.metaKey||C.ctrlKey||C.altKey||C.shiftKey)return;C.preventDefault();let k=x().filter(T=>T.focusable).map(T=>T.ref.current);if(D==="last")k.reverse();else if(D==="prev"||D==="next"){D==="prev"&&k.reverse();const T=k.indexOf(C.currentTarget);k=y.loop?t2(k,T+1):k.slice(T+1)}setTimeout(()=>GS(k))}}),children:typeof d=="function"?d({isCurrentTabStop:b,hasTabStop:_!=null}):d})})});IS.displayName=LS;var KM={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function JM(n,e){return e!=="rtl"?n:n==="ArrowLeft"?"ArrowRight":n==="ArrowRight"?"ArrowLeft":n}function e2(n,e,i){const a=JM(n.key,i);if(!(e==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(e==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return KM[a]}function GS(n,e=!1){const i=document.activeElement;for(const a of n)if(a===i||(a.focus({preventScroll:e}),document.activeElement!==i))return}function t2(n,e){return n.map((i,a)=>n[(e+a)%n.length])}var n2=PS,i2=IS,BS="Toggle",zm=m.forwardRef((n,e)=>{const{pressed:i,defaultPressed:a,onPressedChange:r,...c}=n,[d,h]=_n({prop:i,onChange:r,defaultProp:a??!1,caller:BS});return l.jsx(je.button,{type:"button","aria-pressed":d,"data-state":d?"on":"off","data-disabled":n.disabled?"":void 0,...c,ref:e,onClick:we(n.onClick,()=>{n.disabled||h(!d)})})});zm.displayName=BS;var HS=zm,ss="ToggleGroup",[VS]=cn(ss,[MS]),FS=MS(),Mm=ue.forwardRef((n,e)=>{const{type:i,...a}=n;if(i==="single"){const r=a;return l.jsx(s2,{...r,ref:e})}if(i==="multiple"){const r=a;return l.jsx(a2,{...r,ref:e})}throw new Error(`Missing prop \`type\` expected on \`${ss}\``)});Mm.displayName=ss;var[US,$S]=VS(ss),s2=ue.forwardRef((n,e)=>{const{value:i,defaultValue:a,onValueChange:r=()=>{},...c}=n,[d,h]=_n({prop:i,defaultProp:a??"",onChange:r,caller:ss});return l.jsx(US,{scope:n.__scopeToggleGroup,type:"single",value:ue.useMemo(()=>d?[d]:[],[d]),onItemActivate:h,onItemDeactivate:ue.useCallback(()=>h(""),[h]),children:l.jsx(WS,{...c,ref:e})})}),a2=ue.forwardRef((n,e)=>{const{value:i,defaultValue:a,onValueChange:r=()=>{},...c}=n,[d,h]=_n({prop:i,defaultProp:a??[],onChange:r,caller:ss}),f=ue.useCallback(y=>h((b=[])=>[...b,y]),[h]),p=ue.useCallback(y=>h((b=[])=>b.filter(x=>x!==y)),[h]);return l.jsx(US,{scope:n.__scopeToggleGroup,type:"multiple",value:d,onItemActivate:f,onItemDeactivate:p,children:l.jsx(WS,{...c,ref:e})})});Mm.displayName=ss;var[o2,r2]=VS(ss),WS=ue.forwardRef((n,e)=>{const{__scopeToggleGroup:i,disabled:a=!1,rovingFocus:r=!0,orientation:c,dir:d,loop:h=!0,...f}=n,p=FS(i),y=Kc(d),b={role:"group",dir:y,...f};return l.jsx(o2,{scope:i,rovingFocus:r,disabled:a,children:r?l.jsx(n2,{asChild:!0,...p,orientation:c,dir:y,loop:h,children:l.jsx(je.div,{...b,ref:e})}):l.jsx(je.div,{...b,ref:e})})}),wc="ToggleGroupItem",qS=ue.forwardRef((n,e)=>{const i=$S(wc,n.__scopeToggleGroup),a=r2(wc,n.__scopeToggleGroup),r=FS(n.__scopeToggleGroup),c=i.value.includes(n.value),d=a.disabled||n.disabled,h={...n,pressed:c,disabled:d},f=ue.useRef(null);return a.rovingFocus?l.jsx(i2,{asChild:!0,...r,focusable:!d,active:c,ref:f,children:l.jsx(Nx,{...h,ref:e})}):l.jsx(Nx,{...h,ref:e})});qS.displayName=wc;var Nx=ue.forwardRef((n,e)=>{const{__scopeToggleGroup:i,value:a,...r}=n,c=$S(wc,i),d={role:"radio","aria-checked":n.pressed,"aria-pressed":void 0},h=c.type==="single"?d:void 0;return l.jsx(zm,{...h,...r,ref:e,onPressedChange:f=>{f?c.onItemActivate(a):c.onItemDeactivate(a)}})}),YS=Mm,XS=qS;const QS=Bf("inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground"},size:{default:"h-9 px-2 min-w-9",sm:"h-8 px-1.5 min-w-8",lg:"h-10 px-2.5 min-w-10"}},defaultVariants:{variant:"default",size:"default"}}),l2=m.forwardRef(({className:n,variant:e,size:i,...a},r)=>l.jsx(HS,{ref:r,className:ye(QS({variant:e,size:i,className:n})),...a}));l2.displayName=HS.displayName;const ZS=m.createContext({size:"default",variant:"default"}),KS=m.forwardRef(({className:n,variant:e,size:i,children:a,...r},c)=>l.jsx(YS,{ref:c,className:ye("flex items-center justify-center gap-1",n),...r,children:l.jsx(ZS.Provider,{value:{variant:e,size:i},children:a})}));KS.displayName=YS.displayName;const JS=m.forwardRef(({className:n,children:e,variant:i,size:a,...r},c)=>{const d=m.useContext(ZS);return l.jsx(XS,{ref:c,className:ye(QS({variant:d.variant||i,size:d.size||a}),n),...r,children:e})});JS.displayName=XS.displayName;const jx=["plan","manual","accept"],Zh={plan:"Plan",manual:"Manual",accept:"Accept"},Tx={plan:"Read-only exploration mode",manual:"Ask for permission before actions",accept:"Auto-accept file edits"},c2={plan:"plan",manual:"default",accept:"acceptEdits"},u2={plan:"plan",default:"manual",acceptEdits:"accept"},kx={1:"plan",2:"manual",3:"accept"};function d2(n){m.useEffect(()=>{const e=i=>{(i.metaKey||i.ctrlKey)&&kx[i.key]&&(i.preventDefault(),n(kx[i.key]))};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[n])}function h2(){const[n,e]=m.useState("manual"),[i,a]=m.useState(!0),r=m.useRef(null);m.useEffect(()=>{const h=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/claude`,f=new WebSocket(h);r.current=f,f.onopen=()=>{f.send(JSON.stringify({type:"getMode"}))},f.onmessage=y=>{try{const b=JSON.parse(y.data);if(b.type==="mode"&&b.mode){const x=u2[b.mode]||"manual";e(x),a(!1),console.log("[ModeSwitch] Mode synced:",b.mode,"->",x)}}catch(b){console.error("[ModeSwitch] Failed to parse mode response:",b)}},f.onerror=()=>{a(!1)};const p=setTimeout(()=>{i&&a(!1)},2e3);return()=>{clearTimeout(p),f.readyState===WebSocket.OPEN&&f.close(),r.current=null}},[]);const c=m.useCallback(d=>{const h=c2[d];r.current&&r.current.readyState===WebSocket.OPEN?(r.current.send(JSON.stringify({type:"setMode",mode:h})),e(d),console.log("[ModeSwitch] Mode set to:",d,"->",h)):(e(d),console.warn("[ModeSwitch] WebSocket not connected, mode set locally only"))},[]);return{mode:n,setMode:c,isLoading:i}}function f2({mode:n,defaultMode:e="manual",onModeChange:i,className:a="",disabled:r=!1}){const[c,d]=m.useState(e),[h,f]=m.useState(!1),p=n??c;m.useEffect(()=>{const w=window.matchMedia("(prefers-reduced-motion: reduce)");f(w.matches);const E=_=>{f(_.matches)};return w.addEventListener("change",E),()=>w.removeEventListener("change",E)},[]);const y=jx.indexOf(p),b=m.useCallback(w=>{r||(n||d(w),i?.(w))},[n,r,i]),x=m.useCallback(w=>{w&&b(w)},[b]);return l.jsxs("div",{className:ye("mode-switch",r&&"mode-switch--disabled",h&&"reduced-motion",a),"data-testid":"mode-switch",style:h?{transition:"none"}:void 0,children:[l.jsx("div",{className:"mode-switch__highlight","data-testid":"mode-highlight",style:{transform:`translateX(${y*100}%)`,transition:h?"none":void 0},"data-mode":p}),l.jsx(St,{delayDuration:400,children:l.jsx(KS,{type:"single",value:p,onValueChange:x,disabled:r,className:"relative z-[1] gap-0","aria-label":"Permission mode",children:jx.map(w=>{const E=p===w;return l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(JS,{value:w,"data-mode":w,"data-testid":`mode-${w}`,"aria-label":`${Zh[w]} mode: ${Tx[w]}`,className:ye("mode-option",E&&"active"),children:Zh[w]})}),l.jsx(Te,{side:"bottom",children:Tx[w]})]},w)})})}),l.jsx("div",{className:"visually-hidden",role:"status","aria-live":"polite",children:`${Zh[p]} mode selected`})]})}const Yl=["image/png","image/jpeg","image/gif","image/webp"],m2=20*1024*1024;function p2({commands:n,selectedIndex:e,visible:i,onSelect:a}){return!i||n.length===0?null:l.jsx("div",{className:"completion-popup","data-testid":"completion-popup",children:n.map((r,c)=>l.jsxs("div",{className:`completion-item ${c===e?"selected":""}`,onClick:()=>a(c),"data-testid":`completion-item-${c}`,children:[l.jsx("span",{className:"completion-name",children:r.name}),l.jsx("span",{className:"completion-desc",children:r.description})]},r.name))})}function g2(n){return n?n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"):""}function v2({queue:n,bellMode:e,onRemove:i,onClear:a,onInject:r}){return n.length===0?null:l.jsx(St,{delayDuration:300,children:l.jsxs("div",{className:"queue-display","data-testid":"queue-display",children:[l.jsxs("div",{className:"queue-header",children:[l.jsxs("span",{className:"queue-count",children:[n.length," queued"]}),e&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx($e,{variant:"secondary",className:"queue-mode-badge bell-mode",children:"🔔"})}),l.jsx(Te,{children:"Bell mode active - messages inject via hook"})]}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"sm",type:"button",className:"queue-clear-btn",onClick:a,children:"Clear"})}),l.jsx(Te,{children:"Clear all queued messages"})]})]}),l.jsx("ul",{className:"queue-list",children:n.map((c,d)=>{const h=c.text.length>60?c.text.substring(0,60)+"...":c.text,f=c.images&&c.images.length>0;return l.jsxs("li",{className:"queue-item","data-testid":`queue-item-${d}`,children:[l.jsx("span",{className:"queue-item-text",children:g2(h)}),f&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsxs($e,{variant:"outline",className:"queue-image-indicator",children:["📎",c.images.length]})}),l.jsx(Te,{children:`${c.images.length} image(s) attached`})]}),l.jsxs("div",{className:"queue-item-actions",children:[r&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"icon",type:"button",className:"queue-item-inject",onClick:()=>r(d),children:"▶"})}),l.jsx(Te,{children:"Send now (abort current and send this message)"})]}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"icon",type:"button",className:"queue-item-remove",onClick:()=>i(d),children:"×"})}),l.jsx(Te,{children:"Remove from queue"})]})]})]},d)})})]})})}function y2({images:n,onRemove:e}){return n.length===0?null:l.jsx(St,{delayDuration:300,children:l.jsx("div",{className:"image-preview","data-testid":"image-preview",children:n.map((i,a)=>l.jsxs("div",{className:"image-preview-item",children:[l.jsx("img",{src:i.dataUrl,alt:i.filename}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"icon",type:"button",className:"image-remove",onClick:()=>e(a),children:"X"})}),l.jsx(Te,{children:"Remove image"})]})]},a))})})}function b2({onSubmit:n,isProcessing:e=!1,placeholder:i,onInject:a}){const r=m.useRef(null),[c,d]=m.useState(""),[h,f]=m.useState([]),{mode:p,setMode:y}=h2();d2(y);const{addToHistory:b,navigateUp:x,navigateDown:w,resetNavigation:E}=VM(),{state:_,showCompletion:C,hideCompletion:D,updateCompletion:N,navigateUp:k,navigateDown:T,selectCurrent:R,isVisible:z}=UM(),{queue:O,queueCount:A,bellMode:G,queueMessage:U,removeFromQueue:B,clearQueue:$,setProcessing:ae,resumeQueue:ne}=gS();m.useEffect(()=>{ae(e)},[e,ae]),m.useEffect(()=>{const V=Y=>{d(Y.detail.prompt),r.current?.focus()};return window.addEventListener("cyclist:suggest-prompt",V),()=>{window.removeEventListener("cyclist:suggest-prompt",V)}},[]);const W=m.useCallback(async V=>{let Y=null;if(V.items){for(const le of V.items)if(le.type&&Yl.includes(le.type)){Y=le.getAsFile();break}}if(!Y&&V.files?.length>0){for(const le of V.files)if(le.type&&Yl.includes(le.type)){Y=le;break}}return Y?Y.size>m2?(console.warn("Image too large:",Y.size),!1):new Promise(le=>{const X=new FileReader;X.onload=()=>{const ce=X.result,de=Y.name||`Pasted Image.${Y.type.split("/")[1]||"png"}`;f(De=>[...De,{dataUrl:ce,mimeType:Y.type,filename:de}]),le(!0)},X.onerror=()=>le(!1),X.readAsDataURL(Y)}):!1},[]),M=m.useCallback(V=>{f(Y=>Y.filter((le,X)=>X!==V))},[]),K=m.useCallback(()=>{if(!r.current)return null;const V=r.current.selectionStart,Y=c;let le=V;for(;le>0&&Y[le-1]!==" "&&Y[le-1]!==`
64
- `;)le--;const X=Y.substring(le,V);return X.startsWith("/")?{prefix:X,start:le,end:V}:null},[c]),q=m.useCallback(V=>{const Y=K();if(!Y){d(ce=>ce+V);return}const{start:le,end:X}=Y;d(ce=>ce.substring(0,le)+V+ce.substring(X)),setTimeout(()=>{if(r.current){const ce=le+V.length;r.current.selectionStart=r.current.selectionEnd=ce}},0)},[K]),he=m.useCallback(()=>{const V=c.trim();if(!(!V&&h.length===0)){if(e){U({text:V,images:[...h]})&&(d(""),f([]),r.current?.focus());return}if(b(V),E(),V.startsWith("/")){const Y=V.split(/\s/)[0];RS(Y)}ne(),window.dispatchEvent(new CustomEvent("cyclist:user-submit")),n(V,h),d(""),f([]),r.current?.focus()}},[c,h,e,U,b,E,ne,n]),Se=m.useCallback(V=>{if(V.key==="Tab"&&!V.shiftKey&&!V.ctrlKey&&!V.altKey){if(z){V.preventDefault();const le=R();le&&q(le);return}const Y=K();if(Y){V.preventDefault(),C(Y.prefix);return}}if(V.key==="Escape"&&z){V.preventDefault(),D();return}if(V.key==="Enter"&&!V.shiftKey){if(z){V.preventDefault();const Y=R();Y&&q(Y);return}V.preventDefault(),he();return}if(V.key==="ArrowUp"&&!V.shiftKey&&!V.ctrlKey&&!V.altKey){if(z){V.preventDefault(),k();return}if(r.current?.selectionStart===0){const Y=x(c);if(Y!==null){V.preventDefault(),d(Y);return}}}if(V.key==="ArrowDown"&&!V.shiftKey&&!V.ctrlKey&&!V.altKey){if(z){V.preventDefault(),T();return}if(r.current?.selectionEnd===c.length){const Y=w();if(Y!==null){V.preventDefault(),d(Y);return}}}},[z,R,q,K,C,D,he,k,T,x,w,c]),I=m.useCallback(V=>{const Y=V.target.value;if(d(Y),Y==="/"&&!z){C("/");return}if(z){const le=K();le?N(le.prefix):D()}},[z,C,K,N,D]),L=m.useCallback(async V=>{const Y=V.clipboardData;if(!Y)return;let le=!1;if(Y.items){for(const X of Y.items)if(X.type&&Yl.includes(X.type)){le=!0;break}}if(!le&&Y.files?.length>0){for(const X of Y.files)if(X.type&&Yl.includes(X.type)){le=!0;break}}le&&(V.preventDefault(),await W(Y))},[W]),ee=m.useCallback(V=>{const Y=_.commands[V];Y&&(q(Y.name),D())},[_.commands,q,D]);return l.jsxs("div",{className:"editor-container","data-testid":"editor-container",children:[l.jsx(f2,{mode:p,onModeChange:y,className:"editor-mode-switch"}),l.jsxs("div",{className:"editor-wrapper",id:"editor-wrapper",children:[l.jsx(y2,{images:h,onRemove:M}),l.jsx("textarea",{ref:r,id:"editor-textarea",className:"editor-textarea",value:c,onChange:I,onKeyDown:Se,onPaste:L,placeholder:i,spellCheck:!1,autoFocus:!0,"data-testid":"editor-textarea"}),l.jsx(p2,{commands:_.commands,selectedIndex:_.selectedIndex,visible:z,onSelect:ee})]}),l.jsx(v2,{queue:O,bellMode:G,onRemove:B,onClear:$,onInject:a})]})}function x2(){const[n,e]=m.useState(null),i=m.useCallback(c=>d=>{e(c)},[]),a=m.useCallback(()=>{e(null)},[]),r=m.useCallback(c=>n===c,[n]);return{handleFocus:i,handleBlur:a,isFocused:r}}function w2({currentAgent:n,onAgentSwitch:e}){const[i,a]=m.useState(!1),[r,c]=m.useState([]),d=m.useRef(null);m.useEffect(()=>{fetch("/api/theme-agents/full").then(f=>f.ok?f.json():null).then(f=>{f?.agents&&c(f.agents)}).catch(()=>{})},[]),m.useEffect(()=>{if(!i)return;const f=p=>{d.current&&!d.current.contains(p.target)&&a(!1)};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[i]),m.useEffect(()=>{if(!i)return;const f=p=>{p.key==="Escape"&&(p.stopPropagation(),a(!1))};return document.addEventListener("keydown",f,!0),()=>document.removeEventListener("keydown",f,!0)},[i]);const h=m.useCallback(f=>{f.role!==n&&(e?.(f.role),a(!1))},[n,e]);return l.jsxs("div",{className:"agent-quick-picker-wrapper",ref:d,children:[l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"icon",type:"button",className:`btn-toggle agent-picker-toggle ${i?"active":""}`,"data-testid":"agent-quick-picker",onClick:()=>a(f=>!f),"aria-label":"Switch agent","aria-expanded":i,"aria-haspopup":"listbox",children:l.jsx(lz,{className:"h-4 w-4"})})}),l.jsx(Te,{children:"Switch Agent"})]}),i&&l.jsx("div",{className:"agent-quick-picker-dropdown","data-testid":"agent-quick-picker-dropdown",role:"listbox","aria-label":"Available agents",children:r.map(f=>{const p=f.role===n;return l.jsx("div",{className:`agent-quick-picker-option ${p?"current":""}`,"data-testid":`agent-option-${f.role}`,role:"option","aria-selected":p,"aria-label":`${f.role} (${f.character})`,title:f.character,onClick:()=>h(f),children:l.jsx("span",{className:"agent-option-role",children:f.role})},f.role)})})]})}function S2({isRunning:n,isStopping:e=!1,onStop:i,onForceStop:a,onReset:r,bellMode:c=!1,relayMode:d=!1,onBellModeChange:h,onRelayModeChange:f,contextPercent:p=0,currentAgent:y=null,onTirePump:b,onAgentSwitch:x}){const w=m.useRef(0),E=500,{handleFocus:_,handleBlur:C,isFocused:D}=x2(),N=m.useCallback(k=>{if(k.key!=="Escape"&&k.keyCode!==27||!n)return;const T=Date.now();T-w.current<E&&a?a():i(),w.current=T},[n,i,a]);return m.useEffect(()=>(document.addEventListener("keydown",N),()=>{document.removeEventListener("keydown",N)}),[N]),l.jsx(St,{delayDuration:300,children:l.jsxs("div",{className:"control-bar","data-testid":"control-bar",children:[l.jsxs("div",{className:"control-bar-toggles",children:[l.jsx(w2,{currentAgent:y,onAgentSwitch:x}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"icon",type:"button",className:`btn-toggle bell-toggle ${c?"active":""}`,"data-testid":"bell-mode-toggle",onClick:()=>h?.(!c),"aria-pressed":c,"aria-label":"Bell mode - inject queued messages via hook",children:l.jsx(VO,{className:"h-4 w-4"})})}),l.jsx(Te,{children:"Bell Mode: Inject queued messages during tool use (Cmd+B)"})]}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"icon",type:"button",className:`btn-toggle relay-toggle ${d?"active":""}`,"data-testid":"relay-toggle",onClick:()=>f?.(!d),"aria-pressed":d,"aria-label":"Relay mode - auto-handoff to next agent",children:l.jsx(hz,{className:"h-4 w-4"})})}),l.jsx(Te,{children:"Relay Mode: Auto-handoff to next agent (Cmd+4)"})]}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"icon",type:"button",className:`btn-toggle pump-toggle ${p>=70?"warning":""}`,"data-testid":"pump-toggle",onClick:b,disabled:!y,"aria-label":"TirePump: Clear context and reload agent",children:l.jsx(nz,{className:"h-4 w-4"})})}),l.jsx(Te,{children:y?`TirePump: Clear context (${p}%) and reload ${y}`:"TirePump: No agent loaded"})]})]}),l.jsxs(Ce,{variant:"destructive",type:"button",className:`btn-stop danger ${e?"stopping":""} ${n&&!e?"throbbing":""} ${D("stop")?"focused focus-visible":""}`,"data-testid":"stop-button",onClick:i,disabled:!n||e,"aria-busy":e,"aria-label":"Stop Claude",onFocus:_("stop"),onBlur:C,children:[l.jsx("span",{"data-icon":"stop",className:"icon"}),e?l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"spinner","data-loading":!0}),"Stopping..."]}):"Stop"]}),l.jsx(Ce,{variant:"outline",type:"button",className:`btn-reset ${D("reset")?"focused focus-visible":""}`,"data-testid":"reset-button",onClick:r,"aria-label":"Reset session",onFocus:_("reset"),onBlur:C,children:"Reset"})]})})}function C2(){const[n,e]=m.useState(!1),[i,a]=m.useState(!1),[r,c]=m.useState(!1),[d,h]=m.useState(!1),[f,p]=m.useState(0),[y,b]=m.useState(null),{abort:x,clear:w,clearAndReload:E,send:_,onMessage:C,onComplete:D,onError:N,isConnected:k}=dr();m.useEffect(()=>{function B(W){const M=W?.workflow,K=!!M?.bell_mode,q=!!M?.relay_mode;console.log("[ControlBar] Settings updated:",{bellMode:K,relayMode:q}),c(K),h(q)}async function $(){try{console.log("[ControlBar] Loading settings via REST");const W=await fetch("/api/settings");if(W.ok){const M=await W.json();B(M)}}catch(W){console.error("[ControlBar] Failed to load settings:",W)}}console.log("[ControlBar] useEffect mount - loading settings"),$(),console.log("[ControlBar] Connecting to /ws/settings for real-time sync");const ae=window.location.protocol==="https:"?"wss:":"ws:",ne=new WebSocket(`${ae}//${window.location.host}/ws/settings`);return ne.onmessage=W=>{try{const M=JSON.parse(W.data);(M.type==="init"||M.type==="update")&&B(M.settings)}catch(M){console.error("[ControlBar] Failed to parse WebSocket message:",M)}},ne.onerror=W=>{console.error("[ControlBar] WebSocket error:",W)},()=>{ne.close()}},[]),m.useEffect(()=>{const B=window.location.protocol==="https:"?"wss:":"ws:",$=new WebSocket(`${B}//${window.location.host}/ws/context`);return $.onmessage=ae=>{try{const ne=JSON.parse(ae.data);if(ne.type==="init"||ne.type==="update"){const W=ne.context?.percent??0;p(W)}}catch(ne){console.error("[ControlBar] Failed to parse context message:",ne)}},()=>{$.close()}},[]),m.useEffect(()=>{const B=window.location.protocol==="https:"?"wss:":"ws:",$=new WebSocket(`${B}//${window.location.host}/ws/persona`);return $.onmessage=ae=>{try{const ne=JSON.parse(ae.data);b(ne?.slug??null)}catch(ne){console.error("[ControlBar] Failed to parse persona message:",ne)}},()=>{$.close()}},[]),m.useEffect(()=>{if(!k)return;const B=()=>{e(!0),a(!1)},$=()=>{e(!1),a(!1)},ae=()=>{e(!1),a(!1)},ne=C(B),W=D($),M=N(ae);return()=>{ne(),W(),M()}},[k,C,D,N]);const T=m.useCallback(()=>{a(!0);try{x()}catch(B){console.error("[ControlBar] Stop failed:",B)}},[x]),R=m.useCallback(()=>{a(!0);try{x()}catch(B){console.error("[ControlBar] Force stop failed:",B)}},[x]),z=m.useCallback(()=>{try{w(),e(!1),a(!1)}catch(B){console.error("[ControlBar] Reset failed:",B)}},[w]),O=m.useCallback(async B=>{try{await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({workflow:{bell_mode:B}})}),c(B),console.log("[ControlBar] Bell mode set to:",B)}catch($){console.error("[ControlBar] Failed to toggle bell mode:",$)}},[]),A=m.useCallback(async B=>{try{await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({workflow:{relay_mode:B}})}),h(B),console.log("[ControlBar] Relay mode set to:",B)}catch($){console.error("[ControlBar] Failed to toggle relay mode:",$)}},[]),G=m.useCallback(()=>{if(!y){console.warn("[ControlBar] Cannot TirePump: no current agent");return}try{console.log("[ControlBar] TirePump: clearing context and reloading agent:",y),E(y),e(!1),a(!1),p(0)}catch(B){console.error("[ControlBar] TirePump failed:",B)}},[y,E]),U=m.useCallback(B=>{_(`/${B}`)},[_]);return{isRunning:n,isStopping:i,bellMode:r,relayMode:d,contextPercent:f,currentAgent:y,handleStop:T,handleForceStop:R,handleReset:z,handleBellModeChange:O,handleRelayModeChange:A,handleTirePump:G,handleAgentSwitch:U}}function fe({className:n,...e}){return l.jsx("div",{className:ye("animate-pulse rounded-md bg-primary/10",n),...e})}const Rx={pm:"#a78bfa",sm:"#60a5fa",dev:"#4ade80",tea:"#2dd4bf",reviewer:"#f87171",architect:"#fb923c",devops:"#22d3ee","ux-designer":"#f0abfc","tech-writer":"#e5e5e5",orchestrator:"#e879f9",ba:"#a3e635"};function _2({isOpen:n,onClose:e,currentRole:i,currentTheme:a}){const[r,c]=m.useState(null),[d,h]=m.useState(null),[f,p]=m.useState(!1),[y,b]=m.useState(!1),x=m.useRef(),{send:w}=dr();m.useEffect(()=>{n&&(p(!0),fetch("/api/theme-agents/full").then(N=>N.ok?N.json():null).then(N=>{c(N),h(null),p(!1)}).catch(()=>p(!1)))},[n]),m.useEffect(()=>{b(!1)},[d]),m.useEffect(()=>{if(!n)return;const N=k=>{k.key==="Escape"&&e()};return document.addEventListener("keydown",N),()=>document.removeEventListener("keydown",N)},[n,e]);const E=m.useCallback(N=>{x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{h(N)},100)},[]),_=m.useCallback(()=>{x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{h(null)},200)},[]),C=m.useCallback(N=>{if(N.role===i)return;const k=`/${N.role}`;w(k),e()},[i,w,e]);if(!n)return null;const D=d||r?.agents.find(N=>N.role===i)||r?.agents[0];return l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"agent-popup-backdrop",onClick:e,"aria-hidden":"true"}),l.jsx("div",{className:"agent-popup",role:"dialog","aria-modal":"true","aria-labelledby":"agent-popup-title",children:f?l.jsxs("div",{className:"agent-popup-loading p-4 space-y-3",children:[l.jsx(fe,{className:"h-6 w-40"}),l.jsx(Rt,{}),l.jsxs("div",{className:"flex gap-4",children:[l.jsxs("div",{className:"space-y-2 flex-shrink-0",style:{width:160},children:[l.jsx(fe,{className:"h-5 w-12"}),l.jsx(fe,{className:"h-8 w-full"}),l.jsx(fe,{className:"h-8 w-full"}),l.jsx(fe,{className:"h-8 w-full"}),l.jsx(fe,{className:"h-8 w-full"})]}),l.jsxs("div",{className:"space-y-3 flex-1",children:[l.jsx(fe,{className:"h-24 w-24 rounded-full mx-auto"}),l.jsx(fe,{className:"h-5 w-32 mx-auto"}),l.jsx(fe,{className:"h-4 w-full"}),l.jsx(fe,{className:"h-4 w-3/4"})]})]})]}):r?l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"agent-popup-header",children:[l.jsxs("h2",{id:"agent-popup-title",className:"agent-popup-theme",children:[r.themeName,l.jsx($e,{variant:"secondary",className:`tier-badge ${r.tier?`tier-${r.tier.toLowerCase()}`:"tier-unranked"}`,children:r.tier||"Unranked"})]}),l.jsx(Ce,{variant:"ghost",size:"icon",className:"agent-popup-close",onClick:e,"aria-label":"Close popup",children:"×"})]}),l.jsx(Rt,{className:"my-1"}),l.jsxs("div",{className:"agent-popup-content",children:[l.jsxs("div",{className:"agent-popup-roster",children:[l.jsx("h3",{className:"roster-title",children:"Team"}),l.jsx("ul",{className:"roster-list",role:"listbox",children:r.agents.map(N=>{const k=N.role===i,T=d?.role===N.role,R=Rx[N.role]||"#888";return l.jsxs("li",{className:`roster-item ${k?"current":""} ${T?"previewing":""}`,role:"option","aria-selected":k,onMouseEnter:()=>E(N),onMouseLeave:_,onClick:()=>C(N),children:[l.jsx("span",{className:"roster-character",children:N.character}),l.jsx("span",{className:"roster-role",style:{backgroundColor:R},children:N.role}),k&&l.jsx("span",{className:"roster-current-marker",children:"●"})]},N.role)})})]}),l.jsx("div",{className:"agent-popup-details","data-testid":"agent-popup-details",children:D&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"popup-portrait","data-testid":"popup-portrait",children:!y&&a?l.jsx("img",{src:`/portraits/${a}/large/${D.slug}.png`,alt:D.character,onError:()=>b(!0)}):l.jsx("div",{className:"portrait-placeholder",children:"🤖"})}),l.jsx("h3",{className:"popup-character",children:D.character}),l.jsxs("div",{className:"popup-role-mapping",children:[l.jsx($e,{variant:"default",className:"role-badge",style:{backgroundColor:Rx[D.role]||"#888"},children:D.role}),"→ ",D.character]}),l.jsxs("div",{className:"popup-detail","data-testid":"popup-detail-style",children:[l.jsx("label",{children:"Style:"}),l.jsx("span",{children:D.style||"—"})]}),l.jsxs("div",{className:"popup-detail","data-testid":"popup-detail-background",children:[l.jsx("label",{children:"Background:"}),l.jsx("span",{children:D.background||"—"})]}),D.quirks.length>0&&l.jsxs("div",{className:"popup-detail","data-testid":"popup-detail-quirks",children:[l.jsx("label",{children:"Quirks:"}),l.jsx("span",{children:D.quirks.join(", ")})]}),D.lift!==void 0&&l.jsxs("div",{className:"popup-detail",children:[l.jsx("label",{children:"Lift:"}),l.jsxs("span",{className:`lift-value ${D.lift>=0?"positive":"negative"}`,children:[D.lift>=0?"+":"",D.lift.toFixed(1)]})]})]})})]})]}):l.jsx("div",{className:"agent-popup-error",children:"Failed to load theme data"})})]})}const E2={pm:"PM",sm:"SM",dev:"DEV",tea:"TEA",reviewer:"REV",architect:"ARC",devops:"OPS","ux-designer":"UX","tech-writer":"TW",orchestrator:"ORC",ba:"BA"};function D2({character:n,role:e,slug:i,theme:a,isActive:r,isThinking:c}){const[d,h]=m.useState(!1);if(!r)return null;const f=E2[e]||e.toUpperCase();return l.jsxs("div",{className:`persona-tandem-portrait${c?" avatar-tandem-thinking":""}`,"data-testid":"tandem-portrait",role:"img","aria-label":`${n} (${e}) - observing`,tabIndex:-1,children:[d?l.jsx("span",{className:"tandem-portrait-fallback","aria-hidden":"true",children:"🤖"}):l.jsx("img",{src:`/portraits/${a}/medium/${i}.png`,alt:"","aria-hidden":"true",className:"tandem-portrait-image",onError:()=>h(!0)}),l.jsx("span",{className:"tandem-role-badge","data-testid":"tandem-role-badge","aria-hidden":"true",children:f})]})}const A2={pm:"#a78bfa",sm:"#60a5fa",dev:"#4ade80",tea:"#2dd4bf",reviewer:"#f87171",architect:"#fb923c",devops:"#22d3ee","ux-designer":"#f0abfc","tech-writer":"#e5e5e5",orchestrator:"#e879f9",ba:"#a3e635"},N2={pm:"PM",sm:"SM",dev:"DEV",tea:"TEA",reviewer:"REV",architect:"ARC",devops:"OPS","ux-designer":"UX","tech-writer":"TW",orchestrator:"ORC",ba:"BA"};function j2(n){return n.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function eC(){const{persona:n,isStreaming:e}=Zc(),i=NS(),[a,r]=m.useState(!1),[c,d]=m.useState(!1),[h,f]=m.useState(!1),p=n?.character||"Agent",y=n?.theme||"default",b=n?.role||"agent",x=n?.slug,w=n?.quote,E=n?.tandemAgent,[_,C]=m.useState(!1),D=m.useRef(!1),N=m.useRef(null);m.useEffect(()=>{const O=D.current,A=E?.isThinking??!1;D.current=A,!O&&A&&C(!0)},[E?.isThinking]);const k=m.useCallback(()=>{C(!1)},[]),T=m.useCallback(()=>{d(!0)},[]),R=m.useCallback(()=>{d(!1)},[]),z=A2[b]||"#e879f9";return n?.character?l.jsxs(l.Fragment,{children:[l.jsx(St,{delayDuration:300,children:l.jsxs("div",{className:`persona-header clickable${h?" compact":""}`,"data-testid":"persona-header",role:"button",tabIndex:0,"aria-label":"Current agent persona - click to view team","aria-live":"polite",onClick:T,onKeyDown:O=>O.key==="Enter"&&T(),children:[l.jsxs("div",{className:"persona-portrait-group",children:[l.jsx("div",{className:`persona-portrait${e?" avatar-thinking":""}${_?" avatar-observation-pulse":""}`,"data-testid":"persona-portrait",ref:N,onAnimationEnd:k,children:x&&y&&!a?l.jsx("img",{src:`/portraits/${y}/medium/${x}.png`,alt:p,className:"portrait-image",onError:()=>r(!0)}):l.jsx("span",{className:"portrait-fallback",children:"🤖"})}),E&&l.jsx(D2,{character:E.character,role:E.role,slug:E.slug,theme:E.theme,isActive:!0,isThinking:E.isThinking}),E&&l.jsx("span",{className:"visually-hidden",role:"status","aria-live":"polite","data-testid":"tandem-sr-status",children:E.isThinking?`${E.character} is thinking`:`${E.character} observing`})]}),l.jsxs("div",{className:"persona-info",children:[l.jsxs("div",{className:"persona-name-row",children:[l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx($e,{variant:"default",className:"persona-role","data-testid":"persona-role",style:{backgroundColor:z},children:N2[b]||b})}),l.jsx(Te,{children:b})]}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{className:"persona-character","data-testid":"persona-character",children:p})}),l.jsx(Te,{children:p})]}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{className:"persona-theme","data-testid":"persona-theme",children:j2(y)})}),l.jsx(Te,{children:`Theme: ${y}`})]})]}),w&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsxs("span",{className:"persona-catchphrase","data-testid":"persona-catchphrase",children:['"',w,'"']})}),l.jsx(Te,{children:w})]})]}),l.jsx("img",{src:i==="dark"?"/images/cyclist-dark.png":"/images/cyclist-light.png",alt:"Cyclist",className:"persona-branding"}),l.jsx("button",{className:"persona-collapse-toggle",onClick:O=>{O.stopPropagation(),f(!h)},"aria-label":h?"Expand header":"Collapse header",children:h?"▼":"▲"})]})}),l.jsx(_2,{isOpen:c,onClose:R,currentRole:b,currentTheme:y})]}):l.jsx("div",{className:"persona-header empty","data-testid":"persona-header"})}function T2(n){if(!n)return"—";const e=n.toLowerCase();if(e.includes("opus"))return"opus";if(e.includes("sonnet"))return"sonnet";if(e.includes("haiku"))return"haiku";const i=n.split("-");if(i.length>=2){for(let a=i.length-2;a>=0;a--)if(!/^\d{8}$/.test(i[a]))return i[a]}return n}function k2(n){return n>=85?"level-danger":n>=70?"level-warning":"level-safe"}function R2(n){if(!n)return"";const e=n.split("/");return e[e.length-1]||e[e.length-2]||n}function O2(){const{context:n,stats:e,projectInfo:i}=Om(),a=n?.percent??0,r=e?.model??null,c=i?.pwd??"",d=i?.jiraEmail??null,h=i?.githubUsername??null,f=k2(a),p=R2(c);return l.jsx(St,{delayDuration:300,children:l.jsxs("div",{className:"stats-strip","data-testid":"stats-strip",children:[l.jsxs("div",{className:"stats-left","data-testid":"stats-left",children:[l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{className:"stats-pwd","data-testid":"stats-pwd","data-full-path":c,children:p})}),l.jsx(Te,{children:c})]}),d&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{className:"stats-jira-email","data-testid":"jira-email",children:d})}),l.jsx(Te,{children:`Jira: ${d}`})]}),h&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsxs("span",{className:"stats-github-user","data-testid":"github-user",children:["@",h]})}),l.jsx(Te,{children:`GitHub: ${h}`})]})]}),l.jsxs("div",{className:"stats-right","data-testid":"stats-right",children:[l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx($e,{variant:"secondary",className:"stats-model-badge","data-testid":"model-badge",children:T2(r)})}),r&&l.jsx(Te,{children:r})]}),l.jsxs("div",{className:`stats-context-meter ${f}`,"data-testid":"context-meter",children:[l.jsxs("span",{className:"context-percent","data-testid":"context-percent",children:[a,"%"]}),l.jsx("div",{className:"context-fill","data-testid":"context-fill",style:{width:`${a}%`}})]})]})]})})}function Ox(n){return n.startsWith("Stop hook feedback:")}function z2(n){const e=Date.now(),i=n.parent_tool_use_id||void 0,a=n.subagent_type,r=n.subagent_name,c=[];if(n.type==="assistant"||n.type==="message"){const d=n.message?.content||n.content;if(Array.isArray(d)){const h=d.filter(p=>p.type==="text"&&typeof p.text=="string").map(p=>p.text).join("");h&&h.trim().length>=3&&!Ox(h.trim())&&c.push({type:"agent",content:h,timestamp:e,isStreaming:!0,parent_id:i,subagent_type:a,subagent_name:r});const f=d.filter(p=>p.type==="tool_use");for(const p of f)c.push({type:"tool_use",tool_name:p.name,tool_id:p.id,input:p.input,timestamp:e,parent_id:i,subagent_type:a,subagent_name:r})}else typeof d=="string"&&d.trim().length>=3&&!Ox(d.trim())&&c.push({type:"agent",content:d,timestamp:e,isStreaming:!0,parent_id:i,subagent_type:a,subagent_name:r});return c}if(n.type==="user"){let d="";const h=n.message?.content||n.content;if(Array.isArray(h)){d=h.filter(p=>p.type==="text"&&typeof p.text=="string").map(p=>p.text).join("");const f=h.filter(p=>p.type==="tool_result");for(const p of f)c.push({type:"tool_result",tool_id:p.tool_use_id,content:typeof p.content=="string"?p.content:"",timestamp:e,is_error:p.is_error})}else typeof h=="string"&&(d=h);return d&&c.push({type:"user",content:d,timestamp:e,parent_id:i,subagent_type:a,subagent_name:r}),c}return n.type==="tool_use"?(c.push({type:"tool_use",tool_name:n.tool_name,tool_id:n.tool_id,input:n.input,timestamp:e,parent_id:i,subagent_type:a,subagent_name:r}),c):(n.type==="tool_result"&&c.push({type:"tool_result",tool_id:n.tool_id,content:typeof n.output=="string"?n.output:"",timestamp:e,parent_id:i,subagent_type:a,subagent_name:r,is_error:n.is_error,durationMs:n.durationMs}),c)}function M2(){const[n,e]=m.useState([]),[i,a]=m.useState(!1),{isRunning:r,isStopping:c,bellMode:d,relayMode:h,contextPercent:f,currentAgent:p,handleStop:y,handleForceStop:b,handleReset:x,handleBellModeChange:w,handleRelayModeChange:E,handleTirePump:_,handleAgentSwitch:C}=C2(),{send:D,abort:N,onMessage:k,onComplete:T,onError:R,onUserMessage:z,onClear:O,isConnected:A}=dr(),{persona:G}=Zc(),U=m.useRef(G);U.current=G;const{handleTurnComplete:B,pauseQueue:$,onBellConsumed:ae,injectMessage:ne}=gS(),W=m.useRef();m.useEffect(()=>ae(ce=>{e(de=>[...de,{type:"bell_injected",content:ce.text,timestamp:Date.now(),imageCount:ce.images.length>0?ce.images.length:void 0}])}),[ae]);const M={abort:N,submit:(X,ce)=>{a(!0),D(X,ce)}},K=m.useCallback(X=>{const ce=z2(X);if(ce.length>0){const de=U.current,De=ce.map(Ne=>Ne.type==="agent"&&de?{...Ne,agentSlug:de.slug??void 0,agentTheme:de.theme??void 0,agentCharacter:de.character??void 0}:Ne),Ge=De.filter(Ne=>Ne.type==="tool_result"&&!Ne.parent_id&&Ne.tool_id).map(Ne=>Ne.tool_id);Ge.length>0?e(Ne=>{const dt=new Set(Ge.filter(rt=>Ne.some(An=>An.parent_id===rt)));return dt.size>0?[...Ne.filter(rt=>!rt.parent_id||!dt.has(rt.parent_id)),...De]:[...Ne,...De]}):e(Ne=>[...Ne,...De])}},[]),q=m.useCallback(()=>{a(!1),e(X=>X.map(ce=>ce.type==="agent"&&ce.isStreaming?{...ce,isStreaming:!1}:ce)),W.current&&B(W.current)},[B]),he=m.useCallback(X=>{a(!1),e(ce=>[...ce,{type:"agent",content:`Error: ${X}`,timestamp:Date.now()}])},[]);m.useEffect(()=>z(ce=>{e(de=>[...de,{type:"user",content:ce.prompt,timestamp:ce.timestamp,imageCount:ce.images.length>0?ce.images.length:void 0}])}),[z]),m.useEffect(()=>O(()=>{e(ce=>[...ce,{type:"context_cleared",content:"Context cleared",timestamp:Date.now()}]),a(!1)}),[O]),m.useEffect(()=>{if(!A){console.log("[MessagePanel] Claude WebSocket not connected");return}const X=k(K),ce=T(q),de=R(he);return()=>{X(),ce(),de()}},[A,k,T,R,K,q,he]);const Se=m.useCallback((X,ce)=>{a(!0),D(X,ce)},[D]);m.useEffect(()=>{W.current=Se},[Se]);const I=m.useCallback(()=>{$(),y()},[$,y]),[L,ee]=m.useState(null),V=m.useRef(null),Y=m.useRef(!1),le=m.useCallback(X=>{X.preventDefault(),Y.current=!0;const ce=X.clientY,de=V.current;if(!de)return;const De=de.getBoundingClientRect(),Ge=L??de.querySelector(".message-panel-editor")?.getBoundingClientRect().height??150,Ne=rt=>{if(!Y.current)return;const An=ce-rt.clientY,ei=Math.max(80,Math.min(Ge+An,De.height*.7));ee(ei)},dt=()=>{Y.current=!1,document.removeEventListener("mousemove",Ne),document.removeEventListener("mouseup",dt),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",Ne),document.addEventListener("mouseup",dt),document.body.style.cursor="row-resize",document.body.style.userSelect="none"},[L]);return l.jsxs("div",{className:"message-panel","data-testid":"message-panel",ref:V,children:[l.jsx(eC,{}),l.jsx("div",{className:"message-panel-content",children:l.jsx(BM,{messages:n})}),l.jsx("div",{className:"message-panel-resize-handle",onMouseDown:le}),l.jsx("div",{className:"message-panel-editor",style:L!=null?{height:L,flexShrink:0}:void 0,children:l.jsxs("div",{className:"editor-with-controls",children:[l.jsx("div",{className:"editor-area",children:l.jsx(b2,{onSubmit:Se,isProcessing:i||r,placeholder:"Send a message...",onInject:X=>ne(X,M)})}),l.jsx(S2,{isRunning:r||i,isStopping:c,onStop:I,onForceStop:b,onReset:x,bellMode:d,relayMode:h,onBellModeChange:w,onRelayModeChange:E,contextPercent:f,currentAgent:p,onTirePump:_,onAgentSwitch:C})]})}),l.jsx(O2,{})]})}function P2(n){return n.id?{id:n.id,title:n.title??"",status:n.status??void 0,phase:n.phase??void 0,points:n.points??void 0,criteria:n.criteria,workflowPhases:n.workflow,workflowType:n.workflowType??void 0}:null}function Pm(){const[n,e]=m.useState(null),[i,a]=m.useState(!0),[r,c]=m.useState(null),[d,h]=m.useState(null),f=m.useRef(null),p=m.useRef();return m.useEffect(()=>{const b=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/story`,x=()=>{try{f.current=new WebSocket(b),f.current.onopen=()=>{console.debug("[useStory] WebSocket connected")},f.current.onmessage=w=>{try{const E=JSON.parse(w.data);(E.type==="init"||E.type==="update")&&(e(P2(E)),h(E.availableWorkflows??null),a(!1),c(null))}catch(E){console.error("[useStory] Failed to parse message:",E)}},f.current.onclose=()=>{console.debug("[useStory] WebSocket closed, reconnecting..."),p.current=setTimeout(x,2e3)},f.current.onerror=w=>{console.error("[useStory] WebSocket error:",w),c(new Error("WebSocket connection failed"))}}catch(w){console.error("[useStory] WebSocket init failed:",w),c(w instanceof Error?w:new Error("Failed to connect")),a(!1)}};return x(),()=>{p.current&&clearTimeout(p.current),f.current&&f.current.close()}},[]),{story:n,isLoading:i,error:r,availableWorkflows:d}}function tC(){const[n,e]=m.useState(null),[i,a]=m.useState(!0),[r,c]=m.useState(null),d=m.useRef(null),h=m.useRef(),f=m.useRef(!0);return m.useEffect(()=>{const y=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/sprint`,b=()=>{if(f.current)try{d.current=new WebSocket(y),d.current.onopen=()=>{console.debug("[useSprint] WebSocket connected")},d.current.onmessage=x=>{try{const w=JSON.parse(x.data);if(w.type==="init"||w.type==="update"){const{type:E,..._}=w;e(C=>C?{...C,..._}:_),a(!1),c(null)}}catch(w){console.error("[useSprint] Failed to parse message:",w)}},d.current.onclose=()=>{console.debug("[useSprint] WebSocket closed, reconnecting..."),h.current=setTimeout(b,2e3)},d.current.onerror=x=>{console.error("[useSprint] WebSocket error:",x),c(new Error("WebSocket connection failed"))}}catch(x){console.error("[useSprint] WebSocket init failed:",x),c(x instanceof Error?x:new Error("Failed to connect")),a(!1)}};return b(),()=>{f.current=!1,h.current&&clearTimeout(h.current),d.current&&d.current.close()}},[]),{data:n,isLoading:i,error:r}}function L2(n){if(!n)return null;const e=n.split("@")[0],i=e.split(".");if(i.length>=2){const a=i[0].charAt(0).toUpperCase(),r=i[i.length-1].charAt(0).toUpperCase()+i[i.length-1].slice(1);return`${a}. ${r}`}return e}function I2(n){const e=n.stories.reduce((a,r)=>a+r.points,0);return{done:n.stories.filter(a=>a.status==="done").reduce((a,r)=>a+r.points,0),total:e}}function jf(n){return n.stories.length>0&&n.stories.every(e=>e.status==="done")}function G2(n){switch(n){case"done":return{icon:l.jsx(Ga,{size:12}),className:"status-done"};case"in_progress":return{icon:l.jsx(ez,{size:12}),className:"status-in-progress"};case"blocked":return{icon:l.jsx(oz,{size:12}),className:"status-blocked"};default:return{icon:l.jsx(QO,{size:12}),className:"status-backlog"}}}function zx(n){return`https://1898andco.atlassian.net/browse/${n}`}function Mx({hasContext:n,testIdPrefix:e,id:i}){const a=n?"Context file exists":"No context file";return l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{className:`context-indicator ${n?"has-context":"no-context"}`,"data-testid":`${e}-context-indicator-${i}`,"data-has-context":String(n),title:a,children:n?"📄":""})}),l.jsx(Te,{children:a})]})}function B2({priority:n,storyId:e}){return n?l.jsx("span",{className:"priority-label","data-testid":`story-priority-${e}`,"data-priority":n,title:n,children:n}):null}function H2({status:n,storyId:e}){const{icon:i,className:a}=G2(n);return l.jsx($e,{variant:n==="blocked"?"destructive":n==="done"?"default":"secondary",className:`story-status-badge ${a}`,"data-testid":`story-status-badge-${e}`,"data-status":n,"aria-label":`Status: ${n}`,children:i})}function V2({jiraKey:n,storyId:e}){const i=a=>{a.preventDefault();const r=zx(n);try{const c=window.electronAPI;if(c?.shell?.openExternal){c.shell.openExternal(r);return}}catch{}window.open(r,"_blank")};return l.jsx("a",{className:"jira-link cyclist-link","data-testid":`story-jira-link-${e}`,href:zx(n),onClick:i,children:n})}function Px({text:n}){const[e,i]=m.useState(!1),a=async r=>{r.stopPropagation();try{await navigator.clipboard.writeText(n),i(!0),setTimeout(()=>i(!1),2e3)}catch{}};return l.jsx("button",{className:`copy-id-button ${e?"copied":""}`,onClick:a,"aria-label":`Copy ${n}`,title:"Copy ID + title",children:e?l.jsx(Ga,{size:12}):l.jsx(KO,{size:12})})}function Lx({epic:n,isExpanded:e,isArchiving:i,onToggle:a,onKeyDown:r,onArchive:c}){const{done:d,total:h}=I2(n),f=jf(n);return l.jsxs("div",{className:`epic-group ${f?"epic-completed":""}`,"data-testid":`epic-group-${n.id}`,children:[l.jsxs("div",{className:"epic-header",children:[l.jsx(Ce,{variant:"ghost",size:"icon",className:"epic-toggle","data-testid":`epic-toggle-${n.id}`,onClick:()=>a(n.id),onKeyDown:p=>r(n.id,p),"aria-expanded":e,children:e?"▼":"▶"}),l.jsx("span",{className:"epic-title",children:n.title}),n.jiraKey&&l.jsx("span",{className:"epic-jira",children:n.jiraKey}),l.jsx(Px,{text:`${n.id} ${n.title}`}),l.jsx(Mx,{hasContext:n.hasContext??!1,testIdPrefix:"epic",id:n.id}),f&&n.hasContext&&l.jsx($e,{variant:"default",className:"epic-ready-badge","data-testid":`epic-ready-badge-${n.id}`,children:"Ready"}),l.jsx("div",{className:"epic-progress","data-testid":`epic-progress-${n.id}`,"data-done":String(d),"data-total":String(h),children:l.jsx("div",{className:"progress-bar",style:{width:`${h>0?d/h*100:0}%`}})}),l.jsxs("span",{className:"epic-progress-label","data-testid":`epic-progress-label-${n.id}`,children:[d,"/",h," pts"]}),f&&l.jsxs(l.Fragment,{children:[i&&l.jsx("span",{"data-testid":`archive-loading-${n.id}`,children:"..."}),l.jsx(Ce,{variant:"outline",size:"sm",className:"archive-button","data-testid":`archive-button-${n.id}`,"aria-label":`Archive ${n.id}`,disabled:i,onClick:()=>c(n.id),children:"Archive"})]})]}),e&&l.jsx("div",{className:"epic-stories",children:n.stories.map(p=>{const y=p.hasContext??!1,b=p.status==="blocked",x=L2(p.assignedTo);return l.jsxs("div",{className:`story-item ${y?"":"missing-context"} ${b?"story-blocked":""}`,"data-testid":`story-item-${p.id}`,"data-status":p.status,"data-story-id":p.id,"aria-label":`${p.id}: ${p.title}`,children:[l.jsx(B2,{priority:p.priority,storyId:p.id}),l.jsx(H2,{status:p.status,storyId:p.id}),p.jiraKey&&l.jsx(V2,{jiraKey:p.jiraKey,storyId:p.id}),l.jsx(Px,{text:`${p.id} ${p.title}`}),l.jsxs("div",{className:"story-info",children:[l.jsx("span",{className:"story-title",children:p.title}),l.jsxs("span",{className:"story-meta",children:[x&&l.jsx("span",{className:"story-assignee","data-testid":`story-assignee-${p.id}`,children:x}),p.workflow&&l.jsx("span",{className:"story-workflow-badge","data-testid":`story-workflow-${p.id}`,children:p.workflow}),p.status==="done"&&p.completed&&l.jsx("span",{className:"story-completed-date","data-testid":`story-completed-${p.id}`,children:p.completed})]})]}),l.jsx(Mx,{hasContext:y,testIdPrefix:"story",id:p.id}),l.jsx("span",{className:"story-points","data-testid":`story-points-${p.id}`,children:p.points})]},p.id)})})]})}function nC(){const{data:n,isLoading:e,error:i}=tC(),[a,r]=m.useState(new Set),[c,d]=m.useState(new Set),[h,f]=m.useState(null),[p,y]=m.useState(null),b=n?.epics.filter(R=>!jf(R))??[],x=n?.epics.filter(R=>jf(R))??[],w=m.useRef(!1);m.useEffect(()=>{n?.epics&&!w.current&&(w.current=!0,r(new Set(b.map(R=>R.id))))},[n?.epics]);const E=m.useCallback(R=>{r(z=>{const O=new Set(z);return O.has(R)?O.delete(R):O.add(R),O})},[]),_=m.useCallback((R,z)=>{(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),E(R))},[E]),C=m.useCallback(async R=>{d(z=>new Set(z).add(`archive-${R}`)),f(null),y(null);try{if(typeof window<"u"&&window.electronAPI?.sprint?.archiveEpic)await window.electronAPI.sprint.archiveEpic(R);else if(!(await fetch(`/api/sprint/archive-epic/${R}`,{method:"POST"})).ok)throw new Error("Archive failed")}catch(z){y(z instanceof Error?z:new Error("Archive failed"))}finally{d(z=>{const O=new Set(z);return O.delete(`archive-${R}`),O})}},[]),D=m.useCallback(async R=>{d(z=>new Set(z).add(`promote-${R}`)),y(null);try{if(typeof window<"u"&&window.electronAPI?.sprint?.promoteEpic)await window.electronAPI.sprint.promoteEpic(R);else if(!(await fetch(`/api/sprint/promote-epic/${R}`,{method:"POST"})).ok)throw new Error("Promote failed")}catch(z){y(z instanceof Error?z:new Error("Promote failed"))}finally{d(z=>{const O=new Set(z);return O.delete(`promote-${R}`),O})}},[]);if(e)return l.jsx("div",{className:"enhanced-sprint-panel","data-testid":"enhanced-sprint-panel",children:l.jsxs("div",{className:"loading-state space-y-3 p-2","data-testid":"sprint-panel-loading",children:[l.jsx(fe,{className:"h-5 w-32"}),l.jsx(fe,{className:"h-4 w-full"}),l.jsx(Rt,{className:"my-2"}),l.jsx(fe,{className:"h-5 w-28"}),l.jsx(fe,{className:"h-8 w-full"}),l.jsx(fe,{className:"h-8 w-full"}),l.jsx(Rt,{className:"my-2"}),l.jsx(fe,{className:"h-5 w-36"}),l.jsx(fe,{className:"h-6 w-3/4"})]})});const N=i||p,k=N?l.jsx("div",{className:"error-toast","data-testid":"error-toast",children:N.message}):null,T=h?l.jsxs("div",{className:"confirm-dialog","data-testid":"confirm-archive-dialog",children:[l.jsx("p",{children:"Are you sure you want to archive this epic?"}),l.jsx(Ce,{variant:"destructive",size:"sm","data-testid":"confirm-archive-yes",onClick:()=>C(h),children:"Yes"}),l.jsx(Ce,{variant:"outline",size:"sm","data-testid":"confirm-archive-no",onClick:()=>f(null),children:"No"})]}):null;return l.jsx(St,{delayDuration:300,children:l.jsxs("div",{className:"enhanced-sprint-panel","data-testid":"enhanced-sprint-panel",children:[k,T,l.jsxs("section",{"data-section":"current-story",children:[l.jsx("h2",{children:"Current Story"}),n?.currentStory?l.jsxs("div",{"data-testid":"current-story-section",children:[l.jsx("span",{className:"story-id",children:n.currentStory.id}),l.jsx("span",{className:"story-title",children:n.currentStory.title}),l.jsx("span",{className:"story-status",children:n.currentStory.status}),l.jsxs("span",{className:"story-points","data-testid":"current-story-points",children:[n.currentStory.points," pts"]})]}):n?.nextStory?l.jsxs("div",{"data-testid":"next-up-section",children:[l.jsx("span",{className:"next-up-label",children:"Next up:"}),l.jsx("span",{className:"story-id",children:n.nextStory.id}),l.jsx("span",{className:"story-title",children:n.nextStory.title})]}):l.jsx("div",{"data-testid":"no-stories-section",children:l.jsx("span",{children:"No active story"})})]}),l.jsx(Rt,{className:"my-2"}),l.jsxs("section",{"data-section":"epics",children:[l.jsx("h2",{children:"Current Epics"}),l.jsxs("div",{"data-testid":"epic-tree-view",children:[(!n?.epics||n.epics.length===0)&&l.jsxs("div",{className:"empty-state","data-testid":"no-epics-section",children:[l.jsx("span",{children:"No epics in current sprint"}),l.jsx("p",{className:"hint",children:"Promote an epic from Future Initiatives to get started"})]}),b.map(R=>l.jsx(Lx,{epic:R,isExpanded:a.has(R.id),isArchiving:c.has(`archive-${R.id}`),onToggle:E,onKeyDown:_,onArchive:f},R.id))]})]}),x.length>0&&l.jsxs(l.Fragment,{children:[l.jsx(Rt,{className:"my-2"}),l.jsxs("section",{"data-section":"completed-epics",children:[l.jsx("h2",{children:"Completed Epics"}),l.jsx("div",{"data-testid":"completed-epics-section",children:x.map(R=>l.jsx(Lx,{epic:R,isExpanded:a.has(R.id),isArchiving:c.has(`archive-${R.id}`),onToggle:E,onKeyDown:_,onArchive:f},R.id))})]})]}),l.jsx(Rt,{className:"my-2"}),l.jsxs("section",{"data-section":"future",children:[l.jsx("h2",{children:"Future Initiatives"}),l.jsx("div",{"data-testid":"future-initiatives-section",children:n?.futureEpics.map(R=>{const z=c.has(`promote-${R.id}`),O=R.status==="ready";return l.jsxs("div",{className:"future-epic","data-testid":`future-epic-${R.id}`,children:[l.jsx("span",{className:"future-epic-title",children:R.title}),l.jsxs("span",{className:"future-epic-points",children:[R.estimatedPoints," pts"]}),l.jsx($e,{variant:R.status==="ready"?"default":"secondary",className:"future-epic-status","data-testid":`future-epic-status-${R.id}`,"data-status":R.status,children:R.status}),O&&l.jsx(Ce,{variant:"default",size:"sm",className:"promote-button","data-testid":`promote-button-${R.id}`,"aria-label":`Promote ${R.id} to current sprint`,disabled:z,onClick:()=>D(R.id),children:"Promote"})]},R.id)})})]})]})})}function iC(n){let e=0,i=0,a=0;for(const r of n){const c=r.status[0]||" ",d=r.status[1]||" ";c!==" "&&c!=="?"&&e++,(d==="M"||d==="D")&&i++,c==="?"&&d==="?"&&a++}return{staged:e,modified:i,untracked:a}}function F2(n){return n?.length?n.map(e=>{const i=iC(e.dirtyFiles);return{name:e.name,path:e.path,branch:e.branch,ahead:e.ahead??void 0,behind:e.behind??void 0,developBehind:e.developBehind??void 0,staged:i.staged,modified:i.modified,untracked:i.untracked,isDirty:!e.clean,files:e.dirtyFiles}}):[]}function U2(n){if(!n?.length)return null;const e=n[0];let i=0,a=0,r=0;for(const d of n){const h=iC(d.dirtyFiles);i+=h.staged,a+=h.modified,r+=h.untracked}const c=n.some(d=>!d.clean);return{branch:e.branch,ahead:e.ahead??void 0,behind:e.behind??void 0,staged:i>0?i:void 0,modified:a>0?a:void 0,untracked:r>0?r:void 0,isDirty:c}}function Lm(){const[n,e]=m.useState(null),[i,a]=m.useState([]),[r,c]=m.useState(!0),[d,h]=m.useState(null),f=m.useRef(null),p=m.useRef();return m.useEffect(()=>{const b=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/git`,x=()=>{try{f.current=new WebSocket(b),f.current.onopen=()=>{console.debug("[useGitStatus] WebSocket connected")},f.current.onmessage=w=>{try{const E=JSON.parse(w.data);(E.type==="init"||E.type==="update")&&(e(U2(E.repos)),a(F2(E.repos)),c(!1),h(null))}catch(E){console.error("[useGitStatus] Failed to parse message:",E)}},f.current.onclose=()=>{console.debug("[useGitStatus] WebSocket closed, reconnecting..."),p.current=setTimeout(x,2e3)},f.current.onerror=w=>{console.error("[useGitStatus] WebSocket error:",w),h(new Error("WebSocket connection failed"))}}catch(w){console.error("[useGitStatus] WebSocket init failed:",w),h(w instanceof Error?w:new Error("Failed to connect")),c(!1)}};return x(),()=>{p.current&&clearTimeout(p.current),f.current&&f.current.close()}},[]),{gitStatus:n,repos:i,isLoading:r,error:d}}function $2(n){const e=n[0]||" ",i=n[1]||" ";return e==="?"&&i==="?"?"untracked":e!==" "&&e!=="?"?"staged":"modified"}function W2(n){const e=n[0]||" ",i=n[1]||" ";return e==="?"&&i==="?"?"?":e==="A"?"+":e==="D"||i==="D"?"-":e==="M"||i==="M"?"~":e==="R"?"R":n.trim()||"~"}function q2({files:n}){return l.jsx("ul",{className:"file-list",children:n.map((e,i)=>l.jsxs("li",{className:`file-item ${$2(e.status)}`,children:[l.jsx("span",{className:"file-status-icon",children:W2(e.status)}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{className:"file-path",children:e.path})}),l.jsx(Te,{children:e.path})]})]},`${e.path}-${i}`))})}function Y2({repo:n}){const[e,i]=m.useState(!1),{name:a,branch:r,ahead:c,behind:d,developBehind:h,staged:f,modified:p,untracked:y,isDirty:b,files:x}=n,w=x.length>0;return l.jsx(St,{delayDuration:300,children:l.jsxs("div",{className:`repo-status ${e?"expanded":""}`,"data-testid":`repo-status-${a}`,children:[l.jsxs("div",{className:"repo-header",children:[l.jsx("span",{className:"repo-name",children:a}),b&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx($e,{variant:"destructive",className:"dirty-indicator",children:"●"})}),l.jsx(Te,{children:"Uncommitted changes"})]})]}),l.jsxs("div",{className:"branch-info",children:[l.jsx("span",{className:"branch-icon",children:"⎇"}),l.jsx("span",{className:"branch-name",children:r})]}),(c!==void 0&&c>0||d!==void 0&&d>0||h!==void 0&&h>0)&&l.jsxs("div",{className:"sync-status",children:[c!==void 0&&c>0&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsxs("span",{className:"ahead",children:["↑",c]})}),l.jsx(Te,{children:"Commits ahead of remote"})]}),d!==void 0&&d>0&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsxs("span",{className:"behind",children:["↓",d]})}),l.jsx(Te,{children:"Commits behind remote"})]}),h!==void 0&&h>0&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsxs("span",{className:"develop-behind",children:["⟳",h]})}),l.jsxs(Te,{children:["develop is ",h," commit",h>1?"s":""," ahead"]})]})]}),(f>0||p>0||y>0)&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsxs(Ce,{variant:"ghost",className:"file-status-toggle",onClick:()=>i(!e),children:[l.jsx("span",{className:`toggle-icon ${e?"open":""}`,children:"▶"}),l.jsxs("div",{className:"file-status",children:[f>0&&l.jsxs($e,{variant:"outline",className:"status-item staged",children:["+",f]}),p>0&&l.jsxs($e,{variant:"outline",className:"status-item modified",children:["~",p]}),y>0&&l.jsxs($e,{variant:"outline",className:"status-item untracked",children:["?",y]})]})]})}),l.jsx(Te,{children:e?"Collapse file list":"Expand file list"})]}),e&&w&&l.jsx(q2,{files:x})]})})}function sC(){const{repos:n,isLoading:e,error:i}=Lm();return e?l.jsx("div",{className:"git-panel loading","data-testid":"git-panel",children:l.jsxs("div",{className:"space-y-3 p-2",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx(fe,{className:"h-4 w-32"}),l.jsx(fe,{className:"h-3 w-24"})]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx(fe,{className:"h-4 w-28"}),l.jsx(fe,{className:"h-3 w-20"})]})]})}):i?l.jsx("div",{className:"git-panel error","data-testid":"git-panel",children:l.jsx("div",{className:"error-message",children:i.message})}):n.length===0?l.jsx("div",{className:"git-panel empty","data-testid":"git-panel",children:l.jsx("div",{className:"placeholder",children:"No git repos"})}):l.jsx("div",{className:"git-panel stacked","data-testid":"git-panel",children:n.map(a=>l.jsx(Y2,{repo:a},a.name))})}function X2(n){switch(n){case"done":return"✓";case"current":return"●";default:return"○"}}function Q2(n){return n?["tdd","bdd"].includes(n.toLowerCase())?n.toUpperCase():n.charAt(0).toUpperCase()+n.slice(1):"—"}function Z2({phase:n,isLast:e}){const i=X2(n.status),a=`phase-step ${n.status}`;return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:a,children:[l.jsx("span",{className:"phase-icon",children:i}),l.jsx("span",{className:"phase-label",children:n.label})]}),!e&&l.jsx("span",{className:"phase-arrow",children:"→"})]})}function K2({phases:n}){const e=n.length,i=n.findIndex(d=>d.status==="current"),a=n.filter(d=>d.status==="done").length,r=i>=0?i+1:a===e?e:1,c=i>=0?n[i]:null;return l.jsxs("div",{className:"stepped-progress",children:[l.jsxs("span",{className:"stepped-counter",children:["Step ",r," of ",e]}),c&&l.jsx("span",{className:"stepped-current-label",children:c.label})]})}function J2({workflows:n,onStart:e}){return l.jsxs("div",{className:"available-workflows",children:[l.jsx("div",{className:"available-workflows-header",children:l.jsxs("span",{className:"available-workflows-title",children:["Available Workflows (",n.length,")"]})}),l.jsx("div",{className:"available-workflows-list",children:n.map(i=>l.jsxs("div",{className:"workflow-entry","data-testid":"workflow-entry","data-workflow-entry-type":i.type,children:[l.jsxs("div",{className:"workflow-entry-header",children:[l.jsx("span",{className:"workflow-entry-name",children:i.name}),l.jsx($e,{variant:"outline",className:"workflow-entry-type-badge",children:i.type})]}),l.jsx("div",{className:"workflow-entry-description",children:i.description}),i.type==="stepped"&&l.jsxs("div",{className:"workflow-entry-hint",children:["/workflow start ",i.name]}),l.jsx("div",{className:"workflow-entry-footer",children:l.jsx(Ce,{variant:"ghost",size:"sm",className:"workflow-start-button","data-testid":"workflow-start-button",onClick:()=>e?.(i),children:"Start"})})]},i.name))})]})}function aC(){const{story:n,isLoading:e,error:i,availableWorkflows:a}=Pm(),{send:r,isConnected:c}=dr(),d=m.useCallback(b=>{c&&r(`/workflow start ${b.name}`)},[r,c]);if(e)return l.jsx("div",{className:"workflow-panel loading","data-testid":"workflow-panel",children:l.jsxs("div",{className:"space-y-2 p-2",children:[l.jsx(fe,{className:"h-6 w-16 rounded-full"}),l.jsxs("div",{className:"flex gap-2 items-center",children:[l.jsx(fe,{className:"h-4 w-12"}),l.jsx(fe,{className:"h-4 w-12"}),l.jsx(fe,{className:"h-4 w-12"})]})]})});if(i)return l.jsx("div",{className:"workflow-panel error","data-testid":"workflow-panel",children:l.jsx("div",{className:"error-message",children:i.message})});const h=n?.workflow??null,f=n?.workflowPhases??null,p=n?.workflowType==="stepped";if(!h&&(!f||f.length===0))return a&&a.length>0?l.jsx("div",{className:"workflow-panel","data-testid":"workflow-panel",children:l.jsx(J2,{workflows:a,onStart:d})}):l.jsx("div",{className:"workflow-panel","data-testid":"workflow-panel",children:l.jsx("div",{className:"placeholder",children:"No active workflow"})});const y=Q2(h);return l.jsx("div",{className:"workflow-panel","data-testid":"workflow-panel",children:l.jsxs("div",{className:"workflow-content",children:[l.jsx($e,{variant:"secondary",className:"workflow-type-badge","data-workflow-type":h||"",children:y}),f&&f.length>0&&(p?l.jsx(K2,{phases:f}):l.jsx("div",{className:"phase-progress",children:f.map((b,x)=>l.jsx(Z2,{phase:b,isLast:x===f.length-1},b.name))}))]})})}function eP({item:n}){const e=n.completed?"ac-item ac-done":"ac-item",i=n.completed?"✓":"○";return l.jsxs("div",{className:e,children:[l.jsx("span",{className:"ac-icon",children:i}),l.jsx("span",{className:"ac-text",children:n.text})]})}function oC(){const{story:n,isLoading:e,error:i}=Pm();if(e)return l.jsx("div",{className:"ac-panel loading","data-testid":"ac-panel",children:l.jsxs("div",{className:"space-y-2 p-2",children:[l.jsx(fe,{className:"h-3 w-full"}),l.jsx(fe,{className:"h-4 w-3/4"}),l.jsx(fe,{className:"h-4 w-5/6"}),l.jsx(fe,{className:"h-4 w-2/3"})]})});if(i)return l.jsx("div",{className:"ac-panel error","data-testid":"ac-panel",children:l.jsx("div",{className:"error-message",children:i.message})});const a=n?.criteria??null;if(!a||a.length===0)return l.jsx("div",{className:"ac-panel","data-testid":"ac-panel",children:l.jsx("div",{className:"placeholder",children:"No acceptance criteria"})});const r=a.filter(d=>d.completed).length,c=a.length;return l.jsx("div",{className:"ac-panel","data-testid":"ac-panel",children:l.jsxs("div",{className:"ac-content",children:[l.jsxs("span",{className:"progress-text",children:[r,"/",c]}),l.jsx("div",{className:"progress-bar-container",children:l.jsx("div",{className:"progress-bar",style:{width:`${r/c*100}%`}})}),l.jsx("div",{className:"ac-list",children:a.map((d,h)=>l.jsx(eP,{item:d},h))})]})})}function rC(){const[n,e]=m.useState([]),[i,a]=m.useState(!0),[r,c]=m.useState(null),d=m.useRef(null),h=m.useRef();return m.useEffect(()=>{const p=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/todos`,y=()=>{try{d.current=new WebSocket(p),d.current.onopen=()=>{console.debug("[useTodos] WebSocket connected")},d.current.onmessage=b=>{try{const x=JSON.parse(b.data);(x.type==="init"||x.type==="update")&&(e(x.todos||[]),a(!1),c(null))}catch(x){console.error("[useTodos] Failed to parse message:",x)}},d.current.onclose=()=>{console.debug("[useTodos] WebSocket closed, reconnecting..."),h.current=setTimeout(y,2e3)},d.current.onerror=b=>{console.error("[useTodos] WebSocket error:",b),c(new Error("WebSocket connection failed"))}}catch(b){console.error("[useTodos] WebSocket init failed:",b),c(b instanceof Error?b:new Error("Failed to connect")),a(!1)}};return y(),()=>{h.current&&clearTimeout(h.current),d.current&&d.current.close()}},[]),{todos:n,isLoading:i,error:r}}function Kh({todo:n}){const e={pending:"○",in_progress:"●",completed:"✓"}[n.status],i=`todo-item todo-${n.status}`,a=n.status==="in_progress"&&n.activeForm?n.activeForm:n.content;return l.jsxs("div",{className:i,"data-testid":`todo-${n.id}`,children:[l.jsx("span",{className:"todo-status",children:e}),l.jsx("span",{className:"todo-subject",children:a}),n.blockedBy&&n.blockedBy.length>0&&l.jsx(St,{delayDuration:300,children:l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{className:"todo-blocked",children:"(blocked)"})}),l.jsx(Te,{children:`Blocked by: ${n.blockedBy.join(", ")}`})]})})]})}function lC(){const{todos:n,isLoading:e,error:i}=rC();if(e)return l.jsx("div",{className:"todo-panel loading","data-testid":"todo-panel",children:l.jsxs("div",{className:"space-y-2 p-2",children:[l.jsx(fe,{className:"h-3 w-full"}),l.jsx(fe,{className:"h-4 w-5/6"}),l.jsx(fe,{className:"h-4 w-3/4"}),l.jsx(fe,{className:"h-4 w-4/5"})]})});if(i)return l.jsx("div",{className:"todo-panel error","data-testid":"todo-panel",children:l.jsx("div",{className:"error-message",children:i.message})});if(n.length===0)return l.jsx("div",{className:"todo-panel","data-testid":"todo-panel",children:l.jsx("div",{className:"placeholder",children:"No active tasks"})});const a=n.filter(p=>p.status==="in_progress"),r=n.filter(p=>p.status==="pending"),c=n.filter(p=>p.status==="completed"),d=n.length,h=c.length,f=d>0?Math.round(h/d*100):0;return l.jsx("div",{className:"todo-panel","data-testid":"todo-panel",children:l.jsxs("div",{className:"todo-content",children:[l.jsxs("div",{className:"progress-bar-container",children:[l.jsx("div",{className:"progress-bar",style:{width:`${f}%`}}),l.jsxs("span",{className:"progress-text",children:[h,"/",d]})]}),a.length>0&&l.jsxs("div",{className:"todo-section",children:[l.jsx("h4",{children:"In Progress"}),a.map(p=>l.jsx(Kh,{todo:p},p.id))]}),r.length>0&&l.jsxs("div",{className:"todo-section",children:[l.jsx("h4",{children:"Pending"}),r.map(p=>l.jsx(Kh,{todo:p},p.id))]}),c.length>0&&l.jsxs("div",{className:"todo-section todo-completed",children:[l.jsxs("h4",{children:["Completed (",c.length,")"]}),c.map(p=>l.jsx(Kh,{todo:p},p.id))]})]})})}function tP(){const[n,e]=m.useState([]),i=m.useRef(null),a=m.useRef();m.useEffect(()=>{const f=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/background-tasks`,p=()=>{try{i.current=new WebSocket(f),i.current.onopen=()=>{console.debug("[useBackgroundTasks] WebSocket connected")},i.current.onmessage=y=>{try{const b=JSON.parse(y.data);switch(b.type){case"init":b.tasks&&e(b.tasks);break;case"task:started":b.task&&e(x=>x.some(w=>w.taskId===b.task.taskId)?x:[...x,b.task]);break;case"task:completed":b.task&&e(x=>x.map(w=>w.taskId===b.task.taskId?{...w,...b.task}:w));break}}catch(b){console.error("[useBackgroundTasks] Failed to parse message:",b)}},i.current.onclose=()=>{console.debug("[useBackgroundTasks] WebSocket closed, reconnecting..."),a.current=setTimeout(p,2e3)},i.current.onerror=y=>{console.error("[useBackgroundTasks] WebSocket error:",y)}}catch(y){console.error("[useBackgroundTasks] WebSocket init failed:",y)}};return p(),()=>{a.current&&clearTimeout(a.current),i.current&&i.current.close()}},[]);const r=m.useCallback(()=>{e(h=>h.filter(f=>f.status==="pending"))},[]),c=n.filter(h=>h.status==="pending").length,d=n.filter(h=>h.status==="completed").length;return{tasks:n,pendingCount:c,completedCount:d,clearCompleted:r}}function Ix(n){return n<1e3?`${n}ms`:n<6e4?`${Math.floor(n/1e3)}s`:`${Math.floor(n/6e4)}m`}function nP({task:n,tick:e}){const a=n.status==="pending"?"...":n.success?"v":"x",r=`task-item task-${n.status}${n.success===!1?" task-error":""}`;let c;return n.status==="completed"&&n.durationMs!==void 0?c=Ix(n.durationMs):c=Ix(Date.now()-n.startedAt),l.jsxs("div",{className:r,"data-testid":`task-${n.taskId}`,children:[l.jsx("span",{className:"task-status",children:a}),l.jsxs("div",{className:"task-content",children:[l.jsx("span",{className:"task-description",children:n.description}),l.jsx("span",{className:"task-type",children:n.subagentType})]}),l.jsx("span",{className:"task-elapsed",children:c})]})}function cC(){const{tasks:n,pendingCount:e,completedCount:i,clearCompleted:a}=tP(),[r,c]=m.useState(0);if(m.useEffect(()=>{if(e===0)return;const h=setInterval(()=>{c(f=>f+1)},1e3);return()=>clearInterval(h)},[e]),n.length===0)return l.jsx("div",{className:"background-panel empty","data-testid":"background-panel",children:l.jsx("div",{className:"placeholder",children:"No subagent tasks"})});const d=[...n].sort((h,f)=>h.status==="pending"&&f.status!=="pending"?-1:h.status!=="pending"&&f.status==="pending"?1:f.startedAt-h.startedAt);return l.jsxs("div",{className:"background-panel","data-testid":"background-panel",children:[l.jsxs("div",{className:"panel-header",children:[l.jsxs("span",{className:"task-counts",children:[e>0&&l.jsxs("span",{className:"pending-count",children:[e," running"]}),i>0&&l.jsxs("span",{className:"completed-count",children:[i," done"]})]}),i>0&&l.jsx(Ce,{variant:"ghost",size:"sm",type:"button",className:"clear-button",onClick:a,children:"Clear"})]}),l.jsx("div",{className:"task-list",children:d.map(h=>l.jsx(nP,{task:h,tick:r},h.taskId))})]})}function Tf(n,[e,i]){return Math.min(i,Math.max(e,n))}function iP(n,e){return m.useReducer((i,a)=>e[i][a]??i,n)}var Im="ScrollArea",[uC]=cn(Im),[sP,Dn]=uC(Im),dC=m.forwardRef((n,e)=>{const{__scopeScrollArea:i,type:a="hover",dir:r,scrollHideDelay:c=600,...d}=n,[h,f]=m.useState(null),[p,y]=m.useState(null),[b,x]=m.useState(null),[w,E]=m.useState(null),[_,C]=m.useState(null),[D,N]=m.useState(0),[k,T]=m.useState(0),[R,z]=m.useState(!1),[O,A]=m.useState(!1),G=Ie(e,B=>f(B)),U=Kc(r);return l.jsx(sP,{scope:i,type:a,dir:U,scrollHideDelay:c,scrollArea:h,viewport:p,onViewportChange:y,content:b,onContentChange:x,scrollbarX:w,onScrollbarXChange:E,scrollbarXEnabled:R,onScrollbarXEnabledChange:z,scrollbarY:_,onScrollbarYChange:C,scrollbarYEnabled:O,onScrollbarYEnabledChange:A,onCornerWidthChange:N,onCornerHeightChange:T,children:l.jsx(je.div,{dir:U,...d,ref:G,style:{position:"relative","--radix-scroll-area-corner-width":D+"px","--radix-scroll-area-corner-height":k+"px",...n.style}})})});dC.displayName=Im;var hC="ScrollAreaViewport",fC=m.forwardRef((n,e)=>{const{__scopeScrollArea:i,children:a,nonce:r,...c}=n,d=Dn(hC,i),h=m.useRef(null),f=Ie(e,h,d.onViewportChange);return l.jsxs(l.Fragment,{children:[l.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),l.jsx(je.div,{"data-radix-scroll-area-viewport":"",...c,ref:f,style:{overflowX:d.scrollbarXEnabled?"scroll":"hidden",overflowY:d.scrollbarYEnabled?"scroll":"hidden",...n.style},children:l.jsx("div",{ref:d.onContentChange,style:{minWidth:"100%",display:"table"},children:a})})]})});fC.displayName=hC;var Jn="ScrollAreaScrollbar",Gm=m.forwardRef((n,e)=>{const{forceMount:i,...a}=n,r=Dn(Jn,n.__scopeScrollArea),{onScrollbarXEnabledChange:c,onScrollbarYEnabledChange:d}=r,h=n.orientation==="horizontal";return m.useEffect(()=>(h?c(!0):d(!0),()=>{h?c(!1):d(!1)}),[h,c,d]),r.type==="hover"?l.jsx(aP,{...a,ref:e,forceMount:i}):r.type==="scroll"?l.jsx(oP,{...a,ref:e,forceMount:i}):r.type==="auto"?l.jsx(mC,{...a,ref:e,forceMount:i}):r.type==="always"?l.jsx(Bm,{...a,ref:e}):null});Gm.displayName=Jn;var aP=m.forwardRef((n,e)=>{const{forceMount:i,...a}=n,r=Dn(Jn,n.__scopeScrollArea),[c,d]=m.useState(!1);return m.useEffect(()=>{const h=r.scrollArea;let f=0;if(h){const p=()=>{window.clearTimeout(f),d(!0)},y=()=>{f=window.setTimeout(()=>d(!1),r.scrollHideDelay)};return h.addEventListener("pointerenter",p),h.addEventListener("pointerleave",y),()=>{window.clearTimeout(f),h.removeEventListener("pointerenter",p),h.removeEventListener("pointerleave",y)}}},[r.scrollArea,r.scrollHideDelay]),l.jsx(qt,{present:i||c,children:l.jsx(mC,{"data-state":c?"visible":"hidden",...a,ref:e})})}),oP=m.forwardRef((n,e)=>{const{forceMount:i,...a}=n,r=Dn(Jn,n.__scopeScrollArea),c=n.orientation==="horizontal",d=eu(()=>f("SCROLL_END"),100),[h,f]=iP("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return m.useEffect(()=>{if(h==="idle"){const p=window.setTimeout(()=>f("HIDE"),r.scrollHideDelay);return()=>window.clearTimeout(p)}},[h,r.scrollHideDelay,f]),m.useEffect(()=>{const p=r.viewport,y=c?"scrollLeft":"scrollTop";if(p){let b=p[y];const x=()=>{const w=p[y];b!==w&&(f("SCROLL"),d()),b=w};return p.addEventListener("scroll",x),()=>p.removeEventListener("scroll",x)}},[r.viewport,c,f,d]),l.jsx(qt,{present:i||h!=="hidden",children:l.jsx(Bm,{"data-state":h==="hidden"?"hidden":"visible",...a,ref:e,onPointerEnter:we(n.onPointerEnter,()=>f("POINTER_ENTER")),onPointerLeave:we(n.onPointerLeave,()=>f("POINTER_LEAVE"))})})}),mC=m.forwardRef((n,e)=>{const i=Dn(Jn,n.__scopeScrollArea),{forceMount:a,...r}=n,[c,d]=m.useState(!1),h=n.orientation==="horizontal",f=eu(()=>{if(i.viewport){const p=i.viewport.offsetWidth<i.viewport.scrollWidth,y=i.viewport.offsetHeight<i.viewport.scrollHeight;d(h?p:y)}},10);return Ba(i.viewport,f),Ba(i.content,f),l.jsx(qt,{present:a||c,children:l.jsx(Bm,{"data-state":c?"visible":"hidden",...r,ref:e})})}),Bm=m.forwardRef((n,e)=>{const{orientation:i="vertical",...a}=n,r=Dn(Jn,n.__scopeScrollArea),c=m.useRef(null),d=m.useRef(0),[h,f]=m.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),p=bC(h.viewport,h.content),y={...a,sizes:h,onSizesChange:f,hasThumb:p>0&&p<1,onThumbChange:x=>c.current=x,onThumbPointerUp:()=>d.current=0,onThumbPointerDown:x=>d.current=x};function b(x,w){return hP(x,d.current,h,w)}return i==="horizontal"?l.jsx(rP,{...y,ref:e,onThumbPositionChange:()=>{if(r.viewport&&c.current){const x=r.viewport.scrollLeft,w=Gx(x,h,r.dir);c.current.style.transform=`translate3d(${w}px, 0, 0)`}},onWheelScroll:x=>{r.viewport&&(r.viewport.scrollLeft=x)},onDragScroll:x=>{r.viewport&&(r.viewport.scrollLeft=b(x,r.dir))}}):i==="vertical"?l.jsx(lP,{...y,ref:e,onThumbPositionChange:()=>{if(r.viewport&&c.current){const x=r.viewport.scrollTop,w=Gx(x,h);c.current.style.transform=`translate3d(0, ${w}px, 0)`}},onWheelScroll:x=>{r.viewport&&(r.viewport.scrollTop=x)},onDragScroll:x=>{r.viewport&&(r.viewport.scrollTop=b(x))}}):null}),rP=m.forwardRef((n,e)=>{const{sizes:i,onSizesChange:a,...r}=n,c=Dn(Jn,n.__scopeScrollArea),[d,h]=m.useState(),f=m.useRef(null),p=Ie(e,f,c.onScrollbarXChange);return m.useEffect(()=>{f.current&&h(getComputedStyle(f.current))},[f]),l.jsx(gC,{"data-orientation":"horizontal",...r,ref:p,sizes:i,style:{bottom:0,left:c.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:c.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Jc(i)+"px",...n.style},onThumbPointerDown:y=>n.onThumbPointerDown(y.x),onDragScroll:y=>n.onDragScroll(y.x),onWheelScroll:(y,b)=>{if(c.viewport){const x=c.viewport.scrollLeft+y.deltaX;n.onWheelScroll(x),wC(x,b)&&y.preventDefault()}},onResize:()=>{f.current&&c.viewport&&d&&a({content:c.viewport.scrollWidth,viewport:c.viewport.offsetWidth,scrollbar:{size:f.current.clientWidth,paddingStart:Cc(d.paddingLeft),paddingEnd:Cc(d.paddingRight)}})}})}),lP=m.forwardRef((n,e)=>{const{sizes:i,onSizesChange:a,...r}=n,c=Dn(Jn,n.__scopeScrollArea),[d,h]=m.useState(),f=m.useRef(null),p=Ie(e,f,c.onScrollbarYChange);return m.useEffect(()=>{f.current&&h(getComputedStyle(f.current))},[f]),l.jsx(gC,{"data-orientation":"vertical",...r,ref:p,sizes:i,style:{top:0,right:c.dir==="ltr"?0:void 0,left:c.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Jc(i)+"px",...n.style},onThumbPointerDown:y=>n.onThumbPointerDown(y.y),onDragScroll:y=>n.onDragScroll(y.y),onWheelScroll:(y,b)=>{if(c.viewport){const x=c.viewport.scrollTop+y.deltaY;n.onWheelScroll(x),wC(x,b)&&y.preventDefault()}},onResize:()=>{f.current&&c.viewport&&d&&a({content:c.viewport.scrollHeight,viewport:c.viewport.offsetHeight,scrollbar:{size:f.current.clientHeight,paddingStart:Cc(d.paddingTop),paddingEnd:Cc(d.paddingBottom)}})}})}),[cP,pC]=uC(Jn),gC=m.forwardRef((n,e)=>{const{__scopeScrollArea:i,sizes:a,hasThumb:r,onThumbChange:c,onThumbPointerUp:d,onThumbPointerDown:h,onThumbPositionChange:f,onDragScroll:p,onWheelScroll:y,onResize:b,...x}=n,w=Dn(Jn,i),[E,_]=m.useState(null),C=Ie(e,G=>_(G)),D=m.useRef(null),N=m.useRef(""),k=w.viewport,T=a.content-a.viewport,R=Gt(y),z=Gt(f),O=eu(b,10);function A(G){if(D.current){const U=G.clientX-D.current.left,B=G.clientY-D.current.top;p({x:U,y:B})}}return m.useEffect(()=>{const G=U=>{const B=U.target;E?.contains(B)&&R(U,T)};return document.addEventListener("wheel",G,{passive:!1}),()=>document.removeEventListener("wheel",G,{passive:!1})},[k,E,T,R]),m.useEffect(z,[a,z]),Ba(E,O),Ba(w.content,O),l.jsx(cP,{scope:i,scrollbar:E,hasThumb:r,onThumbChange:Gt(c),onThumbPointerUp:Gt(d),onThumbPositionChange:z,onThumbPointerDown:Gt(h),children:l.jsx(je.div,{...x,ref:C,style:{position:"absolute",...x.style},onPointerDown:we(n.onPointerDown,G=>{G.button===0&&(G.target.setPointerCapture(G.pointerId),D.current=E.getBoundingClientRect(),N.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",w.viewport&&(w.viewport.style.scrollBehavior="auto"),A(G))}),onPointerMove:we(n.onPointerMove,A),onPointerUp:we(n.onPointerUp,G=>{const U=G.target;U.hasPointerCapture(G.pointerId)&&U.releasePointerCapture(G.pointerId),document.body.style.webkitUserSelect=N.current,w.viewport&&(w.viewport.style.scrollBehavior=""),D.current=null})})})}),Sc="ScrollAreaThumb",vC=m.forwardRef((n,e)=>{const{forceMount:i,...a}=n,r=pC(Sc,n.__scopeScrollArea);return l.jsx(qt,{present:i||r.hasThumb,children:l.jsx(uP,{ref:e,...a})})}),uP=m.forwardRef((n,e)=>{const{__scopeScrollArea:i,style:a,...r}=n,c=Dn(Sc,i),d=pC(Sc,i),{onThumbPositionChange:h}=d,f=Ie(e,b=>d.onThumbChange(b)),p=m.useRef(void 0),y=eu(()=>{p.current&&(p.current(),p.current=void 0)},100);return m.useEffect(()=>{const b=c.viewport;if(b){const x=()=>{if(y(),!p.current){const w=fP(b,h);p.current=w,h()}};return h(),b.addEventListener("scroll",x),()=>b.removeEventListener("scroll",x)}},[c.viewport,y,h]),l.jsx(je.div,{"data-state":d.hasThumb?"visible":"hidden",...r,ref:f,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...a},onPointerDownCapture:we(n.onPointerDownCapture,b=>{const w=b.target.getBoundingClientRect(),E=b.clientX-w.left,_=b.clientY-w.top;d.onThumbPointerDown({x:E,y:_})}),onPointerUp:we(n.onPointerUp,d.onThumbPointerUp)})});vC.displayName=Sc;var Hm="ScrollAreaCorner",yC=m.forwardRef((n,e)=>{const i=Dn(Hm,n.__scopeScrollArea),a=!!(i.scrollbarX&&i.scrollbarY);return i.type!=="scroll"&&a?l.jsx(dP,{...n,ref:e}):null});yC.displayName=Hm;var dP=m.forwardRef((n,e)=>{const{__scopeScrollArea:i,...a}=n,r=Dn(Hm,i),[c,d]=m.useState(0),[h,f]=m.useState(0),p=!!(c&&h);return Ba(r.scrollbarX,()=>{const y=r.scrollbarX?.offsetHeight||0;r.onCornerHeightChange(y),f(y)}),Ba(r.scrollbarY,()=>{const y=r.scrollbarY?.offsetWidth||0;r.onCornerWidthChange(y),d(y)}),p?l.jsx(je.div,{...a,ref:e,style:{width:c,height:h,position:"absolute",right:r.dir==="ltr"?0:void 0,left:r.dir==="rtl"?0:void 0,bottom:0,...n.style}}):null});function Cc(n){return n?parseInt(n,10):0}function bC(n,e){const i=n/e;return isNaN(i)?0:i}function Jc(n){const e=bC(n.viewport,n.content),i=n.scrollbar.paddingStart+n.scrollbar.paddingEnd,a=(n.scrollbar.size-i)*e;return Math.max(a,18)}function hP(n,e,i,a="ltr"){const r=Jc(i),c=r/2,d=e||c,h=r-d,f=i.scrollbar.paddingStart+d,p=i.scrollbar.size-i.scrollbar.paddingEnd-h,y=i.content-i.viewport,b=a==="ltr"?[0,y]:[y*-1,0];return xC([f,p],b)(n)}function Gx(n,e,i="ltr"){const a=Jc(e),r=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,c=e.scrollbar.size-r,d=e.content-e.viewport,h=c-a,f=i==="ltr"?[0,d]:[d*-1,0],p=Tf(n,f);return xC([0,d],[0,h])(p)}function xC(n,e){return i=>{if(n[0]===n[1]||e[0]===e[1])return e[0];const a=(e[1]-e[0])/(n[1]-n[0]);return e[0]+a*(i-n[0])}}function wC(n,e){return n>0&&n<e}var fP=(n,e=()=>{})=>{let i={left:n.scrollLeft,top:n.scrollTop},a=0;return(function r(){const c={left:n.scrollLeft,top:n.scrollTop},d=i.left!==c.left,h=i.top!==c.top;(d||h)&&e(),i=c,a=window.requestAnimationFrame(r)})(),()=>window.cancelAnimationFrame(a)};function eu(n,e){const i=Gt(n),a=m.useRef(0);return m.useEffect(()=>()=>window.clearTimeout(a.current),[]),m.useCallback(()=>{window.clearTimeout(a.current),a.current=window.setTimeout(i,e)},[i,e])}function Ba(n,e){const i=Gt(e);Dt(()=>{let a=0;if(n){const r=new ResizeObserver(()=>{cancelAnimationFrame(a),a=window.requestAnimationFrame(i)});return r.observe(n),()=>{window.cancelAnimationFrame(a),r.unobserve(n)}}},[n,i])}var SC=dC,mP=fC,pP=yC;const Vm=m.forwardRef(({className:n,children:e,...i},a)=>l.jsxs(SC,{ref:a,className:ye("relative overflow-hidden",n),...i,children:[l.jsx(mP,{className:"h-full w-full rounded-[inherit]",children:e}),l.jsx(CC,{}),l.jsx(pP,{})]}));Vm.displayName=SC.displayName;const CC=m.forwardRef(({className:n,orientation:e="vertical",...i},a)=>l.jsx(Gm,{ref:a,orientation:e,className:ye("flex touch-none select-none transition-colors",e==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",e==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",n),...i,children:l.jsx(vC,{className:"relative flex-1 rounded-full bg-border"})}));CC.displayName=Gm.displayName;var tu="Collapsible",[gP]=cn(tu),[vP,Fm]=gP(tu),_C=m.forwardRef((n,e)=>{const{__scopeCollapsible:i,open:a,defaultOpen:r,disabled:c,onOpenChange:d,...h}=n,[f,p]=_n({prop:a,defaultProp:r??!1,onChange:d,caller:tu});return l.jsx(vP,{scope:i,disabled:c,contentId:Mt(),open:f,onOpenToggle:m.useCallback(()=>p(y=>!y),[p]),children:l.jsx(je.div,{"data-state":$m(f),"data-disabled":c?"":void 0,...h,ref:e})})});_C.displayName=tu;var EC="CollapsibleTrigger",DC=m.forwardRef((n,e)=>{const{__scopeCollapsible:i,...a}=n,r=Fm(EC,i);return l.jsx(je.button,{type:"button","aria-controls":r.contentId,"aria-expanded":r.open||!1,"data-state":$m(r.open),"data-disabled":r.disabled?"":void 0,disabled:r.disabled,...a,ref:e,onClick:we(n.onClick,r.onOpenToggle)})});DC.displayName=EC;var Um="CollapsibleContent",AC=m.forwardRef((n,e)=>{const{forceMount:i,...a}=n,r=Fm(Um,n.__scopeCollapsible);return l.jsx(qt,{present:i||r.open,children:({present:c})=>l.jsx(yP,{...a,ref:e,present:c})})});AC.displayName=Um;var yP=m.forwardRef((n,e)=>{const{__scopeCollapsible:i,present:a,children:r,...c}=n,d=Fm(Um,i),[h,f]=m.useState(a),p=m.useRef(null),y=Ie(e,p),b=m.useRef(0),x=b.current,w=m.useRef(0),E=w.current,_=d.open||h,C=m.useRef(_),D=m.useRef(void 0);return m.useEffect(()=>{const N=requestAnimationFrame(()=>C.current=!1);return()=>cancelAnimationFrame(N)},[]),Dt(()=>{const N=p.current;if(N){D.current=D.current||{transitionDuration:N.style.transitionDuration,animationName:N.style.animationName},N.style.transitionDuration="0s",N.style.animationName="none";const k=N.getBoundingClientRect();b.current=k.height,w.current=k.width,C.current||(N.style.transitionDuration=D.current.transitionDuration,N.style.animationName=D.current.animationName),f(a)}},[d.open,a]),l.jsx(je.div,{"data-state":$m(d.open),"data-disabled":d.disabled?"":void 0,id:d.contentId,hidden:!_,...c,ref:y,style:{"--radix-collapsible-content-height":x?`${x}px`:void 0,"--radix-collapsible-content-width":E?`${E}px`:void 0,...n.style},children:_&&r})});function $m(n){return n?"open":"closed"}var bP=_C;const NC=bP,jC=DC,TC=AC;function xP(){const[n,e]=m.useState({}),[i,a]=m.useState(new Set),[r,c]=m.useState(null),d=m.useCallback(async h=>{if(!(n[h]||i.has(h))){a(f=>new Set(f).add(h)),c(null);try{const f=h?`?path=${encodeURIComponent(h)}`:"",p=await fetch(`/api/files${f}`);if(!p.ok)throw new Error(`Failed to list directory: ${p.statusText}`);const b=(await p.json()).entries.sort((x,w)=>x.type!==w.type?x.type==="directory"?-1:1:x.name.localeCompare(w.name));e(x=>({...x,[h||"__root__"]:b}))}catch(f){c(f instanceof Error?f.message:"Failed to load directory")}finally{a(f=>{const p=new Set(f);return p.delete(h),p})}}},[n,i]);return{cache:n,loading:i,error:r,fetchDirectory:d}}function kC({entry:n,status:e,depth:i,onFileClick:a}){const r=e==="created"?"+":e==="modified"?"~":e==="deleted"?"-":null;return l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsxs("div",{role:"treeitem",className:`file-item${e?` file-${e}`:""}`,style:{paddingLeft:`${12+i*16}px`},tabIndex:0,"aria-label":`${n.name}${e?`, ${e}`:""}`,onClick:()=>a?.(n,e),onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),a?.(n,e))},children:[r&&l.jsx("span",{className:`status-icon status-${e}`,"aria-hidden":"true",children:r}),l.jsx("span",{className:"file-name",children:n.name})]})}),l.jsx(Te,{children:n.path})]})}function RC({entry:n,depth:e,changedFiles:i,onFileClick:a,fetchDirectory:r,cache:c,loading:d}){const h=Array.from(i.keys()).some(w=>w.startsWith(n.path+"/")),[f,p]=m.useState(h),y=c[n.path],b=d.has(n.path);m.useEffect(()=>{h&&!y&&!d.has(n.path)&&r(n.path)},[h,y,n.path,r,d]),m.useEffect(()=>{h&&p(!0)},[h]);const x=m.useCallback(()=>{const w=!f;p(w),w&&!y&&r(n.path)},[f,y,n.path,r]);return l.jsxs(NC,{open:f,onOpenChange:x,children:[l.jsx(jC,{asChild:!0,children:l.jsxs("div",{className:`directory-header${h?" has-changes":""}`,style:{paddingLeft:`${4+e*16}px`},children:[l.jsx("span",{className:"directory-toggle",children:l.jsx("span",{className:"toggle-icon",children:f?"▼":"▶"})}),l.jsx("span",{className:"directory-name",children:n.name})]})}),l.jsxs(TC,{children:[b&&l.jsx("div",{className:"tree-loading",style:{paddingLeft:`${12+(e+1)*16}px`},children:"Loading..."}),y?.map(w=>w.type==="directory"?l.jsx(RC,{entry:w,depth:e+1,changedFiles:i,onFileClick:a,fetchDirectory:r,cache:c,loading:d},w.path):l.jsx(kC,{entry:w,status:i.get(w.path),depth:e+1,onFileClick:a},w.path))]})]})}function wP({changedFiles:n,onFileClick:e}){const{cache:i,loading:a,error:r,fetchDirectory:c}=xP();m.useEffect(()=>{c("")},[]);const d=i.__root__,h=n.size;return l.jsx(St,{delayDuration:300,children:l.jsxs("div",{role:"tree","aria-label":"Project files",className:"filetree full-filetree",children:[h>0&&l.jsx($e,{variant:"secondary","data-testid":"file-count-badge",className:"file-count-badge","aria-label":`${h} files changed`,children:h}),l.jsxs(Vm,{className:"filetree-scroll",children:[r&&l.jsx("div",{className:"tree-error",children:r}),!d&&!r&&l.jsx("div",{className:"tree-loading",children:"Loading project files..."}),d?.map(f=>f.type==="directory"?l.jsx(RC,{entry:f,depth:0,changedFiles:n,onFileClick:e,fetchDirectory:c,cache:i,loading:a},f.path):l.jsx(kC,{entry:f,status:n.get(f.path),depth:0,onFileClick:e},f.path))]})]})})}function Bx(n){const e=n[0]||" ",i=n[1]||" ";return e==="D"||i==="D"?"deleted":e==="?"||e==="A"?"created":"modified"}function OC(){const{repos:n}=Lm(),e=m.useMemo(()=>{const a=new Map;for(const r of n)for(const c of r.files){const d=n.length>1?`${r.path}/${c.path}`:`${r.path}/${c.path}`;a.set(d,Bx(c.status)),a.set(c.path,Bx(c.status))}return a},[n]),i=m.useCallback((a,r)=>{fetch("/api/files/edit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:a.path})}).catch(c=>console.error("[ChangedPanel] Failed to open file:",c))},[]);return l.jsx("div",{className:"changed-panel","data-testid":"changed-panel",children:l.jsx(wP,{changedFiles:e,onFileClick:i})})}const SP=2e3;function CP(){const[n,e]=m.useState([]),[i,a]=m.useState(null),r=m.useRef(null);m.useEffect(()=>{let h=null,f=!0;const p=()=>{const y=window.location.protocol==="https:"?"wss:":"ws:",b=new WebSocket(`${y}//${window.location.host}/ws/diffs`);r.current=b,b.onopen=()=>{console.log("[useDiffs] WebSocket connected")},b.onmessage=x=>{try{const w=JSON.parse(x.data);if(w.type==="init"){const E=w.diffs||[];e(E),E.length>0&&a(E[E.length-1])}else if(w.type==="diff"){const E=w.diff;e(_=>{const C=_.findIndex(D=>D.path===E.path);if(C>=0){const D=[..._];return D[C]=E,D}return[..._,E]}),a(E)}else if(w.type==="refresh"){const E=w.diffs||[];e(E),E.length>0?a(_=>{if(_){const C=E.find(D=>D.path===_.path);if(C)return C}return E[E.length-1]}):a(null)}}catch(w){console.error("[useDiffs] Failed to parse message:",w)}},b.onclose=()=>{f&&(h=setTimeout(p,SP))},b.onerror=x=>{console.error("[useDiffs] WebSocket error:",x),b.close()}};return p(),()=>{f=!1,h&&clearTimeout(h),r.current?.close()}},[]);const c=m.useCallback(h=>{const f=n.find(p=>p.path===h);a(f||null)},[n]),d=m.useCallback(()=>{e([]),a(null),r.current?.readyState===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"clear"}))},[]);return{diffs:n,selectedDiff:i,selectDiff:c,clearDiffs:d}}function _P({line:n,type:e,lineNum:i}){return l.jsxs("div",{className:`diff-line diff-${e}`,children:[i!==void 0&&l.jsx("span",{className:"line-num",children:i}),l.jsx("span",{className:"line-content",children:n})]})}function EP(n){const e=n.split(`
63
+ `)}function mM(n,e){return n==="Read"&&e.file_path?String(e.file_path):n==="Bash"&&e.command?String(e.command):n==="Glob"&&e.pattern||n==="Grep"&&e.pattern?String(e.pattern):n==="Write"&&e.file_path?String(e.file_path):JSON.stringify(e,null,2)}function ES(n){return{Read:"R",Write:"W",Bash:"B",Glob:"G",Grep:"S",Edit:"E",Task:"T",WebFetch:"F",WebSearch:"W",TodoWrite:"D"}[n]||n.charAt(0).toUpperCase()}function Rm({toolUse:n,result:e,className:i}){const[a,r]=m.useState(!0),[c,d]=m.useState(!0),[h,f]=m.useState(!1),[p,y]=m.useState("idle"),b=e?.is_error===!0,x=mM(n.tool_name,n.input),w=Object.keys(n.input).length,E=cM(n.tool_name),_=m.useMemo(()=>Af(n.tool_name,n.input),[n.tool_name,n.input]),C=m.useMemo(()=>e?hM(e.content):0,[e?.content]),D=C>bx,N=D&&!h,k=m.useMemo(()=>e?N?fM(e.content,bx):e.content:"",[e?.content,N]),T=async()=>{if(e)try{await navigator.clipboard.writeText(e.content),y("copied"),setTimeout(()=>y("idle"),2e3)}catch{y("error")}},R=C===1?"1 line":`${C} lines`,z=["tool-call-block",E,b?"tool-error":"",i||""].filter(Boolean).join(" "),O=ES(n.tool_name);return l.jsx(St,{delayDuration:300,children:l.jsxs("div",{"data-testid":"tool-call-block",className:z,children:[l.jsxs("div",{className:"tool-header",children:[l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx($e,{variant:"default",className:"tool-type-badge",children:O})}),l.jsx(Te,{children:n.tool_name})]}),l.jsx("span",{className:"tool-name",children:_}),l.jsx("span",{"data-testid":"tool-duration",className:"tool-duration",children:e?.durationMs!==void 0?_S(e.durationMs):""})]}),l.jsx("div",{className:"tool-result-header",children:l.jsxs(Ce,{variant:"ghost",size:"sm","data-testid":"tool-prompt-toggle",className:"tool-result-toggle",onClick:()=>d(!c),children:[c?"▶":"▼"," Prompt (",w," ",w===1?"param":"params",")"]})}),l.jsx("div",{"data-testid":"tool-prompt-content",className:`tool-result-content ${c?"collapsed":""}`,children:l.jsx("pre",{children:x})}),e&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"tool-result-header",children:[l.jsxs(Ce,{variant:"ghost",size:"sm","data-testid":"tool-result-toggle",className:"tool-result-toggle",onClick:()=>r(!a),children:[a?"▶":"▼"," Result (",R,")"]}),l.jsx(Ce,{variant:"ghost",size:"icon","data-testid":"tool-result-copy",className:`tool-result-copy ${p==="copied"?"copied":""} ${p==="error"?"copy-error":""}`,onClick:T,"aria-label":"Copy result to clipboard",children:p==="copied"?"✓":"📋"})]}),l.jsxs("div",{"data-testid":"tool-result-content",className:`tool-result-content ${a?"collapsed":""} ${N&&!a?"truncated":""} ${b?"error-content":""}`,children:[l.jsx("pre",{children:k}),D&&!a&&N&&l.jsxs(Ce,{variant:"link",size:"sm","data-testid":"tool-result-expand",className:"tool-result-expand",onClick:()=>f(!0),children:["Show all (",C," lines)"]})]})]})]})})}function pM({stack:n,toolResults:e}){const[i,a]=m.useState(!n.isActive),r=m.useRef(n.isActive);m.useEffect(()=>{r.current&&!n.isActive&&a(!1),r.current=n.isActive},[n.isActive]);const c=`${n.count}`,d=m.useMemo(()=>{if(n.isActive&&n.tools.length>0){const E=n.tools[n.tools.length-1];return Af(E.tool_name,E.input)}return null},[n.tools,n.isActive]),h=m.useMemo(()=>{if(n.tools.length===0)return"";const E=n.tools[n.tools.length-1];return Af(E.tool_name,E.input)},[n.tools]),f=m.useMemo(()=>{const E=new Map;return n.tools.forEach(_=>{const C=E.get(_.tool_name)||0;E.set(_.tool_name,C+1)}),E},[n.tools]),p=m.useMemo(()=>n.tools.reduce((E,_)=>{const C=e.get(_.tool_id);return E+(C?.durationMs||0)},0),[n.tools,e]),y=E=>{const _=n.tools[E],C=e.get(_.tool_id);return n.isActive&&E===n.tools.length-1&&!C?"tool-current":"tool-historical"},b=m.useCallback(()=>{a(E=>!E)},[]),x=m.useCallback(E=>{(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),b())},[b]),w=!i||n.isActive;return l.jsxs("div",{"data-testid":"tool-stack","data-collapsible":"true",className:`tool-stack ${i&&!n.isActive?"collapsed":""}`,children:[l.jsxs("div",{"data-testid":"tool-stack-header",className:"tool-stack-header",onClick:b,onKeyDown:x,role:"button",tabIndex:0,"aria-expanded":!i||n.isActive,"aria-label":`Tool stack with ${c}: ${h}`,children:[l.jsx("span",{className:"tool-stack-toggle",children:i&&!n.isActive?"▶":"▼"}),l.jsx("span",{"data-testid":"tool-stack-count",className:"tool-stack-count-badge",children:c}),n.isActive&&d?l.jsx("span",{className:"tool-stack-active-summary",children:d}):l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"tool-stack-badges",children:l.jsx(St,{delayDuration:300,children:Array.from(f.entries()).slice(0,4).map(([E,_])=>l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx($e,{variant:"outline",className:`tool-mini-badge badge-${E.toLowerCase()}`,children:ES(E)})}),l.jsx(Te,{children:`${_} ${E} call${_>1?"s":""}`})]},E))})}),l.jsx("span",{className:"tool-stack-summary",children:h})]}),l.jsx("span",{className:"tool-stack-duration",children:p>0?_S(p):""})]}),w&&l.jsx("div",{className:"tool-stack-content",children:n.tools.map((E,_)=>{const C=e.get(E.tool_id),D=y(_);return l.jsx(Rm,{toolUse:{type:"tool_use",tool_name:E.tool_name,tool_id:E.tool_id,input:E.input,timestamp:E.timestamp},result:C?{type:"tool_result",tool_id:C.tool_id,content:C.content,timestamp:C.timestamp}:void 0,className:D},E.tool_id||`tool-${_}`)})})]})}const Yh=new Map;let xc=null;async function gM(){if(!xc)try{const n=await fetch("/api/theme-agents/full");n.ok&&(xc=await n.json())}catch{}}async function vM(n){const e=`agent:${n}`;if(Yh.has(e))return Yh.get(e);try{if(await gM(),xc?.agents){const i=xc.agents.find(a=>a.role===n);if(i?.helper)return Yh.set(e,i.helper),i.helper}return null}catch{return null}}const xx={"testing-runner":"Running tests",Explore:"Exploring codebase","sm-setup":"Setting up story","sm-finish":"Finishing story",handoff:"Handing off","workflow-status-check":"Checking workflow status","general-purpose":"Processing task",Plan:"Planning implementation",Bash:"Running commands"};function yM(n,e){const i=e?.plural?"are":"is",a=n.description,r=n.subagent_type;if(r&&xx[r]){const c=xx[r],d=c.charAt(0).toLowerCase()+c.slice(1);return a?`${i} ${d}: ${a}`:`${i} ${d}`}return a||"Working..."}function bM(){const[n,e]=m.useState(null),[i,a]=m.useState(!0),[r,c]=m.useState(null);return m.useEffect(()=>{const d=async p=>{try{const y=await vM(p);e(y),a(!1)}catch(y){c(y instanceof Error?y:new Error("Failed to fetch helper")),a(!1)}},h=window.location.protocol==="https:"?"wss:":"ws:",f=new WebSocket(`${h}//${window.location.host}/ws/persona`);return f.onmessage=p=>{try{const y=JSON.parse(p.data);y?.role&&d(y.role)}catch(y){c(y instanceof Error?y:new Error("Failed to parse persona")),a(!1)}},f.onerror=()=>{c(new Error("WebSocket connection failed")),a(!1)},()=>f.close()},[]),{helper:n,isLoading:i,error:r}}function xM({type:n,name:e,messages:i,defaultCollapsed:a=!0,onCollapseChange:r,helperName:c,helperStyle:d,friendlyMessage:h}){const[f,p]=m.useState(a),{helper:y}=bM(),b=m.useMemo(()=>yM({subagent_type:n,description:e},{plural:y?.plural}),[n,e,y?.plural]),x=c??y?.name,w=d??y?.style,E=h??b,_=x||n,C=E||e,D=i.filter(T=>T.type!=="tool_result").length,N=new Map;i.forEach(T=>{T.type==="tool_result"&&T.tool_id&&N.set(T.tool_id,T)});const k=(T,R)=>{if(T.type==="tool_use"&&T.tool_name&&T.tool_id){const z=N.get(T.tool_id);return l.jsx("div",{"data-testid":"message-tool_use",className:"message message-tool_use",children:l.jsx(Rm,{toolUse:{type:"tool_use",tool_name:T.tool_name,tool_id:T.tool_id,input:T.input||{},timestamp:T.timestamp},result:z?{type:"tool_result",tool_id:z.tool_id,content:z.content||"",timestamp:z.timestamp}:void 0})},`tool-wrapper-${T.tool_id}`)}if(T.type==="tool_result")return null;if(T.type==="user"){const z=(T.content||"").slice(0,120).replace(/\n/g," ");return l.jsx("div",{"data-testid":"subagent-prompt",className:"message message-subagent-prompt",children:l.jsxs("div",{className:"message-content",children:[z,(T.content||"").length>120?"...":""]})},`subagent-prompt-${R}`)}return l.jsx(CS,{message:{type:T.type,content:T.content,timestamp:T.timestamp}},`msg-${R}`)};return l.jsxs("div",{"data-testid":"subagent-span","data-collapsible":"true",className:`subagent-span subagent-${n} ${f?"collapsed":""}`,children:[l.jsxs("div",{"data-testid":"subagent-span-header",className:"subagent-header",onClick:()=>{const T=!f;p(T),r?.(T)},children:[l.jsx("span",{className:"subagent-toggle",children:f?"▶":"▼"}),l.jsx(St,{delayDuration:300,children:w?l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{className:"subagent-helper-name",children:_})}),l.jsx(Te,{children:w})]}):l.jsx("span",{className:"subagent-helper-name",children:_})}),l.jsx("span",{className:"subagent-friendly-message",children:C}),l.jsx($e,{variant:"outline","data-testid":"subagent-type-badge",className:"subagent-type-badge",children:n}),l.jsx("span",{className:"subagent-count",children:D})]}),!f&&l.jsx("div",{className:"subagent-content",children:i.map((T,R)=>k(T,R))})]})}const wx=/<!--\s*CYCLIST:(\w+)(?::([^>]+?))?\s*-->/gi,As={HANDOFF:"handoff",CONTEXT_CLEAR:"context_clear",INVOKE:"invoke",QUESTION:"question",CHOICES:"choices",CONTINUE:"continue"},wM=new Set(["handoff","context_clear","invoke","question","choices","continue"]);function SM(n){return n?n.replace(/```[\s\S]*?```/g,""):""}function CM(n){if(!n)return null;const e=SM(n);if(!e.trim())return null;const i=[];wx.lastIndex=0;let a;for(;(a=wx.exec(e))!==null;){const r=a[1].toLowerCase();wM.has(r)&&i.push({type:r,value:a[2]?.trim()??"",source:"structured_marker"})}return i.length>0?i:null}function _M(n,e){if(!n)return e.map(c=>({number:c,text:`Option ${c}`}));const i=n.replace(/```[\s\S]*?```/g,""),a=[/^\s*(\d+)\.\s+(.+)$/gm,/^\s*(\d+)\)\s+(.+)$/gm,/\*\*(\d+)[.)]\*\*\s*(.+)/gm],r=new Map;for(const c of a){c.lastIndex=0;let d;for(;(d=c.exec(i))!==null;){const h=parseInt(d[1],10);if(e.includes(h)&&!r.has(h)){let f=d[2].trim();const p=f.search(/\s+[-—]\s+/);p>0&&p<30&&(f=f.substring(0,p)),r.set(h,f)}}}return e.map(c=>({number:c,text:r.get(c)||`Option ${c}`}))}function EM(n,e){if(!n||n.length===0)return null;const i=n[0];switch(i.type){case As.HANDOFF:return{type:"handoff",value:i.value,responses:[i.value,"Not yet"]};case As.INVOKE:return{type:"invoke",value:i.value,autoExecute:!0};case As.QUESTION:{if(i.value==="yesno")return{type:"yesno",responses:["Yes","No"]};if(i.value?.startsWith("open")){const r=i.value.indexOf(":");if(r!==-1){const c=i.value.substring(r+1).trim();if(c)return{type:"open",responses:[c]}}return{type:"open"}}const a=n.find(r=>r.type===As.CHOICES);return a?Sx(a.value,e):null}case As.CHOICES:return Sx(i.value,e);case As.CONTEXT_CLEAR:return{type:"context_clear",value:i.value};case As.CONTINUE:return{type:"continue",responses:["Continue"]};default:return null}}function Sx(n,e){const i=n.split(",").map(d=>d.trim()),a=i[0],r=/^\d+$/.test(a);let c;if(r){const d=i.map(h=>parseInt(h,10));c=_M(e,d)}else c=i.map((d,h)=>({number:h+1,text:d}));return{type:"choices",choices:c,responses:c.map(d=>d.text)}}function DM(n){return m.useMemo(()=>{if(!n)return null;const e=CM(n);return e?EM(e,n):null},[n])}async function AM(){try{const n=await fetch("/api/settings");if(n.ok)return(await n.json())?.workflow?.relay_mode??!1}catch{}return!1}function NM(n){const{send:e}=dr(),i=m.useCallback(x=>{console.log("[QuickActions] sendMessage called:",x),e(x,[])},[e]),{onAction:a}=n,[r,c]=m.useState(!1),[d,h]=m.useState(!1),f="message"in n?n.message:void 0,p="actions"in n?n.actions:void 0,y=DM(f?.content);m.useEffect(()=>{c(!1)},[f?.timestamp]),m.useEffect(()=>{AM().then(h)},[]),m.useEffect(()=>{const x=()=>{c(!0)};return window.addEventListener("cyclist:user-submit",x),()=>{window.removeEventListener("cyclist:user-submit",x)}},[]),m.useEffect(()=>{if(y?.type==="handoff"&&d&&y.value){const x=setTimeout(()=>{i(y.value),c(!0),a?.(y.value)},100);return()=>clearTimeout(x)}if(y?.type==="invoke"&&y.value){const x=setTimeout(()=>{i(y.value),c(!0),a?.(y.value)},100);return()=>clearTimeout(x)}},[y,d,a]),m.useEffect(()=>{if(y?.type==="open"&&y.responses&&y.responses.length>0){const x=y.responses[0];window.dispatchEvent(new CustomEvent("cyclist:suggest-prompt",{detail:{prompt:x}}))}},[y]);const b=m.useCallback(x=>{console.log("[QuickActions] Button clicked:",x),c(!0),i(x),a?.(x)},[a]);return p&&p.length>0?l.jsx("div",{className:"quick-actions",children:l.jsx("div",{className:"quick-actions-buttons",children:p.map(x=>l.jsx(Ce,{variant:"secondary",size:"sm",type:"button",className:"quick-action-btn",onClick:()=>b(x.command),disabled:r,"aria-label":`${x.label}: ${x.command}`,children:x.label},x.command))})}):!y||y.type==="open"||y.type==="continue"?null:y.type==="invoke"?l.jsx("div",{className:"quick-actions",children:l.jsxs("span",{className:"auto-invoke-status",children:["Invoking ",y.value,"..."]})}):y.type==="handoff"&&d?l.jsx("div",{className:"quick-actions",children:l.jsxs("span",{className:"auto-invoke-status",children:["Handing off to ",y.value,"..."]})}):l.jsxs("div",{className:"quick-actions",children:[y.type==="handoff"&&y.responses&&l.jsx("div",{className:"quick-actions-buttons",children:y.responses.map(x=>l.jsx(Ce,{variant:"secondary",size:"sm",type:"button",className:"quick-action-btn",onClick:()=>b(x),disabled:r,"aria-label":`Continue with ${x}`,children:x},x))}),y.type==="yesno"&&l.jsxs("div",{className:"quick-actions-buttons",children:[l.jsx(Ce,{variant:"secondary",size:"sm",type:"button",className:"quick-action-btn",onClick:()=>b("Yes"),disabled:r,"aria-label":"Answer Yes",children:"Yes"}),l.jsx(Ce,{variant:"secondary",size:"sm",type:"button",className:"quick-action-btn",onClick:()=>b("No"),disabled:r,"aria-label":"Answer No",children:"No"})]}),y.type==="choices"&&y.choices&&l.jsx("div",{className:"quick-actions-buttons",children:y.choices.map(x=>l.jsx(Ce,{variant:"secondary",size:"sm",type:"button",className:"quick-action-btn",onClick:()=>b(x.text),disabled:r,"aria-label":`Choose option ${x.number}: ${x.text}`,children:x.text},x.number))})]})}var jM="Separator",Cx="horizontal",TM=["horizontal","vertical"],DS=m.forwardRef((n,e)=>{const{decorative:i,orientation:a=Cx,...r}=n,c=kM(a)?a:Cx,h=i?{role:"none"}:{"aria-orientation":c==="vertical"?c:void 0,role:"separator"};return l.jsx(In.div,{"data-orientation":c,...h,...r,ref:e})});DS.displayName=jM;function kM(n){return TM.includes(n)}var AS=DS;const Rt=m.forwardRef(({className:n,orientation:e="horizontal",decorative:i=!0,...a},r)=>l.jsx(AS,{ref:r,decorative:i,orientation:e,className:ye("shrink-0 bg-border",e==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",n),...a}));Rt.displayName=AS.displayName;const RM=["<command-message>","<command-name>","Base directory for this skill:","Launching skill:"],OM=[/^```bash\s*\npf agent start\b/,/^pf agent start\b/,/^<purpose>/,/^<when-to-use>/,/^<execution>/,/^<critical>\s*\n/],ql={sm:"Scrum Master",tea:"Test Engineer",dev:"Developer",reviewer:"Reviewer",architect:"Architect",pm:"Product Manager","tech-writer":"Tech Writer","ux-designer":"UX Designer",devops:"DevOps",orchestrator:"Orchestrator",ba:"Business Analyst"};function zM(n){if(!n||typeof n!="string")return!1;if(RM.some(i=>n.includes(i)))return!0;const e=n.trimStart();return OM.some(i=>i.test(e))}function MM(n){if(!n||typeof n!="string")return null;const e=n.match(/<command-name>\/?([^<]+)<\/command-name>/);if(e){const c=e[1].trim();return ql[c]||c}const i=n.match(/<command-message>([^<]+)<\/command-message>/);if(i){const c=i[1].trim();return ql[c]||c}const a=n.match(/pf agent start\s+"([^"]+)"/);if(a){const c=a[1].trim();return ql[c]||c}const r=n.match(/Launching skill:\s*(\S+)/);if(r){const c=r[1].trim();return ql[c]||c}return null}function _x(n){return n.length===0?"stack-empty":`stack-${n[0].tool_id}`}function PM(n){const e=[];let i=[];for(const a of n)if(a.type==="tool_use")i.push({type:"tool_use",tool_name:a.tool_name||"",tool_id:a.tool_id||"",input:a.input||{},timestamp:a.timestamp,isStreaming:a.isStreaming});else{if(a.type==="tool_result")continue;if(i.length>=1){const r=i[i.length-1];e.push({stackId:_x(i),tools:[...i],count:i.length,isActive:r.isStreaming===!0,timestamp:i[0].timestamp})}i=[]}if(i.length>=1){const a=i[i.length-1];e.push({stackId:_x(i),tools:[...i],count:i.length,isActive:a.isStreaming===!0,timestamp:i[0].timestamp})}return e}function Xh(){const n=document.documentElement.getAttribute("data-variant");return n==="light"||n==="dark"?n:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function NS(){const[n,e]=m.useState(Xh);return m.useEffect(()=>{const i=new MutationObserver(()=>{e(Xh())});i.observe(document.documentElement,{attributes:!0,attributeFilter:["data-variant"]});const a=()=>e(Xh());return window.addEventListener("presetChange",a),()=>{i.disconnect(),window.removeEventListener("presetChange",a)}},[]),n}const Ex=2e3;function Om(){const[n,e]=m.useState(null),[i,a]=m.useState(null),[r,c]=m.useState(null),[d,h]=m.useState(!0),[f,p]=m.useState(null),y=m.useRef({context:!1,stats:!1,projectInfo:!1}),b=m.useCallback(()=>{const x=y.current;x.context&&x.stats&&x.projectInfo&&h(!1)},[]);return m.useEffect(()=>{let x=null,w=null,E=!0;const _=()=>{const C=window.location.protocol==="https:"?"wss:":"ws:";x=new WebSocket(`${C}//${window.location.host}/ws/context`),x.onopen=()=>{console.log("[useStatsStrip] Context WebSocket connected")},x.onmessage=D=>{try{const N=JSON.parse(D.data);if(N.type==="init"||N.type==="update"){const k=N.context;k&&e({percent:k.percent??0,used:k.tokens??void 0,total:k.available?(k.tokens??0)+k.available:void 0}),y.current.context||(y.current.context=!0,b())}}catch(N){console.error("[useStatsStrip] Failed to parse context message:",N)}},x.onclose=()=>{E&&(w=setTimeout(_,Ex))},x.onerror=D=>{console.error("[useStatsStrip] Context WebSocket error:",D),x?.close()}};return _(),()=>{E=!1,w&&clearTimeout(w),x?.close()}},[b]),m.useEffect(()=>{let x=null,w=null,E=!0;const _=()=>{const C=window.location.protocol==="https:"?"wss:":"ws:";x=new WebSocket(`${C}//${window.location.host}/ws/stats`),x.onopen=()=>{console.log("[useStatsStrip] Stats WebSocket connected")},x.onmessage=D=>{try{const N=JSON.parse(D.data);a({model:N.model??null}),N.pwd&&c(k=>({pwd:N.pwd,jiraEmail:k?.jiraEmail??null,githubUsername:k?.githubUsername??null})),y.current.stats||(y.current.stats=!0,b())}catch(N){console.error("[useStatsStrip] Failed to parse stats message:",N)}},x.onclose=()=>{E&&(w=setTimeout(_,Ex))},x.onerror=D=>{console.error("[useStatsStrip] Stats WebSocket error:",D),x?.close()}};return _(),()=>{E=!1,w&&clearTimeout(w),x?.close()}},[b]),m.useEffect(()=>{(async()=>{try{const w=await fetch("/api/identity");if(w.ok){const E=await w.json();c(_=>({pwd:_?.pwd??"",jiraEmail:E.jiraEmail??null,githubUsername:E.githubUsername??null}))}}catch(w){console.error("[useStatsStrip] Failed to fetch identity:",w),p(w instanceof Error?w:new Error("Failed to fetch identity"))}finally{y.current.projectInfo=!0,b()}})()},[b]),{context:n,stats:i,projectInfo:r,isLoading:d,error:f}}const LM={pm:"#a78bfa",sm:"#60a5fa",dev:"#4ade80",tea:"#2dd4bf",reviewer:"#f87171",architect:"#fb923c",devops:"#22d3ee","ux-designer":"#f0abfc","tech-writer":"#e5e5e5",orchestrator:"#e879f9",ba:"#a3e635"},IM={pm:"PM",sm:"SM",dev:"DEV",tea:"TEA",reviewer:"REV",architect:"ARC",devops:"OPS","ux-designer":"UX","tech-writer":"TW",orchestrator:"ORC",ba:"BA"};function Dx(n){return new Date(n).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function GM(n){if("isToolStack"in n||"messages"in n)return"agent";const e=n;return e.type==="context_cleared"?"system":e.type==="user"||e.type==="bell_injected"?"user":"agent"}function BM({messages:n}){const e=m.useRef(null),[i,a]=m.useState(!0),{persona:r}=Zc(),c=NS(),{projectInfo:d}=Om(),h=m.useRef(new Map),f=m.useCallback(C=>{a(C)},[]),p=m.useCallback(()=>{e.current?.scrollToBottom("smooth")},[]),y=m.useMemo(()=>{for(let C=n.length-1;C>=0;C--)if(n[C].type==="agent"&&!n[C].isStreaming)return n[C];return null},[n]),{turns:b,toolResults:x,lastAgentItemIndex:w}=m.useMemo(()=>{const C=new Map;for(const B of n)B.type==="tool_result"&&B.tool_id&&C.set(B.tool_id,B);const D=[],N=new Map;let k=!1;for(const B of n)if(B.type!=="tool_result"){if(B.type==="user"&&zM(B.content)){const $=MM(B.content);$&&!k&&(k=!0,D.push({...B,content:$}));continue}if(B.type==="user"&&(k=!1),B.parent_id){let $=N.get(B.parent_id);$||($={parent_id:B.parent_id,type:B.subagent_type||"unknown",name:B.subagent_name||"unnamed",messages:[]},N.set(B.parent_id,$)),$.messages.push(B);continue}D.push(B)}const T=PM(D),R=new Map;for(const B of T)for(const $ of B.tools)R.set($.tool_id,B);const z=[],O=new Set,A=new Set;for(const B of D)if(B.type==="tool_use"&&B.tool_id&&R.has(B.tool_id)){const $=R.get(B.tool_id);O.has($.stackId)||(O.add($.stackId),z.push({isToolStack:!0,stack:$}))}else z.push(B);for(const[,B]of N)A.has(B.parent_id)||(A.add(B.parent_id),z.push(B));let G=-1;for(let B=z.length-1;B>=0;B--){const $=z[B];if(!("isToolStack"in $)&&!("messages"in $)&&$.type==="agent"){G=B;break}}const U=[];for(const B of z){const $=GM(B),ae=U[U.length-1];ae&&ae.speaker===$?ae.items.push(B):U.push({speaker:$,items:[B],timestamp:"timestamp"in B?B.timestamp:Date.now()})}return{turns:U,toolResults:C,lastAgentItemIndex:G}},[n]),E=(C,D,N)=>{if("isToolStack"in C)return l.jsx(pM,{stack:C.stack,toolResults:x},`stack-${C.stack.stackId}`);if("messages"in C&&"parent_id"in C){const T=C,R=h.current.get(T.parent_id)??!0;return l.jsx(xM,{type:T.type,name:T.name,messages:T.messages,defaultCollapsed:R,onCollapseChange:z=>h.current.set(T.parent_id,z)},`subagent-${T.parent_id}`)}const k=C;if(k.type==="tool_use"&&k.tool_name&&k.tool_id){if(k.tool_name==="AskUserQuestion")return null;const T=x.get(k.tool_id);return l.jsx(Rm,{toolUse:{type:"tool_use",tool_name:k.tool_name,tool_id:k.tool_id,input:k.input||{},timestamp:k.timestamp},result:T?{type:"tool_result",tool_id:T.tool_id,content:T.content||"",timestamp:T.timestamp,is_error:T.is_error,durationMs:T.durationMs}:void 0},`tool-${k.tool_id}`)}return l.jsx(CS,{message:k,isLastAgentMessage:D===w,isFirstInTurn:N},`msg-${D}-${k.timestamp}`)};if(n.length===0)return l.jsx("div",{"data-testid":"message-view",className:"message-view",children:l.jsx("div",{className:"message-view-empty",children:l.jsxs("div",{children:[l.jsx("img",{src:c==="dark"?"/images/cyclist-dark.png":"/images/cyclist-light.png",alt:"Cyclist",style:{height:"2.5rem",opacity:.6,display:"block",margin:"0 auto 0.5rem"}}),l.jsxs("div",{children:["Type ",l.jsx("code",{style:{background:"var(--bg-tertiary, #0f0f1a)",padding:"2px 6px",borderRadius:"3px",fontFamily:"var(--font-mono, monospace)"},children:"/sm"})," to start"]})]})})});let _=0;return l.jsxs("div",{"data-testid":"message-view",className:"message-view",role:"log","aria-live":"polite",children:[l.jsx(SS,{ref:e,onScrollChange:f,autoScroll:i,children:b.map((C,D)=>{if(C.speaker==="system")return C.items.forEach(()=>_++),l.jsx("div",{className:"turn-group turn-system",children:l.jsxs("div",{className:"context-cleared-bar",children:[l.jsx(Rt,{className:"context-cleared-line"}),l.jsx("span",{className:"context-cleared-label",children:"Context cleared"}),l.jsx("span",{className:"context-cleared-time",children:Dx(C.timestamp)}),l.jsx(Rt,{className:"context-cleared-line"})]})},`turn-${D}`);let N=!1;const k=r?.character||"Agent",T=r?.role||null,R=T?IM[T]||T:null,z=T?LM[T]||"#e879f9":void 0,O=d?.githubUsername||"You";return l.jsxs("div",{className:`turn-group turn-${C.speaker}`,children:[l.jsxs("div",{className:"turn-label",children:[l.jsx("span",{className:"turn-speaker",children:C.speaker==="user"?O:k}),C.speaker==="agent"&&R&&l.jsx($e,{variant:"default",className:"turn-role-badge",style:{backgroundColor:z},children:R}),l.jsx("span",{className:"turn-timestamp",children:Dx(C.timestamp)})]}),C.items.map(A=>{const G=_++,U=!("isToolStack"in A)&&!("messages"in A)&&A.type!=="tool_use",B=U&&!N;return U&&(N=!0),E(A,G,B)})]},`turn-${D}`)})}),y&&l.jsx(NM,{message:y}),l.jsx("div",{"data-testid":"auto-scroll-indicator","data-active":i.toString(),className:"auto-scroll-indicator",style:{display:"none"}}),l.jsx(Ce,{variant:"ghost",size:"icon","data-testid":"scroll-to-bottom-button",className:"scroll-to-bottom-button",onClick:p,style:{visibility:i?"hidden":"visible"},children:"↓"})]})}const Ax="cyclist-command-history",HM=100;function VM(){const[n,e]=m.useState(()=>{try{const p=localStorage.getItem(Ax);return p?JSON.parse(p):[]}catch{return[]}}),i=m.useRef(-1),a=m.useRef(""),r=m.useCallback(p=>{try{localStorage.setItem(Ax,JSON.stringify(p))}catch{}},[]),c=m.useCallback(p=>{p.trim()&&e(y=>{if(y.length>0&&y[y.length-1]===p)return y;const b=[...y,p];return b.length>HM&&b.shift(),r(b),b})},[r]),d=m.useCallback(p=>{if(n.length===0)return null;if(i.current===-1)a.current=p,i.current=n.length-1;else if(i.current>0)i.current--;else return null;return n[i.current]},[n]),h=m.useCallback(()=>{if(i.current===-1)return null;if(i.current++,i.current>=n.length){i.current=-1;const p=a.current;return a.current="",p}return n[i.current]},[n]),f=m.useCallback(()=>{i.current=-1,a.current=""},[]);return{addToHistory:c,navigateUp:d,navigateDown:h,resetNavigation:f}}const jS=[{name:"/add",description:"Add files to context"},{name:"/bug",description:"Report a bug"},{name:"/clear",description:"Clear conversation history"},{name:"/compact",description:"Toggle compact mode"},{name:"/config",description:"Show configuration"},{name:"/cost",description:"Show session cost"},{name:"/doctor",description:"Check system health"},{name:"/help",description:"Show available commands"},{name:"/init",description:"Initialize CLAUDE.md"},{name:"/login",description:"Authenticate with Anthropic"},{name:"/logout",description:"Clear authentication"},{name:"/memory",description:"Edit CLAUDE.md memory"},{name:"/model",description:"Switch Claude model"},{name:"/permissions",description:"View/edit permissions"},{name:"/pf-architect",description:"System Architect - Technical design and architecture"},{name:"/pf-ba",description:"Business Analyst - Requirements discovery and stakeholder analysis"},{name:"/pf-benchmark",description:"Compare an agent's performance against a stored baseline"},{name:"/pf-benchmark-control",description:"Create control baseline for a scenario (shortcut for /benchmark control <agent>)"},{name:"/pf-brainstorming",description:"Structured problem-solving brainstorm session"},{name:"/pf-check",description:"Run quality gates (lint, type check, tests) before handoff"},{name:"/pf-chore",description:"Quick commit for small changes without full git-cleanup ceremony"},{name:"/pf-ci",description:"Detect and run CI locally"},{name:"/pf-dev",description:"Developer - Feature implementation and coding"},{name:"/pf-devops",description:"DevOps Engineer - Infrastructure and deployment automation"},{name:"/pf-docs",description:"Domain documentation management"},{name:"/pf-epic",description:"Epic lifecycle - start epics for development and close completed epics"},{name:"/pf-fix-blocker",description:"Quick alias for /patch - fix blocking issue during story work"},{name:"/pf-git",description:"Repository operations - status, cleanup, branches, and release management"},{name:"/pf-health-check",description:"Check Pennyfarthing installation health and apply updates"},{name:"/pf-help",description:"Context-aware help for Pennyfarthing commands, agents, and workflows"},{name:"/pf-job-fair",description:"Discover which characters in a theme excel at each role"},{name:"/pf-orchestrator",description:"Orchestrator - Coordinator of all agents and meta operations"},{name:"/pf-party-mode",description:"Creative brainstorming and multi-agent discussion"},{name:"/pf-patch",description:"Interrupt-driven bug fix during active story work"},{name:"/pf-permissions",description:"View and manage runtime permission grants - list, grant, revoke, or show details"},{name:"/pf-pm",description:"Product Manager - Strategic planning and prioritization"},{name:"/pf-prime",description:"Load essential project context at agent activation"},{name:"/pf-retro",description:"Facilitate a sprint retrospective"},{name:"/pf-reviewer",description:"Code Reviewer - Critical code review and quality enforcement"},{name:"/pf-session",description:"Session lifecycle - start new work and resume checkpoints"},{name:"/pf-setup",description:"/setup - Interactive Project Setup"},{name:"/pf-sm",description:"Scrum Master - Story coordination and sprint management"},{name:"/pf-solo",description:"Run a single agent on a scenario with absolute rubric scoring"},{name:"/pf-sprint",description:"Sprint status, backlog, and story management - check status, find work, archive completed stories"},{name:"/pf-standalone",description:"Wrap current changes into a standalone Jira story, branch, PR, and merge"},{name:"/pf-tea",description:"Test Engineer/Architect - Test strategy and TDD"},{name:"/pf-tech-writer",description:"Technical Writer - Documentation creation and maintenance"},{name:"/pf-theme",description:"Manage persona themes - list, show, set, create, or interactive wizard"},{name:"/pf-ux-designer",description:"UX Designer - User experience design and UI patterns"},{name:"/pf-work",description:"Resume work or start new - smart entry point that picks up where you left off"},{name:"/pf-workflow",description:"List available workflows, show current workflow details, and switch workflows mid-session. Use when checking available workflow types (TDD, trivial, agent-docs), viewing current workflow phase, switching to a different workflow pattern, or managing BikeLane stepped workflows."},{name:"/pr-comments",description:"View PR comments"},{name:"/review",description:"Start code review"},{name:"/status",description:"Show session status"},{name:"/terminal-setup",description:"Configure terminal"},{name:"/vim",description:"Toggle vim mode"}].sort((n,e)=>n.name.localeCompare(e.name)),TS="cyclist:command-frequency";function kS(){if(typeof localStorage>"u")return{};try{const n=localStorage.getItem(TS);return n?JSON.parse(n):{}}catch{return{}}}function RS(n){if(typeof localStorage>"u")return;const e=kS();e[n]=(e[n]||0)+1,localStorage.setItem(TS,JSON.stringify(e))}function FM(n){const e=n.toLowerCase(),i=kS();return jS.filter(a=>a.name.toLowerCase().startsWith(e)).sort((a,r)=>{const c=i[a.name]||0,d=i[r.name]||0;return d!==c?d-c:a.name.localeCompare(r.name)})}function UM(n){const e=m.useMemo(()=>jS,[n]),[i,a]=m.useState({visible:!1,commands:[],selectedIndex:0,prefix:""}),r=m.useCallback(b=>FM(b),[e,n]),c=m.useCallback(b=>{const x=r(b);a({visible:!0,commands:x,selectedIndex:0,prefix:b})},[r]),d=m.useCallback(()=>{a({visible:!1,commands:[],selectedIndex:0,prefix:""})},[]),h=m.useCallback(b=>{const x=r(b);x.length===0?d():a(w=>({...w,commands:x,selectedIndex:0,prefix:b}))},[r,d]),f=m.useCallback(()=>{a(b=>{if(b.commands.length===0)return b;const x=b.selectedIndex<=0?b.commands.length-1:b.selectedIndex-1;return{...b,selectedIndex:x}})},[]),p=m.useCallback(()=>{a(b=>{if(b.commands.length===0)return b;const x=b.selectedIndex>=b.commands.length-1?0:b.selectedIndex+1;return{...b,selectedIndex:x}})},[]),y=m.useCallback(()=>{if(!i.visible||i.commands.length===0)return null;const b=i.commands[i.selectedIndex];return d(),b?.name&&RS(b.name),b?.name||null},[i,d]);return{state:i,showCompletion:c,hideCompletion:d,updateCompletion:h,navigateUp:f,navigateDown:p,selectCurrent:y,isVisible:i.visible}}function OS(n){const e=n+"CollectionProvider",[i,a]=cn(e),[r,c]=i(e,{collectionRef:{current:null},itemMap:new Map}),d=_=>{const{scope:C,children:D}=_,N=ue.useRef(null),k=ue.useRef(new Map).current;return l.jsx(r,{scope:C,itemMap:k,collectionRef:N,children:D})};d.displayName=e;const h=n+"CollectionSlot",f=Pa(h),p=ue.forwardRef((_,C)=>{const{scope:D,children:N}=_,k=c(h,D),T=Ie(C,k.collectionRef);return l.jsx(f,{ref:T,children:N})});p.displayName=h;const y=n+"CollectionItemSlot",b="data-radix-collection-item",x=Pa(y),w=ue.forwardRef((_,C)=>{const{scope:D,children:N,...k}=_,T=ue.useRef(null),R=Ie(C,T),z=c(y,D);return ue.useEffect(()=>(z.itemMap.set(T,{ref:T,...k}),()=>{z.itemMap.delete(T)})),l.jsx(x,{[b]:"",ref:R,children:N})});w.displayName=y;function E(_){const C=c(n+"CollectionConsumer",_);return ue.useCallback(()=>{const N=C.collectionRef.current;if(!N)return[];const k=Array.from(N.querySelectorAll(`[${b}]`));return Array.from(C.itemMap.values()).sort((z,O)=>k.indexOf(z.ref.current)-k.indexOf(O.ref.current))},[C.collectionRef,C.itemMap])}return[{Provider:d,Slot:p,ItemSlot:w},E,a]}var $M=m.createContext(void 0);function Kc(n){const e=m.useContext($M);return n||e||"ltr"}var Qh="rovingFocusGroup.onEntryFocus",WM={bubbles:!1,cancelable:!0},hr="RovingFocusGroup",[Nf,zS,qM]=OS(hr),[YM,MS]=cn(hr,[qM]),[XM,QM]=YM(hr),PS=m.forwardRef((n,e)=>l.jsx(Nf.Provider,{scope:n.__scopeRovingFocusGroup,children:l.jsx(Nf.Slot,{scope:n.__scopeRovingFocusGroup,children:l.jsx(ZM,{...n,ref:e})})}));PS.displayName=hr;var ZM=m.forwardRef((n,e)=>{const{__scopeRovingFocusGroup:i,orientation:a,loop:r=!1,dir:c,currentTabStopId:d,defaultCurrentTabStopId:h,onCurrentTabStopIdChange:f,onEntryFocus:p,preventScrollOnEntryFocus:y=!1,...b}=n,x=m.useRef(null),w=Ie(e,x),E=Kc(c),[_,C]=_n({prop:d,defaultProp:h??null,onChange:f,caller:hr}),[D,N]=m.useState(!1),k=Gt(p),T=zS(i),R=m.useRef(!1),[z,O]=m.useState(0);return m.useEffect(()=>{const A=x.current;if(A)return A.addEventListener(Qh,k),()=>A.removeEventListener(Qh,k)},[k]),l.jsx(XM,{scope:i,orientation:a,dir:E,loop:r,currentTabStopId:_,onItemFocus:m.useCallback(A=>C(A),[C]),onItemShiftTab:m.useCallback(()=>N(!0),[]),onFocusableItemAdd:m.useCallback(()=>O(A=>A+1),[]),onFocusableItemRemove:m.useCallback(()=>O(A=>A-1),[]),children:l.jsx(je.div,{tabIndex:D||z===0?-1:0,"data-orientation":a,...b,ref:w,style:{outline:"none",...n.style},onMouseDown:we(n.onMouseDown,()=>{R.current=!0}),onFocus:we(n.onFocus,A=>{const G=!R.current;if(A.target===A.currentTarget&&G&&!D){const U=new CustomEvent(Qh,WM);if(A.currentTarget.dispatchEvent(U),!U.defaultPrevented){const B=T().filter(M=>M.focusable),$=B.find(M=>M.active),ae=B.find(M=>M.id===_),W=[$,ae,...B].filter(Boolean).map(M=>M.ref.current);GS(W,y)}}R.current=!1}),onBlur:we(n.onBlur,()=>N(!1))})})}),LS="RovingFocusGroupItem",IS=m.forwardRef((n,e)=>{const{__scopeRovingFocusGroup:i,focusable:a=!0,active:r=!1,tabStopId:c,children:d,...h}=n,f=Mt(),p=c||f,y=QM(LS,i),b=y.currentTabStopId===p,x=zS(i),{onFocusableItemAdd:w,onFocusableItemRemove:E,currentTabStopId:_}=y;return m.useEffect(()=>{if(a)return w(),()=>E()},[a,w,E]),l.jsx(Nf.ItemSlot,{scope:i,id:p,focusable:a,active:r,children:l.jsx(je.span,{tabIndex:b?0:-1,"data-orientation":y.orientation,...h,ref:e,onMouseDown:we(n.onMouseDown,C=>{a?y.onItemFocus(p):C.preventDefault()}),onFocus:we(n.onFocus,()=>y.onItemFocus(p)),onKeyDown:we(n.onKeyDown,C=>{if(C.key==="Tab"&&C.shiftKey){y.onItemShiftTab();return}if(C.target!==C.currentTarget)return;const D=e2(C,y.orientation,y.dir);if(D!==void 0){if(C.metaKey||C.ctrlKey||C.altKey||C.shiftKey)return;C.preventDefault();let k=x().filter(T=>T.focusable).map(T=>T.ref.current);if(D==="last")k.reverse();else if(D==="prev"||D==="next"){D==="prev"&&k.reverse();const T=k.indexOf(C.currentTarget);k=y.loop?t2(k,T+1):k.slice(T+1)}setTimeout(()=>GS(k))}}),children:typeof d=="function"?d({isCurrentTabStop:b,hasTabStop:_!=null}):d})})});IS.displayName=LS;var KM={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function JM(n,e){return e!=="rtl"?n:n==="ArrowLeft"?"ArrowRight":n==="ArrowRight"?"ArrowLeft":n}function e2(n,e,i){const a=JM(n.key,i);if(!(e==="vertical"&&["ArrowLeft","ArrowRight"].includes(a))&&!(e==="horizontal"&&["ArrowUp","ArrowDown"].includes(a)))return KM[a]}function GS(n,e=!1){const i=document.activeElement;for(const a of n)if(a===i||(a.focus({preventScroll:e}),document.activeElement!==i))return}function t2(n,e){return n.map((i,a)=>n[(e+a)%n.length])}var n2=PS,i2=IS,BS="Toggle",zm=m.forwardRef((n,e)=>{const{pressed:i,defaultPressed:a,onPressedChange:r,...c}=n,[d,h]=_n({prop:i,onChange:r,defaultProp:a??!1,caller:BS});return l.jsx(je.button,{type:"button","aria-pressed":d,"data-state":d?"on":"off","data-disabled":n.disabled?"":void 0,...c,ref:e,onClick:we(n.onClick,()=>{n.disabled||h(!d)})})});zm.displayName=BS;var HS=zm,ss="ToggleGroup",[VS]=cn(ss,[MS]),FS=MS(),Mm=ue.forwardRef((n,e)=>{const{type:i,...a}=n;if(i==="single"){const r=a;return l.jsx(s2,{...r,ref:e})}if(i==="multiple"){const r=a;return l.jsx(a2,{...r,ref:e})}throw new Error(`Missing prop \`type\` expected on \`${ss}\``)});Mm.displayName=ss;var[US,$S]=VS(ss),s2=ue.forwardRef((n,e)=>{const{value:i,defaultValue:a,onValueChange:r=()=>{},...c}=n,[d,h]=_n({prop:i,defaultProp:a??"",onChange:r,caller:ss});return l.jsx(US,{scope:n.__scopeToggleGroup,type:"single",value:ue.useMemo(()=>d?[d]:[],[d]),onItemActivate:h,onItemDeactivate:ue.useCallback(()=>h(""),[h]),children:l.jsx(WS,{...c,ref:e})})}),a2=ue.forwardRef((n,e)=>{const{value:i,defaultValue:a,onValueChange:r=()=>{},...c}=n,[d,h]=_n({prop:i,defaultProp:a??[],onChange:r,caller:ss}),f=ue.useCallback(y=>h((b=[])=>[...b,y]),[h]),p=ue.useCallback(y=>h((b=[])=>b.filter(x=>x!==y)),[h]);return l.jsx(US,{scope:n.__scopeToggleGroup,type:"multiple",value:d,onItemActivate:f,onItemDeactivate:p,children:l.jsx(WS,{...c,ref:e})})});Mm.displayName=ss;var[o2,r2]=VS(ss),WS=ue.forwardRef((n,e)=>{const{__scopeToggleGroup:i,disabled:a=!1,rovingFocus:r=!0,orientation:c,dir:d,loop:h=!0,...f}=n,p=FS(i),y=Kc(d),b={role:"group",dir:y,...f};return l.jsx(o2,{scope:i,rovingFocus:r,disabled:a,children:r?l.jsx(n2,{asChild:!0,...p,orientation:c,dir:y,loop:h,children:l.jsx(je.div,{...b,ref:e})}):l.jsx(je.div,{...b,ref:e})})}),wc="ToggleGroupItem",qS=ue.forwardRef((n,e)=>{const i=$S(wc,n.__scopeToggleGroup),a=r2(wc,n.__scopeToggleGroup),r=FS(n.__scopeToggleGroup),c=i.value.includes(n.value),d=a.disabled||n.disabled,h={...n,pressed:c,disabled:d},f=ue.useRef(null);return a.rovingFocus?l.jsx(i2,{asChild:!0,...r,focusable:!d,active:c,ref:f,children:l.jsx(Nx,{...h,ref:e})}):l.jsx(Nx,{...h,ref:e})});qS.displayName=wc;var Nx=ue.forwardRef((n,e)=>{const{__scopeToggleGroup:i,value:a,...r}=n,c=$S(wc,i),d={role:"radio","aria-checked":n.pressed,"aria-pressed":void 0},h=c.type==="single"?d:void 0;return l.jsx(zm,{...h,...r,ref:e,onPressedChange:f=>{f?c.onItemActivate(a):c.onItemDeactivate(a)}})}),YS=Mm,XS=qS;const QS=Bf("inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground"},size:{default:"h-9 px-2 min-w-9",sm:"h-8 px-1.5 min-w-8",lg:"h-10 px-2.5 min-w-10"}},defaultVariants:{variant:"default",size:"default"}}),l2=m.forwardRef(({className:n,variant:e,size:i,...a},r)=>l.jsx(HS,{ref:r,className:ye(QS({variant:e,size:i,className:n})),...a}));l2.displayName=HS.displayName;const ZS=m.createContext({size:"default",variant:"default"}),KS=m.forwardRef(({className:n,variant:e,size:i,children:a,...r},c)=>l.jsx(YS,{ref:c,className:ye("flex items-center justify-center gap-1",n),...r,children:l.jsx(ZS.Provider,{value:{variant:e,size:i},children:a})}));KS.displayName=YS.displayName;const JS=m.forwardRef(({className:n,children:e,variant:i,size:a,...r},c)=>{const d=m.useContext(ZS);return l.jsx(XS,{ref:c,className:ye(QS({variant:d.variant||i,size:d.size||a}),n),...r,children:e})});JS.displayName=XS.displayName;const jx=["plan","manual","accept"],Zh={plan:"Plan",manual:"Manual",accept:"Accept"},Tx={plan:"Read-only exploration mode",manual:"Ask for permission before actions",accept:"Auto-accept file edits"},c2={plan:"plan",manual:"default",accept:"acceptEdits"},u2={plan:"plan",default:"manual",acceptEdits:"accept"},kx={1:"plan",2:"manual",3:"accept"};function d2(n){m.useEffect(()=>{const e=i=>{(i.metaKey||i.ctrlKey)&&kx[i.key]&&(i.preventDefault(),n(kx[i.key]))};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[n])}function h2(){const[n,e]=m.useState("manual"),[i,a]=m.useState(!0),r=m.useRef(null);m.useEffect(()=>{const h=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/claude`,f=new WebSocket(h);r.current=f,f.onopen=()=>{f.send(JSON.stringify({type:"getMode"}))},f.onmessage=y=>{try{const b=JSON.parse(y.data);if(b.type==="mode"&&b.mode){const x=u2[b.mode]||"manual";e(x),a(!1),console.log("[ModeSwitch] Mode synced:",b.mode,"->",x)}}catch(b){console.error("[ModeSwitch] Failed to parse mode response:",b)}},f.onerror=()=>{a(!1)};const p=setTimeout(()=>{i&&a(!1)},2e3);return()=>{clearTimeout(p),f.readyState===WebSocket.OPEN&&f.close(),r.current=null}},[]);const c=m.useCallback(d=>{const h=c2[d];r.current&&r.current.readyState===WebSocket.OPEN?(r.current.send(JSON.stringify({type:"setMode",mode:h})),e(d),console.log("[ModeSwitch] Mode set to:",d,"->",h)):(e(d),console.warn("[ModeSwitch] WebSocket not connected, mode set locally only"))},[]);return{mode:n,setMode:c,isLoading:i}}function f2({mode:n,defaultMode:e="manual",onModeChange:i,className:a="",disabled:r=!1}){const[c,d]=m.useState(e),[h,f]=m.useState(!1),p=n??c;m.useEffect(()=>{const w=window.matchMedia("(prefers-reduced-motion: reduce)");f(w.matches);const E=_=>{f(_.matches)};return w.addEventListener("change",E),()=>w.removeEventListener("change",E)},[]);const y=jx.indexOf(p),b=m.useCallback(w=>{r||(n||d(w),i?.(w))},[n,r,i]),x=m.useCallback(w=>{w&&b(w)},[b]);return l.jsxs("div",{className:ye("mode-switch",r&&"mode-switch--disabled",h&&"reduced-motion",a),"data-testid":"mode-switch",style:h?{transition:"none"}:void 0,children:[l.jsx("div",{className:"mode-switch__highlight","data-testid":"mode-highlight",style:{transform:`translateX(${y*100}%)`,transition:h?"none":void 0},"data-mode":p}),l.jsx(St,{delayDuration:400,children:l.jsx(KS,{type:"single",value:p,onValueChange:x,disabled:r,className:"relative z-[1] gap-0","aria-label":"Permission mode",children:jx.map(w=>{const E=p===w;return l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(JS,{value:w,"data-mode":w,"data-testid":`mode-${w}`,"aria-label":`${Zh[w]} mode: ${Tx[w]}`,className:ye("mode-option",E&&"active"),children:Zh[w]})}),l.jsx(Te,{side:"bottom",children:Tx[w]})]},w)})})}),l.jsx("div",{className:"visually-hidden",role:"status","aria-live":"polite",children:`${Zh[p]} mode selected`})]})}const Yl=["image/png","image/jpeg","image/gif","image/webp"],m2=20*1024*1024;function p2({commands:n,selectedIndex:e,visible:i,onSelect:a}){return!i||n.length===0?null:l.jsx("div",{className:"completion-popup","data-testid":"completion-popup",children:n.map((r,c)=>l.jsxs("div",{className:`completion-item ${c===e?"selected":""}`,onClick:()=>a(c),"data-testid":`completion-item-${c}`,children:[l.jsx("span",{className:"completion-name",children:r.name}),l.jsx("span",{className:"completion-desc",children:r.description})]},r.name))})}function g2(n){return n?n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"):""}function v2({queue:n,bellMode:e,onRemove:i,onClear:a,onInject:r}){return n.length===0?null:l.jsx(St,{delayDuration:300,children:l.jsxs("div",{className:"queue-display","data-testid":"queue-display",children:[l.jsxs("div",{className:"queue-header",children:[l.jsxs("span",{className:"queue-count",children:[n.length," queued"]}),e&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx($e,{variant:"secondary",className:"queue-mode-badge bell-mode",children:"🔔"})}),l.jsx(Te,{children:"Bell mode active - messages inject via hook"})]}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"sm",type:"button",className:"queue-clear-btn",onClick:a,children:"Clear"})}),l.jsx(Te,{children:"Clear all queued messages"})]})]}),l.jsx("ul",{className:"queue-list",children:n.map((c,d)=>{const h=c.text.length>60?c.text.substring(0,60)+"...":c.text,f=c.images&&c.images.length>0;return l.jsxs("li",{className:"queue-item","data-testid":`queue-item-${d}`,children:[l.jsx("span",{className:"queue-item-text",children:g2(h)}),f&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsxs($e,{variant:"outline",className:"queue-image-indicator",children:["📎",c.images.length]})}),l.jsx(Te,{children:`${c.images.length} image(s) attached`})]}),l.jsxs("div",{className:"queue-item-actions",children:[r&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"icon",type:"button",className:"queue-item-inject",onClick:()=>r(d),children:"▶"})}),l.jsx(Te,{children:"Send now (abort current and send this message)"})]}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"icon",type:"button",className:"queue-item-remove",onClick:()=>i(d),children:"×"})}),l.jsx(Te,{children:"Remove from queue"})]})]})]},d)})})]})})}function y2({images:n,onRemove:e}){return n.length===0?null:l.jsx(St,{delayDuration:300,children:l.jsx("div",{className:"image-preview","data-testid":"image-preview",children:n.map((i,a)=>l.jsxs("div",{className:"image-preview-item",children:[l.jsx("img",{src:i.dataUrl,alt:i.filename}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"icon",type:"button",className:"image-remove",onClick:()=>e(a),children:"X"})}),l.jsx(Te,{children:"Remove image"})]})]},a))})})}function b2({onSubmit:n,isProcessing:e=!1,placeholder:i,onInject:a}){const r=m.useRef(null),[c,d]=m.useState(""),[h,f]=m.useState([]),{mode:p,setMode:y}=h2();d2(y);const{addToHistory:b,navigateUp:x,navigateDown:w,resetNavigation:E}=VM(),{state:_,showCompletion:C,hideCompletion:D,updateCompletion:N,navigateUp:k,navigateDown:T,selectCurrent:R,isVisible:z}=UM(),{queue:O,queueCount:A,bellMode:G,queueMessage:U,removeFromQueue:B,clearQueue:$,setProcessing:ae,resumeQueue:ne}=gS();m.useEffect(()=>{ae(e)},[e,ae]),m.useEffect(()=>{const V=Y=>{d(Y.detail.prompt),r.current?.focus()};return window.addEventListener("cyclist:suggest-prompt",V),()=>{window.removeEventListener("cyclist:suggest-prompt",V)}},[]);const W=m.useCallback(async V=>{let Y=null;if(V.items){for(const le of V.items)if(le.type&&Yl.includes(le.type)){Y=le.getAsFile();break}}if(!Y&&V.files?.length>0){for(const le of V.files)if(le.type&&Yl.includes(le.type)){Y=le;break}}return Y?Y.size>m2?(console.warn("Image too large:",Y.size),!1):new Promise(le=>{const X=new FileReader;X.onload=()=>{const ce=X.result,de=Y.name||`Pasted Image.${Y.type.split("/")[1]||"png"}`;f(De=>[...De,{dataUrl:ce,mimeType:Y.type,filename:de}]),le(!0)},X.onerror=()=>le(!1),X.readAsDataURL(Y)}):!1},[]),M=m.useCallback(V=>{f(Y=>Y.filter((le,X)=>X!==V))},[]),K=m.useCallback(()=>{if(!r.current)return null;const V=r.current.selectionStart,Y=c;let le=V;for(;le>0&&Y[le-1]!==" "&&Y[le-1]!==`
64
+ `;)le--;const X=Y.substring(le,V);return X.startsWith("/")?{prefix:X,start:le,end:V}:null},[c]),q=m.useCallback(V=>{const Y=K();if(!Y){d(ce=>ce+V);return}const{start:le,end:X}=Y;d(ce=>ce.substring(0,le)+V+ce.substring(X)),setTimeout(()=>{if(r.current){const ce=le+V.length;r.current.selectionStart=r.current.selectionEnd=ce}},0)},[K]),he=m.useCallback(()=>{const V=c.trim();if(!(!V&&h.length===0)){if(e){U({text:V,images:[...h]})&&(d(""),f([]),r.current?.focus());return}if(b(V),E(),V.startsWith("/")){const Y=V.split(/\s/)[0];RS(Y)}ne(),window.dispatchEvent(new CustomEvent("cyclist:user-submit")),n(V,h),d(""),f([]),r.current?.focus()}},[c,h,e,U,b,E,ne,n]),Se=m.useCallback(V=>{if(V.key==="Tab"&&!V.shiftKey&&!V.ctrlKey&&!V.altKey){if(z){V.preventDefault();const le=R();le&&q(le);return}const Y=K();if(Y){V.preventDefault(),C(Y.prefix);return}}if(V.key==="Escape"&&z){V.preventDefault(),D();return}if(V.key==="Enter"&&!V.shiftKey){if(z){V.preventDefault();const Y=R();Y&&q(Y);return}V.preventDefault(),he();return}if(V.key==="ArrowUp"&&!V.shiftKey&&!V.ctrlKey&&!V.altKey){if(z){V.preventDefault(),k();return}if(r.current?.selectionStart===0){const Y=x(c);if(Y!==null){V.preventDefault(),d(Y);return}}}if(V.key==="ArrowDown"&&!V.shiftKey&&!V.ctrlKey&&!V.altKey){if(z){V.preventDefault(),T();return}if(r.current?.selectionEnd===c.length){const Y=w();if(Y!==null){V.preventDefault(),d(Y);return}}}},[z,R,q,K,C,D,he,k,T,x,w,c]),I=m.useCallback(V=>{const Y=V.target.value;if(d(Y),Y==="/"&&!z){C("/");return}if(z){const le=K();le?N(le.prefix):D()}},[z,C,K,N,D]),L=m.useCallback(async V=>{const Y=V.clipboardData;if(!Y)return;let le=!1;if(Y.items){for(const X of Y.items)if(X.type&&Yl.includes(X.type)){le=!0;break}}if(!le&&Y.files?.length>0){for(const X of Y.files)if(X.type&&Yl.includes(X.type)){le=!0;break}}le&&(V.preventDefault(),await W(Y))},[W]),ee=m.useCallback(V=>{const Y=_.commands[V];Y&&(q(Y.name),D())},[_.commands,q,D]);return l.jsxs("div",{className:"editor-container","data-testid":"editor-container",children:[l.jsx(f2,{mode:p,onModeChange:y,className:"editor-mode-switch"}),l.jsxs("div",{className:"editor-wrapper",id:"editor-wrapper",children:[l.jsx(y2,{images:h,onRemove:M}),l.jsx("textarea",{ref:r,id:"editor-textarea",className:"editor-textarea",value:c,onChange:I,onKeyDown:Se,onPaste:L,placeholder:i,spellCheck:!1,autoFocus:!0,"data-testid":"editor-textarea"}),l.jsx(p2,{commands:_.commands,selectedIndex:_.selectedIndex,visible:z,onSelect:ee})]}),l.jsx(v2,{queue:O,bellMode:G,onRemove:B,onClear:$,onInject:a})]})}function x2(){const[n,e]=m.useState(null),i=m.useCallback(c=>d=>{e(c)},[]),a=m.useCallback(()=>{e(null)},[]),r=m.useCallback(c=>n===c,[n]);return{handleFocus:i,handleBlur:a,isFocused:r}}function w2({currentAgent:n,onAgentSwitch:e}){const[i,a]=m.useState(!1),[r,c]=m.useState([]),d=m.useRef(null);m.useEffect(()=>{fetch("/api/theme-agents/full").then(f=>f.ok?f.json():null).then(f=>{f?.agents&&c(f.agents)}).catch(()=>{})},[]),m.useEffect(()=>{if(!i)return;const f=p=>{d.current&&!d.current.contains(p.target)&&a(!1)};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[i]),m.useEffect(()=>{if(!i)return;const f=p=>{p.key==="Escape"&&(p.stopPropagation(),a(!1))};return document.addEventListener("keydown",f,!0),()=>document.removeEventListener("keydown",f,!0)},[i]);const h=m.useCallback(f=>{f.role!==n&&(e?.(f.role),a(!1))},[n,e]);return l.jsxs("div",{className:"agent-quick-picker-wrapper",ref:d,children:[l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"icon",type:"button",className:`btn-toggle agent-picker-toggle ${i?"active":""}`,"data-testid":"agent-quick-picker",onClick:()=>a(f=>!f),"aria-label":"Switch agent","aria-expanded":i,"aria-haspopup":"listbox",children:l.jsx(lz,{className:"h-4 w-4"})})}),l.jsx(Te,{children:"Switch Agent"})]}),i&&l.jsx("div",{className:"agent-quick-picker-dropdown","data-testid":"agent-quick-picker-dropdown",role:"listbox","aria-label":"Available agents",children:r.map(f=>{const p=f.role===n;return l.jsx("div",{className:`agent-quick-picker-option ${p?"current":""}`,"data-testid":`agent-option-${f.role}`,role:"option","aria-selected":p,"aria-label":`${f.role} (${f.character})`,title:f.character,onClick:()=>h(f),children:l.jsx("span",{className:"agent-option-role",children:f.role})},f.role)})})]})}function S2({isRunning:n,isStopping:e=!1,onStop:i,onForceStop:a,onReset:r,bellMode:c=!1,relayMode:d=!1,onBellModeChange:h,onRelayModeChange:f,contextPercent:p=0,currentAgent:y=null,onTirePump:b,onAgentSwitch:x}){const w=m.useRef(0),E=500,{handleFocus:_,handleBlur:C,isFocused:D}=x2(),N=m.useCallback(k=>{if(k.key!=="Escape"&&k.keyCode!==27||!n)return;const T=Date.now();T-w.current<E&&a?a():i(),w.current=T},[n,i,a]);return m.useEffect(()=>(document.addEventListener("keydown",N),()=>{document.removeEventListener("keydown",N)}),[N]),l.jsx(St,{delayDuration:300,children:l.jsxs("div",{className:"control-bar","data-testid":"control-bar",children:[l.jsxs("div",{className:"control-bar-toggles",children:[l.jsx(w2,{currentAgent:y,onAgentSwitch:x}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"icon",type:"button",className:`btn-toggle bell-toggle ${c?"active":""}`,"data-testid":"bell-mode-toggle",onClick:()=>h?.(!c),"aria-pressed":c,"aria-label":"Bell mode - inject queued messages via hook",children:l.jsx(VO,{className:"h-4 w-4"})})}),l.jsx(Te,{children:"Bell Mode: Inject queued messages during tool use (Cmd+B)"})]}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"icon",type:"button",className:`btn-toggle relay-toggle ${d?"active":""}`,"data-testid":"relay-toggle",onClick:()=>f?.(!d),"aria-pressed":d,"aria-label":"Relay mode - auto-handoff to next agent",children:l.jsx(hz,{className:"h-4 w-4"})})}),l.jsx(Te,{children:"Relay Mode: Auto-handoff to next agent (Cmd+4)"})]}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"icon",type:"button",className:`btn-toggle pump-toggle ${p>=70?"warning":""}`,"data-testid":"pump-toggle",onClick:b,disabled:!y,"aria-label":"TirePump: Clear context and reload agent",children:l.jsx(nz,{className:"h-4 w-4"})})}),l.jsx(Te,{children:y?`TirePump: Clear context (${p}%) and reload ${y}`:"TirePump: No agent loaded"})]})]}),l.jsxs(Ce,{variant:"destructive",type:"button",className:`btn-stop danger ${e?"stopping":""} ${n&&!e?"throbbing":""} ${D("stop")?"focused focus-visible":""}`,"data-testid":"stop-button",onClick:i,disabled:!n||e,"aria-busy":e,"aria-label":"Stop Claude",onFocus:_("stop"),onBlur:C,children:[l.jsx("span",{"data-icon":"stop",className:"icon"}),e?l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"spinner","data-loading":!0}),"Stopping..."]}):"Stop"]}),l.jsx(Ce,{variant:"outline",type:"button",className:`btn-reset ${D("reset")?"focused focus-visible":""}`,"data-testid":"reset-button",onClick:r,"aria-label":"Reset session",onFocus:_("reset"),onBlur:C,children:"Reset"})]})})}function C2(){const[n,e]=m.useState(!1),[i,a]=m.useState(!1),[r,c]=m.useState(!1),[d,h]=m.useState(!1),[f,p]=m.useState(0),[y,b]=m.useState(null),{abort:x,clear:w,clearAndReload:E,send:_,onMessage:C,onComplete:D,onError:N,isConnected:k}=dr();m.useEffect(()=>{function B(W){const M=W?.workflow,K=!!M?.bell_mode,q=!!M?.relay_mode;console.log("[ControlBar] Settings updated:",{bellMode:K,relayMode:q}),c(K),h(q)}async function $(){try{console.log("[ControlBar] Loading settings via REST");const W=await fetch("/api/settings");if(W.ok){const M=await W.json();B(M)}}catch(W){console.error("[ControlBar] Failed to load settings:",W)}}console.log("[ControlBar] useEffect mount - loading settings"),$(),console.log("[ControlBar] Connecting to /ws/settings for real-time sync");const ae=window.location.protocol==="https:"?"wss:":"ws:",ne=new WebSocket(`${ae}//${window.location.host}/ws/settings`);return ne.onmessage=W=>{try{const M=JSON.parse(W.data);(M.type==="init"||M.type==="update")&&B(M.settings)}catch(M){console.error("[ControlBar] Failed to parse WebSocket message:",M)}},ne.onerror=W=>{console.error("[ControlBar] WebSocket error:",W)},()=>{ne.close()}},[]),m.useEffect(()=>{const B=window.location.protocol==="https:"?"wss:":"ws:",$=new WebSocket(`${B}//${window.location.host}/ws/context`);return $.onmessage=ae=>{try{const ne=JSON.parse(ae.data);if(ne.type==="init"||ne.type==="update"){const W=ne.context?.percent??0;p(W)}}catch(ne){console.error("[ControlBar] Failed to parse context message:",ne)}},()=>{$.close()}},[]),m.useEffect(()=>{const B=window.location.protocol==="https:"?"wss:":"ws:",$=new WebSocket(`${B}//${window.location.host}/ws/persona`);return $.onmessage=ae=>{try{const ne=JSON.parse(ae.data);b(ne?.slug??null)}catch(ne){console.error("[ControlBar] Failed to parse persona message:",ne)}},()=>{$.close()}},[]),m.useEffect(()=>{if(!k)return;const B=()=>{e(!0),a(!1)},$=()=>{e(!1),a(!1)},ae=()=>{e(!1),a(!1)},ne=C(B),W=D($),M=N(ae);return()=>{ne(),W(),M()}},[k,C,D,N]);const T=m.useCallback(()=>{a(!0);try{x()}catch(B){console.error("[ControlBar] Stop failed:",B)}},[x]),R=m.useCallback(()=>{a(!0);try{x()}catch(B){console.error("[ControlBar] Force stop failed:",B)}},[x]),z=m.useCallback(()=>{try{w(),e(!1),a(!1)}catch(B){console.error("[ControlBar] Reset failed:",B)}},[w]),O=m.useCallback(async B=>{try{await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({workflow:{bell_mode:B}})}),c(B),console.log("[ControlBar] Bell mode set to:",B)}catch($){console.error("[ControlBar] Failed to toggle bell mode:",$)}},[]),A=m.useCallback(async B=>{try{await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({workflow:{relay_mode:B}})}),h(B),console.log("[ControlBar] Relay mode set to:",B)}catch($){console.error("[ControlBar] Failed to toggle relay mode:",$)}},[]),G=m.useCallback(()=>{if(!y){console.warn("[ControlBar] Cannot TirePump: no current agent");return}try{console.log("[ControlBar] TirePump: clearing context and reloading agent:",y),E(y),e(!1),a(!1),p(0)}catch(B){console.error("[ControlBar] TirePump failed:",B)}},[y,E]),U=m.useCallback(B=>{_(`/${B}`)},[_]);return{isRunning:n,isStopping:i,bellMode:r,relayMode:d,contextPercent:f,currentAgent:y,handleStop:T,handleForceStop:R,handleReset:z,handleBellModeChange:O,handleRelayModeChange:A,handleTirePump:G,handleAgentSwitch:U}}function fe({className:n,...e}){return l.jsx("div",{className:ye("animate-pulse rounded-md bg-primary/10",n),...e})}const Rx={pm:"#a78bfa",sm:"#60a5fa",dev:"#4ade80",tea:"#2dd4bf",reviewer:"#f87171",architect:"#fb923c",devops:"#22d3ee","ux-designer":"#f0abfc","tech-writer":"#e5e5e5",orchestrator:"#e879f9",ba:"#a3e635"};function _2({isOpen:n,onClose:e,currentRole:i,currentTheme:a}){const[r,c]=m.useState(null),[d,h]=m.useState(null),[f,p]=m.useState(!1),[y,b]=m.useState(!1),x=m.useRef(),{send:w}=dr();m.useEffect(()=>{n&&(p(!0),fetch("/api/theme-agents/full").then(N=>N.ok?N.json():null).then(N=>{c(N),h(null),p(!1)}).catch(()=>p(!1)))},[n]),m.useEffect(()=>{b(!1)},[d]),m.useEffect(()=>{if(!n)return;const N=k=>{k.key==="Escape"&&e()};return document.addEventListener("keydown",N),()=>document.removeEventListener("keydown",N)},[n,e]);const E=m.useCallback(N=>{x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{h(N)},100)},[]),_=m.useCallback(()=>{x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{h(null)},200)},[]),C=m.useCallback(N=>{if(N.role===i)return;const k=`/${N.role}`;w(k),e()},[i,w,e]);if(!n)return null;const D=d||r?.agents.find(N=>N.role===i)||r?.agents[0];return l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"agent-popup-backdrop",onClick:e,"aria-hidden":"true"}),l.jsx("div",{className:"agent-popup",role:"dialog","aria-modal":"true","aria-labelledby":"agent-popup-title",children:f?l.jsxs("div",{className:"agent-popup-loading p-4 space-y-3",children:[l.jsx(fe,{className:"h-6 w-40"}),l.jsx(Rt,{}),l.jsxs("div",{className:"flex gap-4",children:[l.jsxs("div",{className:"space-y-2 flex-shrink-0",style:{width:160},children:[l.jsx(fe,{className:"h-5 w-12"}),l.jsx(fe,{className:"h-8 w-full"}),l.jsx(fe,{className:"h-8 w-full"}),l.jsx(fe,{className:"h-8 w-full"}),l.jsx(fe,{className:"h-8 w-full"})]}),l.jsxs("div",{className:"space-y-3 flex-1",children:[l.jsx(fe,{className:"h-24 w-24 rounded-full mx-auto"}),l.jsx(fe,{className:"h-5 w-32 mx-auto"}),l.jsx(fe,{className:"h-4 w-full"}),l.jsx(fe,{className:"h-4 w-3/4"})]})]})]}):r?l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"agent-popup-header",children:[l.jsxs("h2",{id:"agent-popup-title",className:"agent-popup-theme",children:[r.themeName,l.jsx($e,{variant:"secondary",className:`tier-badge ${r.tier?`tier-${r.tier.toLowerCase()}`:"tier-unranked"}`,children:r.tier||"Unranked"})]}),l.jsx(Ce,{variant:"ghost",size:"icon",className:"agent-popup-close",onClick:e,"aria-label":"Close popup",children:"×"})]}),l.jsx(Rt,{className:"my-1"}),l.jsxs("div",{className:"agent-popup-content",children:[l.jsxs("div",{className:"agent-popup-roster",children:[l.jsx("h3",{className:"roster-title",children:"Team"}),l.jsx("ul",{className:"roster-list",role:"listbox",children:r.agents.map(N=>{const k=N.role===i,T=d?.role===N.role,R=Rx[N.role]||"#888";return l.jsxs("li",{className:`roster-item ${k?"current":""} ${T?"previewing":""}`,role:"option","aria-selected":k,onMouseEnter:()=>E(N),onMouseLeave:_,onClick:()=>C(N),children:[l.jsx("span",{className:"roster-character",children:N.character}),l.jsx("span",{className:"roster-role",style:{backgroundColor:R},children:N.role}),k&&l.jsx("span",{className:"roster-current-marker",children:"●"})]},N.role)})})]}),l.jsx("div",{className:"agent-popup-details","data-testid":"agent-popup-details",children:D&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"popup-portrait","data-testid":"popup-portrait",children:!y&&a?l.jsx("img",{src:`/portraits/${a}/large/${D.slug}.png`,alt:D.character,onError:()=>b(!0)}):l.jsx("div",{className:"portrait-placeholder",children:"🤖"})}),l.jsx("h3",{className:"popup-character",children:D.character}),l.jsxs("div",{className:"popup-role-mapping",children:[l.jsx($e,{variant:"default",className:"role-badge",style:{backgroundColor:Rx[D.role]||"#888"},children:D.role}),"→ ",D.character]}),l.jsxs("div",{className:"popup-detail","data-testid":"popup-detail-style",children:[l.jsx("label",{children:"Style:"}),l.jsx("span",{children:D.style||"—"})]}),l.jsxs("div",{className:"popup-detail","data-testid":"popup-detail-background",children:[l.jsx("label",{children:"Background:"}),l.jsx("span",{children:D.background||"—"})]}),D.quirks.length>0&&l.jsxs("div",{className:"popup-detail","data-testid":"popup-detail-quirks",children:[l.jsx("label",{children:"Quirks:"}),l.jsx("span",{children:D.quirks.join(", ")})]}),D.lift!==void 0&&l.jsxs("div",{className:"popup-detail",children:[l.jsx("label",{children:"Lift:"}),l.jsxs("span",{className:`lift-value ${D.lift>=0?"positive":"negative"}`,children:[D.lift>=0?"+":"",D.lift.toFixed(1)]})]})]})})]})]}):l.jsx("div",{className:"agent-popup-error",children:"Failed to load theme data"})})]})}const E2={pm:"PM",sm:"SM",dev:"DEV",tea:"TEA",reviewer:"REV",architect:"ARC",devops:"OPS","ux-designer":"UX","tech-writer":"TW",orchestrator:"ORC",ba:"BA"};function D2({character:n,role:e,slug:i,theme:a,isActive:r,isThinking:c}){const[d,h]=m.useState(!1);if(!r)return null;const f=E2[e]||e.toUpperCase();return l.jsxs("div",{className:`persona-tandem-portrait${c?" avatar-tandem-thinking":""}`,"data-testid":"tandem-portrait",role:"img","aria-label":`${n} (${e}) - observing`,tabIndex:-1,children:[d?l.jsx("span",{className:"tandem-portrait-fallback","aria-hidden":"true",children:"🤖"}):l.jsx("img",{src:`/portraits/${a}/medium/${i}.png`,alt:"","aria-hidden":"true",className:"tandem-portrait-image",onError:()=>h(!0)}),l.jsx("span",{className:"tandem-role-badge","data-testid":"tandem-role-badge","aria-hidden":"true",children:f})]})}const A2={pm:"#a78bfa",sm:"#60a5fa",dev:"#4ade80",tea:"#2dd4bf",reviewer:"#f87171",architect:"#fb923c",devops:"#22d3ee","ux-designer":"#f0abfc","tech-writer":"#e5e5e5",orchestrator:"#e879f9",ba:"#a3e635"},N2={pm:"PM",sm:"SM",dev:"DEV",tea:"TEA",reviewer:"REV",architect:"ARC",devops:"OPS","ux-designer":"UX","tech-writer":"TW",orchestrator:"ORC",ba:"BA"};function j2(n){return n.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function eC(){const{persona:n,isStreaming:e}=Zc(),i=NS(),[a,r]=m.useState(!1),[c,d]=m.useState(!1),[h,f]=m.useState(!1),p=n?.character||"Agent",y=n?.theme||"default",b=n?.role||"agent",x=n?.slug,w=n?.quote,E=n?.tandemAgent,[_,C]=m.useState(!1),D=m.useRef(!1),N=m.useRef(null);m.useEffect(()=>{const O=D.current,A=E?.isThinking??!1;D.current=A,!O&&A&&C(!0)},[E?.isThinking]);const k=m.useCallback(()=>{C(!1)},[]),T=m.useCallback(()=>{d(!0)},[]),R=m.useCallback(()=>{d(!1)},[]),z=A2[b]||"#e879f9";return n?.character?l.jsxs(l.Fragment,{children:[l.jsx(St,{delayDuration:300,children:l.jsxs("div",{className:`persona-header clickable${h?" compact":""}`,"data-testid":"persona-header",role:"button",tabIndex:0,"aria-label":"Current agent persona - click to view team","aria-live":"polite",onClick:T,onKeyDown:O=>O.key==="Enter"&&T(),children:[l.jsxs("div",{className:"persona-portrait-group",children:[l.jsx("div",{className:`persona-portrait${e?" avatar-thinking":""}${_?" avatar-observation-pulse":""}`,"data-testid":"persona-portrait",ref:N,onAnimationEnd:k,children:x&&y&&!a?l.jsx("img",{src:`/portraits/${y}/medium/${x}.png`,alt:p,className:"portrait-image",onError:()=>r(!0)}):l.jsx("span",{className:"portrait-fallback",children:"🤖"})}),E&&l.jsx(D2,{character:E.character,role:E.role,slug:E.slug,theme:E.theme,isActive:!0,isThinking:E.isThinking}),E&&l.jsx("span",{className:"visually-hidden",role:"status","aria-live":"polite","data-testid":"tandem-sr-status",children:E.isThinking?`${E.character} is thinking`:`${E.character} observing`})]}),l.jsxs("div",{className:"persona-info",children:[l.jsxs("div",{className:"persona-name-row",children:[l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx($e,{variant:"default",className:"persona-role","data-testid":"persona-role",style:{backgroundColor:z},children:N2[b]||b})}),l.jsx(Te,{children:b})]}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{className:"persona-character","data-testid":"persona-character",children:p})}),l.jsx(Te,{children:p})]}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{className:"persona-theme","data-testid":"persona-theme",children:j2(y)})}),l.jsx(Te,{children:`Theme: ${y}`})]})]}),w&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsxs("span",{className:"persona-catchphrase","data-testid":"persona-catchphrase",children:['"',w,'"']})}),l.jsx(Te,{children:w})]})]}),l.jsx("img",{src:i==="dark"?"/images/cyclist-dark.png":"/images/cyclist-light.png",alt:"Cyclist",className:"persona-branding"}),l.jsx("button",{className:"persona-collapse-toggle",onClick:O=>{O.stopPropagation(),f(!h)},"aria-label":h?"Expand header":"Collapse header",children:h?"▼":"▲"})]})}),l.jsx(_2,{isOpen:c,onClose:R,currentRole:b,currentTheme:y})]}):l.jsx("div",{className:"persona-header empty","data-testid":"persona-header"})}function T2(n){if(!n)return"—";const e=n.toLowerCase();if(e.includes("opus"))return"opus";if(e.includes("sonnet"))return"sonnet";if(e.includes("haiku"))return"haiku";const i=n.split("-");if(i.length>=2){for(let a=i.length-2;a>=0;a--)if(!/^\d{8}$/.test(i[a]))return i[a]}return n}function k2(n){return n>=85?"level-danger":n>=70?"level-warning":"level-safe"}function R2(n){if(!n)return"";const e=n.split("/");return e[e.length-1]||e[e.length-2]||n}function O2(){const{context:n,stats:e,projectInfo:i}=Om(),a=n?.percent??0,r=e?.model??null,c=i?.pwd??"",d=i?.jiraEmail??null,h=i?.githubUsername??null,f=k2(a),p=R2(c);return l.jsx(St,{delayDuration:300,children:l.jsxs("div",{className:"stats-strip","data-testid":"stats-strip",children:[l.jsxs("div",{className:"stats-left","data-testid":"stats-left",children:[l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{className:"stats-pwd","data-testid":"stats-pwd","data-full-path":c,children:p})}),l.jsx(Te,{children:c})]}),d&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{className:"stats-jira-email","data-testid":"jira-email",children:d})}),l.jsx(Te,{children:`Jira: ${d}`})]}),h&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsxs("span",{className:"stats-github-user","data-testid":"github-user",children:["@",h]})}),l.jsx(Te,{children:`GitHub: ${h}`})]})]}),l.jsxs("div",{className:"stats-right","data-testid":"stats-right",children:[l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx($e,{variant:"secondary",className:"stats-model-badge","data-testid":"model-badge",children:T2(r)})}),r&&l.jsx(Te,{children:r})]}),l.jsxs("div",{className:`stats-context-meter ${f}`,"data-testid":"context-meter",children:[l.jsxs("span",{className:"context-percent","data-testid":"context-percent",children:[a,"%"]}),l.jsx("div",{className:"context-fill","data-testid":"context-fill",style:{width:`${a}%`}})]})]})]})})}function Ox(n){return n.startsWith("Stop hook feedback:")}function z2(n){const e=Date.now(),i=n.parent_tool_use_id||void 0,a=n.subagent_type,r=n.subagent_name,c=[];if(n.type==="assistant"||n.type==="message"){const d=n.message?.content||n.content;if(Array.isArray(d)){const h=d.filter(p=>p.type==="text"&&typeof p.text=="string").map(p=>p.text).join("");h&&h.trim().length>=3&&!Ox(h.trim())&&c.push({type:"agent",content:h,timestamp:e,isStreaming:!0,parent_id:i,subagent_type:a,subagent_name:r});const f=d.filter(p=>p.type==="tool_use");for(const p of f)c.push({type:"tool_use",tool_name:p.name,tool_id:p.id,input:p.input,timestamp:e,parent_id:i,subagent_type:a,subagent_name:r})}else typeof d=="string"&&d.trim().length>=3&&!Ox(d.trim())&&c.push({type:"agent",content:d,timestamp:e,isStreaming:!0,parent_id:i,subagent_type:a,subagent_name:r});return c}if(n.type==="user"){let d="";const h=n.message?.content||n.content;if(Array.isArray(h)){d=h.filter(p=>p.type==="text"&&typeof p.text=="string").map(p=>p.text).join("");const f=h.filter(p=>p.type==="tool_result");for(const p of f)c.push({type:"tool_result",tool_id:p.tool_use_id,content:typeof p.content=="string"?p.content:"",timestamp:e,is_error:p.is_error})}else typeof h=="string"&&(d=h);return d&&c.push({type:"user",content:d,timestamp:e,parent_id:i,subagent_type:a,subagent_name:r}),c}return n.type==="tool_use"?(c.push({type:"tool_use",tool_name:n.tool_name,tool_id:n.tool_id,input:n.input,timestamp:e,parent_id:i,subagent_type:a,subagent_name:r}),c):(n.type==="tool_result"&&c.push({type:"tool_result",tool_id:n.tool_id,content:typeof n.output=="string"?n.output:"",timestamp:e,parent_id:i,subagent_type:a,subagent_name:r,is_error:n.is_error,durationMs:n.durationMs}),c)}function M2(){const[n,e]=m.useState([]),[i,a]=m.useState(!1),{isRunning:r,isStopping:c,bellMode:d,relayMode:h,contextPercent:f,currentAgent:p,handleStop:y,handleForceStop:b,handleReset:x,handleBellModeChange:w,handleRelayModeChange:E,handleTirePump:_,handleAgentSwitch:C}=C2(),{send:D,abort:N,onMessage:k,onComplete:T,onError:R,onUserMessage:z,onClear:O,isConnected:A}=dr(),{persona:G}=Zc(),U=m.useRef(G);U.current=G;const{handleTurnComplete:B,pauseQueue:$,onBellConsumed:ae,injectMessage:ne}=gS(),W=m.useRef();m.useEffect(()=>ae(ce=>{e(de=>[...de,{type:"bell_injected",content:ce.text,timestamp:Date.now(),imageCount:ce.images.length>0?ce.images.length:void 0}])}),[ae]);const M={abort:N,submit:(X,ce)=>{a(!0),D(X,ce)}},K=m.useCallback(X=>{const ce=z2(X);if(ce.length>0){const de=U.current,De=ce.map(Ne=>Ne.type==="agent"&&de?{...Ne,agentSlug:de.slug??void 0,agentTheme:de.theme??void 0,agentCharacter:de.character??void 0}:Ne),Ge=De.filter(Ne=>Ne.type==="tool_result"&&!Ne.parent_id&&Ne.tool_id).map(Ne=>Ne.tool_id);Ge.length>0?e(Ne=>{const dt=new Set(Ge.filter(rt=>Ne.some(An=>An.parent_id===rt)));return dt.size>0?[...Ne.filter(rt=>!rt.parent_id||!dt.has(rt.parent_id)),...De]:[...Ne,...De]}):e(Ne=>[...Ne,...De])}},[]),q=m.useCallback(()=>{a(!1),e(X=>X.map(ce=>ce.type==="agent"&&ce.isStreaming?{...ce,isStreaming:!1}:ce)),W.current&&B(W.current)},[B]),he=m.useCallback(X=>{a(!1),e(ce=>[...ce,{type:"agent",content:`Error: ${X}`,timestamp:Date.now()}])},[]);m.useEffect(()=>z(ce=>{e(de=>[...de,{type:"user",content:ce.prompt,timestamp:ce.timestamp,imageCount:ce.images.length>0?ce.images.length:void 0}])}),[z]),m.useEffect(()=>O(()=>{e(ce=>[...ce,{type:"context_cleared",content:"Context cleared",timestamp:Date.now()}]),a(!1)}),[O]),m.useEffect(()=>{if(!A){console.log("[MessagePanel] Claude WebSocket not connected");return}const X=k(K),ce=T(q),de=R(he);return()=>{X(),ce(),de()}},[A,k,T,R,K,q,he]);const Se=m.useCallback((X,ce)=>{a(!0),D(X,ce)},[D]);m.useEffect(()=>{W.current=Se},[Se]);const I=m.useCallback(()=>{$(),y()},[$,y]),[L,ee]=m.useState(null),V=m.useRef(null),Y=m.useRef(!1),le=m.useCallback(X=>{X.preventDefault(),Y.current=!0;const ce=X.clientY,de=V.current;if(!de)return;const De=de.getBoundingClientRect(),Ge=L??de.querySelector(".message-panel-editor")?.getBoundingClientRect().height??150,Ne=rt=>{if(!Y.current)return;const An=ce-rt.clientY,ei=Math.max(80,Math.min(Ge+An,De.height*.7));ee(ei)},dt=()=>{Y.current=!1,document.removeEventListener("mousemove",Ne),document.removeEventListener("mouseup",dt),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",Ne),document.addEventListener("mouseup",dt),document.body.style.cursor="row-resize",document.body.style.userSelect="none"},[L]);return l.jsxs("div",{className:"message-panel","data-testid":"message-panel",ref:V,children:[l.jsx(eC,{}),l.jsx("div",{className:"message-panel-content",children:l.jsx(BM,{messages:n})}),l.jsx("div",{className:"message-panel-resize-handle",onMouseDown:le}),l.jsx("div",{className:"message-panel-editor",style:L!=null?{height:L,flexShrink:0}:void 0,children:l.jsxs("div",{className:"editor-with-controls",children:[l.jsx("div",{className:"editor-area",children:l.jsx(b2,{onSubmit:Se,isProcessing:i||r,placeholder:"Send a message...",onInject:X=>ne(X,M)})}),l.jsx(S2,{isRunning:r||i,isStopping:c,onStop:I,onForceStop:b,onReset:x,bellMode:d,relayMode:h,onBellModeChange:w,onRelayModeChange:E,contextPercent:f,currentAgent:p,onTirePump:_,onAgentSwitch:C})]})}),l.jsx(O2,{})]})}function P2(n){return n.id?{id:n.id,title:n.title??"",status:n.status??void 0,phase:n.phase??void 0,points:n.points??void 0,criteria:n.criteria,workflowPhases:n.workflow,workflowType:n.workflowType??void 0}:null}function Pm(){const[n,e]=m.useState(null),[i,a]=m.useState(!0),[r,c]=m.useState(null),[d,h]=m.useState(null),f=m.useRef(null),p=m.useRef();return m.useEffect(()=>{const b=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/story`,x=()=>{try{f.current=new WebSocket(b),f.current.onopen=()=>{console.debug("[useStory] WebSocket connected")},f.current.onmessage=w=>{try{const E=JSON.parse(w.data);(E.type==="init"||E.type==="update")&&(e(P2(E)),h(E.availableWorkflows??null),a(!1),c(null))}catch(E){console.error("[useStory] Failed to parse message:",E)}},f.current.onclose=()=>{console.debug("[useStory] WebSocket closed, reconnecting..."),p.current=setTimeout(x,2e3)},f.current.onerror=w=>{console.error("[useStory] WebSocket error:",w),c(new Error("WebSocket connection failed"))}}catch(w){console.error("[useStory] WebSocket init failed:",w),c(w instanceof Error?w:new Error("Failed to connect")),a(!1)}};return x(),()=>{p.current&&clearTimeout(p.current),f.current&&f.current.close()}},[]),{story:n,isLoading:i,error:r,availableWorkflows:d}}function tC(){const[n,e]=m.useState(null),[i,a]=m.useState(!0),[r,c]=m.useState(null),d=m.useRef(null),h=m.useRef(),f=m.useRef(!0);return m.useEffect(()=>{const y=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/sprint`,b=()=>{if(f.current)try{d.current=new WebSocket(y),d.current.onopen=()=>{console.debug("[useSprint] WebSocket connected")},d.current.onmessage=x=>{try{const w=JSON.parse(x.data);if(w.type==="init"||w.type==="update"){const{type:E,..._}=w;e(C=>C?{...C,..._}:_),a(!1),c(null)}}catch(w){console.error("[useSprint] Failed to parse message:",w)}},d.current.onclose=()=>{console.debug("[useSprint] WebSocket closed, reconnecting..."),h.current=setTimeout(b,2e3)},d.current.onerror=x=>{console.error("[useSprint] WebSocket error:",x),c(new Error("WebSocket connection failed"))}}catch(x){console.error("[useSprint] WebSocket init failed:",x),c(x instanceof Error?x:new Error("Failed to connect")),a(!1)}};return b(),()=>{f.current=!1,h.current&&clearTimeout(h.current),d.current&&d.current.close()}},[]),{data:n,isLoading:i,error:r}}function L2(n){if(!n)return null;const e=n.split("@")[0],i=e.split(".");if(i.length>=2){const a=i[0].charAt(0).toUpperCase(),r=i[i.length-1].charAt(0).toUpperCase()+i[i.length-1].slice(1);return`${a}. ${r}`}return e}function I2(n){const e=n.stories.reduce((a,r)=>a+r.points,0);return{done:n.stories.filter(a=>a.status==="done").reduce((a,r)=>a+r.points,0),total:e}}function jf(n){return n.stories.length>0&&n.stories.every(e=>e.status==="done"||e.status==="cancelled")}function G2(n){switch(n){case"done":return{icon:l.jsx(Ga,{size:12}),className:"status-done"};case"in_progress":return{icon:l.jsx(ez,{size:12}),className:"status-in-progress"};case"blocked":return{icon:l.jsx(oz,{size:12}),className:"status-blocked"};default:return{icon:l.jsx(QO,{size:12}),className:"status-backlog"}}}function zx(n){return`https://1898andco.atlassian.net/browse/${n}`}function Mx({hasContext:n,testIdPrefix:e,id:i}){const a=n?"Context file exists":"No context file";return l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{className:`context-indicator ${n?"has-context":"no-context"}`,"data-testid":`${e}-context-indicator-${i}`,"data-has-context":String(n),title:a,children:n?"📄":""})}),l.jsx(Te,{children:a})]})}function B2({priority:n,storyId:e}){return n?l.jsx("span",{className:"priority-label","data-testid":`story-priority-${e}`,"data-priority":n,title:n,children:n}):null}function H2({status:n,storyId:e}){const{icon:i,className:a}=G2(n);return l.jsx($e,{variant:n==="blocked"?"destructive":n==="done"?"default":"secondary",className:`story-status-badge ${a}`,"data-testid":`story-status-badge-${e}`,"data-status":n,"aria-label":`Status: ${n}`,children:i})}function V2({jiraKey:n,storyId:e}){const i=a=>{a.preventDefault();const r=zx(n);try{const c=window.electronAPI;if(c?.shell?.openExternal){c.shell.openExternal(r);return}}catch{}window.open(r,"_blank")};return l.jsx("a",{className:"jira-link cyclist-link","data-testid":`story-jira-link-${e}`,href:zx(n),onClick:i,children:n})}function Px({text:n}){const[e,i]=m.useState(!1),a=async r=>{r.stopPropagation();try{await navigator.clipboard.writeText(n),i(!0),setTimeout(()=>i(!1),2e3)}catch{}};return l.jsx("button",{className:`copy-id-button ${e?"copied":""}`,onClick:a,"aria-label":`Copy ${n}`,title:"Copy ID + title",children:e?l.jsx(Ga,{size:12}):l.jsx(KO,{size:12})})}function Lx({epic:n,isExpanded:e,isArchiving:i,onToggle:a,onKeyDown:r,onArchive:c}){const{done:d,total:h}=I2(n),f=jf(n);return l.jsxs("div",{className:`epic-group ${f?"epic-completed":""}`,"data-testid":`epic-group-${n.id}`,children:[l.jsxs("div",{className:"epic-header",children:[l.jsx(Ce,{variant:"ghost",size:"icon",className:"epic-toggle","data-testid":`epic-toggle-${n.id}`,onClick:()=>a(n.id),onKeyDown:p=>r(n.id,p),"aria-expanded":e,children:e?"▼":"▶"}),l.jsx("span",{className:"epic-title",children:n.title}),n.jiraKey&&l.jsx("span",{className:"epic-jira",children:n.jiraKey}),l.jsx(Px,{text:`${n.id} ${n.title}`}),l.jsx(Mx,{hasContext:n.hasContext??!1,testIdPrefix:"epic",id:n.id}),f&&n.hasContext&&l.jsx($e,{variant:"default",className:"epic-ready-badge","data-testid":`epic-ready-badge-${n.id}`,children:"Ready"}),l.jsx("div",{className:"epic-progress","data-testid":`epic-progress-${n.id}`,"data-done":String(d),"data-total":String(h),children:l.jsx("div",{className:"progress-bar",style:{width:`${h>0?d/h*100:0}%`}})}),l.jsxs("span",{className:"epic-progress-label","data-testid":`epic-progress-label-${n.id}`,children:[d,"/",h," pts"]}),f&&l.jsxs(l.Fragment,{children:[i&&l.jsx("span",{"data-testid":`archive-loading-${n.id}`,children:"..."}),l.jsx(Ce,{variant:"outline",size:"sm",className:"archive-button","data-testid":`archive-button-${n.id}`,"aria-label":`Archive ${n.id}`,disabled:i,onClick:()=>c(n.id),children:"Archive"})]})]}),e&&l.jsx("div",{className:"epic-stories",children:n.stories.map(p=>{const y=p.hasContext??!1,b=p.status==="blocked",x=L2(p.assignedTo);return l.jsxs("div",{className:`story-item ${y?"":"missing-context"} ${b?"story-blocked":""}`,"data-testid":`story-item-${p.id}`,"data-status":p.status,"data-story-id":p.id,"aria-label":`${p.id}: ${p.title}`,children:[l.jsx(B2,{priority:p.priority,storyId:p.id}),l.jsx(H2,{status:p.status,storyId:p.id}),p.jiraKey&&l.jsx(V2,{jiraKey:p.jiraKey,storyId:p.id}),l.jsx(Px,{text:`${p.id} ${p.title}`}),l.jsxs("div",{className:"story-info",children:[l.jsx("span",{className:"story-title",children:p.title}),l.jsxs("span",{className:"story-meta",children:[x&&l.jsx("span",{className:"story-assignee","data-testid":`story-assignee-${p.id}`,children:x}),p.workflow&&l.jsx("span",{className:"story-workflow-badge","data-testid":`story-workflow-${p.id}`,children:p.workflow}),p.status==="done"&&p.completed&&l.jsx("span",{className:"story-completed-date","data-testid":`story-completed-${p.id}`,children:p.completed})]})]}),l.jsx(Mx,{hasContext:y,testIdPrefix:"story",id:p.id}),l.jsx("span",{className:"story-points","data-testid":`story-points-${p.id}`,children:p.points})]},p.id)})})]})}function nC(){const{data:n,isLoading:e,error:i}=tC(),[a,r]=m.useState(new Set),[c,d]=m.useState(new Set),[h,f]=m.useState(null),[p,y]=m.useState(null),b=n?.epics.filter(R=>!jf(R))??[],x=n?.epics.filter(R=>jf(R))??[],w=m.useRef(!1);m.useEffect(()=>{n?.epics&&!w.current&&(w.current=!0,r(new Set(b.map(R=>R.id))))},[n?.epics]);const E=m.useCallback(R=>{r(z=>{const O=new Set(z);return O.has(R)?O.delete(R):O.add(R),O})},[]),_=m.useCallback((R,z)=>{(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),E(R))},[E]),C=m.useCallback(async R=>{d(z=>new Set(z).add(`archive-${R}`)),f(null),y(null);try{if(typeof window<"u"&&window.electronAPI?.sprint?.archiveEpic)await window.electronAPI.sprint.archiveEpic(R);else if(!(await fetch(`/api/sprint/archive-epic/${R}`,{method:"POST"})).ok)throw new Error("Archive failed")}catch(z){y(z instanceof Error?z:new Error("Archive failed"))}finally{d(z=>{const O=new Set(z);return O.delete(`archive-${R}`),O})}},[]),D=m.useCallback(async R=>{d(z=>new Set(z).add(`promote-${R}`)),y(null);try{if(typeof window<"u"&&window.electronAPI?.sprint?.promoteEpic)await window.electronAPI.sprint.promoteEpic(R);else if(!(await fetch(`/api/sprint/promote-epic/${R}`,{method:"POST"})).ok)throw new Error("Promote failed")}catch(z){y(z instanceof Error?z:new Error("Promote failed"))}finally{d(z=>{const O=new Set(z);return O.delete(`promote-${R}`),O})}},[]);if(e)return l.jsx("div",{className:"enhanced-sprint-panel","data-testid":"enhanced-sprint-panel",children:l.jsxs("div",{className:"loading-state space-y-3 p-2","data-testid":"sprint-panel-loading",children:[l.jsx(fe,{className:"h-5 w-32"}),l.jsx(fe,{className:"h-4 w-full"}),l.jsx(Rt,{className:"my-2"}),l.jsx(fe,{className:"h-5 w-28"}),l.jsx(fe,{className:"h-8 w-full"}),l.jsx(fe,{className:"h-8 w-full"}),l.jsx(Rt,{className:"my-2"}),l.jsx(fe,{className:"h-5 w-36"}),l.jsx(fe,{className:"h-6 w-3/4"})]})});const N=i||p,k=N?l.jsx("div",{className:"error-toast","data-testid":"error-toast",children:N.message}):null,T=h?l.jsxs("div",{className:"confirm-dialog","data-testid":"confirm-archive-dialog",children:[l.jsx("p",{children:"Are you sure you want to archive this epic?"}),l.jsx(Ce,{variant:"destructive",size:"sm","data-testid":"confirm-archive-yes",onClick:()=>C(h),children:"Yes"}),l.jsx(Ce,{variant:"outline",size:"sm","data-testid":"confirm-archive-no",onClick:()=>f(null),children:"No"})]}):null;return l.jsx(St,{delayDuration:300,children:l.jsxs("div",{className:"enhanced-sprint-panel","data-testid":"enhanced-sprint-panel",children:[k,T,l.jsxs("section",{"data-section":"current-story",children:[l.jsx("h2",{children:"Current Story"}),n?.currentStory?l.jsxs("div",{"data-testid":"current-story-section",children:[l.jsx("span",{className:"story-id",children:n.currentStory.id}),l.jsx("span",{className:"story-title",children:n.currentStory.title}),l.jsx("span",{className:"story-status",children:n.currentStory.status}),l.jsxs("span",{className:"story-points","data-testid":"current-story-points",children:[n.currentStory.points," pts"]})]}):n?.nextStory?l.jsxs("div",{"data-testid":"next-up-section",children:[l.jsx("span",{className:"next-up-label",children:"Next up:"}),l.jsx("span",{className:"story-id",children:n.nextStory.id}),l.jsx("span",{className:"story-title",children:n.nextStory.title})]}):l.jsx("div",{"data-testid":"no-stories-section",children:l.jsx("span",{children:"No active story"})})]}),l.jsx(Rt,{className:"my-2"}),l.jsxs("section",{"data-section":"epics",children:[l.jsx("h2",{children:"Current Epics"}),l.jsxs("div",{"data-testid":"epic-tree-view",children:[(!n?.epics||n.epics.length===0)&&l.jsxs("div",{className:"empty-state","data-testid":"no-epics-section",children:[l.jsx("span",{children:"No epics in current sprint"}),l.jsx("p",{className:"hint",children:"Promote an epic from Future Initiatives to get started"})]}),b.map(R=>l.jsx(Lx,{epic:R,isExpanded:a.has(R.id),isArchiving:c.has(`archive-${R.id}`),onToggle:E,onKeyDown:_,onArchive:f},R.id))]})]}),x.length>0&&l.jsxs(l.Fragment,{children:[l.jsx(Rt,{className:"my-2"}),l.jsxs("section",{"data-section":"completed-epics",children:[l.jsx("h2",{children:"Completed Epics"}),l.jsx("div",{"data-testid":"completed-epics-section",children:x.map(R=>l.jsx(Lx,{epic:R,isExpanded:a.has(R.id),isArchiving:c.has(`archive-${R.id}`),onToggle:E,onKeyDown:_,onArchive:f},R.id))})]})]}),l.jsx(Rt,{className:"my-2"}),l.jsxs("section",{"data-section":"future",children:[l.jsx("h2",{children:"Future Initiatives"}),l.jsx("div",{"data-testid":"future-initiatives-section",children:n?.futureEpics.map(R=>{const z=c.has(`promote-${R.id}`),O=R.status==="ready";return l.jsxs("div",{className:"future-epic","data-testid":`future-epic-${R.id}`,children:[l.jsx("span",{className:"future-epic-title",children:R.title}),l.jsxs("span",{className:"future-epic-points",children:[R.estimatedPoints," pts"]}),l.jsx($e,{variant:R.status==="ready"?"default":"secondary",className:"future-epic-status","data-testid":`future-epic-status-${R.id}`,"data-status":R.status,children:R.status}),O&&l.jsx(Ce,{variant:"default",size:"sm",className:"promote-button","data-testid":`promote-button-${R.id}`,"aria-label":`Promote ${R.id} to current sprint`,disabled:z,onClick:()=>D(R.id),children:"Promote"})]},R.id)})})]})]})})}function iC(n){let e=0,i=0,a=0;for(const r of n){const c=r.status[0]||" ",d=r.status[1]||" ";c!==" "&&c!=="?"&&e++,(d==="M"||d==="D")&&i++,c==="?"&&d==="?"&&a++}return{staged:e,modified:i,untracked:a}}function F2(n){return n?.length?n.map(e=>{const i=iC(e.dirtyFiles);return{name:e.name,path:e.path,branch:e.branch,ahead:e.ahead??void 0,behind:e.behind??void 0,developBehind:e.developBehind??void 0,staged:i.staged,modified:i.modified,untracked:i.untracked,isDirty:!e.clean,files:e.dirtyFiles}}):[]}function U2(n){if(!n?.length)return null;const e=n[0];let i=0,a=0,r=0;for(const d of n){const h=iC(d.dirtyFiles);i+=h.staged,a+=h.modified,r+=h.untracked}const c=n.some(d=>!d.clean);return{branch:e.branch,ahead:e.ahead??void 0,behind:e.behind??void 0,staged:i>0?i:void 0,modified:a>0?a:void 0,untracked:r>0?r:void 0,isDirty:c}}function Lm(){const[n,e]=m.useState(null),[i,a]=m.useState([]),[r,c]=m.useState(!0),[d,h]=m.useState(null),f=m.useRef(null),p=m.useRef();return m.useEffect(()=>{const b=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/git`,x=()=>{try{f.current=new WebSocket(b),f.current.onopen=()=>{console.debug("[useGitStatus] WebSocket connected")},f.current.onmessage=w=>{try{const E=JSON.parse(w.data);(E.type==="init"||E.type==="update")&&(e(U2(E.repos)),a(F2(E.repos)),c(!1),h(null))}catch(E){console.error("[useGitStatus] Failed to parse message:",E)}},f.current.onclose=()=>{console.debug("[useGitStatus] WebSocket closed, reconnecting..."),p.current=setTimeout(x,2e3)},f.current.onerror=w=>{console.error("[useGitStatus] WebSocket error:",w),h(new Error("WebSocket connection failed"))}}catch(w){console.error("[useGitStatus] WebSocket init failed:",w),h(w instanceof Error?w:new Error("Failed to connect")),c(!1)}};return x(),()=>{p.current&&clearTimeout(p.current),f.current&&f.current.close()}},[]),{gitStatus:n,repos:i,isLoading:r,error:d}}function $2(n){const e=n[0]||" ",i=n[1]||" ";return e==="?"&&i==="?"?"untracked":e!==" "&&e!=="?"?"staged":"modified"}function W2(n){const e=n[0]||" ",i=n[1]||" ";return e==="?"&&i==="?"?"?":e==="A"?"+":e==="D"||i==="D"?"-":e==="M"||i==="M"?"~":e==="R"?"R":n.trim()||"~"}function q2({files:n}){return l.jsx("ul",{className:"file-list",children:n.map((e,i)=>l.jsxs("li",{className:`file-item ${$2(e.status)}`,children:[l.jsx("span",{className:"file-status-icon",children:W2(e.status)}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{className:"file-path",children:e.path})}),l.jsx(Te,{children:e.path})]})]},`${e.path}-${i}`))})}function Y2({repo:n}){const[e,i]=m.useState(!1),{name:a,branch:r,ahead:c,behind:d,developBehind:h,staged:f,modified:p,untracked:y,isDirty:b,files:x}=n,w=x.length>0;return l.jsx(St,{delayDuration:300,children:l.jsxs("div",{className:`repo-status ${e?"expanded":""}`,"data-testid":`repo-status-${a}`,children:[l.jsxs("div",{className:"repo-header",children:[l.jsx("span",{className:"repo-name",children:a}),b&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx($e,{variant:"destructive",className:"dirty-indicator",children:"●"})}),l.jsx(Te,{children:"Uncommitted changes"})]})]}),l.jsxs("div",{className:"branch-info",children:[l.jsx("span",{className:"branch-icon",children:"⎇"}),l.jsx("span",{className:"branch-name",children:r})]}),(c!==void 0&&c>0||d!==void 0&&d>0||h!==void 0&&h>0)&&l.jsxs("div",{className:"sync-status",children:[c!==void 0&&c>0&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsxs("span",{className:"ahead",children:["↑",c]})}),l.jsx(Te,{children:"Commits ahead of remote"})]}),d!==void 0&&d>0&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsxs("span",{className:"behind",children:["↓",d]})}),l.jsx(Te,{children:"Commits behind remote"})]}),h!==void 0&&h>0&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsxs("span",{className:"develop-behind",children:["⟳",h]})}),l.jsxs(Te,{children:["develop is ",h," commit",h>1?"s":""," ahead"]})]})]}),(f>0||p>0||y>0)&&l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsxs(Ce,{variant:"ghost",className:"file-status-toggle",onClick:()=>i(!e),children:[l.jsx("span",{className:`toggle-icon ${e?"open":""}`,children:"▶"}),l.jsxs("div",{className:"file-status",children:[f>0&&l.jsxs($e,{variant:"outline",className:"status-item staged",children:["+",f]}),p>0&&l.jsxs($e,{variant:"outline",className:"status-item modified",children:["~",p]}),y>0&&l.jsxs($e,{variant:"outline",className:"status-item untracked",children:["?",y]})]})]})}),l.jsx(Te,{children:e?"Collapse file list":"Expand file list"})]}),e&&w&&l.jsx(q2,{files:x})]})})}function sC(){const{repos:n,isLoading:e,error:i}=Lm();return e?l.jsx("div",{className:"git-panel loading","data-testid":"git-panel",children:l.jsxs("div",{className:"space-y-3 p-2",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx(fe,{className:"h-4 w-32"}),l.jsx(fe,{className:"h-3 w-24"})]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx(fe,{className:"h-4 w-28"}),l.jsx(fe,{className:"h-3 w-20"})]})]})}):i?l.jsx("div",{className:"git-panel error","data-testid":"git-panel",children:l.jsx("div",{className:"error-message",children:i.message})}):n.length===0?l.jsx("div",{className:"git-panel empty","data-testid":"git-panel",children:l.jsx("div",{className:"placeholder",children:"No git repos"})}):l.jsx("div",{className:"git-panel stacked","data-testid":"git-panel",children:n.map(a=>l.jsx(Y2,{repo:a},a.name))})}function X2(n){switch(n){case"done":return"✓";case"current":return"●";default:return"○"}}function Q2(n){return n?["tdd","bdd"].includes(n.toLowerCase())?n.toUpperCase():n.charAt(0).toUpperCase()+n.slice(1):"—"}function Z2({phase:n,isLast:e}){const i=X2(n.status),a=`phase-step ${n.status}`;return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:a,children:[l.jsx("span",{className:"phase-icon",children:i}),l.jsx("span",{className:"phase-label",children:n.label})]}),!e&&l.jsx("span",{className:"phase-arrow",children:"→"})]})}function K2({phases:n}){const e=n.length,i=n.findIndex(d=>d.status==="current"),a=n.filter(d=>d.status==="done").length,r=i>=0?i+1:a===e?e:1,c=i>=0?n[i]:null;return l.jsxs("div",{className:"stepped-progress",children:[l.jsxs("span",{className:"stepped-counter",children:["Step ",r," of ",e]}),c&&l.jsx("span",{className:"stepped-current-label",children:c.label})]})}function J2({workflows:n,onStart:e}){return l.jsxs("div",{className:"available-workflows",children:[l.jsx("div",{className:"available-workflows-header",children:l.jsxs("span",{className:"available-workflows-title",children:["Available Workflows (",n.length,")"]})}),l.jsx("div",{className:"available-workflows-list",children:n.map(i=>l.jsxs("div",{className:"workflow-entry","data-testid":"workflow-entry","data-workflow-entry-type":i.type,children:[l.jsxs("div",{className:"workflow-entry-header",children:[l.jsx("span",{className:"workflow-entry-name",children:i.name}),l.jsx($e,{variant:"outline",className:"workflow-entry-type-badge",children:i.type})]}),l.jsx("div",{className:"workflow-entry-description",children:i.description}),i.type==="stepped"&&l.jsxs("div",{className:"workflow-entry-hint",children:["/workflow start ",i.name]}),l.jsx("div",{className:"workflow-entry-footer",children:l.jsx(Ce,{variant:"ghost",size:"sm",className:"workflow-start-button","data-testid":"workflow-start-button",onClick:()=>e?.(i),children:"Start"})})]},i.name))})]})}function aC(){const{story:n,isLoading:e,error:i,availableWorkflows:a}=Pm(),{send:r,isConnected:c}=dr(),d=m.useCallback(b=>{c&&r(`/workflow start ${b.name}`)},[r,c]);if(e)return l.jsx("div",{className:"workflow-panel loading","data-testid":"workflow-panel",children:l.jsxs("div",{className:"space-y-2 p-2",children:[l.jsx(fe,{className:"h-6 w-16 rounded-full"}),l.jsxs("div",{className:"flex gap-2 items-center",children:[l.jsx(fe,{className:"h-4 w-12"}),l.jsx(fe,{className:"h-4 w-12"}),l.jsx(fe,{className:"h-4 w-12"})]})]})});if(i)return l.jsx("div",{className:"workflow-panel error","data-testid":"workflow-panel",children:l.jsx("div",{className:"error-message",children:i.message})});const h=n?.workflow??null,f=n?.workflowPhases??null,p=n?.workflowType==="stepped";if(!h&&(!f||f.length===0))return a&&a.length>0?l.jsx("div",{className:"workflow-panel","data-testid":"workflow-panel",children:l.jsx(J2,{workflows:a,onStart:d})}):l.jsx("div",{className:"workflow-panel","data-testid":"workflow-panel",children:l.jsx("div",{className:"placeholder",children:"No active workflow"})});const y=Q2(h);return l.jsx("div",{className:"workflow-panel","data-testid":"workflow-panel",children:l.jsxs("div",{className:"workflow-content",children:[l.jsx($e,{variant:"secondary",className:"workflow-type-badge","data-workflow-type":h||"",children:y}),f&&f.length>0&&(p?l.jsx(K2,{phases:f}):l.jsx("div",{className:"phase-progress",children:f.map((b,x)=>l.jsx(Z2,{phase:b,isLast:x===f.length-1},b.name))}))]})})}function eP({item:n}){const e=n.completed?"ac-item ac-done":"ac-item",i=n.completed?"✓":"○";return l.jsxs("div",{className:e,children:[l.jsx("span",{className:"ac-icon",children:i}),l.jsx("span",{className:"ac-text",children:n.text})]})}function oC(){const{story:n,isLoading:e,error:i}=Pm();if(e)return l.jsx("div",{className:"ac-panel loading","data-testid":"ac-panel",children:l.jsxs("div",{className:"space-y-2 p-2",children:[l.jsx(fe,{className:"h-3 w-full"}),l.jsx(fe,{className:"h-4 w-3/4"}),l.jsx(fe,{className:"h-4 w-5/6"}),l.jsx(fe,{className:"h-4 w-2/3"})]})});if(i)return l.jsx("div",{className:"ac-panel error","data-testid":"ac-panel",children:l.jsx("div",{className:"error-message",children:i.message})});const a=n?.criteria??null;if(!a||a.length===0)return l.jsx("div",{className:"ac-panel","data-testid":"ac-panel",children:l.jsx("div",{className:"placeholder",children:"No acceptance criteria"})});const r=a.filter(d=>d.completed).length,c=a.length;return l.jsx("div",{className:"ac-panel","data-testid":"ac-panel",children:l.jsxs("div",{className:"ac-content",children:[l.jsxs("span",{className:"progress-text",children:[r,"/",c]}),l.jsx("div",{className:"progress-bar-container",children:l.jsx("div",{className:"progress-bar",style:{width:`${r/c*100}%`}})}),l.jsx("div",{className:"ac-list",children:a.map((d,h)=>l.jsx(eP,{item:d},h))})]})})}function rC(){const[n,e]=m.useState([]),[i,a]=m.useState(!0),[r,c]=m.useState(null),d=m.useRef(null),h=m.useRef();return m.useEffect(()=>{const p=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/todos`,y=()=>{try{d.current=new WebSocket(p),d.current.onopen=()=>{console.debug("[useTodos] WebSocket connected")},d.current.onmessage=b=>{try{const x=JSON.parse(b.data);(x.type==="init"||x.type==="update")&&(e(x.todos||[]),a(!1),c(null))}catch(x){console.error("[useTodos] Failed to parse message:",x)}},d.current.onclose=()=>{console.debug("[useTodos] WebSocket closed, reconnecting..."),h.current=setTimeout(y,2e3)},d.current.onerror=b=>{console.error("[useTodos] WebSocket error:",b),c(new Error("WebSocket connection failed"))}}catch(b){console.error("[useTodos] WebSocket init failed:",b),c(b instanceof Error?b:new Error("Failed to connect")),a(!1)}};return y(),()=>{h.current&&clearTimeout(h.current),d.current&&d.current.close()}},[]),{todos:n,isLoading:i,error:r}}function Kh({todo:n}){const e={pending:"○",in_progress:"●",completed:"✓"}[n.status],i=`todo-item todo-${n.status}`,a=n.status==="in_progress"&&n.activeForm?n.activeForm:n.content;return l.jsxs("div",{className:i,"data-testid":`todo-${n.id}`,children:[l.jsx("span",{className:"todo-status",children:e}),l.jsx("span",{className:"todo-subject",children:a}),n.blockedBy&&n.blockedBy.length>0&&l.jsx(St,{delayDuration:300,children:l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{className:"todo-blocked",children:"(blocked)"})}),l.jsx(Te,{children:`Blocked by: ${n.blockedBy.join(", ")}`})]})})]})}function lC(){const{todos:n,isLoading:e,error:i}=rC();if(e)return l.jsx("div",{className:"todo-panel loading","data-testid":"todo-panel",children:l.jsxs("div",{className:"space-y-2 p-2",children:[l.jsx(fe,{className:"h-3 w-full"}),l.jsx(fe,{className:"h-4 w-5/6"}),l.jsx(fe,{className:"h-4 w-3/4"}),l.jsx(fe,{className:"h-4 w-4/5"})]})});if(i)return l.jsx("div",{className:"todo-panel error","data-testid":"todo-panel",children:l.jsx("div",{className:"error-message",children:i.message})});if(n.length===0)return l.jsx("div",{className:"todo-panel","data-testid":"todo-panel",children:l.jsx("div",{className:"placeholder",children:"No active tasks"})});const a=n.filter(p=>p.status==="in_progress"),r=n.filter(p=>p.status==="pending"),c=n.filter(p=>p.status==="completed"),d=n.length,h=c.length,f=d>0?Math.round(h/d*100):0;return l.jsx("div",{className:"todo-panel","data-testid":"todo-panel",children:l.jsxs("div",{className:"todo-content",children:[l.jsxs("div",{className:"progress-bar-container",children:[l.jsx("div",{className:"progress-bar",style:{width:`${f}%`}}),l.jsxs("span",{className:"progress-text",children:[h,"/",d]})]}),a.length>0&&l.jsxs("div",{className:"todo-section",children:[l.jsx("h4",{children:"In Progress"}),a.map(p=>l.jsx(Kh,{todo:p},p.id))]}),r.length>0&&l.jsxs("div",{className:"todo-section",children:[l.jsx("h4",{children:"Pending"}),r.map(p=>l.jsx(Kh,{todo:p},p.id))]}),c.length>0&&l.jsxs("div",{className:"todo-section todo-completed",children:[l.jsxs("h4",{children:["Completed (",c.length,")"]}),c.map(p=>l.jsx(Kh,{todo:p},p.id))]})]})})}function tP(){const[n,e]=m.useState([]),i=m.useRef(null),a=m.useRef();m.useEffect(()=>{const f=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/background-tasks`,p=()=>{try{i.current=new WebSocket(f),i.current.onopen=()=>{console.debug("[useBackgroundTasks] WebSocket connected")},i.current.onmessage=y=>{try{const b=JSON.parse(y.data);switch(b.type){case"init":b.tasks&&e(b.tasks);break;case"task:started":b.task&&e(x=>x.some(w=>w.taskId===b.task.taskId)?x:[...x,b.task]);break;case"task:completed":b.task&&e(x=>x.map(w=>w.taskId===b.task.taskId?{...w,...b.task}:w));break}}catch(b){console.error("[useBackgroundTasks] Failed to parse message:",b)}},i.current.onclose=()=>{console.debug("[useBackgroundTasks] WebSocket closed, reconnecting..."),a.current=setTimeout(p,2e3)},i.current.onerror=y=>{console.error("[useBackgroundTasks] WebSocket error:",y)}}catch(y){console.error("[useBackgroundTasks] WebSocket init failed:",y)}};return p(),()=>{a.current&&clearTimeout(a.current),i.current&&i.current.close()}},[]);const r=m.useCallback(()=>{e(h=>h.filter(f=>f.status==="pending"))},[]),c=n.filter(h=>h.status==="pending").length,d=n.filter(h=>h.status==="completed").length;return{tasks:n,pendingCount:c,completedCount:d,clearCompleted:r}}function Ix(n){return n<1e3?`${n}ms`:n<6e4?`${Math.floor(n/1e3)}s`:`${Math.floor(n/6e4)}m`}function nP({task:n,tick:e}){const a=n.status==="pending"?"...":n.success?"v":"x",r=`task-item task-${n.status}${n.success===!1?" task-error":""}`;let c;return n.status==="completed"&&n.durationMs!==void 0?c=Ix(n.durationMs):c=Ix(Date.now()-n.startedAt),l.jsxs("div",{className:r,"data-testid":`task-${n.taskId}`,children:[l.jsx("span",{className:"task-status",children:a}),l.jsxs("div",{className:"task-content",children:[l.jsx("span",{className:"task-description",children:n.description}),l.jsx("span",{className:"task-type",children:n.subagentType})]}),l.jsx("span",{className:"task-elapsed",children:c})]})}function cC(){const{tasks:n,pendingCount:e,completedCount:i,clearCompleted:a}=tP(),[r,c]=m.useState(0);if(m.useEffect(()=>{if(e===0)return;const h=setInterval(()=>{c(f=>f+1)},1e3);return()=>clearInterval(h)},[e]),n.length===0)return l.jsx("div",{className:"background-panel empty","data-testid":"background-panel",children:l.jsx("div",{className:"placeholder",children:"No subagent tasks"})});const d=[...n].sort((h,f)=>h.status==="pending"&&f.status!=="pending"?-1:h.status!=="pending"&&f.status==="pending"?1:f.startedAt-h.startedAt);return l.jsxs("div",{className:"background-panel","data-testid":"background-panel",children:[l.jsxs("div",{className:"panel-header",children:[l.jsxs("span",{className:"task-counts",children:[e>0&&l.jsxs("span",{className:"pending-count",children:[e," running"]}),i>0&&l.jsxs("span",{className:"completed-count",children:[i," done"]})]}),i>0&&l.jsx(Ce,{variant:"ghost",size:"sm",type:"button",className:"clear-button",onClick:a,children:"Clear"})]}),l.jsx("div",{className:"task-list",children:d.map(h=>l.jsx(nP,{task:h,tick:r},h.taskId))})]})}function Tf(n,[e,i]){return Math.min(i,Math.max(e,n))}function iP(n,e){return m.useReducer((i,a)=>e[i][a]??i,n)}var Im="ScrollArea",[uC]=cn(Im),[sP,Dn]=uC(Im),dC=m.forwardRef((n,e)=>{const{__scopeScrollArea:i,type:a="hover",dir:r,scrollHideDelay:c=600,...d}=n,[h,f]=m.useState(null),[p,y]=m.useState(null),[b,x]=m.useState(null),[w,E]=m.useState(null),[_,C]=m.useState(null),[D,N]=m.useState(0),[k,T]=m.useState(0),[R,z]=m.useState(!1),[O,A]=m.useState(!1),G=Ie(e,B=>f(B)),U=Kc(r);return l.jsx(sP,{scope:i,type:a,dir:U,scrollHideDelay:c,scrollArea:h,viewport:p,onViewportChange:y,content:b,onContentChange:x,scrollbarX:w,onScrollbarXChange:E,scrollbarXEnabled:R,onScrollbarXEnabledChange:z,scrollbarY:_,onScrollbarYChange:C,scrollbarYEnabled:O,onScrollbarYEnabledChange:A,onCornerWidthChange:N,onCornerHeightChange:T,children:l.jsx(je.div,{dir:U,...d,ref:G,style:{position:"relative","--radix-scroll-area-corner-width":D+"px","--radix-scroll-area-corner-height":k+"px",...n.style}})})});dC.displayName=Im;var hC="ScrollAreaViewport",fC=m.forwardRef((n,e)=>{const{__scopeScrollArea:i,children:a,nonce:r,...c}=n,d=Dn(hC,i),h=m.useRef(null),f=Ie(e,h,d.onViewportChange);return l.jsxs(l.Fragment,{children:[l.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),l.jsx(je.div,{"data-radix-scroll-area-viewport":"",...c,ref:f,style:{overflowX:d.scrollbarXEnabled?"scroll":"hidden",overflowY:d.scrollbarYEnabled?"scroll":"hidden",...n.style},children:l.jsx("div",{ref:d.onContentChange,style:{minWidth:"100%",display:"table"},children:a})})]})});fC.displayName=hC;var Jn="ScrollAreaScrollbar",Gm=m.forwardRef((n,e)=>{const{forceMount:i,...a}=n,r=Dn(Jn,n.__scopeScrollArea),{onScrollbarXEnabledChange:c,onScrollbarYEnabledChange:d}=r,h=n.orientation==="horizontal";return m.useEffect(()=>(h?c(!0):d(!0),()=>{h?c(!1):d(!1)}),[h,c,d]),r.type==="hover"?l.jsx(aP,{...a,ref:e,forceMount:i}):r.type==="scroll"?l.jsx(oP,{...a,ref:e,forceMount:i}):r.type==="auto"?l.jsx(mC,{...a,ref:e,forceMount:i}):r.type==="always"?l.jsx(Bm,{...a,ref:e}):null});Gm.displayName=Jn;var aP=m.forwardRef((n,e)=>{const{forceMount:i,...a}=n,r=Dn(Jn,n.__scopeScrollArea),[c,d]=m.useState(!1);return m.useEffect(()=>{const h=r.scrollArea;let f=0;if(h){const p=()=>{window.clearTimeout(f),d(!0)},y=()=>{f=window.setTimeout(()=>d(!1),r.scrollHideDelay)};return h.addEventListener("pointerenter",p),h.addEventListener("pointerleave",y),()=>{window.clearTimeout(f),h.removeEventListener("pointerenter",p),h.removeEventListener("pointerleave",y)}}},[r.scrollArea,r.scrollHideDelay]),l.jsx(qt,{present:i||c,children:l.jsx(mC,{"data-state":c?"visible":"hidden",...a,ref:e})})}),oP=m.forwardRef((n,e)=>{const{forceMount:i,...a}=n,r=Dn(Jn,n.__scopeScrollArea),c=n.orientation==="horizontal",d=eu(()=>f("SCROLL_END"),100),[h,f]=iP("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return m.useEffect(()=>{if(h==="idle"){const p=window.setTimeout(()=>f("HIDE"),r.scrollHideDelay);return()=>window.clearTimeout(p)}},[h,r.scrollHideDelay,f]),m.useEffect(()=>{const p=r.viewport,y=c?"scrollLeft":"scrollTop";if(p){let b=p[y];const x=()=>{const w=p[y];b!==w&&(f("SCROLL"),d()),b=w};return p.addEventListener("scroll",x),()=>p.removeEventListener("scroll",x)}},[r.viewport,c,f,d]),l.jsx(qt,{present:i||h!=="hidden",children:l.jsx(Bm,{"data-state":h==="hidden"?"hidden":"visible",...a,ref:e,onPointerEnter:we(n.onPointerEnter,()=>f("POINTER_ENTER")),onPointerLeave:we(n.onPointerLeave,()=>f("POINTER_LEAVE"))})})}),mC=m.forwardRef((n,e)=>{const i=Dn(Jn,n.__scopeScrollArea),{forceMount:a,...r}=n,[c,d]=m.useState(!1),h=n.orientation==="horizontal",f=eu(()=>{if(i.viewport){const p=i.viewport.offsetWidth<i.viewport.scrollWidth,y=i.viewport.offsetHeight<i.viewport.scrollHeight;d(h?p:y)}},10);return Ba(i.viewport,f),Ba(i.content,f),l.jsx(qt,{present:a||c,children:l.jsx(Bm,{"data-state":c?"visible":"hidden",...r,ref:e})})}),Bm=m.forwardRef((n,e)=>{const{orientation:i="vertical",...a}=n,r=Dn(Jn,n.__scopeScrollArea),c=m.useRef(null),d=m.useRef(0),[h,f]=m.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),p=bC(h.viewport,h.content),y={...a,sizes:h,onSizesChange:f,hasThumb:p>0&&p<1,onThumbChange:x=>c.current=x,onThumbPointerUp:()=>d.current=0,onThumbPointerDown:x=>d.current=x};function b(x,w){return hP(x,d.current,h,w)}return i==="horizontal"?l.jsx(rP,{...y,ref:e,onThumbPositionChange:()=>{if(r.viewport&&c.current){const x=r.viewport.scrollLeft,w=Gx(x,h,r.dir);c.current.style.transform=`translate3d(${w}px, 0, 0)`}},onWheelScroll:x=>{r.viewport&&(r.viewport.scrollLeft=x)},onDragScroll:x=>{r.viewport&&(r.viewport.scrollLeft=b(x,r.dir))}}):i==="vertical"?l.jsx(lP,{...y,ref:e,onThumbPositionChange:()=>{if(r.viewport&&c.current){const x=r.viewport.scrollTop,w=Gx(x,h);c.current.style.transform=`translate3d(0, ${w}px, 0)`}},onWheelScroll:x=>{r.viewport&&(r.viewport.scrollTop=x)},onDragScroll:x=>{r.viewport&&(r.viewport.scrollTop=b(x))}}):null}),rP=m.forwardRef((n,e)=>{const{sizes:i,onSizesChange:a,...r}=n,c=Dn(Jn,n.__scopeScrollArea),[d,h]=m.useState(),f=m.useRef(null),p=Ie(e,f,c.onScrollbarXChange);return m.useEffect(()=>{f.current&&h(getComputedStyle(f.current))},[f]),l.jsx(gC,{"data-orientation":"horizontal",...r,ref:p,sizes:i,style:{bottom:0,left:c.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:c.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Jc(i)+"px",...n.style},onThumbPointerDown:y=>n.onThumbPointerDown(y.x),onDragScroll:y=>n.onDragScroll(y.x),onWheelScroll:(y,b)=>{if(c.viewport){const x=c.viewport.scrollLeft+y.deltaX;n.onWheelScroll(x),wC(x,b)&&y.preventDefault()}},onResize:()=>{f.current&&c.viewport&&d&&a({content:c.viewport.scrollWidth,viewport:c.viewport.offsetWidth,scrollbar:{size:f.current.clientWidth,paddingStart:Cc(d.paddingLeft),paddingEnd:Cc(d.paddingRight)}})}})}),lP=m.forwardRef((n,e)=>{const{sizes:i,onSizesChange:a,...r}=n,c=Dn(Jn,n.__scopeScrollArea),[d,h]=m.useState(),f=m.useRef(null),p=Ie(e,f,c.onScrollbarYChange);return m.useEffect(()=>{f.current&&h(getComputedStyle(f.current))},[f]),l.jsx(gC,{"data-orientation":"vertical",...r,ref:p,sizes:i,style:{top:0,right:c.dir==="ltr"?0:void 0,left:c.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Jc(i)+"px",...n.style},onThumbPointerDown:y=>n.onThumbPointerDown(y.y),onDragScroll:y=>n.onDragScroll(y.y),onWheelScroll:(y,b)=>{if(c.viewport){const x=c.viewport.scrollTop+y.deltaY;n.onWheelScroll(x),wC(x,b)&&y.preventDefault()}},onResize:()=>{f.current&&c.viewport&&d&&a({content:c.viewport.scrollHeight,viewport:c.viewport.offsetHeight,scrollbar:{size:f.current.clientHeight,paddingStart:Cc(d.paddingTop),paddingEnd:Cc(d.paddingBottom)}})}})}),[cP,pC]=uC(Jn),gC=m.forwardRef((n,e)=>{const{__scopeScrollArea:i,sizes:a,hasThumb:r,onThumbChange:c,onThumbPointerUp:d,onThumbPointerDown:h,onThumbPositionChange:f,onDragScroll:p,onWheelScroll:y,onResize:b,...x}=n,w=Dn(Jn,i),[E,_]=m.useState(null),C=Ie(e,G=>_(G)),D=m.useRef(null),N=m.useRef(""),k=w.viewport,T=a.content-a.viewport,R=Gt(y),z=Gt(f),O=eu(b,10);function A(G){if(D.current){const U=G.clientX-D.current.left,B=G.clientY-D.current.top;p({x:U,y:B})}}return m.useEffect(()=>{const G=U=>{const B=U.target;E?.contains(B)&&R(U,T)};return document.addEventListener("wheel",G,{passive:!1}),()=>document.removeEventListener("wheel",G,{passive:!1})},[k,E,T,R]),m.useEffect(z,[a,z]),Ba(E,O),Ba(w.content,O),l.jsx(cP,{scope:i,scrollbar:E,hasThumb:r,onThumbChange:Gt(c),onThumbPointerUp:Gt(d),onThumbPositionChange:z,onThumbPointerDown:Gt(h),children:l.jsx(je.div,{...x,ref:C,style:{position:"absolute",...x.style},onPointerDown:we(n.onPointerDown,G=>{G.button===0&&(G.target.setPointerCapture(G.pointerId),D.current=E.getBoundingClientRect(),N.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",w.viewport&&(w.viewport.style.scrollBehavior="auto"),A(G))}),onPointerMove:we(n.onPointerMove,A),onPointerUp:we(n.onPointerUp,G=>{const U=G.target;U.hasPointerCapture(G.pointerId)&&U.releasePointerCapture(G.pointerId),document.body.style.webkitUserSelect=N.current,w.viewport&&(w.viewport.style.scrollBehavior=""),D.current=null})})})}),Sc="ScrollAreaThumb",vC=m.forwardRef((n,e)=>{const{forceMount:i,...a}=n,r=pC(Sc,n.__scopeScrollArea);return l.jsx(qt,{present:i||r.hasThumb,children:l.jsx(uP,{ref:e,...a})})}),uP=m.forwardRef((n,e)=>{const{__scopeScrollArea:i,style:a,...r}=n,c=Dn(Sc,i),d=pC(Sc,i),{onThumbPositionChange:h}=d,f=Ie(e,b=>d.onThumbChange(b)),p=m.useRef(void 0),y=eu(()=>{p.current&&(p.current(),p.current=void 0)},100);return m.useEffect(()=>{const b=c.viewport;if(b){const x=()=>{if(y(),!p.current){const w=fP(b,h);p.current=w,h()}};return h(),b.addEventListener("scroll",x),()=>b.removeEventListener("scroll",x)}},[c.viewport,y,h]),l.jsx(je.div,{"data-state":d.hasThumb?"visible":"hidden",...r,ref:f,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...a},onPointerDownCapture:we(n.onPointerDownCapture,b=>{const w=b.target.getBoundingClientRect(),E=b.clientX-w.left,_=b.clientY-w.top;d.onThumbPointerDown({x:E,y:_})}),onPointerUp:we(n.onPointerUp,d.onThumbPointerUp)})});vC.displayName=Sc;var Hm="ScrollAreaCorner",yC=m.forwardRef((n,e)=>{const i=Dn(Hm,n.__scopeScrollArea),a=!!(i.scrollbarX&&i.scrollbarY);return i.type!=="scroll"&&a?l.jsx(dP,{...n,ref:e}):null});yC.displayName=Hm;var dP=m.forwardRef((n,e)=>{const{__scopeScrollArea:i,...a}=n,r=Dn(Hm,i),[c,d]=m.useState(0),[h,f]=m.useState(0),p=!!(c&&h);return Ba(r.scrollbarX,()=>{const y=r.scrollbarX?.offsetHeight||0;r.onCornerHeightChange(y),f(y)}),Ba(r.scrollbarY,()=>{const y=r.scrollbarY?.offsetWidth||0;r.onCornerWidthChange(y),d(y)}),p?l.jsx(je.div,{...a,ref:e,style:{width:c,height:h,position:"absolute",right:r.dir==="ltr"?0:void 0,left:r.dir==="rtl"?0:void 0,bottom:0,...n.style}}):null});function Cc(n){return n?parseInt(n,10):0}function bC(n,e){const i=n/e;return isNaN(i)?0:i}function Jc(n){const e=bC(n.viewport,n.content),i=n.scrollbar.paddingStart+n.scrollbar.paddingEnd,a=(n.scrollbar.size-i)*e;return Math.max(a,18)}function hP(n,e,i,a="ltr"){const r=Jc(i),c=r/2,d=e||c,h=r-d,f=i.scrollbar.paddingStart+d,p=i.scrollbar.size-i.scrollbar.paddingEnd-h,y=i.content-i.viewport,b=a==="ltr"?[0,y]:[y*-1,0];return xC([f,p],b)(n)}function Gx(n,e,i="ltr"){const a=Jc(e),r=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,c=e.scrollbar.size-r,d=e.content-e.viewport,h=c-a,f=i==="ltr"?[0,d]:[d*-1,0],p=Tf(n,f);return xC([0,d],[0,h])(p)}function xC(n,e){return i=>{if(n[0]===n[1]||e[0]===e[1])return e[0];const a=(e[1]-e[0])/(n[1]-n[0]);return e[0]+a*(i-n[0])}}function wC(n,e){return n>0&&n<e}var fP=(n,e=()=>{})=>{let i={left:n.scrollLeft,top:n.scrollTop},a=0;return(function r(){const c={left:n.scrollLeft,top:n.scrollTop},d=i.left!==c.left,h=i.top!==c.top;(d||h)&&e(),i=c,a=window.requestAnimationFrame(r)})(),()=>window.cancelAnimationFrame(a)};function eu(n,e){const i=Gt(n),a=m.useRef(0);return m.useEffect(()=>()=>window.clearTimeout(a.current),[]),m.useCallback(()=>{window.clearTimeout(a.current),a.current=window.setTimeout(i,e)},[i,e])}function Ba(n,e){const i=Gt(e);Dt(()=>{let a=0;if(n){const r=new ResizeObserver(()=>{cancelAnimationFrame(a),a=window.requestAnimationFrame(i)});return r.observe(n),()=>{window.cancelAnimationFrame(a),r.unobserve(n)}}},[n,i])}var SC=dC,mP=fC,pP=yC;const Vm=m.forwardRef(({className:n,children:e,...i},a)=>l.jsxs(SC,{ref:a,className:ye("relative overflow-hidden",n),...i,children:[l.jsx(mP,{className:"h-full w-full rounded-[inherit]",children:e}),l.jsx(CC,{}),l.jsx(pP,{})]}));Vm.displayName=SC.displayName;const CC=m.forwardRef(({className:n,orientation:e="vertical",...i},a)=>l.jsx(Gm,{ref:a,orientation:e,className:ye("flex touch-none select-none transition-colors",e==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",e==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",n),...i,children:l.jsx(vC,{className:"relative flex-1 rounded-full bg-border"})}));CC.displayName=Gm.displayName;var tu="Collapsible",[gP]=cn(tu),[vP,Fm]=gP(tu),_C=m.forwardRef((n,e)=>{const{__scopeCollapsible:i,open:a,defaultOpen:r,disabled:c,onOpenChange:d,...h}=n,[f,p]=_n({prop:a,defaultProp:r??!1,onChange:d,caller:tu});return l.jsx(vP,{scope:i,disabled:c,contentId:Mt(),open:f,onOpenToggle:m.useCallback(()=>p(y=>!y),[p]),children:l.jsx(je.div,{"data-state":$m(f),"data-disabled":c?"":void 0,...h,ref:e})})});_C.displayName=tu;var EC="CollapsibleTrigger",DC=m.forwardRef((n,e)=>{const{__scopeCollapsible:i,...a}=n,r=Fm(EC,i);return l.jsx(je.button,{type:"button","aria-controls":r.contentId,"aria-expanded":r.open||!1,"data-state":$m(r.open),"data-disabled":r.disabled?"":void 0,disabled:r.disabled,...a,ref:e,onClick:we(n.onClick,r.onOpenToggle)})});DC.displayName=EC;var Um="CollapsibleContent",AC=m.forwardRef((n,e)=>{const{forceMount:i,...a}=n,r=Fm(Um,n.__scopeCollapsible);return l.jsx(qt,{present:i||r.open,children:({present:c})=>l.jsx(yP,{...a,ref:e,present:c})})});AC.displayName=Um;var yP=m.forwardRef((n,e)=>{const{__scopeCollapsible:i,present:a,children:r,...c}=n,d=Fm(Um,i),[h,f]=m.useState(a),p=m.useRef(null),y=Ie(e,p),b=m.useRef(0),x=b.current,w=m.useRef(0),E=w.current,_=d.open||h,C=m.useRef(_),D=m.useRef(void 0);return m.useEffect(()=>{const N=requestAnimationFrame(()=>C.current=!1);return()=>cancelAnimationFrame(N)},[]),Dt(()=>{const N=p.current;if(N){D.current=D.current||{transitionDuration:N.style.transitionDuration,animationName:N.style.animationName},N.style.transitionDuration="0s",N.style.animationName="none";const k=N.getBoundingClientRect();b.current=k.height,w.current=k.width,C.current||(N.style.transitionDuration=D.current.transitionDuration,N.style.animationName=D.current.animationName),f(a)}},[d.open,a]),l.jsx(je.div,{"data-state":$m(d.open),"data-disabled":d.disabled?"":void 0,id:d.contentId,hidden:!_,...c,ref:y,style:{"--radix-collapsible-content-height":x?`${x}px`:void 0,"--radix-collapsible-content-width":E?`${E}px`:void 0,...n.style},children:_&&r})});function $m(n){return n?"open":"closed"}var bP=_C;const NC=bP,jC=DC,TC=AC;function xP(){const[n,e]=m.useState({}),[i,a]=m.useState(new Set),[r,c]=m.useState(null),d=m.useCallback(async h=>{if(!(n[h]||i.has(h))){a(f=>new Set(f).add(h)),c(null);try{const f=h?`?path=${encodeURIComponent(h)}`:"",p=await fetch(`/api/files${f}`);if(!p.ok)throw new Error(`Failed to list directory: ${p.statusText}`);const y=await p.json(),x=(Array.isArray(y)?y:y.entries??[]).sort((w,E)=>w.type!==E.type?w.type==="directory"?-1:1:w.name.localeCompare(E.name));e(w=>({...w,[h||"__root__"]:x}))}catch(f){c(f instanceof Error?f.message:"Failed to load directory")}finally{a(f=>{const p=new Set(f);return p.delete(h),p})}}},[n,i]);return{cache:n,loading:i,error:r,fetchDirectory:d}}function kC({entry:n,status:e,depth:i,onFileClick:a}){const r=e==="created"?"+":e==="modified"?"~":e==="deleted"?"-":null;return l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsxs("div",{role:"treeitem",className:`file-item${e?` file-${e}`:""}`,style:{paddingLeft:`${12+i*16}px`},tabIndex:0,"aria-label":`${n.name}${e?`, ${e}`:""}`,onClick:()=>a?.(n,e),onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),a?.(n,e))},children:[r&&l.jsx("span",{className:`status-icon status-${e}`,"aria-hidden":"true",children:r}),l.jsx("span",{className:"file-name",children:n.name})]})}),l.jsx(Te,{children:n.path})]})}function RC({entry:n,depth:e,changedFiles:i,onFileClick:a,fetchDirectory:r,cache:c,loading:d}){const h=Array.from(i.keys()).some(w=>w.startsWith(n.path+"/")),[f,p]=m.useState(h),y=c[n.path],b=d.has(n.path);m.useEffect(()=>{h&&!y&&!d.has(n.path)&&r(n.path)},[h,y,n.path,r,d]),m.useEffect(()=>{h&&p(!0)},[h]);const x=m.useCallback(()=>{const w=!f;p(w),w&&!y&&r(n.path)},[f,y,n.path,r]);return l.jsxs(NC,{open:f,onOpenChange:x,children:[l.jsx(jC,{asChild:!0,children:l.jsxs("div",{className:`directory-header${h?" has-changes":""}`,style:{paddingLeft:`${4+e*16}px`},children:[l.jsx("span",{className:"directory-toggle",children:l.jsx("span",{className:"toggle-icon",children:f?"▼":"▶"})}),l.jsx("span",{className:"directory-name",children:n.name})]})}),l.jsxs(TC,{children:[b&&l.jsx("div",{className:"tree-loading",style:{paddingLeft:`${12+(e+1)*16}px`},children:"Loading..."}),y?.map(w=>w.type==="directory"?l.jsx(RC,{entry:w,depth:e+1,changedFiles:i,onFileClick:a,fetchDirectory:r,cache:c,loading:d},w.path):l.jsx(kC,{entry:w,status:i.get(w.path),depth:e+1,onFileClick:a},w.path))]})]})}function wP({changedFiles:n,onFileClick:e}){const{cache:i,loading:a,error:r,fetchDirectory:c}=xP();m.useEffect(()=>{c("")},[]);const d=i.__root__,h=n.size;return l.jsx(St,{delayDuration:300,children:l.jsxs("div",{role:"tree","aria-label":"Project files",className:"filetree full-filetree",children:[h>0&&l.jsx($e,{variant:"secondary","data-testid":"file-count-badge",className:"file-count-badge","aria-label":`${h} files changed`,children:h}),l.jsxs(Vm,{className:"filetree-scroll",children:[r&&l.jsx("div",{className:"tree-error",children:r}),!d&&!r&&l.jsx("div",{className:"tree-loading",children:"Loading project files..."}),d?.map(f=>f.type==="directory"?l.jsx(RC,{entry:f,depth:0,changedFiles:n,onFileClick:e,fetchDirectory:c,cache:i,loading:a},f.path):l.jsx(kC,{entry:f,status:n.get(f.path),depth:0,onFileClick:e},f.path))]})]})})}function Bx(n){const e=n[0]||" ",i=n[1]||" ";return e==="D"||i==="D"?"deleted":e==="?"||e==="A"?"created":"modified"}function OC(){const{repos:n}=Lm(),e=m.useMemo(()=>{const a=new Map;for(const r of n)for(const c of r.files){const d=n.length>1?`${r.path}/${c.path}`:`${r.path}/${c.path}`;a.set(d,Bx(c.status)),a.set(c.path,Bx(c.status))}return a},[n]),i=m.useCallback((a,r)=>{fetch("/api/files/edit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:a.path})}).catch(c=>console.error("[ChangedPanel] Failed to open file:",c))},[]);return l.jsx("div",{className:"changed-panel","data-testid":"changed-panel",children:l.jsx(wP,{changedFiles:e,onFileClick:i})})}const SP=2e3;function CP(){const[n,e]=m.useState([]),[i,a]=m.useState(null),r=m.useRef(null);m.useEffect(()=>{let h=null,f=!0;const p=()=>{const y=window.location.protocol==="https:"?"wss:":"ws:",b=new WebSocket(`${y}//${window.location.host}/ws/diffs`);r.current=b,b.onopen=()=>{console.log("[useDiffs] WebSocket connected")},b.onmessage=x=>{try{const w=JSON.parse(x.data);if(w.type==="init"){const E=w.diffs||[];e(E),E.length>0&&a(E[E.length-1])}else if(w.type==="diff"){const E=w.diff;e(_=>{const C=_.findIndex(D=>D.path===E.path);if(C>=0){const D=[..._];return D[C]=E,D}return[..._,E]}),a(E)}else if(w.type==="refresh"){const E=w.diffs||[];e(E),E.length>0?a(_=>{if(_){const C=E.find(D=>D.path===_.path);if(C)return C}return E[E.length-1]}):a(null)}}catch(w){console.error("[useDiffs] Failed to parse message:",w)}},b.onclose=()=>{f&&(h=setTimeout(p,SP))},b.onerror=x=>{console.error("[useDiffs] WebSocket error:",x),b.close()}};return p(),()=>{f=!1,h&&clearTimeout(h),r.current?.close()}},[]);const c=m.useCallback(h=>{const f=n.find(p=>p.path===h);a(f||null)},[n]),d=m.useCallback(()=>{e([]),a(null),r.current?.readyState===WebSocket.OPEN&&r.current.send(JSON.stringify({type:"clear"}))},[]);return{diffs:n,selectedDiff:i,selectDiff:c,clearDiffs:d}}function _P({line:n,type:e,lineNum:i}){return l.jsxs("div",{className:`diff-line diff-${e}`,children:[i!==void 0&&l.jsx("span",{className:"line-num",children:i}),l.jsx("span",{className:"line-content",children:n})]})}function EP(n){const e=n.split(`
65
65
  `),i=[];let a=0;for(const r of e)if(r.startsWith("diff --git")||r.startsWith("index ")||r.startsWith("---")||r.startsWith("+++"))i.push({line:r,type:"header"});else if(r.startsWith("@@")){const c=r.match(/@@ -\d+(?:,\d+)? \+(\d+)/);c&&(a=parseInt(c[1],10)-1),i.push({line:r,type:"hunk"})}else r.startsWith("+")?(a++,i.push({line:r.substring(1),type:"added",lineNum:a})):r.startsWith("-")?i.push({line:r.substring(1),type:"removed"}):r.startsWith(" ")||r===""?(a++,i.push({line:r.substring(1)||"",type:"context",lineNum:a})):i.push({line:r,type:"context"});return i}function DP({diff:n}){const e=n.diff&&n.diff.trim().length>0;let i;if(e)i=EP(n.diff);else{const r=(n.original||"").split(`
66
66
  `),c=(n.modified||"").split(`
67
67
  `);i=[],r.forEach((d,h)=>{c.includes(d)||i.push({line:d,type:"removed",lineNum:h+1})}),c.forEach((d,h)=>{const f=r.includes(d)?"context":"added";i.push({line:d,type:f,lineNum:h+1})})}const a=n.additions!==void 0&&n.deletions!==void 0?`+${n.additions} -${n.deletions}`:null;return l.jsxs("div",{className:"diff-view","data-testid":"diff-view",children:[l.jsxs("div",{className:"diff-header",children:[l.jsx("span",{className:"diff-path",children:n.path}),n.status&&l.jsx("span",{className:`diff-status diff-status-${n.status}`,children:n.status}),a&&l.jsx("span",{className:"diff-stats",children:a}),l.jsx("span",{className:"diff-tool",children:n.toolName})]}),l.jsx("div",{className:"diff-content",children:i.map((r,c)=>l.jsx(_P,{line:r.line,type:r.type,lineNum:r.lineNum},c))})]})}function zC(){const{diffs:n,selectedDiff:e,selectDiff:i,clearDiffs:a}=CP();return n.length===0?l.jsxs("div",{className:"diffs-panel empty","data-testid":"diffs-panel",children:[l.jsx("div",{className:"placeholder",children:"No diffs yet"}),l.jsx("p",{className:"hint",children:"Diffs appear when files are modified"})]}):l.jsxs("div",{className:"diffs-panel","data-testid":"diffs-panel",children:[l.jsxs("div",{className:"panel-header",children:[l.jsxs("span",{className:"diff-count",children:[n.length," file(s)"]}),l.jsx(Ce,{variant:"ghost",size:"sm",type:"button",className:"clear-button",onClick:a,children:"Clear"})]}),n.length>1&&l.jsx("div",{className:"diff-tabs",children:n.map(r=>l.jsx(Ce,{variant:e?.path===r.path?"secondary":"ghost",size:"sm",type:"button",className:`diff-tab ${e?.path===r.path?"active":""}`,onClick:()=>i(r.path),children:r.path.split("/").pop()},r.path))}),e&&l.jsx(DP,{diff:e})]})}function fr({open:n,onOpenChange:e,title:i,description:a,footer:r,className:c,children:d}){return l.jsx(qc,{open:n,onOpenChange:e,children:l.jsxs(ur,{className:ye("max-w-5xl max-h-[80vh] overflow-y-auto",c),children:[l.jsxs(Yc,{children:[l.jsx(Xc,{children:i}),a&&l.jsx(Qc,{children:a})]}),d,r&&l.jsx(_m,{children:r})]})})}function AP(n){const[e,i]=m.useState(null),[a,r]=m.useState(!1),[c,d]=m.useState(null),h=m.useRef(null),f=m.useCallback(()=>{h.current&&h.current.abort();const p=new AbortController;h.current=p,r(!0),d(null);const y=new URLSearchParams({days:String(n.days)});n.repo&&y.set("repo",n.repo);const b=n.skipTypes??(n.includeOrchestrator?[]:["orchestrator"]);for(const x of b)y.append("skip_type",x);fetch(`/api/hotspots?${y}`,{signal:p.signal}).then(x=>{if(!x.ok)throw new Error(`HTTP ${x.status}: ${x.statusText}`);return x.json()}).then(x=>{i(x),r(!1)}).catch(x=>{x.name!=="AbortError"&&(d(x instanceof Error?x:new Error(String(x))),r(!1))})},[n.days,n.repo,n.skipTypes,n.includeOrchestrator]);return m.useEffect(()=>()=>{h.current&&h.current.abort()},[]),{data:e,isLoading:a,error:c,refresh:f}}const NP=[30,60,90],jP=new Set([".ts",".tsx",".js",".jsx",".py",".md",".css",".scss",".html"]),TP=new Set([".json",".yaml",".yml",".toml",".env"]);function kP(n){const e=n.split("/").pop()||"";if(e.startsWith(".")&&!e.includes(".",1))return"."+e.slice(1);const i=e.lastIndexOf(".");return i>0?e.slice(i):""}function Hx(n,e,i){if(!e)return!0;const a=kP(n);return!!(jP.has(a)||i&&TP.has(a))}function wn({label:n,field:e,currentSort:i,currentDirection:a,onSort:r,align:c="right"}){const d=i===e,h=d?a==="desc"?" v":" ^":"";return l.jsxs("th",{className:`text-xs font-medium uppercase tracking-wider text-[var(--text-muted)] pb-2 cursor-pointer select-none ${c==="left"?"text-left":"text-right"} ${d?"text-[var(--text-primary)]":""}`,onClick:()=>r(e),role:"columnheader","aria-sort":d?a==="desc"?"descending":"ascending":"none",children:[n,h]})}function RP({hotspots:n,sortField:e,sortDirection:i,onSort:a}){const r=m.useMemo(()=>{const c=[...n];return c.sort((d,h)=>{const f=d[e],p=h[e];if(typeof f=="number"&&typeof p=="number")return i==="desc"?p-f:f-p;const y=String(f),b=String(p);return i==="desc"?b.localeCompare(y):y.localeCompare(b)}),c},[n,e,i]);return l.jsxs("table",{className:"w-full text-sm",role:"table",children:[l.jsx("thead",{children:l.jsxs("tr",{className:"border-b border-[var(--border)]",children:[l.jsx(wn,{label:"Score",field:"hotspot_score",currentSort:e,currentDirection:i,onSort:a}),l.jsx(wn,{label:"Changes",field:"change_count",currentSort:e,currentDirection:i,onSort:a}),l.jsx(wn,{label:"Fixes",field:"bug_fix_count",currentSort:e,currentDirection:i,onSort:a}),l.jsx(wn,{label:"Authors",field:"author_count",currentSort:e,currentDirection:i,onSort:a}),l.jsx(wn,{label:"Churn",field:"churn",currentSort:e,currentDirection:i,onSort:a}),l.jsx(wn,{label:"File",field:"path",currentSort:e,currentDirection:i,onSort:a,align:"left"})]})}),l.jsx("tbody",{children:r.map(c=>l.jsxs("tr",{className:"text-[var(--text-primary)]",children:[l.jsx("td",{className:"text-right py-1.5",children:l.jsx($e,{variant:c.hotspot_score>=50?"destructive":c.hotspot_score>=25?"outline":"secondary",children:c.hotspot_score.toFixed(1)})}),l.jsx("td",{className:"text-right py-1.5 tabular-nums font-mono",children:c.change_count}),l.jsx("td",{className:"text-right py-1.5 tabular-nums font-mono",children:c.bug_fix_count}),l.jsx("td",{className:"text-right py-1.5 tabular-nums font-mono",children:c.author_count}),l.jsx("td",{className:"text-right py-1.5 tabular-nums font-mono",children:c.churn}),l.jsx("td",{className:"text-left py-1.5",children:l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{className:"truncate max-w-xs inline-block align-bottom font-mono text-xs",children:c.path})}),l.jsx(Te,{children:c.path})]})})]},c.path))})]})}function OP({hotspots:n,sortField:e,sortDirection:i,onSort:a}){const r=m.useMemo(()=>{const c=[...n];return c.sort((d,h)=>{const p={change_count:"total_changes",bug_fix_count:"total_bug_fixes",author_count:"avg_author_count",churn:"file_count"}[e]||e,y=d[p],b=h[p];return typeof y=="number"&&typeof b=="number"?i==="desc"?b-y:y-b:i==="desc"?String(b).localeCompare(String(y)):String(y).localeCompare(String(b))}),c},[n,e,i]);return l.jsxs("table",{className:"w-full text-sm",role:"table",children:[l.jsx("thead",{children:l.jsxs("tr",{className:"border-b border-[var(--border)]",children:[l.jsx(wn,{label:"Score",field:"hotspot_score",currentSort:e,currentDirection:i,onSort:a}),l.jsx(wn,{label:"Changes",field:"change_count",currentSort:e,currentDirection:i,onSort:a}),l.jsx(wn,{label:"Fixes",field:"bug_fix_count",currentSort:e,currentDirection:i,onSort:a}),l.jsx(wn,{label:"Authors",field:"author_count",currentSort:e,currentDirection:i,onSort:a}),l.jsx(wn,{label:"Files",field:"churn",currentSort:e,currentDirection:i,onSort:a}),l.jsx(wn,{label:"Directory",field:"path",currentSort:e,currentDirection:i,onSort:a,align:"left"})]})}),l.jsx("tbody",{children:r.map(c=>l.jsxs("tr",{className:"text-[var(--text-primary)]",children:[l.jsx("td",{className:"text-right py-1.5",children:l.jsx($e,{variant:c.hotspot_score>=50?"destructive":c.hotspot_score>=25?"outline":"secondary",children:c.hotspot_score.toFixed(1)})}),l.jsx("td",{className:"text-right py-1.5 tabular-nums font-mono",children:c.total_changes}),l.jsx("td",{className:"text-right py-1.5 tabular-nums font-mono",children:c.total_bug_fixes}),l.jsx("td",{className:"text-right py-1.5 tabular-nums font-mono",children:c.avg_author_count.toFixed(1)}),l.jsx("td",{className:"text-right py-1.5 tabular-nums font-mono",children:c.file_count}),l.jsx("td",{className:"text-left py-1.5",children:l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{className:"truncate max-w-xs inline-block align-bottom font-mono text-xs",children:c.path})}),l.jsx(Te,{children:c.path})]})})]},c.path))})]})}function zP({open:n,onOpenChange:e}){const[i,a]=m.useState(90),[r,c]=m.useState("files"),[d,h]=m.useState("hotspot_score"),[f,p]=m.useState("desc"),[y,b]=m.useState(!1),[x,w]=m.useState(!1),[E,_]=m.useState(!1),{data:C,isLoading:D,error:N,refresh:k}=AP({days:i,includeOrchestrator:y}),T=m.useCallback($=>{h(ae=>ae===$?(p(ne=>ne==="desc"?"asc":"desc"),ae):(p("desc"),$))},[]),R=m.useMemo(()=>C?C.repo_results?C.repo_results:C.file_hotspots?[{success:C.success,repo_name:C.repo_name||"",repo_path:C.repo_path||"",time_window_days:C.time_window_days||i,commit_count:C.commit_count||0,file_hotspots:C.file_hotspots||[],directory_hotspots:C.directory_hotspots||[]}]:[]:[],[C,i]),z=m.useMemo(()=>{const $=[];for(const ae of R)ae.success&&$.push(...ae.file_hotspots);return $},[R]),O=m.useMemo(()=>{const $=[];for(const ae of R)ae.success&&$.push(...ae.directory_hotspots);return $},[R]),A=m.useMemo(()=>z.filter($=>Hx($.path,x,E)),[z,x,E]),G=m.useMemo(()=>O.filter($=>Hx($.path,x,E)),[O,x,E]),U=R.reduce(($,ae)=>$+(ae.commit_count||0),0),B=()=>D?l.jsx("div",{className:"hotspots-panel loading","data-testid":"hotspots-panel",children:l.jsxs("div",{className:"space-y-3 p-2",children:[l.jsx(fe,{className:"h-4 w-40"}),l.jsx(fe,{className:"h-3 w-full"}),l.jsx(fe,{className:"h-3 w-full"}),l.jsx(fe,{className:"h-3 w-3/4"}),l.jsx(fe,{className:"h-3 w-full"}),l.jsx(fe,{className:"h-3 w-5/6"})]})}):N?l.jsxs("div",{className:"hotspots-panel error","data-testid":"hotspots-panel",children:[l.jsx("div",{className:"error-message",children:N.message}),l.jsx(Ce,{variant:"outline",size:"sm",onClick:k,children:"Retry"})]}):l.jsx(St,{delayDuration:300,children:l.jsxs("div",{className:"hotspots-panel","data-testid":"hotspots-panel",children:[l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[l.jsx("div",{className:"flex gap-1",children:NP.map($=>l.jsxs(Ce,{variant:i===$?"default":"outline",size:"sm",onClick:()=>a($),children:[$,"d"]},$))}),l.jsxs("div",{className:"flex gap-1",children:[l.jsx(Ce,{variant:r==="files"?"default":"outline",size:"sm",onClick:()=>c("files"),children:"Files"}),l.jsx(Ce,{variant:r==="dirs"?"default":"outline",size:"sm",onClick:()=>c("dirs"),children:"Dirs"})]}),l.jsx("div",{className:"ml-auto",children:l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"outline",size:"sm",onClick:k,children:"Analyze"})}),l.jsx(Te,{children:"Run hotspot analysis"})]})})]}),l.jsxs("div",{className:"flex flex-wrap items-center gap-x-6 gap-y-2",children:[l.jsxs("label",{className:"flex items-center gap-2 text-sm text-[var(--text-secondary)] cursor-pointer",children:[l.jsx("input",{type:"checkbox",checked:y,onChange:$=>b($.target.checked)}),"Include orchestrator"]}),l.jsxs("label",{className:"flex items-center gap-2 text-sm text-[var(--text-secondary)] cursor-pointer",children:[l.jsx("input",{type:"checkbox","aria-label":"Code only",checked:x,onChange:$=>w($.target.checked)}),"Code only"]}),l.jsxs("label",{className:"flex items-center gap-2 text-sm text-[var(--text-secondary)] cursor-pointer",children:[l.jsx("input",{type:"checkbox","aria-label":"Include config",checked:E,disabled:!x,onChange:$=>_($.target.checked),className:"disabled:opacity-40"}),l.jsx("span",{className:x?"":"opacity-40",children:"Include config"})]})]})]}),C&&l.jsxs("div",{className:"flex gap-4 text-xs text-[var(--text-muted)]",children:[l.jsxs("span",{children:[U," commits"]}),l.jsxs("span",{children:[A.length," files"]}),l.jsxs("span",{children:[G.length," dirs"]})]}),!C&&l.jsxs("div",{className:"text-center py-12 text-[var(--text-muted)]",children:["Click ",l.jsx("strong",{children:"Analyze"})," to detect code hotspots"]}),C&&r==="files"&&(A.length>0?l.jsx(RP,{hotspots:A.slice(0,50),sortField:d,sortDirection:f,onSort:T}):l.jsx("div",{className:"text-center py-12 text-[var(--text-muted)]",children:"No file hotspots found"})),C&&r==="dirs"&&(G.length>0?l.jsx(OP,{hotspots:G.slice(0,50),sortField:d,sortDirection:f,onSort:T}):l.jsx("div",{className:"text-center py-12 text-[var(--text-muted)]",children:"No directory hotspots found"}))]})});return l.jsx(fr,{open:n,onOpenChange:e,title:"Hotspots",description:"Files and directories ranked by change frequency and complexity",children:B()})}function MP(n){const[e,i]=m.useState(null),[a,r]=m.useState(!1),[c,d]=m.useState(null),h=m.useRef(null),f=m.useCallback(()=>{h.current&&h.current.abort();const p=new AbortController;h.current=p,r(!0),d(null);const y=new URLSearchParams({days:String(n.days)});n.repo&&y.set("repo",n.repo),n.type&&y.set("type",n.type),fetch(`/api/code-markers?${y}`,{signal:p.signal}).then(b=>{if(!b.ok)throw new Error(`HTTP ${b.status}: ${b.statusText}`);return b.json()}).then(b=>{i(b),r(!1)}).catch(b=>{b.name!=="AbortError"&&(d(b instanceof Error?b:new Error(String(b))),r(!1))})},[n.days,n.repo,n.type]);return m.useEffect(()=>()=>{h.current&&h.current.abort()},[]),{data:e,isLoading:a,error:c,refresh:f}}function PP({open:n,onOpenChange:e}){const{data:i,isLoading:a,error:r,refresh:c}=MP({days:90,repo:"pennyfarthing"});m.useEffect(()=>{n&&c()},[n,c]);const[d,h]=m.useState("all"),[f,p]=m.useState("age_days"),[y,b]=m.useState("desc"),x=m.useMemo(()=>{if(!i?.markers)return[];switch(d){case"stale":return i.markers.filter(C=>C.is_stale);case"deprecated":return[];default:return i.markers}},[i,d]),w=m.useMemo(()=>{const C=[...x];return C.sort((D,N)=>{const k=D[f],T=N[f];if(typeof k=="string"&&typeof T=="string")return y==="asc"?k.localeCompare(T):T.localeCompare(k);const R=Number(k),z=Number(T);return y==="asc"?R-z:z-R}),C},[x,f,y]),E=C=>{f===C?b(D=>D==="asc"?"desc":"asc"):(p(C),b("desc"))},_=C=>f!==C?"":y==="desc"?" v":" ^";return l.jsxs(fr,{open:n,onOpenChange:e,title:"Code Markers",description:"TODO, FIXME, HACK, and XXX markers across the codebase",children:[a&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(fe,{className:"h-4 w-full"}),l.jsx(fe,{className:"h-4 w-3/4"}),l.jsx(fe,{className:"h-4 w-1/2"})]}),r&&l.jsx("div",{className:"p-4 rounded border border-[var(--status-error)]/20 bg-[var(--status-error)]/5 text-[var(--status-error)] text-sm",children:r.message}),!a&&!r&&i&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex gap-4 text-xs text-[var(--text-muted)]","data-testid":"code-markers-summary",children:[l.jsxs("span",{"data-testid":"summary-total",children:["Total: ",l.jsx("span",{className:"tabular-nums font-mono",children:i.summary.total_markers})]}),l.jsxs("span",{"data-testid":"summary-stale",children:["Stale: ",l.jsx("span",{className:"tabular-nums font-mono",children:i.summary.stale_markers})]}),Object.entries(i.summary.by_type).map(([C,D])=>l.jsxs("span",{"data-testid":`summary-type-${C.toLowerCase()}`,children:[C,": ",l.jsx("span",{className:"tabular-nums font-mono",children:D})]},C))]}),l.jsx("div",{role:"tablist",className:"flex gap-4 border-b border-[var(--border)] mb-3",children:["all","stale","deprecated"].map(C=>l.jsx("button",{role:"tab","aria-selected":d===C,onClick:()=>h(C),className:`pb-2 text-sm capitalize ${d===C?"border-b-2 border-[var(--accent)] text-[var(--text-primary)] font-medium":"text-[var(--text-muted)]"}`,children:C},C))}),w.length===0?l.jsx("div",{className:"text-center py-12 text-[var(--text-muted)]",children:"No markers found"}):l.jsxs("table",{role:"table",className:"w-full text-sm",children:[l.jsx("thead",{children:l.jsxs("tr",{className:"border-b border-[var(--border)]",children:[l.jsxs("th",{className:"cursor-pointer select-none text-left text-xs font-medium uppercase tracking-wider text-[var(--text-muted)] pb-2",onClick:()=>E("marker_type"),children:["Type",_("marker_type")]}),l.jsxs("th",{className:"cursor-pointer select-none text-left text-xs font-medium uppercase tracking-wider text-[var(--text-muted)] pb-2",onClick:()=>E("path"),children:["File",_("path")]}),l.jsxs("th",{className:"cursor-pointer select-none text-right text-xs font-medium uppercase tracking-wider text-[var(--text-muted)] pb-2",onClick:()=>E("line"),children:["Line",_("line")]}),l.jsx("th",{className:"text-left text-xs font-medium uppercase tracking-wider text-[var(--text-muted)] pb-2",children:"Text"}),l.jsxs("th",{className:"cursor-pointer select-none text-left text-xs font-medium uppercase tracking-wider text-[var(--text-muted)] pb-2",onClick:()=>E("author"),children:["Author",_("author")]}),l.jsxs("th",{className:"cursor-pointer select-none text-right text-xs font-medium uppercase tracking-wider text-[var(--text-muted)] pb-2",onClick:()=>E("age_days"),children:["Age",_("age_days")]})]})}),l.jsx("tbody",{children:w.map((C,D)=>l.jsxs("tr",{className:"text-[var(--text-primary)]",children:[l.jsx("td",{className:"py-1.5",children:l.jsx($e,{variant:C.is_stale?"destructive":"secondary",children:C.marker_type})}),l.jsx("td",{className:"py-1.5 font-mono text-xs",children:C.path}),l.jsx("td",{className:"text-right py-1.5 tabular-nums font-mono",children:C.line}),l.jsx("td",{className:"py-1.5 truncate max-w-xs",children:C.text}),l.jsx("td",{className:"py-1.5",children:C.author}),l.jsxs("td",{className:"text-right py-1.5 tabular-nums font-mono",children:[C.age_days,"d"]})]},`${C.path}:${C.line}:${D}`))})]})]})]})}function LP(n){const[e,i]=m.useState(null),[a,r]=m.useState(!1),[c,d]=m.useState(null),h=m.useRef(null),f=m.useCallback(()=>{h.current&&h.current.abort();const p=new AbortController;h.current=p,r(!0),d(null);const y=new URLSearchParams;n.path&&y.set("path",n.path),n.top&&y.set("top",String(n.top)),fetch(`/api/complexity?${y}`,{signal:p.signal}).then(b=>{if(!b.ok)throw new Error(`HTTP ${b.status}: ${b.statusText}`);return b.json()}).then(b=>{i(b),r(!1)}).catch(b=>{b.name!=="AbortError"&&(d(b instanceof Error?b:new Error(String(b))),r(!1))})},[n.path,n.top]);return m.useEffect(()=>()=>{h.current&&h.current.abort()},[]),{data:e,isLoading:a,error:c,refresh:f}}function Na({label:n,field:e,currentSort:i,currentDirection:a,onSort:r,align:c="right"}){const d=i===e,h=d?a==="desc"?" v":" ^":"";return l.jsxs("th",{className:`text-${c} ${d?"active":""}`,onClick:()=>r(e),role:"columnheader","aria-sort":d?a==="desc"?"descending":"ascending":"none",style:{cursor:"pointer",userSelect:"none",padding:"4px 8px"},children:[n,h]})}function IP({open:n,onOpenChange:e}){const[i,a]=m.useState("avg_cyclomatic_complexity"),[r,c]=m.useState("desc"),{data:d,isLoading:h,error:f,refresh:p}=LP({});m.useEffect(()=>{n&&p()},[n,p]);const y=m.useCallback(w=>{a(E=>E===w?(c(_=>_==="desc"?"asc":"desc"),E):(c("desc"),w))},[]),b=m.useMemo(()=>{if(!d?.files)return[];const w=[...d.files];return w.sort((E,_)=>{const C=E[i],D=_[i];return typeof C=="number"&&typeof D=="number"?r==="desc"?D-C:C-D:r==="desc"?String(D).localeCompare(String(C)):String(C).localeCompare(String(D))}),w},[d,i,r]),x=()=>h?l.jsx("div",{className:"complexity-panel loading","data-testid":"complexity-panel",children:l.jsxs("div",{className:"space-y-3 p-2",children:[l.jsx(fe,{className:"h-4 w-40"}),l.jsx(fe,{className:"h-3 w-full"}),l.jsx(fe,{className:"h-3 w-full"}),l.jsx(fe,{className:"h-3 w-3/4"})]})}):f?l.jsxs("div",{className:"complexity-panel error","data-testid":"complexity-panel",children:[l.jsxs("div",{className:"error-message",children:["Error: ",f.message]}),l.jsx(Ce,{variant:"outline",size:"sm",onClick:p,children:"Retry"})]}):d?l.jsxs("div",{className:"complexity-panel","data-testid":"complexity-panel",children:[l.jsx("div",{className:"complexity-summary",style:{marginBottom:"8px"},children:l.jsxs("span",{children:[d.file_count," files analyzed"]})}),l.jsxs("table",{className:"complexity-table",role:"table",style:{width:"100%",borderCollapse:"collapse"},children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx(Na,{label:"Complexity",field:"avg_cyclomatic_complexity",currentSort:i,currentDirection:r,onSort:y}),l.jsx(Na,{label:"Nesting",field:"max_nesting_depth",currentSort:i,currentDirection:r,onSort:y}),l.jsx(Na,{label:"Longest Fn",field:"longest_function",currentSort:i,currentDirection:r,onSort:y}),l.jsx(Na,{label:"Lines",field:"total_lines",currentSort:i,currentDirection:r,onSort:y}),l.jsx(Na,{label:"Functions",field:"function_count",currentSort:i,currentDirection:r,onSort:y}),l.jsx(Na,{label:"File",field:"path",currentSort:i,currentDirection:r,onSort:y,align:"left"})]})}),l.jsx("tbody",{children:b.map(w=>l.jsxs("tr",{children:[l.jsx("td",{className:"text-right",style:{padding:"4px 8px"},children:l.jsx($e,{variant:w.avg_cyclomatic_complexity>=7?"destructive":w.avg_cyclomatic_complexity>=4?"outline":"secondary",children:Number(w.avg_cyclomatic_complexity).toFixed(1)})}),l.jsx("td",{className:"text-right",style:{padding:"4px 8px"},children:w.max_nesting_depth}),l.jsx("td",{className:"text-right",style:{padding:"4px 8px"},children:w.longest_function}),l.jsx("td",{className:"text-right",style:{padding:"4px 8px"},children:w.total_lines}),l.jsx("td",{className:"text-right",style:{padding:"4px 8px"},children:w.function_count}),l.jsx("td",{className:"text-left",style:{padding:"4px 8px"},children:w.path})]},w.path))})]})]}):l.jsx("div",{className:"complexity-panel","data-testid":"complexity-panel",children:l.jsxs("p",{children:["Click ",l.jsx("strong",{children:"Analyze"})," to run complexity analysis"]})});return l.jsx(fr,{open:n,onOpenChange:e,title:"Complexity",description:"Cyclomatic complexity analysis",children:x()})}function GP(n){const[e,i]=m.useState(null),[a,r]=m.useState(!1),[c,d]=m.useState(null),h=m.useRef(null),f=m.useCallback(()=>{h.current&&h.current.abort();const p=new AbortController;h.current=p,r(!0),d(null);const y=new URLSearchParams;n.path&&y.set("path",n.path),fetch(`/api/dependencies?${y}`,{signal:p.signal}).then(b=>{if(!b.ok)throw new Error(`HTTP ${b.status}: ${b.statusText}`);return b.json()}).then(b=>{i(b),r(!1)}).catch(b=>{b.name!=="AbortError"&&(d(b instanceof Error?b:new Error(String(b))),r(!1))})},[n.path]);return m.useEffect(()=>()=>{h.current&&h.current.abort()},[]),{data:e,isLoading:a,error:c,refresh:f}}function BP(n){return n==="high"||n==="critical"?"destructive":n==="moderate"?"outline":"secondary"}function HP({open:n,onOpenChange:e}){const{data:i,isLoading:a,error:r,refresh:c}=GP({});m.useEffect(()=>{n&&c()},[n,c]);const d=()=>a?l.jsx("div",{className:"dependencies-panel loading","data-testid":"dependencies-panel",children:l.jsxs("div",{className:"space-y-3 p-2",children:[l.jsx(fe,{className:"h-4 w-40"}),l.jsx(fe,{className:"h-3 w-full"}),l.jsx(fe,{className:"h-3 w-full"}),l.jsx(fe,{className:"h-3 w-3/4"})]})}):r?l.jsxs("div",{className:"dependencies-panel error","data-testid":"dependencies-panel",children:[l.jsxs("div",{className:"error-message",children:["Error: ",r.message]}),l.jsx(Ce,{variant:"outline",size:"sm",onClick:c,children:"Retry"})]}):i?l.jsxs("div",{className:"dependencies-panel","data-testid":"dependencies-panel",children:[i.outdated.length>0&&l.jsxs("div",{className:"outdated-section",style:{marginBottom:"16px"},children:[l.jsxs("h4",{children:["Outdated Packages (",i.outdated.length,")"]}),l.jsxs("table",{role:"table",style:{width:"100%",borderCollapse:"collapse"},children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{className:"text-left",style:{padding:"4px 8px"},children:"Package"}),l.jsx("th",{className:"text-left",style:{padding:"4px 8px"},children:"Current"}),l.jsx("th",{className:"text-left",style:{padding:"4px 8px"},children:"Wanted"}),l.jsx("th",{className:"text-left",style:{padding:"4px 8px"},children:"Latest"}),l.jsx("th",{className:"text-left",style:{padding:"4px 8px"},children:"Type"})]})}),l.jsx("tbody",{children:i.outdated.map(h=>l.jsxs("tr",{children:[l.jsx("td",{style:{padding:"4px 8px"},children:h.name}),l.jsx("td",{style:{padding:"4px 8px"},children:h.current}),l.jsx("td",{style:{padding:"4px 8px"},children:h.wanted}),l.jsx("td",{style:{padding:"4px 8px"},children:h.latest}),l.jsx("td",{style:{padding:"4px 8px"},children:h.type})]},h.name))})]})]}),i.advisories.length>0&&l.jsxs("div",{className:"security-section",children:[l.jsx("h4",{children:"Security Advisories"}),l.jsx("div",{style:{display:"flex",gap:"8px",flexWrap:"wrap"},children:i.advisories.map(h=>l.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[l.jsx($e,{variant:BP(h.severity),children:h.severity}),l.jsx("span",{children:h.count})]},h.severity))})]}),i.outdated.length===0&&i.advisories.length===0&&l.jsx("p",{children:"All dependencies are up to date with no known vulnerabilities."})]}):l.jsx("div",{className:"dependencies-panel","data-testid":"dependencies-panel",children:l.jsxs("p",{children:["Click ",l.jsx("strong",{children:"Analyze"})," to check dependencies"]})});return l.jsx(fr,{open:n,onOpenChange:e,title:"Dependencies",description:"Package staleness and security analysis",children:d()})}function VP(n,e=[]){let i=[];function a(c,d){const h=m.createContext(d);h.displayName=c+"Context";const f=i.length;i=[...i,d];const p=b=>{const{scope:x,children:w,...E}=b,_=x?.[n]?.[f]||h,C=m.useMemo(()=>E,Object.values(E));return l.jsx(_.Provider,{value:C,children:w})};p.displayName=c+"Provider";function y(b,x){const w=x?.[n]?.[f]||h,E=m.useContext(w);if(E)return E;if(d!==void 0)return d;throw new Error(`\`${b}\` must be used within \`${c}\``)}return[p,y]}const r=()=>{const c=i.map(d=>m.createContext(d));return function(h){const f=h?.[n]||c;return m.useMemo(()=>({[`__scope${n}`]:{...h,[n]:f}}),[h,f])}};return r.scopeName=n,[a,FP(r,...e)]}function FP(...n){const e=n[0];if(n.length===1)return e;const i=()=>{const a=n.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(c){const d=a.reduce((h,{useScope:f,scopeName:p})=>{const b=f(c)[`__scope${p}`];return{...h,...b}},{});return m.useMemo(()=>({[`__scope${e.scopeName}`]:d}),[d])}};return i.scopeName=e.scopeName,i}var Wm="Progress",qm=100,[UP]=VP(Wm),[$P,WP]=UP(Wm),MC=m.forwardRef((n,e)=>{const{__scopeProgress:i,value:a=null,max:r,getValueLabel:c=qP,...d}=n;(r||r===0)&&!Vx(r)&&console.error(YP(`${r}`,"Progress"));const h=Vx(r)?r:qm;a!==null&&!Fx(a,h)&&console.error(XP(`${a}`,"Progress"));const f=Fx(a,h)?a:null,p=_c(f)?c(f,h):void 0;return l.jsx($P,{scope:i,value:f,max:h,children:l.jsx(In.div,{"aria-valuemax":h,"aria-valuemin":0,"aria-valuenow":_c(f)?f:void 0,"aria-valuetext":p,role:"progressbar","data-state":IC(f,h),"data-value":f??void 0,"data-max":h,...d,ref:e})})});MC.displayName=Wm;var PC="ProgressIndicator",LC=m.forwardRef((n,e)=>{const{__scopeProgress:i,...a}=n,r=WP(PC,i);return l.jsx(In.div,{"data-state":IC(r.value,r.max),"data-value":r.value??void 0,"data-max":r.max,...a,ref:e})});LC.displayName=PC;function qP(n,e){return`${Math.round(n/e*100)}%`}function IC(n,e){return n==null?"indeterminate":n===e?"complete":"loading"}function _c(n){return typeof n=="number"}function Vx(n){return _c(n)&&!isNaN(n)&&n>0}function Fx(n,e){return _c(n)&&!isNaN(n)&&n<=e&&n>=0}function YP(n,e){return`Invalid prop \`max\` of value \`${n}\` supplied to \`${e}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${qm}\`.`}function XP(n,e){return`Invalid prop \`value\` of value \`${n}\` supplied to \`${e}\`. The \`value\` prop must be:
@@ -75,7 +75,7 @@ You can add a description to the \`${Ma}\` by passing a \`${YC}\` component as a
75
75
 
76
76
  Alternatively, you can use your own component as a description by assigning it an \`id\` and passing the same value to the \`aria-describedby\` prop in \`${Ma}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component.
77
77
 
78
- For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return m.useEffect(()=>{document.getElementById(n.current?.getAttribute("aria-describedby"))||console.warn(e)},[e,n]),null},rL=VC,lL=FC,JC=UC,e_=$C,t_=QC,n_=KC,i_=qC,s_=XC;const cL=rL,uL=lL,a_=m.forwardRef(({className:n,...e},i)=>l.jsx(JC,{className:ye("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",n),...e,ref:i}));a_.displayName=JC.displayName;const o_=m.forwardRef(({className:n,...e},i)=>l.jsxs(uL,{children:[l.jsx(a_,{}),l.jsx(e_,{ref:i,className:ye("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",n),...e})]}));o_.displayName=e_.displayName;const r_=({className:n,...e})=>l.jsx("div",{className:ye("flex flex-col space-y-2 text-center sm:text-left",n),...e});r_.displayName="AlertDialogHeader";const l_=({className:n,...e})=>l.jsx("div",{className:ye("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",n),...e});l_.displayName="AlertDialogFooter";const c_=m.forwardRef(({className:n,...e},i)=>l.jsx(i_,{ref:i,className:ye("text-lg font-semibold",n),...e}));c_.displayName=i_.displayName;const u_=m.forwardRef(({className:n,...e},i)=>l.jsx(s_,{ref:i,className:ye("text-sm text-muted-foreground",n),...e}));u_.displayName=s_.displayName;const d_=m.forwardRef(({className:n,...e},i)=>l.jsx(t_,{ref:i,className:ye(Dc(),n),...e}));d_.displayName=t_.displayName;const h_=m.forwardRef(({className:n,...e},i)=>l.jsx(n_,{ref:i,className:ye(Dc({variant:"outline"}),"mt-2 sm:mt-0",n),...e}));h_.displayName=n_.displayName;function dL({isOpen:n,title:e,message:i,confirmLabel:a="Confirm",cancelLabel:r="Cancel",isDanger:c=!1,onConfirm:d,onCancel:h}){return l.jsx(cL,{open:n,onOpenChange:f=>{f||h()},children:l.jsxs(o_,{children:[l.jsxs(r_,{children:[l.jsx(c_,{children:e}),l.jsx(u_,{children:i})]}),l.jsxs(l_,{children:[l.jsx(h_,{onClick:h,children:r}),l.jsx(d_,{className:ye(c&&Dc({variant:"destructive"})),onClick:d,children:a})]})]})})}function hL(n){const[e,i]=ue.useState(!1),a=m.useRef(null),r=m.useCallback(()=>new Promise(f=>{a.current=f,i(!0)}),[]),c=m.useCallback(()=>{i(!1),a.current?.(!0),a.current=null},[]),d=m.useCallback(()=>{i(!1),a.current?.(!1),a.current=null},[]),h={isOpen:e,title:n.title,message:n.message,confirmLabel:n.confirmLabel,cancelLabel:n.cancelLabel,isDanger:n.isDanger,onConfirm:c,onCancel:d};return{isOpen:e,confirm:r,dialogProps:h}}function fL(){const[n,e]=m.useState(null),[i,a]=m.useState(!1),[r,c]=m.useState(null),[d,h]=m.useState(null),f=m.useRef(null),p=m.useCallback(()=>{f.current&&f.current.abort();const b=new AbortController;f.current=b,a(!0),c(null),fetch("/api/agent-load",{signal:b.signal}).then(x=>{if(!x.ok)throw new Error(`HTTP ${x.status}: ${x.statusText}`);return x.json()}).then(x=>{e(x),a(!1)}).catch(x=>{x.name!=="AbortError"&&(c(x instanceof Error?x:new Error(String(x))),a(!1))})},[]),y=m.useCallback(async(b,x)=>{const w=await fetch("/api/agent-load/prune-sidecar",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:b,file:x})});if(!w.ok){h({success:!1,error:`HTTP ${w.status}: ${w.statusText}`});return}const E=await w.json();h(E),E.success&&p()},[p]);return m.useEffect(()=>()=>{f.current&&f.current.abort()},[]),{data:n,isLoading:i,error:r,refresh:p,pruneSidecar:y,pruneResult:d}}const mL=["patterns.md","gotchas.md","decisions.md"];function pL({isOpen:n,onClose:e}){const{data:i,isLoading:a,error:r,refresh:c,pruneSidecar:d,pruneResult:h}=fL(),[f,p]=m.useState(null),[y,b]=m.useState(null),{confirm:x,dialogProps:w}=hL({title:"Clear Sidecar",message:y?`Reset ${y.file} for ${y.agent}? This will replace the sidecar with its default template.`:"",confirmLabel:"Confirm",isDanger:!0});m.useEffect(()=>{n&&c()},[n,c]);const E=m.useMemo(()=>i?[...i.agents].sort((T,R)=>(R.totalTokens??0)-(T.totalTokens??0)):[],[i]),_=m.useMemo(()=>E.length?E[0]?.totalTokens??0:0,[E]),C=T=>{p(R=>R===T?null:T)},D=async(T,R)=>{b({agent:T,file:R}),await x()&&await d(T,R),b(null)},N=T=>{const R=T.totalTokens??0,z=_>0?R/_*100:0,O=f===T.agent,A=R>=5e3?"bg-[var(--status-error,#f14c4c)]":R>=3e3?"bg-[var(--status-warning,#cca700)]":"bg-[var(--status-success,#4ec9b0)]";return l.jsxs(NC,{open:O,onOpenChange:()=>C(T.agent),children:[l.jsx(jC,{asChild:!0,children:l.jsxs("div",{className:"px-4 py-2 cursor-pointer hover:bg-muted/50 rounded-md transition-colors","data-testid":`agent-row-${T.agent}`,children:[l.jsxs("div",{className:"flex items-center justify-between mb-1",children:[l.jsx("span",{className:"font-mono text-sm font-medium",children:T.agent}),l.jsx("span",{className:"font-mono text-sm tabular-nums text-text-secondary",children:R.toLocaleString()})]}),l.jsx(BC,{value:z,className:"h-2.5 bg-[var(--border)]",indicatorClassName:A})]})}),l.jsx(TC,{children:l.jsxs("div",{className:"mx-4 mb-3 rounded-md bg-muted/30 p-3 space-y-1",children:[T.components&&T.components.length>0?T.components.map(G=>l.jsxs("div",{className:"flex items-center justify-between text-xs text-text-secondary",children:[l.jsx("span",{children:f_(G.name)}),l.jsx("span",{className:"tabular-nums",children:G.tokens.toLocaleString()})]},G.name)):l.jsx("div",{className:"text-xs text-text-secondary",children:"No component breakdown available"}),l.jsxs("div",{className:"pt-2 border-t border-muted/50 mt-2",children:[l.jsx("div",{className:"text-xs font-medium mb-1.5 text-text-secondary",children:"Sidecars"}),l.jsx("div",{className:"flex gap-2",children:mL.map(G=>l.jsxs(Ce,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:U=>{U.stopPropagation(),D(T.agent,G)},children:["Clear ",G]},G))})]})]})})]},T.agent)},k=()=>a?l.jsx("div",{className:"space-y-3 p-4",children:Array.from({length:5}).map((T,R)=>l.jsxs("div",{"data-testid":`skeleton-${R}`,className:"space-y-1.5 px-4",children:[l.jsxs("div",{className:"flex justify-between",children:[l.jsx(fe,{className:"h-4 w-24"}),l.jsx(fe,{className:"h-4 w-16"})]}),l.jsx(fe,{className:"h-2.5 w-full rounded-full"})]},R))}):r?l.jsxs("div",{className:"p-4 space-y-3",children:[l.jsx("div",{className:"p-4 rounded border border-[var(--status-error)]/20 bg-[var(--status-error)]/5 text-[var(--status-error)] text-sm",children:r.message}),l.jsx("div",{className:"text-center",children:l.jsx(Ce,{variant:"outline",size:"sm",onClick:c,children:"Retry"})})]}):i?l.jsxs("div",{className:"space-y-0.5",children:[h?.success&&h.tokensFreed!=null&&l.jsxs("div",{className:"text-xs text-green-600 px-4 py-1",children:["Freed ",h.tokensFreed.toLocaleString()," tokens from ",h.agent,"/",h.file]}),l.jsxs("div",{className:"flex items-center justify-between px-4 py-2",children:[l.jsxs("span",{"data-testid":"cached-at",className:"text-xs text-[var(--text-muted)]",children:["Cached: ",new Date(i.cachedAt).toLocaleString()]}),l.jsx(Ce,{variant:"ghost",size:"sm",className:"text-xs h-6 text-[var(--text-muted)] hover:text-[var(--text-primary)]",onClick:c,children:"Refresh"})]}),E.map(T=>N(T))]}):null;return l.jsxs(l.Fragment,{children:[l.jsx(fr,{open:n,onOpenChange:T=>{T||e()},title:"Agent Load Analysis",description:"Token usage breakdown for all agents",className:"max-w-2xl",children:k()}),l.jsx(dL,{...w})]})}function gL(n){const[e,i]=m.useState(null),[a,r]=m.useState(!1),[c,d]=m.useState(null),h=m.useRef(null),f=m.useCallback(()=>{h.current&&h.current.abort();const p=new AbortController;h.current=p,r(!0),d(null);const y=new URLSearchParams({days:String(n.days),layer:n.layer||"all"});n.repo&&y.set("repo",n.repo),fetch(`/api/dead-code?${y}`,{signal:p.signal}).then(b=>{if(!b.ok)throw new Error(`HTTP ${b.status}: ${b.statusText}`);return b.json()}).then(b=>{i(b),r(!1)}).catch(b=>{b.name!=="AbortError"&&(d(b instanceof Error?b:new Error(String(b))),r(!1))})},[n.days,n.repo,n.layer]);return m.useEffect(()=>()=>{h.current&&h.current.abort()},[]),{data:e,isLoading:a,error:c,refresh:f}}function vL({isOpen:n,onClose:e,days:i=180,repo:a}){const{data:r,isLoading:c,error:d,refresh:h}=gL({days:i,repo:a,layer:"all"}),[f,p]=m.useState("stale"),[y,b]=m.useState("days_since_last_commit"),[x,w]=m.useState("desc"),[E,_]=m.useState("file"),[C,D]=m.useState("asc");m.useEffect(()=>{n&&h()},[n,h]);const N=m.useCallback(A=>{w(G=>y===A&&G==="desc"?"asc":"desc"),b(A)},[y]),k=m.useCallback(A=>{D(G=>E===A&&G==="desc"?"asc":"desc"),_(A)},[E]),T=r?.stale_file_count??r?.stale_files?.length??0,R=r?.unused_export_count??r?.unused_exports?.length??0,z=m.useMemo(()=>{const A=[...r?.stale_files||[]];return A.sort((G,U)=>{const B=G[y],$=U[y];if(typeof B=="number"&&typeof $=="number")return x==="asc"?B-$:$-B;const ae=String(B),ne=String($);return x==="asc"?ae.localeCompare(ne):ne.localeCompare(ae)}),A},[r?.stale_files,y,x]),O=m.useMemo(()=>{const A=[...r?.unused_exports||[]];return A.sort((G,U)=>{const B=G[E],$=U[E];if(typeof B=="number"&&typeof $=="number")return C==="asc"?B-$:$-B;const ae=String(B),ne=String($);return C==="asc"?ae.localeCompare(ne):ne.localeCompare(ae)}),A},[r?.unused_exports,E,C]);return l.jsx(qc,{open:n,onOpenChange:A=>{A||e()},children:l.jsxs(ur,{className:"max-w-4xl max-h-[80vh]",children:[l.jsxs(Yc,{children:[l.jsx(Xc,{children:"Dead Code Analysis"}),l.jsx(Qc,{children:"Diagnostic report — files and exports with no recent activity."})]}),l.jsxs("div",{className:"flex gap-4 border-b border-[var(--border)]",children:[l.jsxs("button",{onClick:()=>p("stale"),className:ye("pb-2 text-sm",f==="stale"?"border-b-2 border-[var(--accent)] text-[var(--text-primary)] font-medium":"text-[var(--text-muted)]"),children:["Stale Files ",l.jsx($e,{variant:"secondary",className:"ml-1",children:T})]}),l.jsxs("button",{onClick:()=>p("exports"),className:ye("pb-2 text-sm",f==="exports"?"border-b-2 border-[var(--accent)] text-[var(--text-primary)] font-medium":"text-[var(--text-muted)]"),children:["Unused Exports ",l.jsx($e,{variant:"secondary",className:"ml-1",children:R})]})]}),l.jsxs(Vm,{className:"h-[50vh]",children:[c&&l.jsx("div",{className:"text-center py-12 text-[var(--text-muted)]",children:"Analyzing..."}),d&&l.jsx("div",{className:"m-4 p-4 rounded border border-[var(--status-error)]/20 bg-[var(--status-error)]/5 text-[var(--status-error)] text-sm",children:d.message}),r&&f==="stale"&&(z.length===0?l.jsx("div",{className:"text-center py-12 text-[var(--text-muted)]",children:"No stale files found"}):l.jsxs("table",{className:"w-full text-sm",children:[l.jsx("thead",{children:l.jsxs("tr",{role:"row",className:"border-b border-[var(--border)]",children:[l.jsx("th",{className:"text-left pb-2 cursor-pointer select-none text-xs font-medium uppercase tracking-wider text-[var(--text-muted)]",onClick:()=>N("path"),children:"File"}),l.jsx("th",{className:"text-right pb-2 cursor-pointer select-none text-xs font-medium uppercase tracking-wider text-[var(--text-muted)]",onClick:()=>N("days_since_last_commit"),children:"Days Stale"}),l.jsx("th",{className:"text-right pb-2 cursor-pointer select-none text-xs font-medium uppercase tracking-wider text-[var(--text-muted)]",onClick:()=>N("size_bytes"),children:"Size"}),l.jsx("th",{className:"text-left pb-2 cursor-pointer select-none text-xs font-medium uppercase tracking-wider text-[var(--text-muted)]",onClick:()=>N("last_commit_date"),children:"Last Commit"})]})}),l.jsx("tbody",{children:z.map(A=>l.jsxs("tr",{role:"row",className:"text-[var(--text-primary)]",children:[l.jsx("td",{className:"py-1.5 font-mono text-xs",children:A.path}),l.jsx("td",{className:"py-1.5 text-right tabular-nums font-mono",children:A.days_since_last_commit}),l.jsx("td",{className:"py-1.5 text-right tabular-nums font-mono",children:yL(A.size_bytes)}),l.jsx("td",{className:"py-1.5",children:A.last_commit_date?new Date(A.last_commit_date).toLocaleDateString():"—"})]},A.path))})]})),r&&f==="exports"&&(O.length===0?l.jsx("div",{className:"text-center py-12 text-[var(--text-muted)]",children:"No unused exports found"}):l.jsxs("table",{className:"w-full text-sm",children:[l.jsx("thead",{children:l.jsxs("tr",{role:"row",className:"border-b border-[var(--border)]",children:[l.jsx("th",{className:"text-left pb-2 cursor-pointer select-none text-xs font-medium uppercase tracking-wider text-[var(--text-muted)]",onClick:()=>k("file"),children:"File"}),l.jsx("th",{className:"text-left pb-2 cursor-pointer select-none text-xs font-medium uppercase tracking-wider text-[var(--text-muted)]",onClick:()=>k("symbol"),children:"Export"}),l.jsx("th",{className:"text-right pb-2 cursor-pointer select-none text-xs font-medium uppercase tracking-wider text-[var(--text-muted)]",onClick:()=>k("line"),children:"Line"})]})}),l.jsx("tbody",{children:O.map(A=>l.jsxs("tr",{role:"row",className:"text-[var(--text-primary)]",children:[l.jsx("td",{className:"py-1.5 font-mono text-xs",children:A.file}),l.jsx("td",{className:"py-1.5",children:A.symbol}),l.jsx("td",{className:"py-1.5 text-right tabular-nums font-mono",children:A.line})]},`${A.file}:${A.symbol}`))})]}))]})]})})}function yL(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}const bL=[{min:90,grade:"A",color:"#22c55e"},{min:75,grade:"B",color:"#84cc16"},{min:60,grade:"C",color:"#eab308"},{min:40,grade:"D",color:"#f97316"},{min:0,grade:"F",color:"#ef4444"}],Ux={churn:"Churn",todo_density:"TODO Density",complexity:"Complexity",test_gaps:"Test Gaps",dead_code:"Dead Code",deprecation_debt:"Deprecation Debt",dependency_freshness:"Dependency Freshness",agent_context_efficiency:"Agent Context Efficiency"};function xL(n){for(const e of bL)if(n>=e.min)return{grade:e.grade,color:e.color};return{grade:"F",color:"#ef4444"}}function $x(n,e,i,a,r){const c=Wx(n,e,i,r),d=Wx(n,e,i,a),h=r-a<=180?"0":"1";return`M ${c.x} ${c.y} A ${i} ${i} 0 ${h} 0 ${d.x} ${d.y}`}function Wx(n,e,i,a){const r=(a-90)*Math.PI/180;return{x:n+i*Math.cos(r),y:e+i*Math.sin(r)}}function wL(n){const e=Math.floor(n/1e3);if(e<60)return`${e}s ago`;const i=Math.floor(e/60);return i<60?`${i}m ago`:`${Math.floor(i/60)}h ago`}function SL({score:n,dimensions:e,totalDimensions:i,onDimensionClick:a,isLoading:r,lastFetchedAt:c,onRefresh:d,error:h}){const f=n!=null,p=f?xL(n):null,y=f?n/100*180:0,[b,x]=m.useState(null);m.useEffect(()=>{if(!c){x(null);return}const _=()=>x(wL(Date.now()-c));_();const C=setInterval(_,1e4);return()=>clearInterval(C)},[c]);const w=Object.keys(Ux),E=new Map(e.map(_=>[_.name,_]));return l.jsxs("div",{"data-testid":"health-gauge","data-grade":p?.grade??null,children:[l.jsxs("div",{className:"health-gauge-header",children:[l.jsxs("div",{className:"health-gauge-status",children:[b&&l.jsx("span",{className:"health-gauge-age","data-testid":"health-gauge-age",children:b}),h&&l.jsx("span",{className:"health-gauge-error","data-testid":"health-gauge-error",children:"Failed"})]}),d&&l.jsx(Ce,{variant:"outline",size:"sm",className:"health-gauge-refresh","data-testid":"health-gauge-refresh",onClick:d,disabled:r,children:r?"Analyzing...":f?"Refresh":"Analyze"})]}),l.jsxs("svg",{viewBox:"0 0 200 120",width:"200",height:"120",className:r?"opacity-50":"",children:[l.jsx("path",{d:$x(100,100,80,0,180),fill:"none",stroke:"#333",strokeWidth:"12",strokeLinecap:"round"}),f&&y>0&&l.jsx("path",{d:$x(100,100,80,0,y),fill:"none",stroke:p.color,strokeWidth:"12",strokeLinecap:"round"}),l.jsx("text",{x:"100",y:"85",textAnchor:"middle",fontSize:"28",fill:"currentColor",children:f?String(Math.round(n)):"--"}),p&&l.jsx("text",{x:"100",y:"108",textAnchor:"middle",fontSize:"16",fill:p.color,children:p.grade})]}),f&&i&&e.length<i&&l.jsxs("div",{className:"health-gauge-partial",children:[e.length," of ",i," dimensions"]}),l.jsx("div",{"data-testid":"dimension-breakdown",className:"health-gauge-breakdown",children:w.map(_=>{const C=E.get(_);return l.jsxs("div",{"data-testid":`dimension-${_}`,className:"health-gauge-dimension",onClick:()=>a?.(_),children:[l.jsx("span",{className:"dimension-label",children:Ux[_]||_}),l.jsx("span",{className:"dimension-score",children:C?.score!==null&&C?.score!==void 0?C.score.toFixed(1):"--"})]},_)})})]})}function CL(n){return n>=5e4?"var(--color-danger, #ef4444)":n>=5e3?"var(--color-warning, #f59e0b)":"var(--color-success, #22c55e)"}function _L({history:n}){if(n.length<2)return null;const e=200,i=32,a=2,r=i-a*2,c=n[n.length-1],d=e/n.length;return l.jsx("div",{className:"context-sparkline","data-testid":"context-sparkline",children:l.jsx("svg",{viewBox:`0 0 ${e} ${i}`,role:"img","aria-label":`Context usage trend: currently ${c.percent}%`,children:n.map((h,f)=>{const p=Math.max(1,h.percent/100*r),y=f*d,b=a+r-p;return l.jsx("rect",{x:y,y:b,width:d,height:p,fill:CL(h.tokens),opacity:.8,rx:.5},f)})})})}function EL(){const[n,e]=m.useState(null),[i,a]=m.useState(!1),[r,c]=m.useState(null),[d,h]=m.useState(null),f=m.useRef(null),p=m.useCallback(()=>{f.current&&f.current.abort();const y=new AbortController;f.current=y,a(!0),c(null),fetch("/api/health-score",{signal:y.signal}).then(b=>{if(!b.ok)throw new Error(`HTTP ${b.status}: ${b.statusText}`);return b.json()}).then(b=>{e(b),h(Date.now()),a(!1)}).catch(b=>{b.name!=="AbortError"&&(c(b instanceof Error?b:new Error(String(b))),a(!1))})},[]);return m.useEffect(()=>()=>{f.current?.abort()},[]),{data:n,isLoading:i,error:r,lastFetchedAt:d,refresh:p}}function f_(n){return n==="persona_compressed"?"Persona (Compressed)":n.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function DL(n){if(!n)return 0;switch(n){case"FULL":return 0;case"REFRESH":return 85;case"HANDOFF":return 82;case"MINIMAL":return 95;default:return 0}}function m_(){const[n,e]=m.useState(null),[i,a]=m.useState(null),[r,c]=m.useState(!1),[d,h]=m.useState(!1),[f,p]=m.useState(!1),[y,b]=m.useState(!1),[x,w]=m.useState(!1),[E,_]=m.useState(!1),[C,D]=m.useState(!1),N=EL(),k=m.useRef([]),[T,R]=m.useState(0),z=m.useCallback((U,B)=>{const $=k.current;$.push({percent:U,tokens:B,timestamp:Date.now()}),$.length>50&&$.shift(),R(ae=>ae+1)},[]),O=U=>{switch(U){case"churn":h(!0);break;case"test_gaps":break;case"todo_density":case"deprecation_debt":p(!0);break;case"complexity":b(!0);break;case"dead_code":D(!0);break;case"dependency_freshness":w(!0);break;case"agent_context_efficiency":_(!0);break}};m.useEffect(()=>{const U=window.location.protocol==="https:"?"wss:":"ws:",B=new WebSocket(`${U}//${window.location.host}/ws/context`);B.onmessage=ae=>{try{const ne=JSON.parse(ae.data);if(ne.type==="init"||ne.type==="update"){const W=ne.context;e(W),W.percent!=null&&z(W.percent,W.tokens??0)}}catch{}};const $=new WebSocket(`${U}//${window.location.host}/ws/token-stats`);return $.onmessage=ae=>{try{const ne=JSON.parse(ae.data);a(ne)}catch{}},()=>{B.close(),$.close()}},[z]);const A=n?.tier?`tier-${n.tier.toLowerCase()}`:"",G=DL(n?.tier);return l.jsxs("div",{className:"debug-panel","data-testid":"debug-panel",children:[l.jsx(SL,{score:N.data?.composite_score??null,dimensions:N.data?.dimensions??[],totalDimensions:8,onDimensionClick:O,isLoading:N.isLoading,lastFetchedAt:N.lastFetchedAt,onRefresh:N.refresh,error:N.error}),l.jsx(Rt,{className:"my-3"}),l.jsx("h4",{children:"Context Usage"}),n?l.jsxs("div",{className:"context-info",children:[n.tier&&l.jsxs("div",{className:"tier-display",children:[l.jsx($e,{variant:"outline",className:`tier-badge ${A}`,"data-testid":"tier-badge",children:n.tier}),l.jsxs("span",{className:"tier-savings","data-testid":"tier-savings",children:[G,"% savings"]})]}),n.tokenCounts&&Object.keys(n.tokenCounts).length>0&&l.jsxs("div",{className:"component-breakdown","data-testid":"component-breakdown",children:[l.jsxs("div",{className:"breakdown-header",children:[l.jsxs(Ce,{variant:"ghost",size:"sm",className:"breakdown-toggle","data-testid":"breakdown-toggle",onClick:()=>c(!r),"aria-expanded":r,children:[r?"▼":"▶"," Injected Context"]}),l.jsxs("span",{className:"total-tokens","data-testid":"total-tokens",children:[n.totalTokens?.toLocaleString()," tokens"]})]}),l.jsx("div",{className:`component-list ${r?"expanded":"collapsed"}`,"data-testid":"component-list","aria-expanded":r,children:Object.entries(n.tokenCounts).filter(([,U])=>U>0).sort(([,U],[,B])=>B-U).map(([U,B])=>l.jsxs("div",{className:"component-item","data-testid":`component-${U}`,children:[l.jsx("span",{className:"component-name",children:f_(U)}),l.jsx("span",{className:"component-tokens",children:B.toLocaleString()})]},U))})]}),l.jsx("div",{className:"context-bar",children:l.jsx("div",{className:"context-fill",style:{width:`${n.percent||0}%`}})}),l.jsx(_L,{history:k.current},T),l.jsxs("span",{className:"context-text",children:[(n.tokens??0).toLocaleString()," / ",n.baseline!=null&&n.available!=null?(n.baseline+n.available).toLocaleString():"—"," tokens (",n.percent||0,"%)"]}),n.baseline!=null&&l.jsxs("dl",{className:"context-breakdown",children:[l.jsx("dt",{children:"System Prompt"}),l.jsxs("dd",{children:[n.baseline.toLocaleString()," tokens"]}),l.jsx("dt",{children:"Conversation"}),l.jsxs("dd",{children:[n.usableTokens?.toLocaleString()??"—"," tokens"]}),l.jsx("dt",{children:"Available"}),l.jsxs("dd",{children:[n.available?.toLocaleString()??"—"," tokens"]})]})]}):l.jsx("div",{className:"placeholder",children:"No context data"}),l.jsx(Rt,{className:"my-3"}),l.jsx("h4",{children:"Token Stats"}),i?l.jsxs("dl",{className:"token-stats",children:[i.inputTokens!==void 0&&l.jsxs("div",{className:"token-stat-card","data-testid":"token-stat-input",children:[l.jsx("dt",{children:"Input"}),l.jsx("dd",{children:Number(i.inputTokens).toLocaleString()})]}),i.outputTokens!==void 0&&l.jsxs("div",{className:"token-stat-card","data-testid":"token-stat-output",children:[l.jsx("dt",{children:"Output"}),l.jsx("dd",{children:Number(i.outputTokens).toLocaleString()})]}),i.cacheReadTokens!==void 0&&l.jsxs("div",{className:"token-stat-card","data-testid":"token-stat-cache-read",children:[l.jsx("dt",{children:"Cache Read"}),l.jsx("dd",{children:Number(i.cacheReadTokens).toLocaleString()})]}),i.cacheCreationTokens!==void 0&&l.jsxs("div",{className:"token-stat-card","data-testid":"token-stat-cache-write",children:[l.jsx("dt",{children:"Cache Write"}),l.jsx("dd",{children:Number(i.cacheCreationTokens).toLocaleString()})]}),i.totalCostUsd!==void 0&&Number(i.totalCostUsd)>0&&l.jsxs("div",{className:"token-stat-card","data-testid":"token-stat-cost",children:[l.jsx("dt",{children:"Cost"}),l.jsxs("dd",{children:["$",Number(i.totalCostUsd).toFixed(4)]})]})]}):l.jsx("div",{className:"placeholder",children:"No token stats"}),l.jsx(zP,{open:d,onOpenChange:h}),l.jsx(PP,{open:f,onOpenChange:p}),l.jsx(IP,{open:y,onOpenChange:b}),l.jsx(HP,{open:x,onOpenChange:w}),l.jsx(pL,{isOpen:E,onClose:()=>_(!1)}),l.jsx(vL,{isOpen:C,onClose:()=>D(!1)})]})}function Ym(n){const e=m.useRef({value:n,previous:n});return m.useMemo(()=>(e.current.value!==n&&(e.current.previous=e.current.value,e.current.value=n),e.current.previous),[n])}var nu="Switch",[AL]=cn(nu),[NL,jL]=AL(nu),p_=m.forwardRef((n,e)=>{const{__scopeSwitch:i,name:a,checked:r,defaultChecked:c,required:d,disabled:h,value:f="on",onCheckedChange:p,form:y,...b}=n,[x,w]=m.useState(null),E=Ie(e,k=>w(k)),_=m.useRef(!1),C=x?y||!!x.closest("form"):!0,[D,N]=_n({prop:r,defaultProp:c??!1,onChange:p,caller:nu});return l.jsxs(NL,{scope:i,checked:D,disabled:h,children:[l.jsx(je.button,{type:"button",role:"switch","aria-checked":D,"aria-required":d,"data-state":b_(D),"data-disabled":h?"":void 0,disabled:h,value:f,...b,ref:E,onClick:we(n.onClick,k=>{N(T=>!T),C&&(_.current=k.isPropagationStopped(),_.current||k.stopPropagation())})}),C&&l.jsx(y_,{control:x,bubbles:!_.current,name:a,value:f,checked:D,required:d,disabled:h,form:y,style:{transform:"translateX(-100%)"}})]})});p_.displayName=nu;var g_="SwitchThumb",v_=m.forwardRef((n,e)=>{const{__scopeSwitch:i,...a}=n,r=jL(g_,i);return l.jsx(je.span,{"data-state":b_(r.checked),"data-disabled":r.disabled?"":void 0,...a,ref:e})});v_.displayName=g_;var TL="SwitchBubbleInput",y_=m.forwardRef(({__scopeSwitch:n,control:e,checked:i,bubbles:a=!0,...r},c)=>{const d=m.useRef(null),h=Ie(d,c),f=Ym(i),p=Yf(e);return m.useEffect(()=>{const y=d.current;if(!y)return;const b=window.HTMLInputElement.prototype,w=Object.getOwnPropertyDescriptor(b,"checked").set;if(f!==i&&w){const E=new Event("click",{bubbles:a});w.call(y,i),y.dispatchEvent(E)}},[f,i,a]),l.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:i,...r,tabIndex:-1,ref:h,style:{...r.style,...p,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});y_.displayName=TL;function b_(n){return n?"checked":"unchecked"}var x_=p_,kL=v_;const kf=m.forwardRef(({className:n,...e},i)=>l.jsx(x_,{className:ye("cyclist-switch peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",n),...e,ref:i,children:l.jsx(kL,{className:ye("cyclist-switch-thumb pointer-events-none block h-4 w-4 rounded-full shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));kf.displayName=x_.displayName;var iu="Popover",[w_]=cn(iu,[Wa]),mr=Wa(),[RL,as]=w_(iu),S_=n=>{const{__scopePopover:e,children:i,open:a,defaultOpen:r,onOpenChange:c,modal:d=!1}=n,h=mr(e),f=m.useRef(null),[p,y]=m.useState(!1),[b,x]=_n({prop:a,defaultProp:r??!1,onChange:c,caller:iu});return l.jsx(Zf,{...h,children:l.jsx(RL,{scope:e,contentId:Mt(),triggerRef:f,open:b,onOpenChange:x,onOpenToggle:m.useCallback(()=>x(w=>!w),[x]),hasCustomAnchor:p,onCustomAnchorAdd:m.useCallback(()=>y(!0),[]),onCustomAnchorRemove:m.useCallback(()=>y(!1),[]),modal:d,children:i})})};S_.displayName=iu;var C_="PopoverAnchor",OL=m.forwardRef((n,e)=>{const{__scopePopover:i,...a}=n,r=as(C_,i),c=mr(i),{onCustomAnchorAdd:d,onCustomAnchorRemove:h}=r;return m.useEffect(()=>(d(),()=>h()),[d,h]),l.jsx(kc,{...c,...a,ref:e})});OL.displayName=C_;var __="PopoverTrigger",E_=m.forwardRef((n,e)=>{const{__scopePopover:i,...a}=n,r=as(__,i),c=mr(i),d=Ie(e,r.triggerRef),h=l.jsx(je.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.contentId,"data-state":T_(r.open),...a,ref:d,onClick:we(n.onClick,r.onOpenToggle)});return r.hasCustomAnchor?h:l.jsx(kc,{asChild:!0,...c,children:h})});E_.displayName=__;var Xm="PopoverPortal",[zL,ML]=w_(Xm,{forceMount:void 0}),D_=n=>{const{__scopePopover:e,forceMount:i,children:a,container:r}=n,c=as(Xm,e);return l.jsx(zL,{scope:e,forceMount:i,children:l.jsx(qt,{present:i||c.open,children:l.jsx(rr,{asChild:!0,container:r,children:a})})})};D_.displayName=Xm;var Ha="PopoverContent",A_=m.forwardRef((n,e)=>{const i=ML(Ha,n.__scopePopover),{forceMount:a=i.forceMount,...r}=n,c=as(Ha,n.__scopePopover);return l.jsx(qt,{present:a||c.open,children:c.modal?l.jsx(LL,{...r,ref:e}):l.jsx(IL,{...r,ref:e})})});A_.displayName=Ha;var PL=Pa("PopoverContent.RemoveScroll"),LL=m.forwardRef((n,e)=>{const i=as(Ha,n.__scopePopover),a=m.useRef(null),r=Ie(e,a),c=m.useRef(!1);return m.useEffect(()=>{const d=a.current;if(d)return mm(d)},[]),l.jsx(Vc,{as:PL,allowPinchZoom:!0,children:l.jsx(N_,{...n,ref:r,trapFocus:i.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:we(n.onCloseAutoFocus,d=>{d.preventDefault(),c.current||i.triggerRef.current?.focus()}),onPointerDownOutside:we(n.onPointerDownOutside,d=>{const h=d.detail.originalEvent,f=h.button===0&&h.ctrlKey===!0,p=h.button===2||f;c.current=p},{checkForDefaultPrevented:!1}),onFocusOutside:we(n.onFocusOutside,d=>d.preventDefault(),{checkForDefaultPrevented:!1})})})}),IL=m.forwardRef((n,e)=>{const i=as(Ha,n.__scopePopover),a=m.useRef(!1),r=m.useRef(!1);return l.jsx(N_,{...n,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:c=>{n.onCloseAutoFocus?.(c),c.defaultPrevented||(a.current||i.triggerRef.current?.focus(),c.preventDefault()),a.current=!1,r.current=!1},onInteractOutside:c=>{n.onInteractOutside?.(c),c.defaultPrevented||(a.current=!0,c.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const d=c.target;i.triggerRef.current?.contains(d)&&c.preventDefault(),c.detail.originalEvent.type==="focusin"&&r.current&&c.preventDefault()}})}),N_=m.forwardRef((n,e)=>{const{__scopePopover:i,trapFocus:a,onOpenAutoFocus:r,onCloseAutoFocus:c,disableOutsidePointerEvents:d,onEscapeKeyDown:h,onPointerDownOutside:f,onFocusOutside:p,onInteractOutside:y,...b}=n,x=as(Ha,i),w=mr(i);return fm(),l.jsx(Bc,{asChild:!0,loop:!0,trapped:a,onMountAutoFocus:r,onUnmountAutoFocus:c,children:l.jsx(ar,{asChild:!0,disableOutsidePointerEvents:d,onInteractOutside:y,onEscapeKeyDown:h,onPointerDownOutside:f,onFocusOutside:p,onDismiss:()=>x.onOpenChange(!1),children:l.jsx(Kf,{"data-state":T_(x.open),role:"dialog",id:x.contentId,...w,...b,ref:e,style:{...b.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),j_="PopoverClose",GL=m.forwardRef((n,e)=>{const{__scopePopover:i,...a}=n,r=as(j_,i);return l.jsx(je.button,{type:"button",...a,ref:e,onClick:we(n.onClick,()=>r.onOpenChange(!1))})});GL.displayName=j_;var BL="PopoverArrow",HL=m.forwardRef((n,e)=>{const{__scopePopover:i,...a}=n,r=mr(i);return l.jsx(Jf,{...r,...a,ref:e})});HL.displayName=BL;function T_(n){return n?"open":"closed"}var VL=S_,FL=E_,UL=D_,k_=A_;const $L=VL,WL=FL,R_=m.forwardRef(({className:n,align:e="center",sideOffset:i=4,...a},r)=>l.jsx(UL,{children:l.jsx(k_,{ref:r,align:e,sideOffset:i,className:ye("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-popover-content-transform-origin]",n),...a})}));R_.displayName=k_.displayName;function qL(){const n=Fz(),e=[],i=[];for(const a of n){const r=Sn(a);r&&(r.variant==="light"?i.push(a):e.push(a))}return e.sort((a,r)=>(Sn(a)?.name||"").localeCompare(Sn(r)?.name||"")),i.sort((a,r)=>(Sn(a)?.name||"").localeCompare(Sn(r)?.name||"")),{dark:e,light:i}}function qx({presetId:n}){const e=Sn(n);return e?l.jsxs("div",{className:"preset-swatches",children:[l.jsx("span",{className:"preset-swatch",style:{backgroundColor:e.colors.bgPrimary},title:"Background"}),l.jsx("span",{className:"preset-swatch",style:{backgroundColor:e.colors.bgSecondary},title:"Surface"}),l.jsx("span",{className:"preset-swatch",style:{backgroundColor:e.colors.textPrimary},title:"Text"}),l.jsx("span",{className:"preset-swatch",style:{backgroundColor:e.colors.accent},title:"Accent"})]}):null}function YL({currentPreset:n,onSelect:e,className:i=""}){const[a,r]=m.useState(!1),c=m.useMemo(()=>qL(),[]),d=Sn(n),h=f=>{e?.(f),r(!1)};return l.jsxs($L,{open:a,onOpenChange:r,children:[l.jsx(WL,{asChild:!0,children:l.jsxs(Ce,{variant:"outline",className:ye("theme-palette-button",i),"aria-label":`Select theme, current: ${d?.name||n}`,children:[l.jsxs("span",{className:"theme-palette-current",children:[d&&l.jsx("span",{className:"preset-swatch",style:{backgroundColor:d.colors.bgPrimary}}),l.jsx("span",{className:"theme-palette-name",children:d?.name||n})]}),l.jsx(YO,{className:"theme-palette-chevron"})]})}),l.jsx(R_,{className:"theme-palette-popover p-0",align:"start",children:l.jsxs(Em,{children:[l.jsx(Dm,{placeholder:"Search themes..."}),l.jsxs(Am,{children:[l.jsx(Nm,{children:"No theme found."}),l.jsx(nr,{heading:`Dark (${c.dark.length})`,children:c.dark.map(f=>{const p=Sn(f);if(!p)return null;const y=f===n;return l.jsxs(ir,{value:p.name,onSelect:()=>h(f),"data-preset-id":f,children:[l.jsx(qx,{presetId:f}),l.jsx("span",{className:"preset-name",children:p.name}),l.jsx(Ga,{className:ye("preset-check-icon ml-auto",y?"opacity-100":"opacity-0")})]},f)})}),l.jsx(nr,{heading:`Light (${c.light.length})`,children:c.light.map(f=>{const p=Sn(f);if(!p)return null;const y=f===n;return l.jsxs(ir,{value:p.name,onSelect:()=>h(f),"data-preset-id":f,children:[l.jsx(qx,{presetId:f}),l.jsx("span",{className:"preset-name",children:p.name}),l.jsx(Ga,{className:ye("preset-check-icon ml-auto",y?"opacity-100":"opacity-0")})]},f)})})]})]})})]})}var XL=[" ","Enter","ArrowUp","ArrowDown"],QL=[" ","Enter"],Ps="Select",[su,au,ZL]=OS(Ps),[qa]=cn(Ps,[ZL,Wa]),ou=Wa(),[KL,os]=qa(Ps),[JL,eI]=qa(Ps),O_=n=>{const{__scopeSelect:e,children:i,open:a,defaultOpen:r,onOpenChange:c,value:d,defaultValue:h,onValueChange:f,dir:p,name:y,autoComplete:b,disabled:x,required:w,form:E}=n,_=ou(e),[C,D]=m.useState(null),[N,k]=m.useState(null),[T,R]=m.useState(!1),z=Kc(p),[O,A]=_n({prop:a,defaultProp:r??!1,onChange:c,caller:Ps}),[G,U]=_n({prop:d,defaultProp:h,onChange:f,caller:Ps}),B=m.useRef(null),$=C?E||!!C.closest("form"):!0,[ae,ne]=m.useState(new Set),W=Array.from(ae).map(M=>M.props.value).join(";");return l.jsx(Zf,{..._,children:l.jsxs(KL,{required:w,scope:e,trigger:C,onTriggerChange:D,valueNode:N,onValueNodeChange:k,valueNodeHasChildren:T,onValueNodeHasChildrenChange:R,contentId:Mt(),value:G,onValueChange:U,open:O,onOpenChange:A,dir:z,triggerPointerDownPosRef:B,disabled:x,children:[l.jsx(su.Provider,{scope:e,children:l.jsx(JL,{scope:n.__scopeSelect,onNativeOptionAdd:m.useCallback(M=>{ne(K=>new Set(K).add(M))},[]),onNativeOptionRemove:m.useCallback(M=>{ne(K=>{const q=new Set(K);return q.delete(M),q})},[]),children:i})}),$?l.jsxs(sE,{"aria-hidden":!0,required:w,tabIndex:-1,name:y,autoComplete:b,value:G,onChange:M=>U(M.target.value),disabled:x,form:E,children:[G===void 0?l.jsx("option",{value:""}):null,Array.from(ae)]},W):null]})})};O_.displayName=Ps;var z_="SelectTrigger",M_=m.forwardRef((n,e)=>{const{__scopeSelect:i,disabled:a=!1,...r}=n,c=ou(i),d=os(z_,i),h=d.disabled||a,f=Ie(e,d.onTriggerChange),p=au(i),y=m.useRef("touch"),[b,x,w]=oE(_=>{const C=p().filter(k=>!k.disabled),D=C.find(k=>k.value===d.value),N=rE(C,_,D);N!==void 0&&d.onValueChange(N.value)}),E=_=>{h||(d.onOpenChange(!0),w()),_&&(d.triggerPointerDownPosRef.current={x:Math.round(_.pageX),y:Math.round(_.pageY)})};return l.jsx(kc,{asChild:!0,...c,children:l.jsx(je.button,{type:"button",role:"combobox","aria-controls":d.contentId,"aria-expanded":d.open,"aria-required":d.required,"aria-autocomplete":"none",dir:d.dir,"data-state":d.open?"open":"closed",disabled:h,"data-disabled":h?"":void 0,"data-placeholder":aE(d.value)?"":void 0,...r,ref:f,onClick:we(r.onClick,_=>{_.currentTarget.focus(),y.current!=="mouse"&&E(_)}),onPointerDown:we(r.onPointerDown,_=>{y.current=_.pointerType;const C=_.target;C.hasPointerCapture(_.pointerId)&&C.releasePointerCapture(_.pointerId),_.button===0&&_.ctrlKey===!1&&_.pointerType==="mouse"&&(E(_),_.preventDefault())}),onKeyDown:we(r.onKeyDown,_=>{const C=b.current!=="";!(_.ctrlKey||_.altKey||_.metaKey)&&_.key.length===1&&x(_.key),!(C&&_.key===" ")&&XL.includes(_.key)&&(E(),_.preventDefault())})})})});M_.displayName=z_;var P_="SelectValue",L_=m.forwardRef((n,e)=>{const{__scopeSelect:i,className:a,style:r,children:c,placeholder:d="",...h}=n,f=os(P_,i),{onValueNodeHasChildrenChange:p}=f,y=c!==void 0,b=Ie(e,f.onValueNodeChange);return Dt(()=>{p(y)},[p,y]),l.jsx(je.span,{...h,ref:b,style:{pointerEvents:"none"},children:aE(f.value)?l.jsx(l.Fragment,{children:d}):c})});L_.displayName=P_;var tI="SelectIcon",I_=m.forwardRef((n,e)=>{const{__scopeSelect:i,children:a,...r}=n;return l.jsx(je.span,{"aria-hidden":!0,...r,ref:e,children:a||"▼"})});I_.displayName=tI;var nI="SelectPortal",G_=n=>l.jsx(rr,{asChild:!0,...n});G_.displayName=nI;var Ls="SelectContent",B_=m.forwardRef((n,e)=>{const i=os(Ls,n.__scopeSelect),[a,r]=m.useState();if(Dt(()=>{r(new DocumentFragment)},[]),!i.open){const c=a;return c?sr.createPortal(l.jsx(H_,{scope:n.__scopeSelect,children:l.jsx(su.Slot,{scope:n.__scopeSelect,children:l.jsx("div",{children:n.children})})}),c):null}return l.jsx(V_,{...n,ref:e})});B_.displayName=Ls;var Rn=10,[H_,rs]=qa(Ls),iI="SelectContentImpl",sI=Pa("SelectContent.RemoveScroll"),V_=m.forwardRef((n,e)=>{const{__scopeSelect:i,position:a="item-aligned",onCloseAutoFocus:r,onEscapeKeyDown:c,onPointerDownOutside:d,side:h,sideOffset:f,align:p,alignOffset:y,arrowPadding:b,collisionBoundary:x,collisionPadding:w,sticky:E,hideWhenDetached:_,avoidCollisions:C,...D}=n,N=os(Ls,i),[k,T]=m.useState(null),[R,z]=m.useState(null),O=Ie(e,X=>T(X)),[A,G]=m.useState(null),[U,B]=m.useState(null),$=au(i),[ae,ne]=m.useState(!1),W=m.useRef(!1);m.useEffect(()=>{if(k)return mm(k)},[k]),fm();const M=m.useCallback(X=>{const[ce,...de]=$().map(Ne=>Ne.ref.current),[De]=de.slice(-1),Ge=document.activeElement;for(const Ne of X)if(Ne===Ge||(Ne?.scrollIntoView({block:"nearest"}),Ne===ce&&R&&(R.scrollTop=0),Ne===De&&R&&(R.scrollTop=R.scrollHeight),Ne?.focus(),document.activeElement!==Ge))return},[$,R]),K=m.useCallback(()=>M([A,k]),[M,A,k]);m.useEffect(()=>{ae&&K()},[ae,K]);const{onOpenChange:q,triggerPointerDownPosRef:he}=N;m.useEffect(()=>{if(k){let X={x:0,y:0};const ce=De=>{X={x:Math.abs(Math.round(De.pageX)-(he.current?.x??0)),y:Math.abs(Math.round(De.pageY)-(he.current?.y??0))}},de=De=>{X.x<=10&&X.y<=10?De.preventDefault():k.contains(De.target)||q(!1),document.removeEventListener("pointermove",ce),he.current=null};return he.current!==null&&(document.addEventListener("pointermove",ce),document.addEventListener("pointerup",de,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",ce),document.removeEventListener("pointerup",de,{capture:!0})}}},[k,q,he]),m.useEffect(()=>{const X=()=>q(!1);return window.addEventListener("blur",X),window.addEventListener("resize",X),()=>{window.removeEventListener("blur",X),window.removeEventListener("resize",X)}},[q]);const[Se,I]=oE(X=>{const ce=$().filter(Ge=>!Ge.disabled),de=ce.find(Ge=>Ge.ref.current===document.activeElement),De=rE(ce,X,de);De&&setTimeout(()=>De.ref.current.focus())}),L=m.useCallback((X,ce,de)=>{const De=!W.current&&!de;(N.value!==void 0&&N.value===ce||De)&&(G(X),De&&(W.current=!0))},[N.value]),ee=m.useCallback(()=>k?.focus(),[k]),V=m.useCallback((X,ce,de)=>{const De=!W.current&&!de;(N.value!==void 0&&N.value===ce||De)&&B(X)},[N.value]),Y=a==="popper"?Rf:F_,le=Y===Rf?{side:h,sideOffset:f,align:p,alignOffset:y,arrowPadding:b,collisionBoundary:x,collisionPadding:w,sticky:E,hideWhenDetached:_,avoidCollisions:C}:{};return l.jsx(H_,{scope:i,content:k,viewport:R,onViewportChange:z,itemRefCallback:L,selectedItem:A,onItemLeave:ee,itemTextRefCallback:V,focusSelectedItem:K,selectedItemText:U,position:a,isPositioned:ae,searchRef:Se,children:l.jsx(Vc,{as:sI,allowPinchZoom:!0,children:l.jsx(Bc,{asChild:!0,trapped:N.open,onMountAutoFocus:X=>{X.preventDefault()},onUnmountAutoFocus:we(r,X=>{N.trigger?.focus({preventScroll:!0}),X.preventDefault()}),children:l.jsx(ar,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:X=>X.preventDefault(),onDismiss:()=>N.onOpenChange(!1),children:l.jsx(Y,{role:"listbox",id:N.contentId,"data-state":N.open?"open":"closed",dir:N.dir,onContextMenu:X=>X.preventDefault(),...D,...le,onPlaced:()=>ne(!0),ref:O,style:{display:"flex",flexDirection:"column",outline:"none",...D.style},onKeyDown:we(D.onKeyDown,X=>{const ce=X.ctrlKey||X.altKey||X.metaKey;if(X.key==="Tab"&&X.preventDefault(),!ce&&X.key.length===1&&I(X.key),["ArrowUp","ArrowDown","Home","End"].includes(X.key)){let De=$().filter(Ge=>!Ge.disabled).map(Ge=>Ge.ref.current);if(["ArrowUp","End"].includes(X.key)&&(De=De.slice().reverse()),["ArrowUp","ArrowDown"].includes(X.key)){const Ge=X.target,Ne=De.indexOf(Ge);De=De.slice(Ne+1)}setTimeout(()=>M(De)),X.preventDefault()}})})})})})})});V_.displayName=iI;var aI="SelectItemAlignedPosition",F_=m.forwardRef((n,e)=>{const{__scopeSelect:i,onPlaced:a,...r}=n,c=os(Ls,i),d=rs(Ls,i),[h,f]=m.useState(null),[p,y]=m.useState(null),b=Ie(e,O=>y(O)),x=au(i),w=m.useRef(!1),E=m.useRef(!0),{viewport:_,selectedItem:C,selectedItemText:D,focusSelectedItem:N}=d,k=m.useCallback(()=>{if(c.trigger&&c.valueNode&&h&&p&&_&&C&&D){const O=c.trigger.getBoundingClientRect(),A=p.getBoundingClientRect(),G=c.valueNode.getBoundingClientRect(),U=D.getBoundingClientRect();if(c.dir!=="rtl"){const Ge=U.left-A.left,Ne=G.left-Ge,dt=O.left-Ne,rt=O.width+dt,An=Math.max(rt,A.width),ei=window.innerWidth-Rn,Ya=Tf(Ne,[Rn,Math.max(Rn,ei-An)]);h.style.minWidth=rt+"px",h.style.left=Ya+"px"}else{const Ge=A.right-U.right,Ne=window.innerWidth-G.right-Ge,dt=window.innerWidth-O.right-Ne,rt=O.width+dt,An=Math.max(rt,A.width),ei=window.innerWidth-Rn,Ya=Tf(Ne,[Rn,Math.max(Rn,ei-An)]);h.style.minWidth=rt+"px",h.style.right=Ya+"px"}const B=x(),$=window.innerHeight-Rn*2,ae=_.scrollHeight,ne=window.getComputedStyle(p),W=parseInt(ne.borderTopWidth,10),M=parseInt(ne.paddingTop,10),K=parseInt(ne.borderBottomWidth,10),q=parseInt(ne.paddingBottom,10),he=W+M+ae+q+K,Se=Math.min(C.offsetHeight*5,he),I=window.getComputedStyle(_),L=parseInt(I.paddingTop,10),ee=parseInt(I.paddingBottom,10),V=O.top+O.height/2-Rn,Y=$-V,le=C.offsetHeight/2,X=C.offsetTop+le,ce=W+M+X,de=he-ce;if(ce<=V){const Ge=B.length>0&&C===B[B.length-1].ref.current;h.style.bottom="0px";const Ne=p.clientHeight-_.offsetTop-_.offsetHeight,dt=Math.max(Y,le+(Ge?ee:0)+Ne+K),rt=ce+dt;h.style.height=rt+"px"}else{const Ge=B.length>0&&C===B[0].ref.current;h.style.top="0px";const dt=Math.max(V,W+_.offsetTop+(Ge?L:0)+le)+de;h.style.height=dt+"px",_.scrollTop=ce-V+_.offsetTop}h.style.margin=`${Rn}px 0`,h.style.minHeight=Se+"px",h.style.maxHeight=$+"px",a?.(),requestAnimationFrame(()=>w.current=!0)}},[x,c.trigger,c.valueNode,h,p,_,C,D,c.dir,a]);Dt(()=>k(),[k]);const[T,R]=m.useState();Dt(()=>{p&&R(window.getComputedStyle(p).zIndex)},[p]);const z=m.useCallback(O=>{O&&E.current===!0&&(k(),N?.(),E.current=!1)},[k,N]);return l.jsx(rI,{scope:i,contentWrapper:h,shouldExpandOnScrollRef:w,onScrollButtonChange:z,children:l.jsx("div",{ref:f,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:T},children:l.jsx(je.div,{...r,ref:b,style:{boxSizing:"border-box",maxHeight:"100%",...r.style}})})})});F_.displayName=aI;var oI="SelectPopperPosition",Rf=m.forwardRef((n,e)=>{const{__scopeSelect:i,align:a="start",collisionPadding:r=Rn,...c}=n,d=ou(i);return l.jsx(Kf,{...d,...c,ref:e,align:a,collisionPadding:r,style:{boxSizing:"border-box",...c.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});Rf.displayName=oI;var[rI,Qm]=qa(Ls,{}),Of="SelectViewport",U_=m.forwardRef((n,e)=>{const{__scopeSelect:i,nonce:a,...r}=n,c=rs(Of,i),d=Qm(Of,i),h=Ie(e,c.onViewportChange),f=m.useRef(0);return l.jsxs(l.Fragment,{children:[l.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:a}),l.jsx(su.Slot,{scope:i,children:l.jsx(je.div,{"data-radix-select-viewport":"",role:"presentation",...r,ref:h,style:{position:"relative",flex:1,overflow:"hidden auto",...r.style},onScroll:we(r.onScroll,p=>{const y=p.currentTarget,{contentWrapper:b,shouldExpandOnScrollRef:x}=d;if(x?.current&&b){const w=Math.abs(f.current-y.scrollTop);if(w>0){const E=window.innerHeight-Rn*2,_=parseFloat(b.style.minHeight),C=parseFloat(b.style.height),D=Math.max(_,C);if(D<E){const N=D+w,k=Math.min(E,N),T=N-k;b.style.height=k+"px",b.style.bottom==="0px"&&(y.scrollTop=T>0?T:0,b.style.justifyContent="flex-end")}}}f.current=y.scrollTop})})})]})});U_.displayName=Of;var $_="SelectGroup",[lI,cI]=qa($_),W_=m.forwardRef((n,e)=>{const{__scopeSelect:i,...a}=n,r=Mt();return l.jsx(lI,{scope:i,id:r,children:l.jsx(je.div,{role:"group","aria-labelledby":r,...a,ref:e})})});W_.displayName=$_;var q_="SelectLabel",Y_=m.forwardRef((n,e)=>{const{__scopeSelect:i,...a}=n,r=cI(q_,i);return l.jsx(je.div,{id:r.id,...a,ref:e})});Y_.displayName=q_;var Ec="SelectItem",[uI,X_]=qa(Ec),Q_=m.forwardRef((n,e)=>{const{__scopeSelect:i,value:a,disabled:r=!1,textValue:c,...d}=n,h=os(Ec,i),f=rs(Ec,i),p=h.value===a,[y,b]=m.useState(c??""),[x,w]=m.useState(!1),E=Ie(e,N=>f.itemRefCallback?.(N,a,r)),_=Mt(),C=m.useRef("touch"),D=()=>{r||(h.onValueChange(a),h.onOpenChange(!1))};if(a==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return l.jsx(uI,{scope:i,value:a,disabled:r,textId:_,isSelected:p,onItemTextChange:m.useCallback(N=>{b(k=>k||(N?.textContent??"").trim())},[]),children:l.jsx(su.ItemSlot,{scope:i,value:a,disabled:r,textValue:y,children:l.jsx(je.div,{role:"option","aria-labelledby":_,"data-highlighted":x?"":void 0,"aria-selected":p&&x,"data-state":p?"checked":"unchecked","aria-disabled":r||void 0,"data-disabled":r?"":void 0,tabIndex:r?void 0:-1,...d,ref:E,onFocus:we(d.onFocus,()=>w(!0)),onBlur:we(d.onBlur,()=>w(!1)),onClick:we(d.onClick,()=>{C.current!=="mouse"&&D()}),onPointerUp:we(d.onPointerUp,()=>{C.current==="mouse"&&D()}),onPointerDown:we(d.onPointerDown,N=>{C.current=N.pointerType}),onPointerMove:we(d.onPointerMove,N=>{C.current=N.pointerType,r?f.onItemLeave?.():C.current==="mouse"&&N.currentTarget.focus({preventScroll:!0})}),onPointerLeave:we(d.onPointerLeave,N=>{N.currentTarget===document.activeElement&&f.onItemLeave?.()}),onKeyDown:we(d.onKeyDown,N=>{f.searchRef?.current!==""&&N.key===" "||(QL.includes(N.key)&&D(),N.key===" "&&N.preventDefault())})})})})});Q_.displayName=Ec;var Yo="SelectItemText",Z_=m.forwardRef((n,e)=>{const{__scopeSelect:i,className:a,style:r,...c}=n,d=os(Yo,i),h=rs(Yo,i),f=X_(Yo,i),p=eI(Yo,i),[y,b]=m.useState(null),x=Ie(e,D=>b(D),f.onItemTextChange,D=>h.itemTextRefCallback?.(D,f.value,f.disabled)),w=y?.textContent,E=m.useMemo(()=>l.jsx("option",{value:f.value,disabled:f.disabled,children:w},f.value),[f.disabled,f.value,w]),{onNativeOptionAdd:_,onNativeOptionRemove:C}=p;return Dt(()=>(_(E),()=>C(E)),[_,C,E]),l.jsxs(l.Fragment,{children:[l.jsx(je.span,{id:f.textId,...c,ref:x}),f.isSelected&&d.valueNode&&!d.valueNodeHasChildren?sr.createPortal(c.children,d.valueNode):null]})});Z_.displayName=Yo;var K_="SelectItemIndicator",J_=m.forwardRef((n,e)=>{const{__scopeSelect:i,...a}=n;return X_(K_,i).isSelected?l.jsx(je.span,{"aria-hidden":!0,...a,ref:e}):null});J_.displayName=K_;var zf="SelectScrollUpButton",eE=m.forwardRef((n,e)=>{const i=rs(zf,n.__scopeSelect),a=Qm(zf,n.__scopeSelect),[r,c]=m.useState(!1),d=Ie(e,a.onScrollButtonChange);return Dt(()=>{if(i.viewport&&i.isPositioned){let h=function(){const p=f.scrollTop>0;c(p)};const f=i.viewport;return h(),f.addEventListener("scroll",h),()=>f.removeEventListener("scroll",h)}},[i.viewport,i.isPositioned]),r?l.jsx(nE,{...n,ref:d,onAutoScroll:()=>{const{viewport:h,selectedItem:f}=i;h&&f&&(h.scrollTop=h.scrollTop-f.offsetHeight)}}):null});eE.displayName=zf;var Mf="SelectScrollDownButton",tE=m.forwardRef((n,e)=>{const i=rs(Mf,n.__scopeSelect),a=Qm(Mf,n.__scopeSelect),[r,c]=m.useState(!1),d=Ie(e,a.onScrollButtonChange);return Dt(()=>{if(i.viewport&&i.isPositioned){let h=function(){const p=f.scrollHeight-f.clientHeight,y=Math.ceil(f.scrollTop)<p;c(y)};const f=i.viewport;return h(),f.addEventListener("scroll",h),()=>f.removeEventListener("scroll",h)}},[i.viewport,i.isPositioned]),r?l.jsx(nE,{...n,ref:d,onAutoScroll:()=>{const{viewport:h,selectedItem:f}=i;h&&f&&(h.scrollTop=h.scrollTop+f.offsetHeight)}}):null});tE.displayName=Mf;var nE=m.forwardRef((n,e)=>{const{__scopeSelect:i,onAutoScroll:a,...r}=n,c=rs("SelectScrollButton",i),d=m.useRef(null),h=au(i),f=m.useCallback(()=>{d.current!==null&&(window.clearInterval(d.current),d.current=null)},[]);return m.useEffect(()=>()=>f(),[f]),Dt(()=>{h().find(y=>y.ref.current===document.activeElement)?.ref.current?.scrollIntoView({block:"nearest"})},[h]),l.jsx(je.div,{"aria-hidden":!0,...r,ref:e,style:{flexShrink:0,...r.style},onPointerDown:we(r.onPointerDown,()=>{d.current===null&&(d.current=window.setInterval(a,50))}),onPointerMove:we(r.onPointerMove,()=>{c.onItemLeave?.(),d.current===null&&(d.current=window.setInterval(a,50))}),onPointerLeave:we(r.onPointerLeave,()=>{f()})})}),dI="SelectSeparator",iE=m.forwardRef((n,e)=>{const{__scopeSelect:i,...a}=n;return l.jsx(je.div,{"aria-hidden":!0,...a,ref:e})});iE.displayName=dI;var Pf="SelectArrow",hI=m.forwardRef((n,e)=>{const{__scopeSelect:i,...a}=n,r=ou(i),c=os(Pf,i),d=rs(Pf,i);return c.open&&d.position==="popper"?l.jsx(Jf,{...r,...a,ref:e}):null});hI.displayName=Pf;var fI="SelectBubbleInput",sE=m.forwardRef(({__scopeSelect:n,value:e,...i},a)=>{const r=m.useRef(null),c=Ie(a,r),d=Ym(e);return m.useEffect(()=>{const h=r.current;if(!h)return;const f=window.HTMLSelectElement.prototype,y=Object.getOwnPropertyDescriptor(f,"value").set;if(d!==e&&y){const b=new Event("change",{bubbles:!0});y.call(h,e),h.dispatchEvent(b)}},[d,e]),l.jsx(je.select,{...i,style:{...Yw,...i.style},ref:c,defaultValue:e})});sE.displayName=fI;function aE(n){return n===""||n===void 0}function oE(n){const e=Gt(n),i=m.useRef(""),a=m.useRef(0),r=m.useCallback(d=>{const h=i.current+d;e(h),(function f(p){i.current=p,window.clearTimeout(a.current),p!==""&&(a.current=window.setTimeout(()=>f(""),1e3))})(h)},[e]),c=m.useCallback(()=>{i.current="",window.clearTimeout(a.current)},[]);return m.useEffect(()=>()=>window.clearTimeout(a.current),[]),[i,r,c]}function rE(n,e,i){const r=e.length>1&&Array.from(e).every(p=>p===e[0])?e[0]:e,c=i?n.indexOf(i):-1;let d=mI(n,Math.max(c,0));r.length===1&&(d=d.filter(p=>p!==i));const f=d.find(p=>p.textValue.toLowerCase().startsWith(r.toLowerCase()));return f!==i?f:void 0}function mI(n,e){return n.map((i,a)=>n[(e+a)%n.length])}var pI=O_,lE=M_,gI=L_,vI=I_,yI=G_,cE=B_,bI=U_,xI=W_,uE=Y_,dE=Q_,wI=Z_,SI=J_,hE=eE,fE=tE,mE=iE;const CI=pI,Jh=xI,_I=gI,pE=m.forwardRef(({className:n,children:e,...i},a)=>l.jsxs(lE,{ref:a,className:ye("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background data-[placeholder]:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",n),...i,children:[e,l.jsx(vI,{asChild:!0,children:l.jsx(cS,{className:"h-4 w-4 opacity-50"})})]}));pE.displayName=lE.displayName;const gE=m.forwardRef(({className:n,...e},i)=>l.jsx(hE,{ref:i,className:ye("flex cursor-default items-center justify-center py-1",n),...e,children:l.jsx(WO,{className:"h-4 w-4"})}));gE.displayName=hE.displayName;const vE=m.forwardRef(({className:n,...e},i)=>l.jsx(fE,{ref:i,className:ye("flex cursor-default items-center justify-center py-1",n),...e,children:l.jsx(cS,{className:"h-4 w-4"})}));vE.displayName=fE.displayName;const yE=m.forwardRef(({className:n,children:e,position:i="popper",...a},r)=>l.jsx(yI,{children:l.jsxs(cE,{ref:r,className:ye("relative z-50 max-h-[--radix-select-content-available-height] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-select-content-transform-origin]",i==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",n),position:i,...a,children:[l.jsx(gE,{}),l.jsx(bI,{className:ye("p-1",i==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:e}),l.jsx(vE,{})]})}));yE.displayName=cE.displayName;const sc=m.forwardRef(({className:n,...e},i)=>l.jsx(uE,{ref:i,className:ye("px-2 py-1.5 text-sm font-semibold",n),...e}));sc.displayName=uE.displayName;const ac=m.forwardRef(({className:n,children:e,...i},a)=>l.jsxs(dE,{ref:a,className:ye("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",n),...i,children:[l.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:l.jsx(SI,{children:l.jsx(Ga,{className:"h-4 w-4"})})}),l.jsx(wI,{children:e})]}));ac.displayName=dE.displayName;const EI=m.forwardRef(({className:n,...e},i)=>l.jsx(mE,{ref:i,className:ye("-mx-1 my-1 h-px bg-muted",n),...e}));EI.displayName=mE.displayName;function DI(n,e){const i=n.getUint16(4);for(let a=0;a<i;a++){const r=12+a*16;if(String.fromCharCode(n.getUint8(r),n.getUint8(r+1),n.getUint8(r+2),n.getUint8(r+3))===e)return{offset:n.getUint32(r+8),length:n.getUint32(r+12)}}return null}async function AI(n){try{const i=await(await n.blob()).arrayBuffer(),a=new DataView(i),r=DI(a,"post");return r?a.getUint32(r.offset+12)!==0:!1}catch{return!1}}const Zm="cyclist-system-fonts";function NI(){try{const n=localStorage.getItem(Zm);if(!n)return null;const e=JSON.parse(n);return e.fonts?.length>0?e.fonts:null}catch{return null}}function jI(n,e){try{const i={fonts:n,count:e};localStorage.setItem(Zm,JSON.stringify(i))}catch{}}let Xl=null;async function TI(){return Xl||(Xl=(async()=>{if(!("queryLocalFonts"in window))return[];try{const n=await window.queryLocalFonts(),e=new Map;for(const h of n)e.has(h.family)||e.set(h.family,h);const i=e.size,a=NI();if(a&&a.length>0)try{const h=localStorage.getItem(Zm);if(h&&JSON.parse(h).count===i)return a}catch{}const r=Array.from(e.entries()),c=await Promise.all(r.map(([,h])=>AI(h))),d=r.map(([h],f)=>({family:h,isMonospace:c[f]}));return d.sort((h,f)=>h.family.localeCompare(f.family)),jI(d,i),d}catch{return[]}})(),Xl)}const Ql="system-font:";function Yx({type:n,currentFont:e,customFont:i,onSelect:a,onCustomFontChange:r,className:c=""}){const[d,h]=m.useState(i||""),[f,p]=m.useState([]),[y,b]=m.useState(!1),x=n==="ui"?vS:yS,w=x.find(R=>R.id===e);m.useEffect(()=>{y||TI().then(R=>{p(R),b(!0)})},[y]);const E=m.useMemo(()=>{let R=f;return R=R.filter(z=>/^[\x20-\x7E\u00C0-\u024F]+$/.test(z.family)),n==="code"&&(R=R.filter(z=>z.isMonospace)),R},[f,n]),_=m.useMemo(()=>x.filter(R=>!R.isCustom),[x]);m.useEffect(()=>{i!==void 0&&h(i)},[i]);const C=m.useMemo(()=>e==="custom"&&d?f.some(z=>z.family===d)?`${Ql}${d}`:"custom":e,[e,d,f]),D=m.useCallback(R=>{if(R.startsWith(Ql)){const z=R.slice(Ql.length);a("custom",z)}else a(R==="custom"?"custom":R)},[a]),N=m.useCallback(R=>{const z=R.target.value;h(z),r?.(z),e==="custom"&&a("custom",z)},[e,a,r]),k=f.length>0,T=e==="custom"&&!k;return l.jsxs("div",{className:`font-picker ${c}`,children:[l.jsxs(CI,{value:C,onValueChange:D,children:[l.jsx(pE,{className:"font-picker-trigger","aria-label":`Select ${n} font`,style:{fontFamily:w?.fontFamily||(d?`"${d}"`:"inherit")},children:l.jsx(_I,{placeholder:"Select font..."})}),l.jsxs(yE,{className:"max-h-[300px]",children:[_.length>0&&l.jsxs(Jh,{children:[l.jsx(sc,{children:"Presets"}),_.map(R=>l.jsx(ac,{value:R.id,style:{fontFamily:R.fontFamily||"inherit"},children:l.jsxs("span",{className:"font-picker-item-content",children:[l.jsx("span",{className:"font-name",children:R.name}),l.jsx("span",{className:"font-preview",style:{fontFamily:R.fontFamily},children:"Aa"})]})},R.id))]}),k&&E.length>0&&l.jsxs(Jh,{children:[l.jsxs(sc,{children:["System Fonts (",E.length,")"]}),E.map(R=>l.jsx(ac,{value:`${Ql}${R.family}`,style:{fontFamily:`"${R.family}", inherit`},children:l.jsxs("span",{className:"font-picker-item-content",children:[l.jsx("span",{className:"font-name",children:R.family}),l.jsx("span",{className:"font-preview",style:{fontFamily:`"${R.family}"`},children:"Aa"})]})},R.family))]}),!k&&y&&l.jsxs(Jh,{children:[l.jsx(sc,{children:"Custom"}),l.jsx(ac,{value:"custom",children:"Custom..."})]})]})]}),T&&l.jsx("input",{type:"text",className:"font-picker-custom-input",value:d,onChange:N,placeholder:"Enter font family...","aria-label":"Custom font family"})]})}const kI=["xs","sm","base","lg","xl"];function Xx({currentSize:n,onSelect:e,className:i=""}){return l.jsx(St,{delayDuration:300,children:l.jsx("div",{className:`font-size-picker ${i}`,role:"group","aria-label":"Font size",children:kI.map(a=>l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:a===n?"secondary":"ghost",size:"sm",className:`font-size-option ${a===n?"active":""}`,"data-size":a,onClick:()=>e(a),"aria-pressed":a===n,children:a.toUpperCase()})}),l.jsx(Te,{children:`${Cf[a]} (${a})`})]},a))})})}const Qx={S:0,A:1,B:2};function bE(){const[n,e]=m.useState(null),[i,a]=m.useState([]),[r,c]=m.useState(!1),[d,h]=m.useState(ic),[f,p]=m.useState(Tm);m.useEffect(()=>{async function C(){try{console.log("[SettingsPanel] Loading settings via REST");const T=await fetch("/api/settings");if(T.ok){const R=await T.json();console.log("[SettingsPanel] Settings loaded:",R),e(R)}}catch(T){console.error("[SettingsPanel] Failed to load settings:",T)}}async function D(){try{const T=await fetch("/api/settings/themes");if(T.ok){const R=await T.json();a(R.themes||[])}}catch(T){console.error("[SettingsPanel] Failed to load themes:",T)}}C(),D(),console.log("[SettingsPanel] Connecting to /ws/settings for real-time sync");const N=window.location.protocol==="https:"?"wss:":"ws:",k=new WebSocket(`${N}//${window.location.host}/ws/settings`);return k.onmessage=T=>{try{const R=JSON.parse(T.data);(R.type==="init"||R.type==="update")&&(console.log("[SettingsPanel] Settings update via WebSocket:",R.settings),e(R.settings))}catch(R){console.error("[SettingsPanel] Failed to parse WebSocket message:",R)}},k.onerror=T=>{console.error("[SettingsPanel] WebSocket error:",T)},wS().then(T=>{_f(T),h(T)}),bS().then(T=>{p(T),nc(T)}),()=>k.close()},[]);const y=m.useMemo(()=>[...i].sort((C,D)=>{const N=(Qx[C.tier]??3)-(Qx[D.tier]??3);return N!==0?N:C.name.localeCompare(D.name)}),[i]),b=m.useCallback(async C=>{if(n){c(!0);try{const D={...n,pennyfarthing:{...n.pennyfarthing,theme:C}};await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({pennyfarthing:{theme:C}})}),e(D)}finally{c(!1)}}},[n]),x=m.useCallback(async(C,D,N)=>{if(n){console.log(`[SettingsPanel] Toggle ${C}.${D} = ${N}`),c(!0);try{const k={...n,[C]:{...n[C],[D]:N}};console.log("[SettingsPanel] Saving via REST"),await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({[C]:{[D]:N}})}),console.log("[SettingsPanel] Save complete, updating local state"),e(k)}finally{c(!1)}}},[n]),w=m.useCallback(async C=>{c(!0);try{_f(C),await Uz(C),h(C)}finally{c(!1)}},[]),E=m.useCallback(async(C,D,N)=>{c(!0);try{const k={...f,[C==="ui"?"uiFont":"codeFont"]:D,...D==="custom"&&N?{[C==="ui"?"customUiFont":"customCodeFont"]:N}:{}};nc(k),await px(k),p(k)}finally{c(!1)}},[f]),_=m.useCallback(async(C,D)=>{c(!0);try{const N={...f,[C==="ui"?"uiFontSize":"codeFontSize"]:D};nc(N),await px(N),p(N)}finally{c(!1)}},[f]);return n?l.jsxs("div",{className:"settings-panel","data-testid":"settings-panel",children:[l.jsxs("section",{className:"settings-section",children:[l.jsx("h4",{children:"Theme"}),l.jsx("select",{value:n.pennyfarthing?.theme||"",onChange:C=>b(C.target.value),disabled:r,className:"theme-select",children:y.map(C=>l.jsxs("option",{value:C.id,children:["[",C.tier||"Unranked","] ",C.name]},C.id))})]}),l.jsx(Rt,{className:"my-2"}),l.jsxs("section",{className:"settings-section",children:[l.jsx("h4",{children:"Color Palette"}),l.jsx(YL,{currentPreset:d,onSelect:w})]}),l.jsx(Rt,{className:"my-2"}),l.jsxs("section",{className:"settings-section",children:[l.jsx("h4",{children:"Fonts"}),l.jsxs("div",{className:"font-setting",children:[l.jsx("label",{children:"UI Font"}),l.jsx(Yx,{type:"ui",currentFont:f.uiFont,customFont:f.customUiFont,onSelect:(C,D)=>E("ui",C,D)}),l.jsx(Xx,{currentSize:f.uiFontSize,onSelect:C=>_("ui",C)})]}),l.jsxs("div",{className:"font-setting",children:[l.jsx("label",{children:"Code Font"}),l.jsx(Yx,{type:"code",currentFont:f.codeFont,customFont:f.customCodeFont,onSelect:(C,D)=>E("code",C,D)}),l.jsx(Xx,{currentSize:f.codeFontSize,onSelect:C=>_("code",C)})]})]}),l.jsx(Rt,{className:"my-2"}),l.jsxs("section",{className:"settings-section",children:[l.jsx("h4",{children:"Workflow"}),window.__CYCLIST_MODE__==="cyclist"&&l.jsxs("div",{className:"toggle-setting",children:[l.jsx(kf,{checked:n.workflow?.bell_mode||!1,onCheckedChange:C=>x("workflow","bell_mode",C),disabled:r}),"Bell Mode",l.jsx("span",{className:"setting-description",children:"Inject queued messages via PostToolUse hook instead of waiting"})]}),l.jsxs("div",{className:"toggle-setting",children:[l.jsx(kf,{checked:n.workflow?.relay_mode||!1,onCheckedChange:C=>x("workflow","relay_mode",C),disabled:r}),"Relay Mode",l.jsx("span",{className:"setting-description",children:"Auto-handoff to next agent"})]})]})]}):l.jsx("div",{className:"settings-panel loading","data-testid":"settings-panel",children:l.jsxs("div",{className:"space-y-4 p-2",children:[l.jsx(fe,{className:"h-4 w-24"}),l.jsx(fe,{className:"h-8 w-full"}),l.jsx(fe,{className:"h-4 w-32"}),l.jsx(fe,{className:"h-8 w-full"}),l.jsx(fe,{className:"h-4 w-20"}),l.jsx(fe,{className:"h-6 w-48"})]})})}function RI(n){return new Date(n).toLocaleTimeString()}function Zx(n){return n===void 0?"-":n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function Kx(n,e=60){return n?n.length<=e?n:n.substring(0,e)+"...":"-"}function OI(n){return n===void 0?"":n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}function zI(n){if(!n)return"";const e=n.split("/");return e.length<=3?n:".../"+e.slice(-3).join("/")}function It({label:n,value:e,mono:i}){return e==null||e===""?null:l.jsxs("div",{className:"detail-row",children:[l.jsx("span",{className:"detail-label",children:n}),l.jsx("span",{className:i?"detail-value font-mono":"detail-value",children:e})]})}function xE(){const[n,e]=m.useState([]),[i,a]=m.useState(null),[r,c]=m.useState([]),[d,h]=m.useState(""),[f,p]=m.useState(""),[y,b]=m.useState(!0),[x,w]=m.useState(null),[E,_]=m.useState(null),C=m.useRef(!0),D=m.useRef(null),N=m.useRef(null);m.useEffect(()=>{const A=N.current;if(!A)return;const G=()=>{C.current=A.scrollTop===0};return A.addEventListener("scroll",G),()=>A.removeEventListener("scroll",G)},[y]),m.useEffect(()=>{C.current&&D.current&&n.length>0&&D.current.scrollIntoView()},[n]);const k=m.useCallback(async()=>{try{const A=new URLSearchParams;d&&A.set("toolType",d),f&&A.set("status",f),A.set("limit","200");const G=await fetch(`/api/audit-log?${A}`);if(!G.ok)throw new Error("Failed to fetch audit log");const U=await G.json();e(U.entries||[]),w(null)}catch(A){w(A instanceof Error?A.message:"Unknown error")}},[d,f]),T=m.useCallback(async()=>{try{const A=await fetch("/api/audit-log/stats");if(!A.ok)throw new Error("Failed to fetch stats");const G=await A.json();a(G)}catch(A){console.error("[AuditLogPanel] Stats error:",A)}},[]),R=m.useCallback(async()=>{try{const A=await fetch("/api/audit-log/types");if(!A.ok)throw new Error("Failed to fetch types");const G=await A.json();c(G.types||[])}catch(A){console.error("[AuditLogPanel] Types error:",A)}},[]);m.useEffect(()=>{b(!0),Promise.all([k(),T(),R()]).finally(()=>{b(!1)});const A=new WebSocket(`ws://${window.location.host}/ws/spans`);return A.onmessage=G=>{try{const U=JSON.parse(G.data);U.type==="span"&&U.span&&(e(B=>[U.span,...B].slice(0,200)),T())}catch(U){console.error("[AuditLogPanel] WebSocket parse error:",U)}},()=>A.close()},[k,T,R]),m.useEffect(()=>{k()},[d,f,k]);const z=async A=>{try{const G=new URLSearchParams;G.set("format",A),G.set("download","true"),d&&G.set("toolType",d);const U=await fetch(`/api/audit-log/export?${G}`);if(!U.ok)throw new Error("Export failed");const B=await U.blob(),$=URL.createObjectURL(B),ae=document.createElement("a");ae.href=$,ae.download=`audit-log.${A}`,ae.click(),URL.revokeObjectURL($)}catch(G){console.error("[AuditLogPanel] Export error:",G)}},O=async()=>{if(confirm("Clear all audit log entries?"))try{if(!(await fetch("/api/audit-log",{method:"DELETE"})).ok)throw new Error("Clear failed");e([]),T()}catch(A){console.error("[AuditLogPanel] Clear error:",A)}};return y?l.jsxs("div",{className:"audit-log-panel p-4 space-y-3",children:[l.jsxs("div",{className:"flex gap-4",children:[l.jsx(fe,{className:"h-4 w-20"}),l.jsx(fe,{className:"h-4 w-24"}),l.jsx(fe,{className:"h-4 w-20"})]}),l.jsx(Rt,{}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(fe,{className:"h-6 w-full"}),l.jsx(fe,{className:"h-6 w-full"}),l.jsx(fe,{className:"h-6 w-full"}),l.jsx(fe,{className:"h-6 w-3/4"})]})]}):x?l.jsx("div",{className:"audit-log-panel p-4",children:l.jsxs("div",{className:"text-error",children:["Error: ",x]})}):l.jsx("div",{className:"audit-log-panel flex flex-col h-full",children:l.jsxs(St,{delayDuration:300,children:[i&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"audit-log-stats flex gap-4 p-2 text-sm",children:[l.jsxs("span",{className:"text-muted",children:["Total: ",l.jsx("strong",{children:i.total})]}),l.jsxs("span",{className:"text-success",children:["Success: ",l.jsx("strong",{children:i.successCount})]}),l.jsxs("span",{className:"text-error",children:["Errors: ",l.jsx("strong",{children:i.errorCount})]})]}),l.jsx(Rt,{})]}),l.jsxs("div",{className:"audit-log-toolbar flex p-2 items-center",children:[l.jsxs("select",{value:d,onChange:A=>h(A.target.value),children:[l.jsx("option",{value:"",children:"All Tools"}),r.map(A=>l.jsx("option",{value:A,children:A},A))]}),l.jsxs("select",{value:f,onChange:A=>p(A.target.value),children:[l.jsx("option",{value:"",children:"All Status"}),l.jsx("option",{value:"success",children:"Success"}),l.jsx("option",{value:"error",children:"Errors"})]}),l.jsx("div",{className:"flex-1"}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"sm",className:"audit-log-btn",onClick:()=>z("json"),children:"JSON"})}),l.jsx(Te,{children:"Export as JSON"})]}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"sm",className:"audit-log-btn",onClick:()=>z("csv"),children:"CSV"})}),l.jsx(Te,{children:"Export as CSV"})]}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"sm",className:"audit-log-btn audit-log-btn-clear",onClick:O,children:"Clear"})}),l.jsx(Te,{children:"Clear audit log"})]})]}),l.jsxs("div",{ref:N,className:"audit-log-entries flex-1",style:{overflow:"auto"},children:[l.jsx("div",{ref:D}),n.length===0?l.jsx("div",{className:"p-4 text-muted text-center",children:"No entries"}):l.jsxs("table",{children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{className:"text-left",children:"Time"}),l.jsx("th",{className:"text-left",children:"Tool"}),l.jsx("th",{className:"text-left",children:"Input"}),l.jsx("th",{className:"text-right",children:"Duration"}),l.jsx("th",{className:"text-center",children:"Status"})]})}),l.jsx("tbody",{children:n.map((A,G)=>l.jsxs(ue.Fragment,{children:[l.jsxs("tr",{className:E===G?"expanded":"",onClick:()=>_(E===G?null:G),children:[l.jsx("td",{className:"whitespace-nowrap",children:RI(A.timestamp)}),l.jsx("td",{className:"tool-name font-mono","data-tool":A.toolName.toLowerCase(),children:A.toolName}),l.jsx("td",{className:"truncate max-w-[200px]",children:A.input?l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{children:Kx(A.input)})}),l.jsx(Te,{children:A.input})]}):Kx(A.input)}),l.jsx("td",{className:"text-right whitespace-nowrap",children:Zx(A.durationMs)}),l.jsx("td",{className:"text-center",children:A.success?l.jsx("span",{className:"status-ok",children:"✓"}):l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{className:"status-err",children:"✗"})}),l.jsx(Te,{children:A.error})]})})]}),E===G&&l.jsx("tr",{className:"expanded-detail",children:l.jsxs("td",{colSpan:5,children:[l.jsxs("div",{className:"detail-grid",children:[l.jsx(It,{label:"Tool",value:A.toolName}),l.jsx(It,{label:"Duration",value:A.durationMs!==void 0?Zx(A.durationMs):void 0}),A.exitCode!==void 0&&A.exitCode!==null&&l.jsx(It,{label:"Exit Code",value:A.exitCode,mono:!0}),l.jsx(It,{label:"File",value:A.filePath,mono:!0}),A.language&&l.jsx(It,{label:"Language",value:A.language}),A.fileSize!==void 0&&l.jsx(It,{label:"Size",value:OI(A.fileSize)}),A.lineCount!==void 0&&l.jsx(It,{label:"Lines",value:A.lineCount.toLocaleString()}),A.gitStatus&&l.jsx(It,{label:"Git",value:A.gitStatus}),A.diff&&l.jsx(It,{label:"Diff",value:l.jsxs("span",{children:[l.jsxs("span",{style:{color:"var(--success, #22c55e)"},children:["+",A.diff.added]})," ",l.jsxs("span",{style:{color:"var(--error, #ef4444)"},children:["-",A.diff.removed]})]})}),A.command&&l.jsx(It,{label:"Command",value:A.command,mono:!0}),A.workingDirectory&&l.jsx(It,{label:"CWD",value:zI(A.workingDirectory),mono:!0}),A.subagentType&&l.jsx(It,{label:"Agent",value:A.subagentType}),A.isBackground&&l.jsx(It,{label:"Background",value:"Yes"}),A.promptSummary&&l.jsx(It,{label:"Prompt",value:A.promptSummary}),A.resultSummary&&l.jsx(It,{label:"Result",value:A.resultSummary})]}),A.outputSummary&&A.outputSummary.totalLines>0&&l.jsxs("div",{className:"detail-output",children:[l.jsxs("div",{className:"detail-label",children:["Output (",A.outputSummary.totalLines," lines",A.outputSummary.truncated?", truncated":"",")"]}),l.jsxs("pre",{children:[A.outputSummary.firstLines.join(`
78
+ For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return m.useEffect(()=>{document.getElementById(n.current?.getAttribute("aria-describedby"))||console.warn(e)},[e,n]),null},rL=VC,lL=FC,JC=UC,e_=$C,t_=QC,n_=KC,i_=qC,s_=XC;const cL=rL,uL=lL,a_=m.forwardRef(({className:n,...e},i)=>l.jsx(JC,{className:ye("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",n),...e,ref:i}));a_.displayName=JC.displayName;const o_=m.forwardRef(({className:n,...e},i)=>l.jsxs(uL,{children:[l.jsx(a_,{}),l.jsx(e_,{ref:i,className:ye("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",n),...e})]}));o_.displayName=e_.displayName;const r_=({className:n,...e})=>l.jsx("div",{className:ye("flex flex-col space-y-2 text-center sm:text-left",n),...e});r_.displayName="AlertDialogHeader";const l_=({className:n,...e})=>l.jsx("div",{className:ye("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",n),...e});l_.displayName="AlertDialogFooter";const c_=m.forwardRef(({className:n,...e},i)=>l.jsx(i_,{ref:i,className:ye("text-lg font-semibold",n),...e}));c_.displayName=i_.displayName;const u_=m.forwardRef(({className:n,...e},i)=>l.jsx(s_,{ref:i,className:ye("text-sm text-muted-foreground",n),...e}));u_.displayName=s_.displayName;const d_=m.forwardRef(({className:n,...e},i)=>l.jsx(t_,{ref:i,className:ye(Dc(),n),...e}));d_.displayName=t_.displayName;const h_=m.forwardRef(({className:n,...e},i)=>l.jsx(n_,{ref:i,className:ye(Dc({variant:"outline"}),"mt-2 sm:mt-0",n),...e}));h_.displayName=n_.displayName;function dL({isOpen:n,title:e,message:i,confirmLabel:a="Confirm",cancelLabel:r="Cancel",isDanger:c=!1,onConfirm:d,onCancel:h}){return l.jsx(cL,{open:n,onOpenChange:f=>{f||h()},children:l.jsxs(o_,{children:[l.jsxs(r_,{children:[l.jsx(c_,{children:e}),l.jsx(u_,{children:i})]}),l.jsxs(l_,{children:[l.jsx(h_,{onClick:h,children:r}),l.jsx(d_,{className:ye(c&&Dc({variant:"destructive"})),onClick:d,children:a})]})]})})}function hL(n){const[e,i]=ue.useState(!1),a=m.useRef(null),r=m.useCallback(()=>new Promise(f=>{a.current=f,i(!0)}),[]),c=m.useCallback(()=>{i(!1),a.current?.(!0),a.current=null},[]),d=m.useCallback(()=>{i(!1),a.current?.(!1),a.current=null},[]),h={isOpen:e,title:n.title,message:n.message,confirmLabel:n.confirmLabel,cancelLabel:n.cancelLabel,isDanger:n.isDanger,onConfirm:c,onCancel:d};return{isOpen:e,confirm:r,dialogProps:h}}function fL(){const[n,e]=m.useState(null),[i,a]=m.useState(!1),[r,c]=m.useState(null),[d,h]=m.useState(null),f=m.useRef(null),p=m.useCallback(()=>{f.current&&f.current.abort();const b=new AbortController;f.current=b,a(!0),c(null),fetch("/api/agent-load",{signal:b.signal}).then(x=>{if(!x.ok)throw new Error(`HTTP ${x.status}: ${x.statusText}`);return x.json()}).then(x=>{e(x),a(!1)}).catch(x=>{x.name!=="AbortError"&&(c(x instanceof Error?x:new Error(String(x))),a(!1))})},[]),y=m.useCallback(async(b,x)=>{const w=await fetch("/api/agent-load/prune-sidecar",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:b,file:x})});if(!w.ok){h({success:!1,error:`HTTP ${w.status}: ${w.statusText}`});return}const E=await w.json();h(E),E.success&&p()},[p]);return m.useEffect(()=>()=>{f.current&&f.current.abort()},[]),{data:n,isLoading:i,error:r,refresh:p,pruneSidecar:y,pruneResult:d}}const mL=["patterns.md","gotchas.md","decisions.md"];function pL({isOpen:n,onClose:e}){const{data:i,isLoading:a,error:r,refresh:c,pruneSidecar:d,pruneResult:h}=fL(),[f,p]=m.useState(null),[y,b]=m.useState(null),{confirm:x,dialogProps:w}=hL({title:"Clear Sidecar",message:y?`Reset ${y.file} for ${y.agent}? This will replace the sidecar with its default template.`:"",confirmLabel:"Confirm",isDanger:!0});m.useEffect(()=>{n&&c()},[n,c]);const E=m.useMemo(()=>i?[...i.agents].sort((T,R)=>(R.totalTokens??0)-(T.totalTokens??0)):[],[i]),_=m.useMemo(()=>E.length?E[0]?.totalTokens??0:0,[E]),C=T=>{p(R=>R===T?null:T)},D=async(T,R)=>{b({agent:T,file:R}),await x()&&await d(T,R),b(null)},N=T=>{const R=T.totalTokens??0,z=_>0?R/_*100:0,O=f===T.agent,A=R>=5e3?"bg-[var(--status-error,#f14c4c)]":R>=3e3?"bg-[var(--status-warning,#cca700)]":"bg-[var(--status-success,#4ec9b0)]";return l.jsxs(NC,{open:O,onOpenChange:()=>C(T.agent),children:[l.jsx(jC,{asChild:!0,children:l.jsxs("div",{className:"px-4 py-2 cursor-pointer hover:bg-muted/50 rounded-md transition-colors","data-testid":`agent-row-${T.agent}`,children:[l.jsxs("div",{className:"flex items-center justify-between mb-1",children:[l.jsx("span",{className:"font-mono text-sm font-medium",children:T.agent}),l.jsx("span",{className:"font-mono text-sm tabular-nums text-text-secondary",children:R.toLocaleString()})]}),l.jsx(BC,{value:z,className:"h-2.5 bg-[var(--border)]",indicatorClassName:A})]})}),l.jsx(TC,{children:l.jsxs("div",{className:"mx-4 mb-3 rounded-md bg-muted/30 p-3 space-y-1",children:[T.components&&T.components.length>0?T.components.map(G=>l.jsxs("div",{className:"flex items-center justify-between text-xs text-text-secondary",children:[l.jsx("span",{children:f_(G.name)}),l.jsx("span",{className:"tabular-nums",children:G.tokens.toLocaleString()})]},G.name)):l.jsx("div",{className:"text-xs text-text-secondary",children:"No component breakdown available"}),l.jsxs("div",{className:"pt-2 border-t border-muted/50 mt-2",children:[l.jsx("div",{className:"text-xs font-medium mb-1.5 text-text-secondary",children:"Sidecars"}),l.jsx("div",{className:"flex gap-2",children:mL.map(G=>l.jsxs(Ce,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:U=>{U.stopPropagation(),D(T.agent,G)},children:["Clear ",G]},G))})]})]})})]},T.agent)},k=()=>a?l.jsx("div",{className:"space-y-3 p-4",children:Array.from({length:5}).map((T,R)=>l.jsxs("div",{"data-testid":`skeleton-${R}`,className:"space-y-1.5 px-4",children:[l.jsxs("div",{className:"flex justify-between",children:[l.jsx(fe,{className:"h-4 w-24"}),l.jsx(fe,{className:"h-4 w-16"})]}),l.jsx(fe,{className:"h-2.5 w-full rounded-full"})]},R))}):r?l.jsxs("div",{className:"p-4 space-y-3",children:[l.jsx("div",{className:"p-4 rounded border border-[var(--status-error)]/20 bg-[var(--status-error)]/5 text-[var(--status-error)] text-sm",children:r.message}),l.jsx("div",{className:"text-center",children:l.jsx(Ce,{variant:"outline",size:"sm",onClick:c,children:"Retry"})})]}):i?l.jsxs("div",{className:"space-y-0.5",children:[h?.success&&h.tokensFreed!=null&&l.jsxs("div",{className:"text-xs text-green-600 px-4 py-1",children:["Freed ",h.tokensFreed.toLocaleString()," tokens from ",h.agent,"/",h.file]}),l.jsxs("div",{className:"flex items-center justify-between px-4 py-2",children:[l.jsxs("span",{"data-testid":"cached-at",className:"text-xs text-[var(--text-muted)]",children:["Cached: ",new Date(i.cachedAt).toLocaleString()]}),l.jsx(Ce,{variant:"ghost",size:"sm",className:"text-xs h-6 text-[var(--text-muted)] hover:text-[var(--text-primary)]",onClick:c,children:"Refresh"})]}),E.map(T=>N(T))]}):null;return l.jsxs(l.Fragment,{children:[l.jsx(fr,{open:n,onOpenChange:T=>{T||e()},title:"Agent Load Analysis",description:"Token usage breakdown for all agents",className:"max-w-2xl",children:k()}),l.jsx(dL,{...w})]})}function gL(n){const[e,i]=m.useState(null),[a,r]=m.useState(!1),[c,d]=m.useState(null),h=m.useRef(null),f=m.useCallback(()=>{h.current&&h.current.abort();const p=new AbortController;h.current=p,r(!0),d(null);const y=new URLSearchParams({days:String(n.days),layer:n.layer||"all"});n.repo&&y.set("repo",n.repo),fetch(`/api/dead-code?${y}`,{signal:p.signal}).then(b=>{if(!b.ok)throw new Error(`HTTP ${b.status}: ${b.statusText}`);return b.json()}).then(b=>{i(b),r(!1)}).catch(b=>{b.name!=="AbortError"&&(d(b instanceof Error?b:new Error(String(b))),r(!1))})},[n.days,n.repo,n.layer]);return m.useEffect(()=>()=>{h.current&&h.current.abort()},[]),{data:e,isLoading:a,error:c,refresh:f}}function vL({isOpen:n,onClose:e,days:i=180,repo:a}){const{data:r,isLoading:c,error:d,refresh:h}=gL({days:i,repo:a,layer:"all"}),[f,p]=m.useState("stale"),[y,b]=m.useState("days_since_last_commit"),[x,w]=m.useState("desc"),[E,_]=m.useState("file"),[C,D]=m.useState("asc");m.useEffect(()=>{n&&h()},[n,h]);const N=m.useCallback(A=>{w(G=>y===A&&G==="desc"?"asc":"desc"),b(A)},[y]),k=m.useCallback(A=>{D(G=>E===A&&G==="desc"?"asc":"desc"),_(A)},[E]),T=r?.stale_file_count??r?.stale_files?.length??0,R=r?.unused_export_count??r?.unused_exports?.length??0,z=m.useMemo(()=>{const A=[...r?.stale_files||[]];return A.sort((G,U)=>{const B=G[y],$=U[y];if(typeof B=="number"&&typeof $=="number")return x==="asc"?B-$:$-B;const ae=String(B),ne=String($);return x==="asc"?ae.localeCompare(ne):ne.localeCompare(ae)}),A},[r?.stale_files,y,x]),O=m.useMemo(()=>{const A=[...r?.unused_exports||[]];return A.sort((G,U)=>{const B=G[E],$=U[E];if(typeof B=="number"&&typeof $=="number")return C==="asc"?B-$:$-B;const ae=String(B),ne=String($);return C==="asc"?ae.localeCompare(ne):ne.localeCompare(ae)}),A},[r?.unused_exports,E,C]);return l.jsx(qc,{open:n,onOpenChange:A=>{A||e()},children:l.jsxs(ur,{className:"max-w-4xl max-h-[80vh]",children:[l.jsxs(Yc,{children:[l.jsx(Xc,{children:"Dead Code Analysis"}),l.jsx(Qc,{children:"Diagnostic report — files and exports with no recent activity."})]}),l.jsxs("div",{className:"flex gap-4 border-b border-[var(--border)]",children:[l.jsxs("button",{onClick:()=>p("stale"),className:ye("pb-2 text-sm",f==="stale"?"border-b-2 border-[var(--accent)] text-[var(--text-primary)] font-medium":"text-[var(--text-muted)]"),children:["Stale Files ",l.jsx($e,{variant:"secondary",className:"ml-1",children:T})]}),l.jsxs("button",{onClick:()=>p("exports"),className:ye("pb-2 text-sm",f==="exports"?"border-b-2 border-[var(--accent)] text-[var(--text-primary)] font-medium":"text-[var(--text-muted)]"),children:["Unused Exports ",l.jsx($e,{variant:"secondary",className:"ml-1",children:R})]})]}),l.jsxs(Vm,{className:"h-[50vh]",children:[c&&l.jsx("div",{className:"text-center py-12 text-[var(--text-muted)]",children:"Analyzing..."}),d&&l.jsx("div",{className:"m-4 p-4 rounded border border-[var(--status-error)]/20 bg-[var(--status-error)]/5 text-[var(--status-error)] text-sm",children:d.message}),r&&f==="stale"&&(z.length===0?l.jsx("div",{className:"text-center py-12 text-[var(--text-muted)]",children:"No stale files found"}):l.jsxs("table",{className:"w-full text-sm",children:[l.jsx("thead",{children:l.jsxs("tr",{role:"row",className:"border-b border-[var(--border)]",children:[l.jsx("th",{className:"text-left pb-2 cursor-pointer select-none text-xs font-medium uppercase tracking-wider text-[var(--text-muted)]",onClick:()=>N("path"),children:"File"}),l.jsx("th",{className:"text-right pb-2 cursor-pointer select-none text-xs font-medium uppercase tracking-wider text-[var(--text-muted)]",onClick:()=>N("days_since_last_commit"),children:"Days Stale"}),l.jsx("th",{className:"text-right pb-2 cursor-pointer select-none text-xs font-medium uppercase tracking-wider text-[var(--text-muted)]",onClick:()=>N("size_bytes"),children:"Size"}),l.jsx("th",{className:"text-left pb-2 cursor-pointer select-none text-xs font-medium uppercase tracking-wider text-[var(--text-muted)]",onClick:()=>N("last_commit_date"),children:"Last Commit"})]})}),l.jsx("tbody",{children:z.map(A=>l.jsxs("tr",{role:"row",className:"text-[var(--text-primary)]",children:[l.jsx("td",{className:"py-1.5 font-mono text-xs",children:A.path}),l.jsx("td",{className:"py-1.5 text-right tabular-nums font-mono",children:A.days_since_last_commit}),l.jsx("td",{className:"py-1.5 text-right tabular-nums font-mono",children:yL(A.size_bytes)}),l.jsx("td",{className:"py-1.5",children:A.last_commit_date?new Date(A.last_commit_date).toLocaleDateString():"—"})]},A.path))})]})),r&&f==="exports"&&(O.length===0?l.jsx("div",{className:"text-center py-12 text-[var(--text-muted)]",children:"No unused exports found"}):l.jsxs("table",{className:"w-full text-sm",children:[l.jsx("thead",{children:l.jsxs("tr",{role:"row",className:"border-b border-[var(--border)]",children:[l.jsx("th",{className:"text-left pb-2 cursor-pointer select-none text-xs font-medium uppercase tracking-wider text-[var(--text-muted)]",onClick:()=>k("file"),children:"File"}),l.jsx("th",{className:"text-left pb-2 cursor-pointer select-none text-xs font-medium uppercase tracking-wider text-[var(--text-muted)]",onClick:()=>k("symbol"),children:"Export"}),l.jsx("th",{className:"text-right pb-2 cursor-pointer select-none text-xs font-medium uppercase tracking-wider text-[var(--text-muted)]",onClick:()=>k("line"),children:"Line"})]})}),l.jsx("tbody",{children:O.map(A=>l.jsxs("tr",{role:"row",className:"text-[var(--text-primary)]",children:[l.jsx("td",{className:"py-1.5 font-mono text-xs",children:A.file}),l.jsx("td",{className:"py-1.5",children:A.symbol}),l.jsx("td",{className:"py-1.5 text-right tabular-nums font-mono",children:A.line})]},`${A.file}:${A.symbol}`))})]}))]})]})})}function yL(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}const bL=[{min:90,grade:"A",color:"#22c55e"},{min:75,grade:"B",color:"#84cc16"},{min:60,grade:"C",color:"#eab308"},{min:40,grade:"D",color:"#f97316"},{min:0,grade:"F",color:"#ef4444"}],Ux={churn:"Churn",todo_density:"TODO Density",complexity:"Complexity",test_gaps:"Test Gaps",dead_code:"Dead Code",deprecation_debt:"Deprecation Debt",dependency_freshness:"Dependency Freshness",agent_context_efficiency:"Agent Context Efficiency"};function xL(n){for(const e of bL)if(n>=e.min)return{grade:e.grade,color:e.color};return{grade:"F",color:"#ef4444"}}function $x(n,e,i,a,r){const c=Wx(n,e,i,r),d=Wx(n,e,i,a),h=r-a<=180?"0":"1";return`M ${c.x} ${c.y} A ${i} ${i} 0 ${h} 0 ${d.x} ${d.y}`}function Wx(n,e,i,a){const r=(a-90)*Math.PI/180;return{x:n+i*Math.cos(r),y:e+i*Math.sin(r)}}function wL(n){const e=Math.floor(n/1e3);if(e<60)return`${e}s ago`;const i=Math.floor(e/60);return i<60?`${i}m ago`:`${Math.floor(i/60)}h ago`}function SL({score:n,dimensions:e,totalDimensions:i,onDimensionClick:a,isLoading:r,lastFetchedAt:c,onRefresh:d,error:h}){const f=n!=null,p=f?xL(n):null,y=f?n/100*180:0,[b,x]=m.useState(null);m.useEffect(()=>{if(!c){x(null);return}const _=()=>x(wL(Date.now()-c));_();const C=setInterval(_,1e4);return()=>clearInterval(C)},[c]);const w=Object.keys(Ux),E=new Map(e.map(_=>[_.name,_]));return l.jsxs("div",{"data-testid":"health-gauge","data-grade":p?.grade??null,children:[l.jsxs("div",{className:"health-gauge-header",children:[l.jsxs("div",{className:"health-gauge-status",children:[b&&l.jsx("span",{className:"health-gauge-age","data-testid":"health-gauge-age",children:b}),h&&l.jsx("span",{className:"health-gauge-error","data-testid":"health-gauge-error",children:"Failed"})]}),d&&l.jsx(Ce,{variant:"outline",size:"sm",className:"health-gauge-refresh","data-testid":"health-gauge-refresh",onClick:d,disabled:r,children:r?"Analyzing...":f?"Refresh":"Analyze"})]}),l.jsxs("svg",{viewBox:"0 0 200 120",width:"200",height:"120",className:r?"opacity-50":"",children:[l.jsx("path",{d:$x(100,100,80,0,180),fill:"none",stroke:"#333",strokeWidth:"12",strokeLinecap:"round"}),f&&y>0&&l.jsx("path",{d:$x(100,100,80,0,y),fill:"none",stroke:p.color,strokeWidth:"12",strokeLinecap:"round"}),l.jsx("text",{x:"100",y:"85",textAnchor:"middle",fontSize:"28",fill:"currentColor",children:f?String(Math.round(n)):"--"}),p&&l.jsx("text",{x:"100",y:"108",textAnchor:"middle",fontSize:"16",fill:p.color,children:p.grade})]}),f&&i&&e.length<i&&l.jsxs("div",{className:"health-gauge-partial",children:[e.length," of ",i," dimensions"]}),l.jsx("div",{"data-testid":"dimension-breakdown",className:"health-gauge-breakdown",children:w.map(_=>{const C=E.get(_);return l.jsxs("div",{"data-testid":`dimension-${_}`,className:"health-gauge-dimension",onClick:()=>a?.(_),children:[l.jsx("span",{className:"dimension-label",children:Ux[_]||_}),l.jsx("span",{className:"dimension-score",children:C?.score!==null&&C?.score!==void 0?C.score.toFixed(1):"--"})]},_)})})]})}function CL(n){return n>=5e4?"var(--color-danger, #ef4444)":n>=5e3?"var(--color-warning, #f59e0b)":"var(--color-success, #22c55e)"}function _L({history:n}){if(n.length<2)return null;const e=200,i=32,a=2,r=i-a*2,c=n[n.length-1],d=e/n.length;return l.jsx("div",{className:"context-sparkline","data-testid":"context-sparkline",children:l.jsx("svg",{viewBox:`0 0 ${e} ${i}`,role:"img","aria-label":`Context usage trend: currently ${c.percent}%`,children:n.map((h,f)=>{const p=Math.max(1,h.percent/100*r),y=f*d,b=a+r-p;return l.jsx("rect",{x:y,y:b,width:d,height:p,fill:CL(h.tokens),opacity:.8,rx:.5},f)})})})}function EL(){const[n,e]=m.useState(null),[i,a]=m.useState(!1),[r,c]=m.useState(null),[d,h]=m.useState(null),f=m.useRef(null),p=m.useCallback(()=>{f.current&&f.current.abort();const y=new AbortController;f.current=y,a(!0),c(null),fetch("/api/health-score",{signal:y.signal}).then(b=>{if(!b.ok)throw new Error(`HTTP ${b.status}: ${b.statusText}`);return b.json()}).then(b=>{e(b),h(Date.now()),a(!1)}).catch(b=>{b.name!=="AbortError"&&(c(b instanceof Error?b:new Error(String(b))),a(!1))})},[]);return m.useEffect(()=>(p(),()=>{f.current?.abort()}),[p]),{data:n,isLoading:i,error:r,lastFetchedAt:d,refresh:p}}function f_(n){return n==="persona_compressed"?"Persona (Compressed)":n.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function DL(n){if(!n)return 0;switch(n){case"FULL":return 0;case"REFRESH":return 85;case"HANDOFF":return 82;case"MINIMAL":return 95;default:return 0}}function m_(){const[n,e]=m.useState(null),[i,a]=m.useState(null),[r,c]=m.useState(!1),[d,h]=m.useState(!1),[f,p]=m.useState(!1),[y,b]=m.useState(!1),[x,w]=m.useState(!1),[E,_]=m.useState(!1),[C,D]=m.useState(!1),N=EL(),k=m.useRef([]),[T,R]=m.useState(0),z=m.useCallback((U,B)=>{const $=k.current;$.push({percent:U,tokens:B,timestamp:Date.now()}),$.length>50&&$.shift(),R(ae=>ae+1)},[]),O=U=>{switch(U){case"churn":h(!0);break;case"test_gaps":break;case"todo_density":case"deprecation_debt":p(!0);break;case"complexity":b(!0);break;case"dead_code":D(!0);break;case"dependency_freshness":w(!0);break;case"agent_context_efficiency":_(!0);break}};m.useEffect(()=>{const U=window.location.protocol==="https:"?"wss:":"ws:",B=new WebSocket(`${U}//${window.location.host}/ws/context`);B.onmessage=ae=>{try{const ne=JSON.parse(ae.data);if(ne.type==="init"||ne.type==="update"){const W=ne.context;e(W),W.percent!=null&&z(W.percent,W.tokens??0)}}catch{}};const $=new WebSocket(`${U}//${window.location.host}/ws/token-stats`);return $.onmessage=ae=>{try{const ne=JSON.parse(ae.data);a(ne)}catch{}},()=>{B.close(),$.close()}},[z]);const A=n?.tier?`tier-${n.tier.toLowerCase()}`:"",G=DL(n?.tier);return l.jsxs("div",{className:"debug-panel","data-testid":"debug-panel",children:[l.jsx(SL,{score:N.data?.composite_score??null,dimensions:N.data?.dimensions??[],totalDimensions:8,onDimensionClick:O,isLoading:N.isLoading,lastFetchedAt:N.lastFetchedAt,onRefresh:N.refresh,error:N.error}),l.jsx(Rt,{className:"my-3"}),l.jsx("h4",{children:"Context Usage"}),n?l.jsxs("div",{className:"context-info",children:[n.tier&&l.jsxs("div",{className:"tier-display",children:[l.jsx($e,{variant:"outline",className:`tier-badge ${A}`,"data-testid":"tier-badge",children:n.tier}),l.jsxs("span",{className:"tier-savings","data-testid":"tier-savings",children:[G,"% savings"]})]}),n.tokenCounts&&Object.keys(n.tokenCounts).length>0&&l.jsxs("div",{className:"component-breakdown","data-testid":"component-breakdown",children:[l.jsxs("div",{className:"breakdown-header",children:[l.jsxs(Ce,{variant:"ghost",size:"sm",className:"breakdown-toggle","data-testid":"breakdown-toggle",onClick:()=>c(!r),"aria-expanded":r,children:[r?"▼":"▶"," Injected Context"]}),l.jsxs("span",{className:"total-tokens","data-testid":"total-tokens",children:[n.totalTokens?.toLocaleString()," tokens"]})]}),l.jsx("div",{className:`component-list ${r?"expanded":"collapsed"}`,"data-testid":"component-list","aria-expanded":r,children:Object.entries(n.tokenCounts).filter(([,U])=>U>0).sort(([,U],[,B])=>B-U).map(([U,B])=>l.jsxs("div",{className:"component-item","data-testid":`component-${U}`,children:[l.jsx("span",{className:"component-name",children:f_(U)}),l.jsx("span",{className:"component-tokens",children:B.toLocaleString()})]},U))})]}),l.jsx("div",{className:"context-bar",children:l.jsx("div",{className:"context-fill",style:{width:`${n.percent||0}%`}})}),l.jsx(_L,{history:k.current},T),l.jsxs("span",{className:"context-text",children:[(n.tokens??0).toLocaleString()," / ",n.baseline!=null&&n.available!=null?(n.baseline+n.available).toLocaleString():"—"," tokens (",n.percent||0,"%)"]}),n.baseline!=null&&l.jsxs("dl",{className:"context-breakdown",children:[l.jsx("dt",{children:"System Prompt"}),l.jsxs("dd",{children:[n.baseline.toLocaleString()," tokens"]}),l.jsx("dt",{children:"Conversation"}),l.jsxs("dd",{children:[n.usableTokens?.toLocaleString()??"—"," tokens"]}),l.jsx("dt",{children:"Available"}),l.jsxs("dd",{children:[n.available?.toLocaleString()??"—"," tokens"]})]})]}):l.jsx("div",{className:"placeholder",children:"No context data"}),l.jsx(Rt,{className:"my-3"}),l.jsx("h4",{children:"Token Stats"}),i?l.jsxs("dl",{className:"token-stats",children:[i.inputTokens!==void 0&&l.jsxs("div",{className:"token-stat-card","data-testid":"token-stat-input",children:[l.jsx("dt",{children:"Input"}),l.jsx("dd",{children:Number(i.inputTokens).toLocaleString()})]}),i.outputTokens!==void 0&&l.jsxs("div",{className:"token-stat-card","data-testid":"token-stat-output",children:[l.jsx("dt",{children:"Output"}),l.jsx("dd",{children:Number(i.outputTokens).toLocaleString()})]}),i.cacheReadTokens!==void 0&&l.jsxs("div",{className:"token-stat-card","data-testid":"token-stat-cache-read",children:[l.jsx("dt",{children:"Cache Read"}),l.jsx("dd",{children:Number(i.cacheReadTokens).toLocaleString()})]}),i.cacheCreationTokens!==void 0&&l.jsxs("div",{className:"token-stat-card","data-testid":"token-stat-cache-write",children:[l.jsx("dt",{children:"Cache Write"}),l.jsx("dd",{children:Number(i.cacheCreationTokens).toLocaleString()})]}),i.totalCostUsd!==void 0&&Number(i.totalCostUsd)>0&&l.jsxs("div",{className:"token-stat-card","data-testid":"token-stat-cost",children:[l.jsx("dt",{children:"Cost"}),l.jsxs("dd",{children:["$",Number(i.totalCostUsd).toFixed(4)]})]})]}):l.jsx("div",{className:"placeholder",children:"No token stats"}),l.jsx(zP,{open:d,onOpenChange:h}),l.jsx(PP,{open:f,onOpenChange:p}),l.jsx(IP,{open:y,onOpenChange:b}),l.jsx(HP,{open:x,onOpenChange:w}),l.jsx(pL,{isOpen:E,onClose:()=>_(!1)}),l.jsx(vL,{isOpen:C,onClose:()=>D(!1)})]})}function Ym(n){const e=m.useRef({value:n,previous:n});return m.useMemo(()=>(e.current.value!==n&&(e.current.previous=e.current.value,e.current.value=n),e.current.previous),[n])}var nu="Switch",[AL]=cn(nu),[NL,jL]=AL(nu),p_=m.forwardRef((n,e)=>{const{__scopeSwitch:i,name:a,checked:r,defaultChecked:c,required:d,disabled:h,value:f="on",onCheckedChange:p,form:y,...b}=n,[x,w]=m.useState(null),E=Ie(e,k=>w(k)),_=m.useRef(!1),C=x?y||!!x.closest("form"):!0,[D,N]=_n({prop:r,defaultProp:c??!1,onChange:p,caller:nu});return l.jsxs(NL,{scope:i,checked:D,disabled:h,children:[l.jsx(je.button,{type:"button",role:"switch","aria-checked":D,"aria-required":d,"data-state":b_(D),"data-disabled":h?"":void 0,disabled:h,value:f,...b,ref:E,onClick:we(n.onClick,k=>{N(T=>!T),C&&(_.current=k.isPropagationStopped(),_.current||k.stopPropagation())})}),C&&l.jsx(y_,{control:x,bubbles:!_.current,name:a,value:f,checked:D,required:d,disabled:h,form:y,style:{transform:"translateX(-100%)"}})]})});p_.displayName=nu;var g_="SwitchThumb",v_=m.forwardRef((n,e)=>{const{__scopeSwitch:i,...a}=n,r=jL(g_,i);return l.jsx(je.span,{"data-state":b_(r.checked),"data-disabled":r.disabled?"":void 0,...a,ref:e})});v_.displayName=g_;var TL="SwitchBubbleInput",y_=m.forwardRef(({__scopeSwitch:n,control:e,checked:i,bubbles:a=!0,...r},c)=>{const d=m.useRef(null),h=Ie(d,c),f=Ym(i),p=Yf(e);return m.useEffect(()=>{const y=d.current;if(!y)return;const b=window.HTMLInputElement.prototype,w=Object.getOwnPropertyDescriptor(b,"checked").set;if(f!==i&&w){const E=new Event("click",{bubbles:a});w.call(y,i),y.dispatchEvent(E)}},[f,i,a]),l.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:i,...r,tabIndex:-1,ref:h,style:{...r.style,...p,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});y_.displayName=TL;function b_(n){return n?"checked":"unchecked"}var x_=p_,kL=v_;const kf=m.forwardRef(({className:n,...e},i)=>l.jsx(x_,{className:ye("cyclist-switch peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",n),...e,ref:i,children:l.jsx(kL,{className:ye("cyclist-switch-thumb pointer-events-none block h-4 w-4 rounded-full shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));kf.displayName=x_.displayName;var iu="Popover",[w_]=cn(iu,[Wa]),mr=Wa(),[RL,as]=w_(iu),S_=n=>{const{__scopePopover:e,children:i,open:a,defaultOpen:r,onOpenChange:c,modal:d=!1}=n,h=mr(e),f=m.useRef(null),[p,y]=m.useState(!1),[b,x]=_n({prop:a,defaultProp:r??!1,onChange:c,caller:iu});return l.jsx(Zf,{...h,children:l.jsx(RL,{scope:e,contentId:Mt(),triggerRef:f,open:b,onOpenChange:x,onOpenToggle:m.useCallback(()=>x(w=>!w),[x]),hasCustomAnchor:p,onCustomAnchorAdd:m.useCallback(()=>y(!0),[]),onCustomAnchorRemove:m.useCallback(()=>y(!1),[]),modal:d,children:i})})};S_.displayName=iu;var C_="PopoverAnchor",OL=m.forwardRef((n,e)=>{const{__scopePopover:i,...a}=n,r=as(C_,i),c=mr(i),{onCustomAnchorAdd:d,onCustomAnchorRemove:h}=r;return m.useEffect(()=>(d(),()=>h()),[d,h]),l.jsx(kc,{...c,...a,ref:e})});OL.displayName=C_;var __="PopoverTrigger",E_=m.forwardRef((n,e)=>{const{__scopePopover:i,...a}=n,r=as(__,i),c=mr(i),d=Ie(e,r.triggerRef),h=l.jsx(je.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.contentId,"data-state":T_(r.open),...a,ref:d,onClick:we(n.onClick,r.onOpenToggle)});return r.hasCustomAnchor?h:l.jsx(kc,{asChild:!0,...c,children:h})});E_.displayName=__;var Xm="PopoverPortal",[zL,ML]=w_(Xm,{forceMount:void 0}),D_=n=>{const{__scopePopover:e,forceMount:i,children:a,container:r}=n,c=as(Xm,e);return l.jsx(zL,{scope:e,forceMount:i,children:l.jsx(qt,{present:i||c.open,children:l.jsx(rr,{asChild:!0,container:r,children:a})})})};D_.displayName=Xm;var Ha="PopoverContent",A_=m.forwardRef((n,e)=>{const i=ML(Ha,n.__scopePopover),{forceMount:a=i.forceMount,...r}=n,c=as(Ha,n.__scopePopover);return l.jsx(qt,{present:a||c.open,children:c.modal?l.jsx(LL,{...r,ref:e}):l.jsx(IL,{...r,ref:e})})});A_.displayName=Ha;var PL=Pa("PopoverContent.RemoveScroll"),LL=m.forwardRef((n,e)=>{const i=as(Ha,n.__scopePopover),a=m.useRef(null),r=Ie(e,a),c=m.useRef(!1);return m.useEffect(()=>{const d=a.current;if(d)return mm(d)},[]),l.jsx(Vc,{as:PL,allowPinchZoom:!0,children:l.jsx(N_,{...n,ref:r,trapFocus:i.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:we(n.onCloseAutoFocus,d=>{d.preventDefault(),c.current||i.triggerRef.current?.focus()}),onPointerDownOutside:we(n.onPointerDownOutside,d=>{const h=d.detail.originalEvent,f=h.button===0&&h.ctrlKey===!0,p=h.button===2||f;c.current=p},{checkForDefaultPrevented:!1}),onFocusOutside:we(n.onFocusOutside,d=>d.preventDefault(),{checkForDefaultPrevented:!1})})})}),IL=m.forwardRef((n,e)=>{const i=as(Ha,n.__scopePopover),a=m.useRef(!1),r=m.useRef(!1);return l.jsx(N_,{...n,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:c=>{n.onCloseAutoFocus?.(c),c.defaultPrevented||(a.current||i.triggerRef.current?.focus(),c.preventDefault()),a.current=!1,r.current=!1},onInteractOutside:c=>{n.onInteractOutside?.(c),c.defaultPrevented||(a.current=!0,c.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const d=c.target;i.triggerRef.current?.contains(d)&&c.preventDefault(),c.detail.originalEvent.type==="focusin"&&r.current&&c.preventDefault()}})}),N_=m.forwardRef((n,e)=>{const{__scopePopover:i,trapFocus:a,onOpenAutoFocus:r,onCloseAutoFocus:c,disableOutsidePointerEvents:d,onEscapeKeyDown:h,onPointerDownOutside:f,onFocusOutside:p,onInteractOutside:y,...b}=n,x=as(Ha,i),w=mr(i);return fm(),l.jsx(Bc,{asChild:!0,loop:!0,trapped:a,onMountAutoFocus:r,onUnmountAutoFocus:c,children:l.jsx(ar,{asChild:!0,disableOutsidePointerEvents:d,onInteractOutside:y,onEscapeKeyDown:h,onPointerDownOutside:f,onFocusOutside:p,onDismiss:()=>x.onOpenChange(!1),children:l.jsx(Kf,{"data-state":T_(x.open),role:"dialog",id:x.contentId,...w,...b,ref:e,style:{...b.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),j_="PopoverClose",GL=m.forwardRef((n,e)=>{const{__scopePopover:i,...a}=n,r=as(j_,i);return l.jsx(je.button,{type:"button",...a,ref:e,onClick:we(n.onClick,()=>r.onOpenChange(!1))})});GL.displayName=j_;var BL="PopoverArrow",HL=m.forwardRef((n,e)=>{const{__scopePopover:i,...a}=n,r=mr(i);return l.jsx(Jf,{...r,...a,ref:e})});HL.displayName=BL;function T_(n){return n?"open":"closed"}var VL=S_,FL=E_,UL=D_,k_=A_;const $L=VL,WL=FL,R_=m.forwardRef(({className:n,align:e="center",sideOffset:i=4,...a},r)=>l.jsx(UL,{children:l.jsx(k_,{ref:r,align:e,sideOffset:i,className:ye("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-popover-content-transform-origin]",n),...a})}));R_.displayName=k_.displayName;function qL(){const n=Fz(),e=[],i=[];for(const a of n){const r=Sn(a);r&&(r.variant==="light"?i.push(a):e.push(a))}return e.sort((a,r)=>(Sn(a)?.name||"").localeCompare(Sn(r)?.name||"")),i.sort((a,r)=>(Sn(a)?.name||"").localeCompare(Sn(r)?.name||"")),{dark:e,light:i}}function qx({presetId:n}){const e=Sn(n);return e?l.jsxs("div",{className:"preset-swatches",children:[l.jsx("span",{className:"preset-swatch",style:{backgroundColor:e.colors.bgPrimary},title:"Background"}),l.jsx("span",{className:"preset-swatch",style:{backgroundColor:e.colors.bgSecondary},title:"Surface"}),l.jsx("span",{className:"preset-swatch",style:{backgroundColor:e.colors.textPrimary},title:"Text"}),l.jsx("span",{className:"preset-swatch",style:{backgroundColor:e.colors.accent},title:"Accent"})]}):null}function YL({currentPreset:n,onSelect:e,className:i=""}){const[a,r]=m.useState(!1),c=m.useMemo(()=>qL(),[]),d=Sn(n),h=f=>{e?.(f),r(!1)};return l.jsxs($L,{open:a,onOpenChange:r,children:[l.jsx(WL,{asChild:!0,children:l.jsxs(Ce,{variant:"outline",className:ye("theme-palette-button",i),"aria-label":`Select theme, current: ${d?.name||n}`,children:[l.jsxs("span",{className:"theme-palette-current",children:[d&&l.jsx("span",{className:"preset-swatch",style:{backgroundColor:d.colors.bgPrimary}}),l.jsx("span",{className:"theme-palette-name",children:d?.name||n})]}),l.jsx(YO,{className:"theme-palette-chevron"})]})}),l.jsx(R_,{className:"theme-palette-popover p-0",align:"start",children:l.jsxs(Em,{children:[l.jsx(Dm,{placeholder:"Search themes..."}),l.jsxs(Am,{children:[l.jsx(Nm,{children:"No theme found."}),l.jsx(nr,{heading:`Dark (${c.dark.length})`,children:c.dark.map(f=>{const p=Sn(f);if(!p)return null;const y=f===n;return l.jsxs(ir,{value:p.name,onSelect:()=>h(f),"data-preset-id":f,children:[l.jsx(qx,{presetId:f}),l.jsx("span",{className:"preset-name",children:p.name}),l.jsx(Ga,{className:ye("preset-check-icon ml-auto",y?"opacity-100":"opacity-0")})]},f)})}),l.jsx(nr,{heading:`Light (${c.light.length})`,children:c.light.map(f=>{const p=Sn(f);if(!p)return null;const y=f===n;return l.jsxs(ir,{value:p.name,onSelect:()=>h(f),"data-preset-id":f,children:[l.jsx(qx,{presetId:f}),l.jsx("span",{className:"preset-name",children:p.name}),l.jsx(Ga,{className:ye("preset-check-icon ml-auto",y?"opacity-100":"opacity-0")})]},f)})})]})]})})]})}var XL=[" ","Enter","ArrowUp","ArrowDown"],QL=[" ","Enter"],Ps="Select",[su,au,ZL]=OS(Ps),[qa]=cn(Ps,[ZL,Wa]),ou=Wa(),[KL,os]=qa(Ps),[JL,eI]=qa(Ps),O_=n=>{const{__scopeSelect:e,children:i,open:a,defaultOpen:r,onOpenChange:c,value:d,defaultValue:h,onValueChange:f,dir:p,name:y,autoComplete:b,disabled:x,required:w,form:E}=n,_=ou(e),[C,D]=m.useState(null),[N,k]=m.useState(null),[T,R]=m.useState(!1),z=Kc(p),[O,A]=_n({prop:a,defaultProp:r??!1,onChange:c,caller:Ps}),[G,U]=_n({prop:d,defaultProp:h,onChange:f,caller:Ps}),B=m.useRef(null),$=C?E||!!C.closest("form"):!0,[ae,ne]=m.useState(new Set),W=Array.from(ae).map(M=>M.props.value).join(";");return l.jsx(Zf,{..._,children:l.jsxs(KL,{required:w,scope:e,trigger:C,onTriggerChange:D,valueNode:N,onValueNodeChange:k,valueNodeHasChildren:T,onValueNodeHasChildrenChange:R,contentId:Mt(),value:G,onValueChange:U,open:O,onOpenChange:A,dir:z,triggerPointerDownPosRef:B,disabled:x,children:[l.jsx(su.Provider,{scope:e,children:l.jsx(JL,{scope:n.__scopeSelect,onNativeOptionAdd:m.useCallback(M=>{ne(K=>new Set(K).add(M))},[]),onNativeOptionRemove:m.useCallback(M=>{ne(K=>{const q=new Set(K);return q.delete(M),q})},[]),children:i})}),$?l.jsxs(sE,{"aria-hidden":!0,required:w,tabIndex:-1,name:y,autoComplete:b,value:G,onChange:M=>U(M.target.value),disabled:x,form:E,children:[G===void 0?l.jsx("option",{value:""}):null,Array.from(ae)]},W):null]})})};O_.displayName=Ps;var z_="SelectTrigger",M_=m.forwardRef((n,e)=>{const{__scopeSelect:i,disabled:a=!1,...r}=n,c=ou(i),d=os(z_,i),h=d.disabled||a,f=Ie(e,d.onTriggerChange),p=au(i),y=m.useRef("touch"),[b,x,w]=oE(_=>{const C=p().filter(k=>!k.disabled),D=C.find(k=>k.value===d.value),N=rE(C,_,D);N!==void 0&&d.onValueChange(N.value)}),E=_=>{h||(d.onOpenChange(!0),w()),_&&(d.triggerPointerDownPosRef.current={x:Math.round(_.pageX),y:Math.round(_.pageY)})};return l.jsx(kc,{asChild:!0,...c,children:l.jsx(je.button,{type:"button",role:"combobox","aria-controls":d.contentId,"aria-expanded":d.open,"aria-required":d.required,"aria-autocomplete":"none",dir:d.dir,"data-state":d.open?"open":"closed",disabled:h,"data-disabled":h?"":void 0,"data-placeholder":aE(d.value)?"":void 0,...r,ref:f,onClick:we(r.onClick,_=>{_.currentTarget.focus(),y.current!=="mouse"&&E(_)}),onPointerDown:we(r.onPointerDown,_=>{y.current=_.pointerType;const C=_.target;C.hasPointerCapture(_.pointerId)&&C.releasePointerCapture(_.pointerId),_.button===0&&_.ctrlKey===!1&&_.pointerType==="mouse"&&(E(_),_.preventDefault())}),onKeyDown:we(r.onKeyDown,_=>{const C=b.current!=="";!(_.ctrlKey||_.altKey||_.metaKey)&&_.key.length===1&&x(_.key),!(C&&_.key===" ")&&XL.includes(_.key)&&(E(),_.preventDefault())})})})});M_.displayName=z_;var P_="SelectValue",L_=m.forwardRef((n,e)=>{const{__scopeSelect:i,className:a,style:r,children:c,placeholder:d="",...h}=n,f=os(P_,i),{onValueNodeHasChildrenChange:p}=f,y=c!==void 0,b=Ie(e,f.onValueNodeChange);return Dt(()=>{p(y)},[p,y]),l.jsx(je.span,{...h,ref:b,style:{pointerEvents:"none"},children:aE(f.value)?l.jsx(l.Fragment,{children:d}):c})});L_.displayName=P_;var tI="SelectIcon",I_=m.forwardRef((n,e)=>{const{__scopeSelect:i,children:a,...r}=n;return l.jsx(je.span,{"aria-hidden":!0,...r,ref:e,children:a||"▼"})});I_.displayName=tI;var nI="SelectPortal",G_=n=>l.jsx(rr,{asChild:!0,...n});G_.displayName=nI;var Ls="SelectContent",B_=m.forwardRef((n,e)=>{const i=os(Ls,n.__scopeSelect),[a,r]=m.useState();if(Dt(()=>{r(new DocumentFragment)},[]),!i.open){const c=a;return c?sr.createPortal(l.jsx(H_,{scope:n.__scopeSelect,children:l.jsx(su.Slot,{scope:n.__scopeSelect,children:l.jsx("div",{children:n.children})})}),c):null}return l.jsx(V_,{...n,ref:e})});B_.displayName=Ls;var Rn=10,[H_,rs]=qa(Ls),iI="SelectContentImpl",sI=Pa("SelectContent.RemoveScroll"),V_=m.forwardRef((n,e)=>{const{__scopeSelect:i,position:a="item-aligned",onCloseAutoFocus:r,onEscapeKeyDown:c,onPointerDownOutside:d,side:h,sideOffset:f,align:p,alignOffset:y,arrowPadding:b,collisionBoundary:x,collisionPadding:w,sticky:E,hideWhenDetached:_,avoidCollisions:C,...D}=n,N=os(Ls,i),[k,T]=m.useState(null),[R,z]=m.useState(null),O=Ie(e,X=>T(X)),[A,G]=m.useState(null),[U,B]=m.useState(null),$=au(i),[ae,ne]=m.useState(!1),W=m.useRef(!1);m.useEffect(()=>{if(k)return mm(k)},[k]),fm();const M=m.useCallback(X=>{const[ce,...de]=$().map(Ne=>Ne.ref.current),[De]=de.slice(-1),Ge=document.activeElement;for(const Ne of X)if(Ne===Ge||(Ne?.scrollIntoView({block:"nearest"}),Ne===ce&&R&&(R.scrollTop=0),Ne===De&&R&&(R.scrollTop=R.scrollHeight),Ne?.focus(),document.activeElement!==Ge))return},[$,R]),K=m.useCallback(()=>M([A,k]),[M,A,k]);m.useEffect(()=>{ae&&K()},[ae,K]);const{onOpenChange:q,triggerPointerDownPosRef:he}=N;m.useEffect(()=>{if(k){let X={x:0,y:0};const ce=De=>{X={x:Math.abs(Math.round(De.pageX)-(he.current?.x??0)),y:Math.abs(Math.round(De.pageY)-(he.current?.y??0))}},de=De=>{X.x<=10&&X.y<=10?De.preventDefault():k.contains(De.target)||q(!1),document.removeEventListener("pointermove",ce),he.current=null};return he.current!==null&&(document.addEventListener("pointermove",ce),document.addEventListener("pointerup",de,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",ce),document.removeEventListener("pointerup",de,{capture:!0})}}},[k,q,he]),m.useEffect(()=>{const X=()=>q(!1);return window.addEventListener("blur",X),window.addEventListener("resize",X),()=>{window.removeEventListener("blur",X),window.removeEventListener("resize",X)}},[q]);const[Se,I]=oE(X=>{const ce=$().filter(Ge=>!Ge.disabled),de=ce.find(Ge=>Ge.ref.current===document.activeElement),De=rE(ce,X,de);De&&setTimeout(()=>De.ref.current.focus())}),L=m.useCallback((X,ce,de)=>{const De=!W.current&&!de;(N.value!==void 0&&N.value===ce||De)&&(G(X),De&&(W.current=!0))},[N.value]),ee=m.useCallback(()=>k?.focus(),[k]),V=m.useCallback((X,ce,de)=>{const De=!W.current&&!de;(N.value!==void 0&&N.value===ce||De)&&B(X)},[N.value]),Y=a==="popper"?Rf:F_,le=Y===Rf?{side:h,sideOffset:f,align:p,alignOffset:y,arrowPadding:b,collisionBoundary:x,collisionPadding:w,sticky:E,hideWhenDetached:_,avoidCollisions:C}:{};return l.jsx(H_,{scope:i,content:k,viewport:R,onViewportChange:z,itemRefCallback:L,selectedItem:A,onItemLeave:ee,itemTextRefCallback:V,focusSelectedItem:K,selectedItemText:U,position:a,isPositioned:ae,searchRef:Se,children:l.jsx(Vc,{as:sI,allowPinchZoom:!0,children:l.jsx(Bc,{asChild:!0,trapped:N.open,onMountAutoFocus:X=>{X.preventDefault()},onUnmountAutoFocus:we(r,X=>{N.trigger?.focus({preventScroll:!0}),X.preventDefault()}),children:l.jsx(ar,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:X=>X.preventDefault(),onDismiss:()=>N.onOpenChange(!1),children:l.jsx(Y,{role:"listbox",id:N.contentId,"data-state":N.open?"open":"closed",dir:N.dir,onContextMenu:X=>X.preventDefault(),...D,...le,onPlaced:()=>ne(!0),ref:O,style:{display:"flex",flexDirection:"column",outline:"none",...D.style},onKeyDown:we(D.onKeyDown,X=>{const ce=X.ctrlKey||X.altKey||X.metaKey;if(X.key==="Tab"&&X.preventDefault(),!ce&&X.key.length===1&&I(X.key),["ArrowUp","ArrowDown","Home","End"].includes(X.key)){let De=$().filter(Ge=>!Ge.disabled).map(Ge=>Ge.ref.current);if(["ArrowUp","End"].includes(X.key)&&(De=De.slice().reverse()),["ArrowUp","ArrowDown"].includes(X.key)){const Ge=X.target,Ne=De.indexOf(Ge);De=De.slice(Ne+1)}setTimeout(()=>M(De)),X.preventDefault()}})})})})})})});V_.displayName=iI;var aI="SelectItemAlignedPosition",F_=m.forwardRef((n,e)=>{const{__scopeSelect:i,onPlaced:a,...r}=n,c=os(Ls,i),d=rs(Ls,i),[h,f]=m.useState(null),[p,y]=m.useState(null),b=Ie(e,O=>y(O)),x=au(i),w=m.useRef(!1),E=m.useRef(!0),{viewport:_,selectedItem:C,selectedItemText:D,focusSelectedItem:N}=d,k=m.useCallback(()=>{if(c.trigger&&c.valueNode&&h&&p&&_&&C&&D){const O=c.trigger.getBoundingClientRect(),A=p.getBoundingClientRect(),G=c.valueNode.getBoundingClientRect(),U=D.getBoundingClientRect();if(c.dir!=="rtl"){const Ge=U.left-A.left,Ne=G.left-Ge,dt=O.left-Ne,rt=O.width+dt,An=Math.max(rt,A.width),ei=window.innerWidth-Rn,Ya=Tf(Ne,[Rn,Math.max(Rn,ei-An)]);h.style.minWidth=rt+"px",h.style.left=Ya+"px"}else{const Ge=A.right-U.right,Ne=window.innerWidth-G.right-Ge,dt=window.innerWidth-O.right-Ne,rt=O.width+dt,An=Math.max(rt,A.width),ei=window.innerWidth-Rn,Ya=Tf(Ne,[Rn,Math.max(Rn,ei-An)]);h.style.minWidth=rt+"px",h.style.right=Ya+"px"}const B=x(),$=window.innerHeight-Rn*2,ae=_.scrollHeight,ne=window.getComputedStyle(p),W=parseInt(ne.borderTopWidth,10),M=parseInt(ne.paddingTop,10),K=parseInt(ne.borderBottomWidth,10),q=parseInt(ne.paddingBottom,10),he=W+M+ae+q+K,Se=Math.min(C.offsetHeight*5,he),I=window.getComputedStyle(_),L=parseInt(I.paddingTop,10),ee=parseInt(I.paddingBottom,10),V=O.top+O.height/2-Rn,Y=$-V,le=C.offsetHeight/2,X=C.offsetTop+le,ce=W+M+X,de=he-ce;if(ce<=V){const Ge=B.length>0&&C===B[B.length-1].ref.current;h.style.bottom="0px";const Ne=p.clientHeight-_.offsetTop-_.offsetHeight,dt=Math.max(Y,le+(Ge?ee:0)+Ne+K),rt=ce+dt;h.style.height=rt+"px"}else{const Ge=B.length>0&&C===B[0].ref.current;h.style.top="0px";const dt=Math.max(V,W+_.offsetTop+(Ge?L:0)+le)+de;h.style.height=dt+"px",_.scrollTop=ce-V+_.offsetTop}h.style.margin=`${Rn}px 0`,h.style.minHeight=Se+"px",h.style.maxHeight=$+"px",a?.(),requestAnimationFrame(()=>w.current=!0)}},[x,c.trigger,c.valueNode,h,p,_,C,D,c.dir,a]);Dt(()=>k(),[k]);const[T,R]=m.useState();Dt(()=>{p&&R(window.getComputedStyle(p).zIndex)},[p]);const z=m.useCallback(O=>{O&&E.current===!0&&(k(),N?.(),E.current=!1)},[k,N]);return l.jsx(rI,{scope:i,contentWrapper:h,shouldExpandOnScrollRef:w,onScrollButtonChange:z,children:l.jsx("div",{ref:f,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:T},children:l.jsx(je.div,{...r,ref:b,style:{boxSizing:"border-box",maxHeight:"100%",...r.style}})})})});F_.displayName=aI;var oI="SelectPopperPosition",Rf=m.forwardRef((n,e)=>{const{__scopeSelect:i,align:a="start",collisionPadding:r=Rn,...c}=n,d=ou(i);return l.jsx(Kf,{...d,...c,ref:e,align:a,collisionPadding:r,style:{boxSizing:"border-box",...c.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});Rf.displayName=oI;var[rI,Qm]=qa(Ls,{}),Of="SelectViewport",U_=m.forwardRef((n,e)=>{const{__scopeSelect:i,nonce:a,...r}=n,c=rs(Of,i),d=Qm(Of,i),h=Ie(e,c.onViewportChange),f=m.useRef(0);return l.jsxs(l.Fragment,{children:[l.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:a}),l.jsx(su.Slot,{scope:i,children:l.jsx(je.div,{"data-radix-select-viewport":"",role:"presentation",...r,ref:h,style:{position:"relative",flex:1,overflow:"hidden auto",...r.style},onScroll:we(r.onScroll,p=>{const y=p.currentTarget,{contentWrapper:b,shouldExpandOnScrollRef:x}=d;if(x?.current&&b){const w=Math.abs(f.current-y.scrollTop);if(w>0){const E=window.innerHeight-Rn*2,_=parseFloat(b.style.minHeight),C=parseFloat(b.style.height),D=Math.max(_,C);if(D<E){const N=D+w,k=Math.min(E,N),T=N-k;b.style.height=k+"px",b.style.bottom==="0px"&&(y.scrollTop=T>0?T:0,b.style.justifyContent="flex-end")}}}f.current=y.scrollTop})})})]})});U_.displayName=Of;var $_="SelectGroup",[lI,cI]=qa($_),W_=m.forwardRef((n,e)=>{const{__scopeSelect:i,...a}=n,r=Mt();return l.jsx(lI,{scope:i,id:r,children:l.jsx(je.div,{role:"group","aria-labelledby":r,...a,ref:e})})});W_.displayName=$_;var q_="SelectLabel",Y_=m.forwardRef((n,e)=>{const{__scopeSelect:i,...a}=n,r=cI(q_,i);return l.jsx(je.div,{id:r.id,...a,ref:e})});Y_.displayName=q_;var Ec="SelectItem",[uI,X_]=qa(Ec),Q_=m.forwardRef((n,e)=>{const{__scopeSelect:i,value:a,disabled:r=!1,textValue:c,...d}=n,h=os(Ec,i),f=rs(Ec,i),p=h.value===a,[y,b]=m.useState(c??""),[x,w]=m.useState(!1),E=Ie(e,N=>f.itemRefCallback?.(N,a,r)),_=Mt(),C=m.useRef("touch"),D=()=>{r||(h.onValueChange(a),h.onOpenChange(!1))};if(a==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return l.jsx(uI,{scope:i,value:a,disabled:r,textId:_,isSelected:p,onItemTextChange:m.useCallback(N=>{b(k=>k||(N?.textContent??"").trim())},[]),children:l.jsx(su.ItemSlot,{scope:i,value:a,disabled:r,textValue:y,children:l.jsx(je.div,{role:"option","aria-labelledby":_,"data-highlighted":x?"":void 0,"aria-selected":p&&x,"data-state":p?"checked":"unchecked","aria-disabled":r||void 0,"data-disabled":r?"":void 0,tabIndex:r?void 0:-1,...d,ref:E,onFocus:we(d.onFocus,()=>w(!0)),onBlur:we(d.onBlur,()=>w(!1)),onClick:we(d.onClick,()=>{C.current!=="mouse"&&D()}),onPointerUp:we(d.onPointerUp,()=>{C.current==="mouse"&&D()}),onPointerDown:we(d.onPointerDown,N=>{C.current=N.pointerType}),onPointerMove:we(d.onPointerMove,N=>{C.current=N.pointerType,r?f.onItemLeave?.():C.current==="mouse"&&N.currentTarget.focus({preventScroll:!0})}),onPointerLeave:we(d.onPointerLeave,N=>{N.currentTarget===document.activeElement&&f.onItemLeave?.()}),onKeyDown:we(d.onKeyDown,N=>{f.searchRef?.current!==""&&N.key===" "||(QL.includes(N.key)&&D(),N.key===" "&&N.preventDefault())})})})})});Q_.displayName=Ec;var Yo="SelectItemText",Z_=m.forwardRef((n,e)=>{const{__scopeSelect:i,className:a,style:r,...c}=n,d=os(Yo,i),h=rs(Yo,i),f=X_(Yo,i),p=eI(Yo,i),[y,b]=m.useState(null),x=Ie(e,D=>b(D),f.onItemTextChange,D=>h.itemTextRefCallback?.(D,f.value,f.disabled)),w=y?.textContent,E=m.useMemo(()=>l.jsx("option",{value:f.value,disabled:f.disabled,children:w},f.value),[f.disabled,f.value,w]),{onNativeOptionAdd:_,onNativeOptionRemove:C}=p;return Dt(()=>(_(E),()=>C(E)),[_,C,E]),l.jsxs(l.Fragment,{children:[l.jsx(je.span,{id:f.textId,...c,ref:x}),f.isSelected&&d.valueNode&&!d.valueNodeHasChildren?sr.createPortal(c.children,d.valueNode):null]})});Z_.displayName=Yo;var K_="SelectItemIndicator",J_=m.forwardRef((n,e)=>{const{__scopeSelect:i,...a}=n;return X_(K_,i).isSelected?l.jsx(je.span,{"aria-hidden":!0,...a,ref:e}):null});J_.displayName=K_;var zf="SelectScrollUpButton",eE=m.forwardRef((n,e)=>{const i=rs(zf,n.__scopeSelect),a=Qm(zf,n.__scopeSelect),[r,c]=m.useState(!1),d=Ie(e,a.onScrollButtonChange);return Dt(()=>{if(i.viewport&&i.isPositioned){let h=function(){const p=f.scrollTop>0;c(p)};const f=i.viewport;return h(),f.addEventListener("scroll",h),()=>f.removeEventListener("scroll",h)}},[i.viewport,i.isPositioned]),r?l.jsx(nE,{...n,ref:d,onAutoScroll:()=>{const{viewport:h,selectedItem:f}=i;h&&f&&(h.scrollTop=h.scrollTop-f.offsetHeight)}}):null});eE.displayName=zf;var Mf="SelectScrollDownButton",tE=m.forwardRef((n,e)=>{const i=rs(Mf,n.__scopeSelect),a=Qm(Mf,n.__scopeSelect),[r,c]=m.useState(!1),d=Ie(e,a.onScrollButtonChange);return Dt(()=>{if(i.viewport&&i.isPositioned){let h=function(){const p=f.scrollHeight-f.clientHeight,y=Math.ceil(f.scrollTop)<p;c(y)};const f=i.viewport;return h(),f.addEventListener("scroll",h),()=>f.removeEventListener("scroll",h)}},[i.viewport,i.isPositioned]),r?l.jsx(nE,{...n,ref:d,onAutoScroll:()=>{const{viewport:h,selectedItem:f}=i;h&&f&&(h.scrollTop=h.scrollTop+f.offsetHeight)}}):null});tE.displayName=Mf;var nE=m.forwardRef((n,e)=>{const{__scopeSelect:i,onAutoScroll:a,...r}=n,c=rs("SelectScrollButton",i),d=m.useRef(null),h=au(i),f=m.useCallback(()=>{d.current!==null&&(window.clearInterval(d.current),d.current=null)},[]);return m.useEffect(()=>()=>f(),[f]),Dt(()=>{h().find(y=>y.ref.current===document.activeElement)?.ref.current?.scrollIntoView({block:"nearest"})},[h]),l.jsx(je.div,{"aria-hidden":!0,...r,ref:e,style:{flexShrink:0,...r.style},onPointerDown:we(r.onPointerDown,()=>{d.current===null&&(d.current=window.setInterval(a,50))}),onPointerMove:we(r.onPointerMove,()=>{c.onItemLeave?.(),d.current===null&&(d.current=window.setInterval(a,50))}),onPointerLeave:we(r.onPointerLeave,()=>{f()})})}),dI="SelectSeparator",iE=m.forwardRef((n,e)=>{const{__scopeSelect:i,...a}=n;return l.jsx(je.div,{"aria-hidden":!0,...a,ref:e})});iE.displayName=dI;var Pf="SelectArrow",hI=m.forwardRef((n,e)=>{const{__scopeSelect:i,...a}=n,r=ou(i),c=os(Pf,i),d=rs(Pf,i);return c.open&&d.position==="popper"?l.jsx(Jf,{...r,...a,ref:e}):null});hI.displayName=Pf;var fI="SelectBubbleInput",sE=m.forwardRef(({__scopeSelect:n,value:e,...i},a)=>{const r=m.useRef(null),c=Ie(a,r),d=Ym(e);return m.useEffect(()=>{const h=r.current;if(!h)return;const f=window.HTMLSelectElement.prototype,y=Object.getOwnPropertyDescriptor(f,"value").set;if(d!==e&&y){const b=new Event("change",{bubbles:!0});y.call(h,e),h.dispatchEvent(b)}},[d,e]),l.jsx(je.select,{...i,style:{...Yw,...i.style},ref:c,defaultValue:e})});sE.displayName=fI;function aE(n){return n===""||n===void 0}function oE(n){const e=Gt(n),i=m.useRef(""),a=m.useRef(0),r=m.useCallback(d=>{const h=i.current+d;e(h),(function f(p){i.current=p,window.clearTimeout(a.current),p!==""&&(a.current=window.setTimeout(()=>f(""),1e3))})(h)},[e]),c=m.useCallback(()=>{i.current="",window.clearTimeout(a.current)},[]);return m.useEffect(()=>()=>window.clearTimeout(a.current),[]),[i,r,c]}function rE(n,e,i){const r=e.length>1&&Array.from(e).every(p=>p===e[0])?e[0]:e,c=i?n.indexOf(i):-1;let d=mI(n,Math.max(c,0));r.length===1&&(d=d.filter(p=>p!==i));const f=d.find(p=>p.textValue.toLowerCase().startsWith(r.toLowerCase()));return f!==i?f:void 0}function mI(n,e){return n.map((i,a)=>n[(e+a)%n.length])}var pI=O_,lE=M_,gI=L_,vI=I_,yI=G_,cE=B_,bI=U_,xI=W_,uE=Y_,dE=Q_,wI=Z_,SI=J_,hE=eE,fE=tE,mE=iE;const CI=pI,Jh=xI,_I=gI,pE=m.forwardRef(({className:n,children:e,...i},a)=>l.jsxs(lE,{ref:a,className:ye("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background data-[placeholder]:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",n),...i,children:[e,l.jsx(vI,{asChild:!0,children:l.jsx(cS,{className:"h-4 w-4 opacity-50"})})]}));pE.displayName=lE.displayName;const gE=m.forwardRef(({className:n,...e},i)=>l.jsx(hE,{ref:i,className:ye("flex cursor-default items-center justify-center py-1",n),...e,children:l.jsx(WO,{className:"h-4 w-4"})}));gE.displayName=hE.displayName;const vE=m.forwardRef(({className:n,...e},i)=>l.jsx(fE,{ref:i,className:ye("flex cursor-default items-center justify-center py-1",n),...e,children:l.jsx(cS,{className:"h-4 w-4"})}));vE.displayName=fE.displayName;const yE=m.forwardRef(({className:n,children:e,position:i="popper",...a},r)=>l.jsx(yI,{children:l.jsxs(cE,{ref:r,className:ye("relative z-50 max-h-[--radix-select-content-available-height] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-select-content-transform-origin]",i==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",n),position:i,...a,children:[l.jsx(gE,{}),l.jsx(bI,{className:ye("p-1",i==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:e}),l.jsx(vE,{})]})}));yE.displayName=cE.displayName;const sc=m.forwardRef(({className:n,...e},i)=>l.jsx(uE,{ref:i,className:ye("px-2 py-1.5 text-sm font-semibold",n),...e}));sc.displayName=uE.displayName;const ac=m.forwardRef(({className:n,children:e,...i},a)=>l.jsxs(dE,{ref:a,className:ye("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",n),...i,children:[l.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:l.jsx(SI,{children:l.jsx(Ga,{className:"h-4 w-4"})})}),l.jsx(wI,{children:e})]}));ac.displayName=dE.displayName;const EI=m.forwardRef(({className:n,...e},i)=>l.jsx(mE,{ref:i,className:ye("-mx-1 my-1 h-px bg-muted",n),...e}));EI.displayName=mE.displayName;function DI(n,e){const i=n.getUint16(4);for(let a=0;a<i;a++){const r=12+a*16;if(String.fromCharCode(n.getUint8(r),n.getUint8(r+1),n.getUint8(r+2),n.getUint8(r+3))===e)return{offset:n.getUint32(r+8),length:n.getUint32(r+12)}}return null}async function AI(n){try{const i=await(await n.blob()).arrayBuffer(),a=new DataView(i),r=DI(a,"post");return r?a.getUint32(r.offset+12)!==0:!1}catch{return!1}}const Zm="cyclist-system-fonts";function NI(){try{const n=localStorage.getItem(Zm);if(!n)return null;const e=JSON.parse(n);return e.fonts?.length>0?e.fonts:null}catch{return null}}function jI(n,e){try{const i={fonts:n,count:e};localStorage.setItem(Zm,JSON.stringify(i))}catch{}}let Xl=null;async function TI(){return Xl||(Xl=(async()=>{if(!("queryLocalFonts"in window))return[];try{const n=await window.queryLocalFonts(),e=new Map;for(const h of n)e.has(h.family)||e.set(h.family,h);const i=e.size,a=NI();if(a&&a.length>0)try{const h=localStorage.getItem(Zm);if(h&&JSON.parse(h).count===i)return a}catch{}const r=Array.from(e.entries()),c=await Promise.all(r.map(([,h])=>AI(h))),d=r.map(([h],f)=>({family:h,isMonospace:c[f]}));return d.sort((h,f)=>h.family.localeCompare(f.family)),jI(d,i),d}catch{return[]}})(),Xl)}const Ql="system-font:";function Yx({type:n,currentFont:e,customFont:i,onSelect:a,onCustomFontChange:r,className:c=""}){const[d,h]=m.useState(i||""),[f,p]=m.useState([]),[y,b]=m.useState(!1),x=n==="ui"?vS:yS,w=x.find(R=>R.id===e);m.useEffect(()=>{y||TI().then(R=>{p(R),b(!0)})},[y]);const E=m.useMemo(()=>{let R=f;return R=R.filter(z=>/^[\x20-\x7E\u00C0-\u024F]+$/.test(z.family)),n==="code"&&(R=R.filter(z=>z.isMonospace)),R},[f,n]),_=m.useMemo(()=>x.filter(R=>!R.isCustom),[x]);m.useEffect(()=>{i!==void 0&&h(i)},[i]);const C=m.useMemo(()=>e==="custom"&&d?f.some(z=>z.family===d)?`${Ql}${d}`:"custom":e,[e,d,f]),D=m.useCallback(R=>{if(R.startsWith(Ql)){const z=R.slice(Ql.length);a("custom",z)}else a(R==="custom"?"custom":R)},[a]),N=m.useCallback(R=>{const z=R.target.value;h(z),r?.(z),e==="custom"&&a("custom",z)},[e,a,r]),k=f.length>0,T=e==="custom"&&!k;return l.jsxs("div",{className:`font-picker ${c}`,children:[l.jsxs(CI,{value:C,onValueChange:D,children:[l.jsx(pE,{className:"font-picker-trigger","aria-label":`Select ${n} font`,style:{fontFamily:w?.fontFamily||(d?`"${d}"`:"inherit")},children:l.jsx(_I,{placeholder:"Select font..."})}),l.jsxs(yE,{className:"max-h-[300px]",children:[_.length>0&&l.jsxs(Jh,{children:[l.jsx(sc,{children:"Presets"}),_.map(R=>l.jsx(ac,{value:R.id,style:{fontFamily:R.fontFamily||"inherit"},children:l.jsxs("span",{className:"font-picker-item-content",children:[l.jsx("span",{className:"font-name",children:R.name}),l.jsx("span",{className:"font-preview",style:{fontFamily:R.fontFamily},children:"Aa"})]})},R.id))]}),k&&E.length>0&&l.jsxs(Jh,{children:[l.jsxs(sc,{children:["System Fonts (",E.length,")"]}),E.map(R=>l.jsx(ac,{value:`${Ql}${R.family}`,style:{fontFamily:`"${R.family}", inherit`},children:l.jsxs("span",{className:"font-picker-item-content",children:[l.jsx("span",{className:"font-name",children:R.family}),l.jsx("span",{className:"font-preview",style:{fontFamily:`"${R.family}"`},children:"Aa"})]})},R.family))]}),!k&&y&&l.jsxs(Jh,{children:[l.jsx(sc,{children:"Custom"}),l.jsx(ac,{value:"custom",children:"Custom..."})]})]})]}),T&&l.jsx("input",{type:"text",className:"font-picker-custom-input",value:d,onChange:N,placeholder:"Enter font family...","aria-label":"Custom font family"})]})}const kI=["xs","sm","base","lg","xl"];function Xx({currentSize:n,onSelect:e,className:i=""}){return l.jsx(St,{delayDuration:300,children:l.jsx("div",{className:`font-size-picker ${i}`,role:"group","aria-label":"Font size",children:kI.map(a=>l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:a===n?"secondary":"ghost",size:"sm",className:`font-size-option ${a===n?"active":""}`,"data-size":a,onClick:()=>e(a),"aria-pressed":a===n,children:a.toUpperCase()})}),l.jsx(Te,{children:`${Cf[a]} (${a})`})]},a))})})}const Qx={S:0,A:1,B:2};function bE(){const[n,e]=m.useState(null),[i,a]=m.useState([]),[r,c]=m.useState(!1),[d,h]=m.useState(ic),[f,p]=m.useState(Tm);m.useEffect(()=>{async function C(){try{console.log("[SettingsPanel] Loading settings via REST");const T=await fetch("/api/settings");if(T.ok){const R=await T.json();console.log("[SettingsPanel] Settings loaded:",R),e(R)}}catch(T){console.error("[SettingsPanel] Failed to load settings:",T)}}async function D(){try{const T=await fetch("/api/settings/themes");if(T.ok){const R=await T.json();a(R.themes||[])}}catch(T){console.error("[SettingsPanel] Failed to load themes:",T)}}C(),D(),console.log("[SettingsPanel] Connecting to /ws/settings for real-time sync");const N=window.location.protocol==="https:"?"wss:":"ws:",k=new WebSocket(`${N}//${window.location.host}/ws/settings`);return k.onmessage=T=>{try{const R=JSON.parse(T.data);(R.type==="init"||R.type==="update")&&(console.log("[SettingsPanel] Settings update via WebSocket:",R.settings),e(R.settings))}catch(R){console.error("[SettingsPanel] Failed to parse WebSocket message:",R)}},k.onerror=T=>{console.error("[SettingsPanel] WebSocket error:",T)},wS().then(T=>{_f(T),h(T)}),bS().then(T=>{p(T),nc(T)}),()=>k.close()},[]);const y=m.useMemo(()=>[...i].sort((C,D)=>{const N=(Qx[C.tier]??3)-(Qx[D.tier]??3);return N!==0?N:C.name.localeCompare(D.name)}),[i]),b=m.useCallback(async C=>{if(n){c(!0);try{const D={...n,pennyfarthing:{...n.pennyfarthing,theme:C}};await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({pennyfarthing:{theme:C}})}),e(D)}finally{c(!1)}}},[n]),x=m.useCallback(async(C,D,N)=>{if(n){console.log(`[SettingsPanel] Toggle ${C}.${D} = ${N}`),c(!0);try{const k={...n,[C]:{...n[C],[D]:N}};console.log("[SettingsPanel] Saving via REST"),await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({[C]:{[D]:N}})}),console.log("[SettingsPanel] Save complete, updating local state"),e(k)}finally{c(!1)}}},[n]),w=m.useCallback(async C=>{c(!0);try{_f(C),await Uz(C),h(C)}finally{c(!1)}},[]),E=m.useCallback(async(C,D,N)=>{c(!0);try{const k={...f,[C==="ui"?"uiFont":"codeFont"]:D,...D==="custom"&&N?{[C==="ui"?"customUiFont":"customCodeFont"]:N}:{}};nc(k),await px(k),p(k)}finally{c(!1)}},[f]),_=m.useCallback(async(C,D)=>{c(!0);try{const N={...f,[C==="ui"?"uiFontSize":"codeFontSize"]:D};nc(N),await px(N),p(N)}finally{c(!1)}},[f]);return n?l.jsxs("div",{className:"settings-panel","data-testid":"settings-panel",children:[l.jsxs("section",{className:"settings-section",children:[l.jsx("h4",{children:"Theme"}),l.jsx("select",{value:n.pennyfarthing?.theme||"",onChange:C=>b(C.target.value),disabled:r,className:"theme-select",children:y.map(C=>l.jsxs("option",{value:C.id,children:["[",C.tier||"Unranked","] ",C.name]},C.id))})]}),l.jsx(Rt,{className:"my-2"}),l.jsxs("section",{className:"settings-section",children:[l.jsx("h4",{children:"Color Palette"}),l.jsx(YL,{currentPreset:d,onSelect:w})]}),l.jsx(Rt,{className:"my-2"}),l.jsxs("section",{className:"settings-section",children:[l.jsx("h4",{children:"Fonts"}),l.jsxs("div",{className:"font-setting",children:[l.jsx("label",{children:"UI Font"}),l.jsx(Yx,{type:"ui",currentFont:f.uiFont,customFont:f.customUiFont,onSelect:(C,D)=>E("ui",C,D)}),l.jsx(Xx,{currentSize:f.uiFontSize,onSelect:C=>_("ui",C)})]}),l.jsxs("div",{className:"font-setting",children:[l.jsx("label",{children:"Code Font"}),l.jsx(Yx,{type:"code",currentFont:f.codeFont,customFont:f.customCodeFont,onSelect:(C,D)=>E("code",C,D)}),l.jsx(Xx,{currentSize:f.codeFontSize,onSelect:C=>_("code",C)})]})]}),l.jsx(Rt,{className:"my-2"}),l.jsxs("section",{className:"settings-section",children:[l.jsx("h4",{children:"Workflow"}),window.__CYCLIST_MODE__==="cyclist"&&l.jsxs("div",{className:"toggle-setting",children:[l.jsx(kf,{checked:n.workflow?.bell_mode||!1,onCheckedChange:C=>x("workflow","bell_mode",C),disabled:r}),"Bell Mode",l.jsx("span",{className:"setting-description",children:"Inject queued messages via PostToolUse hook instead of waiting"})]}),l.jsxs("div",{className:"toggle-setting",children:[l.jsx(kf,{checked:n.workflow?.relay_mode||!1,onCheckedChange:C=>x("workflow","relay_mode",C),disabled:r}),"Relay Mode",l.jsx("span",{className:"setting-description",children:"Auto-handoff to next agent"})]})]})]}):l.jsx("div",{className:"settings-panel loading","data-testid":"settings-panel",children:l.jsxs("div",{className:"space-y-4 p-2",children:[l.jsx(fe,{className:"h-4 w-24"}),l.jsx(fe,{className:"h-8 w-full"}),l.jsx(fe,{className:"h-4 w-32"}),l.jsx(fe,{className:"h-8 w-full"}),l.jsx(fe,{className:"h-4 w-20"}),l.jsx(fe,{className:"h-6 w-48"})]})})}function RI(n){return new Date(n).toLocaleTimeString()}function Zx(n){return n===void 0?"-":n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function Kx(n,e=60){return n?n.length<=e?n:n.substring(0,e)+"...":"-"}function OI(n){return n===void 0?"":n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}function zI(n){if(!n)return"";const e=n.split("/");return e.length<=3?n:".../"+e.slice(-3).join("/")}function It({label:n,value:e,mono:i}){return e==null||e===""?null:l.jsxs("div",{className:"detail-row",children:[l.jsx("span",{className:"detail-label",children:n}),l.jsx("span",{className:i?"detail-value font-mono":"detail-value",children:e})]})}function xE(){const[n,e]=m.useState([]),[i,a]=m.useState(null),[r,c]=m.useState([]),[d,h]=m.useState(""),[f,p]=m.useState(""),[y,b]=m.useState(!0),[x,w]=m.useState(null),[E,_]=m.useState(null),C=m.useRef(!0),D=m.useRef(null),N=m.useRef(null);m.useEffect(()=>{const A=N.current;if(!A)return;const G=()=>{C.current=A.scrollTop===0};return A.addEventListener("scroll",G),()=>A.removeEventListener("scroll",G)},[y]),m.useEffect(()=>{C.current&&D.current&&n.length>0&&D.current.scrollIntoView()},[n]);const k=m.useCallback(async()=>{try{const A=new URLSearchParams;d&&A.set("toolType",d),f&&A.set("status",f),A.set("limit","200");const G=await fetch(`/api/audit-log?${A}`);if(!G.ok)throw new Error("Failed to fetch audit log");const U=await G.json();e(U.entries||[]),w(null)}catch(A){w(A instanceof Error?A.message:"Unknown error")}},[d,f]),T=m.useCallback(async()=>{try{const A=await fetch("/api/audit-log/stats");if(!A.ok)throw new Error("Failed to fetch stats");const G=await A.json();a(G)}catch(A){console.error("[AuditLogPanel] Stats error:",A)}},[]),R=m.useCallback(async()=>{try{const A=await fetch("/api/audit-log/types");if(!A.ok)throw new Error("Failed to fetch types");const G=await A.json();c(G.types||[])}catch(A){console.error("[AuditLogPanel] Types error:",A)}},[]);m.useEffect(()=>{b(!0),Promise.all([k(),T(),R()]).finally(()=>{b(!1)});const A=new WebSocket(`ws://${window.location.host}/ws/spans`);return A.onmessage=G=>{try{const U=JSON.parse(G.data);U.type==="span"&&U.span&&(e(B=>[U.span,...B].slice(0,200)),T())}catch(U){console.error("[AuditLogPanel] WebSocket parse error:",U)}},()=>A.close()},[k,T,R]),m.useEffect(()=>{k()},[d,f,k]);const z=async A=>{try{const G=new URLSearchParams;G.set("format",A),G.set("download","true"),d&&G.set("toolType",d);const U=await fetch(`/api/audit-log/export?${G}`);if(!U.ok)throw new Error("Export failed");const B=await U.blob(),$=URL.createObjectURL(B),ae=document.createElement("a");ae.href=$,ae.download=`audit-log.${A}`,ae.click(),URL.revokeObjectURL($)}catch(G){console.error("[AuditLogPanel] Export error:",G)}},O=async()=>{if(confirm("Clear all audit log entries?"))try{if(!(await fetch("/api/audit-log",{method:"DELETE"})).ok)throw new Error("Clear failed");e([]),T()}catch(A){console.error("[AuditLogPanel] Clear error:",A)}};return y?l.jsxs("div",{className:"audit-log-panel p-4 space-y-3",children:[l.jsxs("div",{className:"flex gap-4",children:[l.jsx(fe,{className:"h-4 w-20"}),l.jsx(fe,{className:"h-4 w-24"}),l.jsx(fe,{className:"h-4 w-20"})]}),l.jsx(Rt,{}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(fe,{className:"h-6 w-full"}),l.jsx(fe,{className:"h-6 w-full"}),l.jsx(fe,{className:"h-6 w-full"}),l.jsx(fe,{className:"h-6 w-3/4"})]})]}):x?l.jsx("div",{className:"audit-log-panel p-4",children:l.jsxs("div",{className:"text-error",children:["Error: ",x]})}):l.jsx("div",{className:"audit-log-panel flex flex-col h-full",children:l.jsxs(St,{delayDuration:300,children:[i&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"audit-log-stats flex gap-4 p-2 text-sm",children:[l.jsxs("span",{className:"text-muted",children:["Total: ",l.jsx("strong",{children:i.total})]}),l.jsxs("span",{className:"text-success",children:["Success: ",l.jsx("strong",{children:i.successCount})]}),l.jsxs("span",{className:"text-error",children:["Errors: ",l.jsx("strong",{children:i.errorCount})]})]}),l.jsx(Rt,{})]}),l.jsxs("div",{className:"audit-log-toolbar flex p-2 items-center",children:[l.jsxs("select",{value:d,onChange:A=>h(A.target.value),children:[l.jsx("option",{value:"",children:"All Tools"}),r.map(A=>l.jsx("option",{value:A,children:A},A))]}),l.jsxs("select",{value:f,onChange:A=>p(A.target.value),children:[l.jsx("option",{value:"",children:"All Status"}),l.jsx("option",{value:"success",children:"Success"}),l.jsx("option",{value:"error",children:"Errors"})]}),l.jsx("div",{className:"flex-1"}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"sm",className:"audit-log-btn",onClick:()=>z("json"),children:"JSON"})}),l.jsx(Te,{children:"Export as JSON"})]}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"sm",className:"audit-log-btn",onClick:()=>z("csv"),children:"CSV"})}),l.jsx(Te,{children:"Export as CSV"})]}),l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx(Ce,{variant:"ghost",size:"sm",className:"audit-log-btn audit-log-btn-clear",onClick:O,children:"Clear"})}),l.jsx(Te,{children:"Clear audit log"})]})]}),l.jsxs("div",{ref:N,className:"audit-log-entries flex-1",style:{overflow:"auto"},children:[l.jsx("div",{ref:D}),n.length===0?l.jsx("div",{className:"p-4 text-muted text-center",children:"No entries"}):l.jsxs("table",{children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{className:"text-left",children:"Time"}),l.jsx("th",{className:"text-left",children:"Tool"}),l.jsx("th",{className:"text-left",children:"Input"}),l.jsx("th",{className:"text-right",children:"Duration"}),l.jsx("th",{className:"text-center",children:"Status"})]})}),l.jsx("tbody",{children:n.map((A,G)=>l.jsxs(ue.Fragment,{children:[l.jsxs("tr",{className:E===G?"expanded":"",onClick:()=>_(E===G?null:G),children:[l.jsx("td",{className:"whitespace-nowrap",children:RI(A.timestamp)}),l.jsx("td",{className:"tool-name font-mono","data-tool":A.toolName.toLowerCase(),children:A.toolName}),l.jsx("td",{className:"truncate max-w-[200px]",children:A.input?l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{children:Kx(A.input)})}),l.jsx(Te,{children:A.input})]}):Kx(A.input)}),l.jsx("td",{className:"text-right whitespace-nowrap",children:Zx(A.durationMs)}),l.jsx("td",{className:"text-center",children:A.success?l.jsx("span",{className:"status-ok",children:"✓"}):l.jsxs(Re,{children:[l.jsx(Oe,{asChild:!0,children:l.jsx("span",{className:"status-err",children:"✗"})}),l.jsx(Te,{children:A.error})]})})]}),E===G&&l.jsx("tr",{className:"expanded-detail",children:l.jsxs("td",{colSpan:5,children:[l.jsxs("div",{className:"detail-grid",children:[l.jsx(It,{label:"Tool",value:A.toolName}),l.jsx(It,{label:"Duration",value:A.durationMs!==void 0?Zx(A.durationMs):void 0}),A.exitCode!==void 0&&A.exitCode!==null&&l.jsx(It,{label:"Exit Code",value:A.exitCode,mono:!0}),l.jsx(It,{label:"File",value:A.filePath,mono:!0}),A.language&&l.jsx(It,{label:"Language",value:A.language}),A.fileSize!==void 0&&l.jsx(It,{label:"Size",value:OI(A.fileSize)}),A.lineCount!==void 0&&l.jsx(It,{label:"Lines",value:A.lineCount.toLocaleString()}),A.gitStatus&&l.jsx(It,{label:"Git",value:A.gitStatus}),A.diff&&l.jsx(It,{label:"Diff",value:l.jsxs("span",{children:[l.jsxs("span",{style:{color:"var(--success, #22c55e)"},children:["+",A.diff.added]})," ",l.jsxs("span",{style:{color:"var(--error, #ef4444)"},children:["-",A.diff.removed]})]})}),A.command&&l.jsx(It,{label:"Command",value:A.command,mono:!0}),A.workingDirectory&&l.jsx(It,{label:"CWD",value:zI(A.workingDirectory),mono:!0}),A.subagentType&&l.jsx(It,{label:"Agent",value:A.subagentType}),A.isBackground&&l.jsx(It,{label:"Background",value:"Yes"}),A.promptSummary&&l.jsx(It,{label:"Prompt",value:A.promptSummary}),A.resultSummary&&l.jsx(It,{label:"Result",value:A.resultSummary})]}),A.outputSummary&&A.outputSummary.totalLines>0&&l.jsxs("div",{className:"detail-output",children:[l.jsxs("div",{className:"detail-label",children:["Output (",A.outputSummary.totalLines," lines",A.outputSummary.truncated?", truncated":"",")"]}),l.jsxs("pre",{children:[A.outputSummary.firstLines.join(`
79
79
  `),A.outputSummary.truncated&&A.outputSummary.lastLines.length>0?`
80
80
  ...
81
81
  `+A.outputSummary.lastLines.join(`