@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
@@ -0,0 +1,73 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The review surface's HTTP calls, typed.
8
+ *
9
+ * One module because three callers share the contract: the loading hook, the
10
+ * save, and the delete. `root`/`repo` travel on every request — a document in a
11
+ * nested repo is a different document from a same-named path at the workspace
12
+ * root, and the server keys its rows by the resolved pair.
13
+ *
14
+ * A refusal is REPORTED, never swallowed: a save that silently failed would
15
+ * leave the reader believing a judgement is stored when it is not, which is the
16
+ * one failure this feature cannot tolerate.
17
+ */
18
+
19
+ import type { AnnotationDraft, BlockVerdict, DocumentAnnotation, ReviewTarget } from '@/shared/lib/markdown/blocks/types';
20
+
21
+ /** The body a save sends, minus the scope the server resolves from root/repo. */
22
+ export interface SaveAnnotationBody {
23
+ path: string;
24
+ root?: string | null;
25
+ repo?: string | null;
26
+ blockKey: string;
27
+ lineStart: number;
28
+ lineEnd: number;
29
+ verdict: BlockVerdict;
30
+ note: string;
31
+ quote: string;
32
+ }
33
+
34
+ function scopeParams(target: ReviewTarget): URLSearchParams {
35
+ const params = new URLSearchParams({ path: target.path });
36
+ if (target.root) params.set('root', target.root);
37
+ if (target.repo && target.repo !== '.') params.set('repo', target.repo);
38
+ return params;
39
+ }
40
+
41
+ /** The refusal text a failed request carries, or a status-shaped fallback. */
42
+ async function refusal(response: Response): Promise<string> {
43
+ const payload = (await response.json().catch(() => null)) as { error?: unknown } | null;
44
+ return typeof payload?.error === 'string' ? payload.error : `Request failed (${response.status})`;
45
+ }
46
+
47
+ /** Every judgement stored for one document. */
48
+ export async function fetchAnnotations(target: ReviewTarget, signal?: AbortSignal): Promise<DocumentAnnotation[]> {
49
+ const response = await fetch(`/api/review?${scopeParams(target).toString()}`, { signal });
50
+ if (!response.ok) throw new Error(await refusal(response));
51
+ const payload = (await response.json()) as { annotations?: DocumentAnnotation[] };
52
+ return Array.isArray(payload.annotations) ? payload.annotations : [];
53
+ }
54
+
55
+ /** Store one judgement, answering the row as the server stored it. */
56
+ export async function saveAnnotation(target: ReviewTarget, draft: Omit<AnnotationDraft, 'scope' | 'path'>): Promise<DocumentAnnotation> {
57
+ const body: SaveAnnotationBody = { ...draft, path: target.path, root: target.root, repo: target.repo };
58
+ const response = await fetch('/api/review', {
59
+ method: 'POST',
60
+ headers: { 'Content-Type': 'application/json' },
61
+ body: JSON.stringify(body),
62
+ });
63
+ if (!response.ok) throw new Error(await refusal(response));
64
+ const payload = (await response.json()) as { annotation?: DocumentAnnotation };
65
+ if (!payload.annotation) throw new Error('The server answered without the saved annotation');
66
+ return payload.annotation;
67
+ }
68
+
69
+ /** Remove one judgement. A missing row is an error, not a silent success. */
70
+ export async function removeAnnotation(id: string): Promise<void> {
71
+ const response = await fetch(`/api/review?id=${encodeURIComponent(id)}`, { method: 'DELETE' });
72
+ if (!response.ok) throw new Error(await refusal(response));
73
+ }
@@ -23,29 +23,54 @@ type SetParams = (next: SetParamsInit | SetParamsFn, options?: { replace?: boole
23
23
  export type SetSearchParams = SetParams;
24
24
 
25
25
  const listeners = new Set<() => void>();
26
- let currentSearch = typeof window === 'undefined' ? '' : window.location.search;
27
26
 
28
27
  function emit(): void {
29
28
  for (const listener of listeners) listener();
30
29
  }
31
30
 
32
- function subscribe(listener: () => void): () => void {
33
- listeners.add(listener);
34
- return () => listeners.delete(listener);
31
+ /**
32
+ * The search string of the window in scope RIGHT NOW, never a value cached when
33
+ * this module was first evaluated.
34
+ *
35
+ * A module-level `currentSearch` reads as a harmless cache and is not: it pins
36
+ * the store to whichever `window` existed at import time, and so does the
37
+ * `popstate` listener below. In the browser there is one window forever and the
38
+ * two are equivalent; under `bun test` every DOM suite installs its OWN window,
39
+ * so the pinned pair made the router answer a URL nobody can see and miss
40
+ * `popstate` on the window the suite is actually driving — measured: a suite
41
+ * that set `?sessionId=` and mounted the composer read `''` and drew the
42
+ * landing, failing a case that passes when its file runs alone.
43
+ */
44
+ function liveSearch(): string {
45
+ return typeof window === 'undefined' ? '' : window.location.search;
35
46
  }
36
47
 
37
- /** Re-read `location.search` and notify only when it actually changed. */
38
- function syncFromLocation(): void {
39
- const next = typeof window === 'undefined' ? '' : window.location.search;
40
- if (next === currentSearch) return;
41
- currentSearch = next;
48
+ /**
49
+ * The window this store is currently listening on.
50
+ *
51
+ * Rebound on subscribe rather than once at module load, for the reason above:
52
+ * a suite that replaces `globalThis.window` must get a router that follows it.
53
+ */
54
+ let boundWindow: Window | undefined;
55
+
56
+ function onPopState(): void {
42
57
  emit();
43
58
  }
44
59
 
45
- if (typeof window !== 'undefined') {
60
+ function bindToCurrentWindow(): void {
61
+ const next = typeof window === 'undefined' ? undefined : window;
62
+ if (next === boundWindow) return;
63
+ boundWindow?.removeEventListener('popstate', onPopState);
64
+ boundWindow = next;
46
65
  // Back/forward navigation. `pushState`/`replaceState` do NOT fire popstate,
47
66
  // so setParams notifies directly.
48
- window.addEventListener('popstate', syncFromLocation);
67
+ next?.addEventListener('popstate', onPopState);
68
+ }
69
+
70
+ function subscribe(listener: () => void): () => void {
71
+ listeners.add(listener);
72
+ bindToCurrentWindow();
73
+ return () => listeners.delete(listener);
49
74
  }
50
75
 
51
76
  function toSearchString(init: SetParamsInit): string {
@@ -63,22 +88,19 @@ function resolveNext(next: SetParamsInit | SetParamsFn, current: URLSearchParams
63
88
  return toSearchString(next);
64
89
  }
65
90
 
66
- function getSnapshot(): string {
67
- return currentSearch;
68
- }
69
-
70
91
  export function useSearchParams(): [URLSearchParams, SetParams] {
71
92
  // Preact's `useSyncExternalStore` takes only (subscribe, getSnapshot) — no
72
- // server-snapshot argument — and the app is client-rendered, so `currentSearch`
73
- // is the single source of truth.
74
- const search = useSyncExternalStore(subscribe, getSnapshot);
93
+ // server-snapshot argument — and the app is client-rendered, so the live
94
+ // `location.search` is the single source of truth. It is read on demand, and
95
+ // `useSyncExternalStore` compares snapshots by value, so an unchanged URL
96
+ // costs one string comparison and no render.
97
+ const search = useSyncExternalStore(subscribe, liveSearch);
75
98
 
76
99
  const setParams = useCallback<SetParams>((next, options) => {
77
- const searchString = resolveNext(next, new URLSearchParams(currentSearch));
100
+ const searchString = resolveNext(next, new URLSearchParams(liveSearch()));
78
101
  const url = `${window.location.pathname}${searchString}${window.location.hash}`;
79
102
  if (options?.replace) window.history.replaceState(null, '', url);
80
103
  else window.history.pushState(null, '', url);
81
- currentSearch = searchString;
82
104
  emit();
83
105
  }, []);
84
106
 
@@ -852,3 +852,68 @@ html[data-theme-variant="dark"] .shiki span { color: var(--shiki-dark); }
852
852
  transform: translateX(33%);
853
853
  }
854
854
  }
855
+
856
+ /* ---------------------------------------------------------------------------
857
+ * Review mode on a rendered markdown document.
858
+ *
859
+ * The verdict lives on `data-md-verdict` on the block element, painted by the
860
+ * renderer after the annotations land. Two rules make it legible without
861
+ * spending the palette:
862
+ *
863
+ * - a LEFT RAIL is the mark. It is the only thing that survives a reflow —
864
+ * a background tint over a 3-line paragraph and over a 40-line code block
865
+ * read as unrelated states.
866
+ * - `needs-work` is the one state that uses chroma (`--theme-error`), because
867
+ * it is the one state the reader must not miss. Chroma stays reserved for it.
868
+ *
869
+ * `data-md-selected` is the block whose popover is open: it gets an outline, not
870
+ * a colour, so it composes with either verdict.
871
+ * ------------------------------------------------------------------------- */
872
+
873
+ .md-review-active .prose-content [data-md-block] {
874
+ position: relative;
875
+ cursor: pointer;
876
+ border-radius: 0.25rem;
877
+ }
878
+
879
+ /* The hover affordance exists only where a review is possible, and only for a
880
+ * block that has not been judged yet — a judged block already says so. */
881
+ .md-review-active .prose-content [data-md-block]:hover:not([data-md-verdict]) {
882
+ background: color-mix(in srgb, var(--theme-ink) 4%, transparent);
883
+ }
884
+
885
+ .md-review-active .prose-content [data-md-verdict]::before {
886
+ content: '';
887
+ position: absolute;
888
+ inset-block: 0;
889
+ left: -0.6rem;
890
+ width: 3px;
891
+ border-radius: 2px;
892
+ background: color-mix(in srgb, var(--theme-ink) 35%, transparent);
893
+ }
894
+
895
+ .md-review-active .prose-content [data-md-verdict='needs-work']::before {
896
+ background: var(--theme-error);
897
+ }
898
+
899
+ /* A judged block keeps a faint tint so the marks read as a set when scrolled
900
+ * past quickly; `needs-work` is the only one allowed to be a colour. */
901
+ .md-review-active .prose-content [data-md-verdict='good'] {
902
+ background: color-mix(in srgb, var(--theme-ink) 3%, transparent);
903
+ }
904
+
905
+ .md-review-active .prose-content [data-md-verdict='needs-work'] {
906
+ background: color-mix(in srgb, var(--theme-error) 8%, transparent);
907
+ }
908
+
909
+ .md-review-active .prose-content [data-md-selected] {
910
+ outline: 1px solid color-mix(in srgb, var(--theme-ink) 40%, transparent);
911
+ outline-offset: 2px;
912
+ }
913
+
914
+ /* Review mode is a reading mode: a link inside a block is part of what is being
915
+ * judged, and following it would leave the block. The handler consumes the
916
+ * click; this only says so. */
917
+ .md-review-active .prose-content [data-md-block] a {
918
+ cursor: pointer;
919
+ }
@@ -15,7 +15,7 @@
15
15
  */
16
16
 
17
17
  import type { RpcProcess, RpcFrame } from '@/server/lib/omp/rpc/process';
18
- import { GET_STATE_TIMEOUT_MS, IDLE_REAP_MS, PROMPT_ACK_TIMEOUT_MS } from '@/server/lib/omp/rpc/constants';
18
+ import { GET_STATE_TIMEOUT_MS, IDLE_REAP_MS, promptAckTimeoutMs } from '@/server/lib/omp/rpc/constants';
19
19
  import { buildBtwPrompt } from '@/server/lib/btw/prompt';
20
20
  import { boundSideReply } from '@/server/lib/btw/reply';
21
21
  import { appendBtwTurn, settleRunningBtwTurns, updateBtwTurn } from '@/server/lib/btw/store.server';
@@ -63,7 +63,7 @@ export async function askSideQuestion(host: BtwLifecycleHost, question: string,
63
63
  const proc = await host.start();
64
64
  await proc.sendCommand(
65
65
  { type: 'prompt', message: buildBtwPrompt(question), ...(images?.length ? { images } : {}) },
66
- PROMPT_ACK_TIMEOUT_MS,
66
+ promptAckTimeoutMs(images),
67
67
  );
68
68
  } catch (error) {
69
69
  await settleSideTurn(host, 'error');
@@ -19,7 +19,9 @@ import { ensureWaitingSchema } from '@/server/lib/waiting/schema.server';
19
19
  import { ensurePluginSchema } from '@/server/lib/plugins/schema.server';
20
20
  import { ensureModelRolePresetSchema } from '@/server/lib/model-roles/schema.server';
21
21
  import { ensureProviderIconSchema } from '@/server/lib/models/provider-icon-store.server';
22
+ import { ensureUsageIndexSchema } from '@/server/lib/usage/index-schema.server';
22
23
  import { ensureWorktreeSchema } from '@/server/lib/db/worktree-registry.server';
24
+ import { ensureReviewSchema } from '@/server/lib/review/schema.server';
23
25
  import { migrateWorkspaceFolderColumns } from '@/shared/lib/workspace/schema-migrations';
24
26
  import { migrateSessionStreamStateColumns } from '@/shared/lib/omp/session/schema-migrations';
25
27
 
@@ -126,9 +128,14 @@ export async function initSchema(db: DbClient): Promise<void> {
126
128
  // Named model-role presets (the role editor's preset picker).
127
129
  await ensureModelRolePresetSchema(db);
128
130
  await ensureProviderIconSchema(db);
131
+ // Token-usage index: the rollup the telemetry panel reads instead of
132
+ // re-scanning every transcript on each request.
133
+ await ensureUsageIndexSchema(db);
129
134
  // Worktree registry: the ref each worktree branched from, and the identity
130
135
  // cache that keys its folder.
131
136
  await ensureWorktreeSchema(db);
137
+ // Review annotations on a rendered markdown document (per block, per file).
138
+ await ensureReviewSchema(db);
132
139
 
133
140
  await db.exec(`
134
141
  CREATE TABLE IF NOT EXISTS files (
@@ -39,6 +39,7 @@ import {
39
39
  type TerminalSession,
40
40
  type TerminalViewer,
41
41
  } from '@/server/lib/terminal/session.server';
42
+ import { createTerminalOutputQueue } from '@/server/lib/terminal/output';
42
43
  import { clampTerminalSize } from '@/shared/lib/workspace/terminal/protocol';
43
44
  import { testPosix } from '@/test-support/platform';
44
45
  describe('clampTerminalSize and session constants', () => {
@@ -213,6 +214,9 @@ function fakeSession(
213
214
  term: undefined as unknown as Bun.Terminal,
214
215
  proc: null,
215
216
  history: undefined as never,
217
+ // A real queue: `closeTerminalStream` disposes it, which is one of the
218
+ // behaviours this file pins.
219
+ output: createTerminalOutputQueue(() => {}),
216
220
  viewers: new Set(viewers),
217
221
  cols: 80,
218
222
  rows: 24,
@@ -0,0 +1,273 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Native agent definitions: discovery, and the writer that edits omp's own
8
+ * markdown files in place.
9
+ *
10
+ * The field set here is omp's contract, measured against the installed
11
+ * `@oh-my-pi/pi-coding-agent` 18.16.0 (`discovery/helpers.ts`
12
+ * `parseAgentFields`): `name`, `description`, `tools`, `spawns`, `model`,
13
+ * `thinkingLevel`, and the body as the system prompt. Two failures are pinned:
14
+ *
15
+ * - **A key omp ignores must not be offered or written.** `mode`,
16
+ * `temperature` and `top_p` are none of omp's business; a pane editing them
17
+ * changed a file to no effect.
18
+ * - **A write must not delete what it does not own.** A shipped agent's
19
+ * block-list `tools:`, its `spawns:` and its nested `output:` schema have to
20
+ * survive an edit to the prompt or the model.
21
+ */
22
+
23
+ import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
24
+ import fs from 'node:fs';
25
+ import { tmpdir } from 'node:os';
26
+ import { join } from 'node:path';
27
+
28
+ import { deleteAgentDefinition, discoverNativeAgents, writeAgentDefinition } from '@/server/lib/omp/config/agents';
29
+
30
+ let root = '';
31
+ let agentDir = '';
32
+ let userAgents = '';
33
+ let projectAgents = '';
34
+ let prevAgentDir: string | undefined;
35
+
36
+ /** Write a fixture file, creating its parent directory. */
37
+ function write(file: string, content: string): string {
38
+ fs.mkdirSync(join(file, '..'), { recursive: true });
39
+ fs.writeFileSync(file, content);
40
+ return file;
41
+ }
42
+
43
+ beforeAll(() => {
44
+ root = fs.mkdtempSync(join(tmpdir(), 'kabmo-agent-definitions-'));
45
+ agentDir = join(root, 'agent');
46
+ userAgents = join(agentDir, 'agents');
47
+ projectAgents = join(root, 'project-agents');
48
+ fs.mkdirSync(userAgents, { recursive: true });
49
+ fs.mkdirSync(projectAgents, { recursive: true });
50
+ prevAgentDir = Bun.env.PI_CODING_AGENT_DIR;
51
+ Bun.env.PI_CODING_AGENT_DIR = agentDir;
52
+ });
53
+
54
+ beforeEach(() => {
55
+ for (const dir of [userAgents, projectAgents]) {
56
+ for (const entry of fs.readdirSync(dir)) fs.rmSync(join(dir, entry), { recursive: true, force: true });
57
+ }
58
+ Bun.env.PI_CODING_AGENT_DIR = agentDir;
59
+ });
60
+
61
+ afterAll(() => {
62
+ if (prevAgentDir === undefined) delete Bun.env.PI_CODING_AGENT_DIR;
63
+ else Bun.env.PI_CODING_AGENT_DIR = prevAgentDir;
64
+ fs.rmSync(root, { recursive: true, force: true });
65
+ });
66
+
67
+ describe('discoverNativeAgents', () => {
68
+ /**
69
+ * Only the keys omp actually parses are surfaced. `mode` and `temperature`
70
+ * are NOT among them (measured against 18.16.0 `parseAgentFields`), so a
71
+ * panel that offered them was editing a file omp ignores.
72
+ */
73
+ test('shapes the frontmatter keys omp parses and skips non-markdown entries', async () => {
74
+ write(join(userAgents, 'one.md'), [
75
+ '---',
76
+ 'name: First',
77
+ 'description: "a description"',
78
+ 'model: kenari/deepseek-v4-flash',
79
+ 'thinking: high',
80
+ 'temperature: 0.5',
81
+ 'spawns: "*"',
82
+ '---',
83
+ '',
84
+ ' system prompt ',
85
+ '',
86
+ ].join('\n'));
87
+ write(join(userAgents, 'two.md'), 'no frontmatter body\n');
88
+ write(join(userAgents, 'ignored.txt'), 'x');
89
+ fs.mkdirSync(join(userAgents, 'nested.md'), { recursive: true });
90
+
91
+ const found = await discoverNativeAgents();
92
+ expect(found.map((agent) => agent.id).sort()).toEqual(['omp-user-one', 'omp-user-two']);
93
+ // By id, never by index: `readdir` order is not guaranteed (Windows returned `two` first).
94
+ const byId = new Map(found.map((agent) => [agent.id, agent]));
95
+ expect(byId.get('omp-user-one')).toMatchObject({
96
+ name: 'First',
97
+ description: 'a description',
98
+ model: 'kenari/deepseek-v4-flash',
99
+ thinkingLevel: 'high',
100
+ spawns: '*',
101
+ systemPrompt: 'system prompt',
102
+ sourceRoot: 'user',
103
+ filePath: join(userAgents, 'one.md'),
104
+ });
105
+ // `temperature` is not an agent key omp reads, so it is not carried.
106
+ expect(byId.get('omp-user-one')).not.toHaveProperty('temperature');
107
+ expect(byId.get('omp-user-two')).toMatchObject({
108
+ name: 'two', description: '', systemPrompt: 'no frontmatter body',
109
+ });
110
+ });
111
+
112
+ test('a model written as a block list is read, not missed', async () => {
113
+ // omp writes `model:` as a YAML sequence (its own shipped agents do), which
114
+ // a scalar-only frontmatter parser reads as an empty value.
115
+ write(join(userAgents, 'block.md'), '---\nname: Block\nmodel:\n - "@smol"\nthinkingLevel: medium\n---\nbody\n');
116
+ const agent = (await discoverNativeAgents()).find((item) => item.id === 'omp-user-block');
117
+ expect(agent).toMatchObject({ model: '@smol', thinkingLevel: 'medium' });
118
+ });
119
+
120
+ test('a user agent wins over a project agent with the same base name', async () => {
121
+ write(join(userAgents, 'shared.md'), '---\nname: FromUser\n---\nuser body\n');
122
+ write(join(projectAgents, 'shared.md'), '---\nname: FromProject\n---\nproject body\n');
123
+ write(join(projectAgents, 'project-only.md'), '---\nname: OnlyProject\n---\nbody\n');
124
+
125
+ const found = await discoverNativeAgents(projectAgents);
126
+ expect(found.find((agent) => agent.filePath === join(userAgents, 'shared.md'))?.name).toBe('FromUser');
127
+ expect(found.some((agent) => agent.filePath === join(projectAgents, 'shared.md'))).toBe(false);
128
+ expect(found.find((agent) => agent.id === 'omp-project-project-only')?.sourceRoot).toBe('project');
129
+ });
130
+
131
+ test('an oversized definition is skipped and a missing directory is not an error', async () => {
132
+ write(join(userAgents, 'huge.md'), `---\nname: Huge\n---\n${'x'.repeat(512 * 1024 + 1)}\n`);
133
+ const found = await discoverNativeAgents();
134
+ expect(found.some((agent) => agent.name === 'Huge')).toBe(false);
135
+ expect(await discoverNativeAgents(join(root, 'no-such-dir'))).toEqual(found);
136
+ });
137
+ });
138
+
139
+ describe('writeAgentDefinition', () => {
140
+ test('refuses an unsafe file name and an empty system prompt', async () => {
141
+ await expect(writeAgentDefinition({ fileName: '../escape', name: 'X', description: '', systemPrompt: 'x' }))
142
+ .rejects.toThrow(/may contain letters/);
143
+ await expect(writeAgentDefinition({ fileName: 'ok', name: 'X', description: '', systemPrompt: ' ' }))
144
+ .rejects.toThrow(/cannot be empty/);
145
+ expect(fs.existsSync(join(userAgents, 'ok.md'))).toBe(false);
146
+ });
147
+
148
+ test('writes the keys omp reads, quoting scalars, then deletes on request', async () => {
149
+ const { path } = await writeAgentDefinition({
150
+ fileName: 'written',
151
+ name: 'Written Agent',
152
+ description: 'has "quotes" and \\ slashes',
153
+ model: 'kenari/deepseek-v4-flash',
154
+ thinkingLevel: 'low',
155
+ spawns: '*',
156
+ tools: ['read', 'bash'],
157
+ systemPrompt: 'do the thing',
158
+ });
159
+ expect(path).toBe(join(userAgents, 'written.md'));
160
+ const text = fs.readFileSync(path, 'utf8');
161
+ expect(text).toContain('name: "Written Agent"');
162
+ expect(text).toContain('model: "kenari/deepseek-v4-flash"');
163
+ expect(text).toContain('thinkingLevel: low');
164
+ expect(text).toContain('spawns: "*"');
165
+ expect(text).toContain('tools: read, bash');
166
+ expect(text).toContain('has \\"quotes\\" and \\\\ slashes');
167
+ // Keys omp ignores are never written: they would be dead config.
168
+ expect(text).not.toContain('mode:');
169
+ expect(text).not.toContain('temperature');
170
+ expect(text).not.toContain('top_p');
171
+ expect(text.endsWith('\n')).toBe(true);
172
+
173
+ expect(await deleteAgentDefinition('written')).toBe(true);
174
+ expect(await deleteAgentDefinition('written')).toBe(false);
175
+ await expect(deleteAgentDefinition('bad/name')).rejects.toThrow(/Invalid agent file name/);
176
+ });
177
+
178
+ test('editing a shipped definition keeps the keys the panel does not own', async () => {
179
+ // A real omp agent file: a tools block list, an `output:` schema, and a key
180
+ // order the panel has no business rewriting.
181
+ write(join(userAgents, 'shipped.md'), [
182
+ '---',
183
+ 'name: shipped',
184
+ 'description: "Ship it"',
185
+ 'tools:',
186
+ ' - read',
187
+ ' - grep',
188
+ 'model:',
189
+ ' - "@smol"',
190
+ 'thinkingLevel: medium',
191
+ 'output:',
192
+ ' properties:',
193
+ ' summary:',
194
+ ' type: string',
195
+ '---',
196
+ '',
197
+ 'old prompt',
198
+ '',
199
+ ].join('\n'));
200
+
201
+ await writeAgentDefinition({
202
+ fileName: 'shipped',
203
+ name: 'shipped',
204
+ description: 'Ship it',
205
+ model: 'kenari/deepseek-v4-flash',
206
+ thinkingLevel: 'high',
207
+ systemPrompt: 'new prompt',
208
+ });
209
+
210
+ const text = fs.readFileSync(join(userAgents, 'shipped.md'), 'utf8');
211
+ // Preserved verbatim: the panel never touched them.
212
+ expect(text).toContain('tools:\n - read\n - grep\n');
213
+ expect(text).toContain('output:\n properties:\n summary:\n type: string\n');
214
+ // Replaced where it stood, so a stale `model:` block list cannot survive.
215
+ expect(text).toContain('model: "kenari/deepseek-v4-flash"');
216
+ expect(text).toContain('thinkingLevel: high');
217
+ expect(text).not.toContain('"@smol"');
218
+ expect(text).toContain('new prompt');
219
+ expect(text).not.toContain('old prompt');
220
+ // One name and one description, never a duplicate appended below.
221
+ expect(text.match(/^name:/gm)).toHaveLength(1);
222
+ expect(text.match(/^description:/gm)).toHaveLength(1);
223
+ });
224
+
225
+ test('an untouched tools field leaves the block list exactly as it was', async () => {
226
+ // The pane's tools box is a CSV view of a YAML list. Re-sending the same
227
+ // names as CSV rewrote four lines into one, which is a silent reformat of a
228
+ // file the user never edited.
229
+ const original = [
230
+ '---',
231
+ 'name: keep',
232
+ 'description: "Keep the list"',
233
+ 'tools:',
234
+ ' - read',
235
+ ' - grep',
236
+ '---',
237
+ '',
238
+ 'body',
239
+ '',
240
+ ].join('\n');
241
+ write(join(userAgents, 'keep.md'), original);
242
+
243
+ await writeAgentDefinition({
244
+ fileName: 'keep',
245
+ name: 'keep',
246
+ description: 'Keep the list',
247
+ systemPrompt: 'new body',
248
+ });
249
+
250
+ const text = fs.readFileSync(join(userAgents, 'keep.md'), 'utf8');
251
+ expect(text).toContain('tools:\n - read\n - grep\n');
252
+ expect(text).toContain('new body');
253
+ });
254
+
255
+ test('clearing the model removes the key so omp falls back to the role default', async () => {
256
+ await writeAgentDefinition({
257
+ fileName: 'clear',
258
+ name: 'clear',
259
+ description: '',
260
+ model: 'kenari/deepseek-v4-flash',
261
+ systemPrompt: 'body',
262
+ });
263
+ await writeAgentDefinition({
264
+ fileName: 'clear',
265
+ name: 'clear',
266
+ description: '',
267
+ model: '',
268
+ systemPrompt: 'body',
269
+ });
270
+ const text = fs.readFileSync(join(userAgents, 'clear.md'), 'utf8');
271
+ expect(text).not.toContain('model:');
272
+ });
273
+ });