@kabmo-labs/kabmo 0.23.0 → 0.25.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 (325) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +805 -736
  3. package/dist/client/static/js/index-bc9aa4mx.css +1 -0
  4. package/dist/client/static/js/{index-ph0q59rs.js → index-ga8cbpt4.js} +1071 -1171
  5. package/package.json +2 -4
  6. package/src/cli/lib/args.js +24 -1
  7. package/src/cli/lib/args.test.js +16 -0
  8. package/src/cli/lib/commands/session.js +233 -0
  9. package/src/cli/lib/commands/session.test.js +103 -0
  10. package/src/cli/main.js +1 -1
  11. package/src/client/components/common/ComposerPicker.tsx +3 -0
  12. package/src/client/components/common/Modal.tsx +2 -6
  13. package/src/client/components/common/code-surface/shiki.test.ts +82 -0
  14. package/src/client/components/common/code-surface/shiki.ts +28 -7
  15. package/src/client/components/common/session-actions-menu/NewChildSessionDialog.tsx +113 -0
  16. package/src/client/components/common/session-actions-menu/index.tsx +33 -2
  17. package/src/client/components/common/session-row/StatusSlot.tsx +4 -4
  18. package/src/client/components/common/session-row/index.tsx +27 -1
  19. package/src/client/components/layout/desktop-layout/WorkspacePanels.tsx +7 -1
  20. package/src/client/components/layout/desktop-layout/resizer/separator-drag.ts +3 -3
  21. package/src/client/components/layout/session-sidebar/CategoryItem.tsx +25 -12
  22. package/src/client/components/layout/session-sidebar/ChildSessionList.tsx +66 -0
  23. package/src/client/components/layout/session-sidebar/SessionItem.tsx +28 -3
  24. package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.test.tsx +20 -0
  25. package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.tsx +59 -12
  26. package/src/client/components/layout/session-sidebar/about-modal/HarnessTableLog.test.tsx +94 -0
  27. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.test.tsx +130 -0
  28. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.tsx +120 -0
  29. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogLine.tsx +47 -0
  30. package/src/client/components/layout/session-sidebar/about-modal/index.test.tsx +122 -0
  31. package/src/client/components/layout/session-sidebar/about-modal/index.tsx +55 -46
  32. package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +18 -5
  33. package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +21 -4
  34. package/src/client/components/mobile/mobile-session-sidebar/SessionRow.tsx +27 -5
  35. package/src/client/components/settings/categories/harness-settings/EnvProviderForm.tsx +31 -0
  36. package/src/client/components/settings/categories/harness-settings/provider-panel.test.tsx +49 -0
  37. package/src/client/components/workspace/chat-timeline/ChatOverlays.tsx +5 -2
  38. package/src/client/components/workspace/chat-timeline/ComposerDock.tsx +64 -70
  39. package/src/client/components/workspace/chat-timeline/ComposerDockFrame.tsx +35 -0
  40. package/src/client/components/workspace/chat-timeline/EmptyWorkspacePrompt.tsx +135 -118
  41. package/src/client/components/workspace/chat-timeline/MessageItem.tsx +22 -1
  42. package/src/client/components/workspace/chat-timeline/MessageList.test.ts +14 -0
  43. package/src/client/components/workspace/chat-timeline/MessageList.tsx +4 -0
  44. package/src/client/components/workspace/chat-timeline/TimelineBody.tsx +3 -0
  45. package/src/client/components/workspace/chat-timeline/chat-input/index.tsx +4 -3
  46. package/src/client/components/workspace/chat-timeline/composer-dock-frame.test.tsx +155 -0
  47. package/src/client/components/workspace/chat-timeline/index.tsx +5 -2
  48. package/src/client/components/workspace/chat-timeline/pending-harness.test.tsx +1 -1
  49. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/FrameControl.tsx +11 -20
  50. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/GroupedAsk.tsx +1 -1
  51. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/QuestionBlock.tsx +1 -1
  52. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/drafts.ts +1 -1
  53. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/index.tsx +2 -1
  54. package/src/client/components/workspace/file-explorer/index.test.ts +25 -0
  55. package/src/client/components/workspace/file-explorer/index.tsx +9 -3
  56. package/src/client/components/workspace/model-dropdown/harness-models.test.ts +17 -0
  57. package/src/client/components/workspace/model-dropdown/harness-models.ts +33 -18
  58. package/src/client/components/workspace/model-dropdown/index.tsx +3 -3
  59. package/src/client/components/workspace/model-dropdown/popover-metrics.ts +4 -1
  60. package/src/client/components/workspace/terminal-panel/KeyBar.tsx +10 -8
  61. package/src/client/components/workspace/terminal-panel/{RealtimeXtermView.tsx → RealtimeTerminalView.tsx} +51 -58
  62. package/src/client/components/workspace/terminal-panel/fit.test.ts +37 -0
  63. package/src/client/components/workspace/terminal-panel/fit.ts +64 -0
  64. package/src/client/components/workspace/terminal-panel/fonts.test.ts +161 -0
  65. package/src/client/components/workspace/terminal-panel/fonts.ts +164 -0
  66. package/src/client/components/workspace/terminal-panel/grid.test.ts +52 -0
  67. package/src/client/components/workspace/terminal-panel/grid.ts +118 -0
  68. package/src/client/components/workspace/terminal-panel/index.tsx +25 -21
  69. package/src/client/components/workspace/terminal-panel/mount.ts +247 -223
  70. package/src/client/components/workspace/terminal-panel/navigation.test.ts +54 -0
  71. package/src/client/components/workspace/terminal-panel/navigation.ts +47 -0
  72. package/src/client/data/settings/omp-schema.json +5 -5
  73. package/src/client/data/theme/terminal.test.ts +25 -0
  74. package/src/client/data/theme/terminal.ts +96 -79
  75. package/src/client/hooks/chat/composer/items.test.ts +12 -26
  76. package/src/client/hooks/chat/composer/pick-mapping.test.ts +42 -0
  77. package/src/client/hooks/chat/omp/prompt-send.test.ts +7 -7
  78. package/src/client/hooks/chat/omp/prompt-send.ts +26 -14
  79. package/src/client/hooks/chat/timeline/actions.ts +2 -2
  80. package/src/client/hooks/chat/timeline/ask-frames.ts +5 -4
  81. package/src/client/hooks/chat/timeline/new-chat-open.test.ts +86 -0
  82. package/src/client/hooks/chat/timeline/new-chat-open.ts +23 -5
  83. package/src/client/hooks/chat/timeline/new-chat.test.ts +32 -4
  84. package/src/client/hooks/chat/timeline/new-chat.ts +18 -6
  85. package/src/client/hooks/chat/timeline/prompt-text.test.ts +34 -1
  86. package/src/client/hooks/chat/timeline/prompt-text.ts +47 -20
  87. package/src/client/hooks/chat/timeline/rewind-actions.test.ts +24 -1
  88. package/src/client/hooks/chat/timeline/rewind-actions.ts +15 -11
  89. package/src/client/hooks/chat/timeline/run-identity.test.ts +52 -0
  90. package/src/client/hooks/chat/timeline/run-identity.ts +23 -11
  91. package/src/client/hooks/chat/timeline/send-execute.test.ts +56 -0
  92. package/src/client/hooks/chat/timeline/send-helpers.ts +30 -1
  93. package/src/client/hooks/chat/timeline/send-props.ts +5 -3
  94. package/src/client/hooks/chat/timeline/send-steer.test.ts +4 -4
  95. package/src/client/hooks/chat/timeline/send.test-util.ts +8 -2
  96. package/src/client/hooks/chat/timeline/send.test.ts +4 -4
  97. package/src/client/hooks/chat/timeline/send.ts +59 -53
  98. package/src/client/hooks/chat/timeline/session-load.test-util.ts +6 -2
  99. package/src/client/hooks/chat/timeline/session-load.test.ts +31 -0
  100. package/src/client/hooks/chat/timeline/session-load.ts +6 -14
  101. package/src/client/hooks/chat/timeline/session-shapes.ts +32 -0
  102. package/src/client/hooks/chat/timeline/use-fork-session.ts +49 -0
  103. package/src/client/hooks/models/harness-catalog.ts +114 -0
  104. package/src/client/hooks/models/provider-writes.test.ts +81 -0
  105. package/src/client/hooks/models/provider-writes.ts +10 -3
  106. package/src/client/hooks/models/use-harness-update.test.ts +193 -0
  107. package/src/client/hooks/models/use-harness-update.ts +202 -0
  108. package/src/client/hooks/models/use-harnesses-controller.ts +57 -0
  109. package/src/client/hooks/models/use-harnesses-signal.test.ts +128 -0
  110. package/src/client/hooks/models/use-harnesses.test.ts +2 -1
  111. package/src/client/hooks/models/use-harnesses.ts +48 -114
  112. package/src/client/hooks/workspace/child-expansion.ts +33 -0
  113. package/src/client/hooks/workspace/terminal/index.ts +17 -3
  114. package/src/client/hooks/workspace/terminal/socket.ts +9 -4
  115. package/src/client/lib/session-tree.test.ts +50 -0
  116. package/src/client/lib/session-tree.ts +59 -0
  117. package/src/client/tailwind.css +26 -12
  118. package/src/server/index.ts +2 -0
  119. package/src/server/lib/auth/guard.ts +10 -0
  120. package/src/server/lib/btw/session-copy.server.ts +6 -44
  121. package/src/server/lib/btw/session-copy.test.ts +2 -1
  122. package/src/server/lib/db/schema.ts +4 -0
  123. package/src/server/lib/db/seed-terminal.test.ts +1 -1
  124. package/src/server/lib/db/seed.test.ts +1 -1
  125. package/src/server/lib/harness/acp/activation.test.ts +81 -0
  126. package/src/server/lib/harness/acp/activation.ts +72 -0
  127. package/src/server/lib/harness/acp/background-work.test.ts +262 -0
  128. package/src/server/lib/harness/acp/background-work.ts +320 -0
  129. package/src/server/lib/harness/acp/client.ts +2 -2
  130. package/src/server/lib/harness/acp/frames.test.ts +50 -1
  131. package/src/server/lib/harness/acp/frames.ts +17 -5
  132. package/src/server/lib/harness/acp/gateway-env.test.ts +64 -0
  133. package/src/server/lib/harness/acp/gateway-env.ts +70 -0
  134. package/src/server/lib/harness/acp/mapper.ts +6 -4
  135. package/src/server/lib/harness/acp/prompt.test.ts +20 -0
  136. package/src/server/lib/harness/acp/prompt.ts +19 -3
  137. package/src/server/lib/harness/acp/session-background.test.ts +129 -0
  138. package/src/server/lib/harness/acp/session-config.test.ts +73 -0
  139. package/src/server/lib/harness/acp/session-config.ts +87 -6
  140. package/src/server/lib/harness/acp/session-exit.ts +31 -0
  141. package/src/server/lib/harness/acp/session-handshake.test.ts +108 -0
  142. package/src/server/lib/harness/acp/session-handshake.ts +36 -3
  143. package/src/server/lib/harness/acp/session-idle.ts +51 -0
  144. package/src/server/lib/harness/acp/session-listeners.ts +31 -0
  145. package/src/server/lib/harness/acp/session-notifications.ts +19 -3
  146. package/src/server/lib/harness/acp/session-observers.test.ts +9 -0
  147. package/src/server/lib/harness/acp/session-options.ts +33 -0
  148. package/src/server/lib/harness/acp/session-reaper.test.ts +96 -0
  149. package/src/server/lib/harness/acp/session-requests.ts +47 -0
  150. package/src/server/lib/harness/acp/session-turns.ts +20 -5
  151. package/src/server/lib/harness/acp/session.test-util.ts +54 -3
  152. package/src/server/lib/harness/acp/session.test.ts +65 -3
  153. package/src/server/lib/harness/acp/session.ts +79 -79
  154. package/src/server/lib/harness/acp/turn.test.ts +81 -0
  155. package/src/server/lib/harness/acp/turn.ts +54 -13
  156. package/src/server/lib/harness/acp/verbs.ts +12 -2
  157. package/src/server/lib/harness/auto-probe.server.test.ts +121 -0
  158. package/src/server/lib/harness/auto-probe.server.ts +178 -0
  159. package/src/server/lib/harness/config.server.test.ts +1 -1
  160. package/src/server/lib/harness/config.server.ts +1 -1
  161. package/src/server/lib/harness/launch-table.ts +195 -0
  162. package/src/server/lib/harness/launch.test.ts +37 -0
  163. package/src/server/lib/harness/launch.ts +16 -116
  164. package/src/server/lib/harness/provider-entry.ts +32 -0
  165. package/src/server/lib/harness/provider-file.server.ts +3 -0
  166. package/src/server/lib/harness/provider-sources.server.test.ts +45 -0
  167. package/src/server/lib/harness/provider-sources.server.ts +26 -2
  168. package/src/server/lib/harness/provider-write.server.ts +21 -32
  169. package/src/server/lib/harness/provider-zcode.server.test.ts +270 -0
  170. package/src/server/lib/harness/provider-zcode.server.ts +324 -0
  171. package/src/server/lib/harness/spawn.server.ts +15 -2
  172. package/src/server/lib/harness/update-job-store.test.ts +126 -0
  173. package/src/server/lib/harness/update-job-store.ts +109 -0
  174. package/src/server/lib/harness/update-job.server.ts +203 -0
  175. package/src/server/lib/harness/update-state.server.ts +15 -20
  176. package/src/server/lib/harness/update-worker.test.ts +153 -0
  177. package/src/server/lib/harness/update-worker.ts +197 -0
  178. package/src/server/lib/lifecycle/after-listen.ts +7 -0
  179. package/src/server/lib/lifecycle/paths.ts +23 -0
  180. package/src/server/lib/models/registry-refresh.server.test.ts +87 -0
  181. package/src/server/lib/models/registry-refresh.server.ts +98 -0
  182. package/src/server/lib/omp/rpc/child-config.ts +5 -4
  183. package/src/server/lib/omp/rpc/constants.test.ts +2 -1
  184. package/src/server/lib/omp/rpc/forked-resume.test.ts +14 -3
  185. package/src/server/lib/omp/rpc/manager.ts +5 -5
  186. package/src/server/lib/omp/rpc/prewarm-pool.ts +12 -3
  187. package/src/server/lib/omp/rpc/session-registry.ts +14 -2
  188. package/src/server/lib/omp/rpc/terminal-settle.ts +53 -5
  189. package/src/server/lib/omp/session/delete-flow.server.ts +62 -8
  190. package/src/server/lib/omp/session/delete.server.ts +17 -0
  191. package/src/server/lib/omp/session/rewind-file.ts +39 -21
  192. package/src/server/lib/omp/session/sidebar-data.server.ts +6 -6
  193. package/src/server/lib/omp/session/transcript-copy.ts +123 -0
  194. package/src/server/lib/sessions/agent-token.server.test.ts +64 -0
  195. package/src/server/lib/sessions/agent-token.server.ts +134 -0
  196. package/src/server/lib/sessions/answers.server.test.ts +33 -0
  197. package/src/server/lib/sessions/answers.server.ts +37 -0
  198. package/src/server/lib/sessions/dispatch.server.test.ts +143 -0
  199. package/src/server/lib/sessions/dispatch.server.ts +128 -0
  200. package/src/server/lib/sessions/fork.server.test.ts +209 -0
  201. package/src/server/lib/sessions/fork.server.ts +304 -0
  202. package/src/server/lib/sessions/lifecycle.server.test.ts +75 -0
  203. package/src/server/lib/sessions/lifecycle.server.ts +71 -0
  204. package/src/server/lib/sessions/notify.server.test.ts +112 -0
  205. package/src/server/lib/sessions/notify.server.ts +212 -0
  206. package/src/server/lib/sessions/relation-types.ts +76 -0
  207. package/src/server/lib/sessions/relations.server.test.ts +207 -0
  208. package/src/server/lib/sessions/relations.server.ts +337 -0
  209. package/src/server/lib/sessions/resolve.server.ts +106 -0
  210. package/src/server/lib/sessions/schema.server.ts +82 -0
  211. package/src/server/lib/sessions/sidebar-relations.server.test.ts +61 -0
  212. package/src/server/lib/sessions/sidebar-relations.server.ts +47 -0
  213. package/src/server/lib/sessions/spawn.server.test.ts +196 -0
  214. package/src/server/lib/sessions/spawn.server.ts +310 -0
  215. package/src/server/lib/terminal/attach-replay.test.ts +2 -2
  216. package/src/server/lib/terminal/output.test.ts +2 -2
  217. package/src/server/lib/terminal/output.ts +1 -1
  218. package/src/server/lib/terminal/resize.test.ts +99 -0
  219. package/src/server/lib/terminal/runtime.server.ts +26 -6
  220. package/src/server/lib/terminal/send-result.test.ts +18 -1
  221. package/src/server/lib/terminal/send-result.ts +26 -2
  222. package/src/server/lib/terminal/session.server.ts +6 -6
  223. package/src/server/lib/usage/new-api.test.ts +92 -0
  224. package/src/server/lib/usage/new-api.ts +131 -0
  225. package/src/server/lib/usage/provider-endpoint.test.ts +106 -0
  226. package/src/server/lib/usage/provider-key.ts +33 -0
  227. package/src/server/lib/usage/providers.server.ts +10 -3
  228. package/src/server/lib/usage/vendor-balance.server.ts +4 -53
  229. package/src/server/lib/usage/vendor-http.ts +41 -0
  230. package/src/server/lib/usage/window.ts +55 -0
  231. package/src/server/routes/agent/command.ts +14 -1
  232. package/src/server/routes/agent/harness-command.ts +6 -0
  233. package/src/server/routes/agent/new.ts +15 -0
  234. package/src/server/routes/chat/rewind.test.ts +147 -0
  235. package/src/server/routes/chat/rewind.ts +29 -7
  236. package/src/server/routes/chat/session.test.ts +165 -10
  237. package/src/server/routes/chat/session.ts +60 -7
  238. package/src/server/routes/harness/add-provider.test.ts +9 -1
  239. package/src/server/routes/harness/import-action.ts +22 -4
  240. package/src/server/routes/harness/import.test.ts +1 -1
  241. package/src/server/routes/harness/index.ts +5 -1
  242. package/src/server/routes/harness/root.ts +8 -49
  243. package/src/server/routes/harness/toggle.test.ts +20 -0
  244. package/src/server/routes/harness/update-status.ts +26 -0
  245. package/src/server/routes/harness/update.test.ts +119 -0
  246. package/src/server/routes/harness/update.ts +67 -113
  247. package/src/server/routes/harness/versions.ts +5 -1
  248. package/src/server/routes/sessions/answer.ts +24 -0
  249. package/src/server/routes/sessions/batch-delete.ts +11 -5
  250. package/src/server/routes/sessions/delete-acp.test.ts +227 -0
  251. package/src/server/routes/sessions/delete.ts +4 -2
  252. package/src/server/routes/sessions/fork.ts +74 -0
  253. package/src/server/routes/sessions/index.ts +14 -0
  254. package/src/server/routes/sessions/relations.ts +85 -0
  255. package/src/server/routes/sessions/session.ts +4 -0
  256. package/src/server/routes/sessions/spawn.ts +134 -0
  257. package/src/server/routes/settings/model-override.ts +5 -2
  258. package/src/server/routes/settings/provider-entry.ts +2 -2
  259. package/src/server/routes/settings/provider-model.ts +2 -2
  260. package/src/server/routes/settings/provider-models.ts +2 -2
  261. package/src/server/routes/settings/provider-refresh.ts +6 -4
  262. package/src/server/routes/settings/providers.ts +3 -1
  263. package/src/server/routes/settings/settings-config-routes.test.ts +10 -2
  264. package/src/server/routes/terminal/ws.ts +3 -3
  265. package/src/shared/lib/chat/ask-form/fields.ts +76 -0
  266. package/src/shared/lib/chat/ask-form/index.ts +323 -0
  267. package/src/shared/lib/chat/ask-form/tokens.ts +199 -0
  268. package/src/shared/lib/chat/ask-form/types.ts +43 -0
  269. package/src/shared/lib/chat/ask-form.test.ts +137 -0
  270. package/src/shared/lib/chat/ask-questions.test.ts +65 -1
  271. package/src/shared/lib/chat/ask-questions.ts +51 -145
  272. package/src/shared/lib/chat/ask-results.ts +198 -0
  273. package/src/shared/lib/chat/composer/client.ts +31 -2
  274. package/src/shared/lib/chat/composer/delegation.test.ts +93 -0
  275. package/src/shared/lib/chat/composer/delegation.ts +206 -0
  276. package/src/shared/lib/chat/notice-text.ts +1 -1
  277. package/src/shared/lib/chat/timeline/omp-callbacks.ts +13 -1
  278. package/src/shared/lib/chat/timeline/prompt-error.test.ts +146 -0
  279. package/src/shared/lib/chat/timeline/prompt-error.ts +88 -0
  280. package/src/shared/lib/chat/tool/summary-wait.test.ts +11 -0
  281. package/src/shared/lib/code/ansi.ts +1 -1
  282. package/src/shared/lib/fonts/nerd-symbols.css +4 -3
  283. package/src/shared/lib/fonts/nerd-symbols.test.ts +9 -9
  284. package/src/shared/lib/harness/catalog.test.ts +1 -1
  285. package/src/shared/lib/harness/config-fields.test.ts +4 -0
  286. package/src/shared/lib/harness/config-fields.ts +19 -4
  287. package/src/shared/lib/harness/dialects.test.ts +8 -0
  288. package/src/shared/lib/harness/dialects.ts +12 -0
  289. package/src/shared/lib/harness/provider-facts.test.ts +59 -8
  290. package/src/shared/lib/harness/provider-facts.ts +46 -11
  291. package/src/shared/lib/harness/providers.ts +44 -1
  292. package/src/shared/lib/harness/rewind.ts +24 -0
  293. package/src/shared/lib/harness/update-job.ts +33 -0
  294. package/src/shared/lib/harness/update-plan.test.ts +69 -4
  295. package/src/shared/lib/harness/update-plan.ts +57 -9
  296. package/src/shared/lib/harness/updates.test.ts +22 -0
  297. package/src/shared/lib/harness/updates.ts +24 -1
  298. package/src/shared/lib/models/client.ts +10 -1
  299. package/src/shared/lib/omp/dialog-methods.ts +4 -3
  300. package/src/shared/lib/omp/session/wait-idle.test.ts +11 -0
  301. package/src/shared/lib/omp/session/wait-idle.ts +12 -2
  302. package/src/shared/lib/theme/catalog.test.ts +13 -9
  303. package/src/shared/lib/theme/color.test.ts +2 -2
  304. package/src/shared/lib/theme/color.ts +4 -4
  305. package/src/shared/lib/theme/css.ts +2 -0
  306. package/src/shared/lib/theme/ink-scale.ts +21 -1
  307. package/src/shared/lib/theme/theme.test.ts +26 -10
  308. package/src/shared/lib/ui/safe-area.test.ts +28 -0
  309. package/src/shared/lib/ui/safe-area.ts +42 -0
  310. package/src/shared/lib/workspace/terminal/input.test.ts +27 -0
  311. package/src/shared/lib/workspace/terminal/input.ts +33 -0
  312. package/src/shared/lib/workspace/terminal/keys.test.ts +1 -1
  313. package/src/shared/lib/workspace/terminal/keys.ts +7 -7
  314. package/src/shared/types/chat.ts +1 -1
  315. package/src/shared/types/harness-update.ts +65 -0
  316. package/src/shared/types/harness.ts +30 -4
  317. package/src/shared/types/omp/agent.ts +19 -2
  318. package/src/shared/types/workspace.ts +4 -0
  319. package/src/test-support/fake-omp-fork.ts +16 -2
  320. package/src/test-support/file-explorer-render.test-util.ts +37 -0
  321. package/src/test-support/file-explorer.test-util.ts +20 -18
  322. package/src/test-support/harness-table.test-util.ts +21 -4
  323. package/dist/client/static/js/index-jhmg4w91.css +0 -1
  324. package/src/client/components/workspace/terminal-panel/webgl.test.ts +0 -75
  325. package/src/client/components/workspace/terminal-panel/webgl.ts +0 -108
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kabmo-labs/kabmo",
3
- "version": "0.23.0",
3
+ "version": "0.25.0",
4
4
  "description": "Web console and diagnostic workbench for AI coding agents: Elysia + Preact on Bun.",
