claude-code-session-manager 0.98.0 → 0.100.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (431) hide show
  1. package/README.md +3 -3
  2. package/bin/cli.cjs +16 -4
  3. package/bin/node-floor.cjs +41 -0
  4. package/dist/assets/{DataModel-DCEgMTjH.js → DataModel-HdR0AxFq.js} +1 -1
  5. package/dist/assets/{History-Bfdoywlh.js → History-Dr4Jr_5z.js} +2 -2
  6. package/dist/assets/{Hooks-CKDJjTJV.js → Hooks-NhrvH3JP.js} +3 -3
  7. package/dist/assets/{Library-7akfgy67.js → Library-Dv_EtIMr.js} +1 -1
  8. package/dist/assets/{MarkdownEditor-DDesiqet.js → MarkdownEditor-DTKDWV_n.js} +1 -1
  9. package/dist/assets/{McpServers-D4lZtXof.js → McpServers-M034G9B3.js} +2 -2
  10. package/dist/assets/{Memory-CeI8G1w5.js → Memory-DzF1B4gx.js} +6 -6
  11. package/dist/assets/{Permissions-BGleLja4.js → Permissions-DrgbSGWl.js} +3 -3
  12. package/dist/assets/{Plugins-P4eCXy_S.js → Plugins-Bd3ef35w.js} +2 -2
  13. package/dist/assets/{ProvenanceBadge-BFczzI1B.js → ProvenanceBadge-DcBHT1Iy.js} +1 -1
  14. package/dist/assets/{SaveBar-l9jnEMES.js → SaveBar-rimJem-Y.js} +1 -1
  15. package/dist/assets/Scheduler-DjgFJl2w.js +16 -0
  16. package/dist/assets/{ScopeSwitcher-CjJi8ST5.js → ScopeSwitcher-CnAzTBrl.js} +1 -1
  17. package/dist/assets/Settings-Dc1F_sSg.js +3 -0
  18. package/dist/assets/{SkillReferenceGraph-CjbO01Sg.js → SkillReferenceGraph-B9aZDecM.js} +1 -1
  19. package/dist/assets/{Skills-BxZ9_fCR.js → Skills-DRXd18gu.js} +2 -2
  20. package/dist/assets/{SystemPrompt-D8vfFb8b.js → SystemPrompt-ahy5-Fwe.js} +1 -1
  21. package/dist/assets/{TagLibrary-2vzUo7YL.js → TagLibrary-C_tToDeL.js} +1 -1
  22. package/dist/assets/{TiptapBody-B8ZfbK90.js → TiptapBody-DvdefS6K.js} +1 -1
  23. package/dist/assets/{Toggle-BbW4nGGf.js → Toggle-6Jl5Njc6.js} +1 -1
  24. package/dist/assets/{index-CKH5Uxik.css → index-Bta-hwud.css} +1 -1
  25. package/dist/assets/{index-Cd98Q1lD.js → index-vx8O73l8.js} +497 -502
  26. package/dist/assets/{settingsSchema-IhUfucCF.js → settingsSchema-D6iRguNV.js} +1 -1
  27. package/dist/index.html +2 -2
  28. package/package.json +25 -29
  29. package/plugins/CLAUDE.md +6 -6
  30. package/plugins/session-manager-dev/skills/builder/4-manual/SKILL.md +21 -19
  31. package/plugins/session-manager-dev/skills/builder/SKILL.md +3 -3
  32. package/plugins/session-manager-dev/skills/develop/SKILL.md +254 -510
  33. package/plugins/session-manager-dev/skills/develop/standards.md +17 -22
  34. package/scripts/README.md +3 -11
  35. package/scripts/audit-ops-hygiene.cjs +3 -3
  36. package/scripts/hooks/lib/guard-prd-writes-policy.cjs +1 -1
  37. package/scripts/hooks/lib/guard-self-schedule-policy.cjs +1 -1
  38. package/scripts/mint-epic.cjs +2 -3
  39. package/scripts/scheduler-mcp-server.cjs +36 -7
  40. package/src/main/agentLibrary.cjs +22 -2
  41. package/src/main/build-info.json +4 -4
  42. package/src/main/config.cjs +41 -38
  43. package/src/main/docEdit.cjs +4 -1
  44. package/src/main/files.cjs +2 -5
  45. package/src/main/health.cjs +1 -1
  46. package/src/main/index.cjs +23 -10
  47. package/src/main/ipcSchemas.cjs +28 -35
  48. package/src/main/lib/agentPersonaSchema.cjs +13 -2
  49. package/src/main/lib/atomicFs.cjs +116 -0
  50. package/src/main/lib/branchSweep.cjs +13 -12
  51. package/src/main/lib/buildTarget.cjs +3 -3
  52. package/src/main/lib/claudeCliCaps.cjs +129 -0
  53. package/src/main/lib/credentials.cjs +2 -4
  54. package/src/main/lib/crossProjectFeedback.cjs +3 -3
  55. package/src/main/lib/cwdClassify.cjs +15 -3
  56. package/src/main/lib/definitionOfDone.cjs +207 -125
  57. package/src/main/lib/dodDrainHook.cjs +11 -5
  58. package/src/main/lib/epicMint.cjs +2 -4
  59. package/src/main/lib/epicStatusMirror.cjs +8 -10
  60. package/src/main/lib/epicWorktreeProjectConfig.cjs +2 -4
  61. package/src/main/lib/gateAuthority.cjs +96 -0
  62. package/src/main/lib/gitExec.cjs +69 -0
  63. package/src/main/lib/gitWorktree.cjs +656 -92
  64. package/src/main/lib/instanceLock.cjs +5 -8
  65. package/src/main/lib/launchFailure.cjs +2 -3
  66. package/src/main/lib/macroLibrary.cjs +386 -0
  67. package/src/main/lib/mcpToolCatalog.cjs +26 -17
  68. package/src/main/lib/needsReviewLedger.cjs +1 -1
  69. package/src/main/lib/opsErrorLog.cjs +11 -1
  70. package/src/main/lib/opsOwnership.cjs +0 -5
  71. package/src/main/lib/pidAlive.cjs +32 -0
  72. package/src/main/lib/prdCreate.cjs +121 -12
  73. package/src/main/lib/prdDisposition.cjs +2 -2
  74. package/src/main/lib/prdGateFiles.cjs +284 -0
  75. package/src/main/lib/prdLocations.cjs +61 -0
  76. package/src/main/lib/prdMigration.cjs +2 -3
  77. package/src/main/lib/prdSizing.cjs +2 -1
  78. package/src/main/lib/promptSessionSchema.cjs +10 -2
  79. package/src/main/lib/rcaReport.cjs +4 -6
  80. package/src/main/lib/reaperHelpers.cjs +8 -1
  81. package/src/main/lib/reservationExpiry.cjs +6 -1
  82. package/src/main/lib/reviewNotice.cjs +263 -0
  83. package/src/main/lib/runClaudeP.cjs +4 -1
  84. package/src/main/lib/schedulerPaths.cjs +22 -2
  85. package/src/main/lib/sessionSlots.cjs +2 -4
  86. package/src/main/lib/shippedPersonaSeeds.cjs +179 -0
  87. package/src/main/lib/timeoutShim.cjs +123 -0
  88. package/src/main/lib/timeoutShimScript.cjs +275 -0
  89. package/src/main/lib/upgradeDrain.cjs +4 -10
  90. package/src/main/lib/watchdogHelpers.cjs +12 -25
  91. package/src/main/lib/workTypeLibrary.cjs +7 -1
  92. package/src/main/promptSessionEvents.cjs +37 -13
  93. package/src/main/scheduler.cjs +910 -198
  94. package/src/main/seedAgentPersonas.cjs +278 -23
  95. package/src/main/supervisor.cjs +4 -1
  96. package/src/main/templates/PRD_AUTHORING.md +126 -406
  97. package/src/preload/__tests__/preload-surface.test.cjs +68 -0
  98. package/src/preload/api.d.ts +41 -94
  99. package/src/preload/index.cjs +14 -9
  100. package/src/seed/agents/architect.md +1 -0
  101. package/src/seed/agents/dev-lead.md +17 -18
  102. package/src/seed/agents/project-home-builder.md +1 -0
  103. package/src/seed/agents/validator.md +10 -4
  104. package/dist/assets/HostBilko-CDVHE0hT.js +0 -1
  105. package/dist/assets/Scheduler-C_phpeUS.js +0 -16
  106. package/dist/assets/Settings-BIwZ3FGQ.js +0 -3
  107. package/src/main/__tests__/activeIndexMerge.test.cjs +0 -235
  108. package/src/main/__tests__/agentEffortResolve.test.cjs +0 -117
  109. package/src/main/__tests__/agentLibrary.test.cjs +0 -276
  110. package/src/main/__tests__/agentModelResolve.test.cjs +0 -311
  111. package/src/main/__tests__/agentOverlayWrite.test.cjs +0 -95
  112. package/src/main/__tests__/bilkoHost-deriveSlug.test.cjs +0 -26
  113. package/src/main/__tests__/bilkoHost-integration.test.cjs +0 -118
  114. package/src/main/__tests__/bilkoHostCore.test.cjs +0 -72
  115. package/src/main/__tests__/broadcastCoalescer.test.cjs +0 -122
  116. package/src/main/__tests__/chat-cancel-terminal.test.cjs +0 -120
  117. package/src/main/__tests__/chat-dead-channels.test.cjs +0 -63
  118. package/src/main/__tests__/chat-exit-close-race.test.cjs +0 -146
  119. package/src/main/__tests__/chat-mcp-consent-notice.test.cjs +0 -139
  120. package/src/main/__tests__/chat-preamble-anchors.test.cjs +0 -100
  121. package/src/main/__tests__/chat-queue.test.cjs +0 -97
  122. package/src/main/__tests__/chat-stop-signal.test.cjs +0 -89
  123. package/src/main/__tests__/chatRunner-epic-worktree-execcwd.test.cjs +0 -125
  124. package/src/main/__tests__/chatRunner-session-flag-retry.test.cjs +0 -252
  125. package/src/main/__tests__/classifyPromptTicket.test.cjs +0 -101
  126. package/src/main/__tests__/classifyTranscriptLine.test.cjs +0 -201
  127. package/src/main/__tests__/computeDepHistorySatisfaction.test.cjs +0 -66
  128. package/src/main/__tests__/config-readText-bounded.test.cjs +0 -84
  129. package/src/main/__tests__/configWriteBoundaryOwners.test.cjs +0 -59
  130. package/src/main/__tests__/crossProjectFeedback.test.cjs +0 -334
  131. package/src/main/__tests__/crossProjectFeedbackRoutes.test.cjs +0 -161
  132. package/src/main/__tests__/dep-orphan-archive-health.test.cjs +0 -77
  133. package/src/main/__tests__/develop-skill-failure-modes.test.cjs +0 -70
  134. package/src/main/__tests__/docEdit.test.cjs +0 -244
  135. package/src/main/__tests__/dod-batchkey.test.cjs +0 -183
  136. package/src/main/__tests__/dod-drain-hook.test.cjs +0 -302
  137. package/src/main/__tests__/dod-report.test.cjs +0 -304
  138. package/src/main/__tests__/dod-reverify.test.cjs +0 -285
  139. package/src/main/__tests__/epicContextDigest.test.cjs +0 -174
  140. package/src/main/__tests__/epicMint.test.cjs +0 -332
  141. package/src/main/__tests__/epicMintTelemetryTap.test.cjs +0 -64
  142. package/src/main/__tests__/epicStatusMirror.test.cjs +0 -110
  143. package/src/main/__tests__/epicValidationHook.test.cjs +0 -291
  144. package/src/main/__tests__/exchanges.test.cjs +0 -122
  145. package/src/main/__tests__/exchangesPromptId.test.cjs +0 -61
  146. package/src/main/__tests__/extractJson.test.cjs +0 -51
  147. package/src/main/__tests__/files-reject-credentials.test.cjs +0 -40
  148. package/src/main/__tests__/fixtures/1218-fo-01-move-scripts-lib-into-src-main-lib.log +0 -556
  149. package/src/main/__tests__/flatPrdTickSweep.test.cjs +0 -110
  150. package/src/main/__tests__/health-build-freshness.test.cjs +0 -39
  151. package/src/main/__tests__/health-claude-md-budget.test.cjs +0 -57
  152. package/src/main/__tests__/health-credentials.test.cjs +0 -81
  153. package/src/main/__tests__/health-delegation-chain.test.cjs +0 -124
  154. package/src/main/__tests__/health-per-project-stall.test.cjs +0 -84
  155. package/src/main/__tests__/health-prd-migration.test.cjs +0 -37
  156. package/src/main/__tests__/health-queue-dispatch.test.cjs +0 -135
  157. package/src/main/__tests__/health-starve-escalation.test.cjs +0 -94
  158. package/src/main/__tests__/health-tick-liveness.test.cjs +0 -179
  159. package/src/main/__tests__/health-usage-poller.test.cjs +0 -144
  160. package/src/main/__tests__/health-worktree-cap-blocked.test.cjs +0 -65
  161. package/src/main/__tests__/heapSnapshot.test.cjs +0 -121
  162. package/src/main/__tests__/historyAggregatorIntraday.test.cjs +0 -313
  163. package/src/main/__tests__/historyDashboard.test.cjs +0 -163
  164. package/src/main/__tests__/historyRollup.test.cjs +0 -333
  165. package/src/main/__tests__/intradayRefresh.test.cjs +0 -39
  166. package/src/main/__tests__/ipcSchemas-dependsOn.test.cjs +0 -39
  167. package/src/main/__tests__/kg-augment.test.cjs +0 -195
  168. package/src/main/__tests__/loadGateDetailTick.test.cjs +0 -31
  169. package/src/main/__tests__/machineProfile.test.cjs +0 -152
  170. package/src/main/__tests__/mcpStatus.test.cjs +0 -61
  171. package/src/main/__tests__/memoryAggregate.test.cjs +0 -109
  172. package/src/main/__tests__/memoryStale.test.cjs +0 -88
  173. package/src/main/__tests__/needsReviewLedger.test.cjs +0 -162
  174. package/src/main/__tests__/openExternalApp-spawn-error.test.cjs +0 -25
  175. package/src/main/__tests__/opsErrorLog.test.cjs +0 -109
  176. package/src/main/__tests__/opsErrorLogTelemetryTap.test.cjs +0 -173
  177. package/src/main/__tests__/personaMerge.test.cjs +0 -169
  178. package/src/main/__tests__/planValidator.test.cjs +0 -125
  179. package/src/main/__tests__/pollLoop-dispatch-on-failure.test.cjs +0 -176
  180. package/src/main/__tests__/prd-group-allocator.test.cjs +0 -119
  181. package/src/main/__tests__/prdAdminRouteParity.test.cjs +0 -70
  182. package/src/main/__tests__/prdAdminRoutes.test.cjs +0 -718
  183. package/src/main/__tests__/prdAgentType.test.cjs +0 -103
  184. package/src/main/__tests__/prdAuthoringSeed.test.cjs +0 -39
  185. package/src/main/__tests__/prdCreate.test.cjs +0 -979
  186. package/src/main/__tests__/prdCreateAdoption.test.cjs +0 -205
  187. package/src/main/__tests__/prdCreateDisposition.test.cjs +0 -201
  188. package/src/main/__tests__/prdCreatePlanId.test.cjs +0 -132
  189. package/src/main/__tests__/prdFrontmatterAgentType.test.cjs +0 -117
  190. package/src/main/__tests__/prdFrontmatterDependsOn.test.cjs +0 -136
  191. package/src/main/__tests__/prdFrontmatterDisposition.test.cjs +0 -125
  192. package/src/main/__tests__/prdFrontmatterQuietMachine.test.cjs +0 -108
  193. package/src/main/__tests__/prdLocations.test.cjs +0 -195
  194. package/src/main/__tests__/prdLocationsArchived.test.cjs +0 -201
  195. package/src/main/__tests__/prdMigration.test.cjs +0 -349
  196. package/src/main/__tests__/prdMigrationLegacyAdopt.test.cjs +0 -91
  197. package/src/main/__tests__/prdParserHighWater.test.cjs +0 -74
  198. package/src/main/__tests__/prdParserSourcePromptId.test.cjs +0 -65
  199. package/src/main/__tests__/prdSetDisposition.test.cjs +0 -222
  200. package/src/main/__tests__/prdSizing.test.cjs +0 -106
  201. package/src/main/__tests__/prdSourcePromptIdBackfill.test.cjs +0 -118
  202. package/src/main/__tests__/prdUpdateDependsOn.test.cjs +0 -160
  203. package/src/main/__tests__/proc-role-env.test.cjs +0 -125
  204. package/src/main/__tests__/procname-claude-spawn-sites.test.cjs +0 -304
  205. package/src/main/__tests__/procname-sm-processes.test.cjs +0 -127
  206. package/src/main/__tests__/projectHomeAdminRoutes.test.cjs +0 -177
  207. package/src/main/__tests__/projectPages.test.cjs +0 -137
  208. package/src/main/__tests__/promptSessionEvents.test.cjs +0 -234
  209. package/src/main/__tests__/promptSessionSchema.test.cjs +0 -101
  210. package/src/main/__tests__/promptSessionTranscript.test.cjs +0 -0
  211. package/src/main/__tests__/promptSessionsCreateEpicHandler.test.cjs +0 -159
  212. package/src/main/__tests__/pty-epic-worktree-spawn-cwd.test.cjs +0 -282
  213. package/src/main/__tests__/pty-session-open-telemetry.test.cjs +0 -96
  214. package/src/main/__tests__/pty-write-result.test.cjs +0 -46
  215. package/src/main/__tests__/queue-health-verdict.test.cjs +0 -170
  216. package/src/main/__tests__/queue-starvation-dispatch-driver.test.cjs +0 -286
  217. package/src/main/__tests__/queue-starvation-per-project.test.cjs +0 -147
  218. package/src/main/__tests__/queueHistory.test.cjs +0 -355
  219. package/src/main/__tests__/queueOps-interactive-ac-lint.test.cjs +0 -65
  220. package/src/main/__tests__/queueOpsArchiveDestination.test.cjs +0 -65
  221. package/src/main/__tests__/queueOpsAutoArchive.test.cjs +0 -211
  222. package/src/main/__tests__/rateLimitPollerStreak.test.cjs +0 -128
  223. package/src/main/__tests__/rcaReport.test.cjs +0 -266
  224. package/src/main/__tests__/reconcileFlatPrdSweep.test.cjs +0 -119
  225. package/src/main/__tests__/reconcileTiming.test.cjs +0 -135
  226. package/src/main/__tests__/runLogRetention.test.cjs +0 -489
  227. package/src/main/__tests__/runVerify-atomic-verdicts.test.cjs +0 -26
  228. package/src/main/__tests__/runVerify-blocked-by-foreign-wip.test.cjs +0 -58
  229. package/src/main/__tests__/runVerify-landed-commit-outranks.test.cjs +0 -191
  230. package/src/main/__tests__/runVerify-policy-denial.test.cjs +0 -89
  231. package/src/main/__tests__/runVerify-transcript-commit-evidence.test.cjs +0 -225
  232. package/src/main/__tests__/runVerify.test.cjs +0 -1784
  233. package/src/main/__tests__/scheduleJobSchema.test.cjs +0 -127
  234. package/src/main/__tests__/scheduleJobStatusDrift.test.cjs +0 -65
  235. package/src/main/__tests__/scheduleJobTransitions.test.cjs +0 -277
  236. package/src/main/__tests__/scheduleJobTransitionsGrep.test.cjs +0 -59
  237. package/src/main/__tests__/scheduleJobTransitionsTelemetryTap.test.cjs +0 -72
  238. package/src/main/__tests__/scheduler-admin-routes.test.cjs +0 -199
  239. package/src/main/__tests__/scheduler-adopted-run-supervision.test.cjs +0 -143
  240. package/src/main/__tests__/scheduler-already-satisfied-on-main.test.cjs +0 -105
  241. package/src/main/__tests__/scheduler-archive-completed-prd.test.cjs +0 -102
  242. package/src/main/__tests__/scheduler-archived-twin-guard.test.cjs +0 -155
  243. package/src/main/__tests__/scheduler-autofix-outcome.test.cjs +0 -188
  244. package/src/main/__tests__/scheduler-autofix-select.test.cjs +0 -439
  245. package/src/main/__tests__/scheduler-autopromote.test.cjs +0 -51
  246. package/src/main/__tests__/scheduler-bash-timeout-env.test.cjs +0 -101
  247. package/src/main/__tests__/scheduler-blocked-by-foreign-wip.test.cjs +0 -107
  248. package/src/main/__tests__/scheduler-boot-orphans.test.cjs +0 -153
  249. package/src/main/__tests__/scheduler-broadcast-reconcile.test.cjs +0 -121
  250. package/src/main/__tests__/scheduler-clear-queue-history.test.cjs +0 -134
  251. package/src/main/__tests__/scheduler-commit-guard-noop.test.cjs +0 -244
  252. package/src/main/__tests__/scheduler-committed-in-window.test.cjs +0 -182
  253. package/src/main/__tests__/scheduler-cross-project-batch.test.cjs +0 -43
  254. package/src/main/__tests__/scheduler-default-eligible-heal.test.cjs +0 -168
  255. package/src/main/__tests__/scheduler-dispatch-loop.test.cjs +0 -58
  256. package/src/main/__tests__/scheduler-effective-concurrency.test.cjs +0 -81
  257. package/src/main/__tests__/scheduler-epic-digest.test.cjs +0 -227
  258. package/src/main/__tests__/scheduler-failed-autoreset.test.cjs +0 -121
  259. package/src/main/__tests__/scheduler-finalize-dispatch-guards.test.cjs +0 -229
  260. package/src/main/__tests__/scheduler-find-prd-dir.test.cjs +0 -75
  261. package/src/main/__tests__/scheduler-fix-plan-path.test.cjs +0 -119
  262. package/src/main/__tests__/scheduler-force-tick-outcome.test.cjs +0 -46
  263. package/src/main/__tests__/scheduler-foreign-wip-manifest.test.cjs +0 -78
  264. package/src/main/__tests__/scheduler-gate-shadow.test.cjs +0 -119
  265. package/src/main/__tests__/scheduler-guard-verdict-autoresolve.test.cjs +0 -390
  266. package/src/main/__tests__/scheduler-heal-refusal.test.cjs +0 -61
  267. package/src/main/__tests__/scheduler-heartbeat-payload.test.cjs +0 -80
  268. package/src/main/__tests__/scheduler-inplace-salvage.test.cjs +0 -323
  269. package/src/main/__tests__/scheduler-integration-failure-stamp.test.cjs +0 -41
  270. package/src/main/__tests__/scheduler-investigation-clean-skip.test.cjs +0 -63
  271. package/src/main/__tests__/scheduler-investigation-prompt.test.cjs +0 -123
  272. package/src/main/__tests__/scheduler-job-budget.test.cjs +0 -172
  273. package/src/main/__tests__/scheduler-job-overrun.test.cjs +0 -175
  274. package/src/main/__tests__/scheduler-launch-failure.test.cjs +0 -199
  275. package/src/main/__tests__/scheduler-leftover-fields.test.cjs +0 -52
  276. package/src/main/__tests__/scheduler-leftover-quarantine.test.cjs +0 -199
  277. package/src/main/__tests__/scheduler-looks-done.test.cjs +0 -537
  278. package/src/main/__tests__/scheduler-manual-pause.test.cjs +0 -118
  279. package/src/main/__tests__/scheduler-mechanical-recovery.test.cjs +0 -245
  280. package/src/main/__tests__/scheduler-meta-code-sha.test.cjs +0 -46
  281. package/src/main/__tests__/scheduler-mutate-reentrancy.test.cjs +0 -117
  282. package/src/main/__tests__/scheduler-needs-review-autoresolve.test.cjs +0 -197
  283. package/src/main/__tests__/scheduler-never-stop.test.cjs +0 -157
  284. package/src/main/__tests__/scheduler-no-dead-end-status.test.cjs +0 -152
  285. package/src/main/__tests__/scheduler-no-orphan-run-dir.test.cjs +0 -81
  286. package/src/main/__tests__/scheduler-notify-originating-tab-transcript.test.cjs +0 -87
  287. package/src/main/__tests__/scheduler-notify-originating-tab.test.cjs +0 -343
  288. package/src/main/__tests__/scheduler-periodic-reverify-guard.test.cjs +0 -217
  289. package/src/main/__tests__/scheduler-porcelain-rename.test.cjs +0 -164
  290. package/src/main/__tests__/scheduler-prd-missing-skip.test.cjs +0 -161
  291. package/src/main/__tests__/scheduler-prd-persona-spawn.test.cjs +0 -178
  292. package/src/main/__tests__/scheduler-quarantine-autoresolve.test.cjs +0 -165
  293. package/src/main/__tests__/scheduler-quiet-machine-lease.test.cjs +0 -257
  294. package/src/main/__tests__/scheduler-rate-limit-cooldown-freshness.test.cjs +0 -123
  295. package/src/main/__tests__/scheduler-rate-limit-pause.test.cjs +0 -152
  296. package/src/main/__tests__/scheduler-rate-limit-spin-guard.test.cjs +0 -156
  297. package/src/main/__tests__/scheduler-reap-dead-running-jobs.test.cjs +0 -754
  298. package/src/main/__tests__/scheduler-reaper-helpers-basics.test.cjs +0 -87
  299. package/src/main/__tests__/scheduler-reconcile-cwd-preserve.test.cjs +0 -100
  300. package/src/main/__tests__/scheduler-reconcile-history-backfill.test.cjs +0 -105
  301. package/src/main/__tests__/scheduler-reconcile-invalid-repair.test.cjs +0 -203
  302. package/src/main/__tests__/scheduler-reconcile-quarantine.test.cjs +0 -247
  303. package/src/main/__tests__/scheduler-reset-job-fields-guard.test.cjs +0 -77
  304. package/src/main/__tests__/scheduler-resume-recovery.test.cjs +0 -254
  305. package/src/main/__tests__/scheduler-shard-quarantine.test.cjs +0 -115
  306. package/src/main/__tests__/scheduler-shared-tree-guard.test.cjs +0 -380
  307. package/src/main/__tests__/scheduler-sigterm-commit.test.cjs +0 -43
  308. package/src/main/__tests__/scheduler-stall-per-project.test.cjs +0 -126
  309. package/src/main/__tests__/scheduler-starve-escalation.test.cjs +0 -154
  310. package/src/main/__tests__/scheduler-stranded-autofix-park.test.cjs +0 -252
  311. package/src/main/__tests__/scheduler-stranded-investigation.test.cjs +0 -185
  312. package/src/main/__tests__/scheduler-stuck-failed-escalation.test.cjs +0 -136
  313. package/src/main/__tests__/scheduler-supervisor-record.test.cjs +0 -81
  314. package/src/main/__tests__/scheduler-tick-cancel-token.test.cjs +0 -54
  315. package/src/main/__tests__/scheduler-tick-wedge.test.cjs +0 -172
  316. package/src/main/__tests__/scheduler-transient-failure.test.cjs +0 -141
  317. package/src/main/__tests__/scheduler-unreadable-queue-guard.test.cjs +0 -62
  318. package/src/main/__tests__/scheduler-utilization-hold.test.cjs +0 -89
  319. package/src/main/__tests__/scheduler-verify-prd-path.test.cjs +0 -109
  320. package/src/main/__tests__/scheduler-worktree-cap-defer.test.cjs +0 -234
  321. package/src/main/__tests__/scheduler-worktree-exec-cwd.test.cjs +0 -120
  322. package/src/main/__tests__/scheduler-writeprd-epic-rollback.test.cjs +0 -105
  323. package/src/main/__tests__/schedulerBatchRootBlocker.test.cjs +0 -117
  324. package/src/main/__tests__/schedulerStateSidecarRestore.test.cjs +0 -110
  325. package/src/main/__tests__/seedAgentPersonas.test.cjs +0 -184
  326. package/src/main/__tests__/seedSchedulerMcp.test.cjs +0 -211
  327. package/src/main/__tests__/seedStatus.test.cjs +0 -100
  328. package/src/main/__tests__/seedValidatorPersona.test.cjs +0 -116
  329. package/src/main/__tests__/stop-signal-anchor.test.cjs +0 -75
  330. package/src/main/__tests__/telemetryClient.test.cjs +0 -1055
  331. package/src/main/__tests__/telemetryContract.test.cjs +0 -930
  332. package/src/main/__tests__/telemetrySettings.test.cjs +0 -210
  333. package/src/main/__tests__/transcripts-batch-flush.test.cjs +0 -249
  334. package/src/main/__tests__/transcripts-doFlush-array.test.cjs +0 -124
  335. package/src/main/__tests__/transcripts-paged-reads.test.cjs +0 -241
  336. package/src/main/__tests__/transcripts-worktree-epic-path.test.cjs +0 -154
  337. package/src/main/__tests__/transcriptsUsageFor.test.cjs +0 -206
  338. package/src/main/__tests__/uniquePrdNumbers.test.cjs +0 -153
  339. package/src/main/__tests__/usageSingleFlight.test.cjs +0 -169
  340. package/src/main/__tests__/validationSentinels.test.cjs +0 -84
  341. package/src/main/__tests__/workTypeLibrary.test.cjs +0 -89
  342. package/src/main/bilkoHost.cjs +0 -314
  343. package/src/main/bilkoHostCore.cjs +0 -89
  344. package/src/main/lib/__tests__/active-sessions.test.cjs +0 -251
  345. package/src/main/lib/__tests__/activeIndexRebuild.test.cjs +0 -179
  346. package/src/main/lib/__tests__/agentPersonaSchema.test.cjs +0 -67
  347. package/src/main/lib/__tests__/auditLog.test.cjs +0 -38
  348. package/src/main/lib/__tests__/bootSelfHeal.test.cjs +0 -107
  349. package/src/main/lib/__tests__/branchSweep.test.cjs +0 -164
  350. package/src/main/lib/__tests__/buildIdentity.test.cjs +0 -121
  351. package/src/main/lib/__tests__/buildTarget.test.cjs +0 -52
  352. package/src/main/lib/__tests__/childWithLog.test.cjs +0 -321
  353. package/src/main/lib/__tests__/coldBootPromptSessionsWrite.test.cjs +0 -87
  354. package/src/main/lib/__tests__/crashTelemetry.test.cjs +0 -103
  355. package/src/main/lib/__tests__/credentials-futile-refresh.test.cjs +0 -115
  356. package/src/main/lib/__tests__/cwdClassify.test.cjs +0 -111
  357. package/src/main/lib/__tests__/definitionOfDoneSequence.test.cjs +0 -95
  358. package/src/main/lib/__tests__/delegationReadiness.test.cjs +0 -1175
  359. package/src/main/lib/__tests__/dispatchLoop.test.cjs +0 -63
  360. package/src/main/lib/__tests__/effectiveModelInfo.test.cjs +0 -244
  361. package/src/main/lib/__tests__/ephemeralCwd.test.cjs +0 -91
  362. package/src/main/lib/__tests__/epicDelegationStats.test.cjs +0 -137
  363. package/src/main/lib/__tests__/epicSpawnCwd.test.cjs +0 -283
  364. package/src/main/lib/__tests__/epicSpawnPlan.test.cjs +0 -196
  365. package/src/main/lib/__tests__/epicTranscriptPath.test.cjs +0 -163
  366. package/src/main/lib/__tests__/epicWorktreeBoot.test.cjs +0 -136
  367. package/src/main/lib/__tests__/epicWorktreeMerge.test.cjs +0 -130
  368. package/src/main/lib/__tests__/epicWorktreeMint.test.cjs +0 -117
  369. package/src/main/lib/__tests__/epicWorktreeProjectConfig.test.cjs +0 -137
  370. package/src/main/lib/__tests__/fixChainDepth.test.cjs +0 -40
  371. package/src/main/lib/__tests__/fixtures/204-mercury-steam-horse.log.txt +0 -13
  372. package/src/main/lib/__tests__/fixtures/scheduler-machine.json.corrupt-1789147548 +0 -34
  373. package/src/main/lib/__tests__/gateFixtures.json +0 -20
  374. package/src/main/lib/__tests__/gitCacheBound.test.cjs +0 -69
  375. package/src/main/lib/__tests__/gitWorktree.test.cjs +0 -1478
  376. package/src/main/lib/__tests__/gitWorktreeSalvage.test.cjs +0 -107
  377. package/src/main/lib/__tests__/gitWorktreeSalvageDelta.test.cjs +0 -153
  378. package/src/main/lib/__tests__/guardShims.test.cjs +0 -158
  379. package/src/main/lib/__tests__/importReferences.spec.cjs +0 -56
  380. package/src/main/lib/__tests__/instanceLock.test.cjs +0 -173
  381. package/src/main/lib/__tests__/jobSupervisorRecord.test.cjs +0 -78
  382. package/src/main/lib/__tests__/jobWorktree.test.cjs +0 -199
  383. package/src/main/lib/__tests__/jobWorktreeBootLive.test.cjs +0 -82
  384. package/src/main/lib/__tests__/landedSinceRun.test.cjs +0 -133
  385. package/src/main/lib/__tests__/launchFailure.test.cjs +0 -220
  386. package/src/main/lib/__tests__/loadGate.test.cjs +0 -303
  387. package/src/main/lib/__tests__/localAdminHttp.test.cjs +0 -214
  388. package/src/main/lib/__tests__/loopDelay.test.cjs +0 -68
  389. package/src/main/lib/__tests__/mcpToolCatalog.test.cjs +0 -107
  390. package/src/main/lib/__tests__/modelCatalog.test.cjs +0 -202
  391. package/src/main/lib/__tests__/opsOwnership.test.cjs +0 -113
  392. package/src/main/lib/__tests__/opsRootAbsoluteCwd.test.cjs +0 -328
  393. package/src/main/lib/__tests__/opsRootNestedWrite.test.cjs +0 -51
  394. package/src/main/lib/__tests__/opsRootResolve.test.cjs +0 -149
  395. package/src/main/lib/__tests__/prdDeclaredPaths.test.cjs +0 -82
  396. package/src/main/lib/__tests__/prdDisposition.test.cjs +0 -224
  397. package/src/main/lib/__tests__/procIdentity.test.cjs +0 -119
  398. package/src/main/lib/__tests__/procName.test.cjs +0 -92
  399. package/src/main/lib/__tests__/projectBriefCore.test.cjs +0 -216
  400. package/src/main/lib/__tests__/projectRootResolve.test.cjs +0 -148
  401. package/src/main/lib/__tests__/queueHealth.test.cjs +0 -58
  402. package/src/main/lib/__tests__/queueStoreAtomicWrite.test.cjs +0 -88
  403. package/src/main/lib/__tests__/queueStoreMachineStateRecovery.test.cjs +0 -190
  404. package/src/main/lib/__tests__/quietMachineLease.test.cjs +0 -39
  405. package/src/main/lib/__tests__/rateLimitWindow.test.cjs +0 -88
  406. package/src/main/lib/__tests__/reaperHelpers.test.cjs +0 -577
  407. package/src/main/lib/__tests__/schedulerBatchDepends.test.cjs +0 -312
  408. package/src/main/lib/__tests__/schedulerBatchFairness.test.cjs +0 -213
  409. package/src/main/lib/__tests__/schedulerBatchLaunchHold.test.cjs +0 -125
  410. package/src/main/lib/__tests__/schedulerBatchProjectCap.test.cjs +0 -127
  411. package/src/main/lib/__tests__/schedulerBatchQuietMachine.test.cjs +0 -109
  412. package/src/main/lib/__tests__/schedulerMcpServerHeadlessRefusal.test.cjs +0 -71
  413. package/src/main/lib/__tests__/schedulerMcpServerHelp.test.cjs +0 -216
  414. package/src/main/lib/__tests__/schedulerMcpServerProjectHome.test.cjs +0 -183
  415. package/src/main/lib/__tests__/schedulerPaths.test.cjs +0 -226
  416. package/src/main/lib/__tests__/schedulerPathsWorktree.test.cjs +0 -133
  417. package/src/main/lib/__tests__/schedulerRuntimeState.test.cjs +0 -56
  418. package/src/main/lib/__tests__/sessionSlots.test.cjs +0 -144
  419. package/src/main/lib/__tests__/telemetryBacklog.test.cjs +0 -626
  420. package/src/main/lib/__tests__/telemetryBoot.test.cjs +0 -134
  421. package/src/main/lib/__tests__/telemetryConsent.test.cjs +0 -136
  422. package/src/main/lib/__tests__/telemetryCounters.test.cjs +0 -57
  423. package/src/main/lib/__tests__/telemetryCountersMetadataColumn.test.cjs +0 -98
  424. package/src/main/lib/__tests__/terminalRunOutcome.test.cjs +0 -200
  425. package/src/main/lib/__tests__/toolUseClassify.test.cjs +0 -53
  426. package/src/main/lib/__tests__/updateCheck.test.cjs +0 -63
  427. package/src/main/lib/__tests__/upgradeDrain.test.cjs +0 -130
  428. package/src/main/lib/__tests__/usageCircuit.test.cjs +0 -354
  429. package/src/main/lib/__tests__/watchdog-helpers.test.cjs +0 -441
  430. package/src/main/lib/__tests__/watchdog-relaunch.test.cjs +0 -266
  431. package/src/main/lib/kgExchangePairing.cjs +0 -75
