@kabmo-labs/kabmo 0.17.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 (269) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +538 -457
  3. package/dist/client/static/js/index-hp75vsv9.css +1 -0
  4. package/dist/client/static/js/{index-rerjq5th.js → index-tc09dtca.js} +823 -814
  5. package/package.json +1 -1
  6. package/src/client/components/common/MarkdownRenderer.tsx +136 -89
  7. package/src/client/components/common/anchored-menu/index.test.tsx +141 -0
  8. package/src/client/components/common/anchored-menu/index.tsx +143 -0
  9. package/src/client/components/common/markdown-review/ReviewPopover.tsx +144 -0
  10. package/src/client/components/common/markdown-review/ReviewSummary.tsx +108 -0
  11. package/src/client/components/common/markdown-review/index.tsx +129 -0
  12. package/src/client/components/common/server-control/Panel.tsx +33 -23
  13. package/src/client/components/common/server-control/index.test.tsx +11 -5
  14. package/src/client/components/common/server-control/index.tsx +10 -8
  15. package/src/client/components/layout/session-sidebar/CategoryHeader.tsx +42 -21
  16. package/src/client/components/layout/session-sidebar/CategoryHeader.worktree.test.tsx +36 -17
  17. package/src/client/components/layout/session-sidebar/CategoryItem.tsx +8 -7
  18. package/src/client/components/layout/session-sidebar/about-modal/NotesDialog.tsx +94 -0
  19. package/src/client/components/layout/session-sidebar/about-modal/VersionLine.test.tsx +68 -0
  20. package/src/client/components/layout/session-sidebar/about-modal/VersionLine.tsx +36 -0
  21. package/src/client/components/layout/session-sidebar/about-modal/index.tsx +57 -34
  22. package/src/client/components/layout/session-sidebar/modern/WorkspaceHeader.tsx +28 -10
  23. package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +7 -6
  24. package/src/client/components/layout/session-sidebar/modern/workspace-header.test.tsx +1 -1
  25. package/src/client/components/layout/update-popup/ReleaseNotes.tsx +8 -3
  26. package/src/client/components/layout/update-popup/index.tsx +5 -1
  27. package/src/client/components/mobile/mobile-right-sidebar/FullEditor.tsx +13 -15
  28. package/src/client/components/mobile/mobile-right-sidebar/Header.tsx +23 -1
  29. package/src/client/components/mobile/mobile-right-sidebar/MissingFileBanner.tsx +30 -0
  30. package/src/client/components/mobile/mobile-right-sidebar/PreviewScroller.tsx +18 -2
  31. package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +22 -67
  32. package/src/client/components/mobile/mobile-session-sidebar/ItemMenu.tsx +110 -0
  33. package/src/client/components/settings/SettingsSidebarList.tsx +20 -0
  34. package/src/client/components/settings/categories/AgentSettings.tsx +23 -50
  35. package/src/client/components/settings/categories/CommandSettings.tsx +2 -2
  36. package/src/client/components/settings/categories/McpSettings.tsx +4 -21
  37. package/src/client/components/settings/categories/OmpSettings.tsx +147 -194
  38. package/src/client/components/settings/categories/SkillSettings.tsx +2 -2
  39. package/src/client/components/settings/categories/TokenUsageSettings.tsx +211 -229
  40. package/src/client/components/settings/categories/agent-settings/DetailPane.tsx +229 -237
  41. package/src/client/components/settings/categories/agent-settings/ModelPicker.tsx +71 -0
  42. package/src/client/components/settings/categories/agent-settings/SidebarList.tsx +9 -2
  43. package/src/client/components/settings/categories/agent-settings/levels.ts +38 -0
  44. package/src/client/components/settings/categories/behavior-settings/Editor.tsx +27 -7
  45. package/src/client/components/settings/categories/chat-settings/ToolRenderSection.tsx +23 -5
  46. package/src/client/components/settings/categories/command-settings/DetailPane.tsx +75 -33
  47. package/src/client/components/settings/categories/command-settings/SidebarList.tsx +7 -0
  48. package/src/client/components/settings/categories/mcp-settings/DetailPane.tsx +91 -76
  49. package/src/client/components/settings/categories/mcp-settings/EnvVarsSection.tsx +83 -0
  50. package/src/client/components/settings/categories/mcp-settings/ImportModal.tsx +26 -13
  51. package/src/client/components/settings/categories/mcp-settings/SidebarList.tsx +20 -0
  52. package/src/client/components/settings/categories/omp-settings/ConfigTabs.tsx +97 -36
  53. package/src/client/components/settings/categories/omp-settings/EngineHeader.tsx +151 -0
  54. package/src/client/components/settings/categories/omp-settings/ExtensionsPanel.tsx +68 -32
  55. package/src/client/components/settings/categories/omp-settings/OrderedChips.tsx +119 -0
  56. package/src/client/components/settings/categories/omp-settings/PresetBar.tsx +14 -7
  57. package/src/client/components/settings/categories/omp-settings/RoleEditor.tsx +15 -6
  58. package/src/client/components/settings/categories/omp-settings/RowEditor.tsx +165 -226
  59. package/src/client/components/settings/categories/omp-settings/types.ts +28 -0
  60. package/src/client/components/settings/categories/skill-settings/DetailHeader.tsx +35 -7
  61. package/src/client/components/settings/categories/skill-settings/DetailPane.tsx +34 -14
  62. package/src/client/components/settings/categories/skill-settings/SidebarList.tsx +21 -0
  63. package/src/client/components/settings/categories/skill-settings/pane.test.tsx +15 -6
  64. package/src/client/components/settings/categories/token-usage-settings/Breakdown.tsx +242 -102
  65. package/src/client/components/settings/categories/token-usage-settings/Chart.tsx +130 -56
  66. package/src/client/components/settings/categories/token-usage-settings/Controls.tsx +135 -0
  67. package/src/client/components/settings/categories/token-usage-settings/MetricsGrid.tsx +55 -33
  68. package/src/client/components/settings/categories/token-usage-settings/Provenance.tsx +59 -0
  69. package/src/client/components/settings/categories/token-usage-settings/panel.test.tsx +239 -0
  70. package/src/client/components/workspace/browser-panel/Screencast.test.ts +1 -0
  71. package/src/client/components/workspace/browser-panel/Screencast.tsx +17 -22
  72. package/src/client/components/workspace/browser-panel/TabStrip.test.tsx +158 -0
  73. package/src/client/components/workspace/browser-panel/TabStrip.tsx +90 -0
  74. package/src/client/components/workspace/browser-panel/index.tsx +50 -4
  75. package/src/client/components/workspace/browser-toolbar/index.tsx +41 -1
  76. package/src/client/components/workspace/chat-timeline/ThinkingSection.tsx +3 -1
  77. package/src/client/components/workspace/chat-timeline/ToolCallingSection.tsx +2 -0
  78. package/src/client/components/workspace/chat-timeline/block-chrome.test.tsx +13 -2
  79. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Bash.test.ts +88 -0
  80. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Bash.tsx +24 -1
  81. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Read.test.ts +34 -0
  82. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Read.tsx +5 -1
  83. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/ArtifactChip.tsx +7 -6
  84. package/src/client/components/workspace/chat-timeline/tool-renderers/styles/Tui.test.tsx +237 -0
  85. package/src/client/components/workspace/chat-timeline/tool-renderers/styles/Tui.tsx +191 -0
  86. package/src/client/components/workspace/chat-timeline/tool-renderers/styles/styles.test.tsx +1 -1
  87. package/src/client/components/workspace/diff-panel/MergeDiffView.tsx +21 -7
  88. package/src/client/components/workspace/diff-panel/changes.test.ts +51 -0
  89. package/src/client/components/workspace/diff-panel/changes.ts +28 -12
  90. package/src/client/components/workspace/diff-panel/merge.test.ts +28 -0
  91. package/src/client/components/workspace/diff-panel/merge.ts +21 -1
  92. package/src/client/components/workspace/editor/Body.tsx +7 -0
  93. package/src/client/components/workspace/editor/FileDocument.tsx +15 -21
  94. package/src/client/components/workspace/editor/FilePane.tsx +12 -0
  95. package/src/client/components/workspace/editor/PreviewPane.tsx +70 -0
  96. package/src/client/components/workspace/editor/Toolbar.tsx +17 -1
  97. package/src/client/components/workspace/editor/index.tsx +25 -22
  98. package/src/client/components/workspace/editor/toolbar-clusters.test.ts +14 -0
  99. package/src/client/components/workspace/editor/toolbar-clusters.tsx +12 -86
  100. package/src/client/components/workspace/editor/toolbar-toggle.tsx +53 -0
  101. package/src/client/components/workspace/editor/toolbar-write-clusters.tsx +112 -0
  102. package/src/client/components/workspace/git-panel/commit-modal.test.ts +5 -3
  103. package/src/client/components/workspace/user-browser-panel/AddressBar.tsx +5 -0
  104. package/src/client/components/workspace/user-browser-panel/AnnotateBar.test.tsx +201 -0
  105. package/src/client/components/workspace/user-browser-panel/AnnotateBar.tsx +112 -0
  106. package/src/client/components/workspace/user-browser-panel/AnnotateLayer.test.tsx +225 -0
  107. package/src/client/components/workspace/user-browser-panel/AnnotateLayer.tsx +217 -0
  108. package/src/client/components/workspace/user-browser-panel/AnnotateTarget.tsx +99 -0
  109. package/src/client/components/workspace/user-browser-panel/Frame.tsx +30 -1
  110. package/src/client/components/workspace/user-browser-panel/index.tsx +81 -2
  111. package/src/client/data/agent-data/builtin.ts +0 -10
  112. package/src/client/data/agent-data/orchestrator.ts +0 -45
  113. package/src/client/data/agent-data/specialist.ts +0 -100
  114. package/src/client/data/mock/token-usage.ts +170 -120
  115. package/src/client/data/settings/omp-schema.json +33 -1
  116. package/src/client/hooks/browser/use-annotate.test.ts +143 -0
  117. package/src/client/hooks/browser/use-annotate.ts +98 -0
  118. package/src/client/hooks/browser/use-close-tab.test.ts +148 -0
  119. package/src/client/hooks/browser/use-close-tab.ts +67 -0
  120. package/src/client/hooks/browser/use-screencast.ts +13 -1
  121. package/src/client/hooks/chat/composer/browser-context.test.ts +117 -0
  122. package/src/client/hooks/chat/composer/browser-context.ts +40 -16
  123. package/src/client/hooks/chat/composer/items.test.ts +1 -1
  124. package/src/client/hooks/chat/composer/review-context.ts +38 -0
  125. package/src/client/hooks/chat/composer/use-draft.test.ts +132 -0
  126. package/src/client/hooks/chat/composer/use-draft.ts +31 -2
  127. package/src/client/hooks/chat/timeline/row-window.test.ts +15 -2
  128. package/src/client/hooks/editor/use-document-annotations.ts +124 -0
  129. package/src/client/hooks/editor/use-editor-panel-ui.ts +52 -0
  130. package/src/client/hooks/editor/use-file-review-mode.ts +35 -0
  131. package/src/client/hooks/editor/use-preview-review.ts +148 -0
  132. package/src/client/hooks/settings/agents.ts +149 -0
  133. package/src/client/hooks/settings/crud-list.test.ts +28 -6
  134. package/src/client/hooks/settings/crud-list.ts +96 -57
  135. package/src/client/hooks/settings/omp-config.ts +164 -0
  136. package/src/client/hooks/settings/useTokenUsage.ts +125 -0
  137. package/src/client/hooks/settings/write-feedback.test.ts +104 -0
  138. package/src/client/hooks/settings/write-feedback.ts +63 -0
  139. package/src/client/hooks/ui/markdown-hydration.ts +125 -0
  140. package/src/client/hooks/ui/updates/index.test.ts +100 -1
  141. package/src/client/hooks/ui/updates/index.ts +50 -0
  142. package/src/client/hooks/ui/updates/notes.test.ts +138 -0
  143. package/src/client/hooks/ui/updates/notes.ts +57 -0
  144. package/src/client/lib/browser/element-at.test.ts +229 -0
  145. package/src/client/lib/browser/element-at.ts +139 -0
  146. package/src/client/lib/review/client.ts +73 -0
  147. package/src/client/lib/router/search-params.ts +42 -20
  148. package/src/client/tailwind.css +65 -0
  149. package/src/server/lib/btw/lifecycle.server.ts +2 -2
  150. package/src/server/lib/db/schema.ts +7 -0
  151. package/src/server/lib/db/seed-terminal.test.ts +4 -0
  152. package/src/server/lib/omp/config/agent-definitions.test.ts +273 -0
  153. package/src/server/lib/omp/config/agents.ts +231 -61
  154. package/src/server/lib/omp/config/definitions.test.ts +9 -105
  155. package/src/server/lib/omp/config/extensions.ts +16 -7
  156. package/src/server/lib/omp/config/omp-config-files.test.ts +27 -0
  157. package/src/server/lib/omp/rpc/constants.test.ts +11 -0
  158. package/src/server/lib/omp/rpc/constants.ts +15 -0
  159. package/src/server/lib/omp/rpc/process.ts +11 -14
  160. package/src/server/lib/omp/rpc/session-commands.ts +6 -3
  161. package/src/server/lib/omp/rpc/utility-agent-dir.test.ts +134 -0
  162. package/src/server/lib/omp/rpc/utility-agent-dir.ts +138 -0
  163. package/src/server/lib/omp/rpc/utility.ts +12 -0
  164. package/src/server/lib/review/schema.server.ts +45 -0
  165. package/src/server/lib/review/store.server.ts +138 -0
  166. package/src/server/lib/terminal/attach-replay.test.ts +132 -0
  167. package/src/server/lib/terminal/output.test.ts +166 -0
  168. package/src/server/lib/terminal/output.ts +104 -0
  169. package/src/server/lib/terminal/runtime.server.ts +5 -0
  170. package/src/server/lib/terminal/send-result.test.ts +33 -0
  171. package/src/server/lib/terminal/send-result.ts +32 -0
  172. package/src/server/lib/terminal/session.server.ts +45 -11
  173. package/src/server/lib/terminal/store-liveness.test.ts +4 -0
  174. package/src/server/lib/updates/active-notes.test.ts +149 -0
  175. package/src/server/lib/updates/active-notes.ts +75 -0
  176. package/src/server/lib/updates/changelog-file.ts +42 -11
  177. package/src/server/lib/updates/changelog.test.ts +15 -1
  178. package/src/server/lib/updates/omp.ts +42 -15
  179. package/src/server/lib/updates/release-url.ts +27 -1
  180. package/src/server/lib/usage/index-parse.test.ts +200 -0
  181. package/src/server/lib/usage/index-parse.ts +178 -0
  182. package/src/server/lib/usage/index-query.server.ts +248 -0
  183. package/src/server/lib/usage/index-scan.server.ts +343 -0
  184. package/src/server/lib/usage/index-schema.server.ts +82 -0
  185. package/src/server/lib/usage/index.test.ts +234 -0
  186. package/src/server/lib/usage/providers.server.ts +4 -53
  187. package/src/server/routes/browser/index.ts +3 -0
  188. package/src/server/routes/browser/stream.ts +31 -2
  189. package/src/server/routes/browser/tabs.test.ts +94 -0
  190. package/src/server/routes/browser/tabs.ts +85 -0
  191. package/src/server/routes/index.ts +2 -0
  192. package/src/server/routes/review/bindings.ts +11 -0
  193. package/src/server/routes/review/index.ts +127 -0
  194. package/src/server/routes/review/routes.test.ts +191 -0
  195. package/src/server/routes/settings/agents.test.ts +180 -0
  196. package/src/server/routes/settings/agents.ts +95 -102
  197. package/src/server/routes/settings/mcp.test.ts +135 -0
  198. package/src/server/routes/settings/mcp.ts +14 -6
  199. package/src/server/routes/settings/settings-store-routes.test.ts +6 -113
  200. package/src/server/routes/telemetry/tokens.test.ts +145 -0
  201. package/src/server/routes/telemetry/tokens.ts +70 -149
  202. package/src/server/routes/terminal/ws.ts +6 -5
  203. package/src/server/routes/updates/index.ts +2 -0
  204. package/src/server/routes/updates/notes.ts +34 -0
  205. package/src/server/routes/updates/routes.test.ts +49 -0
  206. package/src/shared/lib/browser/annotate.test.ts +283 -0
  207. package/src/shared/lib/browser/annotate.ts +231 -0
  208. package/src/shared/lib/browser/browser-viewer.test.ts +26 -4
  209. package/src/shared/lib/browser/frame-gate.test.ts +91 -0
  210. package/src/shared/lib/browser/frame-gate.ts +69 -0
  211. package/src/shared/lib/browser/frame-params.test.ts +43 -0
  212. package/src/shared/lib/browser/frame-params.ts +60 -0
  213. package/src/shared/lib/browser/frame-pipeline.test.ts +132 -0
  214. package/src/shared/lib/browser/frame-pipeline.ts +80 -0
  215. package/src/shared/lib/browser/page-context.ts +60 -4
  216. package/src/shared/lib/browser/snapshot.test.ts +115 -0
  217. package/src/shared/lib/browser/snapshot.ts +112 -0
  218. package/src/shared/lib/browser/tab-close.test.ts +74 -0
  219. package/src/shared/lib/browser/tab-close.ts +77 -0
  220. package/src/shared/lib/browser/viewer.ts +45 -26
  221. package/src/shared/lib/chat/timeline/block-chrome.ts +19 -0
  222. package/src/shared/lib/chat/timeline/tool-render-mode.ts +17 -4
  223. package/src/shared/lib/chat/tool/artifact.ts +55 -20
  224. package/src/shared/lib/chat/tool/bash-facts.ts +96 -0
  225. package/src/shared/lib/chat/tool/minimized.test.ts +98 -0
  226. package/src/shared/lib/chat/tool/minimized.ts +64 -0
  227. package/src/shared/lib/chat/tool/summary.test.ts +28 -8
  228. package/src/shared/lib/chat/tool/summary.ts +3 -32
  229. package/src/shared/lib/markdown/blocks/anchor.ts +63 -0
  230. package/src/shared/lib/markdown/blocks/blocks.test.ts +141 -0
  231. package/src/shared/lib/markdown/blocks/renderer.ts +120 -0
  232. package/src/shared/lib/markdown/blocks/scan.ts +100 -0
  233. package/src/shared/lib/markdown/blocks/types.ts +62 -0
  234. package/src/shared/lib/markdown/marked.ts +58 -147
  235. package/src/shared/lib/markdown/math-extensions.ts +168 -0
  236. package/src/shared/lib/markdown/review/prompt.ts +77 -0
  237. package/src/shared/lib/markdown/review/reconcile.ts +55 -0
  238. package/src/shared/lib/markdown/review/review.test.ts +96 -0
  239. package/src/shared/lib/markdown/xml-sections.test.ts +140 -0
  240. package/src/shared/lib/markdown/xml-sections.ts +139 -0
  241. package/src/shared/lib/models/provider/label.ts +57 -0
  242. package/src/shared/lib/omp/config/agent-file.test.ts +54 -0
  243. package/src/shared/lib/omp/config/agent-file.ts +43 -0
  244. package/src/shared/lib/omp/config/row-value.test.ts +95 -0
  245. package/src/shared/lib/omp/config/row-value.ts +97 -0
  246. package/src/shared/lib/omp/config/schema.test.ts +31 -0
  247. package/src/shared/lib/omp/config/schema.ts +6 -0
  248. package/src/shared/lib/omp/rpc/frame.test.ts +48 -47
  249. package/src/shared/lib/omp/rpc/frame.ts +49 -40
  250. package/src/shared/lib/ui/menu-anchor.test.ts +69 -0
  251. package/src/shared/lib/ui/menu-anchor.ts +89 -0
  252. package/src/shared/lib/usage/breakdown.test.ts +197 -0
  253. package/src/shared/lib/usage/breakdown.ts +241 -0
  254. package/src/shared/lib/usage/range.test.ts +204 -0
  255. package/src/shared/lib/usage/range.ts +240 -0
  256. package/src/shared/lib/usage/view.test.ts +85 -0
  257. package/src/shared/lib/usage/view.ts +74 -0
  258. package/src/shared/types/browser.ts +78 -0
  259. package/src/shared/types/index.ts +1 -0
  260. package/src/shared/types/settings/agent.ts +28 -6
  261. package/src/shared/types/settings/state.ts +4 -3
  262. package/src/shared/types/settings/write.ts +6 -0
  263. package/src/shared/types/tokenUsage.ts +128 -21
  264. package/src/shared/types/updates.ts +20 -0
  265. package/dist/client/static/js/index-3ve31rzx.css +0 -1
  266. package/src/server/lib/omp/session/usage/aggregate-shaping.test.ts +0 -149
  267. package/src/server/lib/omp/session/usage/aggregate.test.ts +0 -243
  268. package/src/server/lib/omp/session/usage/aggregate.ts +0 -330
  269. package/src/server/lib/omp/session/usage/shaping.ts +0 -130