5
5
  "license": "MIT",
6
6
  "author": "Wijanarko Putra Rajeb <wijanarko.rajeb@gmail.com>",
@@ -82,11 +82,9 @@
82
82
  "@shikijs/langs": "^4.4.3",
83
83
  "@shikijs/themes": "^4.4.3",
84
84
  "@tailwindcss/postcss": "^4.1.14",
85
- "@xterm/addon-fit": "^0.11.0",
86
- "@xterm/addon-webgl": "^0.19.0",
87
- "@xterm/xterm": "^6.0.0",
88
85
  "dompurify": "^3.4.15",
89
86
  "elysia": "^1.4.30",
87
+ "ghostty-web": "0.4.0-next.21.g640db46",
90
88
  "jsonc-parser": "^3.3.1",
91
89
  "katex": "^0.18.7",
92
90
  "lucide-preact": "^1.47.0",
@@ -25,6 +25,7 @@ const BOOLEAN_LONG = new Set([
25
25
  'quiet',
26
26
  'help',
27
27
  'version',
28
+ 'parent-self',
28
29
  ]);
29
30
 
30
31
  // Flags that set a DIFFERENTLY NAMED option, so a hyphenated flag can land on a
@@ -66,7 +67,8 @@ function takeValue(tokens, index, inline) {
66
67
  return { value: inline, nextIndex: index };
67
68
  }
