@kabmo-labs/kabmo 0.16.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (381) hide show
  1. package/README.md +2 -2
  2. package/dist/client/index.html +1 -1
  3. package/dist/client/index.js +552 -471
  4. package/dist/client/static/js/index-hp75vsv9.css +1 -0
  5. package/dist/client/static/js/{index-cpydmygd.js → index-tc09dtca.js} +897 -886
  6. package/package.json +1 -1
  7. package/src/client/components/common/MarkdownRenderer.tsx +136 -89
  8. package/src/client/components/common/anchored-menu/index.test.tsx +141 -0
  9. package/src/client/components/common/anchored-menu/index.tsx +143 -0
  10. package/src/client/components/common/code-surface/bracket-guide.test.ts +2 -2
  11. package/src/client/components/common/code-surface/bracket-guide.ts +2 -2
  12. package/src/client/components/common/code-surface/conflict-markers.ts +5 -5
  13. package/src/client/components/common/code-surface/extensions.ts +7 -4
  14. package/src/client/components/common/code-surface/theme.ts +34 -9
  15. package/src/client/components/common/code-surface/whitespace.test.ts +223 -0
  16. package/src/client/components/common/code-surface/whitespace.ts +140 -0
  17. package/src/client/components/common/markdown-review/ReviewPopover.tsx +144 -0
  18. package/src/client/components/common/markdown-review/ReviewSummary.tsx +108 -0
  19. package/src/client/components/common/markdown-review/index.tsx +129 -0
  20. package/src/client/components/common/{server-switcher/index.tsx → server-control/Panel.tsx} +92 -44
  21. package/src/client/components/common/server-control/index.test.tsx +217 -0
  22. package/src/client/components/common/server-control/index.tsx +120 -0
  23. package/src/client/components/layout/desktop-layout/TopNavbar.tsx +8 -50
  24. package/src/client/components/layout/session-sidebar/CategoryHeader.tsx +42 -21
  25. package/src/client/components/layout/session-sidebar/CategoryHeader.worktree.test.tsx +36 -17
  26. package/src/client/components/layout/session-sidebar/CategoryItem.tsx +8 -7
  27. package/src/client/components/layout/session-sidebar/about-modal/NotesDialog.tsx +94 -0
  28. package/src/client/components/layout/session-sidebar/about-modal/VersionLine.test.tsx +68 -0
  29. package/src/client/components/layout/session-sidebar/about-modal/VersionLine.tsx +36 -0
  30. package/src/client/components/layout/session-sidebar/about-modal/index.tsx +57 -34
  31. package/src/client/components/layout/session-sidebar/modern/WorkspaceHeader.tsx +28 -10
  32. package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +7 -6
  33. package/src/client/components/layout/session-sidebar/modern/workspace-header.test.tsx +1 -1
  34. package/src/client/components/layout/update-popup/ReleaseNotes.tsx +8 -3
  35. package/src/client/components/layout/update-popup/index.tsx +5 -1
  36. package/src/client/components/mobile/mobile-main-view/Header.tsx +6 -12
  37. package/src/client/components/mobile/mobile-right-sidebar/FullEditor.tsx +13 -15
  38. package/src/client/components/mobile/mobile-right-sidebar/Header.tsx +23 -1
  39. package/src/client/components/mobile/mobile-right-sidebar/MissingFileBanner.tsx +30 -0
  40. package/src/client/components/mobile/mobile-right-sidebar/PreviewScroller.tsx +18 -2
  41. package/src/client/components/mobile/mobile-session-sidebar/Header.tsx +41 -13
  42. package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +22 -67
  43. package/src/client/components/mobile/mobile-session-sidebar/ItemMenu.tsx +110 -0
  44. package/src/client/components/settings/Modal.tsx +9 -3
  45. package/src/client/components/settings/ProjectSelectorDropdown.tsx +19 -9
  46. package/src/client/components/settings/SettingsSidebarList.tsx +20 -0
  47. package/src/client/components/settings/categories/AgentSettings.tsx +38 -44
  48. package/src/client/components/settings/categories/CommandSettings.tsx +2 -2
  49. package/src/client/components/settings/categories/McpSettings.tsx +4 -21
  50. package/src/client/components/settings/categories/OmpSettings.tsx +147 -194
  51. package/src/client/components/settings/categories/ProjectSettings.tsx +122 -156
  52. package/src/client/components/settings/categories/SkillCatalogSettings.tsx +220 -260
  53. package/src/client/components/settings/categories/SkillSettings.tsx +8 -5
  54. package/src/client/components/settings/categories/TokenUsageSettings.tsx +211 -229
  55. package/src/client/components/settings/categories/agent-settings/DetailPane.tsx +229 -237
  56. package/src/client/components/settings/categories/agent-settings/ModelPicker.tsx +71 -0
  57. package/src/client/components/settings/categories/agent-settings/SidebarList.tsx +14 -2
  58. package/src/client/components/settings/categories/agent-settings/levels.ts +38 -0
  59. package/src/client/components/settings/categories/behavior-settings/Editor.tsx +27 -7
  60. package/src/client/components/settings/categories/chat-settings/ToolRenderSection.tsx +23 -5
  61. package/src/client/components/settings/categories/command-settings/DetailPane.tsx +75 -33
  62. package/src/client/components/settings/categories/command-settings/SidebarList.tsx +7 -0
  63. package/src/client/components/settings/categories/mcp-settings/DetailPane.tsx +91 -76
  64. package/src/client/components/settings/categories/mcp-settings/EnvVarsSection.tsx +83 -0
  65. package/src/client/components/settings/categories/mcp-settings/ImportModal.tsx +26 -13
  66. package/src/client/components/settings/categories/mcp-settings/SidebarList.tsx +20 -0
  67. package/src/client/components/settings/categories/omp-settings/ConfigTabs.tsx +97 -36
  68. package/src/client/components/settings/categories/omp-settings/EngineHeader.tsx +151 -0
  69. package/src/client/components/settings/categories/omp-settings/ExtensionsPanel.tsx +68 -32
  70. package/src/client/components/settings/categories/omp-settings/OrderedChips.tsx +119 -0
  71. package/src/client/components/settings/categories/omp-settings/PresetBar.tsx +14 -7
  72. package/src/client/components/settings/categories/omp-settings/RoleEditor.tsx +15 -6
  73. package/src/client/components/settings/categories/omp-settings/RowEditor.tsx +165 -226
  74. package/src/client/components/settings/categories/omp-settings/types.ts +28 -0
  75. package/src/client/components/settings/categories/project-settings/AccentPalette.test.tsx +189 -0
  76. package/src/client/components/settings/categories/project-settings/AccentPalette.tsx +156 -24
  77. package/src/client/components/settings/categories/project-settings/AddProjectModal.tsx +175 -0
  78. package/src/client/components/settings/categories/project-settings/DeleteProjectModal.tsx +107 -0
  79. package/src/client/components/settings/categories/project-settings/DetailsForm.tsx +40 -24
  80. package/src/client/components/settings/categories/project-settings/DetailsHeader.tsx +17 -7
  81. package/src/client/components/settings/categories/project-settings/IconGrid.tsx +164 -69
  82. package/src/client/components/settings/categories/project-settings/ModelDropdown.test.tsx +122 -0
  83. package/src/client/components/settings/categories/project-settings/ModelDropdown.tsx +124 -53
  84. package/src/client/components/settings/categories/project-settings/NameInput.tsx +57 -11
  85. package/src/client/components/settings/categories/project-settings/PathField.tsx +122 -0
  86. package/src/client/components/settings/categories/project-settings/SidebarList.tsx +100 -59
  87. package/src/client/components/settings/categories/skill-catalog/GitImportPanel.tsx +253 -0
  88. package/src/client/components/settings/categories/skill-catalog/SkillCard.tsx +89 -0
  89. package/src/client/components/settings/categories/skill-catalog/SourceRail.tsx +122 -0
  90. package/src/client/components/settings/categories/skill-catalog/catalog-ui.test.tsx +179 -0
  91. package/src/client/components/settings/categories/skill-settings/DetailHeader.tsx +236 -0
  92. package/src/client/components/settings/categories/skill-settings/DetailPane.tsx +164 -239
  93. package/src/client/components/settings/categories/skill-settings/InstructionsEditor.tsx +84 -0
  94. package/src/client/components/settings/categories/skill-settings/SidebarList.tsx +144 -87
  95. package/src/client/components/settings/categories/skill-settings/pane.test.tsx +188 -0
  96. package/src/client/components/settings/categories/skill-settings/row-meta.ts +58 -0
  97. package/src/client/components/settings/categories/token-usage-settings/Breakdown.tsx +242 -102
  98. package/src/client/components/settings/categories/token-usage-settings/Chart.tsx +130 -56
  99. package/src/client/components/settings/categories/token-usage-settings/Controls.tsx +135 -0
  100. package/src/client/components/settings/categories/token-usage-settings/MetricsGrid.tsx +55 -33
  101. package/src/client/components/settings/categories/token-usage-settings/Provenance.tsx +59 -0
  102. package/src/client/components/settings/categories/token-usage-settings/panel.test.tsx +239 -0
  103. package/src/client/components/workspace/browser-panel/Screencast.test.ts +1 -0
  104. package/src/client/components/workspace/browser-panel/Screencast.tsx +17 -22
  105. package/src/client/components/workspace/browser-panel/TabStrip.test.tsx +158 -0
  106. package/src/client/components/workspace/browser-panel/TabStrip.tsx +90 -0
  107. package/src/client/components/workspace/browser-panel/index.tsx +50 -4
  108. package/src/client/components/workspace/browser-toolbar/index.tsx +41 -1
  109. package/src/client/components/workspace/chat-timeline/ThinkingSection.tsx +3 -1
  110. package/src/client/components/workspace/chat-timeline/ToolCallingSection.tsx +2 -0
  111. package/src/client/components/workspace/chat-timeline/block-chrome.test.tsx +13 -2
  112. package/src/client/components/workspace/chat-timeline/index.tsx +6 -1
  113. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Bash.test.ts +88 -0
  114. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Bash.tsx +24 -1
  115. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Proc.test.ts +46 -0
  116. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Proc.tsx +15 -6
  117. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Read.test.ts +34 -0
  118. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Read.tsx +5 -1
  119. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Wait.test.ts +29 -0
  120. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Wait.tsx +11 -3
  121. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/ArtifactChip.tsx +7 -6
  122. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/card-header.test.ts +24 -1
  123. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/card-header.ts +6 -2
  124. package/src/client/components/workspace/chat-timeline/tool-renderers/styles/Tui.test.tsx +237 -0
  125. package/src/client/components/workspace/chat-timeline/tool-renderers/styles/Tui.tsx +191 -0
  126. package/src/client/components/workspace/chat-timeline/tool-renderers/styles/styles.test.tsx +1 -1
  127. package/src/client/components/workspace/diff-panel/MergeDiffView.tsx +21 -7
  128. package/src/client/components/workspace/diff-panel/changes.test.ts +51 -0
  129. package/src/client/components/workspace/diff-panel/changes.ts +28 -12
  130. package/src/client/components/workspace/diff-panel/merge.test.ts +28 -0
  131. package/src/client/components/workspace/diff-panel/merge.ts +21 -1
  132. package/src/client/components/workspace/editor/Body.tsx +7 -0
  133. package/src/client/components/workspace/editor/FileDocument.tsx +15 -21
  134. package/src/client/components/workspace/editor/FilePane.tsx +12 -0
  135. package/src/client/components/workspace/editor/PreviewPane.tsx +70 -0
  136. package/src/client/components/workspace/editor/Toolbar.tsx +17 -1
  137. package/src/client/components/workspace/editor/index.tsx +25 -22
  138. package/src/client/components/workspace/editor/toolbar-clusters.test.ts +14 -0
  139. package/src/client/components/workspace/editor/toolbar-clusters.tsx +12 -86
  140. package/src/client/components/workspace/editor/toolbar-toggle.tsx +53 -0
  141. package/src/client/components/workspace/editor/toolbar-write-clusters.tsx +112 -0
  142. package/src/client/components/workspace/editor/viewers/SvgPreview.tsx +18 -2
  143. package/src/client/components/workspace/editor/viewers/viewers.test.ts +39 -0
  144. package/src/client/components/workspace/file-explorer/ContextMenu.tsx +18 -5
  145. package/src/client/components/workspace/file-explorer/Modals.tsx +15 -1
  146. package/src/client/components/workspace/file-explorer/RowLabel.tsx +68 -0
  147. package/src/client/components/workspace/file-explorer/TreeItem.tsx +47 -57
  148. package/src/client/components/workspace/file-explorer/collapsed-chain.test.ts +167 -0
  149. package/src/client/components/workspace/file-explorer/drag-props.ts +42 -0
  150. package/src/client/components/workspace/file-explorer/drag.test.ts +43 -0
  151. package/src/client/components/workspace/file-explorer/index.tsx +21 -20
  152. package/src/client/components/workspace/git-panel/commit-modal.test.ts +5 -3
  153. package/src/client/components/workspace/user-browser-panel/AddressBar.tsx +5 -0
  154. package/src/client/components/workspace/user-browser-panel/AnnotateBar.test.tsx +201 -0
  155. package/src/client/components/workspace/user-browser-panel/AnnotateBar.tsx +112 -0
  156. package/src/client/components/workspace/user-browser-panel/AnnotateLayer.test.tsx +225 -0
  157. package/src/client/components/workspace/user-browser-panel/AnnotateLayer.tsx +217 -0
  158. package/src/client/components/workspace/user-browser-panel/AnnotateTarget.tsx +99 -0
  159. package/src/client/components/workspace/user-browser-panel/Frame.tsx +30 -1
  160. package/src/client/components/workspace/user-browser-panel/index.tsx +81 -2
  161. package/src/client/data/agent-data/builtin.ts +0 -10
  162. package/src/client/data/agent-data/orchestrator.ts +0 -45
  163. package/src/client/data/agent-data/specialist.ts +0 -100
  164. package/src/client/data/mock/token-usage.ts +170 -120
  165. package/src/client/data/settings/omp-schema.json +123 -4
  166. package/src/client/data/settings/project.ts +9 -28
  167. package/src/client/data/settings/skill.ts +6 -32
  168. package/src/client/hooks/browser/use-annotate.test.ts +143 -0
  169. package/src/client/hooks/browser/use-annotate.ts +98 -0
  170. package/src/client/hooks/browser/use-close-tab.test.ts +148 -0
  171. package/src/client/hooks/browser/use-close-tab.ts +67 -0
  172. package/src/client/hooks/browser/use-screencast.ts +13 -1
  173. package/src/client/hooks/chat/composer/browser-context.test.ts +117 -0
  174. package/src/client/hooks/chat/composer/browser-context.ts +40 -16
  175. package/src/client/hooks/chat/composer/items.test.ts +1 -1
  176. package/src/client/hooks/chat/composer/review-context.ts +38 -0
  177. package/src/client/hooks/chat/composer/use-draft.test.ts +132 -0
  178. package/src/client/hooks/chat/composer/use-draft.ts +31 -2
  179. package/src/client/hooks/chat/timeline/pending-model.ts +28 -0
  180. package/src/client/hooks/chat/timeline/row-window.test.ts +15 -2
  181. package/src/client/hooks/editor/use-document-annotations.ts +124 -0
  182. package/src/client/hooks/editor/use-editor-panel-ui.ts +52 -0
  183. package/src/client/hooks/editor/use-file-review-mode.ts +35 -0
  184. package/src/client/hooks/editor/use-preview-review.ts +148 -0
  185. package/src/client/hooks/settings/agents.ts +149 -0
  186. package/src/client/hooks/settings/crud-list.test.ts +28 -6
  187. package/src/client/hooks/settings/crud-list.ts +96 -57
  188. package/src/client/hooks/settings/omp-config.ts +164 -0
  189. package/src/client/hooks/settings/projects/index.ts +294 -0
  190. package/src/client/hooks/settings/projects.test.ts +237 -0
  191. package/src/client/hooks/settings/skill-catalog.ts +101 -9
  192. package/src/client/hooks/settings/skill-git-import.ts +153 -0
  193. package/src/client/hooks/settings/useTokenUsage.ts +125 -0
  194. package/src/client/hooks/settings/write-feedback.test.ts +104 -0
  195. package/src/client/hooks/settings/write-feedback.ts +63 -0
  196. package/src/client/hooks/shell/servers.test.ts +166 -0
  197. package/src/client/hooks/{desktop → shell}/servers.ts +17 -14
  198. package/src/client/hooks/ui/markdown-hydration.ts +125 -0
  199. package/src/client/hooks/ui/updates/index.test.ts +100 -1
  200. package/src/client/hooks/ui/updates/index.ts +50 -0
  201. package/src/client/hooks/ui/updates/notes.test.ts +138 -0
  202. package/src/client/hooks/ui/updates/notes.ts +57 -0
  203. package/src/client/hooks/ui/updates/shell-download.ts +1 -1
  204. package/src/client/hooks/ui/updates/shell-update.ts +2 -6
  205. package/src/client/hooks/workspace/file-row-drag.ts +41 -0
  206. package/src/client/hooks/workspace/file-tree-actions.ts +25 -1
  207. package/src/client/hooks/workspace/file-tree-edits.ts +23 -6
  208. package/src/client/hooks/workspace/root-drop-target.ts +77 -0
  209. package/src/client/hooks/workspace/unfolded-chains.ts +165 -0
  210. package/src/client/lib/browser/element-at.test.ts +229 -0
  211. package/src/client/lib/browser/element-at.ts +139 -0
  212. package/src/client/lib/desktop/dropped-paths.ts +1 -1
  213. package/src/client/lib/desktop/titlebar.test.ts +12 -3
  214. package/src/client/lib/desktop/titlebar.ts +1 -1
  215. package/src/client/lib/review/client.ts +73 -0
  216. package/src/client/lib/router/search-params.ts +42 -20
  217. package/src/client/lib/shell/desktop.ts +117 -0
  218. package/src/client/lib/shell/servers.ts +75 -0
  219. package/src/client/lib/shell/transport.ts +216 -0
  220. package/src/client/main.tsx +9 -0
  221. package/src/client/tailwind.css +65 -0
  222. package/src/server/lib/btw/lifecycle.server.ts +2 -2
  223. package/src/server/lib/db/schema.ts +7 -0
  224. package/src/server/lib/db/seed-terminal.test.ts +4 -0
  225. package/src/server/lib/fs/git-merge-conflict.test.ts +14 -1
  226. package/src/server/lib/omp/config/agent-definitions.test.ts +273 -0
  227. package/src/server/lib/omp/config/agents.ts +231 -61
  228. package/src/server/lib/omp/config/definitions.test.ts +9 -105
  229. package/src/server/lib/omp/config/extensions.ts +16 -7
  230. package/src/server/lib/omp/config/omp-config-files.test.ts +27 -0
  231. package/src/server/lib/omp/config/skill-sources.ts +49 -0
  232. package/src/server/lib/omp/config/skills-git-install.ts +155 -0
  233. package/src/server/lib/omp/config/skills-git-repo.ts +288 -0
  234. package/src/server/lib/omp/config/skills-git.test.ts +220 -0
  235. package/src/server/lib/omp/rpc/constants.test.ts +11 -0
  236. package/src/server/lib/omp/rpc/constants.ts +15 -0
  237. package/src/server/lib/omp/rpc/process.ts +11 -14
  238. package/src/server/lib/omp/rpc/session-commands.ts +6 -3
  239. package/src/server/lib/omp/rpc/utility-agent-dir.test.ts +134 -0
  240. package/src/server/lib/omp/rpc/utility-agent-dir.ts +138 -0
  241. package/src/server/lib/omp/rpc/utility.ts +12 -0
  242. package/src/server/lib/review/schema.server.ts +45 -0
  243. package/src/server/lib/review/store.server.ts +138 -0
  244. package/src/server/lib/terminal/attach-replay.test.ts +132 -0
  245. package/src/server/lib/terminal/output.test.ts +166 -0
  246. package/src/server/lib/terminal/output.ts +104 -0
  247. package/src/server/lib/terminal/runtime.server.ts +5 -0
  248. package/src/server/lib/terminal/send-result.test.ts +33 -0
  249. package/src/server/lib/terminal/send-result.ts +32 -0
  250. package/src/server/lib/terminal/session.server.ts +45 -11
  251. package/src/server/lib/terminal/store-liveness.test.ts +4 -0
  252. package/src/server/lib/updates/active-notes.test.ts +149 -0
  253. package/src/server/lib/updates/active-notes.ts +75 -0
  254. package/src/server/lib/updates/changelog-file.ts +42 -11
  255. package/src/server/lib/updates/changelog.test.ts +15 -1
  256. package/src/server/lib/updates/omp.ts +42 -15
  257. package/src/server/lib/updates/release-url.ts +27 -1
  258. package/src/server/lib/usage/index-parse.test.ts +200 -0
  259. package/src/server/lib/usage/index-parse.ts +178 -0
  260. package/src/server/lib/usage/index-query.server.ts +248 -0
  261. package/src/server/lib/usage/index-scan.server.ts +343 -0
  262. package/src/server/lib/usage/index-schema.server.ts +82 -0
  263. package/src/server/lib/usage/index.test.ts +234 -0
  264. package/src/server/lib/usage/providers.server.ts +4 -53
  265. package/src/server/lib/workspace/project-model.server.test.ts +102 -0
  266. package/src/server/lib/workspace/project-model.server.ts +47 -0
  267. package/src/server/lib/workspace/project-patch.server.ts +156 -0
  268. package/src/server/routes/agent/new.ts +8 -1
  269. package/src/server/routes/browser/index.ts +3 -0
  270. package/src/server/routes/browser/stream.ts +31 -2
  271. package/src/server/routes/browser/tabs.test.ts +94 -0
  272. package/src/server/routes/browser/tabs.ts +85 -0
  273. package/src/server/routes/index.ts +2 -0
  274. package/src/server/routes/review/bindings.ts +11 -0
  275. package/src/server/routes/review/index.ts +127 -0
  276. package/src/server/routes/review/routes.test.ts +191 -0
  277. package/src/server/routes/settings/agents.test.ts +180 -0
  278. package/src/server/routes/settings/agents.ts +99 -94
  279. package/src/server/routes/settings/mcp.test.ts +135 -0
  280. package/src/server/routes/settings/mcp.ts +14 -6
  281. package/src/server/routes/settings/projects.ts +53 -19
  282. package/src/server/routes/settings/settings-projects-routes.test.ts +214 -0
  283. package/src/server/routes/settings/settings-store-routes.test.ts +11 -115
  284. package/src/server/routes/settings/skills-catalog-actions.ts +195 -0
  285. package/src/server/routes/settings/skills.test.ts +225 -0
  286. package/src/server/routes/settings/skills.ts +18 -15
  287. package/src/server/routes/telemetry/tokens.test.ts +145 -0
  288. package/src/server/routes/telemetry/tokens.ts +70 -149
  289. package/src/server/routes/terminal/ws.ts +6 -5
  290. package/src/server/routes/updates/index.ts +2 -0
  291. package/src/server/routes/updates/notes.ts +34 -0
  292. package/src/server/routes/updates/routes.test.ts +49 -0
  293. package/src/shared/lib/browser/annotate.test.ts +283 -0
  294. package/src/shared/lib/browser/annotate.ts +231 -0
  295. package/src/shared/lib/browser/browser-viewer.test.ts +26 -4
  296. package/src/shared/lib/browser/frame-gate.test.ts +91 -0
  297. package/src/shared/lib/browser/frame-gate.ts +69 -0
  298. package/src/shared/lib/browser/frame-params.test.ts +43 -0
  299. package/src/shared/lib/browser/frame-params.ts +60 -0
  300. package/src/shared/lib/browser/frame-pipeline.test.ts +132 -0
  301. package/src/shared/lib/browser/frame-pipeline.ts +80 -0
  302. package/src/shared/lib/browser/page-context.ts +60 -4
  303. package/src/shared/lib/browser/snapshot.test.ts +115 -0
  304. package/src/shared/lib/browser/snapshot.ts +112 -0
  305. package/src/shared/lib/browser/tab-close.test.ts +74 -0
  306. package/src/shared/lib/browser/tab-close.ts +77 -0
  307. package/src/shared/lib/browser/viewer.ts +45 -26
  308. package/src/shared/lib/chat/timeline/block-chrome.ts +19 -0
  309. package/src/shared/lib/chat/timeline/tool-render-mode.ts +17 -4
  310. package/src/shared/lib/chat/tool/artifact.ts +55 -20
  311. package/src/shared/lib/chat/tool/bash-facts.ts +96 -0
  312. package/src/shared/lib/chat/tool/minimized.test.ts +98 -0
  313. package/src/shared/lib/chat/tool/minimized.ts +64 -0
  314. package/src/shared/lib/chat/tool/summary.test.ts +28 -8
  315. package/src/shared/lib/chat/tool/summary.ts +3 -32
  316. package/src/shared/lib/fs/folder-chain.test.ts +81 -1
  317. package/src/shared/lib/fs/folder-chain.ts +84 -0
  318. package/src/shared/lib/markdown/blocks/anchor.ts +63 -0
  319. package/src/shared/lib/markdown/blocks/blocks.test.ts +141 -0
  320. package/src/shared/lib/markdown/blocks/renderer.ts +120 -0
  321. package/src/shared/lib/markdown/blocks/scan.ts +100 -0
  322. package/src/shared/lib/markdown/blocks/types.ts +62 -0
  323. package/src/shared/lib/markdown/marked.ts +58 -147
  324. package/src/shared/lib/markdown/math-extensions.ts +168 -0
  325. package/src/shared/lib/markdown/review/prompt.ts +77 -0
  326. package/src/shared/lib/markdown/review/reconcile.ts +55 -0
  327. package/src/shared/lib/markdown/review/review.test.ts +96 -0
  328. package/src/shared/lib/markdown/xml-sections.test.ts +140 -0
  329. package/src/shared/lib/markdown/xml-sections.ts +139 -0
  330. package/src/shared/lib/models/provider/label.ts +57 -0
  331. package/src/shared/lib/omp/config/agent-file.test.ts +54 -0
  332. package/src/shared/lib/omp/config/agent-file.ts +43 -0
  333. package/src/shared/lib/omp/config/row-value.test.ts +95 -0
  334. package/src/shared/lib/omp/config/row-value.ts +97 -0
  335. package/src/shared/lib/omp/config/schema.test.ts +66 -0
  336. package/src/shared/lib/omp/config/schema.ts +6 -0
  337. package/src/shared/lib/omp/rpc/frame.test.ts +48 -47
  338. package/src/shared/lib/omp/rpc/frame.ts +49 -40
  339. package/src/shared/lib/omp/session/job-progress.test.ts +37 -1
  340. package/src/shared/lib/omp/session/job-progress.ts +31 -0
  341. package/src/shared/lib/omp/session/proc.ts +5 -0
  342. package/src/shared/lib/omp/session/wait.ts +5 -0
  343. package/src/shared/lib/ui/menu-anchor.test.ts +69 -0
  344. package/src/shared/lib/ui/menu-anchor.ts +89 -0
  345. package/src/shared/lib/ui/mobile-overlay.ts +61 -0
  346. package/src/shared/lib/ui/svg-scope.test.ts +97 -0
  347. package/src/shared/lib/ui/svg-scope.ts +134 -0
  348. package/src/shared/lib/usage/breakdown.test.ts +197 -0
  349. package/src/shared/lib/usage/breakdown.ts +241 -0
  350. package/src/shared/lib/usage/range.test.ts +204 -0
  351. package/src/shared/lib/usage/range.ts +240 -0
  352. package/src/shared/lib/usage/view.test.ts +85 -0
  353. package/src/shared/lib/usage/view.ts +74 -0
  354. package/src/shared/lib/workspace/project-accent.test.ts +69 -0
  355. package/src/shared/lib/workspace/project-accent.ts +63 -0
  356. package/src/shared/lib/workspace/project-icon.ts +40 -0
  357. package/src/shared/lib/workspace/project-model.test.ts +79 -0
  358. package/src/shared/lib/workspace/project-model.ts +64 -0
  359. package/src/shared/types/browser.ts +78 -0
  360. package/src/shared/types/index.ts +1 -0
  361. package/src/shared/types/settings/agent.ts +28 -6
  362. package/src/shared/types/settings/skill.ts +53 -3
  363. package/src/shared/types/settings/state.ts +4 -3
  364. package/src/shared/types/settings/write.ts +6 -0
  365. package/src/shared/types/tokenUsage.ts +128 -21
  366. package/src/shared/types/updates.ts +20 -0
  367. package/src/test-support/file-explorer-disk.test-util.ts +25 -1
  368. package/src/test-support/file-explorer-drag.test-util.ts +88 -0
  369. package/src/test-support/file-explorer.test-util.ts +47 -47
  370. package/dist/client/static/js/index-fjnq2z2d.css +0 -1
  371. package/src/client/components/common/code-surface/indent-guide.ts +0 -104
  372. package/src/client/components/common/server-switcher/index.test.tsx +0 -150
  373. package/src/client/components/settings/categories/skill-catalog/AddSourceModal.tsx +0 -133
  374. package/src/client/hooks/desktop/servers.test.ts +0 -73
  375. package/src/client/lib/desktop/bridge.ts +0 -203
  376. package/src/server/lib/omp/session/usage/aggregate-shaping.test.ts +0 -149
  377. package/src/server/lib/omp/session/usage/aggregate.test.ts +0 -243
  378. package/src/server/lib/omp/session/usage/aggregate.ts +0 -330
  379. package/src/server/lib/omp/session/usage/shaping.ts +0 -130
  380. package/src/shared/lib/code/editor/indent-guide-rule.test.ts +0 -65
  381. package/src/shared/lib/code/editor/indent-guide-rule.ts +0 -47
