@kabmo-labs/kabmo 0.16.0 → 0.18.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 (381) hide show
  1. package/README.md +2 -2
  2. package/dist/client/index.html +1 -1
  3. package/dist/client/index.js +552 -471
  4. package/dist/client/static/js/index-hp75vsv9.css +1 -0
  5. package/dist/client/static/js/{index-cpydmygd.js → index-tc09dtca.js} +897 -886
  6. package/package.json +1 -1
  7. package/src/client/components/common/MarkdownRenderer.tsx +136 -89
  8. package/src/client/components/common/anchored-menu/index.test.tsx +141 -0
  9. package/src/client/components/common/anchored-menu/index.tsx +143 -0
  10. package/src/client/components/common/code-surface/bracket-guide.test.ts +2 -2
  11. package/src/client/components/common/code-surface/bracket-guide.ts +2 -2
  12. package/src/client/components/common/code-surface/conflict-markers.ts +5 -5
  13. package/src/client/components/common/code-surface/extensions.ts +7 -4
  14. package/src/client/components/common/code-surface/theme.ts +34 -9
  15. package/src/client/components/common/code-surface/whitespace.test.ts +223 -0
  16. package/src/client/components/common/code-surface/whitespace.ts +140 -0
  17. package/src/client/components/common/markdown-review/ReviewPopover.tsx +144 -0
  18. package/src/client/components/common/markdown-review/ReviewSummary.tsx +108 -0
  19. package/src/client/components/common/markdown-review/index.tsx +129 -0
  20. package/src/client/components/common/{server-switcher/index.tsx → server-control/Panel.tsx} +92 -44
  21. package/src/client/components/common/server-control/index.test.tsx +217 -0
  22. package/src/client/components/common/server-control/index.tsx +120 -0
  23. package/src/client/components/layout/desktop-layout/TopNavbar.tsx +8 -50
  24. package/src/client/components/layout/session-sidebar/CategoryHeader.tsx +42 -21
  25. package/src/client/components/layout/session-sidebar/CategoryHeader.worktree.test.tsx +36 -17
  26. package/src/client/components/layout/session-sidebar/CategoryItem.tsx +8 -7
  27. package/src/client/components/layout/session-sidebar/about-modal/NotesDialog.tsx +94 -0
  28. package/src/client/components/layout/session-sidebar/about-modal/VersionLine.test.tsx +68 -0
  29. package/src/client/components/layout/session-sidebar/about-modal/VersionLine.tsx +36 -0
  30. package/src/client/components/layout/session-sidebar/about-modal/index.tsx +57 -34
  31. package/src/client/components/layout/session-sidebar/modern/WorkspaceHeader.tsx +28 -10
  32. package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +7 -6
  33. package/src/client/components/layout/session-sidebar/modern/workspace-header.test.tsx +1 -1
  34. package/src/client/components/layout/update-popup/ReleaseNotes.tsx +8 -3
  35. package/src/client/components/layout/update-popup/index.tsx +5 -1
  36. package/src/client/components/mobile/mobile-main-view/Header.tsx +6 -12
  37. package/src/client/components/mobile/mobile-right-sidebar/FullEditor.tsx +13 -15
  38. package/src/client/components/mobile/mobile-right-sidebar/Header.tsx +23 -1
  39. package/src/client/components/mobile/mobile-right-sidebar/MissingFileBanner.tsx +30 -0
  40. package/src/client/components/mobile/mobile-right-sidebar/PreviewScroller.tsx +18 -2
  41. package/src/client/components/mobile/mobile-session-sidebar/Header.tsx +41 -13
  42. package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +22 -67
  43. package/src/client/components/mobile/mobile-session-sidebar/ItemMenu.tsx +110 -0
  44. package/src/client/components/settings/Modal.tsx +9 -3
  45. package/src/client/components/settings/ProjectSelectorDropdown.tsx +19 -9
  46. package/src/client/components/settings/SettingsSidebarList.tsx +20 -0
  47. package/src/client/components/settings/categories/AgentSettings.tsx +38 -44
  48. package/src/client/components/settings/categories/CommandSettings.tsx +2 -2
  49. package/src/client/components/settings/categories/McpSettings.tsx +4 -21
  50. package/src/client/components/settings/categories/OmpSettings.tsx +147 -194
  51. package/src/client/components/settings/categories/ProjectSettings.tsx +122 -156
  52. package/src/client/components/settings/categories/SkillCatalogSettings.tsx +220 -260
  53. package/src/client/components/settings/categories/SkillSettings.tsx +8 -5
  54. package/src/client/components/settings/categories/TokenUsageSettings.tsx +211 -229
  55. package/src/client/components/settings/categories/agent-settings/DetailPane.tsx +229 -237
  56. package/src/client/components/settings/categories/agent-settings/ModelPicker.tsx +71 -0
  57. package/src/client/components/settings/categories/agent-settings/SidebarList.tsx +14 -2
  58. package/src/client/components/settings/categories/agent-settings/levels.ts +38 -0
  59. package/src/client/components/settings/categories/behavior-settings/Editor.tsx +27 -7
  60. package/src/client/components/settings/categories/chat-settings/ToolRenderSection.tsx +23 -5
  61. package/src/client/components/settings/categories/command-settings/DetailPane.tsx +75 -33
  62. package/src/client/components/settings/categories/command-settings/SidebarList.tsx +7 -0
  63. package/src/client/components/settings/categories/mcp-settings/DetailPane.tsx +91 -76
  64. package/src/client/components/settings/categories/mcp-settings/EnvVarsSection.tsx +83 -0
  65. package/src/client/components/settings/categories/mcp-settings/ImportModal.tsx +26 -13
  66. package/src/client/components/settings/categories/mcp-settings/SidebarList.tsx +20 -0
  67. package/src/client/components/settings/categories/omp-settings/ConfigTabs.tsx +97 -36
  68. package/src/client/components/settings/categories/omp-settings/EngineHeader.tsx +151 -0
  69. package/src/client/components/settings/categories/omp-settings/ExtensionsPanel.tsx +68 -32
  70. package/src/client/components/settings/categories/omp-settings/OrderedChips.tsx +119 -0
  71. package/src/client/components/settings/categories/omp-settings/PresetBar.tsx +14 -7
  72. package/src/client/components/settings/categories/omp-settings/RoleEditor.tsx +15 -6
  73. package/src/client/components/settings/categories/omp-settings/RowEditor.tsx +165 -226
  74. package/src/client/components/settings/categories/omp-settings/types.ts +28 -0
  75. package/src/client/components/settings/categories/project-settings/AccentPalette.test.tsx +189 -0
  76. package/src/client/components/settings/categories/project-settings/AccentPalette.tsx +156 -24
  77. package/src/client/components/settings/categories/project-settings/AddProjectModal.tsx +175 -0
  78. package/src/client/components/settings/categories/project-settings/DeleteProjectModal.tsx +107 -0
  79. package/src/client/components/settings/categories/project-settings/DetailsForm.tsx +40 -24
  80. package/src/client/components/settings/categories/project-settings/DetailsHeader.tsx +17 -7
  81. package/src/client/components/settings/categories/project-settings/IconGrid.tsx +164 -69
  82. package/src/client/components/settings/categories/project-settings/ModelDropdown.test.tsx +122 -0
  83. package/src/client/components/settings/categories/project-settings/ModelDropdown.tsx +124 -53
  84. package/src/client/components/settings/categories/project-settings/NameInput.tsx +57 -11
  85. package/src/client/components/settings/categories/project-settings/PathField.tsx +122 -0
  86. package/src/client/components/settings/categories/project-settings/SidebarList.tsx +100 -59
  87. package/src/client/components/settings/categories/skill-catalog/GitImportPanel.tsx +253 -0
  88. package/src/client/components/settings/categories/skill-catalog/SkillCard.tsx +89 -0
  89. package/src/client/components/settings/categories/skill-catalog/SourceRail.tsx +122 -0
  90. package/src/client/components/settings/categories/skill-catalog/catalog-ui.test.tsx +179 -0
  91. package/src/client/components/settings/categories/skill-settings/DetailHeader.tsx +236 -0
  92. package/src/client/components/settings/categories/skill-settings/DetailPane.tsx +164 -239
  93. package/src/client/components/settings/categories/skill-settings/InstructionsEditor.tsx +84 -0
  94. package/src/client/components/settings/categories/skill-settings/SidebarList.tsx +144 -87
  95. package/src/client/components/settings/categories/skill-settings/pane.test.tsx +188 -0
  96. package/src/client/components/settings/categories/skill-settings/row-meta.ts +58 -0
  97. package/src/client/components/settings/categories/token-usage-settings/Breakdown.tsx +242 -102
  98. package/src/client/components/settings/categories/token-usage-settings/Chart.tsx +130 -56
  99. package/src/client/components/settings/categories/token-usage-settings/Controls.tsx +135 -0
  100. package/src/client/components/settings/categories/token-usage-settings/MetricsGrid.tsx +55 -33
  101. package/src/client/components/settings/categories/token-usage-settings/Provenance.tsx +59 -0
  102. package/src/client/components/settings/categories/token-usage-settings/panel.test.tsx +239 -0
  103. package/src/client/components/workspace/browser-panel/Screencast.test.ts +1 -0
  104. package/src/client/components/workspace/browser-panel/Screencast.tsx +17 -22
  105. package/src/client/components/workspace/browser-panel/TabStrip.test.tsx +158 -0
  106. package/src/client/components/workspace/browser-panel/TabStrip.tsx +90 -0
  107. package/src/client/components/workspace/browser-panel/index.tsx +50 -4
  108. package/src/client/components/workspace/browser-toolbar/index.tsx +41 -1
  109. package/src/client/components/workspace/chat-timeline/ThinkingSection.tsx +3 -1
  110. package/src/client/components/workspace/chat-timeline/ToolCallingSection.tsx +2 -0
  111. package/src/client/components/workspace/chat-timeline/block-chrome.test.tsx +13 -2
  112. package/src/client/components/workspace/chat-timeline/index.tsx +6 -1
  113. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Bash.test.ts +88 -0
  114. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Bash.tsx +24 -1
  115. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Proc.test.ts +46 -0
  116. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Proc.tsx +15 -6
  117. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Read.test.ts +34 -0
  118. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Read.tsx +5 -1
  119. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Wait.test.ts +29 -0
  120. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Wait.tsx +11 -3
  121. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/ArtifactChip.tsx +7 -6
  122. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/card-header.test.ts +24 -1
  123. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/card-header.ts +6 -2
  124. package/src/client/components/workspace/chat-timeline/tool-renderers/styles/Tui.test.tsx +237 -0
  125. package/src/client/components/workspace/chat-timeline/tool-renderers/styles/Tui.tsx +191 -0
  126. package/src/client/components/workspace/chat-timeline/tool-renderers/styles/styles.test.tsx +1 -1
  127. package/src/client/components/workspace/diff-panel/MergeDiffView.tsx +21 -7
  128. package/src/client/components/workspace/diff-panel/changes.test.ts +51 -0
  129. package/src/client/components/workspace/diff-panel/changes.ts +28 -12
  130. package/src/client/components/workspace/diff-panel/merge.test.ts +28 -0
  131. package/src/client/components/workspace/diff-panel/merge.ts +21 -1
  132. package/src/client/components/workspace/editor/Body.tsx +7 -0
  133. package/src/client/components/workspace/editor/FileDocument.tsx +15 -21
  134. package/src/client/components/workspace/editor/FilePane.tsx +12 -0
  135. package/src/client/components/workspace/editor/PreviewPane.tsx +70 -0
  136. package/src/client/components/workspace/editor/Toolbar.tsx +17 -1
  137. package/src/client/components/workspace/editor/index.tsx +25 -22
  138. package/src/client/components/workspace/editor/toolbar-clusters.test.ts +14 -0
  139. package/src/client/components/workspace/editor/toolbar-clusters.tsx +12 -86
  140. package/src/client/components/workspace/editor/toolbar-toggle.tsx +53 -0
  141. package/src/client/components/workspace/editor/toolbar-write-clusters.tsx +112 -0
  142. package/src/client/components/workspace/editor/viewers/SvgPreview.tsx +18 -2
  143. package/src/client/components/workspace/editor/viewers/viewers.test.ts +39 -0
  144. package/src/client/components/workspace/file-explorer/ContextMenu.tsx +18 -5
  145. package/src/client/components/workspace/file-explorer/Modals.tsx +15 -1
  146. package/src/client/components/workspace/file-explorer/RowLabel.tsx +68 -0
  147. package/src/client/components/workspace/file-explorer/TreeItem.tsx +47 -57
  148. package/src/client/components/workspace/file-explorer/collapsed-chain.test.ts +167 -0
  149. package/src/client/components/workspace/file-explorer/drag-props.ts +42 -0
  150. package/src/client/components/workspace/file-explorer/drag.test.ts +43 -0
  151. package/src/client/components/workspace/file-explorer/index.tsx +21 -20
  152. package/src/client/components/workspace/git-panel/commit-modal.test.ts +5 -3
  153. package/src/client/components/workspace/user-browser-panel/AddressBar.tsx +5 -0
  154. package/src/client/components/workspace/user-browser-panel/AnnotateBar.test.tsx +201 -0
  155. package/src/client/components/workspace/user-browser-panel/AnnotateBar.tsx +112 -0
  156. package/src/client/components/workspace/user-browser-panel/AnnotateLayer.test.tsx +225 -0
  157. package/src/client/components/workspace/user-browser-panel/AnnotateLayer.tsx +217 -0
  158. package/src/client/components/workspace/user-browser-panel/AnnotateTarget.tsx +99 -0
  159. package/src/client/components/workspace/user-browser-panel/Frame.tsx +30 -1
  160. package/src/client/components/workspace/user-browser-panel/index.tsx +81 -2
  161. package/src/client/data/agent-data/builtin.ts +0 -10
  162. package/src/client/data/agent-data/orchestrator.ts +0 -45
  163. package/src/client/data/agent-data/specialist.ts +0 -100
  164. package/src/client/data/mock/token-usage.ts +170 -120
  165. package/src/client/data/settings/omp-schema.json +123 -4
  166. package/src/client/data/settings/project.ts +9 -28
  167. package/src/client/data/settings/skill.ts +6 -32
  168. package/src/client/hooks/browser/use-annotate.test.ts +143 -0
  169. package/src/client/hooks/browser/use-annotate.ts +98 -0
  170. package/src/client/hooks/browser/use-close-tab.test.ts +148 -0
  171. package/src/client/hooks/browser/use-close-tab.ts +67 -0
  172. package/src/client/hooks/browser/use-screencast.ts +13 -1
  173. package/src/client/hooks/chat/composer/browser-context.test.ts +117 -0
  174. package/src/client/hooks/chat/composer/browser-context.ts +40 -16
  175. package/src/client/hooks/chat/composer/items.test.ts +1 -1
  176. package/src/client/hooks/chat/composer/review-context.ts +38 -0
  177. package/src/client/hooks/chat/composer/use-draft.test.ts +132 -0
  178. package/src/client/hooks/chat/composer/use-draft.ts +31 -2
  179. package/src/client/hooks/chat/timeline/pending-model.ts +28 -0
  180. package/src/client/hooks/chat/timeline/row-window.test.ts +15 -2
  181. package/src/client/hooks/editor/use-document-annotations.ts +124 -0
  182. package/src/client/hooks/editor/use-editor-panel-ui.ts +52 -0
  183. package/src/client/hooks/editor/use-file-review-mode.ts +35 -0
  184. package/src/client/hooks/editor/use-preview-review.ts +148 -0
  185. package/src/client/hooks/settings/agents.ts +149 -0
  186. package/src/client/hooks/settings/crud-list.test.ts +28 -6
  187. package/src/client/hooks/settings/crud-list.ts +96 -57
  188. package/src/client/hooks/settings/omp-config.ts +164 -0
  189. package/src/client/hooks/settings/projects/index.ts +294 -0
  190. package/src/client/hooks/settings/projects.test.ts +237 -0
  191. package/src/client/hooks/settings/skill-catalog.ts +101 -9
  192. package/src/client/hooks/settings/skill-git-import.ts +153 -0
  193. package/src/client/hooks/settings/useTokenUsage.ts +125 -0
  194. package/src/client/hooks/settings/write-feedback.test.ts +104 -0
  195. package/src/client/hooks/settings/write-feedback.ts +63 -0
  196. package/src/client/hooks/shell/servers.test.ts +166 -0
  197. package/src/client/hooks/{desktop → shell}/servers.ts +17 -14
  198. package/src/client/hooks/ui/markdown-hydration.ts +125 -0
  199. package/src/client/hooks/ui/updates/index.test.ts +100 -1
  200. package/src/client/hooks/ui/updates/index.ts +50 -0
  201. package/src/client/hooks/ui/updates/notes.test.ts +138 -0
  202. package/src/client/hooks/ui/updates/notes.ts +57 -0
  203. package/src/client/hooks/ui/updates/shell-download.ts +1 -1
  204. package/src/client/hooks/ui/updates/shell-update.ts +2 -6
  205. package/src/client/hooks/workspace/file-row-drag.ts +41 -0
  206. package/src/client/hooks/workspace/file-tree-actions.ts +25 -1
  207. package/src/client/hooks/workspace/file-tree-edits.ts +23 -6
  208. package/src/client/hooks/workspace/root-drop-target.ts +77 -0
  209. package/src/client/hooks/workspace/unfolded-chains.ts +165 -0
  210. package/src/client/lib/browser/element-at.test.ts +229 -0
  211. package/src/client/lib/browser/element-at.ts +139 -0
  212. package/src/client/lib/desktop/dropped-paths.ts +1 -1
  213. package/src/client/lib/desktop/titlebar.test.ts +12 -3
  214. package/src/client/lib/desktop/titlebar.ts +1 -1
  215. package/src/client/lib/review/client.ts +73 -0
  216. package/src/client/lib/router/search-params.ts +42 -20
  217. package/src/client/lib/shell/desktop.ts +117 -0
  218. package/src/client/lib/shell/servers.ts +75 -0
  219. package/src/client/lib/shell/transport.ts +216 -0
  220. package/src/client/main.tsx +9 -0
  221. package/src/client/tailwind.css +65 -0
  222. package/src/server/lib/btw/lifecycle.server.ts +2 -2
  223. package/src/server/lib/db/schema.ts +7 -0
  224. package/src/server/lib/db/seed-terminal.test.ts +4 -0
  225. package/src/server/lib/fs/git-merge-conflict.test.ts +14 -1
  226. package/src/server/lib/omp/config/agent-definitions.test.ts +273 -0
  227. package/src/server/lib/omp/config/agents.ts +231 -61
  228. package/src/server/lib/omp/config/definitions.test.ts +9 -105
  229. package/src/server/lib/omp/config/extensions.ts +16 -7
  230. package/src/server/lib/omp/config/omp-config-files.test.ts +27 -0
  231. package/src/server/lib/omp/config/skill-sources.ts +49 -0
  232. package/src/server/lib/omp/config/skills-git-install.ts +155 -0
  233. package/src/server/lib/omp/config/skills-git-repo.ts +288 -0
  234. package/src/server/lib/omp/config/skills-git.test.ts +220 -0
  235. package/src/server/lib/omp/rpc/constants.test.ts +11 -0
  236. package/src/server/lib/omp/rpc/constants.ts +15 -0
  237. package/src/server/lib/omp/rpc/process.ts +11 -14
  238. package/src/server/lib/omp/rpc/session-commands.ts +6 -3
  239. package/src/server/lib/omp/rpc/utility-agent-dir.test.ts +134 -0
  240. package/src/server/lib/omp/rpc/utility-agent-dir.ts +138 -0
  241. package/src/server/lib/omp/rpc/utility.ts +12 -0
  242. package/src/server/lib/review/schema.server.ts +45 -0
  243. package/src/server/lib/review/store.server.ts +138 -0
  244. package/src/server/lib/terminal/attach-replay.test.ts +132 -0
  245. package/src/server/lib/terminal/output.test.ts +166 -0
  246. package/src/server/lib/terminal/output.ts +104 -0
  247. package/src/server/lib/terminal/runtime.server.ts +5 -0
  248. package/src/server/lib/terminal/send-result.test.ts +33 -0
  249. package/src/server/lib/terminal/send-result.ts +32 -0
  250. package/src/server/lib/terminal/session.server.ts +45 -11
  251. package/src/server/lib/terminal/store-liveness.test.ts +4 -0
  252. package/src/server/lib/updates/active-notes.test.ts +149 -0
  253. package/src/server/lib/updates/active-notes.ts +75 -0
  254. package/src/server/lib/updates/changelog-file.ts +42 -11
  255. package/src/server/lib/updates/changelog.test.ts +15 -1
  256. package/src/server/lib/updates/omp.ts +42 -15
  257. package/src/server/lib/updates/release-url.ts +27 -1
  258. package/src/server/lib/usage/index-parse.test.ts +200 -0
  259. package/src/server/lib/usage/index-parse.ts +178 -0
  260. package/src/server/lib/usage/index-query.server.ts +248 -0
  261. package/src/server/lib/usage/index-scan.server.ts +343 -0
  262. package/src/server/lib/usage/index-schema.server.ts +82 -0
  263. package/src/server/lib/usage/index.test.ts +234 -0
  264. package/src/server/lib/usage/providers.server.ts +4 -53
  265. package/src/server/lib/workspace/project-model.server.test.ts +102 -0
  266. package/src/server/lib/workspace/project-model.server.ts +47 -0
  267. package/src/server/lib/workspace/project-patch.server.ts +156 -0
  268. package/src/server/routes/agent/new.ts +8 -1
  269. package/src/server/routes/browser/index.ts +3 -0
  270. package/src/server/routes/browser/stream.ts +31 -2
  271. package/src/server/routes/browser/tabs.test.ts +94 -0
  272. package/src/server/routes/browser/tabs.ts +85 -0
  273. package/src/server/routes/index.ts +2 -0
  274. package/src/server/routes/review/bindings.ts +11 -0
  275. package/src/server/routes/review/index.ts +127 -0
  276. package/src/server/routes/review/routes.test.ts +191 -0
  277. package/src/server/routes/settings/agents.test.ts +180 -0
  278. package/src/server/routes/settings/agents.ts +99 -94
  279. package/src/server/routes/settings/mcp.test.ts +135 -0
  280. package/src/server/routes/settings/mcp.ts +14 -6
  281. package/src/server/routes/settings/projects.ts +53 -19
  282. package/src/server/routes/settings/settings-projects-routes.test.ts +214 -0
  283. package/src/server/routes/settings/settings-store-routes.test.ts +11 -115
  284. package/src/server/routes/settings/skills-catalog-actions.ts +195 -0
  285. package/src/server/routes/settings/skills.test.ts +225 -0
  286. package/src/server/routes/settings/skills.ts +18 -15
  287. package/src/server/routes/telemetry/tokens.test.ts +145 -0
  288. package/src/server/routes/telemetry/tokens.ts +70 -149
  289. package/src/server/routes/terminal/ws.ts +6 -5
  290. package/src/server/routes/updates/index.ts +2 -0
  291. package/src/server/routes/updates/notes.ts +34 -0
  292. package/src/server/routes/updates/routes.test.ts +49 -0
  293. package/src/shared/lib/browser/annotate.test.ts +283 -0
  294. package/src/shared/lib/browser/annotate.ts +231 -0
  295. package/src/shared/lib/browser/browser-viewer.test.ts +26 -4
  296. package/src/shared/lib/browser/frame-gate.test.ts +91 -0
  297. package/src/shared/lib/browser/frame-gate.ts +69 -0
  298. package/src/shared/lib/browser/frame-params.test.ts +43 -0
  299. package/src/shared/lib/browser/frame-params.ts +60 -0
  300. package/src/shared/lib/browser/frame-pipeline.test.ts +132 -0
  301. package/src/shared/lib/browser/frame-pipeline.ts +80 -0
  302. package/src/shared/lib/browser/page-context.ts +60 -4
  303. package/src/shared/lib/browser/snapshot.test.ts +115 -0
  304. package/src/shared/lib/browser/snapshot.ts +112 -0
  305. package/src/shared/lib/browser/tab-close.test.ts +74 -0
  306. package/src/shared/lib/browser/tab-close.ts +77 -0
  307. package/src/shared/lib/browser/viewer.ts +45 -26
  308. package/src/shared/lib/chat/timeline/block-chrome.ts +19 -0
  309. package/src/shared/lib/chat/timeline/tool-render-mode.ts +17 -4
  310. package/src/shared/lib/chat/tool/artifact.ts +55 -20
  311. package/src/shared/lib/chat/tool/bash-facts.ts +96 -0
  312. package/src/shared/lib/chat/tool/minimized.test.ts +98 -0
  313. package/src/shared/lib/chat/tool/minimized.ts +64 -0
  314. package/src/shared/lib/chat/tool/summary.test.ts +28 -8
  315. package/src/shared/lib/chat/tool/summary.ts +3 -32
  316. package/src/shared/lib/fs/folder-chain.test.ts +81 -1
  317. package/src/shared/lib/fs/folder-chain.ts +84 -0
  318. package/src/shared/lib/markdown/blocks/anchor.ts +63 -0
  319. package/src/shared/lib/markdown/blocks/blocks.test.ts +141 -0
  320. package/src/shared/lib/markdown/blocks/renderer.ts +120 -0
  321. package/src/shared/lib/markdown/blocks/scan.ts +100 -0
  322. package/src/shared/lib/markdown/blocks/types.ts +62 -0
  323. package/src/shared/lib/markdown/marked.ts +58 -147
  324. package/src/shared/lib/markdown/math-extensions.ts +168 -0
  325. package/src/shared/lib/markdown/review/prompt.ts +77 -0
  326. package/src/shared/lib/markdown/review/reconcile.ts +55 -0
  327. package/src/shared/lib/markdown/review/review.test.ts +96 -0
  328. package/src/shared/lib/markdown/xml-sections.test.ts +140 -0
  329. package/src/shared/lib/markdown/xml-sections.ts +139 -0
  330. package/src/shared/lib/models/provider/label.ts +57 -0
  331. package/src/shared/lib/omp/config/agent-file.test.ts +54 -0
  332. package/src/shared/lib/omp/config/agent-file.ts +43 -0
  333. package/src/shared/lib/omp/config/row-value.test.ts +95 -0
  334. package/src/shared/lib/omp/config/row-value.ts +97 -0
  335. package/src/shared/lib/omp/config/schema.test.ts +66 -0
  336. package/src/shared/lib/omp/config/schema.ts +6 -0
  337. package/src/shared/lib/omp/rpc/frame.test.ts +48 -47
  338. package/src/shared/lib/omp/rpc/frame.ts +49 -40
  339. package/src/shared/lib/omp/session/job-progress.test.ts +37 -1
  340. package/src/shared/lib/omp/session/job-progress.ts +31 -0
  341. package/src/shared/lib/omp/session/proc.ts +5 -0
  342. package/src/shared/lib/omp/session/wait.ts +5 -0
  343. package/src/shared/lib/ui/menu-anchor.test.ts +69 -0
  344. package/src/shared/lib/ui/menu-anchor.ts +89 -0
  345. package/src/shared/lib/ui/mobile-overlay.ts +61 -0
  346. package/src/shared/lib/ui/svg-scope.test.ts +97 -0
  347. package/src/shared/lib/ui/svg-scope.ts +134 -0
  348. package/src/shared/lib/usage/breakdown.test.ts +197 -0
  349. package/src/shared/lib/usage/breakdown.ts +241 -0
  350. package/src/shared/lib/usage/range.test.ts +204 -0
  351. package/src/shared/lib/usage/range.ts +240 -0
  352. package/src/shared/lib/usage/view.test.ts +85 -0
  353. package/src/shared/lib/usage/view.ts +74 -0
  354. package/src/shared/lib/workspace/project-accent.test.ts +69 -0
  355. package/src/shared/lib/workspace/project-accent.ts +63 -0
  356. package/src/shared/lib/workspace/project-icon.ts +40 -0
  357. package/src/shared/lib/workspace/project-model.test.ts +79 -0
  358. package/src/shared/lib/workspace/project-model.ts +64 -0
  359. package/src/shared/types/browser.ts +78 -0
  360. package/src/shared/types/index.ts +1 -0
  361. package/src/shared/types/settings/agent.ts +28 -6
  362. package/src/shared/types/settings/skill.ts +53 -3
  363. package/src/shared/types/settings/state.ts +4 -3
  364. package/src/shared/types/settings/write.ts +6 -0
  365. package/src/shared/types/tokenUsage.ts +128 -21
  366. package/src/shared/types/updates.ts +20 -0
  367. package/src/test-support/file-explorer-disk.test-util.ts +25 -1
  368. package/src/test-support/file-explorer-drag.test-util.ts +88 -0
  369. package/src/test-support/file-explorer.test-util.ts +47 -47
  370. package/dist/client/static/js/index-fjnq2z2d.css +0 -1
  371. package/src/client/components/common/code-surface/indent-guide.ts +0 -104
  372. package/src/client/components/common/server-switcher/index.test.tsx +0 -150
  373. package/src/client/components/settings/categories/skill-catalog/AddSourceModal.tsx +0 -133
  374. package/src/client/hooks/desktop/servers.test.ts +0 -73
  375. package/src/client/lib/desktop/bridge.ts +0 -203
  376. package/src/server/lib/omp/session/usage/aggregate-shaping.test.ts +0 -149
  377. package/src/server/lib/omp/session/usage/aggregate.test.ts +0 -243
  378. package/src/server/lib/omp/session/usage/aggregate.ts +0 -330
  379. package/src/server/lib/omp/session/usage/shaping.ts +0 -130
  380. package/src/shared/lib/code/editor/indent-guide-rule.test.ts +0 -65
  381. package/src/shared/lib/code/editor/indent-guide-rule.ts +0 -47