package/README.md CHANGED
@@ -21,7 +21,7 @@ Single-author hobby project. Linux and macOS only. Free, MIT, anonymous opt-out
21
21
  - **Hooks** — all 29 documented events with inline tooltips explaining what each event fires on. Definitions editor plus a test-fire runner so you can verify a hook without rebuilding state.
22
22
  - **Plugins** — manifest inspector for installed plugins plus a Discover panel that lists first-party plugins with one-click install (pty-wrapped `claude plugin install`).
23
23
  - **MCP servers** — five transports (stdio, http, streamable-http, ws, sse) with a reserved-name linter so you don't waste a launch on a server Claude refuses to load.
24
- - **Voice** — local Whisper ASR plus Silero VAD running in a Web Worker. Push-to-talk hotkey, continuous listening, auto-submit, and barge-in that ducks TTS playback. Nothing leaves the machine.
24
+ - **Voice** — local Moonshine ASR (English) plus Silero VAD running in a Web Worker. Push-to-talk hotkey, continuous listening, auto-submit, and barge-in that ducks TTS playback. Nothing leaves the machine.
25
25
  - **Toast notifications + 4-scope drift surfacing** — non-fatal errors land in a corner toast instead of being swallowed. Settings show drift across the default / user / project / local scopes so you always know which value actually wins.
26
26
  ## Install
27
27
 
@@ -29,7 +29,7 @@ Single-author hobby project. Linux and macOS only. Free, MIT, anonymous opt-out
29
29
  npx claude-code-session-manager@latest