@@ -0,0 +1,132 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * A viewer that attaches while output is in flight must receive the stream
8
+ * exactly once: the replay's last line followed immediately by live output.
9
+ *
10
+ * The two ways this breaks are both silent, and both are duplicate/garbled text
11
+ * in xterm rather than an error. Output is appended to `history` and queued for
12
+ * delivery, so a replay captured BEFORE the queue is flushed carries the pending
13
+ * bytes and the queued frame carries them again (each line printed twice); a
14
+ * frame delivered before the replay arrives ahead of it in the wrong order.
15
+ * `attachTerminal` flushes first for exactly this reason, and this is the test
16
+ * that catches its removal.
17
+ *
18
+ * A REAL PTY on purpose: the seam only exists because reads and frames are
19
+ * different things, and a fake producer would have to reproduce Bun's read sizes
20
+ * to reproduce it. The assertions are on line numbers, which is what makes a gap
21
+ * or a duplicate visible at all.
22
+ */
23
+
24
+ import { afterAll, expect, test } from 'bun:test';
25
+ import { attachTerminal, forgetTerminal, writeTerminalInput } from '@/server/lib/terminal/runtime.server';
26
+ import type { TerminalViewer } from '@/server/lib/terminal/session.server';
27
+
28
+ const dec = new TextDecoder();
29
+ const TOTAL = 30_000;
30
+
31
+ interface Collected {
32
+ viewer: TerminalViewer;
33
+ frames: Uint8Array[];
34
+ text: () => string;
35
+ }
36
+
37
+ function collector(): Collected {
38
+ const frames: Uint8Array[] = [];
39
+ return {
40
+ viewer: {
41
+ send(frame) {
42
+ if (typeof frame !== 'string') frames.push(frame);
43
+ return true;
44
+ },
45
+ drop() {},
46
+ },
47
+ frames,
48
+ text: () => dec.decode(join(frames)),
49
+ };
50
+ }
51
+
52
+ function join(parts: Uint8Array[]): Uint8Array {
53
+ const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
54
+ let offset = 0;
55
+ for (const part of parts) {
56
+ out.set(part, offset);
57
+ offset += part.length;
58
+ }
59
+ return out;
60
+ }
61
+
62
+ /** The numbered lines in `text`, in arrival order. */
63
+ function numbers(text: string): number[] {
64
+ return text
65
+ .split('\n')
66
+ .map((line) => line.replace(/\r$/, '').trim())
67
+ .filter((line) => /^\d+$/.test(line))
68
+ .map(Number);
69
+ }
70
+
71
+ /** `null` when every line follows the previous one, else the offending pair. */
72
+ function gap(sequence: number[]): string | null {
73
+ for (let i = 1; i < sequence.length; i++) {
74
+ if (sequence[i] !== sequence[i - 1] + 1) return `${sequence[i - 1]} -> ${sequence[i]} at ${i}`;
75
+ }
76
+ return null;
77
+ }
78
+
79
+ async function until(predicate: () => boolean, timeoutMs = 20_000): Promise<boolean> {
80
+ const started = Date.now();
81
+ while (Date.now() - started < timeoutMs) {
82
+ if (predicate()) return true;
83
+ await Bun.sleep(5);
84
+ }
85
+ return false;
86
+ }
87
+
88
+ const ids: string[] = [];
89
+
90
+ afterAll(() => {
91
+ for (const id of ids.splice(0)) forgetTerminal(id);
92
+ });
93
+
94
+ test('a viewer attaching mid-stream sees the replay and live output exactly once', async () => {
95
+ const id = `attach-replay-${Bun.randomUUIDv7()}`;
96
+ ids.push(id);
97
+
98
+ const first = collector();
99
+ await attachTerminal(first.viewer, { id, cols: 100, rows: 30, theme: 'dark' });
100
+
101
+ writeTerminalInput(id, new TextEncoder().encode(`seq 1 ${TOTAL}\r`));
102
+ expect(await until(() => numbers(first.text()).length > 2_000)).toBe(true);
103
+
104
+ // Mid-flood by construction: the shell is emitting, the first viewer is
105
+ // receiving, and the coalescer holds bytes that history already has.
106
+ const second = collector();
107
+ const attachment = await attachTerminal(second.viewer, { id, cols: 100, rows: 30, theme: 'dark' });
108
+ const replayed = numbers(dec.decode(attachment.replay));
109
+
110
+ expect(await until(() => numbers(first.text()).at(-1) === TOTAL)).toBe(true);
111
+ expect(await until(() => numbers(second.text()).at(-1) === TOTAL)).toBe(true);
112
+
113
+ const firstLines = numbers(first.text());
114
+ const secondLines = numbers(second.text());
115
+
116
+ // The viewer there from the start saw every line once, in order.
117
+ expect(gap(firstLines)).toBeNull();
118
+ expect(firstLines.length).toBe(new Set(firstLines).size);
119
+ expect(firstLines.at(-1)).toBe(TOTAL);
120
+
121
+ // The late viewer's replay is the retained scrollback, contiguous…
122
+ expect(replayed.length).toBeGreaterThan(0);
123
+ expect(gap(replayed)).toBeNull();
124
+
125
+ // …and its live stream continues from the replay's last line: not one line
126
+ // earlier (a duplicate) and not one line later (a gap).
127
+ expect(secondLines.length).toBeGreaterThan(0);
128
+ expect(secondLines[0]).toBe((replayed.at(-1) ?? 0) + 1);
129
+ expect(gap([replayed.at(-1) ?? 0, ...secondLines])).toBeNull();
130
+ expect(new Set(secondLines).size).toBe(secondLines.length);
131
+ expect(secondLines.at(-1)).toBe(TOTAL);
132
+ }, 60_000);
@@ -0,0 +1,166 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The coalescer is a byte-stream transformer, so the assertions are about the
8
+ * stream and not about the queue: the concatenation of the frames a viewer
9
+ * receives must equal the concatenation of the reads, in the same order, and the
10
+ * framing must be bounded.
11
+ *
12
+ * Two failures it must not have, both of which xterm renders as garbage rather
13
+ * than as an error: dropping a trailing partial frame (a prompt that never
14
+ * appears until the next keypress) and reordering (an escape sequence split
15
+ * across two reads, reassembled after a later one).
16
+ *
17
+ * Time is driven with fake timers: a real `setTimeout` wait would make every run
18
+ * pay the flush delay and would fail as a timeout under load instead of pointing
19
+ * at the ordering rule that broke.
20
+ */
21
+
22
+ import { afterEach, describe, expect, test, vi } from 'bun:test';
23
+ import {
24
+ OUTPUT_FLUSH_BYTES,
25
+ OUTPUT_FLUSH_MS,
26
+ createTerminalOutputQueue,
27
+ } from '@/server/lib/terminal/output';
28
+
29
+ const enc = new TextEncoder();
30
+ const dec = new TextDecoder();
31
+
32
+ afterEach(() => {
33
+ vi.useRealTimers();
34
+ });
35
+
36
+ function collector(): { frames: Uint8Array[]; sink: (frame: Uint8Array) => void; text: () => string } {
37
+ const frames: Uint8Array[] = [];
38
+ return {
39
+ frames,
40
+ sink: (frame) => frames.push(frame),
41
+ text: () => dec.decode(join(frames)),
42
+ };
43
+ }
44
+
45
+ function join(parts: Uint8Array[]): Uint8Array {
46
+ const total = parts.reduce((sum, part) => sum + part.length, 0);
47
+ const out = new Uint8Array(total);
48
+ let offset = 0;
49
+ for (const part of parts) {
50
+ out.set(part, offset);
51
+ offset += part.length;
52
+ }
53
+ return out;
54
+ }
55
+
56
+ describe('createTerminalOutputQueue', () => {
57
+ test('a burst of reads leaves as one frame, in order, byte for byte', () => {
58
+ vi.useFakeTimers();
59
+ const { frames, sink, text } = collector();
60
+ const queue = createTerminalOutputQueue(sink);
61
+
62
+ const lines = Array.from({ length: 200 }, (_, i) => `line ${i}\r\n`);
63
+ for (const line of lines) queue.push(enc.encode(line));
64
+ expect(frames.length).toBe(0);
65
+ vi.advanceTimersByTime(OUTPUT_FLUSH_MS + 1);
66
+
67
+ expect(frames.length).toBe(1);
68
+ expect(text()).toBe(lines.join(''));
69
+ queue.dispose();
70
+ });
71
+
72
+ test('pending bytes are flushed by the timer, once', () => {
73
+ vi.useFakeTimers();
74
+ const { frames, sink, text } = collector();
75
+ const queue = createTerminalOutputQueue(sink);
76
+
77
+ queue.push(enc.encode('hello'));
78
+ expect(frames.length).toBe(0);
79
+ vi.advanceTimersByTime(OUTPUT_FLUSH_MS + 1);
80
+ expect(frames.length).toBe(1);
81
+ expect(text()).toBe('hello');
82
+
83
+ // A second tick must not re-send it: the timer is one-shot, not an interval.
84
+ vi.advanceTimersByTime(OUTPUT_FLUSH_MS + 1);
85
+ expect(frames.length).toBe(1);
86
+ queue.dispose();
87
+ });
88
+
89
+ test('crossing the size threshold delivers without waiting', () => {
90
+ vi.useFakeTimers();
91
+ const { frames, sink } = collector();
92
+ const queue = createTerminalOutputQueue(sink);
93
+
94
+ const half = new Uint8Array(OUTPUT_FLUSH_BYTES / 2).fill(0x41);
95
+ queue.push(half);
96
+ expect(frames.length).toBe(0);
97
+ queue.push(half);
98
+ expect(frames.length).toBe(1);
99
+ expect(frames[0].length).toBe(OUTPUT_FLUSH_BYTES);
100
+
101
+ // The timer that the first read armed was cancelled, not left to fire twice.
102
+ vi.advanceTimersByTime(OUTPUT_FLUSH_MS + 1);
103
+ expect(frames.length).toBe(1);
104
+ queue.dispose();
105
+ });
106
+
107
+ test('a lone read reaches the sink as the same bytes, not a copy', () => {
108
+ const { frames, sink } = collector();
109
+ const queue = createTerminalOutputQueue(sink);
110
+
111
+ const read = enc.encode('one read');
112
+ queue.push(read);
113
+ queue.flush();
114
+
115
+ expect(frames[0]).toBe(read);
116
+ queue.dispose();
117
+ });
118
+
119
+ test('an escape sequence split across reads survives the frame boundary', () => {
120
+ vi.useFakeTimers();
121
+ const { sink, text } = collector();
122
+ const queue = createTerminalOutputQueue(sink);
123
+
124
+ // Exactly what a PTY does to a colour sequence: the split falls inside it.
125
+ queue.push(enc.encode('\x1b[3'));
126
+ queue.push(enc.encode('8;5;196mred'));
127
+ vi.advanceTimersByTime(OUTPUT_FLUSH_MS + 1);
128
+ queue.push(enc.encode('\x1b[0m'));
129
+ queue.flush();
130
+
131
+ expect(text()).toBe('\x1b[38;5;196mred\x1b[0m');
132
+ queue.dispose();
133
+ });
134
+
135
+ test('an empty read is ignored and arms nothing', () => {
136
+ vi.useFakeTimers();
137
+ const { frames, sink } = collector();
138
+ const queue = createTerminalOutputQueue(sink);
139
+
140
+ queue.push(new Uint8Array(0));
141
+ vi.advanceTimersByTime(OUTPUT_FLUSH_MS + 1);
142
+ queue.flush();
143
+ expect(frames.length).toBe(0);
144
+ queue.dispose();
145
+ });
146
+
147
+ test('flush with nothing pending sends nothing', () => {
148
+ const { frames, sink } = collector();
149
+ const queue = createTerminalOutputQueue(sink);
150
+ queue.flush();
151
+ expect(frames.length).toBe(0);
152
+ queue.dispose();
153
+ });
154
+
155
+ test('dispose drops the pending bytes and the armed timer', () => {
156
+ vi.useFakeTimers();
157
+ const { frames, sink } = collector();
158
+ const queue = createTerminalOutputQueue(sink);
159
+
160
+ queue.push(enc.encode('never delivered'));
161
+ queue.dispose();
162
+ vi.advanceTimersByTime(OUTPUT_FLUSH_MS + 1);
163
+ queue.flush();
164
+ expect(frames.length).toBe(0);
165
+ });
166
+ });
@@ -0,0 +1,104 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Coalesces PTY reads into one frame per flush.
8
+ *
9
+ * `Bun.Terminal` hands its `data` callback whatever one read returned, which for
10
+ * a line-oriented producer is tiny: `seq 1 300000` arrived as 182,259 reads,
11
+ * p50 = 12 bytes, 419 reads/ms. Forwarding each read as its own WebSocket frame
12
+ * (what the session used to do) spends the socket on framing instead of bytes:
13
+ * 249,349 frames carried 33.7 MB at 2.12 MB/s, and the same output coalesced
14
+ * into ~1,300 frames reached 6.9–7.3 MB/s — 3.3× on the same xterm, and the
15
+ * ceiling was then the PTY producer itself, not the client.
16
+ *
17
+ * Three things this deliberately does not do:
18
+ *
19
+ * - **Copy on push.** Bun does not reuse the buffer it hands `data` (verified
20
+ * against 1.4.4: 2,000 `seq` lines collected across 1,104 reads and
21
+ * concatenated after exit are byte-identical), and `history.append` already
22
+ * retains those views for its 512 KiB scrollback, so a defensive copy per
23
+ * read would cost exactly what the coalescing is there to save.
24
+ * - **Split sequences.** xterm parses a byte stream across `write` calls, so a
25
+ * frame boundary mid-escape is harmless — dropping bytes is not, which is why
26
+ * a flush never discards anything it accepted.
27
+ * - **Buffer without a bound.** The flush is size- or time-triggered, so a
28
+ * flood becomes 8 KiB frames instead of growing a queue.
29
+ */
30
+
31
+ /** Quiet period before a partial frame is flushed: two 60 Hz frames' worth. */
32
+ export const OUTPUT_FLUSH_MS = 4;
33
+
34
+ /** Pending bytes that force a flush without waiting for the timer. */
35
+ export const OUTPUT_FLUSH_BYTES = 8 * 1024;
36
+
37
+ export interface TerminalOutputQueue {
38
+ /** Accept one PTY read. Delivered now if the frame is already full. */
39
+ push: (bytes: Uint8Array) => void;
40
+ /** Deliver everything pending — used before a replay and before control frames. */
41
+ flush: () => void;
42
+ /** Drop pending bytes and the timer; the session record is going away. */
43
+ dispose: () => void;
44
+ }
45
+
46
+ /**
47
+ * One queue per PTY session. `sink` receives the concatenated frame and is the
48
+ * session's own fan-out, so a queue never has to know about viewers.
49
+ */
50
+ export function createTerminalOutputQueue(sink: (frame: Uint8Array) => void): TerminalOutputQueue {
51
+ let pending: Uint8Array[] = [];
52
+ let pendingBytes = 0;
53
+ let timer: ReturnType<typeof setTimeout> | null = null;
54
+
55
+ const flush = () => {
56
+ if (timer !== null) {
57
+ clearTimeout(timer);
58
+ timer = null;
59
+ }
60
+ if (pendingBytes === 0) return;
61
+ // A single read is passed through: on `cat` of a large file most flushes
62
+ // are one 1 KiB read, and a copy there would buy nothing.
63
+ const frame = pending.length === 1 ? pending[0] : join(pending, pendingBytes);
64
+ pending = [];
65
+ pendingBytes = 0;
66
+ sink(frame);
67
+ };
68
+
69
+ return {
70
+ push(bytes) {
71
+ if (bytes.length === 0) return;
72
+ pending.push(bytes);
73
+ pendingBytes += bytes.length;
74
+ if (pendingBytes >= OUTPUT_FLUSH_BYTES) {
75
+ flush();
76
+ return;
77
+ }
78
+ if (timer === null) {
79
+ timer = setTimeout(flush, OUTPUT_FLUSH_MS);
80
+ // A pending flush must never hold the server open at shutdown.
81
+ timer.unref?.();
82
+ }
83
+ },
84
+ flush,
85
+ dispose() {
86
+ if (timer !== null) {
87
+ clearTimeout(timer);
88
+ timer = null;
89
+ }
90
+ pending = [];
91
+ pendingBytes = 0;
92
+ },
93
+ };
94
+ }
95
+
96
+ function join(parts: Uint8Array[], total: number): Uint8Array {
97
+ const frame = new Uint8Array(total);
98
+ let offset = 0;
99
+ for (const part of parts) {
100
+ frame.set(part, offset);
101
+ offset += part.length;
102
+ }
103
+ return frame;
104
+ }
@@ -55,6 +55,11 @@ const resizeTimers = registry.resizeTimers;
55
55
  export async function attachTerminal(viewer: TerminalViewer, request: AttachRequest): Promise<TerminalAttachment> {
56
56
  const session = await openTerminal(request);
57
57
 
58
+ // Pending bytes are already in history, so they have to leave the coalescer
59
+ // BEFORE the replay is captured: delivered after, the viewer would receive
60
+ // them twice; captured first, they would be missing from the replay and then
61
+ // arrive out of order. Either way xterm shows duplicated or shuffled lines.
62
+ session.output.flush();
58
63
  const replay = session.history.replay();
59
64
  const snapshot = snapshotOf(session);
60
65
  session.viewers.add(viewer);
@@ -0,0 +1,33 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The two halves of Bun's `send` contract that used to be read backwards: `-1`
8
+ * is "queued, draining" and `0` is "dropped". Both directions are asserted,
9
+ * because a mapping that answers `true` everywhere is as broken as one that
10
+ * answers `false` everywhere — it just fails on the other side.
11
+ */
12
+
13
+ import { describe, expect, test } from 'bun:test';
14
+ import { frameAccepted } from '@/server/lib/terminal/send-result';
15
+
16
+ describe('frameAccepted', () => {
17
+ test('bytes queued is a delivery', () => {
18
+ expect(frameAccepted(1)).toBe(true);
19
+ expect(frameAccepted(65_536)).toBe(true);
20
+ });
21
+
22
+ test('backpressure is still a delivery', () => {
23
+ // Bun enqueued the frame and promises a `drain`; closing the viewer here
24
+ // killed healthy terminals at the first burst.
25
+ expect(frameAccepted(-1)).toBe(true);
26
+ });
27
+
28
+ test('zero is the only drop', () => {
29
+ // Closed socket, or past the 16 MiB backpressure limit: the frame is lost,
30
+ // so the viewer must be dropped and the client must replay.
31
+ expect(frameAccepted(0)).toBe(false);
32
+ });
33
+ });
@@ -0,0 +1,32 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * What `Bun.ServerWebSocket.send`'s return value means — the one fact the
8
+ * terminal's drop rule rests on, kept here because both readings of it are
9
+ * silent failures.
10
+ *
11
+ * Bun 1.4.4 (`bun.com/docs/runtime/websockets`, Backpressure):
12
+ *
13
+ * - **`> 0`** — that many bytes were queued. Sent.
14
+ * - **`-1`** — queued *with backpressure*: the socket is over its high-water
15
+ * mark, and Bun calls `drain` once the buffered data has been written. **The
16
+ * frame is delivered.** This is the normal state of a terminal under a burst.
17
+ * - **`0`** — **dropped**: the connection is closed, or it already buffered
18
+ * more than `backpressureLimit` (16 MiB by default). The bytes are gone.
19
+ *
20
+ * Reading `-1` as failure closes a healthy viewer at the first burst; reading
21
+ * `0` as success is worse, because the client keeps xterm attached to a stream
22
+ * with a hole in it — exactly the mid-sequence corruption the drop rule exists
23
+ * to prevent. Measured against Bun 1.4.4, 20,000 frames of 4 KiB: the old
24
+ * `!== -1` rule stopped at frame 160 (655 KiB, 0.8 %) while the socket was
25
+ * still accepting, and a 40,000 × 1 KiB burst returned `-1` 17,870 times and
26
+ * `0` 20,851 times.
27
+ *
28
+ * Never call this with an empty frame: `send('')` succeeds but reports `0`.
29
+ */
30
+ export function frameAccepted(result: number): boolean {
31
+ return result !== 0;
32
+ }
@@ -29,6 +29,14 @@
29
29
  *
30
30
  * A fourth: a PTY read may split a multi-byte character, so bytes are forwarded
31
31
  * verbatim and xterm's own streaming decoder reassembles them.
32
+ *
33
+ * A fifth, and the reason `output.ts` exists: **reads are coalesced into frames,
34
+ * never forwarded one-per-read**. One read is one line for a line-oriented
35
+ * producer (`seq 1 300000` arrived as 182,259 reads, p50 = 12 bytes), so
36
+ * framing each read spent the socket on headers: measured end to end, 249,349
37
+ * frames carried 33.7 MB at 2.12 MB/s, and the same bytes coalesced reached
38
+ * 6.9–7.3 MB/s — where the PTY producer, not the client, was the ceiling. The
39
+ * ordering rule that comes with it is stated at `attachTerminal`.
32
40
  */
33
41
 
34
42
  import { resolveRoot } from '@/server/lib/fs/root';
@@ -37,6 +45,7 @@ import { scopeToRepo } from '@/server/lib/fs/repo-scope';
37
45
  import { describeSpawnFailure } from '@/server/lib/lifecycle/fd-pressure';
38
46
  import { killProcessTree } from '@/server/lib/lifecycle/kill-tree';
39
47
  import { createTerminalHistory, type TerminalHistory } from '@/server/lib/terminal/history';
48
+ import { createTerminalOutputQueue, type TerminalOutputQueue } from '@/server/lib/terminal/output';
40
49
  import { resolveShellExecutable, shellCandidates, shellLaunch, terminalEnv } from '@/server/lib/terminal/shell';
41
50
  import { shellSpawnOptions } from '@/server/lib/terminal/spawn';
42
51
  import {
@@ -50,13 +59,14 @@ export const TERMINATION_GRACE_MS = 1000;
50
59
  /** A socket attached to a terminal. Output is raw PTY bytes; control is JSON. */
51
60
  export interface TerminalViewer {
52
61
  /**
53
- * Deliver one frame. Returns false when the viewer could not accept it —
54
- * the socket's send buffer is over its high-water mark — which the session
55
- * treats as "this viewer is gone": a PTY producer cannot be paused, so the
56
- * alternative is buffering unbounded output in a socket nobody is reading.
62
+ * Deliver one frame. Returns false only when it was DROPPED — not when the
63
+ * socket merely reported backpressure, which Bun's `send` does with `-1` and
64
+ * still delivers (see `send-result.ts`). A false return means this viewer can
65
+ * no longer be trusted with the byte stream: the PTY cannot be paused, so the
66
+ * session drops it and the client replays from history on reconnect.
57
67
  */
58
68
  send(frame: string | Uint8Array): boolean;
59
- /** Detach this viewer. Called when `send` reports it cannot keep up. */
69
+ /** Detach this viewer. Called when `send` reports the frame was dropped. */
60
70
  drop(): void;
61
71
  }
62
72
 
@@ -67,6 +77,8 @@ export interface TerminalSession {
67
77
  term: Bun.Terminal;
68
78
  proc: Bun.Subprocess | null;
69
79
  history: TerminalHistory;
80
+ /** Pending PTY bytes, framed on a timer or a size threshold. See `output.ts`. */
81
+ output: TerminalOutputQueue;
70
82
  viewers: Set<TerminalViewer>;
71
83
  cols: number;
72
84
  rows: number;
@@ -82,13 +94,13 @@ export interface TerminalSession {
82
94
  /**
83
95
  * Deliver `frame` to every viewer, dropping the ones that cannot keep up.
84
96
  *
85
- * `Bun.ServerWebSocket.send` returns the bytes queued, or `-1` when the socket
86
- * is over its high-water mark and the frame was NOT sent (verified on 1.4.2:
87
- * 40 sends of 1 MiB to a socket nobody reads all return `-1`). A viewer that
88
- * reports `-1` is closed rather than skipped — skipping would leave xterm's
97
+ * A viewer reports false only for a real drop (`send-result.ts` owns that
98
+ * contract: Bun's `-1` means "queued, draining" and `0` means "dropped"). A
99
+ * dropped viewer is closed rather than skipped — skipping would leave xterm's
89
100
  * parser mid-sequence, so the honest outcome is a reconnect that replays the
90
101
  * scrollback. The PTY cannot be paused, so this is the only backpressure a
91
- * terminal has.
102
+ * terminal has; coalescing in `output.ts` is what keeps it from firing on a
103
+ * producer that simply emits many small reads.
92
104
  */
93
105
  export function fanOut(session: TerminalSession, frame: string | Uint8Array): void {
94
106
  for (const viewer of session.viewers) {
@@ -135,6 +147,8 @@ export async function createSession(request: AttachRequest): Promise<TerminalSes
135
147
  term: undefined as unknown as Bun.Terminal,
136
148
  proc: null,
137
149
  history: createTerminalHistory(),
150
+ // Same reason as `term`: the queue's sink fans out through `session`.
151
+ output: undefined as unknown as TerminalOutputQueue,
138
152
  viewers: new Set(),
139
153
  cols: size.cols,
140
154
  rows: size.rows,
@@ -146,14 +160,21 @@ export async function createSession(request: AttachRequest): Promise<TerminalSes
146
160
  lastActivity: Date.now(),
147
161
  };
148
162
 
163
+ session.output = createTerminalOutputQueue((frame) => fanOut(session, frame));
164
+
149
165
  const term = new Bun.Terminal({
150
166
  cols: size.cols,
151
167
  rows: size.rows,
152
168
  name: 'xterm-256color',
153
169
  data(_term, bytes) {
170
+ // History first, then the frame: every byte that can reach a viewer is
171
+ // already replayable, which is what lets `attachTerminal` flush and then
172
+ // capture a replay without the two ever overlapping.
154
173
  session.history.append(bytes);
155
174
  session.lastActivity = Date.now();
156
- fanOut(session, bytes);
175
+ // Nobody watching: the replay carries it on the next attach, so there is
176
+ // nothing to frame — and an unwatched session pays no queue cost at all.
177
+ if (session.viewers.size > 0) session.output.push(bytes);
157
178
  },
158
179
  });
159
180
  session.term = term;
@@ -180,6 +201,10 @@ export async function createSession(request: AttachRequest): Promise<TerminalSes
180
201
  session.exitCode = code ?? null;
181
202
  session.signal = signalName(proc.signalCode);
182
203
  session.lastActivity = Date.now();
204
+ // Queued output is older than this frame. Flushing first keeps xterm's
205
+ // order honest: otherwise the shell's last bytes would print after the
206
+ // notice that the shell is gone.
207
+ session.output.flush();
183
208
  const frame = JSON.stringify({ t: 'exit', exitCode: session.exitCode, signal: session.signal });
184
209
  fanOut(session, frame);
185
210
  });
@@ -248,7 +273,16 @@ export function signalGroup(session: TerminalSession, signal: NodeJS.Signals): v
248
273
  killProcessTree(pid, signal === 'SIGKILL', signal);
249
274
  }
250
275
 
276
+ /**
277
+ * Release the PTY and anything still queued for it.
278
+ *
279
+ * The coalescer's timer and its pending bytes are dropped here rather than at
280
+ * each caller: every path that closes the stream (spawn failure, `forgetTerminal`,
281
+ * process exit) leaves no viewer to deliver them to, and an armed timer would
282
+ * otherwise keep the process alive for another flush tick.
283
+ */
251
284
  export function closeTerminalStream(session: TerminalSession): void {
285
+ session.output.dispose();
252
286
  try {
253
287
  session.term.close();
254
288
  } catch {
@@ -30,6 +30,7 @@ import { attachTerminal, disposeAllTerminals } from '@/server/lib/terminal/runti
30
30
  import { terminalStore, type TerminalStore, type TerminalTimeout } from '@/server/lib/terminal/store';
31
31
  import { countLiveTerminals, distinguishesIdleShells, listTerminals } from '@/server/lib/terminal/liveness.server';
32
32
  import type { TerminalSession, TerminalViewer } from '@/server/lib/terminal/session.server';
33
+ import { createTerminalOutputQueue } from '@/server/lib/terminal/output';
33
34
  import { join } from 'node:path';
34
35
  import { describePosix, testPosix } from '@/test-support/platform';
35
36
 
@@ -44,6 +45,9 @@ function fakeSession(over: Partial<TerminalSession> & { id: string }): TerminalS
44
45
  term: undefined as unknown as Bun.Terminal,
45
46
  proc: null,
46
47
  history: { replay: () => '' } as unknown as TerminalSession['history'],
48
+ // The real queue, not a stub: `disposeAllTerminals` disposes it, and a
49
+ // shape-only fake would hide a missing `dispose` at exactly that point.
50
+ output: createTerminalOutputQueue(() => {}),
47
51
  viewers: new Set(),
48
52
  cols: 80,
49
53
  rows: 24,