@@ -1,243 +0,0 @@
1
- /**
2
- * @license
3
- * SPDX-License-Identifier: MIT
4
- */
5
-
6
- /**
7
- * The usage rollup behind `/api/telemetry/tokens` (`aggregate.ts`).
8
- *
9
- * The aggregator folds a whole sessions tree into one aggregate per window, so
10
- * every risk here is arithmetic or filtering: a record counted in the wrong
11
- * window, a missing `usage` field read as NaN instead of 0, an entry that
12
- * carries `usage` but is not a `message` inflating the totals, an explicit
13
- * `totalTokens` ignored in favour of a re-derived sum, or an explicit
14
- * `cost.total` overridden by its parts. Each case pins one of those with
15
- * exact values, because a wrong number only surfaces later as a user's bill
16
- * disagreeing with the panel. The shaping half moved to
17
- * `aggregate-shaping.test.ts` so both files stay under the 350-line ceiling.
18
- *
19
- * The aggregator keeps its transcript scan in a module-scope cache (60 s TTL)
20
- * that nothing can reset, and `bun test` shares one module registry across
21
- * files. A query-suffixed dynamic import therefore loads a PRIVATE instance
22
- * per scenario: the unreadable-root case cannot leak into the populated one,
23
- * and the instance other suites import is never called from here.
24
- */
25
-
26
- import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
27
- import fs from 'fs';
28
- import os from 'os';
29
- import path from 'path';
30
-
31
- import type { TimeRangeType } from '@/shared/types';
32
- import { PRESET_RANGES, type UsageAggregate, type UsageWindow } from '@/server/lib/omp/session/usage/aggregate';
33
-
34
-
35
- /** The slice of the aggregator these tests drive, typed without an inline import. */
36
- interface AggregateModule {
37
- aggregateUsage(window: UsageWindow): Promise<UsageAggregate>;
38
- aggregateUsageWindows(window: UsageWindow): Promise<{
39
- ranges: Record<Exclude<TimeRangeType, 'custom'>, UsageAggregate>;
40
- active: UsageAggregate;
41
- }>;
42
- }
43
-
44
- const tempRoots: string[] = [];
45
- let savedAgentDir: string | undefined;
46
- let caseId = 0;
47
-
48
- /** A private module instance — see the header for why one per scenario. */
49
- async function loadAggregate(): Promise<AggregateModule> {
50
- // Built at runtime so TypeScript never tries to resolve the query suffix.
51
- const specifier = `./aggregate.ts?case=${caseId++}`;
52
- return (await import(specifier)) as AggregateModule;
53
- }
54
-
55
- function tempRoot(): string {
56
- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kabmo-test-'));
57
- tempRoots.push(root);
58
- return root;
59
- }
60
-
61
- /** Point `getSessionsDir()` at `<root>/agent/sessions`. */
62
- function useAgentDir(root: string): string {
63
- const agent = path.join(root, 'agent');
64
- process.env.PI_CODING_AGENT_DIR = agent;
65
- return path.join(agent, 'sessions');
66
- }
67
-
68
- function writeSession(sessionsRoot: string, project: string, file: string, lines: Array<unknown | string>): void {
69
- const target = path.join(sessionsRoot, project, file);
70
- fs.mkdirSync(path.dirname(target), { recursive: true });
71
- fs.writeFileSync(target, lines.map((line) => (typeof line === 'string' ? line : JSON.stringify(line))).join('\n') + '\n');
72
- }
73
-
74
- const DAY_MS = 24 * 60 * 60 * 1000;
75
- /** `YYYY-MM-DD` of an instant in LOCAL time — the frame a custom range parses in. */
76
- function localDay(ms: number): string {
77
- const d = new Date(ms);
78
- const p = (n: number) => String(n).padStart(2, '0');
79
- return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
80
- }
81
-
82
- let now = 0;
83
- let todayIso = '';
84
- let threeDaysIso = '';
85
- let tenDaysIso = '';
86
- /** The populated tree, scanned by private instances of the module. */
87
- let populatedRoot = '';
88
- /** The temp root `useAgentDir` takes — it appends `agent` itself, so passing
89
- * the sessions dir back in would look for `<tmp>/agent/agent`. */
90
- let populatedRootBase = '';
91
-
92
- function message(id: string, timestamp: string, model: string, usage: Record<string, unknown>): unknown {
93
- return {
94
- type: 'message',
95
- id,
96
- timestamp,
97
- message: { role: 'assistant', model, content: [{ type: 'text', text: 'answer' }], usage },
98
- };
99
- }
100
-
101
- beforeAll(() => {
102
- savedAgentDir = process.env.PI_CODING_AGENT_DIR;
103
- now = Date.now();
104
- todayIso = new Date(now).toISOString();
105
- threeDaysIso = new Date(now - 3 * DAY_MS).toISOString();
106
- tenDaysIso = new Date(now - 10 * DAY_MS).toISOString();
107
-
108
- populatedRootBase = tempRoot();
109
- populatedRoot = useAgentDir(populatedRootBase);
110
- const header = (id: string) => ({ type: 'session', id, cwd: '/work/alpha', timestamp: todayIso });
111
-
112
- writeSession(populatedRoot, 'proj-alpha', 'a1.jsonl', [
113
- header('s-alpha-1'),
114
- // A user row with no usage, and an assistant row with none either:
115
- // neither can be folded, and neither may be counted as a record.
116
- { type: 'message', id: 'm-user', timestamp: todayIso, message: { role: 'user', content: 'hello' } },
117
- { type: 'message', id: 'm-asst', timestamp: todayIso, message: { role: 'assistant', content: [{ type: 'text', text: 'hi' }] } },
118
- // Carries usage but is not a message entry: the filter must drop it.
119
- { type: 'custom', customType: 'tool_execution_start', timestamp: todayIso, message: { role: 'assistant', usage: { input: 999, output: 999, cost: { total: 9 } } } },
120
- // Explicit totalTokens, and a cost breakdown whose parts sum to `total`.
121
- message('m-1', todayIso, 'claude-x', {
122
- input: 100, output: 50, cacheRead: 200, cacheWrite: 10, reasoningTokens: 7, totalTokens: 360,
123
- cost: { input: 0.5, output: 0.25, cacheRead: 0.05, cacheWrite: 0.02, total: 0.82 },
124
- }),
125
- // No totalTokens (the derived sum is used) and no cache costs.
126
- message('m-2', threeDaysIso, 'gpt-y', { input: 1000, output: 200, cacheRead: 0, cacheWrite: 0, cost: { input: 1, output: 0.5, total: 1.5 } }),
127
- ]);
128
-
129
- writeSession(populatedRoot, 'proj-alpha', 'a2.jsonl', [
130
- header('s-alpha-2'),
131
- message('m-3', tenDaysIso, 'claude-x', { input: 10, output: 5, cacheRead: 0, cacheWrite: 0, totalTokens: 15, cost: { total: 0.03 } }),
132
- '{"type":"message","message":{"usage":{', // torn write: must not throw
133
- 'note mentioning "usage" in tool output', // parses to nothing
134
- '{"type":"message","message":{"role":"assistant","content":"plain"}}', // no usage key at all
135
- ]);
136
-
137
- // Non-session files and a nested directory must not become transcripts.
138
- fs.writeFileSync(path.join(populatedRoot, 'notes.txt'), 'not a session\n');
139
- fs.writeFileSync(path.join(populatedRoot, 'proj-alpha', 'README.md'), 'not a session\n');
140
- fs.mkdirSync(path.join(populatedRoot, 'proj-alpha', 'nested'), { recursive: true });
141
- });
142
-
143
- afterAll(() => {
144
- if (savedAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
145
- else process.env.PI_CODING_AGENT_DIR = savedAgentDir;
146
- for (const root of tempRoots) fs.rmSync(root, { recursive: true, force: true });
147
- });
148
-
149
- describe('aggregateUsage', () => {
150
- test('an unreadable sessions root yields the zero aggregate, not a throw', async () => {
151
- useAgentDir(tempRoot()); // no `agent/sessions` directory at all
152
- const { aggregateUsage } = await loadAggregate();
153
- const a = await aggregateUsage({ kind: 'all' });
154
- expect(a.scannedTranscripts).toBe(0);
155
- expect(a.usageRecords).toBe(0);
156
- expect(a.costTotal).toBe(0);
157
- expect(a.inputTokens + a.outputTokens + a.cacheReadTokens + a.cacheWriteTokens).toBe(0);
158
- expect(a.activeDays.size).toBe(0);
159
- expect([...a.byModel.keys()]).toEqual([]);
160
- expect([...a.byDay.keys()]).toEqual([]);
161
- });
162
-
163
- test('folds every usage record of the tree, with exact token and cost totals', async () => {
164
- useAgentDir(populatedRootBase);
165
- const { aggregateUsage } = await loadAggregate();
166
- const a = await aggregateUsage({ kind: 'all' });
167
-
168
- // Two .jsonl files; notes.txt, README.md and the nested dir are skipped.
169
- expect(a.scannedTranscripts).toBe(2);
170
- expect(a.usageRecords).toBe(3);
171
- expect(a.inputTokens).toBe(1110);
172
- expect(a.outputTokens).toBe(255);
173
- expect(a.cacheReadTokens).toBe(200);
174
- expect(a.cacheWriteTokens).toBe(10);
175
- expect(a.reasoningTokens).toBe(7);
176
- expect(a.costInput).toBeCloseTo(1.5, 10);
177
- expect(a.costOutput).toBeCloseTo(0.75, 10);
178
- expect(a.costCacheRead).toBeCloseTo(0.05, 10);
179
- expect(a.costCacheWrite).toBeCloseTo(0.02, 10);
180
- expect(a.costTotal).toBeCloseTo(2.35, 10);
181
-
182
- expect([...a.activeDays].sort()).toEqual([tenDaysIso, threeDaysIso, todayIso].map((iso) => iso.slice(0, 10)).sort());
183
- // byModel/byProject/byDay count `totalTokens`, with the derived fallback.
184
- expect(a.byModel.get('claude-x')).toEqual({ tokens: 375, cost: 0.85 });
185
- expect(a.byModel.get('gpt-y')).toEqual({ tokens: 1200, cost: 1.5 });
186
- const alpha = a.byProject.get('proj-alpha');
187
- expect(alpha?.tokens).toBe(1575);
188
- // 0.85 + 1.5 accumulates as binary floats (2.3499999999999996) — the
189
- // rollup sums what it read and does not round, so the exact literal would
190
- // pin an accident of float addition rather than the arithmetic.
191
- expect(alpha?.cost).toBeCloseTo(2.35, 10);
192
- expect(a.byDay.get(threeDaysIso.slice(0, 10))).toEqual({ tokens: 1200, cost: 1.5 });
193
- });
194
-
195
- test('windows exclude records outside their bounds', async () => {
196
- useAgentDir(populatedRootBase);
197
- const { aggregateUsage } = await loadAggregate();
198
-
199
- const today = await aggregateUsage({ kind: 'preset', range: 'today' });
200
- expect(today.usageRecords).toBe(1);
201
- expect(today.inputTokens).toBe(100);
202
- expect(today.costTotal).toBeCloseTo(0.82, 10);
203
- expect([...today.byModel.keys()]).toEqual(['claude-x']);
204
-
205
- const week = await aggregateUsage({ kind: 'preset', range: '7d' });
206
- expect(week.usageRecords).toBe(2);
207
- expect(week.inputTokens).toBe(1100);
208
- expect(week.outputTokens).toBe(250);
209
- expect(week.costTotal).toBeCloseTo(2.32, 10);
210
-
211
- // A single local calendar day, ten days back.
212
- const custom = await aggregateUsage({ kind: 'custom', from: localDay(now - 10 * DAY_MS), to: localDay(now - 10 * DAY_MS) });
213
- expect(custom.usageRecords).toBe(1);
214
- expect(custom.inputTokens).toBe(10);
215
- expect(custom.costTotal).toBeCloseTo(0.03, 10);
216
- });
217
-
218
- test('an unusable custom range falls back to unbounded rather than empty', async () => {
219
- useAgentDir(populatedRootBase);
220
- const { aggregateUsage } = await loadAggregate();
221
- expect((await aggregateUsage({ kind: 'custom', from: '2026-01-02', to: '2026-01-01' })).usageRecords).toBe(3);
222
- expect((await aggregateUsage({ kind: 'custom', from: 'not-a-date', to: '2026-01-01' })).usageRecords).toBe(3);
223
- });
224
- });
225
-
226
- describe('aggregateUsageWindows', () => {
227
- test('folds every preset plus the active window from one scan', async () => {
228
- useAgentDir(populatedRootBase);
229
- const { aggregateUsageWindows } = await loadAggregate();
230
- const { ranges, active } = await aggregateUsageWindows({ kind: 'custom', from: '1999-01-01', to: '1999-01-02' });
231
-
232
- // Every range the tokens endpoint reports, in display order.
233
- expect(PRESET_RANGES).toEqual(['today', '7d', '30d', '90d', 'all']);
234
- expect(Object.keys(ranges)).toEqual(['today', '7d', '30d', '90d', 'all']);
235
- expect(ranges.today.usageRecords).toBe(1);
236
- expect(ranges['7d'].usageRecords).toBe(2);
237
- expect(ranges['30d'].usageRecords).toBe(3);
238
- expect(ranges['90d'].usageRecords).toBe(3);
239
- expect(ranges.all.usageRecords).toBe(3);
240
- expect(active.usageRecords).toBe(0);
241
- for (const range of PRESET_RANGES) expect(ranges[range].scannedTranscripts).toBe(2);
242
- });
243
- });
@@ -1,330 +0,0 @@
1
- /**
2
- * @license
3
- * SPDX-License-Identifier: MIT
4
- */
5
-
6
- /**
7
- * Real token/cost usage aggregation from oh-my-pi session files
8
- * (~/.omp/agent/sessions/<project>/*.jsonl). Faithful to the omp session
9
- * format parsed by lib/omp/session (usage blocks with input/output/cache/
10
- * reasoning tokens and per-message cost). Powers /api/telemetry/tokens in
11
- * real mode so telemetry reflects actual omp activity instead of zeros.
12
- */
13
-
14
- import fs from 'fs';
15
- import { join } from 'path';
16
- import { getSessionsDir } from '@/server/lib/omp/core/paths';
17
- import type { TimeRangeType } from '@/shared/types';
18
- import type { OmpMessageEntry, OmpUsage } from '@/shared/types/omp/session';
19
-
20
- export type UsageWindow =
21
- | { kind: 'preset'; range: Exclude<TimeRangeType, 'custom'> }
22
- | { kind: 'custom'; from: string; to: string }
23
- | { kind: 'all' };
24
-
25
- const PRESET_DAYS: Record<Exclude<TimeRangeType, 'custom' | 'all' | 'today'>, number> = { '7d': 7, '30d': 30, '90d': 90 };
26
-
27
- /** Every range the tokens endpoint reports, in display order. */
28
- export const PRESET_RANGES: Exclude<TimeRangeType, 'custom'>[] = ['today', '7d', '30d', '90d', 'all'];
29
-
30
- const TTL_MS = 60_000;
31
- const cache = new Map<string, { at: number; data: UsageAggregate }>();
32
-
33
- export interface UsageAggregate {
34
- scannedTranscripts: number;
35
- usageRecords: number;
36
- costTotal: number;
37
- costInput: number;
38
- costOutput: number;
39
- costCacheRead: number;
40
- costCacheWrite: number;
41
- inputTokens: number;
42
- outputTokens: number;
43
- cacheReadTokens: number;
44
- cacheWriteTokens: number;
45
- reasoningTokens: number;
46
- activeDays: Set<string>;
47
- byModel: Map<string, { tokens: number; cost: number }>;
48
- byDay: Map<string, { tokens: number; cost: number }>;
49
- byProject: Map<string, { tokens: number; cost: number }>;
50
- }
51
-
52
- function emptyAggregate(): UsageAggregate {
53
- return {
54
- scannedTranscripts: 0,
55
- usageRecords: 0,
56
- costTotal: 0,
57
- costInput: 0,
58
- costOutput: 0,
59
- costCacheRead: 0,
60
- costCacheWrite: 0,
61
- inputTokens: 0,
62
- outputTokens: 0,
63
- cacheReadTokens: 0,
64
- cacheWriteTokens: 0,
65
- reasoningTokens: 0,
66
- activeDays: new Set(),
67
- byModel: new Map(),
68
- byDay: new Map(),
69
- byProject: new Map(),
70
- };
71
- }
72
-
73
- function bump(map: Map<string, { tokens: number; cost: number }>, key: string, tokens: number, cost: number): void {
74
- const current = map.get(key) ?? { tokens: 0, cost: 0 };
75
- current.tokens += tokens;
76
- current.cost += cost;
77
- map.set(key, current);
78
- }
79
-
80
- function cacheKey(window: UsageWindow): string {
81
- if (window.kind === 'all') return 'all';
82
- if (window.kind === 'custom') return `custom:${window.from}:${window.to}`;
83
- return window.range;
84
- }
85
-
86
- /**
87
- * One usage record, with everything a window needs to decide whether it counts.
88
- *
89
- * The scan that produces these is the expensive part — measured 795 ms over 455
90
- * transcripts / 327 MB — so it runs ONCE and every window is derived from the
91
- * same array. Aggregating per window re-read the whole tree for each of the five
92
- * presets plus the active window, which is why `/api/telemetry/tokens` took
93
- * 3.3 s cold.
94
- */
95
- interface UsageRecord {
96
- /** Epoch ms of the entry's timestamp, or undefined when it has none. */
97
- at: number | undefined;
98
- /** `YYYY-MM-DD` of `at`, or undefined. */
99
- day: string | undefined;
100
- model: string;
101
- project: string;
102
- cost: number;
103
- costInput: number;
104
- costOutput: number;
105
- costCacheRead: number;
106
- costCacheWrite: number;
107
- input: number;
108
- output: number;
109
- cacheRead: number;
110
- cacheWrite: number;
111
- reasoning: number;
112
- total: number;
113
- }
114
-
115
- interface UsageScan {
116
- at: number;
117
- records: UsageRecord[];
118
- /** Transcripts visited, counted once for every window. */
119
- scannedTranscripts: number;
120
- }
121
-
122
- let scanCache: UsageScan | null = null;
123
-
124
- /** A session entry narrowed to the one shape the scan folds. */
125
- interface UsageEntry {
126
- entry: OmpMessageEntry;
127
- /** The message, with `usage` proven present by the filter above. */
128
- message: { usage: OmpUsage; model?: string };
129
- }
130
-
131
- /**
132
- * The `usage` blocks in one transcript, without parsing the entries that carry
133
- * none.
134
- *
135
- * A session file is mostly tool output — on the measured 11 MB session, 987 of
136
- * 3252 lines carry usage. `JSON.parse` of the other two thirds was the whole
137
- * cost of the scan, so each line is tested for the literal `"usage"` first:
138
- * JSON.stringify writes that key verbatim, so a line that lacks it cannot be a
139
- * message with usage. A line whose tool output happens to contain the text is
140
- * parsed and then dropped by the type check — a wasted parse, never a missed
141
- * record. Measured over the 478-file sessions tree: 493 ms → 281 ms, identical
142
- * record count.
143
- */
144
- function parseUsageLines(body: string): UsageEntry[] {
145
- const out: UsageEntry[] = [];
146
- for (const raw of body.split('\n')) {
147
- if (!raw.includes('"usage"')) continue;
148
- const line = raw.trim();
149
- if (!line) continue;
150
- try {
151
- const entry = JSON.parse(line) as OmpMessageEntry;
152
- const message = entry.message;
153
- if (entry.type === 'message' && message?.usage) out.push({ entry, message: { usage: message.usage, model: message.model } });
154
- } catch {
155
- // Torn write / prefix-window truncation — same tolerance as the lenient parse.
156
- }
157
- }
158
- return out;
159
- }
160
-
161
- /** Every usage record in the sessions tree, read at most once per TTL. */
162
- async function scanUsage(): Promise<UsageScan> {
163
- if (scanCache && Date.now() - scanCache.at < TTL_MS) return scanCache;
164
-
165
- const sessionsRoot = getSessionsDir();
166
- const records: UsageRecord[] = [];
167
- let scannedTranscripts = 0;
168
- let projectDirs: string[] = [];
169
- try {
170
- projectDirs = (await fs.promises.readdir(sessionsRoot, { withFileTypes: true }))
171
- .filter((d) => d.isDirectory() || d.isFile())
172
- .map((d) => d.name);
173
- } catch {
174
- scanCache = { at: Date.now(), records, scannedTranscripts };
175
- return scanCache;
176
- }
177
-
178
- for (const project of projectDirs) {
179
- const projectPath = join(sessionsRoot, project);
180
- let files: string[] = [];
181
- try {
182
- if ((await Bun.file(projectPath).stat()).isFile()) {
183
- files = project.endsWith('.jsonl') ? [projectPath] : [];
184
- } else {
185
- files = (await fs.promises.readdir(projectPath))
186
- .filter((f) => f.endsWith('.jsonl'))
187
- .map((f) => join(projectPath, f));
188
- }
189
- } catch {
190
- continue;
191
- }
192
-
193
- for (const file of files) {
194
- scannedTranscripts++;
195
- try {
196
- const ufile = Bun.file(file);
197
- if ((await ufile.stat()).size > 64 * 1024 * 1024) continue;
198
- for (const { entry, message } of parseUsageLines(await ufile.text())) {
199
- const usage = message.usage;
200
- const ts = entry.timestamp;
201
- const parsed = ts ? Date.parse(ts) : Number.NaN;
202
- records.push({
203
- at: Number.isNaN(parsed) ? undefined : parsed,
204
- day: ts ? ts.slice(0, 10) : undefined,
205
- model: message.model || 'unknown',
206
- project,
207
- cost: usage.cost?.total ?? 0,
208
- costInput: usage.cost?.input ?? 0,
209
- costOutput: usage.cost?.output ?? 0,
210
- costCacheRead: usage.cost?.cacheRead ?? 0,
211
- costCacheWrite: usage.cost?.cacheWrite ?? 0,
212
- input: usage.input ?? 0,
213
- output: usage.output ?? 0,
214
- cacheRead: usage.cacheRead ?? 0,
215
- cacheWrite: usage.cacheWrite ?? 0,
216
- reasoning: usage.reasoningTokens ?? 0,
217
- total: usage.totalTokens ?? (usage.input ?? 0) + (usage.output ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0),
218
- });
219
- }
220
- } catch {
221
- // Unreadable transcript — skip rather than failing the whole report.
222
- }
223
- }
224
- }
225
-
226
- scanCache = { at: Date.now(), records, scannedTranscripts };
227
- return scanCache;
228
- }
229
-
230
- /** Fold the scanned records that fall inside `window` into an aggregate. */
231
- function foldWindow(records: readonly UsageRecord[], window: UsageWindow, now: number, scannedTranscripts: number): UsageAggregate {
232
- const aggregate = emptyAggregate();
233
- aggregate.scannedTranscripts = scannedTranscripts;
234
- const bounds = windowBounds(window, now);
235
- for (const record of records) {
236
- // An entry with no usable timestamp is kept by EVERY window — a missing
237
- // date is not evidence of age, and this matches the previous per-record
238
- // behaviour.
239
- if (record.at !== undefined && (record.at < bounds.from || record.at > bounds.to)) continue;
240
- aggregate.usageRecords++;
241
- aggregate.costTotal += record.cost;
242
- aggregate.costInput += record.costInput;
243
- aggregate.costOutput += record.costOutput;
244
- aggregate.costCacheRead += record.costCacheRead;
245
- aggregate.costCacheWrite += record.costCacheWrite;
246
- aggregate.inputTokens += record.input;
247
- aggregate.outputTokens += record.output;
248
- aggregate.cacheReadTokens += record.cacheRead;
249
- aggregate.cacheWriteTokens += record.cacheWrite;
250
- aggregate.reasoningTokens += record.reasoning;
251
- if (record.day) {
252
- aggregate.activeDays.add(record.day);
253
- bump(aggregate.byDay, record.day, record.total, record.cost);
254
- }
255
- bump(aggregate.byModel, record.model, record.total, record.cost);
256
- bump(aggregate.byProject, record.project, record.total, record.cost);
257
- }
258
- return aggregate;
259
- }
260
-
261
- interface WindowBounds {
262
- /** Inclusive epoch-ms bounds; `-Infinity`/`Infinity` for an unbounded side. */
263
- from: number;
264
- to: number;
265
- }
266
-
267
- /**
268
- * Epoch-ms bounds for a window, computed once per fold.
269
- *
270
- * `today` is a local CALENDAR day (`setHours(0,0,0,0)`), not "the last 24h":
271
- * the panel's "today" tab counts the day the user is in, and the previous
272
- * implementation compared year/month/date for the same reason.
273
- */
274
- function windowBounds(window: UsageWindow, now: number): WindowBounds {
275
- if (window.kind === 'custom') {
276
- const from = Date.parse(`${window.from}T00:00:00`);
277
- const to = Date.parse(`${window.to}T23:59:59.999`);
278
- if (Number.isNaN(from) || Number.isNaN(to) || from > to) return { from: -Infinity, to: Infinity };
279
- return { from, to };
280
- }
281
- if (window.kind === 'all') return { from: -Infinity, to: Infinity };
282
- switch (window.range) {
283
- case 'all':
284
- return { from: -Infinity, to: Infinity };
285
- case 'today': {
286
- const start = new Date(now);
287
- start.setHours(0, 0, 0, 0);
288
- const end = new Date(start);
289
- end.setDate(end.getDate() + 1);
290
- return { from: start.getTime(), to: end.getTime() - 1 };
291
- }
292
- default:
293
- return { from: now - PRESET_DAYS[window.range] * 24 * 60 * 60 * 1000, to: Infinity };
294
- }
295
- }
296
-
297
- /** Aggregate all omp session files within a time window. Cached for 60s. */
298
- export async function aggregateUsage(window: UsageWindow): Promise<UsageAggregate> {
299
- const key = cacheKey(window);
300
- const cached = cache.get(key);
301
- if (cached && Date.now() - cached.at < TTL_MS) return cached.data;
302
-
303
- const scan = await scanUsage();
304
- const data = foldWindow(scan.records, window, Date.now(), scan.scannedTranscripts);
305
- if (cache.size > 20) cache.clear();
306
- cache.set(key, { at: Date.now(), data });
307
- return data;
308
- }
309
-
310
- /**
311
- * Aggregate EVERY preset range plus `window` from one scan.
312
- *
313
- * The tokens endpoint needs all six, and folding them from one scan costs the
314
- * fold (linear in records) rather than six more tree reads.
315
- */
316
- export async function aggregateUsageWindows(
317
- window: UsageWindow,
318
- ): Promise<{ ranges: Record<Exclude<TimeRangeType, 'custom'>, UsageAggregate>; active: UsageAggregate }> {
319
- const scan = await scanUsage();
320
- const now = Date.now();
321
- const ranges = {} as Record<Exclude<TimeRangeType, 'custom'>, UsageAggregate>;
322
- for (const range of PRESET_RANGES) {
323
- ranges[range] = foldWindow(scan.records, { kind: 'preset', range }, now, scan.scannedTranscripts);
324
- }
325
- const active = foldWindow(scan.records, window, now, scan.scannedTranscripts);
326
- // Cache each fold under its own key so a later single-window call reuses it.
327
- for (const range of PRESET_RANGES) cache.set(range, { at: now, data: ranges[range] });
328
- cache.set(cacheKey(window), { at: now, data: active });
329
- return { ranges, active };
330
- }