30
30
  ```
31
31
 
32
- Linux and macOS only. The first launch downloads Electron (~200 MB) and runs `electron-rebuild` on `node-pty` so it links against the bundled Electron ABI. Subsequent launches are instant from the npx cache.
32
+ Linux and macOS only. Needs Node.js 22.12+ (Electron 42's installer needs it) and Claude Code installed and signed in — Claude Code's native installer does not bring Node with it. The first launch downloads Electron (~200 MB) and runs `electron-rebuild` on `node-pty` so it links against the bundled Electron ABI. Subsequent launches are instant from the npx cache.
33
33
 
34
34
  macOS needs Xcode Command Line Tools: `xcode-select --install`.
35
35
  Linux needs `build-essential` and `python3` for the rebuild.
@@ -84,7 +84,7 @@ The queue-health linter scans every queued PRD for two patterns that have caused
84
84
 
85
85
  ## Architecture
86
86
 
87
- Electron 42 with a CommonJS main process and a Vite-built React 18 renderer. xterm and node-pty drive the terminals. zustand owns renderer state. Whisper via `@huggingface/transformers` plus Silero VAD via `@ricky0123/vad-web` runs voice on-device through onnxruntime-web. Tailwind for styling. Single-author project, no backwards-compat shims — when something needs renaming, it gets renamed.
87
+ Electron 42 with a CommonJS main process and a Vite-built React 18 renderer. xterm and node-pty drive the terminals. zustand owns renderer state. Moonshine via `@huggingface/transformers` plus Silero VAD via `@ricky0123/vad-web` runs voice on-device through onnxruntime-web. Tailwind for styling. Single-author project, no backwards-compat shims — when something needs renaming, it gets renamed.
88
88
 
89
89
  ## Contributing / development
90
90
 
package/bin/cli.cjs CHANGED
@@ -5,6 +5,7 @@
5
5
  */
6
6
  const { spawn } = require('node:child_process');
7
7
  const path = require('node:path');
8
+ const { nodeFloor, isBelow } = require('./node-floor.cjs');
8
9
 
9
10
  if (process.platform !== 'linux' && process.platform !== 'darwin') {
10
11
  console.error('[claude-code-session-manager] Windows is not supported yet.');
@@ -15,10 +16,21 @@ let electronBin;
15
16
  try {
16
17
  electronBin = require('electron');
17
18
  } catch (err) {
18
- // `electron`'s own postinstall downloads its ~100MB binary from GitHub releases; a failure
19
- // here almost always means that download didn't complete (flaky network, a corporate
20
- // proxy/firewall blocking GitHub release downloads, low disk space) — not a bug in this
21
- // package. Point at the likely causes and a retry path instead of just "reinstall" (gh-9).
19
+ // `require('electron')` downloads its ~100MB binary from GitHub releases on first use.
20
+ // Electron 42's downloader (@electron/get 5) is ESM-only, so below Node 22.12 it can't
21
+ // even load (ERR_REQUIRE_ESM). Name that cause instead of blaming the network. Checked
22
+ // only after a failure: an already-downloaded binary still launches on older Node.
23
+ const floor = nodeFloor();
24
+ if (floor && isBelow(process.versions.node, floor)) {
25
+ console.error(`[claude-code-session-manager] Node.js ${floor.join('.')} or newer is required — this is Node ${process.versions.node}.`);
26
+ console.error('Electron, which this app runs on, cannot download itself on older Node. Upgrade Node, then re-run:');
27
+ console.error(' npx claude-code-session-manager@latest');
28
+ process.exit(1);
29
+ }
30
+ // Otherwise a failure here almost always means that download didn't complete (flaky
31
+ // network, a corporate proxy/firewall blocking GitHub release downloads, low disk space) —
32
+ // not a bug in this package. Point at the likely causes and a retry path instead of just
33
+ // "reinstall" (gh-9).
22
34
  console.error('[claude-code-session-manager] electron dependency is missing — its binary download did not complete.');
23
35
  console.error('This is usually a network issue, not a problem with this package. Try:');
24
36
  console.error(' 1. Re-run: npx claude-code-session-manager@latest (retries the download)');
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The Node.js floor this package runs on, read from package.json `engines.node` so there is
3
+ * one source of truth.
4
+ *
5
+ * bin/cli.cjs uses it to tell an old Node apart from a failed Electron download. Electron 42
6
+ * downloads its binary lazily on the first `require('electron')`, through `@electron/get` 5,
7
+ * which is an ES module. Below Node 22.12 that `require()` dies with ERR_REQUIRE_ESM, and the
8
+ * launcher would otherwise blame the network.
9
+ *
10
+ * Plain ES2015 syntax on purpose: this has to parse on the old Node it is diagnosing.
11
+ */
12
+ 'use strict';
13
+
14
+ /** `">=22.12.0"` / `">= 22.12"` -> `[22, 12, 0]`; anything else -> null (no diagnosis). */
15
+ function parseFloor(range) {
16
+ const m = /^\s*>=\s*v?(\d+)(?:\.(\d+))?(?:\.(\d+))?\s*$/.exec(String(range == null ? '' : range));
17
+ if (!m) return null;
18
+ return [Number(m[1]), Number(m[2] || 0), Number(m[3] || 0)];
19
+ }
20
+
21
+ /** True when `version` (e.g. process.versions.node, `"18.20.4"`) is older than `floor`. */
22
+ function isBelow(version, floor) {
23
+ const parts = String(version).replace(/^v/, '').split('.');
24
+ for (let i = 0; i < 3; i++) {
25
+ const n = parseInt(parts[i], 10) || 0;
26
+ if (n !== floor[i]) return n < floor[i];
27
+ }
28
+ return false;
29
+ }
30
+
31
+ /** This package's own floor, or null if package.json can't be read or the range isn't `>=x.y.z`. */
32
+ function nodeFloor() {
33
+ try {
34
+ const engines = require('../package.json').engines;
35
+ return parseFloor(engines && engines.node);
36
+ } catch (_err) {
37
+ return null;
38
+ }
39
+ }
40
+
41
+ module.exports = { parseFloor, isBelow, nodeFloor };
@@ -1 +1 @@
1
- import{az as d,i as j,al as $,a4 as g,ak as e,v as E,m as N,X as S,an as D,a5 as b,aD as T,a as p,$ as R,j as v,E as C}from"./index-Cd98Q1lD.js";import"./monaco-editor-BW5C4Iv1.js";const G=[{key:"diagram",label:"Diagram"},{key:"tables",label:"Tables"}];function M(){const[s,t]=d.useState("diagram"),[a,i]=d.useState(null),[l,n]=d.useState(()=>new Set),c=d.useMemo(()=>j.filter(r=>!l.has(r.group)),[l]),m=d.useMemo(()=>$(c),[c]),o=r=>{n(x=>{const h=new Set(x);return h.has(r)?h.delete(r):h.add(r),h}),i(null)},u=a?g(a):null,y=r=>c.some(x=>x.id===r);return e.jsx(E,{toolbar:e.jsxs(e.Fragment,{children:[e.jsx(S,{options:G,active:s,onChange:t}),e.jsx(O,{hiddenGroups:l,onToggle:o}),e.jsxs("span",{className:"ml-auto text-fg-faint",children:[j.length," entities"]})]}),children:s==="diagram"?e.jsxs("div",{className:"h-full flex",children:[e.jsx("div",{className:"flex-1 min-w-0 overflow-auto",children:e.jsx(V,{layout:m,selectedId:a,onSelect:r=>i(x=>x===r?null:r)})}),e.jsx("div",{className:"w-96 shrink-0 border-l border-line overflow-y-auto",children:u?e.jsx(F,{entity:u,onSelectRelated:r=>y(r)?i(r):void 0}):e.jsx(N,{title:"select an entity",hint:"click a box in the diagram to see its storage, fields, and relations"})})]}):e.jsx(B,{})})}const X=d.memo(M);function O({hiddenGroups:s,onToggle:t}){return e.jsx("div",{className:"flex items-center gap-1.5 flex-wrap",children:v.map(a=>{const i=s.has(a.id);return e.jsxs("button",{onClick:()=>t(a.id),title:`${a.blurb} (${a.realm})`,className:`flex items-center gap-1 px-1.5 py-0.5 rounded border text-[10.5px] ${i?"border-line text-fg-faint opacity-50":"border-line text-fg-dim hover:text-fg"}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${a.tone.dot}`}),a.label,e.jsx("span",{className:"text-fg-faint",children:a.realm})]},a.id)})})}function V({layout:s,selectedId:t,onSelect:a}){const i=d.useMemo(()=>t?new Set(D(t)):null,[t]),l=n=>!!t&&(n.relation.from===t||n.relation.to===t);return s.boxes.length===0?e.jsx(N,{title:"no entities in view",hint:"toggle a group in the legend to show its entities"}):e.jsxs("div",{className:"relative p-4",style:{width:s.width+32,height:s.height+32},children:[e.jsxs("svg",{width:s.width,height:s.height,className:"absolute left-4 top-4 overflow-visible",children:[s.edges.map(n=>{const c=l(n);return e.jsx("path",{"data-testid":`erd-edge-${n.relation.from}-${n.relation.to}`,d:n.d,fill:"none",className:c?"stroke-accent":"stroke-line",strokeWidth:c?2:1,opacity:t&&!c?.25:1},`${n.relation.from}-${n.relation.to}-${n.relation.label}`)}),s.edges.map(n=>l(n)?e.jsx("text",{x:n.mx,y:n.my,textAnchor:"middle",className:"fill-fg-dim text-[10px]",children:n.relation.label},`label-${n.relation.from}-${n.relation.to}-${n.relation.label}`):null)]}),s.boxes.map(n=>e.jsx(_,{box:n,selected:n.id===t,dimmed:!!t&&n.id!==t&&!(i!=null&&i.has(n.id)),onClick:()=>a(n.id)},n.id))]})}function _({box:s,selected:t,dimmed:a,onClick:i}){const l=g(s.id),n=b(s.group),c=l.fields.slice(0,C),m=l.fields.length-c.length;return e.jsxs("button",{type:"button","data-testid":`erd-box-${s.id}`,onClick:i,className:`absolute text-left rounded border overflow-hidden bg-bg-hi ${t?"border-accent ring-1 ring-accent":"border-line"} ${a?"opacity-30":""}`,style:{left:s.x,top:s.y,width:s.w,height:s.h},children:[e.jsxs("div",{className:"px-2 py-1 border-b border-line flex items-center gap-1.5",children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${n.tone.dot}`}),e.jsx("span",{className:"text-[11px] font-semibold text-fg truncate",children:l.name})]}),l.aka&&e.jsx("div",{className:"px-2 pt-0.5 text-[9.5px] text-fg-faint truncate",children:l.aka}),e.jsxs("div",{className:"px-2 py-0.5",children:[c.map(o=>e.jsxs("div",{className:"text-[9.5px] font-mono text-fg-dim truncate flex items-center gap-1",children:[o.key&&e.jsx("span",{className:"text-fg-faint",children:o.key}),e.jsx("span",{className:"truncate",children:o.name})]},o.name)),m>0&&e.jsxs("div",{className:"text-[9.5px] text-fg-faint italic",children:["+",m," more"]})]})]})}function w({fields:s}){return e.jsxs("table",{className:"w-full text-[11px] font-mono",children:[e.jsx("thead",{className:"text-fg-faint uppercase tracking-wide text-[9.5px]",children:e.jsxs("tr",{className:"border-b border-line",children:[e.jsx("th",{className:"text-left font-normal px-2 py-1",children:"name"}),e.jsx("th",{className:"text-left font-normal px-2 py-1",children:"type"}),e.jsx("th",{className:"text-left font-normal px-2 py-1",children:"key"}),e.jsx("th",{className:"text-left font-normal px-2 py-1",children:"note"})]})}),e.jsx("tbody",{children:s.map(t=>e.jsxs("tr",{className:"border-b border-line/50",children:[e.jsxs("td",{className:"px-2 py-1 text-fg",children:[t.name,t.optional&&e.jsx("span",{className:"text-fg-faint",children:"?"})]}),e.jsx("td",{className:"px-2 py-1 text-fg-dim",children:t.type}),e.jsx("td",{className:"px-2 py-1",children:t.key&&e.jsxs(p,{tone:t.key==="pk"?"accent":"dim",children:[t.key,t.ref?` → ${t.ref}`:""]})}),e.jsx("td",{className:"px-2 py-1 text-fg-faint",children:t.note})]},t.name))})]})}function k({entity:s}){return e.jsxs("div",{className:"space-y-1 text-[11px]",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-fg-faint w-20 shrink-0",children:"path"}),e.jsx("span",{className:"font-mono text-fg-dim break-all",children:s.store.path})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-fg-faint w-20 shrink-0",children:"format"}),e.jsx("span",{className:"font-mono text-fg-dim",children:s.store.format})]}),s.store.writer&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-fg-faint w-20 shrink-0",children:"writer"}),e.jsxs(p,{tone:"accent",children:["single-writer: ",s.store.writer]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-fg-faint w-20 shrink-0",children:"definedIn"}),e.jsx("span",{className:"font-mono text-fg-dim break-all",children:s.store.definedIn})]})]})}function F({entity:s,onSelectRelated:t}){const a=b(s.group),i=T(s.id);return e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${a.tone.dot}`}),e.jsx("span",{className:"text-sm font-semibold text-fg",children:s.name})]}),s.aka&&e.jsx("div",{className:"text-[10.5px] text-fg-faint",children:s.aka}),e.jsx(p,{tone:"dim",className:"mt-1",children:a.label})]}),e.jsx("div",{className:"text-xs text-fg-dim leading-relaxed",children:s.summary}),e.jsxs("div",{children:[e.jsx(f,{children:"storage"}),e.jsx(k,{entity:s})]}),e.jsxs("div",{children:[e.jsx(f,{children:"fields"}),e.jsx(w,{fields:s.fields})]}),s.notes&&s.notes.length>0&&e.jsxs("div",{children:[e.jsx(f,{children:"notes"}),e.jsx("ul",{className:"list-disc pl-4 space-y-0.5 text-xs text-fg-dim",children:s.notes.map(l=>e.jsx("li",{children:l},l))})]}),e.jsxs("div",{children:[e.jsx(f,{children:"relations"}),i.length===0?e.jsx("div",{className:"text-xs text-fg-faint italic",children:"no relations"}):e.jsx("ul",{className:"space-y-1",children:i.map(l=>{const n=l.from===s.id?l.to:l.from,c=g(n);return e.jsxs("li",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx("span",{className:"font-mono text-fg-faint w-10 shrink-0",children:R(l.cardinality)}),e.jsx("span",{className:"text-fg-dim",children:l.label}),l.via&&e.jsxs("span",{className:"font-mono text-[10px] text-fg-faint",children:["via ",l.via]}),e.jsx("button",{type:"button",onClick:()=>t(n),className:"ml-auto text-accent hover:underline font-mono",children:c.name})]},`${l.from}-${l.to}-${l.label}`)})})]})]})}function f({children:s}){return e.jsx("div",{className:"text-[10.5px] uppercase tracking-wide text-fg-faint mb-1 font-mono",children:s})}function B(){return e.jsx("div",{className:"p-4 space-y-6",children:v.map(s=>{const t=j.filter(a=>a.group===s.id);return t.length===0?null:e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${s.tone.dot}`}),e.jsx("span",{className:"text-xs font-semibold text-fg",children:s.label}),e.jsx("span",{className:"text-[10.5px] text-fg-faint",children:s.realm})]}),e.jsx("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-3",children:t.map(a=>e.jsxs("div",{className:"border border-line rounded bg-bg-hi p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-semibold text-fg",children:a.name}),a.aka&&e.jsx("span",{className:"text-[10.5px] text-fg-faint",children:a.aka})]}),e.jsx(p,{tone:"dim",className:"mt-1",children:s.label})]}),e.jsx("div",{className:"text-xs text-fg-dim leading-relaxed",children:a.summary}),e.jsx(k,{entity:a}),e.jsx(w,{fields:a.fields}),a.notes&&a.notes.length>0&&e.jsx("ul",{className:"list-disc pl-4 space-y-0.5 text-xs text-fg-dim",children:a.notes.map(i=>e.jsx("li",{children:i},i))})]},a.id))})]},s.id)})})}export{X as DataModel};
1
+ import{ay as d,i as j,ak as $,a3 as g,aj as e,v as E,m as N,X as S,am as T,a4 as b,aC as D,a as p,$ as C,j as v,E as R}from"./index-vx8O73l8.js";import"./monaco-editor-BW5C4Iv1.js";const G=[{key:"diagram",label:"Diagram"},{key:"tables",label:"Tables"}];function M(){const[s,t]=d.useState("diagram"),[a,i]=d.useState(null),[l,n]=d.useState(()=>new Set),c=d.useMemo(()=>j.filter(r=>!l.has(r.group)),[l]),m=d.useMemo(()=>$(c),[c]),o=r=>{n(x=>{const h=new Set(x);return h.has(r)?h.delete(r):h.add(r),h}),i(null)},u=a?g(a):null,y=r=>c.some(x=>x.id===r);return e.jsx(E,{toolbar:e.jsxs(e.Fragment,{children:[e.jsx(S,{options:G,active:s,onChange:t}),e.jsx(O,{hiddenGroups:l,onToggle:o}),e.jsxs("span",{className:"ml-auto text-fg-faint",children:[j.length," entities"]})]}),children:s==="diagram"?e.jsxs("div",{className:"h-full flex",children:[e.jsx("div",{className:"flex-1 min-w-0 overflow-auto",children:e.jsx(V,{layout:m,selectedId:a,onSelect:r=>i(x=>x===r?null:r)})}),e.jsx("div",{className:"w-96 shrink-0 border-l border-line overflow-y-auto",children:u?e.jsx(F,{entity:u,onSelectRelated:r=>y(r)?i(r):void 0}):e.jsx(N,{title:"select an entity",hint:"click a box in the diagram to see its storage, fields, and relations"})})]}):e.jsx(B,{})})}const X=d.memo(M);function O({hiddenGroups:s,onToggle:t}){return e.jsx("div",{className:"flex items-center gap-1.5 flex-wrap",children:v.map(a=>{const i=s.has(a.id);return e.jsxs("button",{onClick:()=>t(a.id),title:`${a.blurb} (${a.realm})`,className:`flex items-center gap-1 px-1.5 py-0.5 rounded border text-[10.5px] ${i?"border-line text-fg-faint opacity-50":"border-line text-fg-dim hover:text-fg"}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${a.tone.dot}`}),a.label,e.jsx("span",{className:"text-fg-faint",children:a.realm})]},a.id)})})}function V({layout:s,selectedId:t,onSelect:a}){const i=d.useMemo(()=>t?new Set(T(t)):null,[t]),l=n=>!!t&&(n.relation.from===t||n.relation.to===t);return s.boxes.length===0?e.jsx(N,{title:"no entities in view",hint:"toggle a group in the legend to show its entities"}):e.jsxs("div",{className:"relative p-4",style:{width:s.width+32,height:s.height+32},children:[e.jsxs("svg",{width:s.width,height:s.height,className:"absolute left-4 top-4 overflow-visible",children:[s.edges.map(n=>{const c=l(n);return e.jsx("path",{"data-testid":`erd-edge-${n.relation.from}-${n.relation.to}`,d:n.d,fill:"none",className:c?"stroke-accent":"stroke-line",strokeWidth:c?2:1,opacity:t&&!c?.25:1},`${n.relation.from}-${n.relation.to}-${n.relation.label}`)}),s.edges.map(n=>l(n)?e.jsx("text",{x:n.mx,y:n.my,textAnchor:"middle",className:"fill-fg-dim text-[10px]",children:n.relation.label},`label-${n.relation.from}-${n.relation.to}-${n.relation.label}`):null)]}),s.boxes.map(n=>e.jsx(_,{box:n,selected:n.id===t,dimmed:!!t&&n.id!==t&&!(i!=null&&i.has(n.id)),onClick:()=>a(n.id)},n.id))]})}function _({box:s,selected:t,dimmed:a,onClick:i}){const l=g(s.id),n=b(s.group),c=l.fields.slice(0,R),m=l.fields.length-c.length;return e.jsxs("button",{type:"button","data-testid":`erd-box-${s.id}`,onClick:i,className:`absolute text-left rounded border overflow-hidden bg-bg-hi ${t?"border-accent ring-1 ring-accent":"border-line"} ${a?"opacity-30":""}`,style:{left:s.x,top:s.y,width:s.w,height:s.h},children:[e.jsxs("div",{className:"px-2 py-1 border-b border-line flex items-center gap-1.5",children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${n.tone.dot}`}),e.jsx("span",{className:"text-[11px] font-semibold text-fg truncate",children:l.name})]}),l.aka&&e.jsx("div",{className:"px-2 pt-0.5 text-[9.5px] text-fg-faint truncate",children:l.aka}),e.jsxs("div",{className:"px-2 py-0.5",children:[c.map(o=>e.jsxs("div",{className:"text-[9.5px] font-mono text-fg-dim truncate flex items-center gap-1",children:[o.key&&e.jsx("span",{className:"text-fg-faint",children:o.key}),e.jsx("span",{className:"truncate",children:o.name})]},o.name)),m>0&&e.jsxs("div",{className:"text-[9.5px] text-fg-faint italic",children:["+",m," more"]})]})]})}function w({fields:s}){return e.jsxs("table",{className:"w-full text-[11px] font-mono",children:[e.jsx("thead",{className:"text-fg-faint uppercase tracking-wide text-[9.5px]",children:e.jsxs("tr",{className:"border-b border-line",children:[e.jsx("th",{className:"text-left font-normal px-2 py-1",children:"name"}),e.jsx("th",{className:"text-left font-normal px-2 py-1",children:"type"}),e.jsx("th",{className:"text-left font-normal px-2 py-1",children:"key"}),e.jsx("th",{className:"text-left font-normal px-2 py-1",children:"note"})]})}),e.jsx("tbody",{children:s.map(t=>e.jsxs("tr",{className:"border-b border-line/50",children:[e.jsxs("td",{className:"px-2 py-1 text-fg",children:[t.name,t.optional&&e.jsx("span",{className:"text-fg-faint",children:"?"})]}),e.jsx("td",{className:"px-2 py-1 text-fg-dim",children:t.type}),e.jsx("td",{className:"px-2 py-1",children:t.key&&e.jsxs(p,{tone:t.key==="pk"?"accent":"dim",children:[t.key,t.ref?` → ${t.ref}`:""]})}),e.jsx("td",{className:"px-2 py-1 text-fg-faint",children:t.note})]},t.name))})]})}function k({entity:s}){return e.jsxs("div",{className:"space-y-1 text-[11px]",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-fg-faint w-20 shrink-0",children:"path"}),e.jsx("span",{className:"font-mono text-fg-dim break-all",children:s.store.path})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-fg-faint w-20 shrink-0",children:"format"}),e.jsx("span",{className:"font-mono text-fg-dim",children:s.store.format})]}),s.store.writer&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-fg-faint w-20 shrink-0",children:"writer"}),e.jsxs(p,{tone:"accent",children:["single-writer: ",s.store.writer]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-fg-faint w-20 shrink-0",children:"definedIn"}),e.jsx("span",{className:"font-mono text-fg-dim break-all",children:s.store.definedIn})]})]})}function F({entity:s,onSelectRelated:t}){const a=b(s.group),i=D(s.id);return e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${a.tone.dot}`}),e.jsx("span",{className:"text-sm font-semibold text-fg",children:s.name})]}),s.aka&&e.jsx("div",{className:"text-[10.5px] text-fg-faint",children:s.aka}),e.jsx(p,{tone:"dim",className:"mt-1",children:a.label})]}),e.jsx("div",{className:"text-xs text-fg-dim leading-relaxed",children:s.summary}),e.jsxs("div",{children:[e.jsx(f,{children:"storage"}),e.jsx(k,{entity:s})]}),e.jsxs("div",{children:[e.jsx(f,{children:"fields"}),e.jsx(w,{fields:s.fields})]}),s.notes&&s.notes.length>0&&e.jsxs("div",{children:[e.jsx(f,{children:"notes"}),e.jsx("ul",{className:"list-disc pl-4 space-y-0.5 text-xs text-fg-dim",children:s.notes.map(l=>e.jsx("li",{children:l},l))})]}),e.jsxs("div",{children:[e.jsx(f,{children:"relations"}),i.length===0?e.jsx("div",{className:"text-xs text-fg-faint italic",children:"no relations"}):e.jsx("ul",{className:"space-y-1",children:i.map(l=>{const n=l.from===s.id?l.to:l.from,c=g(n);return e.jsxs("li",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx("span",{className:"font-mono text-fg-faint w-10 shrink-0",children:C(l.cardinality)}),e.jsx("span",{className:"text-fg-dim",children:l.label}),l.via&&e.jsxs("span",{className:"font-mono text-[10px] text-fg-faint",children:["via ",l.via]}),e.jsx("button",{type:"button",onClick:()=>t(n),className:"ml-auto text-accent hover:underline font-mono",children:c.name})]},`${l.from}-${l.to}-${l.label}`)})})]})]})}function f({children:s}){return e.jsx("div",{className:"text-[10.5px] uppercase tracking-wide text-fg-faint mb-1 font-mono",children:s})}function B(){return e.jsx("div",{className:"p-4 space-y-6",children:v.map(s=>{const t=j.filter(a=>a.group===s.id);return t.length===0?null:e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${s.tone.dot}`}),e.jsx("span",{className:"text-xs font-semibold text-fg",children:s.label}),e.jsx("span",{className:"text-[10.5px] text-fg-faint",children:s.realm})]}),e.jsx("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-3",children:t.map(a=>e.jsxs("div",{className:"border border-line rounded bg-bg-hi p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-semibold text-fg",children:a.name}),a.aka&&e.jsx("span",{className:"text-[10.5px] text-fg-faint",children:a.aka})]}),e.jsx(p,{tone:"dim",className:"mt-1",children:s.label})]}),e.jsx("div",{className:"text-xs text-fg-dim leading-relaxed",children:a.summary}),e.jsx(k,{entity:a}),e.jsx(w,{fields:a.fields}),a.notes&&a.notes.length>0&&e.jsx("ul",{className:"list-disc pl-4 space-y-0.5 text-xs text-fg-dim",children:a.notes.map(i=>e.jsx("li",{children:i},i))})]},a.id))})]},s.id)})})}export{X as DataModel};
@@ -1,2 +1,2 @@
1
- import{at as xe,aC as Le,bc as Ie,ak as e,az as m,aN as q,au as A,av as W,aZ as We,b5 as Ne,ao as ze,aY as Ke,m as Ge,v as Ye}from"./index-Cd98Q1lD.js";import"./monaco-editor-BW5C4Iv1.js";function re(){return{promptCount:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,toolCallCount:0,sessionCount:0,errorCount:0,activeMinutes:0,estimatedCostUsd:0}}function we(t,s){t.promptCount+=s.promptCount,t.inputTokens+=s.inputTokens,t.outputTokens+=s.outputTokens,t.cacheReadTokens+=s.cacheReadTokens,t.cacheCreationTokens+=s.cacheCreationTokens,t.toolCallCount+=s.toolCallCount,t.sessionCount+=s.sessionCount,t.errorCount+=s.errorCount,t.activeMinutes+=s.activeMinutes,t.estimatedCostUsd+=s.estimatedCostUsd}function Ve(t){return t.promptCount>0||t.sessionCount>0||t.toolCallCount>0||t.inputTokens>0||t.outputTokens>0}function Xe(t,s){const n=s===null,c=[],o=re(),r={};let a=0;for(const l of t.days){const u=re();let d=!1;for(const[i,x]of Object.entries(l.byProject))if(!(!n&&!s.has(i))){we(u,x),we(o,x),Ve(x)&&(d=!0);for(const[f,v]of Object.entries(x.byModel)){const C=r[f]??(r[f]={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0});C.inputTokens+=v.inputTokens,C.outputTokens+=v.outputTokens,C.cacheReadTokens+=v.cacheReadTokens,C.cacheCreationTokens+=v.cacheCreationTokens,C.costUsd+=v.costUsd,v.estimated&&(C.estimated=!0)}}d&&(a+=1),c.push({date:l.date,totals:u})}return{days:c,totals:o,prevTotals:n?t.prevTotals:re(),prevAvailable:n,byModelTotals:r,activeDays:a}}function Ue(t,s){if(!s)return{pct:null,direction:"flat"};const n=(t-s)/s*100,c=n>0?"up":n<0?"down":"flat";return{pct:n,direction:c}}function Ze(t,s,n){return s<=0?0:t/s*n}const Ee={in:"In tokens",out:"Out tokens",total:"Total tokens",prompts:"Prompts",sessions:"Sessions",time:"Time",spend:"Spend"};function R(t,s){const n=t.inputTokens+t.cacheReadTokens+t.cacheCreationTokens;switch(s){case"in":return n;case"out":return t.outputTokens;case"total":return n+t.outputTokens;case"prompts":return t.promptCount;case"sessions":return t.sessionCount;case"time":return t.activeMinutes;case"spend":return t.estimatedCostUsd}}function Qe(t,s){const n=R(t.totals,s),c=t.prevAvailable?Ue(n,R(t.prevTotals,s)):null,o=t.days.map(r=>R(r.totals,s));return{value:n,delta:c,series:o}}function Me(t,s){const n=new Map,c=Math.ceil(t.length/2);t.forEach((a,l)=>{for(const[u,d]of Object.entries(a.byProject)){let i=n.get(u);i||(i={totals:{promptCount:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,toolCallCount:0,sessionCount:0,errorCount:0,activeMinutes:0,estimatedCostUsd:0},toolBreakdown:{},firstHalf:0,secondHalf:0},n.set(u,i)),i.totals.promptCount+=d.promptCount,i.totals.inputTokens+=d.inputTokens,i.totals.outputTokens+=d.outputTokens,i.totals.cacheReadTokens+=d.cacheReadTokens,i.totals.cacheCreationTokens+=d.cacheCreationTokens,i.totals.toolCallCount+=d.toolCallCount,i.totals.sessionCount+=d.sessionCount,i.totals.errorCount+=d.errorCount,i.totals.activeMinutes+=d.activeMinutes,i.totals.estimatedCostUsd+=d.estimatedCostUsd;for(const[f,v]of Object.entries(d.toolBreakdown))i.toolBreakdown[f]=(i.toolBreakdown[f]??0)+v;const x=R(d,s);l<c?i.firstHalf+=x:i.secondHalf+=x}});const o=Array.from(n.entries()).map(([a,l])=>{let u="",d=-1;for(const[i,x]of Object.entries(l.toolBreakdown))x>d&&(d=x,u=i);return{projectDir:a,value:R(l.totals,s),sharePct:0,trend:Ue(l.secondHalf,l.firstHalf),sessions:l.totals.sessionCount,topTool:u}}),r=o.reduce((a,l)=>a+l.value,0);for(const a of o)a.sharePct=r>0?a.value/r*100:0;return o.sort((a,l)=>l.value-a.value)}const qe=["date","cost_usd","input_tokens","output_tokens","cache_write_tokens","cache_read_tokens","total_tokens","cache_hit_pct","num_models","top_model"];function Je(t){return/[",\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}function Se(t){return t.inputTokens+t.outputTokens+t.cacheReadTokens+t.cacheCreationTokens}function et(t){const s=t.map(n=>{const c=n.inputTokens+n.outputTokens+n.cacheCreationTokens+n.cacheReadTokens,o=n.inputTokens+n.cacheReadTokens+n.cacheCreationTokens,r=o>0?n.cacheReadTokens/o*100:0,a=Object.entries(n.byModel).filter(([,i])=>Se(i)>0);let l="",u=-1;for(const[i,x]of a){const f=Se(x);f>u&&(u=f,l=i)}return[n.date,n.costUsd.toFixed(4),String(n.inputTokens),String(n.outputTokens),String(n.cacheCreationTokens),String(n.cacheReadTokens),String(c),r.toFixed(1),String(a.length),l?xe(l):""].map(Je).join(",")});return[qe.join(","),...s].join(`
2
- `)}const tt={folderCount:0,sessionCount:0,promptCount:0,estimatedCostUsd:0,totalTokens:0};function st(t,s){t.promptCount+=s.promptCount,t.inputTokens+=s.inputTokens,t.outputTokens+=s.outputTokens,t.cacheReadTokens+=s.cacheReadTokens,t.cacheCreationTokens+=s.cacheCreationTokens,t.toolCallCount+=s.toolCallCount,t.sessionCount+=s.sessionCount,t.errorCount+=s.errorCount,t.activeMinutes+=s.activeMinutes,t.estimatedCostUsd+=s.estimatedCostUsd;for(const[n,c]of Object.entries(s.toolBreakdown??{}))t.toolBreakdown[n]=(t.toolBreakdown[n]??0)+c;for(const[n,c]of Object.entries(s.byModel??{})){const o=t.byModel[n]??(t.byModel[n]={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0});o.inputTokens+=c.inputTokens,o.outputTokens+=c.outputTokens,o.cacheReadTokens+=c.cacheReadTokens,o.cacheCreationTokens+=c.cacheCreationTokens,o.costUsd+=c.costUsd,c.estimated&&(o.estimated=!0)}}function nt(t,s){const n={};for(const[c,o]of Object.entries(t.byModel??{}))n[c]={...o};return{...t,projectDir:s,toolBreakdown:{...t.toolBreakdown??{}},byModel:n}}function ot(t,s){const n={...tt},c=new Set,o=t.map(r=>{const a={};for(const[l,u]of Object.entries(r.byProject)){const d=s[l];if(!d){c.add(l),n.sessionCount+=u.sessionCount,n.promptCount+=u.promptCount,n.estimatedCostUsd+=u.estimatedCostUsd,n.totalTokens+=u.inputTokens+u.outputTokens;continue}const i=a[d];i?st(i,u):a[d]=nt(u,d)}return{...r,byProject:a}});return n.folderCount=c.size,{days:o,excluded:n}}function at(t){return t.folderCount>0}function ct(t){const s=[`${t.folderCount} transcript folder${t.folderCount===1?"":"s"} with no resolvable working directory`];return t.sessionCount&&s.push(`${t.sessionCount.toLocaleString()} sessions`),t.promptCount&&s.push(`${t.promptCount.toLocaleString()} prompts`),t.estimatedCostUsd>=.005&&s.push(`$${t.estimatedCostUsd.toFixed(2)}`),`Excluded: ${s.join(" · ")}`}async function he(){return(await Le()).history??{}}let $e=Promise.resolve();function ue(t){const s=$e.then(async()=>{const n=await he();await Ie({history:{...n,...t}})});return $e=s.catch(()=>{}),s}const rt=["in","out","total","prompts","sessions","time","spend"],it=[{value:30,label:"30d"},{value:60,label:"60d"},{value:90,label:"90d"},{value:0,label:"All time"}];function Re({value:t,options:s,onChange:n}){return e.jsx("div",{className:"flex gap-0.5 p-0.5 rounded bg-bg-elev shadow-[inset_0_0_0_1px_rgba(0,0,0,0.06)] text-[11px]",children:s.map(c=>e.jsx("button",{onClick:()=>n(c.value),className:`px-2 py-1 rounded whitespace-nowrap font-mono ${t===c.value?"bg-bg-hi text-fg shadow-sm":"text-fg-faint hover:text-fg"}`,children:c.label},String(c.value)))})}function lt({measure:t,onMeasure:s,range:n,onRange:c,projectsShown:o,projectsTotal:r,fromDate:a,toDate:l,onRefresh:u,onExport:d,exportDisabled:i}){return e.jsxs("div",{className:"sticky top-0 z-10 border-b border-line px-4 py-2.5 flex flex-wrap items-center gap-3 backdrop-blur-sm",style:{backgroundColor:"rgba(246,239,225,0.93)"},children:[e.jsx(Re,{value:t,options:rt.map(x=>({value:x,label:Ee[x]})),onChange:s}),e.jsx(Re,{value:n,options:it,onChange:c}),e.jsxs("span",{className:"text-[11px] text-fg-faint font-mono",children:[o," / ",r," projects"]}),e.jsxs("span",{className:"text-[11px] text-fg-faint font-mono",children:[a," → ",l]}),e.jsx("div",{className:"flex-1"}),e.jsx("button",{onClick:u,className:"px-2 py-1 text-[11px] border border-line rounded hover:text-fg hover:bg-bg-hi text-fg-faint",title:"Re-fetch the rollup (no scan)",children:"↻ Refresh"}),e.jsx("button",{onClick:d,disabled:i,className:"px-2 py-1 text-[11px] border border-line rounded hover:text-fg hover:bg-bg-hi text-fg-faint disabled:opacity-40 disabled:pointer-events-none",children:"Export CSV"})]})}function E(t){const s=Number.isFinite(t)?t:0,n=Math.abs(s)<1?4:2;return`$${s.toFixed(n)}`}function z(t){const s=Number.isFinite(t)?t:0,n=Math.abs(s);return n>=1e9?`${(s/1e9).toFixed(1)}B`:n>=1e6?`${(s/1e6).toFixed(1)}M`:n>=1e3?`${(s/1e3).toFixed(1)}K`:`${Math.round(s)}`}function K(t){const s=Number.isFinite(t)?t:0;return Math.round(s).toLocaleString("en-US")}function Pe(t){const s=Math.max(0,Math.round(Number.isFinite(t)?t:0));if(s<60)return`${s}m`;const n=Math.floor(s/60),c=s%60;return c===0?`${n}h`:`${n}h ${c}m`}function Fe(t){return Number.isFinite(t)?t>0&&t<1?"<1%":`${t.toFixed(1)}%`:"0.0%"}const M="rounded-card bg-bg-hi border border-line",dt="#ded2bd",ut="#6f7d52";function D({kicker:t,title:s,right:n}){return e.jsxs("div",{className:"flex items-baseline justify-between gap-3 mb-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wider text-accent font-mono",children:t}),e.jsx("h2",{className:"font-serif text-[25px] leading-tight tracking-tight text-fg",children:s})]}),n]})}function J(t,s){switch(t){case"spend":return E(s);case"in":case"out":case"total":return z(s);case"time":return Pe(s);default:return K(s)}}function pt({measure:t,headline:s,activeDays:n,projectsTouched:c,totalSessions:o}){const r=n>0?s.value/n:0,a=o>0?s.value/o:0,{delta:l}=s,u=l&&(t==="spend"?l.direction==="down":l.direction==="up"),d=l&&l.direction!=="flat"&&(t==="spend"?l.direction==="up":l.direction==="down"),i=u?"text-delta-good":d?"text-delta-bad":"text-fg-faint";return e.jsxs("div",{className:`${M} p-4`,children:[e.jsx(D,{kicker:"01 · overview",title:Ee[t]}),e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[52px] leading-none font-mono tracking-tight text-fg",children:J(t,s.value)}),l?e.jsxs("div",{className:`text-xs font-mono mt-2 ${i}`,children:[l.direction==="up"?"▲":l.direction==="down"?"▼":"·"," ",Fe(Math.abs(l.pct??0))," vs prior period"]}):e.jsx("div",{className:"text-xs text-fg-faint mt-2",children:"no prior window to compare"})]}),e.jsx("div",{className:"flex-1 min-w-0 self-stretch",children:e.jsx(xt,{series:s.series})})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-3 mt-4 pt-3 border-t border-line",children:[e.jsx(Q,{label:"per active day",value:J(t,r)}),e.jsx(Q,{label:"per session",value:J(t,a)}),e.jsx(Q,{label:"active days",value:K(n)}),e.jsx(Q,{label:"projects touched",value:K(c)})]})]})}function Q({label:t,value:s}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-fg-faint uppercase tracking-wider",children:t}),e.jsx("div",{className:"text-[17px] font-mono tracking-tight text-fg-dim",children:s})]})}function xt({series:t}){if(t.length<2)return null;const c=Math.max(...t,0),o=Math.min(...t,0),r=c-o||1,a=160/(t.length-1),l=t.map((d,i)=>`${i*a},${48-(d-o)/r*48}`).join(" "),u=`0,48 ${l} 160,48`;return e.jsxs("svg",{viewBox:"0 0 160 48",preserveAspectRatio:"none",className:"w-full h-full min-h-[48px]",children:[e.jsx("polygon",{points:u,fill:"#b85c34",opacity:.15}),e.jsx("polyline",{points:l,fill:"none",stroke:"#b85c34",strokeWidth:1.5,vectorEffect:"non-scaling-stroke"})]})}const ht=50;function ft({days:t}){const[s,n]=m.useState(ht),c=m.useRef(!1);m.useEffect(()=>{let d=!1;return he().then(i=>{d||c.current||typeof i.budgetCapUsd=="number"&&Number.isFinite(i.budgetCapUsd)&&i.budgetCapUsd>0&&n(i.budgetCapUsd)}),()=>{d=!0}},[]);const o=d=>{c.current=!0;const i=s;n(d),ue({budgetCapUsd:d}).catch(()=>{n(i),q.error("Couldn't save the budget cap — reverted.")})},{mtdSpend:r,projectedSpend:a}=m.useMemo(()=>{const d=new Date,i=d.toLocaleDateString("en-CA").slice(0,7),x=new Date(d.getFullYear(),d.getMonth()+1,0).getDate(),f=d.getDate();let v=0;for(const C of t)if(C.date.startsWith(i))for(const S of Object.values(C.byProject))v+=S.estimatedCostUsd;return{mtdSpend:v,projectedSpend:Ze(v,f,x)}},[t]),l=a>s,u=s>0?Math.min(100,r/s*100):0;return e.jsxs("div",{className:`${M} p-3`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h3",{className:"text-[10.5px] uppercase tracking-wider text-fg-faint font-mono",children:"Monthly budget"}),e.jsxs("label",{className:"flex items-center gap-1.5 text-[10px] text-fg-faint",children:["cap",e.jsx("span",{children:"$"}),e.jsx("input",{type:"number",min:1,step:1,value:s,onChange:d=>{const i=Number(d.target.value);Number.isFinite(i)&&i>0&&o(i)},className:"w-16 bg-bg border border-line rounded px-1.5 py-0.5 text-xs text-fg font-mono"})]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs font-mono mb-1.5",children:[e.jsxs("span",{className:"text-fg",children:[E(r)," ",e.jsx("span",{className:"text-fg-faint",children:"month-to-date"})]}),e.jsxs("span",{className:l?"text-delta-bad":"text-fg-dim",children:[E(a)," ",e.jsx("span",{className:"text-fg-faint",children:"projected"})]})]}),e.jsx("div",{className:"h-1.5 rounded bg-bg-hi overflow-hidden",children:e.jsx("div",{className:`h-full ${l?"bg-delta-bad":"bg-sage"}`,style:{width:`${Math.max(u,u>0?2:0)}%`}})}),e.jsx("div",{className:`text-[10px] mt-1 font-mono ${l?"text-delta-bad":"text-fg-faint"}`,children:l?`projected to exceed $${s.toFixed(0)} cap`:`${u.toFixed(0)}% of $${s.toFixed(0)} cap`})]})}function mt({chips:t,keep:s,onToggle:n,onIsolate:c,onShowAll:o}){const r=s===null;return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsxs("button",{onClick:o,className:`px-2 py-1 rounded text-[11px] font-mono border ${r?"bg-accent text-white border-accent":"border-line text-fg-faint hover:text-fg hover:bg-bg-hi"}`,children:["show all (",t.length,")"]}),t.map(a=>{const l=r||s.has(a.projectDir);return e.jsxs("button",{onClick:u=>u.shiftKey?c(a.projectDir):n(a.projectDir),title:a.projectDir,className:`inline-flex items-center gap-1.5 px-2 py-1 rounded text-[11px] font-mono border ${l?"border-line text-fg-dim bg-bg-hi":"border-line text-fg-faint opacity-40 hover:opacity-70"}`,children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:A(a.projectDir)}}),W(a.projectDir)??a.projectDir]},a.projectDir)})]})}function jt(t,s){const n=new Map;for(const o of t)for(const[r,a]of Object.entries(o.values))n.set(r,(n.get(r)??0)+a);const c=Array.from(n.entries()).sort((o,r)=>r[1]-o[1]).map(([o])=>o);return t.map(o=>{const r=c.reduce((u,d)=>u+(o.values[d]??0),0);let a=0;const l=c.map(u=>{const d=o.values[u]??0;if(r<=0)return{projectDir:u,value:d,y0:0,y1:0};const i=s==="share"?d/r:d,x=a,f=a+i;return a=f,{projectDir:u,value:d,y0:x,y1:f}});return{date:o.date,bands:l,total:r}})}const ie=720,le=220,de=44,gt=20;function kt(t,s){return t==="spend"?E(s):z(s)}function bt({days:t,measure:s,selected:n,onSelect:c}){const[o,r]=m.useState("absolute"),a=m.useMemo(()=>jt(t,o),[t,o]),l=m.useMemo(()=>{if(o==="share")return 1;let h=0;for(const k of a)h=Math.max(h,k.total);return h||1},[a,o]),u=ie-de,d=le-gt,i=a.length>1?u/(a.length-1):u,x=h=>de+h*i,f=h=>d-h/l*d,v=Math.max(1,Math.ceil(a.length/8)),C=4,S=Array.from({length:C+1},(h,k)=>l/C*k);return e.jsxs("div",{className:`${M} p-4`,children:[e.jsx(D,{kicker:"02 · over time",title:"Trend by project",right:e.jsx("div",{className:"flex border border-line rounded overflow-hidden text-[10px] font-mono",children:["absolute","share"].map(h=>e.jsx("button",{onClick:()=>r(h),className:`px-2 py-0.5 ${o===h?"bg-accent text-white":"text-fg-faint hover:text-fg"}`,children:h},h))})}),e.jsxs("svg",{width:"100%",viewBox:`0 0 ${ie} ${le}`,className:"overflow-visible",children:[S.map((h,k)=>e.jsxs("g",{children:[e.jsx("line",{x1:de,x2:ie,y1:f(h),y2:f(h),stroke:"currentColor",className:"text-line",strokeWidth:1}),e.jsx("text",{x:0,y:f(h)+3,fontSize:9,className:"fill-fg-faint",children:o==="share"?`${Math.round(h*100)}%`:kt(s,h)})]},k)),a.map((h,k)=>{if(k===0)return null;const P=a[k-1];return h.bands.map((j,te)=>{const G=P.bands[te],B=n!==null&&n!==j.projectDir,se=B?dt:A(j.projectDir),ne=[`${x(k-1)},${f(G.y0)}`,`${x(k)},${f(j.y0)}`,`${x(k)},${f(j.y1)}`,`${x(k-1)},${f(G.y1)}`].join(" ");return e.jsx("polygon",{points:ne,fill:se,opacity:B?.6:.75,className:"cursor-pointer",onClick:()=>c(n===j.projectDir?null:j.projectDir),children:e.jsx("title",{children:W(j.projectDir)??j.projectDir})},`${j.projectDir}-${k}`)})}),a.map((h,k)=>k%v!==0&&k!==a.length-1?null:e.jsx("text",{x:x(k),y:le-4,fontSize:9,textAnchor:"middle",className:"fill-fg-faint",children:h.date.slice(5)},h.date))]})]})}function vt({rows:t,measure:s,selected:n,onSelect:c}){return t.length?e.jsxs("div",{className:`${M} overflow-hidden`,children:[e.jsx("div",{className:"p-4 pb-0",children:e.jsx(D,{kicker:"03 · by project",title:"Ranking"})}),e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"bg-bg-elev",children:e.jsx("tr",{children:["project","share","value","share %","trend","sessions","top tool"].map(o=>e.jsx("th",{className:"text-left px-3 py-2 text-fg-faint uppercase tracking-wider whitespace-nowrap",children:o},o))})}),e.jsx("tbody",{children:t.map(o=>{const r=A(o.projectDir),a=n===o.projectDir;return e.jsxs("tr",{onClick:()=>c(o.projectDir),className:`border-t border-line hover:bg-bg-elev cursor-pointer ${a?"bg-bg-elev":""}`,children:[e.jsx("td",{className:"px-3 py-2 font-mono text-fg-dim",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:r}}),W(o.projectDir)??o.projectDir]})}),e.jsx("td",{className:"px-3 py-2 w-32",children:e.jsx("div",{className:"h-1.5 rounded bg-bg-hi overflow-hidden",children:e.jsx("div",{className:"h-full",style:{width:`${Math.max(o.sharePct,o.sharePct>0?2:0)}%`,backgroundColor:r}})})}),e.jsx("td",{className:"px-3 py-2 text-fg-faint font-mono",children:J(s,o.value)}),e.jsxs("td",{className:"px-3 py-2 text-fg-faint font-mono",children:[o.sharePct.toFixed(1),"%"]}),e.jsx("td",{className:"px-3 py-2 font-mono",children:o.trend.pct===null?e.jsx("span",{className:"text-fg-faint",children:"—"}):e.jsxs("span",{className:o.trend.direction==="up"?"text-delta-good":o.trend.direction==="down"?"text-delta-bad":"text-fg-faint",children:[o.trend.direction==="up"?"▲":o.trend.direction==="down"?"▼":"·"," ",Fe(Math.abs(o.trend.pct))]})}),e.jsx("td",{className:"px-3 py-2 text-fg-faint font-mono",children:K(o.sessions)}),e.jsx("td",{className:"px-3 py-2 text-fg-faint font-mono",children:o.topTool||"—"})]},o.projectDir)})})]})]}):e.jsxs("div",{className:`${M} p-4`,children:[e.jsx(D,{kicker:"03 · by project",title:"Ranking"}),e.jsx("div",{className:"text-xs text-fg-faint",children:"no projects in range"})]})}function Ct({projectDir:t,totals:s,byModel:n,toolBreakdown:c,onClear:o}){var i;const r=R(s,"in"),a=R(s,"out"),l=Object.entries(n).sort((x,f)=>f[1].costUsd-x[1].costUsd),u=Object.entries(c).sort((x,f)=>f[1]-x[1]),d=((i=u[0])==null?void 0:i[1])??0;return e.jsxs("div",{className:`${M} p-4`,children:[e.jsx(D,{kicker:"04 · drill in",title:W(t)??t,right:e.jsx("button",{onClick:o,className:"text-[11px] text-fg-faint hover:text-fg font-mono",children:"clear ✕"})}),e.jsx("div",{className:"flex items-center gap-1.5 -mt-2 mb-3",children:e.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:A(t)}})}),e.jsxs("div",{className:"grid grid-cols-6 gap-3 mb-4",children:[e.jsx(I,{label:"prompts",value:K(s.promptCount)}),e.jsx(I,{label:"sessions",value:K(s.sessionCount)}),e.jsx(I,{label:"in tokens",value:z(r)}),e.jsx(I,{label:"out tokens",value:z(a)}),e.jsx(I,{label:"spend",value:E(s.estimatedCostUsd)}),e.jsx(I,{label:"time",value:Pe(s.activeMinutes)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-fg-faint uppercase tracking-wider mb-1.5",children:"model mix"}),l.length===0?e.jsx("div",{className:"text-xs text-fg-faint",children:"no model data"}):e.jsx("div",{className:"space-y-1",children:l.map(([x,f])=>e.jsxs("div",{className:"flex items-center justify-between text-[11px] font-mono text-fg-dim",children:[e.jsx("span",{children:xe(x)}),e.jsx("span",{className:"text-fg-faint",children:E(f.costUsd)})]},x))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-fg-faint uppercase tracking-wider mb-1.5",children:"tool mix"}),u.length===0?e.jsx("div",{className:"text-xs text-fg-faint",children:"no tool data"}):e.jsx("div",{className:"space-y-1",children:u.slice(0,6).map(([x,f])=>e.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[e.jsx("span",{className:"w-20 shrink-0 truncate text-fg-dim font-mono",children:x}),e.jsx("div",{className:"flex-1 h-1.5 rounded bg-bg-hi overflow-hidden",children:e.jsx("div",{className:"h-full bg-hive-teal",style:{width:`${d>0?f/d*100:0}%`}})}),e.jsx("span",{className:"text-fg-faint font-mono w-8 text-right",children:f})]},x))})]})]})]})}function I({label:t,value:s}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-fg-faint uppercase tracking-wider",children:t}),e.jsx("div",{className:"text-[17px] font-mono tracking-tight text-fg",children:s})]})}function Tt({byModelTotals:t}){const s=Object.entries(t).sort((c,o)=>o[1].costUsd-c[1].costUsd),n=s.reduce((c,[,o])=>c+o.costUsd,0);return e.jsxs("div",{className:`${M} p-4`,children:[e.jsx(D,{kicker:"05 · composition",title:"Model mix",right:e.jsxs("span",{className:"text-xs font-mono text-fg-faint",children:[E(n)," total"]})}),s.length===0?e.jsx("div",{className:"text-xs text-fg-faint",children:"no model data in range"}):e.jsx("div",{className:"space-y-2",children:s.map(([c,o])=>{const r=n>0?o.costUsd/n*100:0,a=A(c);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-0.5",children:[e.jsxs("span",{className:"flex items-center gap-1.5 font-mono text-fg-dim truncate",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm shrink-0",style:{backgroundColor:a}}),xe(c),o.estimated&&e.jsx("span",{className:"text-fg-faint",children:"(est.)"})]}),e.jsxs("span",{className:"text-fg-faint whitespace-nowrap ml-2",children:[E(o.costUsd)," · ",r.toFixed(0),"%"]})]}),e.jsx("div",{className:"h-1.5 rounded bg-bg-hi overflow-hidden",children:e.jsx("div",{className:"h-full",style:{width:`${Math.max(r,r>0?2:0)}%`,backgroundColor:a}})})]},c)})})]})}function yt({rows:t}){const s=t.slice(0,3),n=s.reduce((r,a)=>r+a.sharePct,0),c=t.slice(3),o=c.reduce((r,a)=>r+a.sharePct,0);return e.jsxs("div",{className:`${M} p-4`,children:[e.jsx(D,{kicker:"05 · composition",title:"Concentration",right:e.jsxs("span",{className:"text-xs font-mono text-fg-faint",children:["top 3 = ",n.toFixed(0),"%"]})}),t.length===0?e.jsx("div",{className:"text-xs text-fg-faint",children:"no projects in range"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex h-3 rounded overflow-hidden mb-2",children:t.map(r=>e.jsx("div",{style:{width:`${Math.max(r.sharePct,.5)}%`,backgroundColor:A(r.projectDir)},title:`${W(r.projectDir)??r.projectDir} · ${r.sharePct.toFixed(1)}%`},r.projectDir))}),e.jsx("div",{className:"space-y-1 mb-2",children:s.map(r=>e.jsxs("div",{className:"flex items-center justify-between text-[11px] font-mono",children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-fg-dim truncate",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:A(r.projectDir)}}),W(r.projectDir)??r.projectDir]}),e.jsxs("span",{className:"text-fg-faint",children:[r.sharePct.toFixed(1),"%"]})]},r.projectDir))}),c.length>0&&e.jsxs("p",{className:"text-[10px] text-fg-faint",children:[c.length," more project",c.length===1?"":"s"," account for ",o.toFixed(1),"% (long tail)."]})]})]})}const ee=30,pe=9,F=(ee+pe)*2;function Nt({totals:t}){const s=t.inputTokens+t.cacheReadTokens+t.cacheCreationTokens,n=s>0?t.cacheReadTokens/s*100:0,c=2*Math.PI*ee,o=F/2;return e.jsxs("div",{className:`${M} p-4`,children:[e.jsx(D,{kicker:"05 · composition",title:"Cache"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"relative shrink-0",style:{width:F,height:F},children:[e.jsxs("svg",{width:F,height:F,viewBox:`0 0 ${F} ${F}`,className:"-rotate-90",children:[e.jsx("circle",{cx:o,cy:o,r:ee,fill:"none",stroke:"currentColor",className:"text-bg-hi",strokeWidth:pe}),e.jsx("circle",{cx:o,cy:o,r:ee,fill:"none",stroke:ut,strokeWidth:pe,strokeDasharray:c,strokeDashoffset:c*(1-n/100),strokeLinecap:"round"})]}),e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center text-[13px] font-mono text-fg",children:[n.toFixed(0),"%"]})]}),e.jsxs("div",{className:"text-[11px] space-y-1 font-mono",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-fg-faint",children:"reused (cache read)"}),e.jsx("span",{className:"text-fg-dim",children:z(t.cacheReadTokens)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-fg-faint",children:"written to cache"}),e.jsx("span",{className:"text-fg-dim",children:z(t.cacheCreationTokens)})]})]})]})]})}const wt=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function Mt({days:t,measure:s}){const{buckets:n,weekendShare:c,peakIdx:o}=m.useMemo(()=>{const a=new Array(7).fill(0);for(const i of t){const[x,f,v]=i.date.split("-").map(Number),C=new Date(x,f-1,v).getDay();a[C]+=R(i.totals,s)}const l=a.reduce((i,x)=>i+x,0),u=a[0]+a[6];let d=0;for(let i=1;i<7;i++)a[i]>a[d]&&(d=i);return{buckets:a,weekendShare:l>0?u/l*100:0,peakIdx:d}},[t,s]),r=Math.max(...n,1);return e.jsxs("div",{className:`${M} p-4`,children:[e.jsx(D,{kicker:"05 · composition",title:"Rhythm",right:e.jsxs("span",{className:"text-xs font-mono text-fg-faint",children:["weekend ",c.toFixed(0),"%"]})}),e.jsx("div",{className:"flex items-end gap-2 h-24",children:n.map((a,l)=>e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-end gap-1 h-full",children:[e.jsx("div",{className:`w-full rounded-t ${l===o?"bg-accent":"bg-rhythm"}`,style:{height:`${r>0?a/r*100:0}%`,minHeight:a>0?2:0}}),e.jsx("span",{className:"text-[9px] text-fg-faint font-mono",children:wt[l]})]},l))})]})}const St=["in","out","total","prompts","sessions","time","spend"],$t=[30,60,90,0],Rt="spend",Dt=30,Ut=[];function Et(){return{promptCount:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,toolCallCount:0,sessionCount:0,errorCount:0,activeMinutes:0,estimatedCostUsd:0}}function Pt(){var be;const[t,s]=m.useState(Rt),[n,c]=m.useState(Dt),o=m.useRef(!1),r=m.useRef(!1),a=p=>{o.current=!0;const g=t;s(p),ue({measure:p}).catch(()=>{s(g),q.error("Couldn't save the measure preference — reverted.")})},l=p=>{r.current=!0;const g=n;c(p),ue({range:p}).catch(()=>{c(g),q.error("Couldn't save the range preference — reverted.")})};m.useEffect(()=>{let p=!1;return he().then(g=>{p||(!o.current&&g.measure&&St.includes(g.measure)&&s(g.measure),!r.current&&g.range!==void 0&&$t.includes(g.range)&&c(g.range))}),()=>{p=!0}},[]);const u=We(p=>p.navFace),d=Ne(p=>p.tabs),i=Ne(p=>p.activeTabId),x=((be=d.find(p=>p.id===i))==null?void 0:be.cwd)??null,f=m.useRef(u),v=x?ze(x):null,[C,S]=m.useState(null),h=m.useMemo(()=>u==="project"&&v?new Set([v]):C,[u,v,C]),[k,P]=m.useState(null),[j,te]=m.useState(null),[G,B]=m.useState(!0),[se,ne]=m.useState(0);m.useEffect(()=>{let p=!1;return B(!0),window.api.history.dashboard({rangeDays:n}).then(g=>{p||(te(g),B(!1))}).catch(g=>{p||(B(!1),q.error(`History analytics failed to load: ${String(g)}`))}),()=>{p=!0}},[n,se]);const fe=m.useRef(!1);m.useEffect(()=>{if(!fe.current){fe.current=!0;return}S(null),P(null)},[n]),m.useEffect(()=>{f.current!==u&&(f.current=u,u==="home"&&S(null))},[u]);const{projects:me,resolving:je}=Ke(),ge=m.useMemo(()=>{const p={};for(const g of me)for(const T of g.encodedIds)p[T]=g.cwd;return p},[me]),_=m.useMemo(()=>j&&!je?ot(j.days,ge):null,[j,ge,je]),y=(_==null?void 0:_.days)??(j==null?void 0:j.days)??Ut,oe=(_==null?void 0:_.excluded)??null,$=m.useMemo(()=>j?Xe({days:y,totals:j.totals,prevTotals:j.prevTotals},h):null,[j,y,h]),O=m.useMemo(()=>h===null?y:y.map(p=>({date:p.date,byProject:Object.fromEntries(Object.entries(p.byProject).filter(([g])=>h.has(g)))})),[y,h]),Y=m.useMemo(()=>Me(y,t),[y,t]),ae=m.useMemo(()=>Me(O,t),[O,t]),Ae=m.useMemo(()=>O.map(p=>({date:p.date,values:Object.fromEntries(Object.entries(p.byProject).map(([g,T])=>[g,R(T,t)]))})),[O,t]),ke=m.useMemo(()=>$?Qe($,t):null,[$,t]),V=m.useMemo(()=>{if(!j||!k)return null;const p=Et(),g={},T={};for(const H of y){const b=H.byProject[k];if(b){p.promptCount+=b.promptCount,p.inputTokens+=b.inputTokens,p.outputTokens+=b.outputTokens,p.cacheReadTokens+=b.cacheReadTokens,p.cacheCreationTokens+=b.cacheCreationTokens,p.toolCallCount+=b.toolCallCount,p.sessionCount+=b.sessionCount,p.errorCount+=b.errorCount,p.activeMinutes+=b.activeMinutes,p.estimatedCostUsd+=b.estimatedCostUsd;for(const[N,w]of Object.entries(b.byModel)){const U=g[N]??(g[N]={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0});U.inputTokens+=w.inputTokens,U.outputTokens+=w.outputTokens,U.cacheReadTokens+=w.cacheReadTokens,U.cacheCreationTokens+=w.cacheCreationTokens,U.costUsd+=w.costUsd}for(const[N,w]of Object.entries(b.toolBreakdown))T[N]=(T[N]??0)+w}}return{totals:p,byModel:g,toolBreakdown:T}},[j,y,k]);m.useEffect(()=>{k&&h!==null&&!h.has(k)&&P(null)},[k,h]);function Be(p){S(g=>{const T=new Set(Y.map(N=>N.projectDir)),H=g??new Set(T),b=new Set(H);return b.has(p)?b.delete(p):b.add(p),b.size>=T.size?null:b})}function _e(p){S(new Set([p]))}function Oe(){S(null)}function He(){if(!j)return;const p=O.map(N=>{let w=0,U=0,ve=0,Ce=0,Te=0;const ce={};for(const L of Object.values(N.byProject)){w+=L.estimatedCostUsd,U+=L.inputTokens,ve+=L.outputTokens,Ce+=L.cacheCreationTokens,Te+=L.cacheReadTokens;for(const[ye,X]of Object.entries(L.byModel)){const Z=ce[ye]??(ce[ye]={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0});Z.inputTokens+=X.inputTokens,Z.outputTokens+=X.outputTokens,Z.cacheReadTokens+=X.cacheReadTokens,Z.cacheCreationTokens+=X.cacheCreationTokens}}return{date:N.date,costUsd:w,inputTokens:U,outputTokens:ve,cacheCreationTokens:Ce,cacheReadTokens:Te,byModel:ce}}),g=et(p),T=new Blob([g],{type:"text/csv"}),H=URL.createObjectURL(T),b=document.createElement("a");b.href=H,b.download=`usage-history-${j.from}-${j.to}.csv`,b.click(),URL.revokeObjectURL(H)}return G&&!j?e.jsx(De,{}):j&&j.days.length===0?e.jsx(Ge,{title:"no sessions in range",hint:"Widen the range or check back after your next session."}):!j||!$||!ke?e.jsx(De,{}):e.jsxs("div",{"data-testid":"history-dashboard",className:"flex flex-col h-full",children:[e.jsxs("h1",{className:"font-serif text-[42px] leading-tight tracking-tight text-fg px-4 pt-4",children:["Where your ",e.jsx("em",{className:"italic text-accent",children:"Claude time"})," goes"]}),e.jsx(lt,{measure:t,onMeasure:a,range:n,onRange:l,projectsShown:h===null?Y.length:h.size,projectsTotal:Y.length,fromDate:j.from,toDate:j.to,onRefresh:()=>ne(p=>p+1),onExport:He,exportDisabled:O.length===0}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-4 space-y-4",children:[e.jsx(pt,{measure:t,headline:ke,activeDays:$.activeDays,projectsTouched:ae.length,totalSessions:$.totals.sessionCount}),e.jsx(ft,{days:y}),oe&&at(oe)&&e.jsx("div",{"data-testid":"history-excluded-note",className:"rounded-[10px] border border-line bg-bg-hi px-3 py-2 text-[11.5px] font-mono text-fg-faint",title:"A project is a working directory. ~/.claude/projects holds one folder per path the CLI was ever launched from — throwaway /tmp dirs and test fixtures included — and a folder whose cwd can't be recovered from its transcripts is not a project. Their totals are stated here rather than silently folded into the charts.",children:ct(oe)}),u==="home"&&e.jsx(mt,{chips:Y.map(p=>({projectDir:p.projectDir,value:p.value})),keep:h,onToggle:Be,onIsolate:_e,onShowAll:Oe}),e.jsx(bt,{days:Ae,measure:t,selected:k,onSelect:P}),e.jsx(vt,{rows:ae,measure:t,selected:k,onSelect:P}),k&&V&&e.jsx(Ct,{projectDir:k,totals:V.totals,byModel:V.byModel,toolBreakdown:V.toolBreakdown,onClear:()=>P(null)}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(Tt,{byModelTotals:$.byModelTotals}),e.jsx(yt,{rows:ae}),e.jsx(Nt,{totals:$.totals}),e.jsx(Mt,{days:$.days,measure:t})]})]})]})}function De(){return e.jsxs("div",{className:"p-4 space-y-4 animate-pulse",children:[e.jsx("div",{className:"h-24 bg-bg-elev rounded"}),e.jsx("div",{className:"h-16 bg-bg-elev rounded"}),e.jsx("div",{className:"h-8 bg-bg-elev rounded"}),e.jsx("div",{className:"h-56 bg-bg-elev rounded"}),e.jsx("div",{className:"h-40 bg-bg-elev rounded"})]})}function Ft(){return e.jsx(Ye,{children:e.jsx(Pt,{})})}const _t=m.memo(Ft);export{_t as History};
1
+ import{as as xe,aB as Le,ba as Ie,aj as e,ay as m,aM as q,at as A,au as W,aX as We,b3 as Ne,an as ze,aW as Ke,m as Ge,v as Ye}from"./index-vx8O73l8.js";import"./monaco-editor-BW5C4Iv1.js";function re(){return{promptCount:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,toolCallCount:0,sessionCount:0,errorCount:0,activeMinutes:0,estimatedCostUsd:0}}function we(t,s){t.promptCount+=s.promptCount,t.inputTokens+=s.inputTokens,t.outputTokens+=s.outputTokens,t.cacheReadTokens+=s.cacheReadTokens,t.cacheCreationTokens+=s.cacheCreationTokens,t.toolCallCount+=s.toolCallCount,t.sessionCount+=s.sessionCount,t.errorCount+=s.errorCount,t.activeMinutes+=s.activeMinutes,t.estimatedCostUsd+=s.estimatedCostUsd}function Xe(t){return t.promptCount>0||t.sessionCount>0||t.toolCallCount>0||t.inputTokens>0||t.outputTokens>0}function Ve(t,s){const n=s===null,c=[],o=re(),r={};let a=0;for(const l of t.days){const u=re();let d=!1;for(const[i,x]of Object.entries(l.byProject))if(!(!n&&!s.has(i))){we(u,x),we(o,x),Xe(x)&&(d=!0);for(const[f,v]of Object.entries(x.byModel)){const C=r[f]??(r[f]={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0});C.inputTokens+=v.inputTokens,C.outputTokens+=v.outputTokens,C.cacheReadTokens+=v.cacheReadTokens,C.cacheCreationTokens+=v.cacheCreationTokens,C.costUsd+=v.costUsd,v.estimated&&(C.estimated=!0)}}d&&(a+=1),c.push({date:l.date,totals:u})}return{days:c,totals:o,prevTotals:n?t.prevTotals:re(),prevAvailable:n,byModelTotals:r,activeDays:a}}function Ue(t,s){if(!s)return{pct:null,direction:"flat"};const n=(t-s)/s*100,c=n>0?"up":n<0?"down":"flat";return{pct:n,direction:c}}function Qe(t,s,n){return s<=0?0:t/s*n}const Ee={in:"In tokens",out:"Out tokens",total:"Total tokens",prompts:"Prompts",sessions:"Sessions",time:"Time",spend:"Spend"};function R(t,s){const n=t.inputTokens+t.cacheReadTokens+t.cacheCreationTokens;switch(s){case"in":return n;case"out":return t.outputTokens;case"total":return n+t.outputTokens;case"prompts":return t.promptCount;case"sessions":return t.sessionCount;case"time":return t.activeMinutes;case"spend":return t.estimatedCostUsd}}function Ze(t,s){const n=R(t.totals,s),c=t.prevAvailable?Ue(n,R(t.prevTotals,s)):null,o=t.days.map(r=>R(r.totals,s));return{value:n,delta:c,series:o}}function Me(t,s){const n=new Map,c=Math.ceil(t.length/2);t.forEach((a,l)=>{for(const[u,d]of Object.entries(a.byProject)){let i=n.get(u);i||(i={totals:{promptCount:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,toolCallCount:0,sessionCount:0,errorCount:0,activeMinutes:0,estimatedCostUsd:0},toolBreakdown:{},firstHalf:0,secondHalf:0},n.set(u,i)),i.totals.promptCount+=d.promptCount,i.totals.inputTokens+=d.inputTokens,i.totals.outputTokens+=d.outputTokens,i.totals.cacheReadTokens+=d.cacheReadTokens,i.totals.cacheCreationTokens+=d.cacheCreationTokens,i.totals.toolCallCount+=d.toolCallCount,i.totals.sessionCount+=d.sessionCount,i.totals.errorCount+=d.errorCount,i.totals.activeMinutes+=d.activeMinutes,i.totals.estimatedCostUsd+=d.estimatedCostUsd;for(const[f,v]of Object.entries(d.toolBreakdown))i.toolBreakdown[f]=(i.toolBreakdown[f]??0)+v;const x=R(d,s);l<c?i.firstHalf+=x:i.secondHalf+=x}});const o=Array.from(n.entries()).map(([a,l])=>{let u="",d=-1;for(const[i,x]of Object.entries(l.toolBreakdown))x>d&&(d=x,u=i);return{projectDir:a,value:R(l.totals,s),sharePct:0,trend:Ue(l.secondHalf,l.firstHalf),sessions:l.totals.sessionCount,topTool:u}}),r=o.reduce((a,l)=>a+l.value,0);for(const a of o)a.sharePct=r>0?a.value/r*100:0;return o.sort((a,l)=>l.value-a.value)}const qe=["date","cost_usd","input_tokens","output_tokens","cache_write_tokens","cache_read_tokens","total_tokens","cache_hit_pct","num_models","top_model"];function Je(t){return/[",\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}function Se(t){return t.inputTokens+t.outputTokens+t.cacheReadTokens+t.cacheCreationTokens}function et(t){const s=t.map(n=>{const c=n.inputTokens+n.outputTokens+n.cacheCreationTokens+n.cacheReadTokens,o=n.inputTokens+n.cacheReadTokens+n.cacheCreationTokens,r=o>0?n.cacheReadTokens/o*100:0,a=Object.entries(n.byModel).filter(([,i])=>Se(i)>0);let l="",u=-1;for(const[i,x]of a){const f=Se(x);f>u&&(u=f,l=i)}return[n.date,n.costUsd.toFixed(4),String(n.inputTokens),String(n.outputTokens),String(n.cacheCreationTokens),String(n.cacheReadTokens),String(c),r.toFixed(1),String(a.length),l?xe(l):""].map(Je).join(",")});return[qe.join(","),...s].join(`
2
+ `)}const tt={folderCount:0,sessionCount:0,promptCount:0,estimatedCostUsd:0,totalTokens:0};function st(t,s){t.promptCount+=s.promptCount,t.inputTokens+=s.inputTokens,t.outputTokens+=s.outputTokens,t.cacheReadTokens+=s.cacheReadTokens,t.cacheCreationTokens+=s.cacheCreationTokens,t.toolCallCount+=s.toolCallCount,t.sessionCount+=s.sessionCount,t.errorCount+=s.errorCount,t.activeMinutes+=s.activeMinutes,t.estimatedCostUsd+=s.estimatedCostUsd;for(const[n,c]of Object.entries(s.toolBreakdown??{}))t.toolBreakdown[n]=(t.toolBreakdown[n]??0)+c;for(const[n,c]of Object.entries(s.byModel??{})){const o=t.byModel[n]??(t.byModel[n]={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0});o.inputTokens+=c.inputTokens,o.outputTokens+=c.outputTokens,o.cacheReadTokens+=c.cacheReadTokens,o.cacheCreationTokens+=c.cacheCreationTokens,o.costUsd+=c.costUsd,c.estimated&&(o.estimated=!0)}}function nt(t,s){const n={};for(const[c,o]of Object.entries(t.byModel??{}))n[c]={...o};return{...t,projectDir:s,toolBreakdown:{...t.toolBreakdown??{}},byModel:n}}function ot(t,s){const n={...tt},c=new Set,o=t.map(r=>{const a={};for(const[l,u]of Object.entries(r.byProject)){const d=s[l];if(!d){c.add(l),n.sessionCount+=u.sessionCount,n.promptCount+=u.promptCount,n.estimatedCostUsd+=u.estimatedCostUsd,n.totalTokens+=u.inputTokens+u.outputTokens;continue}const i=a[d];i?st(i,u):a[d]=nt(u,d)}return{...r,byProject:a}});return n.folderCount=c.size,{days:o,excluded:n}}function at(t){return t.folderCount>0}function ct(t){const s=[`${t.folderCount} transcript folder${t.folderCount===1?"":"s"} with no resolvable working directory`];return t.sessionCount&&s.push(`${t.sessionCount.toLocaleString()} sessions`),t.promptCount&&s.push(`${t.promptCount.toLocaleString()} prompts`),t.estimatedCostUsd>=.005&&s.push(`$${t.estimatedCostUsd.toFixed(2)}`),`Excluded: ${s.join(" · ")}`}async function he(){return(await Le()).history??{}}let $e=Promise.resolve();function ue(t){const s=$e.then(async()=>{const n=await he();await Ie({history:{...n,...t}})});return $e=s.catch(()=>{}),s}const rt=["in","out","total","prompts","sessions","time","spend"],it=[{value:30,label:"30d"},{value:60,label:"60d"},{value:90,label:"90d"},{value:0,label:"All time"}];function Re({value:t,options:s,onChange:n}){return e.jsx("div",{className:"flex gap-0.5 p-0.5 rounded bg-bg-elev shadow-[inset_0_0_0_1px_rgba(0,0,0,0.06)] text-[11px]",children:s.map(c=>e.jsx("button",{onClick:()=>n(c.value),className:`px-2 py-1 rounded whitespace-nowrap font-mono ${t===c.value?"bg-bg-hi text-fg shadow-sm":"text-fg-faint hover:text-fg"}`,children:c.label},String(c.value)))})}function lt({measure:t,onMeasure:s,range:n,onRange:c,projectsShown:o,projectsTotal:r,fromDate:a,toDate:l,onRefresh:u,onExport:d,exportDisabled:i}){return e.jsxs("div",{className:"sticky top-0 z-10 border-b border-line px-4 py-2.5 flex flex-wrap items-center gap-3 backdrop-blur-sm",style:{backgroundColor:"rgba(246,239,225,0.93)"},children:[e.jsx(Re,{value:t,options:rt.map(x=>({value:x,label:Ee[x]})),onChange:s}),e.jsx(Re,{value:n,options:it,onChange:c}),e.jsxs("span",{className:"text-[11px] text-fg-faint font-mono",children:[o," / ",r," projects"]}),e.jsxs("span",{className:"text-[11px] text-fg-faint font-mono",children:[a," → ",l]}),e.jsx("div",{className:"flex-1"}),e.jsx("button",{onClick:u,className:"px-2 py-1 text-[11px] border border-line rounded hover:text-fg hover:bg-bg-hi text-fg-faint",title:"Re-fetch the rollup (no scan)",children:"↻ Refresh"}),e.jsx("button",{onClick:d,disabled:i,className:"px-2 py-1 text-[11px] border border-line rounded hover:text-fg hover:bg-bg-hi text-fg-faint disabled:opacity-40 disabled:pointer-events-none",children:"Export CSV"})]})}function E(t){const s=Number.isFinite(t)?t:0,n=Math.abs(s)<1?4:2;return`$${s.toFixed(n)}`}function z(t){const s=Number.isFinite(t)?t:0,n=Math.abs(s);return n>=1e9?`${(s/1e9).toFixed(1)}B`:n>=1e6?`${(s/1e6).toFixed(1)}M`:n>=1e3?`${(s/1e3).toFixed(1)}K`:`${Math.round(s)}`}function K(t){const s=Number.isFinite(t)?t:0;return Math.round(s).toLocaleString("en-US")}function Pe(t){const s=Math.max(0,Math.round(Number.isFinite(t)?t:0));if(s<60)return`${s}m`;const n=Math.floor(s/60),c=s%60;return c===0?`${n}h`:`${n}h ${c}m`}function Fe(t){return Number.isFinite(t)?t>0&&t<1?"<1%":`${t.toFixed(1)}%`:"0.0%"}const M="rounded-card bg-bg-hi border border-line",dt="#ded2bd",ut="#6f7d52";function D({kicker:t,title:s,right:n}){return e.jsxs("div",{className:"flex items-baseline justify-between gap-3 mb-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wider text-accent font-mono",children:t}),e.jsx("h2",{className:"font-serif text-[25px] leading-tight tracking-tight text-fg",children:s})]}),n]})}function J(t,s){switch(t){case"spend":return E(s);case"in":case"out":case"total":return z(s);case"time":return Pe(s);default:return K(s)}}function pt({measure:t,headline:s,activeDays:n,projectsTouched:c,totalSessions:o}){const r=n>0?s.value/n:0,a=o>0?s.value/o:0,{delta:l}=s,u=l&&(t==="spend"?l.direction==="down":l.direction==="up"),d=l&&l.direction!=="flat"&&(t==="spend"?l.direction==="up":l.direction==="down"),i=u?"text-delta-good":d?"text-delta-bad":"text-fg-faint";return e.jsxs("div",{className:`${M} p-4`,children:[e.jsx(D,{kicker:"01 · overview",title:Ee[t]}),e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[52px] leading-none font-mono tracking-tight text-fg",children:J(t,s.value)}),l?e.jsxs("div",{className:`text-xs font-mono mt-2 ${i}`,children:[l.direction==="up"?"▲":l.direction==="down"?"▼":"·"," ",Fe(Math.abs(l.pct??0))," vs prior period"]}):e.jsx("div",{className:"text-xs text-fg-faint mt-2",children:"no prior window to compare"})]}),e.jsx("div",{className:"flex-1 min-w-0 self-stretch",children:e.jsx(xt,{series:s.series})})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-3 mt-4 pt-3 border-t border-line",children:[e.jsx(Z,{label:"per active day",value:J(t,r)}),e.jsx(Z,{label:"per session",value:J(t,a)}),e.jsx(Z,{label:"active days",value:K(n)}),e.jsx(Z,{label:"projects touched",value:K(c)})]})]})}function Z({label:t,value:s}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-fg-faint uppercase tracking-wider",children:t}),e.jsx("div",{className:"text-[17px] font-mono tracking-tight text-fg-dim",children:s})]})}function xt({series:t}){if(t.length<2)return null;const c=Math.max(...t,0),o=Math.min(...t,0),r=c-o||1,a=160/(t.length-1),l=t.map((d,i)=>`${i*a},${48-(d-o)/r*48}`).join(" "),u=`0,48 ${l} 160,48`;return e.jsxs("svg",{viewBox:"0 0 160 48",preserveAspectRatio:"none",className:"w-full h-full min-h-[48px]",children:[e.jsx("polygon",{points:u,fill:"#b85c34",opacity:.15}),e.jsx("polyline",{points:l,fill:"none",stroke:"#b85c34",strokeWidth:1.5,vectorEffect:"non-scaling-stroke"})]})}const ht=50;function ft({days:t}){const[s,n]=m.useState(ht),c=m.useRef(!1);m.useEffect(()=>{let d=!1;return he().then(i=>{d||c.current||typeof i.budgetCapUsd=="number"&&Number.isFinite(i.budgetCapUsd)&&i.budgetCapUsd>0&&n(i.budgetCapUsd)}),()=>{d=!0}},[]);const o=d=>{c.current=!0;const i=s;n(d),ue({budgetCapUsd:d}).catch(()=>{n(i),q.error("Couldn't save the budget cap — reverted.")})},{mtdSpend:r,projectedSpend:a}=m.useMemo(()=>{const d=new Date,i=d.toLocaleDateString("en-CA").slice(0,7),x=new Date(d.getFullYear(),d.getMonth()+1,0).getDate(),f=d.getDate();let v=0;for(const C of t)if(C.date.startsWith(i))for(const S of Object.values(C.byProject))v+=S.estimatedCostUsd;return{mtdSpend:v,projectedSpend:Qe(v,f,x)}},[t]),l=a>s,u=s>0?Math.min(100,r/s*100):0;return e.jsxs("div",{className:`${M} p-3`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h3",{className:"text-[10.5px] uppercase tracking-wider text-fg-faint font-mono",children:"Monthly budget"}),e.jsxs("label",{className:"flex items-center gap-1.5 text-[10px] text-fg-faint",children:["cap",e.jsx("span",{children:"$"}),e.jsx("input",{type:"number",min:1,step:1,value:s,onChange:d=>{const i=Number(d.target.value);Number.isFinite(i)&&i>0&&o(i)},className:"w-16 bg-bg border border-line rounded px-1.5 py-0.5 text-xs text-fg font-mono"})]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs font-mono mb-1.5",children:[e.jsxs("span",{className:"text-fg",children:[E(r)," ",e.jsx("span",{className:"text-fg-faint",children:"month-to-date"})]}),e.jsxs("span",{className:l?"text-delta-bad":"text-fg-dim",children:[E(a)," ",e.jsx("span",{className:"text-fg-faint",children:"projected"})]})]}),e.jsx("div",{className:"h-1.5 rounded bg-bg-hi overflow-hidden",children:e.jsx("div",{className:`h-full ${l?"bg-delta-bad":"bg-sage"}`,style:{width:`${Math.max(u,u>0?2:0)}%`}})}),e.jsx("div",{className:`text-[10px] mt-1 font-mono ${l?"text-delta-bad":"text-fg-faint"}`,children:l?`projected to exceed $${s.toFixed(0)} cap`:`${u.toFixed(0)}% of $${s.toFixed(0)} cap`})]})}function mt({chips:t,keep:s,onToggle:n,onIsolate:c,onShowAll:o}){const r=s===null;return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsxs("button",{onClick:o,className:`px-2 py-1 rounded text-[11px] font-mono border ${r?"bg-accent text-white border-accent":"border-line text-fg-faint hover:text-fg hover:bg-bg-hi"}`,children:["show all (",t.length,")"]}),t.map(a=>{const l=r||s.has(a.projectDir);return e.jsxs("button",{onClick:u=>u.shiftKey?c(a.projectDir):n(a.projectDir),title:a.projectDir,className:`inline-flex items-center gap-1.5 px-2 py-1 rounded text-[11px] font-mono border ${l?"border-line text-fg-dim bg-bg-hi":"border-line text-fg-faint opacity-40 hover:opacity-70"}`,children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:A(a.projectDir)}}),W(a.projectDir)??a.projectDir]},a.projectDir)})]})}function jt(t,s){const n=new Map;for(const o of t)for(const[r,a]of Object.entries(o.values))n.set(r,(n.get(r)??0)+a);const c=Array.from(n.entries()).sort((o,r)=>r[1]-o[1]).map(([o])=>o);return t.map(o=>{const r=c.reduce((u,d)=>u+(o.values[d]??0),0);let a=0;const l=c.map(u=>{const d=o.values[u]??0;if(r<=0)return{projectDir:u,value:d,y0:0,y1:0};const i=s==="share"?d/r:d,x=a,f=a+i;return a=f,{projectDir:u,value:d,y0:x,y1:f}});return{date:o.date,bands:l,total:r}})}const ie=720,le=220,de=44,gt=20;function kt(t,s){return t==="spend"?E(s):z(s)}function bt({days:t,measure:s,selected:n,onSelect:c}){const[o,r]=m.useState("absolute"),a=m.useMemo(()=>jt(t,o),[t,o]),l=m.useMemo(()=>{if(o==="share")return 1;let h=0;for(const k of a)h=Math.max(h,k.total);return h||1},[a,o]),u=ie-de,d=le-gt,i=a.length>1?u/(a.length-1):u,x=h=>de+h*i,f=h=>d-h/l*d,v=Math.max(1,Math.ceil(a.length/8)),C=4,S=Array.from({length:C+1},(h,k)=>l/C*k);return e.jsxs("div",{className:`${M} p-4`,children:[e.jsx(D,{kicker:"02 · over time",title:"Trend by project",right:e.jsx("div",{className:"flex border border-line rounded overflow-hidden text-[10px] font-mono",children:["absolute","share"].map(h=>e.jsx("button",{onClick:()=>r(h),className:`px-2 py-0.5 ${o===h?"bg-accent text-white":"text-fg-faint hover:text-fg"}`,children:h},h))})}),e.jsxs("svg",{width:"100%",viewBox:`0 0 ${ie} ${le}`,className:"overflow-visible",children:[S.map((h,k)=>e.jsxs("g",{children:[e.jsx("line",{x1:de,x2:ie,y1:f(h),y2:f(h),stroke:"currentColor",className:"text-line",strokeWidth:1}),e.jsx("text",{x:0,y:f(h)+3,fontSize:9,className:"fill-fg-faint",children:o==="share"?`${Math.round(h*100)}%`:kt(s,h)})]},k)),a.map((h,k)=>{if(k===0)return null;const P=a[k-1];return h.bands.map((j,te)=>{const G=P.bands[te],B=n!==null&&n!==j.projectDir,se=B?dt:A(j.projectDir),ne=[`${x(k-1)},${f(G.y0)}`,`${x(k)},${f(j.y0)}`,`${x(k)},${f(j.y1)}`,`${x(k-1)},${f(G.y1)}`].join(" ");return e.jsx("polygon",{points:ne,fill:se,opacity:B?.6:.75,className:"cursor-pointer",onClick:()=>c(n===j.projectDir?null:j.projectDir),children:e.jsx("title",{children:W(j.projectDir)??j.projectDir})},`${j.projectDir}-${k}`)})}),a.map((h,k)=>k%v!==0&&k!==a.length-1?null:e.jsx("text",{x:x(k),y:le-4,fontSize:9,textAnchor:"middle",className:"fill-fg-faint",children:h.date.slice(5)},h.date))]})]})}function vt({rows:t,measure:s,selected:n,onSelect:c}){return t.length?e.jsxs("div",{className:`${M} overflow-hidden`,children:[e.jsx("div",{className:"p-4 pb-0",children:e.jsx(D,{kicker:"03 · by project",title:"Ranking"})}),e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"bg-bg-elev",children:e.jsx("tr",{children:["project","share","value","share %","trend","sessions","top tool"].map(o=>e.jsx("th",{className:"text-left px-3 py-2 text-fg-faint uppercase tracking-wider whitespace-nowrap",children:o},o))})}),e.jsx("tbody",{children:t.map(o=>{const r=A(o.projectDir),a=n===o.projectDir;return e.jsxs("tr",{onClick:()=>c(o.projectDir),className:`border-t border-line hover:bg-bg-elev cursor-pointer ${a?"bg-bg-elev":""}`,children:[e.jsx("td",{className:"px-3 py-2 font-mono text-fg-dim",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:r}}),W(o.projectDir)??o.projectDir]})}),e.jsx("td",{className:"px-3 py-2 w-32",children:e.jsx("div",{className:"h-1.5 rounded bg-bg-hi overflow-hidden",children:e.jsx("div",{className:"h-full",style:{width:`${Math.max(o.sharePct,o.sharePct>0?2:0)}%`,backgroundColor:r}})})}),e.jsx("td",{className:"px-3 py-2 text-fg-faint font-mono",children:J(s,o.value)}),e.jsxs("td",{className:"px-3 py-2 text-fg-faint font-mono",children:[o.sharePct.toFixed(1),"%"]}),e.jsx("td",{className:"px-3 py-2 font-mono",children:o.trend.pct===null?e.jsx("span",{className:"text-fg-faint",children:"—"}):e.jsxs("span",{className:o.trend.direction==="up"?"text-delta-good":o.trend.direction==="down"?"text-delta-bad":"text-fg-faint",children:[o.trend.direction==="up"?"▲":o.trend.direction==="down"?"▼":"·"," ",Fe(Math.abs(o.trend.pct))]})}),e.jsx("td",{className:"px-3 py-2 text-fg-faint font-mono",children:K(o.sessions)}),e.jsx("td",{className:"px-3 py-2 text-fg-faint font-mono",children:o.topTool||"—"})]},o.projectDir)})})]})]}):e.jsxs("div",{className:`${M} p-4`,children:[e.jsx(D,{kicker:"03 · by project",title:"Ranking"}),e.jsx("div",{className:"text-xs text-fg-faint",children:"no projects in range"})]})}function Ct({projectDir:t,totals:s,byModel:n,toolBreakdown:c,onClear:o}){var i;const r=R(s,"in"),a=R(s,"out"),l=Object.entries(n).sort((x,f)=>f[1].costUsd-x[1].costUsd),u=Object.entries(c).sort((x,f)=>f[1]-x[1]),d=((i=u[0])==null?void 0:i[1])??0;return e.jsxs("div",{className:`${M} p-4`,children:[e.jsx(D,{kicker:"04 · drill in",title:W(t)??t,right:e.jsx("button",{onClick:o,className:"text-[11px] text-fg-faint hover:text-fg font-mono",children:"clear ✕"})}),e.jsx("div",{className:"flex items-center gap-1.5 -mt-2 mb-3",children:e.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:A(t)}})}),e.jsxs("div",{className:"grid grid-cols-6 gap-3 mb-4",children:[e.jsx(I,{label:"prompts",value:K(s.promptCount)}),e.jsx(I,{label:"sessions",value:K(s.sessionCount)}),e.jsx(I,{label:"in tokens",value:z(r)}),e.jsx(I,{label:"out tokens",value:z(a)}),e.jsx(I,{label:"spend",value:E(s.estimatedCostUsd)}),e.jsx(I,{label:"time",value:Pe(s.activeMinutes)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-fg-faint uppercase tracking-wider mb-1.5",children:"model mix"}),l.length===0?e.jsx("div",{className:"text-xs text-fg-faint",children:"no model data"}):e.jsx("div",{className:"space-y-1",children:l.map(([x,f])=>e.jsxs("div",{className:"flex items-center justify-between text-[11px] font-mono text-fg-dim",children:[e.jsx("span",{children:xe(x)}),e.jsx("span",{className:"text-fg-faint",children:E(f.costUsd)})]},x))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-fg-faint uppercase tracking-wider mb-1.5",children:"tool mix"}),u.length===0?e.jsx("div",{className:"text-xs text-fg-faint",children:"no tool data"}):e.jsx("div",{className:"space-y-1",children:u.slice(0,6).map(([x,f])=>e.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[e.jsx("span",{className:"w-20 shrink-0 truncate text-fg-dim font-mono",children:x}),e.jsx("div",{className:"flex-1 h-1.5 rounded bg-bg-hi overflow-hidden",children:e.jsx("div",{className:"h-full bg-hive-teal",style:{width:`${d>0?f/d*100:0}%`}})}),e.jsx("span",{className:"text-fg-faint font-mono w-8 text-right",children:f})]},x))})]})]})]})}function I({label:t,value:s}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-fg-faint uppercase tracking-wider",children:t}),e.jsx("div",{className:"text-[17px] font-mono tracking-tight text-fg",children:s})]})}function Tt({byModelTotals:t}){const s=Object.entries(t).sort((c,o)=>o[1].costUsd-c[1].costUsd),n=s.reduce((c,[,o])=>c+o.costUsd,0);return e.jsxs("div",{className:`${M} p-4`,children:[e.jsx(D,{kicker:"05 · composition",title:"Model mix",right:e.jsxs("span",{className:"text-xs font-mono text-fg-faint",children:[E(n)," total"]})}),s.length===0?e.jsx("div",{className:"text-xs text-fg-faint",children:"no model data in range"}):e.jsx("div",{className:"space-y-2",children:s.map(([c,o])=>{const r=n>0?o.costUsd/n*100:0,a=A(c);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-0.5",children:[e.jsxs("span",{className:"flex items-center gap-1.5 font-mono text-fg-dim truncate",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm shrink-0",style:{backgroundColor:a}}),xe(c),o.estimated&&e.jsx("span",{className:"text-fg-faint",children:"(est.)"})]}),e.jsxs("span",{className:"text-fg-faint whitespace-nowrap ml-2",children:[E(o.costUsd)," · ",r.toFixed(0),"%"]})]}),e.jsx("div",{className:"h-1.5 rounded bg-bg-hi overflow-hidden",children:e.jsx("div",{className:"h-full",style:{width:`${Math.max(r,r>0?2:0)}%`,backgroundColor:a}})})]},c)})})]})}function yt({rows:t}){const s=t.slice(0,3),n=s.reduce((r,a)=>r+a.sharePct,0),c=t.slice(3),o=c.reduce((r,a)=>r+a.sharePct,0);return e.jsxs("div",{className:`${M} p-4`,children:[e.jsx(D,{kicker:"05 · composition",title:"Concentration",right:e.jsxs("span",{className:"text-xs font-mono text-fg-faint",children:["top 3 = ",n.toFixed(0),"%"]})}),t.length===0?e.jsx("div",{className:"text-xs text-fg-faint",children:"no projects in range"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex h-3 rounded overflow-hidden mb-2",children:t.map(r=>e.jsx("div",{style:{width:`${Math.max(r.sharePct,.5)}%`,backgroundColor:A(r.projectDir)},title:`${W(r.projectDir)??r.projectDir} · ${r.sharePct.toFixed(1)}%`},r.projectDir))}),e.jsx("div",{className:"space-y-1 mb-2",children:s.map(r=>e.jsxs("div",{className:"flex items-center justify-between text-[11px] font-mono",children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-fg-dim truncate",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:A(r.projectDir)}}),W(r.projectDir)??r.projectDir]}),e.jsxs("span",{className:"text-fg-faint",children:[r.sharePct.toFixed(1),"%"]})]},r.projectDir))}),c.length>0&&e.jsxs("p",{className:"text-[10px] text-fg-faint",children:[c.length," more project",c.length===1?"":"s"," account for ",o.toFixed(1),"% (long tail)."]})]})]})}const ee=30,pe=9,F=(ee+pe)*2;function Nt({totals:t}){const s=t.inputTokens+t.cacheReadTokens+t.cacheCreationTokens,n=s>0?t.cacheReadTokens/s*100:0,c=2*Math.PI*ee,o=F/2;return e.jsxs("div",{className:`${M} p-4`,children:[e.jsx(D,{kicker:"05 · composition",title:"Cache"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"relative shrink-0",style:{width:F,height:F},children:[e.jsxs("svg",{width:F,height:F,viewBox:`0 0 ${F} ${F}`,className:"-rotate-90",children:[e.jsx("circle",{cx:o,cy:o,r:ee,fill:"none",stroke:"currentColor",className:"text-bg-hi",strokeWidth:pe}),e.jsx("circle",{cx:o,cy:o,r:ee,fill:"none",stroke:ut,strokeWidth:pe,strokeDasharray:c,strokeDashoffset:c*(1-n/100),strokeLinecap:"round"})]}),e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center text-[13px] font-mono text-fg",children:[n.toFixed(0),"%"]})]}),e.jsxs("div",{className:"text-[11px] space-y-1 font-mono",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-fg-faint",children:"reused (cache read)"}),e.jsx("span",{className:"text-fg-dim",children:z(t.cacheReadTokens)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-fg-faint",children:"written to cache"}),e.jsx("span",{className:"text-fg-dim",children:z(t.cacheCreationTokens)})]})]})]})]})}const wt=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function Mt({days:t,measure:s}){const{buckets:n,weekendShare:c,peakIdx:o}=m.useMemo(()=>{const a=new Array(7).fill(0);for(const i of t){const[x,f,v]=i.date.split("-").map(Number),C=new Date(x,f-1,v).getDay();a[C]+=R(i.totals,s)}const l=a.reduce((i,x)=>i+x,0),u=a[0]+a[6];let d=0;for(let i=1;i<7;i++)a[i]>a[d]&&(d=i);return{buckets:a,weekendShare:l>0?u/l*100:0,peakIdx:d}},[t,s]),r=Math.max(...n,1);return e.jsxs("div",{className:`${M} p-4`,children:[e.jsx(D,{kicker:"05 · composition",title:"Rhythm",right:e.jsxs("span",{className:"text-xs font-mono text-fg-faint",children:["weekend ",c.toFixed(0),"%"]})}),e.jsx("div",{className:"flex items-end gap-2 h-24",children:n.map((a,l)=>e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-end gap-1 h-full",children:[e.jsx("div",{className:`w-full rounded-t ${l===o?"bg-accent":"bg-rhythm"}`,style:{height:`${r>0?a/r*100:0}%`,minHeight:a>0?2:0}}),e.jsx("span",{className:"text-[9px] text-fg-faint font-mono",children:wt[l]})]},l))})]})}const St=["in","out","total","prompts","sessions","time","spend"],$t=[30,60,90,0],Rt="spend",Dt=30,Ut=[];function Et(){return{promptCount:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,toolCallCount:0,sessionCount:0,errorCount:0,activeMinutes:0,estimatedCostUsd:0}}function Pt(){var be;const[t,s]=m.useState(Rt),[n,c]=m.useState(Dt),o=m.useRef(!1),r=m.useRef(!1),a=p=>{o.current=!0;const g=t;s(p),ue({measure:p}).catch(()=>{s(g),q.error("Couldn't save the measure preference — reverted.")})},l=p=>{r.current=!0;const g=n;c(p),ue({range:p}).catch(()=>{c(g),q.error("Couldn't save the range preference — reverted.")})};m.useEffect(()=>{let p=!1;return he().then(g=>{p||(!o.current&&g.measure&&St.includes(g.measure)&&s(g.measure),!r.current&&g.range!==void 0&&$t.includes(g.range)&&c(g.range))}),()=>{p=!0}},[]);const u=We(p=>p.navFace),d=Ne(p=>p.tabs),i=Ne(p=>p.activeTabId),x=((be=d.find(p=>p.id===i))==null?void 0:be.cwd)??null,f=m.useRef(u),v=x?ze(x):null,[C,S]=m.useState(null),h=m.useMemo(()=>u==="project"&&v?new Set([v]):C,[u,v,C]),[k,P]=m.useState(null),[j,te]=m.useState(null),[G,B]=m.useState(!0),[se,ne]=m.useState(0);m.useEffect(()=>{let p=!1;return B(!0),window.api.history.dashboard({rangeDays:n}).then(g=>{p||(te(g),B(!1))}).catch(g=>{p||(B(!1),q.error(`History analytics failed to load: ${String(g)}`))}),()=>{p=!0}},[n,se]);const fe=m.useRef(!1);m.useEffect(()=>{if(!fe.current){fe.current=!0;return}S(null),P(null)},[n]),m.useEffect(()=>{f.current!==u&&(f.current=u,u==="home"&&S(null))},[u]);const{projects:me,resolving:je}=Ke(),ge=m.useMemo(()=>{const p={};for(const g of me)for(const T of g.encodedIds)p[T]=g.cwd;return p},[me]),_=m.useMemo(()=>j&&!je?ot(j.days,ge):null,[j,ge,je]),y=(_==null?void 0:_.days)??(j==null?void 0:j.days)??Ut,oe=(_==null?void 0:_.excluded)??null,$=m.useMemo(()=>j?Ve({days:y,totals:j.totals,prevTotals:j.prevTotals},h):null,[j,y,h]),O=m.useMemo(()=>h===null?y:y.map(p=>({date:p.date,byProject:Object.fromEntries(Object.entries(p.byProject).filter(([g])=>h.has(g)))})),[y,h]),Y=m.useMemo(()=>Me(y,t),[y,t]),ae=m.useMemo(()=>Me(O,t),[O,t]),Ae=m.useMemo(()=>O.map(p=>({date:p.date,values:Object.fromEntries(Object.entries(p.byProject).map(([g,T])=>[g,R(T,t)]))})),[O,t]),ke=m.useMemo(()=>$?Ze($,t):null,[$,t]),X=m.useMemo(()=>{if(!j||!k)return null;const p=Et(),g={},T={};for(const H of y){const b=H.byProject[k];if(b){p.promptCount+=b.promptCount,p.inputTokens+=b.inputTokens,p.outputTokens+=b.outputTokens,p.cacheReadTokens+=b.cacheReadTokens,p.cacheCreationTokens+=b.cacheCreationTokens,p.toolCallCount+=b.toolCallCount,p.sessionCount+=b.sessionCount,p.errorCount+=b.errorCount,p.activeMinutes+=b.activeMinutes,p.estimatedCostUsd+=b.estimatedCostUsd;for(const[N,w]of Object.entries(b.byModel)){const U=g[N]??(g[N]={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0});U.inputTokens+=w.inputTokens,U.outputTokens+=w.outputTokens,U.cacheReadTokens+=w.cacheReadTokens,U.cacheCreationTokens+=w.cacheCreationTokens,U.costUsd+=w.costUsd}for(const[N,w]of Object.entries(b.toolBreakdown))T[N]=(T[N]??0)+w}}return{totals:p,byModel:g,toolBreakdown:T}},[j,y,k]);m.useEffect(()=>{k&&h!==null&&!h.has(k)&&P(null)},[k,h]);function Be(p){S(g=>{const T=new Set(Y.map(N=>N.projectDir)),H=g??new Set(T),b=new Set(H);return b.has(p)?b.delete(p):b.add(p),b.size>=T.size?null:b})}function _e(p){S(new Set([p]))}function Oe(){S(null)}function He(){if(!j)return;const p=O.map(N=>{let w=0,U=0,ve=0,Ce=0,Te=0;const ce={};for(const L of Object.values(N.byProject)){w+=L.estimatedCostUsd,U+=L.inputTokens,ve+=L.outputTokens,Ce+=L.cacheCreationTokens,Te+=L.cacheReadTokens;for(const[ye,V]of Object.entries(L.byModel)){const Q=ce[ye]??(ce[ye]={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0});Q.inputTokens+=V.inputTokens,Q.outputTokens+=V.outputTokens,Q.cacheReadTokens+=V.cacheReadTokens,Q.cacheCreationTokens+=V.cacheCreationTokens}}return{date:N.date,costUsd:w,inputTokens:U,outputTokens:ve,cacheCreationTokens:Ce,cacheReadTokens:Te,byModel:ce}}),g=et(p),T=new Blob([g],{type:"text/csv"}),H=URL.createObjectURL(T),b=document.createElement("a");b.href=H,b.download=`usage-history-${j.from}-${j.to}.csv`,b.click(),URL.revokeObjectURL(H)}return G&&!j?e.jsx(De,{}):j&&j.days.length===0?e.jsx(Ge,{title:"no sessions in range",hint:"Widen the range or check back after your next session."}):!j||!$||!ke?e.jsx(De,{}):e.jsxs("div",{"data-testid":"history-dashboard",className:"flex flex-col h-full",children:[e.jsxs("h1",{className:"font-serif text-[42px] leading-tight tracking-tight text-fg px-4 pt-4",children:["Where your ",e.jsx("em",{className:"italic text-accent",children:"Claude time"})," goes"]}),e.jsx(lt,{measure:t,onMeasure:a,range:n,onRange:l,projectsShown:h===null?Y.length:h.size,projectsTotal:Y.length,fromDate:j.from,toDate:j.to,onRefresh:()=>ne(p=>p+1),onExport:He,exportDisabled:O.length===0}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-4 space-y-4",children:[e.jsx(pt,{measure:t,headline:ke,activeDays:$.activeDays,projectsTouched:ae.length,totalSessions:$.totals.sessionCount}),e.jsx(ft,{days:y}),oe&&at(oe)&&e.jsx("div",{"data-testid":"history-excluded-note",className:"rounded-[10px] border border-line bg-bg-hi px-3 py-2 text-[11.5px] font-mono text-fg-faint",title:"A project is a working directory. ~/.claude/projects holds one folder per path the CLI was ever launched from — throwaway /tmp dirs and test fixtures included — and a folder whose cwd can't be recovered from its transcripts is not a project. Their totals are stated here rather than silently folded into the charts.",children:ct(oe)}),u==="home"&&e.jsx(mt,{chips:Y.map(p=>({projectDir:p.projectDir,value:p.value})),keep:h,onToggle:Be,onIsolate:_e,onShowAll:Oe}),e.jsx(bt,{days:Ae,measure:t,selected:k,onSelect:P}),e.jsx(vt,{rows:ae,measure:t,selected:k,onSelect:P}),k&&X&&e.jsx(Ct,{projectDir:k,totals:X.totals,byModel:X.byModel,toolBreakdown:X.toolBreakdown,onClear:()=>P(null)}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(Tt,{byModelTotals:$.byModelTotals}),e.jsx(yt,{rows:ae}),e.jsx(Nt,{totals:$.totals}),e.jsx(Mt,{days:$.days,measure:t})]})]})]})}function De(){return e.jsxs("div",{className:"p-4 space-y-4 animate-pulse",children:[e.jsx("div",{className:"h-24 bg-bg-elev rounded"}),e.jsx("div",{className:"h-16 bg-bg-elev rounded"}),e.jsx("div",{className:"h-8 bg-bg-elev rounded"}),e.jsx("div",{className:"h-56 bg-bg-elev rounded"}),e.jsx("div",{className:"h-40 bg-bg-elev rounded"})]})}function Ft(){return e.jsx(Ye,{children:e.jsx(Pt,{})})}const _t=m.memo(Ft);export{_t as History};
@@ -1,3 +1,3 @@
1
- import{az as d,aX as Z,aO as Q,aZ as ee,aR as F,am as te,aq as se,ag as ae,ak as e,m as E,v as R,r as oe,W as ne,H as re,X as ie,aG as le,u as ce}from"./index-Cd98Q1lD.js";import{S as de}from"./SaveBar-l9jnEMES.js";import{S as I}from"./ScopeSwitcher-CjJi8ST5.js";import{P as me}from"./ProvenanceBadge-BFczzI1B.js";import{u as pe,E as ue,s as he}from"./settingsSchema-IhUfucCF.js";import{H as xe}from"./Library-7akfgy67.js";import"./monaco-editor-BW5C4Iv1.js";const ge={UserPromptSubmit:{when:"Fires just before the user prompt is sent to the model.",payload:"{ prompt: string }",example:"Block submission if the prompt mentions a secret."},UserPromptExpansion:{when:"Fires when a slash command expands into its final prompt text.",payload:"{ command: string, expanded: string }",example:"Audit which slash commands actually run, post-expansion."},PreToolUse:{when:"Fires before any tool runs. Can block the call.",payload:"{ tool_name: string, tool_input: object }",example:'matcher="Bash" — block dangerous shell commands.'},PostToolUse:{when:"Fires after a tool completes successfully.",payload:"{ tool_name: string, tool_input: object, tool_result: string }",example:'matcher="Write|Edit" — run a linter on changed files.'},PostToolUseFailure:{when:"Fires after a tool errors out (non-zero exit, exception, or refusal).",payload:"{ tool_name: string, tool_input: object, error: string }",example:"Pipe failed Bash runs into a desktop notification."},PostToolBatch:{when:"Fires once after a parallel batch of tool calls all complete.",payload:"{ tool_uses: Array<{ tool_name, tool_input, tool_result? }> }",example:"Aggregate file-edit batches into a single commit message."},Stop:{when:"Fires when the model emits end_turn.",payload:"{ stop_reason: string, output_tokens: number }",example:"Play a chime when the agent finishes a long task."},StopFailure:{when:"Fires when a turn aborts without end_turn (rate-limit, network, OOM).",payload:'{ reason: "rate_limit"|"network"|"oom"|"killed"|string }',example:"Auto-resume on transient failures."},SessionStart:{when:"Fires once when a session boots (claude or claude -p).",payload:'{ source: "startup"|"resume", model: string, agent_type: string }',example:"Inject a project-specific system prompt addendum."},SessionEnd:{when:"Fires once when the session terminates.",payload:'{ reason: "user_quit"|"timeout"|"error"|string }',example:"Persist transcript summary to ~/.claude/projects/<>."},Setup:{when:"Fires during interactive setup (claude /setup, /init).",payload:'{ mode: "init"|"reconfigure"|string }'},PreCompact:{when:"Fires before transcript compaction runs.",payload:'{ transcript_path: string, trigger: "manual"|"auto" }',example:"Snapshot the pre-compact transcript for later diffing."},PostCompact:{when:"Fires after compaction; the active transcript is the compacted one.",payload:'{ transcript_path: string, trigger: "manual"|"auto" }'},InstructionsLoaded:{when:"Fires after CLAUDE.md and any imported memory files are loaded.",payload:'{ source: "session_start"|"reload" }'},Notification:{when:"Fires when Claude Code emits a desktop notification.",payload:"{ title: string, message: string }",example:"Forward to your own notify-send / osascript pipeline."},PermissionRequest:{when:"Fires when a tool needs user permission (per the permissions block).",payload:"{ tool_name: string, tool_input?: object }",example:"Auto-allow npm test invocations."},PermissionDenied:{when:"Fires when the user (or policy) denies a permission request.",payload:"{ tool_name: string, retry: boolean }",example:"Track which tools the user habitually rejects."},SubagentStart:{when:"Fires when a subagent (Task tool) spawns.",payload:"{ agent_type: string }",example:'matcher="security-reviewer" — log every security scan.'},SubagentStop:{when:"Fires when a subagent finishes.",payload:'{ agent_type: string, reason: "end_turn"|"error"|string }'},TeammateIdle:{when:"Fires when a teammate agent goes idle (waiting for input).",payload:"{ teammate_id?: string }"},TaskCreated:{when:"Fires when a new Task is created via the Task tool.",payload:"{ task: { description: string, ...} }",example:"Track each spawned task in an external queue."},TaskCompleted:{when:"Fires when a Task completes (success or failure).",payload:"{ task: { description: string, ...} }"},ConfigChange:{when:"Fires when settings.json (any scope) is mutated mid-session.",payload:'{ source: "user_settings"|"project_settings"|"local_settings" }',example:"Reload tooling that depends on env vars on config change."},CwdChanged:{when:"Fires when the working directory changes (e.g. agent cd-ing).",payload:"{ old_cwd: string, new_cwd: string }",example:"Refresh project-scoped indexers when cwd drifts."},FileChanged:{when:"Fires when a watched file outside Claude Code's edits changes.",payload:'{ file_path: string, change_type: "modified"|"created"|"deleted" }',example:"Re-run typecheck when any .ts file changes."},WorktreeCreate:{when:"Fires after a git worktree is created via /worktree or subagent isolation.",payload:"{ worktree_path?: string, branch?: string }"},WorktreeRemove:{when:"Fires after a git worktree is removed.",payload:"{ worktree_path?: string }"},Elicitation:{when:"Fires when Claude asks the user a multiple-choice question.",payload:'{ action: "accept"|"reject", ...}'},ElicitationResult:{when:"Fires after the user resolves an elicitation prompt.",payload:"{ choice?: string }"}},L=["UserPromptSubmit","UserPromptExpansion","PreToolUse","PostToolUse","PostToolUseFailure","PostToolBatch","Stop","StopFailure","SessionStart","SessionEnd","Setup","PreCompact","PostCompact","InstructionsLoaded","Notification","PermissionRequest","PermissionDenied","SubagentStart","SubagentStop","TeammateIdle","TaskCreated","TaskCompleted","ConfigChange","CwdChanged","FileChanged","WorktreeCreate","WorktreeRemove","Elicitation","ElicitationResult"],fe=new Set(L),be=["command","http","prompt","agent","mcp_tool"],ye={UserPromptSubmit:{prompt:"hello"},UserPromptExpansion:{command:"/example",expanded:"hello"},PreToolUse:{tool_name:"Bash",tool_input:{command:"ls"}},PostToolUse:{tool_name:"Bash",tool_input:{command:"ls"},tool_result:""},PostToolUseFailure:{tool_name:"Bash",tool_input:{command:"ls"},error:""},PostToolBatch:{tool_uses:[]},Stop:{stop_reason:"end_turn",output_tokens:0},StopFailure:{reason:"rate_limit"},SessionStart:{source:"startup",model:"",agent_type:""},SessionEnd:{reason:"user_quit"},Setup:{mode:"init"},PreCompact:{transcript_path:"",trigger:"manual"},PostCompact:{transcript_path:"",trigger:"manual"},InstructionsLoaded:{source:"session_start"},Notification:{title:"test",message:"test notification"},PermissionRequest:{tool_name:"Bash"},PermissionDenied:{tool_name:"Bash",retry:!1},SubagentStart:{agent_type:"general-purpose"},SubagentStop:{agent_type:"general-purpose",reason:"end_turn"},TeammateIdle:{},TaskCreated:{task:{description:""}},TaskCompleted:{task:{description:""}},ConfigChange:{source:"user_settings"},CwdChanged:{old_cwd:"",new_cwd:""},FileChanged:{file_path:"",change_type:"modified"},WorktreeCreate:{},WorktreeRemove:{},Elicitation:{action:"accept"},ElicitationResult:{}};function ve(t){if(t.trim()==="")return{full:{},hooks:{},err:null};try{const n=JSON.parse(t);return{full:n,hooks:n.hooks??{},err:null}}catch(n){return{full:{},hooks:{},err:n.message}}}function je(t,n){return JSON.stringify({...t,hooks:n},null,2)+`
2
- `}function we(t,n){return(t[n]??[]).reduce((o,l)=>{var c;return o+(((c=l.hooks)==null?void 0:c.length)??0)},0)}function ke(){const t=Z(),n=Q(),o=(n==null?void 0:n.cwd)??null,l=ee(a=>a.navFace),c=d.useRef(!1),g=d.useRef(l),[m,x]=d.useState(()=>l==="project"&&o?"project":"user"),[r,u]=d.useState("PreToolUse"),[s,S]=d.useState("effective");d.useEffect(()=>{if(g.current!==l){if(g.current=l,c.current){c.current=!1;return}x(l==="project"&&o?"project":"user")}},[l,o]),d.useEffect(()=>{l==="project"&&s==="library"&&S("effective")},[l,s]);const f=a=>{c.current=!0,x(a)},j=pe(re,t,o),p=j[m]??null,w=F(a=>a.files),O=F(a=>a.setDraft),D=F(a=>a.saveJson),J=F(a=>a.revert),[W,N]=d.useState(null),[C,H]=d.useState(null),T=e.jsx(ie,{options:[{key:"effective",label:"Effective"},{key:"events",label:"Events"},...l==="home"?[{key:"library",label:"Library"}]:[]],active:s,onChange:S}),M=d.useMemo(()=>{const a=te(se(w,j));return ae(a,["hooks"])??{kind:"object",children:{}}},[w,j]),$=(a,h)=>{var q;const i=j[m];if(!i)return;N(null);const k=((q=w[i])==null?void 0:q.draftRaw)??"";let v={};if(k.trim())try{v=JSON.parse(k)}catch{v={}}const X=le(v.hooks??{},a,h),Y={...v,hooks:X};O(i,JSON.stringify(Y,null,2)+`
3
- `)};if(!t)return e.jsx(E,{title:"loading…"});if(s==="library")return e.jsx(R,{toolbar:T,children:e.jsx(xe,{})});if(m!=="user"&&!o)return e.jsx(R,{toolbar:e.jsxs(e.Fragment,{children:[T,e.jsx("span",{className:"mx-2 text-fg-faint",children:"·"}),e.jsx(I,{scopes:["user","project","local"],active:m,onChange:f})]}),children:e.jsx(E,{title:"no active project"})});if(!p)return e.jsx(E,{title:"loading…"});const b=w[p],{full:G,hooks:y,err:U}=b?ve(b.draftRaw):{full:{},hooks:{},err:null},A=Object.keys(y).filter(a=>!fe.has(a)),B=A.reduce((a,h)=>a+(y[h]??[]).reduce((i,k)=>{var v;return i+(((v=k.hooks)==null?void 0:v.length)??0)},0),0),P=a=>{N(null),O(p,je(G,a))},_=y[r]??[],K=()=>{P({...y,[r]:[..._,{matcher:"",hooks:[{type:"command",command:""}]}]})},V=(a,h)=>{const i=_.slice();i[a]=h,P({...y,[r]:i})},z=a=>{P({...y,[r]:_.filter((h,i)=>i!==a)})};return e.jsxs(R,{toolbar:e.jsxs(e.Fragment,{children:[T,e.jsx("span",{className:"mx-2 text-fg-faint",children:"·"}),e.jsx(I,{scopes:["user","project","local"],active:m,onChange:f}),e.jsx("span",{className:"ml-3 text-fg-faint truncate",children:s==="effective"?`overrides → ${p}`:p}),e.jsx("div",{className:"flex-1"}),e.jsx("a",{href:"https://code.claude.com/docs/en/hooks",target:"_blank",rel:"noreferrer",className:"text-fg-faint hover:text-fg-dim underline-offset-2 hover:underline",children:"hook reference ↗"})]}),footer:b?e.jsx(de,{dirty:b.dirty,busy:b.busy,parseError:W||U||b.parseError,lastSavedAt:b.lastSavedAt,onSave:async()=>{N(null);const a=await D(p);a.ok||N(a.error??"save failed")},onRevert:()=>{N(null),J(p)}}):null,children:[s==="effective"?e.jsx(ue,{node:M,targetScope:m,onOverride:$,schema:he().rootedAt(["hooks"]),rootLabel:"hooks"}):e.jsxs("div",{className:"flex flex-col h-full",children:[B>0?e.jsxs("div",{className:"px-3 py-2 border-b border-line text-xs bg-bg-elev text-fg-dim",children:[e.jsx("span",{className:"text-yellow-400",children:"⚠"})," ",B," hook(s) configured under unknown event names: ",e.jsx("span",{className:"font-mono text-fg",children:A.join(", ")}),e.jsx("span",{className:"text-fg-faint",children:" · these are ignored by Claude Code 2026; edit settings.json directly to remove."})]}):null,e.jsx(oe,{sidebarWidth:"14rem",sidebar:e.jsx("div",{className:"py-1",children:L.map(a=>{const h=we(y,a),i=ge[a],k=i?e.jsxs("span",{className:"block space-y-1",children:[e.jsx("span",{className:"block text-fg",children:i.when}),e.jsxs("span",{className:"block text-fg-faint font-mono",children:["payload: ",i.payload]}),i.example?e.jsxs("span",{className:"block text-fg-faint italic",children:["e.g. ",i.example]}):null]}):e.jsx("span",{className:"text-fg-faint italic",children:"no documentation yet"});return e.jsx("div",{className:"[&>span]:w-full",children:e.jsx(ne,{content:k,align:"bottom-center",children:e.jsxs("button",{onClick:()=>u(a),title:i==null?void 0:i.when,className:`w-full text-left px-3 py-1 text-xs ${r===a?"bg-bg-hi text-fg":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"truncate",children:a}),h>0&&e.jsx("span",{className:"text-accent shrink-0 ml-2",children:h})]}),i?e.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:i.when}):e.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 italic font-normal truncate",children:"no documentation yet"})]})})},a)})}),detail:e.jsxs("div",{className:"p-4 space-y-3 max-w-3xl",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg",children:r}),e.jsx("button",{onClick:K,className:"px-2 py-0.5 text-xs border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi",children:"+ add group"})]}),_.length===0?e.jsx("div",{className:"text-fg-faint text-xs",children:"no hooks for this event"}):_.map((a,h)=>e.jsx(Ne,{group:a,jsonInvalid:!!U,onChange:i=>V(h,i),onRemove:()=>z(h),onTestFire:i=>H({event:r,matcher:a.matcher??"",command:i.command??""})},h))]})})]}),C?e.jsx(Fe,{event:C.event,matcher:C.matcher,command:C.command,onClose:()=>H(null)}):null]})}const Ae=d.memo(ke);function Ne({group:t,jsonInvalid:n,onChange:o,onRemove:l,onTestFire:c}){const g=()=>o({...t,hooks:[...t.hooks??[],{type:"command",command:""}]}),m=(r,u)=>{const s=t.hooks.slice();s[r]=u,o({...t,hooks:s})},x=r=>o({...t,hooks:t.hooks.filter((u,s)=>s!==r)});return e.jsxs("div",{className:"border border-line rounded p-3 bg-bg-elev space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-fg-faint w-16",children:"matcher"}),e.jsx("input",{value:t.matcher??"",onChange:r=>o({...t,matcher:r.target.value}),placeholder:"tool name regex or exact match (optional)",className:"flex-1 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg font-mono"}),e.jsx("button",{onClick:l,className:"text-fg-faint hover:text-red-400 text-xs",title:"remove group",children:"× group"})]}),(t.hooks??[]).map((r,u)=>e.jsx(_e,{rule:r,jsonInvalid:n,onChange:s=>m(u,s),onRemove:()=>x(u),onTestFire:()=>c(r)},u)),e.jsx("button",{onClick:g,className:"text-xs text-fg-faint hover:text-fg",children:"+ add hook"})]})}function _e({rule:t,jsonInvalid:n,onChange:o,onRemove:l,onTestFire:c}){const g=s=>({command:"e.g. node ./scripts/lint.js $FILE",http:"e.g. https://hooks.example.com/notify",prompt:"e.g. Review this change for security issues",agent:"e.g. security-reviewer",mcp_tool:"e.g. mcp__server__tool"})[s],m=t.type==="command"?"command":t.type==="http"?"url":t.type==="prompt"?"prompt":t.type==="mcp_tool"?"mcpTool":"agent",x=t[m]??"",r=(t.args??[]).join(" "),u={type:"hook",name:x||t.type,command:t.type==="command"?t.command:void 0,url:t.type==="http"?t.url:void 0};return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("select",{value:t.type,onChange:s=>o({type:s.target.value}),className:"bg-bg border border-line rounded px-1 py-0.5 text-xs text-fg",children:be.map(s=>e.jsx("option",{value:s,children:s},s))}),e.jsx(me,{interactive:!1,input:u}),e.jsx("input",{value:x,onChange:s=>o({...t,[m]:s.target.value}),placeholder:g(t.type),className:`flex-1 bg-bg border rounded px-2 py-0.5 text-xs text-fg font-mono ${n?"border-red-500/70":x.trim()?"border-line":"border-yellow-600/50"}`}),n?e.jsx("span",{className:"text-red-400 text-xs",title:"The enclosing settings.json is malformed; fix the JSON before editing.",children:"× invalid"}):null,e.jsx("input",{value:t.timeout??"",onChange:s=>o({...t,timeout:s.target.value?Number(s.target.value):void 0}),placeholder:"timeout ms",className:"w-20 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),t.type==="command"?e.jsx("button",{onClick:c,disabled:n||!x.trim(),className:"px-2 py-0.5 text-xs border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi disabled:opacity-40 disabled:cursor-not-allowed",title:"Run this command with a fake event payload",children:"test fire"}):null,e.jsx("button",{onClick:l,className:"text-fg-faint hover:text-red-400 text-xs",children:"×"})]}),t.type==="command"?e.jsxs("div",{className:"flex items-center gap-2 pl-[3.75rem]",children:[e.jsx("span",{className:"text-xs text-fg-faint w-12",children:"args"}),e.jsx("input",{value:r,onChange:s=>o({...t,args:s.target.value.trim()?s.target.value.split(/\s+/).filter(Boolean):void 0}),placeholder:"argv array (v2.1.139+ exec form, no shell)",className:"flex-1 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg font-mono"})]}):null,e.jsxs("div",{className:"flex items-center gap-2 pl-[3.75rem]",children:[e.jsx("span",{className:"text-xs text-fg-faint w-12",children:"term"}),e.jsx("input",{value:t.terminalSequence??"",onChange:s=>o({...t,terminalSequence:s.target.value||void 0}),placeholder:"terminalSequence — e.g. \\\\a (bell), v2.1.141+",className:"flex-1 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg font-mono"})]})]})}function Se(t){return JSON.stringify(ye[t]??{},null,2)}function Ce(t,n){if(!t.trim())return{matched:!0,target:null,note:"empty matcher → matches all"};const o=n&&typeof n=="object"&&"tool_name"in n?String(n.tool_name??""):null;if(o==null)return{matched:!1,target:null,note:"payload has no tool_name to match against"};try{return{matched:new RegExp(`^(?:${t})$`).test(o),target:o}}catch{return{matched:t===o,target:o,note:"matcher not valid regex; fell back to exact match"}}}function Fe({event:t,matcher:n,command:o,onClose:l}){const[c,g]=d.useState(()=>Se(t)),[m,x]=d.useState(!1),[r,u]=d.useState(null),[s,S]=d.useState(null);let f=null;try{JSON.parse(c)}catch(p){f=p.message}const j=async()=>{x(!0),u(null);let p=null;try{p=JSON.parse(c)}catch{}S(Ce(n,p));try{const w=await window.api.app.testFireHook({command:o,payload:c,timeoutMs:5e3});u(w)}finally{x(!1)}};return e.jsx(ce,{open:!0,onClose:l,title:`Test fire — ${t}`,children:e.jsxs("div",{className:"space-y-3 text-xs",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-fg-faint mb-1",children:"resolved command"}),e.jsx("div",{className:"font-mono text-fg bg-bg border border-line rounded px-2 py-1 break-all",children:o})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-fg-faint mb-1",children:"matcher"}),e.jsx("div",{className:"font-mono text-fg bg-bg border border-line rounded px-2 py-1",children:n||e.jsx("span",{className:"text-fg-faint",children:"(empty — matches all)"})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-fg-faint",children:"fake event payload (stdin)"}),f?e.jsxs("span",{className:"text-red-400",children:["× ",f]}):null]}),e.jsx("textarea",{value:c,onChange:p=>g(p.target.value),rows:8,className:`w-full bg-bg border rounded px-2 py-1 font-mono text-fg ${f?"border-red-500/70":"border-line"}`})]}),s?e.jsxs("div",{children:[e.jsx("div",{className:"text-fg-faint mb-1",children:"matcher result"}),e.jsxs("div",{className:"font-mono",children:[e.jsx("span",{className:s.matched?"text-green-400":"text-red-400",children:s.matched?"✓ match":"✗ no match"}),s.target!=null?e.jsxs("span",{className:"text-fg-dim",children:[' · target tool_name="',s.target,'"']}):null,s.note?e.jsx("div",{className:"text-fg-faint",children:s.note}):null]})]}):null,r?e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-fg-faint",children:["exit ",r.exitCode," · ",r.durationMs,"ms"]}),r.stdout?e.jsxs("div",{children:[e.jsx("div",{className:"text-fg-faint",children:"stdout"}),e.jsx("pre",{className:"bg-bg border border-line rounded p-2 font-mono text-fg whitespace-pre-wrap break-all max-h-40 overflow-auto",children:r.stdout})]}):null,r.stderr?e.jsxs("div",{children:[e.jsx("div",{className:"text-fg-faint",children:"stderr"}),e.jsx("pre",{className:"bg-bg border border-line rounded p-2 font-mono text-red-300 whitespace-pre-wrap break-all max-h-40 overflow-auto",children:r.stderr})]}):null]}):null,e.jsxs("div",{className:"flex items-center justify-end gap-2 pt-1",children:[e.jsx("button",{onClick:l,className:"px-2 py-0.5 text-xs border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi",children:"close"}),e.jsx("button",{onClick:j,disabled:m||!!f||!o.trim(),className:"px-2 py-0.5 text-xs border border-line rounded text-fg hover:bg-bg-hi disabled:opacity-40 disabled:cursor-not-allowed",children:m?"running…":"run"})]})]})})}export{Ae as Hooks};
1
+ import{ay as d,aV as Q,aN as Z,aX as ee,aP as F,al as te,ap as se,af as ae,aj as e,m as E,v as R,r as oe,W as ne,H as re,X as ie,aF as le,u as ce}from"./index-vx8O73l8.js";import{S as de}from"./SaveBar-rimJem-Y.js";import{S as L}from"./ScopeSwitcher-CnAzTBrl.js";import{P as me}from"./ProvenanceBadge-DcBHT1Iy.js";import{u as pe,E as ue,s as he}from"./settingsSchema-D6iRguNV.js";import{H as xe}from"./Library-Dv_EtIMr.js";import"./monaco-editor-BW5C4Iv1.js";const ge={UserPromptSubmit:{when:"Fires just before the user prompt is sent to the model.",payload:"{ prompt: string }",example:"Block submission if the prompt mentions a secret."},UserPromptExpansion:{when:"Fires when a slash command expands into its final prompt text.",payload:"{ command: string, expanded: string }",example:"Audit which slash commands actually run, post-expansion."},PreToolUse:{when:"Fires before any tool runs. Can block the call.",payload:"{ tool_name: string, tool_input: object }",example:'matcher="Bash" — block dangerous shell commands.'},PostToolUse:{when:"Fires after a tool completes successfully.",payload:"{ tool_name: string, tool_input: object, tool_result: string }",example:'matcher="Write|Edit" — run a linter on changed files.'},PostToolUseFailure:{when:"Fires after a tool errors out (non-zero exit, exception, or refusal).",payload:"{ tool_name: string, tool_input: object, error: string }",example:"Pipe failed Bash runs into a desktop notification."},PostToolBatch:{when:"Fires once after a parallel batch of tool calls all complete.",payload:"{ tool_uses: Array<{ tool_name, tool_input, tool_result? }> }",example:"Aggregate file-edit batches into a single commit message."},Stop:{when:"Fires when the model emits end_turn.",payload:"{ stop_reason: string, output_tokens: number }",example:"Play a chime when the agent finishes a long task."},StopFailure:{when:"Fires when a turn aborts without end_turn (rate-limit, network, OOM).",payload:'{ reason: "rate_limit"|"network"|"oom"|"killed"|string }',example:"Auto-resume on transient failures."},SessionStart:{when:"Fires once when a session boots (claude or claude -p).",payload:'{ source: "startup"|"resume", model: string, agent_type: string }',example:"Inject a project-specific system prompt addendum."},SessionEnd:{when:"Fires once when the session terminates.",payload:'{ reason: "user_quit"|"timeout"|"error"|string }',example:"Persist transcript summary to ~/.claude/projects/<>."},Setup:{when:"Fires during interactive setup (claude /setup, /init).",payload:'{ mode: "init"|"reconfigure"|string }'},PreCompact:{when:"Fires before transcript compaction runs.",payload:'{ transcript_path: string, trigger: "manual"|"auto" }',example:"Snapshot the pre-compact transcript for later diffing."},PostCompact:{when:"Fires after compaction; the active transcript is the compacted one.",payload:'{ transcript_path: string, trigger: "manual"|"auto" }'},InstructionsLoaded:{when:"Fires after CLAUDE.md and any imported memory files are loaded.",payload:'{ source: "session_start"|"reload" }'},Notification:{when:"Fires when Claude Code emits a desktop notification.",payload:"{ title: string, message: string }",example:"Forward to your own notify-send / osascript pipeline."},PermissionRequest:{when:"Fires when a tool needs user permission (per the permissions block).",payload:"{ tool_name: string, tool_input?: object }",example:"Auto-allow npm test invocations."},PermissionDenied:{when:"Fires when the user (or policy) denies a permission request.",payload:"{ tool_name: string, retry: boolean }",example:"Track which tools the user habitually rejects."},SubagentStart:{when:"Fires when a subagent (Task tool) spawns.",payload:"{ agent_type: string }",example:'matcher="security-reviewer" — log every security scan.'},SubagentStop:{when:"Fires when a subagent finishes.",payload:'{ agent_type: string, reason: "end_turn"|"error"|string }'},TeammateIdle:{when:"Fires when a teammate agent goes idle (waiting for input).",payload:"{ teammate_id?: string }"},TaskCreated:{when:"Fires when a new Task is created via the Task tool.",payload:"{ task: { description: string, ...} }",example:"Track each spawned task in an external queue."},TaskCompleted:{when:"Fires when a Task completes (success or failure).",payload:"{ task: { description: string, ...} }"},ConfigChange:{when:"Fires when settings.json (any scope) is mutated mid-session.",payload:'{ source: "user_settings"|"project_settings"|"local_settings" }',example:"Reload tooling that depends on env vars on config change."},CwdChanged:{when:"Fires when the working directory changes (e.g. agent cd-ing).",payload:"{ old_cwd: string, new_cwd: string }",example:"Refresh project-scoped indexers when cwd drifts."},FileChanged:{when:"Fires when a watched file outside Claude Code's edits changes.",payload:'{ file_path: string, change_type: "modified"|"created"|"deleted" }',example:"Re-run typecheck when any .ts file changes."},WorktreeCreate:{when:"Fires after a git worktree is created via /worktree or subagent isolation.",payload:"{ worktree_path?: string, branch?: string }"},WorktreeRemove:{when:"Fires after a git worktree is removed.",payload:"{ worktree_path?: string }"},Elicitation:{when:"Fires when Claude asks the user a multiple-choice question.",payload:'{ action: "accept"|"reject", ...}'},ElicitationResult:{when:"Fires after the user resolves an elicitation prompt.",payload:"{ choice?: string }"}},q=["UserPromptSubmit","UserPromptExpansion","PreToolUse","PostToolUse","PostToolUseFailure","PostToolBatch","Stop","StopFailure","SessionStart","SessionEnd","Setup","PreCompact","PostCompact","InstructionsLoaded","Notification","PermissionRequest","PermissionDenied","SubagentStart","SubagentStop","TeammateIdle","TaskCreated","TaskCompleted","ConfigChange","CwdChanged","FileChanged","WorktreeCreate","WorktreeRemove","Elicitation","ElicitationResult"],fe=new Set(q),be=["command","http","prompt","agent","mcp_tool"],ye={UserPromptSubmit:{prompt:"hello"},UserPromptExpansion:{command:"/example",expanded:"hello"},PreToolUse:{tool_name:"Bash",tool_input:{command:"ls"}},PostToolUse:{tool_name:"Bash",tool_input:{command:"ls"},tool_result:""},PostToolUseFailure:{tool_name:"Bash",tool_input:{command:"ls"},error:""},PostToolBatch:{tool_uses:[]},Stop:{stop_reason:"end_turn",output_tokens:0},StopFailure:{reason:"rate_limit"},SessionStart:{source:"startup",model:"",agent_type:""},SessionEnd:{reason:"user_quit"},Setup:{mode:"init"},PreCompact:{transcript_path:"",trigger:"manual"},PostCompact:{transcript_path:"",trigger:"manual"},InstructionsLoaded:{source:"session_start"},Notification:{title:"test",message:"test notification"},PermissionRequest:{tool_name:"Bash"},PermissionDenied:{tool_name:"Bash",retry:!1},SubagentStart:{agent_type:"general-purpose"},SubagentStop:{agent_type:"general-purpose",reason:"end_turn"},TeammateIdle:{},TaskCreated:{task:{description:""}},TaskCompleted:{task:{description:""}},ConfigChange:{source:"user_settings"},CwdChanged:{old_cwd:"",new_cwd:""},FileChanged:{file_path:"",change_type:"modified"},WorktreeCreate:{},WorktreeRemove:{},Elicitation:{action:"accept"},ElicitationResult:{}};function ve(t){if(t.trim()==="")return{full:{},hooks:{},err:null};try{const n=JSON.parse(t);return{full:n,hooks:n.hooks??{},err:null}}catch(n){return{full:{},hooks:{},err:n.message}}}function je(t,n){return JSON.stringify({...t,hooks:n},null,2)+`
2
+ `}function we(t,n){return(t[n]??[]).reduce((o,l)=>{var c;return o+(((c=l.hooks)==null?void 0:c.length)??0)},0)}function ke(){const t=Q(),n=Z(),o=(n==null?void 0:n.cwd)??null,l=ee(a=>a.navFace),c=d.useRef(!1),g=d.useRef(l),[m,x]=d.useState(()=>l==="project"&&o?"project":"user"),[r,u]=d.useState("PreToolUse"),[s,S]=d.useState("effective");d.useEffect(()=>{if(g.current!==l){if(g.current=l,c.current){c.current=!1;return}x(l==="project"&&o?"project":"user")}},[l,o]),d.useEffect(()=>{l==="project"&&s==="library"&&S("effective")},[l,s]);const f=a=>{c.current=!0,x(a)},j=pe(re,t,o),p=j[m]??null,w=F(a=>a.files),O=F(a=>a.setDraft),D=F(a=>a.saveJson),J=F(a=>a.revert),[W,N]=d.useState(null),[C,H]=d.useState(null),T=e.jsx(ie,{options:[{key:"effective",label:"Effective"},{key:"events",label:"Events"},...l==="home"?[{key:"library",label:"Library"}]:[]],active:s,onChange:S}),M=d.useMemo(()=>{const a=te(se(w,j));return ae(a,["hooks"])??{kind:"object",children:{}}},[w,j]),$=(a,h)=>{var I;const i=j[m];if(!i)return;N(null);const k=((I=w[i])==null?void 0:I.draftRaw)??"";let v={};if(k.trim())try{v=JSON.parse(k)}catch{v={}}const X=le(v.hooks??{},a,h),Y={...v,hooks:X};O(i,JSON.stringify(Y,null,2)+`
3
+ `)};if(!t)return e.jsx(E,{title:"loading…"});if(s==="library")return e.jsx(R,{toolbar:T,children:e.jsx(xe,{})});if(m!=="user"&&!o)return e.jsx(R,{toolbar:e.jsxs(e.Fragment,{children:[T,e.jsx("span",{className:"mx-2 text-fg-faint",children:"·"}),e.jsx(L,{scopes:["user","project","local"],active:m,onChange:f})]}),children:e.jsx(E,{title:"no active project"})});if(!p)return e.jsx(E,{title:"loading…"});const b=w[p],{full:K,hooks:y,err:U}=b?ve(b.draftRaw):{full:{},hooks:{},err:null},A=Object.keys(y).filter(a=>!fe.has(a)),B=A.reduce((a,h)=>a+(y[h]??[]).reduce((i,k)=>{var v;return i+(((v=k.hooks)==null?void 0:v.length)??0)},0),0),P=a=>{N(null),O(p,je(K,a))},_=y[r]??[],V=()=>{P({...y,[r]:[..._,{matcher:"",hooks:[{type:"command",command:""}]}]})},G=(a,h)=>{const i=_.slice();i[a]=h,P({...y,[r]:i})},z=a=>{P({...y,[r]:_.filter((h,i)=>i!==a)})};return e.jsxs(R,{toolbar:e.jsxs(e.Fragment,{children:[T,e.jsx("span",{className:"mx-2 text-fg-faint",children:"·"}),e.jsx(L,{scopes:["user","project","local"],active:m,onChange:f}),e.jsx("span",{className:"ml-3 text-fg-faint truncate",children:s==="effective"?`overrides → ${p}`:p}),e.jsx("div",{className:"flex-1"}),e.jsx("a",{href:"https://code.claude.com/docs/en/hooks",target:"_blank",rel:"noreferrer",className:"text-fg-faint hover:text-fg-dim underline-offset-2 hover:underline",children:"hook reference ↗"})]}),footer:b?e.jsx(de,{dirty:b.dirty,busy:b.busy,parseError:W||U||b.parseError,lastSavedAt:b.lastSavedAt,onSave:async()=>{N(null);const a=await D(p);a.ok||N(a.error??"save failed")},onRevert:()=>{N(null),J(p)}}):null,children:[s==="effective"?e.jsx(ue,{node:M,targetScope:m,onOverride:$,schema:he().rootedAt(["hooks"]),rootLabel:"hooks"}):e.jsxs("div",{className:"flex flex-col h-full",children:[B>0?e.jsxs("div",{className:"px-3 py-2 border-b border-line text-xs bg-bg-elev text-fg-dim",children:[e.jsx("span",{className:"text-yellow-400",children:"⚠"})," ",B," hook(s) configured under unknown event names: ",e.jsx("span",{className:"font-mono text-fg",children:A.join(", ")}),e.jsx("span",{className:"text-fg-faint",children:" · these are ignored by Claude Code 2026; edit settings.json directly to remove."})]}):null,e.jsx(oe,{sidebarWidth:"14rem",sidebar:e.jsx("div",{className:"py-1",children:q.map(a=>{const h=we(y,a),i=ge[a],k=i?e.jsxs("span",{className:"block space-y-1",children:[e.jsx("span",{className:"block text-fg",children:i.when}),e.jsxs("span",{className:"block text-fg-faint font-mono",children:["payload: ",i.payload]}),i.example?e.jsxs("span",{className:"block text-fg-faint italic",children:["e.g. ",i.example]}):null]}):e.jsx("span",{className:"text-fg-faint italic",children:"no documentation yet"});return e.jsx("div",{className:"[&>span]:w-full",children:e.jsx(ne,{content:k,align:"bottom-center",children:e.jsxs("button",{onClick:()=>u(a),title:i==null?void 0:i.when,className:`w-full text-left px-3 py-1 text-xs ${r===a?"bg-bg-hi text-fg":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"truncate",children:a}),h>0&&e.jsx("span",{className:"text-accent shrink-0 ml-2",children:h})]}),i?e.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:i.when}):e.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 italic font-normal truncate",children:"no documentation yet"})]})})},a)})}),detail:e.jsxs("div",{className:"p-4 space-y-3 max-w-3xl",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg",children:r}),e.jsx("button",{onClick:V,className:"px-2 py-0.5 text-xs border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi",children:"+ add group"})]}),_.length===0?e.jsx("div",{className:"text-fg-faint text-xs",children:"no hooks for this event"}):_.map((a,h)=>e.jsx(Ne,{group:a,jsonInvalid:!!U,onChange:i=>G(h,i),onRemove:()=>z(h),onTestFire:i=>H({event:r,matcher:a.matcher??"",command:i.command??""})},h))]})})]}),C?e.jsx(Fe,{event:C.event,matcher:C.matcher,command:C.command,onClose:()=>H(null)}):null]})}const Ae=d.memo(ke);function Ne({group:t,jsonInvalid:n,onChange:o,onRemove:l,onTestFire:c}){const g=()=>o({...t,hooks:[...t.hooks??[],{type:"command",command:""}]}),m=(r,u)=>{const s=t.hooks.slice();s[r]=u,o({...t,hooks:s})},x=r=>o({...t,hooks:t.hooks.filter((u,s)=>s!==r)});return e.jsxs("div",{className:"border border-line rounded p-3 bg-bg-elev space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-fg-faint w-16",children:"matcher"}),e.jsx("input",{value:t.matcher??"",onChange:r=>o({...t,matcher:r.target.value}),placeholder:"tool name regex or exact match (optional)",className:"flex-1 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg font-mono"}),e.jsx("button",{onClick:l,className:"text-fg-faint hover:text-red-400 text-xs",title:"remove group",children:"× group"})]}),(t.hooks??[]).map((r,u)=>e.jsx(_e,{rule:r,jsonInvalid:n,onChange:s=>m(u,s),onRemove:()=>x(u),onTestFire:()=>c(r)},u)),e.jsx("button",{onClick:g,className:"text-xs text-fg-faint hover:text-fg",children:"+ add hook"})]})}function _e({rule:t,jsonInvalid:n,onChange:o,onRemove:l,onTestFire:c}){const g=s=>({command:"e.g. node ./scripts/lint.js $FILE",http:"e.g. https://hooks.example.com/notify",prompt:"e.g. Review this change for security issues",agent:"e.g. security-reviewer",mcp_tool:"e.g. mcp__server__tool"})[s],m=t.type==="command"?"command":t.type==="http"?"url":t.type==="prompt"?"prompt":t.type==="mcp_tool"?"mcpTool":"agent",x=t[m]??"",r=(t.args??[]).join(" "),u={type:"hook",name:x||t.type,command:t.type==="command"?t.command:void 0,url:t.type==="http"?t.url:void 0};return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("select",{value:t.type,onChange:s=>o({type:s.target.value}),className:"bg-bg border border-line rounded px-1 py-0.5 text-xs text-fg",children:be.map(s=>e.jsx("option",{value:s,children:s},s))}),e.jsx(me,{interactive:!1,input:u}),e.jsx("input",{value:x,onChange:s=>o({...t,[m]:s.target.value}),placeholder:g(t.type),className:`flex-1 bg-bg border rounded px-2 py-0.5 text-xs text-fg font-mono ${n?"border-red-500/70":x.trim()?"border-line":"border-yellow-600/50"}`}),n?e.jsx("span",{className:"text-red-400 text-xs",title:"The enclosing settings.json is malformed; fix the JSON before editing.",children:"× invalid"}):null,e.jsx("input",{value:t.timeout??"",onChange:s=>o({...t,timeout:s.target.value?Number(s.target.value):void 0}),placeholder:"timeout ms",className:"w-20 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),t.type==="command"?e.jsx("button",{onClick:c,disabled:n||!x.trim(),className:"px-2 py-0.5 text-xs border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi disabled:opacity-40 disabled:cursor-not-allowed",title:"Run this command with a fake event payload",children:"test fire"}):null,e.jsx("button",{onClick:l,className:"text-fg-faint hover:text-red-400 text-xs",children:"×"})]}),t.type==="command"?e.jsxs("div",{className:"flex items-center gap-2 pl-[3.75rem]",children:[e.jsx("span",{className:"text-xs text-fg-faint w-12",children:"args"}),e.jsx("input",{value:r,onChange:s=>o({...t,args:s.target.value.trim()?s.target.value.split(/\s+/).filter(Boolean):void 0}),placeholder:"argv array (v2.1.139+ exec form, no shell)",className:"flex-1 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg font-mono"})]}):null,e.jsxs("div",{className:"flex items-center gap-2 pl-[3.75rem]",children:[e.jsx("span",{className:"text-xs text-fg-faint w-12",children:"term"}),e.jsx("input",{value:t.terminalSequence??"",onChange:s=>o({...t,terminalSequence:s.target.value||void 0}),placeholder:"terminalSequence — e.g. \\\\a (bell), v2.1.141+",className:"flex-1 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg font-mono"})]})]})}function Se(t){return JSON.stringify(ye[t]??{},null,2)}function Ce(t,n){if(!t.trim())return{matched:!0,target:null,note:"empty matcher → matches all"};const o=n&&typeof n=="object"&&"tool_name"in n?String(n.tool_name??""):null;if(o==null)return{matched:!1,target:null,note:"payload has no tool_name to match against"};try{return{matched:new RegExp(`^(?:${t})$`).test(o),target:o}}catch{return{matched:t===o,target:o,note:"matcher not valid regex; fell back to exact match"}}}function Fe({event:t,matcher:n,command:o,onClose:l}){const[c,g]=d.useState(()=>Se(t)),[m,x]=d.useState(!1),[r,u]=d.useState(null),[s,S]=d.useState(null);let f=null;try{JSON.parse(c)}catch(p){f=p.message}const j=async()=>{x(!0),u(null);let p=null;try{p=JSON.parse(c)}catch{}S(Ce(n,p));try{const w=await window.api.app.testFireHook({command:o,payload:c,timeoutMs:5e3});u(w)}finally{x(!1)}};return e.jsx(ce,{open:!0,onClose:l,title:`Test fire — ${t}`,children:e.jsxs("div",{className:"space-y-3 text-xs",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-fg-faint mb-1",children:"resolved command"}),e.jsx("div",{className:"font-mono text-fg bg-bg border border-line rounded px-2 py-1 break-all",children:o})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-fg-faint mb-1",children:"matcher"}),e.jsx("div",{className:"font-mono text-fg bg-bg border border-line rounded px-2 py-1",children:n||e.jsx("span",{className:"text-fg-faint",children:"(empty — matches all)"})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-fg-faint",children:"fake event payload (stdin)"}),f?e.jsxs("span",{className:"text-red-400",children:["× ",f]}):null]}),e.jsx("textarea",{value:c,onChange:p=>g(p.target.value),rows:8,className:`w-full bg-bg border rounded px-2 py-1 font-mono text-fg ${f?"border-red-500/70":"border-line"}`})]}),s?e.jsxs("div",{children:[e.jsx("div",{className:"text-fg-faint mb-1",children:"matcher result"}),e.jsxs("div",{className:"font-mono",children:[e.jsx("span",{className:s.matched?"text-green-400":"text-red-400",children:s.matched?"✓ match":"✗ no match"}),s.target!=null?e.jsxs("span",{className:"text-fg-dim",children:[' · target tool_name="',s.target,'"']}):null,s.note?e.jsx("div",{className:"text-fg-faint",children:s.note}):null]})]}):null,r?e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-fg-faint",children:["exit ",r.exitCode," · ",r.durationMs,"ms"]}),r.stdout?e.jsxs("div",{children:[e.jsx("div",{className:"text-fg-faint",children:"stdout"}),e.jsx("pre",{className:"bg-bg border border-line rounded p-2 font-mono text-fg whitespace-pre-wrap break-all max-h-40 overflow-auto",children:r.stdout})]}):null,r.stderr?e.jsxs("div",{children:[e.jsx("div",{className:"text-fg-faint",children:"stderr"}),e.jsx("pre",{className:"bg-bg border border-line rounded p-2 font-mono text-red-300 whitespace-pre-wrap break-all max-h-40 overflow-auto",children:r.stderr})]}):null]}):null,e.jsxs("div",{className:"flex items-center justify-end gap-2 pt-1",children:[e.jsx("button",{onClick:l,className:"px-2 py-0.5 text-xs border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi",children:"close"}),e.jsx("button",{onClick:j,disabled:m||!!f||!o.trim(),className:"px-2 py-0.5 text-xs border border-line rounded text-fg hover:bg-bg-hi disabled:opacity-40 disabled:cursor-not-allowed",children:m?"running…":"run"})]})]})})}export{Ae as Hooks};