@@ -4,12 +4,25 @@
4
4
  */
5
5
 
6
6
  /**
7
- * Bounded protocol-v2 framing for OMP's NDJSON RPC transport.
7
+ * NDJSON framing for OMP's RPC transport, in both directions.
8
8
  *
9
- * Faithful port of omp-web/lib/omp/rpc-frame.ts. Logical RPC frames are
10
- * carried as single JSONL lines when small; frames larger than the transport
11
- * limit are split into `rpc_chunk` sequences (base64 payloads) and
12
- * reassembled on the receiving side.
9
+ * The two directions are NOT symmetric, and treating them as if they were is
10
+ * what silently dropped every prompt carrying a real image:
11
+ *
12
+ * - **omp → Kabmo** frames are bounded at `MAX_RPC_FRAME_BYTES`; under protocol
13
+ * v2 (`negotiate_protocol`) a larger event arrives as an `rpc_chunk`
14
+ * sequence, which `RpcFrameDecoder` reassembles.
15
+ * - **Kabmo → omp** frames must go out as ONE line, however long. omp
16
+ * advertises protocol v2 and acks the negotiation, but its rpc-ui stdin loop
17
+ * has no `rpc_chunk` handler: measured against omp 18.14.0 and 18.16.0, every
18
+ * chunk came back `{success:false,error:"Unknown command: rpc_chunk"}` and the
19
+ * prompt was never dispatched — 6 records for a 1.3 MB image, no `agent_start`,
20
+ * no ack, and Kabmo reset the session after `PROMPT_ACK_TIMEOUT_MS`. A single
21
+ * 30 MB line for the same image is accepted and acked in ~26 s, so the limit
22
+ * here is a guard against unbounded writes, not a transport limit.
23
+ *
24
+ * Hence: one encoder (`encodeRpcFrameLine`) that never chunks, and a decoder
25
+ * that still understands chunks.
13
26
  */