68
69
  const candidate = tokens[index + 1];
69
- if (typeof candidate === 'string' && !candidate.startsWith('-')) {
70
+ // `-` is a VALUE for `--prompt-file`/`--message-file` (stdin), not a flag.
71
+ if (typeof candidate === 'string' && (candidate === '-' || !candidate.startsWith('-'))) {
70
72
  return { value: candidate, nextIndex: index + 1 };
71
73
  }
72
74
  return { value: undefined, nextIndex: index };
@@ -133,6 +135,25 @@ export function parseArgs(argv) {
133
135
  options.host = typeof value === 'string' ? value : null;
134
136
  return nextIndex;
135
137
  }
138
+ // `kabmo session` flags. The shared parser rejects anything it does not
139
+ // know, so a command's own options have to be named here — one table, one
140
+ // place an unknown flag is caught.
141
+ if (
142
+ name === 'prompt' ||
143
+ name === 'prompt-file' ||
144
+ name === 'harness' ||
145
+ name === 'anchor-entry' ||
146
+ name === 'model' ||
147
+ name === 'cwd' ||
148
+ name === 'title' ||
149
+ name === 'message' ||
150
+ name === 'message-file' ||
151
+ name === 'timeout'
152
+ ) {
153
+ const { value, nextIndex } = takeValue(tokens, index, inline);
154
+ options[name] = typeof value === 'string' && value.length > 0 ? value : null;
155
+ return nextIndex;
156
+ }
136
157
  const negated = NEGATED_LONG[name];
137
158
  if (negated) {
138
159
  options[negated.key] = negated.value;
@@ -227,6 +248,8 @@ COMMANDS:
227
248
  logs Print or follow server logs (every instance, or --port <port>)
228
249
  plugin Build, type, scaffold or list panel plugins
229
250
  (build|types|new|list; see "${bin} plugin --help")
251
+ session Spawn, fork, message or inspect a session through the server
252
+ (spawn|fork|tell|relations|output; see "${bin} session --help")
230
253
 
231
254
  REQUIRED: oh-my-pi (\`omp\`)
232
255
  Kabmo drives your existing omp binary; it never installs one for you.
@@ -100,3 +100,19 @@ describe('--ui-password-file', () => {
100
100
  expect(parseArgs(['serve', '--ui-password-file']).options.uiPasswordFile).toBeNull();
101
101
  });
102
102
  });
103
+
104
+ describe('session stdin flags', () => {
105
+ // `-` is the documented stdin spelling for --prompt-file/--message-file. It
106
+ // must be consumed as the VALUE, not pushed into positionals, or the spawn
107
+ // answers "prompt is required" while the heredoc sits unread on stdin.
108
+ test('a lone dash is the prompt-file value', () => {
109
+ const { options, positionals } = parseArgs(['session', 'spawn', '--prompt-file', '-']);
110
+ expect(options['prompt-file']).toBe('-');
111
+ expect(positionals).not.toContain('-');
112
+ });
113
+
114
+ test('a lone dash is the message-file value', () => {
115
+ const { options } = parseArgs(['session', 'tell', 'abc', '--message-file', '-']);
116
+ expect(options['message-file']).toBe('-');
117
+ });
118
+ });
@@ -0,0 +1,233 @@
1
+ // `kabmo session` — the agent-facing half of the console.
2
+ //
3
+ // Every command talks to the SAME HTTP routes the browser uses, with the
4
+ // per-session bearer token injected at spawn. No second API and no direct
5
+ // database access: an agent must be able to do exactly what a tab can.
6
+ //
7
+ // Usage:
8
+ // kabmo session spawn --prompt-file - [--parent-self] [--harness <id>] [--model <provider/model>] [--thinking <level>] [--json]
9
+ // kabmo session fork <source-id> [--anchor-entry <id>] [--prompt-file -] [--json]
10
+ // kabmo session tell <id> --message-file - [--json]
11
+ // kabmo session relations <id> [--json]
12
+ // kabmo session output <id> [--json]
13
+ // kabmo session wait <id> [--timeout 600] [--json]
14
+
15
+ import { readFileSync } from 'node:fs';
16
+ import { fail, log, ok, printJson, isJson } from '@/cli/lib/output.js';
17
+
18
+ const SERVER_URL = () => Bun.env.KABMO_SERVER_URL || 'http://localhost:3000';
19
+ const AGENT_TOKEN = () => Bun.env.KABMO_AGENT_TOKEN || '';
20
+
21
+ function usage() {
22
+ return `Usage: kabmo session <command> [options]
23
+
24
+ COMMANDS:
25
+ spawn Create a child session (requires --prompt/-file)
26
+ fork <source-id> Branch a session at an entry (or its tip)
27
+ tell <id> Send a prompt to a session
28
+ relations <id> Print the parent, children, forks and owner
29
+ output <id> Print the session's last assistant answer
30
+ wait <id> Wait until the session is idle (default 600s)
31
+
32
+ OPTIONS:
33
+ --prompt <text> First prompt (spawn/fork)
34
+ --prompt-file <path> Read it from a file; '-' reads stdin
35
+ --message <text> Message (tell)
36
+ --message-file <path> Read it from a file; '-' reads stdin
37
+ --parent-self Parent the new session to this agent's session
38
+ --harness <id> Harness for the child (omp-rpc, claude, codex, ...)
39
+ --model <provider/model> Pin the child's model; omit for the harness default
40
+ --thinking <level> Pin the child's thinking/effort level
41
+ --cwd <path> Working directory (defaults to the parent's)
42
+ --anchor-entry <id> Fork at this entry instead of the tip
43
+ --timeout <seconds> wait's deadline (default 600)
44
+ --json Machine-readable output
45
+ `;
46
+ }
47
+
48
+ function readText(options, inlineKey, fileKey) {
49
+ const inline = options[inlineKey];
50
+ const file = options[fileKey];
51
+ if (inline && file) fail(`Use --${inlineKey} or --${fileKey}, not both.`);
52
+ if (typeof inline === 'string') return inline;
53
+ if (typeof file !== 'string') fail(`--${inlineKey} or --${fileKey} is required.`);
54
+ if (file === '-') {
55
+ // Bun.stdin.text() is the CLI's own stdin; `session spawn` is normally run
56
+ // by an agent with a heredoc, never interactively.
57
+ return Bun.stdin.text();
58
+ }
59
+ try {
60
+ return readFileSync(file, 'utf8');
61
+ } catch (cause) {
62
+ fail(`Could not read ${file}: ${cause.message}`);
63
+ }
64
+ }
65
+
66
+ async function call(path, init = {}) {
67
+ const token = AGENT_TOKEN();
68
+ const base = SERVER_URL();
69
+ const request = (origin) => fetch(`${origin}${path}`, {
70
+ ...init,
71
+ headers: {
72
+ 'content-type': 'application/json',
73
+ ...(token ? { authorization: `Bearer ${token}` } : {}),
74
+ ...(init.headers ?? {}),
75
+ },
76
+ });
77
+ let response;
78
+ try {
79
+ response = await request(base);
80
+ } catch (cause) {
81
+ // localhost may resolve to ::1 while the operator wrote 127.0.0.1 (or the
82
+ // reverse). Try the other loopback spelling before reporting a dead server.
83
+ const alternate = alternateLoopback(base);
84
+ if (!alternate) fail(`Could not reach Kabmo at ${base}: ${cause.message}`);
85
+ try {
86
+ response = await request(alternate);
87
+ } catch {
88
+ fail(`Could not reach Kabmo at ${base}: ${cause.message}`);
89
+ }
90
+ }
91
+ const body = await response.json().catch(() => null);
92
+ if (!response.ok) {
93
+ fail(body?.error ?? `${response.status} ${response.statusText}`);
94
+ }
95
+ return body;
96
+ }
97
+
98
+ /** The other loopback spelling, or null for a non-loopback host. */
99
+ function alternateLoopback(base) {
100
+ try {
101
+ const url = new URL(base);
102
+ const host = url.hostname;
103
+ if (host === '127.0.0.1') url.hostname = 'localhost';
104
+ else if (host === 'localhost' || host === '::1' || host === '[::1]') url.hostname = '127.0.0.1';
105
+ else return null;
106
+ return url.origin;
107
+ } catch {
108
+ return null;
109
+ }
110
+ }
111
+
112
+ async function spawn(options) {
113
+ const prompt = await readText(options, 'prompt', 'prompt-file');
114
+ const model = typeof options.model === 'string' && options.model.trim()
115
+ ? modelSelection(options.model.trim())
116
+ : null;
117
+ const body = await call('/api/sessions/spawn', {
118
+ method: 'POST',
119
+ body: JSON.stringify({
120
+ prompt: prompt.trim(),
121
+ ...(options['parent-self'] ? { parentSelf: true } : {}),
122
+ ...(options.harness ? { harness: options.harness } : {}),
123
+ ...(model ? { model } : {}),
124
+ ...(options.thinking ? { thinkingLevel: options.thinking } : {}),
125
+ ...(options.cwd ? { cwd: options.cwd } : {}),
126
+ }),
127
+ });
128
+ if (isJson()) return printJson(body);
129
+ ok(`Spawned ${body.sessionId} (${body.harness}, depth ${body.depth})`);
130
+ log(body.sessionId);
131
+ }
132
+
133
+ /** `provider/model` as the spawn route stores it. A bare value keeps an empty
134
+ * provider: an ACP agent matches its own `modelId`, and omp resolves its own. */
135
+ function modelSelection(value) {
136
+ const slash = value.indexOf('/');
137
+ return slash > 0
138
+ ? { provider: value.slice(0, slash), modelId: value.slice(slash + 1) }
139
+ : { provider: '', modelId: value };
140
+ }
141
+
142
+ async function fork(options, sourceId) {
143
+ if (!sourceId) fail('fork needs a source session id.');
144
+ const prompt = options.prompt || options['prompt-file']
145
+ ? (await readText(options, 'prompt', 'prompt-file')).trim()
146
+ : '';
147
+ const body = await call(`/api/sessions/${encodeURIComponent(sourceId)}/fork`, {
148
+ method: 'POST',
149
+ body: JSON.stringify({
150
+ ...(options['anchor-entry'] ? { anchorEntryId: options['anchor-entry'] } : {}),
151
+ ...(prompt ? { prompt } : {}),
152
+ }),
153
+ });
154
+ if (isJson()) return printJson(body);
155
+ ok(`Forked ${sourceId} → ${body.sessionId}`);
156
+ log(body.sessionId);
157
+ }
158
+
159
+ async function tell(options, sessionId) {
160
+ if (!sessionId) fail('tell needs a session id.');
161
+ const message = (await readText(options, 'message', 'message-file')).trim();
162
+ const body = await call(`/api/agent/${encodeURIComponent(sessionId)}`, {
163
+ method: 'POST',
164
+ body: JSON.stringify({ type: 'prompt', message }),
165
+ });
166
+ if (isJson()) return printJson(body);
167
+ ok(`Sent to ${sessionId}`);
168
+ }
169
+
170
+ async function relations(options, sessionId) {
171
+ if (!sessionId) fail('relations needs a session id.');
172
+ const body = await call(`/api/sessions/${encodeURIComponent(sessionId)}/relations`);
173
+ if (isJson()) return printJson(body);
174
+ log(`parent: ${body.parent?.sessionId ?? '—'}`);
175
+ log(`children: ${body.children.map((row) => row.sessionId).join(', ') || '—'}`);
176
+ log(`forks: ${body.forks.map((row) => row.sessionId).join(', ') || '—'}`);
177
+ log(`owner: ${body.lifecycleOwner?.sessionId ?? '—'}`);
178
+ }
179
+
180
+ async function wait(options, sessionId) {
181
+ if (!sessionId) fail('wait needs a session id.');
182
+ const deadline = Date.now() + (Number(options.timeout ?? 600) * 1000);
183
+ const interval = Number(Bun.env.KABMO_WAIT_INTERVAL_MS ?? 2000);
184
+ let state = { running: true };
185
+ while (Date.now() < deadline) {
186
+ state = await call(`/api/agent/${encodeURIComponent(sessionId)}`);
187
+ if (state?.running !== true) break;
188
+ await Bun.sleep(interval);
189
+ }
190
+ if (state?.running === true) fail(`Timed out waiting for ${sessionId}.`);
191
+ if (isJson()) return printJson(state);
192
+ ok(`${sessionId} is idle`);
193
+ }
194
+
195
+ async function output(options, sessionId) {
196
+ if (!sessionId) fail('output needs a session id.');
197
+ const body = await call(`/api/chat/${encodeURIComponent(sessionId)}`);
198
+ if (isJson()) return printJson(body);
199
+ const messages = body?.session?.messages ?? [];
200
+ const assistant = [...messages].reverse().find((message) => message.role === 'assistant' || message.role === 'ai');
201
+ if (assistant?.content) {
202
+ log(assistant.content);
203
+ return;
204
+ }
205
+ // ACP keeps its history with the agent; Kabmo stores the last closed answer
206
+ // precisely so this command still has something to print.
207
+ const stored = await call(`/api/sessions/${encodeURIComponent(sessionId)}/answer`);
208
+ log(stored?.answer ?? 'No assistant answer recorded.');
209
+ }
210
+
211
+ export async function run(options) {
212
+ const [subcommand, ...args] = options.args ?? [];
213
+ if (!subcommand || options.help) {
214
+ process.stdout.write(usage());
215
+ return;
216
+ }
217
+ switch (subcommand) {
218
+ case 'spawn':
219
+ return spawn(options);
220
+ case 'fork':
221
+ return fork(options, args[0]);
222
+ case 'tell':
223
+ return tell(options, args[0]);
224
+ case 'relations':
225
+ return relations(options, args[0]);
226
+ case 'output':
227
+ return output(options, args[0]);
228
+ case 'wait':
229
+ return wait(options, args[0]);
230
+ default:
231
+ fail(`Unknown session command: ${subcommand}\n${usage()}`);
232
+ }
233
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The CLI is a thin client: these cases prove it sends the right path, body and
8
+ * bearer token, not that the server handles them (route tests own that).
9
+ */
10
+
11
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
12
+ import { run } from './session.js';
13
+
14
+ let server;
15
+ let captured;
16
+ let waitCalls;
17
+ let savedUrl;
18
+ let savedToken;
19
+
20
+ beforeEach(() => {
21
+ captured = [];
22
+ waitCalls = 0;
23
+ savedUrl = Bun.env.KABMO_SERVER_URL;
24
+ savedToken = Bun.env.KABMO_AGENT_TOKEN;
25
+ server = Bun.serve({
26
+ port: 0,
27
+ async fetch(request) {
28
+ const body = request.method === 'POST' ? await request.json().catch(() => null) : null;
29
+ captured.push({
30
+ url: new URL(request.url).pathname,
31
+ method: request.method,
32
+ authorization: request.headers.get('authorization'),
33
+ body,
34
+ });
35
+ if (request.url.endsWith('/api/agent/w')) {
36
+ waitCalls += 1;
37
+ return Response.json({ running: waitCalls < 2 });
38
+ }
39
+ if (request.url.includes('/fork')) {
40
+ return Response.json({ sessionId: 'child', sourceSessionId: 'root', originKind: 'fork' });
41
+ }
42
+ if (request.url.endsWith('/api/sessions/spawn')) {
43
+ return Response.json({ sessionId: 'child', harness: 'omp-rpc', parentSessionId: 'root', depth: 1 });
44
+ }
45
+ return Response.json({ ok: true });
46
+ },
47
+ });
48
+ Bun.env.KABMO_SERVER_URL = `http://127.0.0.1:${server.port}`;
49
+ Bun.env.KABMO_AGENT_TOKEN = 'agent-token';
50
+ });
51
+
52
+ afterEach(() => {
53
+ server.stop(true);
54
+ if (savedUrl === undefined) delete Bun.env.KABMO_SERVER_URL;
55
+ else Bun.env.KABMO_SERVER_URL = savedUrl;
56
+ if (savedToken === undefined) delete Bun.env.KABMO_AGENT_TOKEN;
57
+ else Bun.env.KABMO_AGENT_TOKEN = savedToken;
58
+ });
59
+
60
+ describe('kabmo session', () => {
61
+ test('spawn sends parentSelf and the token', async () => {
62
+ await run({ args: ['spawn'], prompt: 'review this', 'parent-self': true, harness: 'codex', json: true });
63
+ expect(captured).toEqual([
64
+ {
65
+ url: '/api/sessions/spawn',
66
+ method: 'POST',
67
+ authorization: 'Bearer agent-token',
68
+ body: { prompt: 'review this', parentSelf: true, harness: 'codex' },
69
+ },
70
+ ]);
71
+ });
72
+
73
+ test('fork sends the anchor and no empty prompt', async () => {
74
+ await run({ args: ['fork', 'root'], 'anchor-entry': 'a1', json: true });
75
+ expect(captured[0]).toMatchObject({
76
+ url: '/api/sessions/root/fork',
77
+ method: 'POST',
78
+ body: { anchorEntryId: 'a1' },
79
+ });
80
+ });
81
+
82
+ test('tell posts the prompt command to the agent route', async () => {
83
+ await run({ args: ['tell', 'child'], message: 'hello', json: true });
84
+ expect(captured[0]).toMatchObject({
85
+ url: '/api/agent/child',
86
+ method: 'POST',
87
+ body: { type: 'prompt', message: 'hello' },
88
+ });
89
+ });
90
+
91
+ test('wait polls until the session is idle', async () => {
92
+ const savedInterval = Bun.env.KABMO_WAIT_INTERVAL_MS;
93
+ Bun.env.KABMO_WAIT_INTERVAL_MS = '1';
94
+ try {
95
+ await run({ args: ['wait', 'w'], timeout: 5, json: true });
96
+ } finally {
97
+ if (savedInterval === undefined) delete Bun.env.KABMO_WAIT_INTERVAL_MS;
98
+ else Bun.env.KABMO_WAIT_INTERVAL_MS = savedInterval;
99
+ }
100
+ expect(waitCalls).toBe(2);
101
+ expect(captured.map((entry) => entry.url)).toEqual(['/api/agent/w', '/api/agent/w']);
102
+ });
103
+ });
package/src/cli/main.js CHANGED
@@ -16,7 +16,7 @@ import { migrateLegacyDataDir } from '@/server/lib/lifecycle/paths';
16
16
 
17
17
  const { version } = packageJson;
18
18
 
19
- const COMMANDS = ['serve', 'update', 'stop', 'restart', 'status', 'doctor', 'logs', 'plugin'];
19
+ const COMMANDS = ['serve', 'update', 'stop', 'restart', 'status', 'doctor', 'logs', 'plugin', 'session'];
20
20
 
21
21
  export async function runCli(bin = 'kabmo') {
22
22
  const { command, positionals, options, unknown } = parseArgs(process.argv.slice(2));
@@ -120,6 +120,9 @@ export function ComposerPicker({
120
120
  <span className="truncate">
121
121
  <OptionName item={item} />
122
122
  </span>
123
+ {item.source === 'harness' && (
124
+ <span className="text-ink/40 text-[10px] uppercase shrink-0">harness</span>
125
+ )}
123
126
  {item.source === 'file' && (
124
127
  <span className="text-ink/40 text-[10px] uppercase shrink-0">file</span>
125
128
  )}
@@ -2,6 +2,7 @@ import { useId, useRef } from 'preact/hooks';
2
2
  import type { FormEvent, ReactNode } from 'preact/compat';
3
3
  import { X } from 'lucide-preact';
4
4
  import { useDialogBehaviour } from '@/client/hooks/ui/dialog-behaviour';
5
+ import { safeAreaPadding } from '@/shared/lib/ui/safe-area';
5
6
 
6
7
  export interface ModalProps {
7
8
  /** Backdrop click / close-button handler. */
@@ -60,12 +61,7 @@ export function Modal({
60
61
  return (
61
62
  <div
62
63
  className={`fixed inset-0 modal-scrim backdrop-blur-[2px] ${zClass} flex items-center justify-center p-4`}
63
- style={{
64
- paddingTop: 'max(1rem, env(safe-area-inset-top, 0px))',
65
- paddingBottom: 'max(1rem, env(safe-area-inset-bottom, 0px))',
66
- paddingLeft: 'max(1rem, env(safe-area-inset-left, 0px))',
67
- paddingRight: 'max(1rem, env(safe-area-inset-right, 0px))',
68
- }}
64
+ style={safeAreaPadding(1)}
69
65
  onClick={onClose}
70
66
  >
71
67
  {/* `role="dialog"` + `aria-modal`: every modal built on this shell (the
@@ -0,0 +1,82 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The tokenizer's long-line guard, per language.
8
+ *
9
+ * Markdown's grammar backtracks superlinearly on a long prose line (see
10
+ * `LINE_CHAR_LIMITS` in `shiki.ts`), which is why the guard is tighter than the
11
+ * minified-bundle default. The rule is silent when it regresses — a viewport
12
+ * simply costs seconds — so the guard is asserted through a mounted view: the
13
+ * short line paints `shiki-tok` spans, the long one stays plain text.
14
+ */
15
+
16
+ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
17
+ import { EditorState } from '@codemirror/state';
18
+ import { EditorView } from '@codemirror/view';
19
+ import { Window } from 'happy-dom';
20
+
21
+ import { shikiHighlight } from '@/client/components/common/code-surface/shiki';
22
+ import { bootSyntax, getHighlighterSync } from '@/shared/lib/code/highlighter';
23
+ import { ensureLanguage } from '@/shared/lib/code/highlighter-lazy';
24
+ import { installDomGlobals, restoreDomGlobals } from '@/test-support/pristine-globals';
25
+
26
+ const EXTRA_GLOBALS = ['MutationObserver', 'ResizeObserver'] as const;
27
+ const native: Partial<Record<(typeof EXTRA_GLOBALS)[number], unknown>> = {};
28
+
29
+ beforeAll(async () => {
30
+ const win = new Window({ url: 'http://localhost' });
31
+ installDomGlobals(win);
32
+ const target = globalThis as unknown as Record<string, unknown>;
33
+ for (const key of EXTRA_GLOBALS) {
34
+ native[key] = target[key];
35
+ target[key] = (win as unknown as Record<string, unknown>)[key];
36
+ }
37
+ await bootSyntax();
38
+ const highlighter = getHighlighterSync();
39
+ if (highlighter) await ensureLanguage(highlighter, 'markdown');
40
+ });
41
+
42
+ afterAll(() => {
43
+ const target = globalThis as unknown as Record<string, unknown>;
44
+ for (const key of EXTRA_GLOBALS) {
45
+ if (native[key] === undefined) delete target[key];
46
+ else target[key] = native[key];
47
+ }
48
+ restoreDomGlobals();
49
+ });
50
+
51
+ /** `- **bold** words …`, padded past the guard so the grammar would pay for it. */
52
+ function longMarkdownLine(): string {
53
+ return `- **${'bold words '.repeat(120)}** tail`;
54
+ }
55
+
56
+ function mountMarkdown(doc: string): { view: EditorView; host: HTMLElement } {
57
+ const host = document.body.appendChild(document.createElement('div'));
58
+ const view = new EditorView({
59
+ parent: host,
60
+ state: EditorState.create({ doc, extensions: [shikiHighlight('markdown')] }),
61
+ });
62
+ return { view, host };
63
+ }
64
+
65
+ describe('markdown long-line guard', () => {
66
+ test('a line past the guard renders plain while a short line still tokenizes', () => {
67
+ const long = longMarkdownLine();
68
+ expect(long.length).toBeGreaterThanOrEqual(1_000);
69
+
70
+ const { view, host } = mountMarkdown(['short **bold** line', long].join('\n'));
71
+ try {
72
+ const lines = host.querySelectorAll<HTMLElement>('.cm-line');
73
+ expect(lines.length).toBe(2);
74
+ expect(lines[0].querySelectorAll('.shiki-tok').length).toBeGreaterThan(0);
75
+ expect(lines[1].textContent).toBe(long);
76
+ expect(lines[1].querySelectorAll('.shiki-tok').length).toBe(0);
77
+ } finally {
78
+ view.destroy();
79
+ host.remove();
80
+ }
81
+ });
82
+ });
@@ -18,9 +18,10 @@
18
18
  * window that opens inside a block comment or a template literal still
19
19
  * tokenizes as one. Measured: 2.1 ms per keystroke at 20 000 lines, flat,
20
20
  * because the window is ~100 lines whatever the document is.
21
- * - **A line at or past `MAX_LINE_CHARS` is left plain.** A minified bundle is
22
- * one line of hundreds of KB, and tokenizing it on every scroll is what makes
23
- * an editor feel dead.
21
+ * - **A line at or past the language's guard is left plain.** A minified bundle
22
+ * is one line of hundreds of KB, and tokenizing it on every scroll is what
23
+ * makes an editor feel dead. Markdown gets a tighter guard because its
24
+ * grammar's own cost grows with the spans on a line — see `LINE_CHAR_LIMITS`.
24
25
  *
25
26
  * The colours are NOT inline. Every token carries Shiki's two custom properties
26
27
  * (`--shiki-light` / `--shiki-dark`) and `theme.ts` picks one through
@@ -38,8 +39,27 @@ import { SHIKI_THEMES } from '@/shared/lib/code/shiki-themes';
38
39
  /** Lines tokenized above the viewport, to seed the grammar's own state. */
39
40
  const CONTEXT_LINES = 40;
40
41
 
41
- /** Lines at or above this length render as plain text (see the module note). */
42
- const MAX_LINE_CHARS = 12_000;
42
+ /**
43
+ * Lines at or above this length render as plain text (see the module note).
44
+ *
45
+ * The default is the minified-bundle guard: one line of hundreds of KB is not
46
+ * worth tokenizing on every scroll.
47
+ */
48
+ const DEFAULT_LINE_CHARS = 12_000;
49
+
50
+ /**
51
+ * Per-language tighter guards, for grammars whose own rules make a long line far
52
+ * more expensive than its length suggests.
53
+ *
54
+ * Markdown is the measured case. Its `bold`/`italic` rules are nested
55
+ * lookarounds, and with Shiki's JS regex engine the cost grows with the number
56
+ * of spans on the line: measured on `.wiki/App-Shell-and-Layout.md`, tokenizing
57
+ * one 140-line viewport took **6.3 s** at the default cap (4 100 ms at 4 000,
58
+ * 500 ms at 2 000) and **12–38 ms** once lines of 1 000+ characters are left
59
+ * plain. Those are exactly the prose bullets the wiki is written in, which is
60
+ * why opening a markdown diff felt broken while a code diff did not.
61
+ */
62
+ const LINE_CHAR_LIMITS: Record<string, number> = { markdown: 1_000 };
43
63
 
44
64
  /** Marks are shared by their style string: a file has a few dozen distinct ones. */
45
65
  const markCache = new Map<string, Decoration>();
@@ -94,6 +114,7 @@ function buildDecorations(
94
114
  if (!highlighter || language === 'text' || !requestLanguage(language)) return Decoration.none;
95
115
 
96
116
  const doc = view.state.doc;
117
+ const lineLimit = LINE_CHAR_LIMITS[language] ?? DEFAULT_LINE_CHARS;
97
118
  const firstLine = doc.lineAt(view.viewport.from).number;
98
119
  const lastLine = doc.lineAt(view.viewport.to).number;
99
120
  const contextStart = Math.max(1, firstLine - CONTEXT_LINES);
@@ -110,7 +131,7 @@ function buildDecorations(
110
131
  // the pair is a plain string map, which is what it accepts at runtime.
111
132
  themes: themes as unknown as Record<string, string>,
112
133
  defaultColor: false,
113
- tokenizeMaxLineLength: MAX_LINE_CHARS,
134
+ tokenizeMaxLineLength: lineLimit,
114
135
  }).tokens as typeof tokenized;
115
136
  } catch {
116
137
  // A grammar the engine refuses (or a Shiki internal): plain text is the
@@ -121,7 +142,7 @@ function buildDecorations(
121
142
  const builder = new RangeSetBuilder<Decoration>();
122
143
  for (let index = 0; index < tokenized.length && index < lines.length; index++) {
123
144
  const line = doc.line(contextStart + index);
124
- if (line.length >= MAX_LINE_CHARS) continue;
145
+ if (line.length >= lineLimit) continue;
125
146
  let offset = 0;
126
147
  for (const token of tokenized[index]) {
127
148
  const length = token.content.length;