14
27
 
15
28
  import { isRecord } from '@/shared/lib/util/guards';
@@ -35,26 +48,15 @@ function isSafeInteger(value: unknown): value is number {
35
48
  }
36
49
 
37
50
  /**
38
- * One encoder for every length check on this path.
51
+ * The byte-length probe for an outbound frame.
39
52
  *
40
- * `encode()` allocates a throwaway array just to read `.byteLength`, and this
41
- * runs once per frame written to the child's stdin — every `message_update`,
42
- * every steer, every tool result. Hoisting it measured 17.2 ms → 8.6 ms per
43
- * 200k checks. A hoisted encoder rather than `Buffer.byteLength` because this
44
- * module is in `src/shared/` and is therefore browser-safe: `Buffer` is not.
53
+ * A hoisted encoder rather than `Buffer.byteLength` because this module is in
54
+ * `src/shared/` and is therefore browser-safe: `Buffer` is not.
45
55
  */
46
56
  const utf8 = new TextEncoder();
47
57
  /** Strict decoder for reassembled chunk payloads — a truncated sequence is an error. */
48
58
  const fatalUtf8 = new TextDecoder('utf-8', { fatal: true });
49
59
 
50
- function utf8ByteLength(value: string): number {
51
- return utf8.encode(value).byteLength;
52
- }
53
-
54
- function lineByteLength(value: string): number {
55
- return utf8ByteLength(value) + 1;
56
- }
57
-
58
60
  /** Strict base64 decode (canonical padding + round-trip equality). */
59
61
  function decodeBase64(value: unknown): Uint8Array {
60
62
  if (
@@ -125,27 +127,34 @@ export class RpcFrameDecoder {
125
127
  }
126
128
  }
127
129
 
128
- /** Physical JSONL records for a logical RPC frame at the selected protocol. */
129
- export function encodeRpcFrames(frame: RpcFrameRecord, protocolVersion: RpcProtocolVersion, chunkId: string): string[] {
130
+ /**
131
+ * Largest logical frame Kabmo will WRITE to an omp child, as one JSONL line.
132
+ *
133
+ * omp reads its command loop line by line, so this is only a guard against an
134
+ * unbounded write (a runaway attachment, a corrupted payload) — not a
135
+ * transport limit. Measured: a 30 MB prompt line is accepted and acked in
136
+ * ~26 s, while the same payload split into `rpc_chunk`s is rejected outright.
137
+ * The ceiling matches the reassembly limit omp advertises for the other
138
+ * direction (`maxReassembledFrameBytes`), so neither side can claim a payload
139
+ * the other refuses.
140
+ */
141
+ export const MAX_OUTBOUND_FRAME_BYTES = MAX_RPC_REASSEMBLED_BYTES;
142
+
143
+ /**
144
+ * One physical JSONL line for a logical RPC frame.
145
+ *
146
+ * NEVER chunked, whatever `negotiate_protocol` answered: omp's rpc-ui stdin
147
+ * loop answers `Unknown command: rpc_chunk` to every chunk record (verified on
148
+ * 18.14.0 and 18.16.0) and the command is then never dispatched — a prompt
149
+ * carrying a >1 MiB image sat unacked until the ack timeout reset the session.
150
+ * The refusal is thrown at the caller instead, so a payload omp would drop is
151
+ * reported rather than silently lost.
152
+ */
153
+ export function encodeRpcFrameLine(frame: RpcFrameRecord): string {
130
154
  const json = JSON.stringify(frame);
131
- // Encode once and keep the bytes: the length check needs them either way, and
132
- // the oversized path below needs them again. Previously this encoded the
133
- // whole frame to measure it, discarded that array, then encoded it a second
134
- // time to slice it.
135
- const bytes = utf8.encode(json);
136
- if (bytes.byteLength + 1 <= MAX_RPC_FRAME_BYTES) return [`${json}\n`];
137
- if (protocolVersion === 1) throw new Error('RPC frame exceeds the v1 transport limit');
138
- if (bytes.byteLength > MAX_RPC_REASSEMBLED_BYTES) throw new Error('RPC frame exceeds the v2 reassembly limit');
139
- const count = Math.ceil(bytes.byteLength / RPC_CHUNK_PAYLOAD_BYTES);
140
- const lines: string[] = [];
141
- for (let index = 0; index < count; index++) {
142
- const chunk = {
143
- type: 'rpc_chunk', chunkId, index, count, byteLength: bytes.byteLength,
144
- data: bytes.subarray(index * RPC_CHUNK_PAYLOAD_BYTES, (index + 1) * RPC_CHUNK_PAYLOAD_BYTES).toBase64(),
145
- };
146
- const line = JSON.stringify(chunk);
147
- if (lineByteLength(line) > MAX_RPC_FRAME_BYTES) throw new Error('RPC chunk exceeds the transport limit');
148
- lines.push(`${line}\n`);
155
+ const bytes = utf8.encode(json).byteLength + 1;
156
+ if (bytes > MAX_OUTBOUND_FRAME_BYTES) {
157
+ throw new Error(`RPC frame of ${bytes} bytes exceeds the ${MAX_OUTBOUND_FRAME_BYTES}-byte outbound limit`);
149
158
  }
150
- return lines;
159
+ return `${json}\n`;
151
160
  }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The menu placement arithmetic, without a layout engine.
8
+ *
9
+ * These are the three outcomes a user can SEE: the panel hangs below the
10
+ * trigger, flips above it near the bottom edge, and clamps inside the window's
11
+ * left/right edges. Each was a real defect before the portal existed — the
12
+ * sidebar's folder menu ran off the bottom of a 460px window, and the phone's
13
+ * server sheet was written `absolute` at 340px, which runs off the right edge of
14
+ * a 390px screen.
15
+ */
16
+
17
+ import { describe, expect, test } from 'bun:test';
18
+ import { placeMenu, type AnchorRect } from '@/shared/lib/ui/menu-anchor';
19
+
20
+ const VIEWPORT = { width: 1200, height: 800 };
21
+
22
+ /** A trailing `⋯` at (x, y): 22px wide, 22px tall. */
23
+ function anchorAt(left: number, top: number): AnchorRect {
24
+ return { left, right: left + 22, top, bottom: top + 22 };
25
+ }
26
+
27
+ describe('placeMenu', () => {
28
+ test('it hangs below the trigger, right edges aligned', () => {
29
+ const placement = placeMenu(anchorAt(200, 100), { width: 176, height: 94 }, VIEWPORT);
30
+ // 4px gap below the trigger, and the menu's right edge on the trigger's.
31
+ expect(placement.top).toBe(126);
32
+ expect(placement.left).toBe(222 - 176);
33
+ });
34
+
35
+ test('it flips above when the space below cannot hold it', () => {
36
+ const placement = placeMenu(anchorAt(200, 740), { width: 176, height: 94 }, VIEWPORT);
37
+ // Above the trigger rather than past the bottom edge.
38
+ expect(placement.top).toBe(740 - 4 - 94);
39
+ expect(placement.top + 94).toBeLessThanOrEqual(VIEWPORT.height);
40
+ });
41
+
42
+ test('a menu taller than the window pins to the margin and becomes scrollable', () => {
43
+ const placement = placeMenu(anchorAt(200, 300), { width: 176, height: 2000 }, VIEWPORT);
44
+ expect(placement.top).toBe(8);
45
+ expect(placement.maxHeight).toBe(VIEWPORT.height - 8 - 8);
46
+ });
47
+
48
+ test('a trailing menu cannot run past the right edge', () => {
49
+ // This trigger's right edge is 32px off the window: aligned to it, the menu
50
+ // is still inside the margin, so the clamp is what a trigger ON the edge
51
+ // exercises.
52
+ const placement = placeMenu(anchorAt(1150, 100), { width: 176, height: 94 }, VIEWPORT);
53
+ expect(placement.left + 176).toBe(1172);
54
+ expect(placement.left + 176).toBeLessThanOrEqual(VIEWPORT.width - 8);
55
+
56
+ const onEdge = placeMenu(anchorAt(1190, 100), { width: 176, height: 94 }, VIEWPORT);
57
+ expect(onEdge.left).toBe(VIEWPORT.width - 176 - 8);
58
+ });
59
+
60
+ test('a start-aligned menu cannot run past the left edge', () => {
61
+ const placement = placeMenu(anchorAt(-40, 100), { width: 176, height: 94 }, VIEWPORT, 'start');
62
+ expect(placement.left).toBe(8);
63
+ });
64
+
65
+ test('start alignment puts the menu’s left edge on the trigger’s', () => {
66
+ const placement = placeMenu(anchorAt(500, 100), { width: 176, height: 94 }, VIEWPORT, 'start');
67
+ expect(placement.left).toBe(500);
68
+ });
69
+ });
@@ -0,0 +1,89 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Where a popover hangs, as arithmetic.
8
+ *
9
+ * A menu that is placed by CSS alone (`absolute right-0 top-full`) cannot see
10
+ * the edge of the window, so it runs off the bottom of a short window and off
11
+ * the right of a narrow one, and it is placed inside whatever stacking context
12
+ * its trigger happens to live in. Both failure modes were measured on this
13
+ * app's own folder menu and server panel (see `common/anchored-menu/`), which
14
+ * is why the geometry below is computed from the VIEWPORT and then applied to
15
+ * a portalled, `fixed` panel.
16
+ *
17
+ * Pure and viewport-injected (no `window` read) so a test can assert the flip
18
+ * and the clamp without a layout engine.
19
+ */
20
+
21
+ /** The trigger's rectangle in viewport coordinates. */
22
+ export interface AnchorRect {
23
+ top: number;
24
+ right: number;
25
+ bottom: number;
26
+ left: number;
27
+ }
28
+
29
+ /**
30
+ * Which edge of the trigger the menu aligns to.
31
+ *
32
+ * `end` hangs the menu's right edge off the trigger's — what a trailing `⋯`
33
+ * expects. `start` puts the menu's left edge at the trigger's.
34
+ */
35
+ export type MenuAlign = 'start' | 'end';
36
+
37
+ export interface MenuPlacement {
38
+ top: number;
39
+ left: number;
40
+ /** The panel must scroll rather than run past the bottom edge. */
41
+ maxHeight: number;
42
+ }
43
+
44
+ /** Room kept between a menu and the window's edges. */
45
+ const MARGIN = 8;
46
+
47
+ /** Room between the trigger and the menu that hangs off it. */
48
+ const GAP = 4;
49
+
50
+ function clamp(value: number, min: number, max: number): number {
51
+ return Math.max(min, Math.min(value, max));
52
+ }
53
+
54
+ /**
55
+ * Place a menu of `size` against `anchor`, inside `viewport`.
56
+ *
57
+ * Below the trigger first, because that is where a menu is expected; above it
58
+ * when the space below cannot hold it and the space above can. When neither
59
+ * fits, it pins to the top margin and `maxHeight` makes the panel scroll — a
60
+ * menu taller than the window is readable, one pushed past the bottom edge is
61
+ * not.
62
+ */
63
+ export function placeMenu(
64
+ anchor: AnchorRect,
65
+ size: { width: number; height: number },
66
+ viewport: { width: number; height: number },
67
+ align: MenuAlign = 'end',
68
+ ): MenuPlacement {
69
+ const below = anchor.bottom + GAP;
70
+ const above = anchor.top - GAP;
71
+
72
+ let top: number;
73
+ if (below + size.height + MARGIN <= viewport.height) top = below;
74
+ else if (above - size.height >= MARGIN) top = above - size.height;
75
+ else top = MARGIN;
76
+
77
+ const widest = Math.max(MARGIN, viewport.width - size.width - MARGIN);
78
+ const left = align === 'end'
79
+ ? clamp(anchor.right - size.width, MARGIN, widest)
80
+ : clamp(anchor.left, MARGIN, widest);
81
+
82
+ return { top, left, maxHeight: Math.max(MARGIN, viewport.height - top - MARGIN) };
83
+ }
84
+
85
+ /** The trigger's rect, as the anchor type above. */
86
+ export function anchorRectOf(element: Element): AnchorRect {
87
+ const rect = element.getBoundingClientRect();
88
+ return { top: rect.top, right: rect.right, bottom: rect.bottom, left: rect.left };
89
+ }
@@ -0,0 +1,197 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Breakdown and chart view models (`breakdown.ts`).
8
+ *
9
+ * These are the rows a user reads, so each case pins a value that would be a
10
+ * bug if it drifted: a model shown under the wrong provider, a share computed
11
+ * against the wrong denominator, a cadence that relabels without re-bucketing,
12
+ * or a per-bucket average divided by the wrong count.
13
+ */
14
+
15
+ import { describe, expect, test } from 'bun:test';
16
+
17
+ import {
18
+ breakdownRows,
19
+ bucketDays,
20
+ chartSeries,
21
+ dayRows,
22
+ providerModelRows,
23
+ } from '@/shared/lib/usage/breakdown';
24
+ import type { UsageDayRow, UsageProviderRow, UsageTotals } from '@/shared/types';
25
+
26
+ const counters = (cost: number, tokens: number, records = 1, cacheRead = 0, input = 0) => ({
27
+ cost, tokens, input, output: tokens - input - cacheRead, cacheRead, cacheWrite: 0,
28
+ reasoning: 0, cacheReadCost: cost * 0.1, records, unpriced: 0,
29
+ });
30
+
31
+ const provider = (id: string, name: string, models: Array<[string, number, number]>): UsageProviderRow => {
32
+ const rows = models.map(([model, cost, tokens]) => ({ model, ...counters(cost, tokens) }));
33
+ return {
34
+ id,
35
+ name,
36
+ models: rows,
37
+ ...rows.reduce(
38
+ (acc, row) => ({
39
+ ...acc,
40
+ cost: acc.cost + row.cost,
41
+ tokens: acc.tokens + row.tokens,
42
+ records: acc.records + row.records,
43
+ }),
44
+ { cost: 0, tokens: 0, records: 0 },
45
+ ),
46
+ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0, cacheReadCost: 0, unpriced: 0,
47
+ } as UsageProviderRow;
48
+ };
49
+
50
+ const totals: UsageTotals = {
51
+ ...counters(20, 1_000_000, 40, 900_000, 50_000),
52
+ unpriced: 4,
53
+ activeDays: 6,
54
+ };
55
+
56
+ const day = (key: string, cost: number, tokens: number, providers: Record<string, { cost: number; tokens: number }>): UsageDayRow => ({
57
+ day: key,
58
+ providers,
59
+ ...counters(cost, tokens),
60
+ });
61
+
62
+ describe('bucketDays', () => {
63
+ const days = [
64
+ day('2026-10-31', 1, 10, { kenari: { cost: 1, tokens: 10 } }),
65
+ day('2026-11-02', 3, 30, { 'kenari-jatis': { cost: 2, tokens: 20 }, kenari: { cost: 1, tokens: 10 } }),
66
+ day('2026-11-03', 4, 40, { 'kenari-jatis': { cost: 4, tokens: 40 } }),
67
+ ];
68
+
69
+ test('a week merges its days and sums each provider separately', () => {
70
+ const buckets = bucketDays(days, 'week');
71
+ // Oct 31 is a Saturday in the week of Oct 26; Nov 2–3 fall in the week of Nov 2.
72
+ expect(buckets.map((bucket) => bucket.label)).toEqual(['Oct 26', 'Nov 2']);
73
+ expect(buckets[1].cost).toBe(7);
74
+ expect(buckets[1].byProvider['kenari-jatis']).toEqual({ cost: 6, tokens: 60 });
75
+ expect(buckets[1].byProvider.kenari).toEqual({ cost: 1, tokens: 10 });
76
+ });
77
+
78
+ test('a month keeps one bucket per month, ordered', () => {
79
+ const buckets = bucketDays(days, 'month');
80
+ expect(buckets.map((bucket) => bucket.label)).toEqual(['Oct', 'Nov']);
81
+ expect(buckets[1].cost).toBe(7);
82
+ });
83
+
84
+ test('the flat series matches the buckets it summarises', () => {
85
+ expect(chartSeries(days, 'day')).toEqual([
86
+ { label: 'Oct 31', cost: 1, tokens: 10 },
87
+ { label: 'Nov 2', cost: 3, tokens: 30 },
88
+ { label: 'Nov 3', cost: 4, tokens: 40 },
89
+ ]);
90
+ });
91
+ });
92
+
93
+ describe('providerModelRows', () => {
94
+ const providers = [
95
+ provider('kenari-jatis', 'Kenari Jatis', [['deepseek-v4-1-flash', 18, 900]]),
96
+ provider('kenari', 'Kenari.id', [['deepseek-v4-1-flash', 1.5, 80], ['minimax-m3', 0.5, 20]]),
97
+ ];
98
+
99
+ test('one model id under two providers is two subtrees, not one row', () => {
100
+ const rows = providerModelRows(providers, 20);
101
+ expect(rows.map((row) => `${row.kind}:${row.label}`)).toEqual([
102
+ 'group:Kenari Jatis',
103
+ 'row:deepseek-v4-1-flash',
104
+ 'group:Kenari.id',
105
+ 'row:deepseek-v4-1-flash',
106
+ 'row:minimax-m3',
107
+ ]);
108
+ // Keys stay unique even where the label repeats.
109
+ expect(new Set(rows.map((row) => row.key)).size).toBe(rows.length);
110
+ });
111
+
112
+ test('model share is of the period, and of its provider', () => {
113
+ const rows = providerModelRows(providers, 20);
114
+ const jatisModel = rows[1];
115
+ expect(jatisModel.sharePercent).toBe(90);
116
+ expect(jatisModel.shareOfParentPercent).toBe(100);
117
+ const kenariSmall = rows[4];
118
+ expect(kenariSmall.sharePercent).toBe(2.5);
119
+ expect(kenariSmall.shareOfParentPercent).toBe(25);
120
+ });
121
+
122
+ test('a row is the period total, with no derived per-day figure', () => {
123
+ const rows = providerModelRows(providers, 20);
124
+ expect(rows[0].cost).toBe(18);
125
+ expect(rows[1].cost).toBe(18);
126
+ expect(rows[1].tokens).toBe(900);
127
+ expect('display' in rows[1]).toBe(false);
128
+ });
129
+
130
+ test('a zero total does not divide by zero', () => {
131
+ const rows = providerModelRows([provider('x', 'X', [['m', 0, 0]])], 0);
132
+ expect(rows.every((row) => row.sharePercent === 0)).toBe(true);
133
+ });
134
+ });
135
+
136
+ describe('dayRows', () => {
137
+ const days = [
138
+ day('2026-11-02', 1, 10, { kenari: { cost: 1, tokens: 10 } }),
139
+ day('2026-11-03', 3, 30, { kenari: { cost: 3, tokens: 30 } }),
140
+ ];
141
+
142
+ test('lists the period oldest first, and a quiet day is still listed', () => {
143
+ // Nov 1 has no records at all; the table must still show it, or the list
144
+ // silently stops matching the period it claims to describe.
145
+ const rows = dayRows(days, 'day', 4, { from: '2026-11-01', to: '2026-11-03' });
146
+ expect(rows.map((row) => row.label)).toEqual(['Nov 1', 'Nov 2', 'Nov 3']);
147
+ expect(rows[0].cost).toBe(0);
148
+ expect(rows[0].sharePercent).toBe(0);
149
+ expect(rows[2].sharePercent).toBe(75);
150
+ });
151
+
152
+ test('a weekly bucket sums the week into one row per week of the period', () => {
153
+ const rows = dayRows(days, 'week', 4, { from: '2026-11-02', to: '2026-11-03' });
154
+ expect(rows).toHaveLength(1);
155
+ expect(rows[0].label).toBe('Nov 2');
156
+ expect(rows[0].cost).toBe(4);
157
+ expect(rows[0].records).toBe(2);
158
+ });
159
+
160
+ test('all time lists every month between its first and last recorded day', () => {
161
+ // A quiet month in the middle of the history must not vanish: the rows
162
+ // have to add up to the totals shown beside them.
163
+ const rows = dayRows(
164
+ [day('2026-06-24', 1, 10, { kenari: { cost: 1, tokens: 10 } }), day('2026-08-02', 2, 20, { kenari: { cost: 2, tokens: 20 } })],
165
+ 'month',
166
+ 3,
167
+ { from: '2026-06-24', to: '2026-08-02' },
168
+ );
169
+ expect(rows.map((row) => row.label)).toEqual(['Jun', 'Jul', 'Aug']);
170
+ expect(rows[1].cost).toBe(0);
171
+ });
172
+
173
+ test('without a window only the days that saw usage are listed', () => {
174
+ // All-time has no bounded window, so the rollup's own days are the list.
175
+ const rows = dayRows(days, 'day', 4, null);
176
+ expect(rows.map((row) => row.label)).toEqual(['Nov 2', 'Nov 3']);
177
+ });
178
+ });
179
+
180
+ describe('breakdownRows', () => {
181
+ const providers = [provider('kenari', 'Kenari.id', [['m', 4, 40]])];
182
+ const payload = {
183
+ totals: { ...totals, cost: 4, tokens: 40, activeDays: 1 },
184
+ providers,
185
+ days: [day('2026-11-03', 4, 40, { kenari: { cost: 4, tokens: 40 } })],
186
+ projects: [],
187
+ };
188
+
189
+ test('provider and model tabs draw the same tree', () => {
190
+ expect(breakdownRows('provider', payload, 'day', null)).toEqual(breakdownRows('model', payload, 'day', null));
191
+ });
192
+
193
+ test('each tab selects its own source', () => {
194
+ expect(breakdownRows('day', payload, 'day', null)[0].label).toBe('Nov 3');
195
+ expect(breakdownRows('project', payload, 'day', null)).toEqual([]);
196
+ });
197
+ });