@kabmo-labs/kabmo 0.11.1 → 0.12.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 (324) hide show
  1. package/README.md +67 -421
  2. package/dist/client/index.html +1 -1
  3. package/dist/client/index.js +426 -413
  4. package/dist/client/static/js/{index-amss8pge.js → index-0smc9gm2.js} +1123 -747
  5. package/dist/client/static/js/index-shexbk5f.css +1 -0
  6. package/marketplace/marketplace.json +13 -3
  7. package/marketplace/plugins/command-runner/package.json +4 -2
  8. package/marketplace/plugins/git-forge/README.md +219 -0
  9. package/marketplace/plugins/git-forge/icon.svg +20 -0
  10. package/marketplace/plugins/git-forge/package.json +56 -0
  11. package/marketplace/plugins/git-forge/src/app.tsx +82 -0
  12. package/marketplace/plugins/git-forge/src/command.test.ts +181 -0
  13. package/marketplace/plugins/git-forge/src/command.ts +119 -0
  14. package/marketplace/plugins/git-forge/src/header.tsx +87 -0
  15. package/marketplace/plugins/git-forge/src/panel/Badge.tsx +76 -0
  16. package/marketplace/plugins/git-forge/src/panel/Change.tsx +150 -0
  17. package/marketplace/plugins/git-forge/src/panel/CiBadge.tsx +51 -0
  18. package/marketplace/plugins/git-forge/src/panel/Credential.tsx +107 -0
  19. package/marketplace/plugins/git-forge/src/panel/Glyph.tsx +70 -0
  20. package/marketplace/plugins/git-forge/src/panel/Header.tsx +255 -0
  21. package/marketplace/plugins/git-forge/src/panel/ItemView.tsx +198 -0
  22. package/marketplace/plugins/git-forge/src/panel/List.tsx +89 -0
  23. package/marketplace/plugins/git-forge/src/panel/Row.tsx +68 -0
  24. package/marketplace/plugins/git-forge/src/panel/Sidebar.tsx +94 -0
  25. package/marketplace/plugins/git-forge/src/panel/Write.tsx +236 -0
  26. package/marketplace/plugins/git-forge/src/panel/format.ts +78 -0
  27. package/marketplace/plugins/git-forge/src/panel/index.test.tsx +344 -0
  28. package/marketplace/plugins/git-forge/src/panel/index.tsx +193 -0
  29. package/marketplace/plugins/git-forge/src/panel/use-forge.ts +250 -0
  30. package/marketplace/plugins/git-forge/src/panel/write.test.tsx +269 -0
  31. package/marketplace/plugins/git-forge/src/protocol.ts +308 -0
  32. package/marketplace/plugins/git-forge/src/server/adapters.test.ts +274 -0
  33. package/marketplace/plugins/git-forge/src/server/bitbucket.ts +307 -0
  34. package/marketplace/plugins/git-forge/src/server/capabilities.test.ts +116 -0
  35. package/marketplace/plugins/git-forge/src/server/capabilities.ts +105 -0
  36. package/marketplace/plugins/git-forge/src/server/ci.test.ts +88 -0
  37. package/marketplace/plugins/git-forge/src/server/ci.ts +118 -0
  38. package/marketplace/plugins/git-forge/src/server/context.ts +76 -0
  39. package/marketplace/plugins/git-forge/src/server/diff.test.ts +127 -0
  40. package/marketplace/plugins/git-forge/src/server/diff.ts +120 -0
  41. package/marketplace/plugins/git-forge/src/server/filters.test.ts +138 -0
  42. package/marketplace/plugins/git-forge/src/server/filters.ts +138 -0
  43. package/marketplace/plugins/git-forge/src/server/forges.test.ts +235 -0
  44. package/marketplace/plugins/git-forge/src/server/gitea.ts +296 -0
  45. package/marketplace/plugins/git-forge/src/server/github-extras.ts +92 -0
  46. package/marketplace/plugins/git-forge/src/server/github.ts +320 -0
  47. package/marketplace/plugins/git-forge/src/server/gitlab-detail.ts +207 -0
  48. package/marketplace/plugins/git-forge/src/server/gitlab.test.ts +195 -0
  49. package/marketplace/plugins/git-forge/src/server/gitlab.ts +176 -0
  50. package/marketplace/plugins/git-forge/src/server/http.test.ts +270 -0
  51. package/marketplace/plugins/git-forge/src/server/http.ts +329 -0
  52. package/marketplace/plugins/git-forge/src/server/map.ts +120 -0
  53. package/marketplace/plugins/git-forge/src/server/registry.ts +47 -0
  54. package/marketplace/plugins/git-forge/src/server/remote.test.ts +146 -0
  55. package/marketplace/plugins/git-forge/src/server/remote.ts +188 -0
  56. package/marketplace/plugins/git-forge/src/server/scope-probe.test.ts +98 -0
  57. package/marketplace/plugins/git-forge/src/server/scope-probe.ts +128 -0
  58. package/marketplace/plugins/git-forge/src/server/scope.ts +66 -0
  59. package/marketplace/plugins/git-forge/src/server/test-context.ts +67 -0
  60. package/marketplace/plugins/git-forge/src/server/test-host.ts +51 -0
  61. package/marketplace/plugins/git-forge/src/server/token.test.ts +107 -0
  62. package/marketplace/plugins/git-forge/src/server/token.ts +139 -0
  63. package/marketplace/plugins/git-forge/src/server/write-http.test.ts +127 -0
  64. package/marketplace/plugins/git-forge/src/server/write-http.ts +110 -0
  65. package/marketplace/plugins/git-forge/src/server/writes.test.ts +218 -0
  66. package/marketplace/plugins/git-forge/src/server/writes.ts +313 -0
  67. package/marketplace/plugins/git-forge/src/server.ts +284 -0
  68. package/marketplace/plugins/git-forge/tsconfig.json +16 -0
  69. package/marketplace/plugins/session-info/package.json +4 -2
  70. package/marketplace/plugins/stats/package.json +4 -2
  71. package/package.json +6 -1
  72. package/src/client/components/common/code-surface/blame-hover.ts +188 -0
  73. package/src/client/components/common/code-surface/blame-panel.test.ts +304 -0
  74. package/src/client/components/common/code-surface/blame-panel.ts +306 -0
  75. package/src/client/components/common/code-surface/blame.test.ts +303 -0
  76. package/src/client/components/common/code-surface/blame.ts +227 -0
  77. package/src/client/components/common/code-surface/conflict-markers.test.ts +135 -0
  78. package/src/client/components/common/code-surface/conflict-markers.ts +144 -0
  79. package/src/client/components/common/code-surface/documents.ts +48 -1
  80. package/src/client/components/common/code-surface/extensions.test.ts +4 -0
  81. package/src/client/components/common/code-surface/extensions.ts +44 -0
  82. package/src/client/components/common/code-surface/fold-stack.test.ts +4 -0
  83. package/src/client/components/common/code-surface/indent.test.ts +5 -0
  84. package/src/client/components/common/code-surface/index.tsx +16 -2
  85. package/src/client/components/common/code-surface/lint-parsers.test.ts +109 -0
  86. package/src/client/components/common/code-surface/lint-parsers.ts +134 -0
  87. package/src/client/components/common/code-surface/lint.test.ts +101 -0
  88. package/src/client/components/common/code-surface/lint.ts +85 -0
  89. package/src/client/components/common/code-surface/props.ts +17 -0
  90. package/src/client/components/common/code-surface/surface-failures.test.ts +132 -0
  91. package/src/client/components/common/code-surface/theme.ts +71 -0
  92. package/src/client/components/common/header-controls/index.test.tsx +1 -1
  93. package/src/client/components/common/header-controls/plugin-entry.test.tsx +1 -1
  94. package/src/client/components/common/header-controls/shell-chrome.test.tsx +1 -1
  95. package/src/client/components/common/provider-icon/Plate.tsx +88 -0
  96. package/src/client/components/common/provider-icon/index.tsx +55 -11
  97. package/src/client/components/layout/session-sidebar/SessionsView.tsx +5 -2
  98. package/src/client/components/mobile/SessionSidebar.tsx +2 -10
  99. package/src/client/components/mobile/mobile-right-sidebar/FullEditor.tsx +6 -0
  100. package/src/client/components/mobile/mobile-right-sidebar/StatusBar.tsx +8 -0
  101. package/src/client/components/settings/categories/AppearanceSettings.tsx +3 -0
  102. package/src/client/components/settings/categories/ProviderSettings.tsx +43 -41
  103. package/src/client/components/settings/categories/appearance-settings/EditorBlameSection.tsx +97 -0
  104. package/src/client/components/settings/categories/panel-plugins/AvailableList.tsx +106 -54
  105. package/src/client/components/settings/categories/panel-plugins/GitFreshness.tsx +14 -1
  106. package/src/client/components/settings/categories/panel-plugins/InstalledList.tsx +39 -150
  107. package/src/client/components/settings/categories/panel-plugins/Meta.test.tsx +143 -0
  108. package/src/client/components/settings/categories/panel-plugins/Meta.tsx +157 -0
  109. package/src/client/components/settings/categories/panel-plugins/Placement.test.tsx +149 -0
  110. package/src/client/components/settings/categories/panel-plugins/Placement.tsx +99 -0
  111. package/src/client/components/settings/categories/panel-plugins/PluginCard.tsx +270 -0
  112. package/src/client/components/settings/categories/panel-plugins/Section.tsx +11 -3
  113. package/src/client/components/settings/categories/provider-settings/AddModelModal.tsx +25 -0
  114. package/src/client/components/settings/categories/provider-settings/AuthSection.tsx +135 -80
  115. package/src/client/components/settings/categories/provider-settings/DeleteProviderModal.tsx +51 -21
  116. package/src/client/components/settings/categories/provider-settings/EntryAdvanced.tsx +175 -0
  117. package/src/client/components/settings/categories/provider-settings/EntryModal.tsx +275 -0
  118. package/src/client/components/settings/categories/provider-settings/Header.tsx +40 -9
  119. package/src/client/components/settings/categories/provider-settings/LoginModal.tsx +142 -160
  120. package/src/client/components/settings/categories/provider-settings/LogoutProviderModal.tsx +2 -2
  121. package/src/client/components/settings/categories/provider-settings/ModelCapabilitiesModal.tsx +84 -46
  122. package/src/client/components/settings/categories/provider-settings/ModelsList.tsx +217 -102
  123. package/src/client/components/settings/categories/provider-settings/PresetPicker.tsx +5 -2
  124. package/src/client/components/settings/categories/provider-settings/SidebarList.plugin.test.ts +3 -3
  125. package/src/client/components/settings/categories/provider-settings/SidebarList.tsx +158 -102
  126. package/src/client/components/settings/categories/provider-settings/auth-section.test.tsx +135 -0
  127. package/src/client/components/settings/categories/provider-settings/groups.test.ts +98 -0
  128. package/src/client/components/settings/categories/provider-settings/groups.ts +108 -0
  129. package/src/client/components/settings/categories/provider-settings/layout.test.tsx +325 -0
  130. package/src/client/components/settings/categories/provider-settings/model-dialogs.test.tsx +135 -0
  131. package/src/client/components/settings/categories/provider-settings/preset-picker.test.tsx +73 -0
  132. package/src/client/components/settings/categories/usage-settings/ProviderCard.tsx +22 -2
  133. package/src/client/components/settings/categories/usage-settings/ProviderDetail.tsx +2 -0
  134. package/src/client/components/settings/categories/usage-settings/SidebarList.tsx +16 -6
  135. package/src/client/components/settings/categories/usage-settings/providers.ts +3 -0
  136. package/src/client/components/settings/categories/usage-settings/usage-and-picker.test.ts +19 -0
  137. package/src/client/components/settings/categories/usage-settings/usage-icons.test.tsx +143 -0
  138. package/src/client/components/workspace/chat-timeline/MinimapShortcuts.test.ts +2 -1
  139. package/src/client/components/workspace/chat-timeline/chat-input/GoalBanner.test.ts +23 -19
  140. package/src/client/components/workspace/chat-timeline/chat-input/ModeToggles.test.ts +23 -19
  141. package/src/client/components/workspace/chat-timeline/chat-input/Toolbar.test.ts +20 -18
  142. package/src/client/components/workspace/chat-timeline/chat-input/compact.test.tsx +19 -6
  143. package/src/client/components/workspace/chat-timeline/index.tsx +7 -16
  144. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Wait.missing.test.ts +100 -0
  145. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Wait.test.ts +3 -47
  146. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Wait.tsx +8 -1
  147. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/wait-test-util.ts +62 -0
  148. package/src/client/components/workspace/diff-panel/HunkStepper.tsx +62 -0
  149. package/src/client/components/workspace/diff-panel/MergeDiffView.tsx +29 -0
  150. package/src/client/components/workspace/diff-panel/Toolbar.tsx +32 -1
  151. package/src/client/components/workspace/diff-panel/changes.ts +69 -0
  152. package/src/client/components/workspace/diff-panel/chunks.ts +85 -0
  153. package/src/client/components/workspace/diff-panel/index.tsx +21 -1
  154. package/src/client/components/workspace/diff-panel/merge.test.ts +145 -0
  155. package/src/client/components/workspace/diff-panel/merge.ts +63 -68
  156. package/src/client/components/workspace/editor/EditorDropOverlay.tsx +6 -1
  157. package/src/client/components/workspace/editor/FileDocument.tsx +51 -1
  158. package/src/client/components/workspace/editor/FilePane.tsx +25 -1
  159. package/src/client/components/workspace/editor/StatusBar.tsx +19 -0
  160. package/src/client/components/workspace/editor/Toolbar.tsx +29 -5
  161. package/src/client/components/workspace/editor/toolbar-clusters.test.ts +86 -0
  162. package/src/client/components/workspace/editor/toolbar-clusters.tsx +48 -16
  163. package/src/client/components/workspace/editor/viewers/bytes.ts +16 -0
  164. package/src/client/components/workspace/git-panel/index.test.ts +46 -1
  165. package/src/client/components/workspace/git-panel/index.tsx +11 -38
  166. package/src/client/components/workspace/model-dropdown/Item.plugin.test.ts +66 -0
  167. package/src/client/components/workspace/model-dropdown/Item.tsx +71 -62
  168. package/src/client/components/workspace/model-dropdown/Section.tsx +31 -14
  169. package/src/client/components/workspace/model-dropdown/collapsed.ts +72 -0
  170. package/src/client/components/workspace/model-dropdown/index.tsx +42 -19
  171. package/src/client/components/workspace/model-dropdown/refresh.test.tsx +260 -0
  172. package/src/client/components/workspace/model-dropdown/trigger.test.ts +34 -0
  173. package/src/client/components/workspace/model-dropdown/use-catalog.ts +13 -2
  174. package/src/client/components/workspace/usage-panel/ProviderSelect.tsx +19 -3
  175. package/src/client/hooks/chat/omp/folder-auto-expand.ts +113 -0
  176. package/src/client/hooks/chat/omp/index.ts +20 -0
  177. package/src/client/hooks/chat/omp/pending-rows.ts +21 -0
  178. package/src/client/hooks/chat/omp/pending-sessions.test.ts +16 -1
  179. package/src/client/hooks/chat/omp/session-sidebar-controller.test.ts +102 -0
  180. package/src/client/hooks/chat/omp/session-sidebar-controller.ts +21 -1
  181. package/src/client/hooks/chat/omp/stream.ts +8 -1
  182. package/src/client/hooks/chat/timeline/index.ts +1 -1
  183. package/src/client/hooks/chat/timeline/new-chat-open.ts +60 -0
  184. package/src/client/hooks/editor/blame-settings.ts +67 -0
  185. package/src/client/hooks/editor/blame.test.ts +272 -0
  186. package/src/client/hooks/editor/blame.ts +232 -0
  187. package/src/client/hooks/editor/file-editor-types.ts +23 -0
  188. package/src/client/hooks/editor/save-file.test.ts +20 -0
  189. package/src/client/hooks/editor/use-editor-drop.test-util.ts +198 -0
  190. package/src/client/hooks/editor/use-editor-drop.test.ts +70 -175
  191. package/src/client/hooks/editor/use-editor-drop.ts +19 -36
  192. package/src/client/hooks/editor/use-file-editor.ts +7 -1
  193. package/src/client/hooks/settings/providers/actions.ts +90 -194
  194. package/src/client/hooks/settings/providers/api.ts +7 -1
  195. package/src/client/hooks/settings/providers/index.ts +171 -59
  196. package/src/client/hooks/settings/providers/login.test.ts +79 -0
  197. package/src/client/hooks/settings/providers/login.ts +276 -0
  198. package/src/client/hooks/settings/providers/messages.ts +28 -0
  199. package/src/client/hooks/settings/providers/model-actions.ts +178 -0
  200. package/src/client/hooks/ui/editor-error-toast.ts +47 -0
  201. package/src/client/hooks/ui/open-file.ts +7 -0
  202. package/src/client/hooks/ui/toasts.ts +7 -0
  203. package/src/client/hooks/workspace/file-tabs.ts +4 -1
  204. package/src/client/hooks/workspace/folder-expansion.test.ts +62 -0
  205. package/src/client/hooks/workspace/folder-expansion.ts +33 -0
  206. package/src/client/hooks/workspace/git-action-outcome.ts +86 -0
  207. package/src/client/hooks/workspace/git-actions.ts +29 -2
  208. package/src/client/hooks/workspace/plugin-contributions.test.ts +117 -0
  209. package/src/client/hooks/workspace/plugin-contributions.ts +146 -0
  210. package/src/client/lib/editor-errors.test.ts +85 -0
  211. package/src/client/lib/editor-errors.ts +71 -0
  212. package/src/client/lib/fs/resolve-open.test.ts +125 -0
  213. package/src/client/lib/fs/resolve-open.ts +90 -0
  214. package/src/client/lib/git/action-message.test.ts +82 -0
  215. package/src/client/lib/git/action-message.ts +160 -0
  216. package/src/client/lib/launch/device-files.test.ts +160 -0
  217. package/src/client/lib/launch/device-files.ts +197 -0
  218. package/src/client/lib/native/open-paths.test.ts +140 -0
  219. package/src/client/lib/native/open-paths.ts +157 -0
  220. package/src/client/lib/plugins/bootstrap.test.ts +1 -1
  221. package/src/client/main.tsx +20 -0
  222. package/src/server/db.server.test.ts +39 -0
  223. package/src/server/db.server.ts +21 -2
  224. package/src/server/lib/db/schema.ts +2 -0
  225. package/src/server/lib/fs/external-roots.test.ts +100 -0
  226. package/src/server/lib/fs/external-roots.ts +101 -0
  227. package/src/server/lib/fs/git-actions-branch.ts +15 -2
  228. package/src/server/lib/fs/git-actions-shared.ts +24 -0
  229. package/src/server/lib/fs/git-actions-sync.test.ts +18 -7
  230. package/src/server/lib/fs/git-actions-worktree.ts +5 -1
  231. package/src/server/lib/fs/git-blame.test.ts +206 -0
  232. package/src/server/lib/fs/git-blame.ts +189 -0
  233. package/src/server/lib/fs/root.ts +14 -0
  234. package/src/server/lib/http/same-origin.ts +28 -7
  235. package/src/server/lib/models/catalog.server.ts +230 -0
  236. package/src/server/lib/models/catalog.test.ts +83 -0
  237. package/src/server/lib/models/credential-origin.server.ts +108 -0
  238. package/src/server/lib/models/credential-origin.test.ts +132 -0
  239. package/src/server/lib/models/provider-icon-fetch.ts +115 -0
  240. package/src/server/lib/models/provider-icon-parse.test.ts +134 -0
  241. package/src/server/lib/models/provider-icon-parse.ts +139 -0
  242. package/src/server/lib/models/provider-icon-store.server.ts +118 -0
  243. package/src/server/lib/models/provider-icon-store.test.ts +107 -0
  244. package/src/server/lib/models/provider-icon.server.ts +209 -0
  245. package/src/server/lib/models/provider-items.server.ts +211 -37
  246. package/src/server/lib/models/provider-items.test.ts +201 -0
  247. package/src/server/lib/models/provider-registry.server.test.ts +27 -9
  248. package/src/server/lib/models/provider-registry.server.ts +160 -67
  249. package/src/server/lib/models/registry.server.test.ts +3 -3
  250. package/src/server/lib/models/registry.server.ts +8 -0
  251. package/src/server/lib/omp/config/definitions.test.ts +5 -4
  252. package/src/server/lib/omp/config/models-config.ts +42 -0
  253. package/src/server/lib/omp/config/provider-entry.test.ts +205 -0
  254. package/src/server/lib/omp/config/provider-entry.ts +197 -0
  255. package/src/server/lib/omp/config/provider-seeds.ts +10 -0
  256. package/src/server/lib/omp/core/models-json.ts +69 -0
  257. package/src/server/lib/omp/session/messages.ts +17 -3
  258. package/src/server/lib/omp/session/sidebar-data.canonical.test.ts +13 -3
  259. package/src/server/lib/panels/bundled-catalog.server.ts +7 -0
  260. package/src/server/lib/panels/catalog-offers.server.ts +68 -0
  261. package/src/server/lib/panels/git-update.server.test.ts +14 -0
  262. package/src/server/lib/panels/git-update.server.ts +63 -1
  263. package/src/server/lib/panels/manifest.test.ts +65 -0
  264. package/src/server/lib/panels/manifest.ts +55 -1
  265. package/src/server/lib/panels/offers.server.test.ts +191 -0
  266. package/src/server/lib/panels/offers.server.ts +108 -0
  267. package/src/server/lib/panels/registry.server.test.ts +35 -1
  268. package/src/server/lib/panels/registry.server.ts +51 -142
  269. package/src/server/lib/panels/scan.server.ts +162 -0
  270. package/src/server/lib/route-adapter.ts +13 -2
  271. package/src/server/lib/tray/tray.test.ts +2 -1
  272. package/src/server/lib/usage/providers.server.ts +4 -1
  273. package/src/server/routes/chat/session.ts +7 -1
  274. package/src/server/routes/fs/git-blame-loader.test.ts +146 -0
  275. package/src/server/routes/fs/git.ts +17 -0
  276. package/src/server/routes/fs/grant.test.ts +135 -0
  277. package/src/server/routes/fs/grant.ts +79 -0
  278. package/src/server/routes/fs/index.ts +2 -0
  279. package/src/server/routes/fs/scope.ts +34 -17
  280. package/src/server/routes/omp/login.ts +41 -14
  281. package/src/server/routes/omp/routes.test.ts +23 -10
  282. package/src/server/routes/settings/index.ts +8 -0
  283. package/src/server/routes/settings/provider-entry.ts +108 -0
  284. package/src/server/routes/settings/provider-icon.ts +99 -0
  285. package/src/server/routes/settings/provider-model.ts +4 -1
  286. package/src/server/routes/settings/provider-refresh.ts +87 -0
  287. package/src/server/routes/settings/providers.ts +31 -2
  288. package/src/shared/lib/chat/omp/fold.test.ts +34 -0
  289. package/src/shared/lib/chat/omp/tool-frames.test.ts +20 -0
  290. package/src/shared/lib/chat/omp/tool-frames.ts +5 -1
  291. package/src/shared/lib/chat/omp/tool-results.ts +29 -3
  292. package/src/shared/lib/chat/tool/wait-facts.ts +4 -0
  293. package/src/shared/lib/fs/git-blame.test.ts +266 -0
  294. package/src/shared/lib/fs/git-blame.ts +246 -0
  295. package/src/shared/lib/git/url.ts +18 -0
  296. package/src/shared/lib/markdown/sanitize.test.ts +57 -0
  297. package/src/shared/lib/markdown/sanitize.ts +30 -7
  298. package/src/shared/lib/models/provider/connection.ts +135 -0
  299. package/src/shared/lib/models/provider/dialect.test.ts +4 -2
  300. package/src/shared/lib/models/provider/dialect.ts +76 -6
  301. package/src/shared/lib/models/provider/models.ts +2 -0
  302. package/src/shared/lib/models/provider/origin.ts +94 -0
  303. package/src/shared/lib/models/provider/provider-ui.test.ts +7 -0
  304. package/src/shared/lib/models/server-cache.ts +8 -3
  305. package/src/shared/lib/omp/session/messages-map-pending.test.ts +110 -0
  306. package/src/shared/lib/omp/session/messages-map.ts +34 -2
  307. package/src/shared/lib/omp/session/prewarm-misc.test.ts +7 -90
  308. package/src/shared/lib/omp/session/prewarm.test.ts +133 -0
  309. package/src/shared/lib/omp/session/prewarm.ts +23 -1
  310. package/src/shared/lib/omp/session/wait.test.ts +28 -0
  311. package/src/shared/lib/omp/session/wait.ts +38 -3
  312. package/src/shared/lib/panels/slot-labels.test.ts +61 -0
  313. package/src/shared/lib/panels/slot-labels.ts +133 -0
  314. package/src/shared/lib/workspace/panel-ids.ts +11 -0
  315. package/src/shared/types/fs.ts +6 -0
  316. package/src/shared/types/index.ts +1 -0
  317. package/src/shared/types/models.ts +12 -0
  318. package/src/shared/types/panels-registry.ts +277 -0
  319. package/src/shared/types/panels.ts +46 -213
  320. package/src/shared/types/settings/provider.ts +58 -0
  321. package/src/shared/types/settings/usage.ts +10 -0
  322. package/src/test-support/pristine-globals.ts +7 -0
  323. package/dist/client/static/js/index-bq6qeayr.css +0 -1
  324. package/src/client/components/settings/categories/provider-settings/ReconnectModal.tsx +0 -184
@@ -0,0 +1,82 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The Source Control panel's toast wording.
8
+ *
9
+ * Three rules are pinned here, and each is a sentence the user reads:
10
+ *
11
+ * - **A stopped operation never claims its verb's outcome.** `git merge`,
12
+ * `cherry-pick`, `revert`, `rebase`, `pull` and `stash pop` all SUCCEED while
13
+ * leaving the tree to the operation bar; "Merged feature" over a merge that
14
+ * stopped on a conflict is the panel reporting an outcome git did not
15
+ * produce. A stopped Sync is the sharpest case: the pull ran and the push
16
+ * did not.
17
+ * - **The silent verbs stay silent.** The change list is the answer for a
18
+ * stage, an unstage, a discard or a resolved conflict, so a toast per row
19
+ * would turn a five-file stage into five popups.
20
+ * - **The sentence names what the user acted on** — the branch, the commit
21
+ * subject, the stash ref — from the fields the panel dispatched.
22
+ */
23
+
24
+ import { describe, expect, test } from 'bun:test';
25
+ import { gitActionSuccessMessage } from '@/client/lib/git/action-message';
26
+
27
+ describe('gitActionSuccessMessage', () => {
28
+ test('names the remote verbs', () => {
29
+ expect(gitActionSuccessMessage({ actionType: 'sync' })).toBe('Synced with upstream');
30
+ expect(gitActionSuccessMessage({ actionType: 'push' })).toBe('Pushed to upstream');
31
+ expect(gitActionSuccessMessage({ actionType: 'pull' })).toBe('Pulled from upstream');
32
+ expect(gitActionSuccessMessage({ actionType: 'fetch' })).toBe('Fetched every remote');
33
+ });
34
+
35
+ test('a commit carries its subject, and an amend says it rewrote one', () => {
36
+ expect(gitActionSuccessMessage({ actionType: 'commit', extra: { message: 'fix(git): toast\n\nbody' } }))
37
+ .toBe('Committed “fix(git): toast”');
38
+ expect(gitActionSuccessMessage({ actionType: 'commit', extra: { message: 'x', amend: '1' } }))
39
+ .toBe('Amended the last commit');
40
+ });
41
+
42
+ test('a long subject is shortened, never wrapped', () => {
43
+ const subject = 'a'.repeat(80);
44
+ const message = gitActionSuccessMessage({ actionType: 'commit', extra: { message: subject } }) ?? '';
45
+ expect(message).toBe(`Committed “${'a'.repeat(47)}…”`);
46
+ });
47
+
48
+ test('names the branch, the commit and the stash ref the panel dispatched', () => {
49
+ expect(gitActionSuccessMessage({ actionType: 'checkout', extra: { branch: 'feat/x' } })).toBe('Switched to feat/x');
50
+ expect(gitActionSuccessMessage({ actionType: 'delete_branch', extra: { branch: 'feat/x' } })).toBe('Deleted branch feat/x');
51
+ expect(gitActionSuccessMessage({ actionType: 'rename_branch', extra: { branch: 'a', newName: 'b' } }))
52
+ .toBe('Renamed a to b');
53
+ expect(gitActionSuccessMessage({ actionType: 'cherry_pick', extra: { hash: '0123456789abcdef' } }))
54
+ .toBe('Cherry-picked 0123456');
55
+ expect(gitActionSuccessMessage({ actionType: 'stash_apply', extra: { ref: 'stash@{2}', pop: '1' } }))
56
+ .toBe('Popped stash@{2}');
57
+ expect(gitActionSuccessMessage({ actionType: 'stash_apply', extra: {} })).toBe('Applied stash@{0}');
58
+ });
59
+
60
+ test('a stopped operation is reported as started, never as finished', () => {
61
+ expect(gitActionSuccessMessage({ actionType: 'merge_branch', extra: { branch: 'feat' }, stopped: 'merge' }))
62
+ .toBe('Merging feat — the merge stopped on a conflict; resolve it above');
63
+ expect(gitActionSuccessMessage({ actionType: 'sync', stopped: 'merge' }))
64
+ .toBe('Pulled, but nothing was pushed — the merge stopped on a conflict; resolve it above, then Sync again');
65
+ expect(gitActionSuccessMessage({ actionType: 'pull', stopped: 'rebase' }))
66
+ .toBe('Pulled — the rebase stopped on a conflict; resolve it above');
67
+ expect(gitActionSuccessMessage({ actionType: 'stash_apply', extra: { pop: '1' }, stopped: 'stash-pop' }))
68
+ .toBe('Popping stash@{0} — the stash pop stopped on a conflict; resolve it above');
69
+ });
70
+
71
+ test('the change-list verbs stay silent', () => {
72
+ for (const actionType of ['stage', 'stage_all', 'unstage', 'unstage_all', 'revert', 'revert_all', 'resolve_conflict']) {
73
+ expect(gitActionSuccessMessage({ actionType })).toBeNull();
74
+ }
75
+ });
76
+
77
+ test('the read actions never toast — the modal is their answer', () => {
78
+ expect(gitActionSuccessMessage({ actionType: 'history' })).toBeNull();
79
+ expect(gitActionSuccessMessage({ actionType: 'graph' })).toBeNull();
80
+ expect(gitActionSuccessMessage({ actionType: 'commit_diff' })).toBeNull();
81
+ });
82
+ });
@@ -0,0 +1,160 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The sentence the Source Control panel toasts after an accepted action.
8
+ *
9
+ * A table, not a `switch` at the call site, and one that returns `null` on
10
+ * purpose. **An action whose result is already on screen stays silent**: the
11
+ * change list IS the feedback for a stage, an unstage, a discard or a resolved
12
+ * conflict, and a toast per row would turn a five-file stage into five popups.
13
+ *
14
+ * The actions that DO speak are the ones the list cannot show:
15
+ *
16
+ * - `push`/`pull`/`fetch`/`sync`, whose effect is on the REMOTE — the working
17
+ * tree above is byte-identical afterwards, so nothing on screen moves.
18
+ * - a branch or ref move (`checkout`, `create_branch`, `merge`, `rebase`,
19
+ * `reset`, `cherry-pick`, `revert`), where the list is the same files on a
20
+ * different base.
21
+ * - `commit`, because the box clears and the files leave "Staged" with no
22
+ * sentence saying the commit landed.
23
+ * - the stash, which folds a section shut and leaves a list that looks the
24
+ * same as before.
25
+ *
26
+ * The wording names WHAT the user acted on — the branch, the commit, the stash
27
+ * ref — from the fields the panel dispatched: "Operation succeeded" over a panel
28
+ * with eleven verbs is a toast the reader has to reconstruct.
29
+ *
30
+ * **A stopped operation has its own sentence.** `git merge`, `cherry-pick`,
31
+ * `revert`, `rebase` and `git pull` exit successfully while leaving an
32
+ * operation in progress, and `git stash pop` leaves conflicts with no operation
33
+ * file at all. The server reports which one (`stopped`), and reporting "Merged
34
+ * feature" over a merge that stopped on a conflict is the panel claiming an
35
+ * outcome git did not produce.
36
+ */
37
+
38
+ import { OPERATION_LABELS } from '@/shared/lib/fs/git-unmerged';
39
+
40
+ export interface GitActionMessageInput {
41
+ actionType: string;
42
+ /** The fields the panel dispatched with the action. */
43
+ extra?: Record<string, string>;
44
+ /**
45
+ * The operation the action STOPPED on, as the server read it back.
46
+ *
47
+ * Only the verbs that can leave one report it, and a `sync` that stopped is a
48
+ * pull whose push never ran.
49
+ */
50
+ stopped?: string | null;
51
+ }
52
+
53
+ /** The two sentences a verb can have: what it did, and what it started. */
54
+ interface Phrases {
55
+ done: string;
56
+ /** The wording while an operation is left in progress; absent = cannot stop. */
57
+ stopped?: string;
58
+ }
59
+
60
+ /** Longest commit subject a toast carries on one line. */
61
+ const MAX_SUBJECT = 48;
62
+
63
+ /** The sentence a completed action gets, or `null` for the silent verbs. */
64
+ function phrasesFor(actionType: string, extra: Record<string, string> | undefined): Phrases | null {
65
+ const branch = extra?.branch?.trim() ?? '';
66
+ const hash = (extra?.hash ?? '').slice(0, 7);
67
+ const ref = extra?.ref?.trim() || 'stash@{0}';
68
+
69
+ switch (actionType) {
70
+ case 'init':
71
+ return { done: 'Initialized the repository' };
72
+ case 'fetch':
73
+ return { done: 'Fetched every remote' };
74
+ case 'push':
75
+ return { done: 'Pushed to upstream' };
76
+ case 'pull':
77
+ return { done: 'Pulled from upstream', stopped: 'Pulled' };
78
+ case 'sync':
79
+ return { done: 'Synced with upstream', stopped: 'Pulled, but nothing was pushed' };
80
+ case 'abort_operation':
81
+ return { done: 'Aborted the operation in progress' };
82
+ case 'continue_operation':
83
+ return { done: 'Concluded the operation' };
84
+ case 'commit': {
85
+ if (extra?.amend === '1') return { done: 'Amended the last commit' };
86
+ const subject = (extra?.message ?? '').split('\n')[0].trim();
87
+ if (!subject) return { done: 'Commit created' };
88
+ const shown = subject.length > MAX_SUBJECT ? `${subject.slice(0, MAX_SUBJECT - 1)}…` : subject;
89
+ return { done: `Committed “${shown}”` };
90
+ }
91
+ case 'checkout':
92
+ return { done: branch ? `Switched to ${branch}` : 'Switched branch' };
93
+ case 'create_branch':
94
+ case 'create_branch_at':
95
+ return { done: branch ? `Created branch ${branch}` : 'Created branch' };
96
+ case 'rename_branch': {
97
+ const to = extra?.newName?.trim() ?? '';
98
+ return { done: branch && to ? `Renamed ${branch} to ${to}` : 'Renamed branch' };
99
+ }
100
+ case 'delete_branch':
101
+ return { done: branch ? `Deleted branch ${branch}` : 'Deleted branch' };
102
+ case 'merge_branch':
103
+ return {
104
+ done: branch ? `Merged ${branch}` : 'Merged branch',
105
+ stopped: branch ? `Merging ${branch}` : 'Merging the branch',
106
+ };
107
+ case 'merge_commit':
108
+ return {
109
+ done: hash ? `Merged commit ${hash}` : 'Merged commit',
110
+ stopped: hash ? `Merging ${hash}` : 'Merging the commit',
111
+ };
112
+ case 'cherry_pick':
113
+ return {
114
+ done: hash ? `Cherry-picked ${hash}` : 'Cherry-picked commit',
115
+ stopped: hash ? `Cherry-picking ${hash}` : 'Cherry-picking the commit',
116
+ };
117
+ case 'revert_commit':
118
+ return {
119
+ done: hash ? `Reverted commit ${hash}` : 'Reverted commit',
120
+ stopped: hash ? `Reverting ${hash}` : 'Reverting the commit',
121
+ };
122
+ case 'rebase_commit':
123
+ return {
124
+ done: hash ? `Rebased onto ${hash}` : 'Rebased',
125
+ stopped: hash ? `Rebasing onto ${hash}` : 'Rebasing',
126
+ };
127
+ case 'reset_commit': {
128
+ const mode = extra?.mode ?? 'mixed';
129
+ return { done: hash ? `Reset to ${hash} (${mode})` : `Reset (${mode})` };
130
+ }
131
+ case 'stash_push':
132
+ return { done: 'Stashed your changes' };
133
+ case 'stash_apply':
134
+ return {
135
+ done: extra?.pop === '1' ? `Popped ${ref}` : `Applied ${ref}`,
136
+ stopped: extra?.pop === '1' ? `Popping ${ref}` : `Applying ${ref}`,
137
+ };
138
+ case 'stash_drop':
139
+ return { done: `Dropped ${ref}` };
140
+ default:
141
+ // stage/unstage/revert/resolve_conflict/history/graph/… — the list and
142
+ // the modals are their feedback, and a toast would only be noise.
143
+ return null;
144
+ }
145
+ }
146
+
147
+ /** The toast for an accepted action, or `null` when the panel stays silent. */
148
+ export function gitActionSuccessMessage({ actionType, extra, stopped }: GitActionMessageInput): string | null {
149
+ const phrases = phrasesFor(actionType, extra);
150
+ if (!stopped) return phrases?.done ?? null;
151
+
152
+ const label = (OPERATION_LABELS as Record<string, string>)[stopped] ?? stopped;
153
+ const head = phrases?.stopped ?? phrases?.done ?? '';
154
+ // A stopped Sync has not pushed, so its own sentence already says so; the
155
+ // instruction differs because the answer is to Sync again once it concludes.
156
+ const resolve = actionType === 'sync' ? 'resolve it above, then Sync again' : 'resolve it above';
157
+ return head
158
+ ? `${head} — the ${label} stopped on a conflict; ${resolve}`
159
+ : `The ${label} stopped on a conflict; ${resolve}`;
160
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * A document a PHONE handed over, delivered as bytes.
8
+ *
9
+ * The rules under test are the ones that fail silently on a device: a truncated
10
+ * transfer that opens as a corrupt document, two files of one name colliding,
11
+ * and a text file whose bytes are pushed into a tab that then tries to SAVE it
12
+ * to a path the console cannot reach.
13
+ */
14
+
15
+ import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
16
+ import { Window } from 'happy-dom';
17
+ import {
18
+ DEVICE_CHUNK_PROPERTY,
19
+ DEVICE_FILES_PROPERTY,
20
+ decodeBase64,
21
+ deviceFileFor,
22
+ installDeviceFiles,
23
+ } from '@/client/lib/launch/device-files';
24
+
25
+ const DOM_GLOBALS = ['window', 'document', 'navigator', 'CustomEvent', 'atob'] as const;
26
+ const nativeGlobals: Partial<Record<(typeof DOM_GLOBALS)[number], unknown>> = {};
27
+
28
+ let opened: { path?: string; name?: string; content?: string; handleId?: string; deviceFile?: boolean }[] = [];
29
+ let reported: { name: string; ok: boolean; message: string }[] = [];
30
+
31
+ beforeAll(() => {
32
+ const win = new Window({ url: 'http://localhost' });
33
+ const target = globalThis as unknown as Record<string, unknown>;
34
+ for (const key of DOM_GLOBALS) {
35
+ nativeGlobals[key] = target[key];
36
+ // `atob` is a Bun global too, so it is borrowed from the window like the
37
+ // rest — the module calls it on the decode path.
38
+ target[key] = key === 'atob' ? (win as unknown as Record<string, unknown>)[key] ?? target[key] : (win as unknown as Record<string, unknown>)[key];
39
+ }
40
+ win.addEventListener('omp:open-file', (event) => {
41
+ opened.push((event as unknown as CustomEvent).detail);
42
+ });
43
+ });
44
+
45
+ afterAll(() => {
46
+ const target = globalThis as unknown as Record<string, unknown>;
47
+ for (const key of DOM_GLOBALS) {
48
+ if (nativeGlobals[key] === undefined) delete target[key];
49
+ else target[key] = nativeGlobals[key];
50
+ }
51
+ });
52
+
53
+ beforeEach(() => {
54
+ opened = [];
55
+ reported = [];
56
+ installDeviceFiles({ onResult: (results) => reported.push(...results) });
57
+ });
58
+
59
+ /** What a shell does: announce, then stream the file in `chunk`-byte pieces. */
60
+ function deliver(meta: { id: string; name: string; mimeType?: string }, text: string, chunk = 4) {
61
+ const host = globalThis.window as unknown as Record<string, unknown>;
62
+ const announce = host[DEVICE_FILES_PROPERTY] as (metas: unknown) => void;
63
+ const push = host[DEVICE_CHUNK_PROPERTY] as (id: string, base64: string, last: boolean) => void;
64
+ announce([meta]);
65
+ const bytes = new TextEncoder().encode(text);
66
+ const base64 = btoa(String.fromCharCode(...bytes));
67
+ const pieces: string[] = [];
68
+ for (let index = 0; index < base64.length; index += chunk) pieces.push(base64.slice(index, index + chunk));
69
+ pieces.forEach((piece, index) => push(meta.id, piece, index === pieces.length - 1));
70
+ }
71
+
72
+ describe('decodeBase64', () => {
73
+ test('decodes to the same bytes the shell encoded', () => {
74
+ const text = 'hello, kabmo';
75
+ const bytes = decodeBase64(btoa(text));
76
+ expect(new TextDecoder().decode(bytes)).toBe(text);
77
+ });
78
+
79
+ test('an empty string decodes to nothing rather than throwing', () => {
80
+ expect(decodeBase64('').byteLength).toBe(0);
81
+ });
82
+ });
83
+
84
+ describe('installDeviceFiles', () => {
85
+ test('a delivered text file opens a tab with its content, marked device-backed', () => {
86
+ deliver({ id: 'dev-1', name: 'notes.md' }, '# hi\n');
87
+
88
+ expect(opened).toHaveLength(1);
89
+ expect(opened[0]).toMatchObject({ path: 'notes.md', name: 'notes.md', content: '# hi\n', handleId: 'dev-1', deviceFile: true });
90
+ // The bytes stay registered: the tab's byte source reads them for a viewer
91
+ // (a document, a picture), and the map is the only copy.
92
+ expect(deviceFileFor('dev-1')?.bytes.byteLength).toBe(5);
93
+ expect(reported.at(-1)).toMatchObject({ name: 'notes.md', ok: true });
94
+ });
95
+
96
+ test('the file is assembled from every chunk, not only the last', () => {
97
+ // 4-byte chunks over a 24-byte base64 payload: a handler that kept only the
98
+ // final piece would open a file whose content is the last 3 characters.
99
+ deliver({ id: 'dev-2', name: 'a.txt' }, 'abcdefghijklmnop', 4);
100
+ expect(opened[0]?.content).toBe('abcdefghijklmnop');
101
+ });
102
+
103
+ test('a binary file is refused with the shared sentence, and registers nothing', () => {
104
+ // A NUL in the head is git's own binary test, and the classification is the
105
+ // one the drop path and the read route use.
106
+ const host = globalThis.window as unknown as Record<string, unknown>;
107
+ (host[DEVICE_FILES_PROPERTY] as (metas: unknown) => void)([{ id: 'dev-3', name: 'blob.bin' }]);
108
+ const base64 = btoa(String.fromCharCode(0, 1, 2, 3));
109
+ (host[DEVICE_CHUNK_PROPERTY] as (id: string, b64: string, last: boolean) => void)('dev-3', base64, true);
110
+
111
+ expect(opened).toHaveLength(0);
112
+ expect(deviceFileFor('dev-3')).toBeNull();
113
+ expect(reported.at(-1)?.ok).toBe(false);
114
+ expect(reported.at(-1)?.message).toContain('not text');
115
+ });
116
+
117
+ test('an incomplete transfer is reported instead of opening half a file', () => {
118
+ const host = globalThis.window as unknown as Record<string, unknown>;
119
+ (host[DEVICE_FILES_PROPERTY] as (metas: unknown) => void)([{ id: 'dev-4', name: 'broken.pdf' }]);
120
+ // `last: false` forever — the shell died mid-transfer.
121
+ (host[DEVICE_CHUNK_PROPERTY] as (id: string, b64: string, last: boolean) => void)('dev-4', 'JVBERi0x', false);
122
+
123
+ expect(opened).toHaveLength(0);
124
+ expect(reported).toHaveLength(0);
125
+ // …and a chunk for an id nobody announced is ignored rather than creating a
126
+ // tab with no name.
127
+ (host[DEVICE_CHUNK_PROPERTY] as (id: string, b64: string, last: boolean) => void)('dev-unknown', 'AAAA', true);
128
+ expect(opened).toHaveLength(0);
129
+ });
130
+
131
+ test('two deliveries of one name are two tabs, keyed by id', () => {
132
+ deliver({ id: 'dev-5', name: 'report.md' }, 'first');
133
+ deliver({ id: 'dev-6', name: 'report.md' }, 'second');
134
+
135
+ expect(opened).toHaveLength(2);
136
+ expect(deviceFileFor('dev-5') && new TextDecoder().decode(deviceFileFor('dev-5')!.bytes)).toBe('first');
137
+ expect(deviceFileFor('dev-6') && new TextDecoder().decode(deviceFileFor('dev-6')!.bytes)).toBe('second');
138
+ });
139
+
140
+ test('a re-announced id restarts the transfer instead of appending to it', () => {
141
+ const host = globalThis.window as unknown as Record<string, unknown>;
142
+ const announce = host[DEVICE_FILES_PROPERTY] as (metas: unknown) => void;
143
+ const push = host[DEVICE_CHUNK_PROPERTY] as (id: string, b64: string, last: boolean) => void;
144
+ announce([{ id: 'dev-7', name: 'a.txt' }]);
145
+ push('dev-7', btoa('old'), false);
146
+ // The shell abandoned that delivery and started again.
147
+ announce([{ id: 'dev-7', name: 'a.txt' }]);
148
+ push('dev-7', btoa('new'), true);
149
+
150
+ expect(opened[0]?.content).toBe('new');
151
+ });
152
+
153
+ test('a malformed announcement is ignored', () => {
154
+ const host = globalThis.window as unknown as Record<string, unknown>;
155
+ const announce = host[DEVICE_FILES_PROPERTY] as (metas: unknown) => void;
156
+ announce('not an array');
157
+ announce([{ name: 'no-id.txt' }, { id: 'no-name' }, null]);
158
+ expect(opened).toHaveLength(0);
159
+ });
160
+ });
@@ -0,0 +1,197 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * A document the phone handed to Kabmo, delivered as BYTES.
8
+ *
9
+ * The desktop shells hand over a PATH and the server opens it, because the
10
+ * server runs on the same machine. On a phone that is not true: Kabmo is a
11
+ * client of a console that may be across the room or across the world, so a file
12
+ * picked in the Files app or a "Open with → Kabmo" from Gmail exists only on the
13
+ * DEVICE. The server cannot read it, and `/api/fs/grant` would be granting a
14
+ * path on a machine that has never seen the file.
15
+ *
16
+ * So the shell reads the bytes and pushes them here, and the tab is
17
+ * DEVICE-BACKED: it renders, and it cannot be written back (there is no path to
18
+ * write to and no writable handle). That is the honest model — the same one a
19
+ * PWA launch uses on a desktop, minus the handle — and the editor says so
20
+ * instead of offering a Save that would fail.
21
+ *
22
+ * ## Why chunks
23
+ *
24
+ * `evaluateJavascript`/`evaluateJavaScript` take one STRING, and a document the
25
+ * editor will accept reaches 20-32 MiB, which is ~27-43 MiB of base64. A single
26
+ * call of that size is a multi-second main-thread stall on both platforms and
27
+ * has no documented ceiling, so the shell announces the file and streams it:
28
+ *
29
+ * __kabmoOpenFiles([{ id, name, mimeType, size }])
30
+ * __kabmoOpenChunk(id, base64, last) // repeated; `last` closes it
31
+ *
32
+ * The page accumulates and only decodes when the final chunk arrives, so a
33
+ * half-delivered file can never open as a truncated document.
34
+ *
35
+ * Both globals are plain functions rather than bridge commands, for the reason
36
+ * `native/open-paths.ts` states: the shell needs no reply, and the console is
37
+ * the only place a refusal can be read.
38
+ */
39
+
40
+ import { BINARY_SNIFF_BYTES, classifyEditorFile, unsupportedEditorMessage } from '@/shared/lib/fs/file-kind';
41
+ import { openFileInEditor } from '@/client/hooks/ui/open-file';
42
+
43
+ /** What a shell announces before it sends any bytes. */
44
+ export interface DeviceFileMeta {
45
+ /** Unique per delivery, so two files of one name do not collide. */
46
+ id: string;
47
+ name: string;
48
+ mimeType?: string;
49
+ size?: number;
50
+ }
51
+
52
+ /** Where one file went. */
53
+ export interface DeviceFileResult {
54
+ name: string;
55
+ ok: boolean;
56
+ message: string;
57
+ }
58
+
59
+ /** The property a shell calls to announce files. */
60
+ export const DEVICE_FILES_PROPERTY = '__kabmoOpenFiles';
61
+
62
+ /** The property a shell calls with each chunk of base64. */
63
+ export const DEVICE_CHUNK_PROPERTY = '__kabmoOpenChunk';
64
+
65
+ /** Bytes of a file the phone opened, kept for the life of the page. */
66
+ interface DeviceBytes {
67
+ name: string;
68
+ mimeType: string | null;
69
+ bytes: Uint8Array;
70
+ }
71
+
72
+ /**
73
+ * The bytes a device-backed tab draws from, keyed by the tab's `handleId`.
74
+ *
75
+ * Module-level rather than `globalThis`: a device file cannot outlive the page
76
+ * that received it (nothing can re-read it — the URI permission belongs to the
77
+ * native intent), so a reload SHOULD lose it, exactly like a
78
+ * `FileSystemFileHandle`. The tab keeps its name and says it must be reopened.
79
+ */
80
+ const files = new Map<string, DeviceBytes>();
81
+
82
+ /** Files announced but not yet complete. */
83
+ const pending = new Map<string, { meta: DeviceFileMeta; parts: string[] }>();
84
+
85
+ /** The bytes for a device-backed tab, or null when this page did not receive them. */
86
+ export function deviceFileFor(id: string | undefined): DeviceBytes | null {
87
+ if (!id) return null;
88
+ return files.get(id) ?? null;
89
+ }
90
+
91
+ /** A MIME type from a file name, for the blob URL a viewer builds. */
92
+ function mimeFor(meta: DeviceFileMeta): string | null {
93
+ if (meta.mimeType && meta.mimeType.includes('/')) return meta.mimeType;
94
+ return null;
95
+ }
96
+
97
+ /**
98
+ * Base64 → bytes.
99
+ *
100
+ * An explicit loop rather than `Uint8Array.from(atob(b64), c => c.charCodeAt(0))`:
101
+ * the array-literal form allocates a 20-million-element intermediate for a
102
+ * 20 MiB document and then copies it. One `Uint8Array` of the decoded length,
103
+ * filled in place, is the same work with half the peak memory.
104
+ */
105
+ export function decodeBase64(base64: string): Uint8Array {
106
+ const binary = atob(base64);
107
+ const out = new Uint8Array(binary.length);
108
+ for (let index = 0; index < binary.length; index += 1) out[index] = binary.charCodeAt(index);
109
+ return out;
110
+ }
111
+
112
+ /**
113
+ * Open one delivered file as a tab.
114
+ *
115
+ * The classification is the SAME one the drop path and the read route apply, so
116
+ * a binary or an oversized document is refused with the shared sentence rather
117
+ * than opened as a tab whose whole content is a refusal.
118
+ */
119
+ function openDeliveredFile(meta: DeviceFileMeta, bytes: Uint8Array): DeviceFileResult {
120
+ const kind = classifyEditorFile({
121
+ path: meta.name,
122
+ size: bytes.byteLength,
123
+ head: bytes.subarray(0, BINARY_SNIFF_BYTES),
124
+ });
125
+ if (kind === 'binary' || kind === 'too-large') {
126
+ return { name: meta.name, ok: false, message: unsupportedEditorMessage(kind, bytes.byteLength, meta.name) };
127
+ }
128
+
129
+ files.set(meta.id, { name: meta.name, mimeType: mimeFor(meta), bytes });
130
+
131
+ // A text file is decoded here so the editor opens with a buffer; a document,
132
+ // a picture or a grid keeps its bytes and its viewer fetches them from the
133
+ // registry (`byteSourceFor`).
134
+ const content = kind === 'text' ? new TextDecoder().decode(bytes) : undefined;
135
+ openFileInEditor({
136
+ path: meta.name,
137
+ name: meta.name,
138
+ content,
139
+ handleId: meta.id,
140
+ deviceFile: true,
141
+ });
142
+ return { name: meta.name, ok: true, message: `Opened ${meta.name}` };
143
+ }
144
+
145
+ /**
146
+ * Install the two globals a shell calls, and open a tab per completed file.
147
+ *
148
+ * Idempotent: the properties are overwritten, and a second install replaces the
149
+ * reporter rather than stacking one.
150
+ */
151
+ export function installDeviceFiles(
152
+ options: { onResult?: (results: DeviceFileResult[]) => void } = {},
153
+ ): void {
154
+ if (typeof window === 'undefined') return;
155
+ const host = window as unknown as Record<string, unknown>;
156
+
157
+ const report = options.onResult ?? ((results: DeviceFileResult[]) => {
158
+ for (const result of results) {
159
+ if (!result.ok) console.warn(`[kabmo] ${result.name}: ${result.message}`);
160
+ }
161
+ });
162
+
163
+ host[DEVICE_FILES_PROPERTY] = (metas: unknown) => {
164
+ if (!Array.isArray(metas)) return;
165
+ for (const raw of metas) {
166
+ if (typeof raw !== 'object' || raw === null) continue;
167
+ const meta = raw as Partial<DeviceFileMeta>;
168
+ if (typeof meta.id !== 'string' || !meta.id || typeof meta.name !== 'string' || !meta.name) continue;
169
+ // Announced again (a retry, a second chunk sequence for one intent): the
170
+ // accumulator restarts, because the earlier bytes belong to a delivery the
171
+ // shell abandoned.
172
+ pending.set(meta.id, { meta: { id: meta.id, name: meta.name, mimeType: meta.mimeType, size: meta.size }, parts: [] });
173
+ }
174
+ };
175
+
176
+ host[DEVICE_CHUNK_PROPERTY] = (id: unknown, base64: unknown, last: unknown) => {
177
+ if (typeof id !== 'string' || typeof base64 !== 'string') return;
178
+ const entry = pending.get(id);
179
+ if (!entry) return;
180
+ entry.parts.push(base64);
181
+ if (last !== true) return;
182
+
183
+ pending.delete(id);
184
+ const joined = entry.parts.join('');
185
+ entry.parts = [];
186
+ let bytes: Uint8Array;
187
+ try {
188
+ bytes = decodeBase64(joined);
189
+ } catch {
190
+ // Truncated or mis-encoded base64 is a broken delivery, not a broken
191
+ // document: opening half of it would render a corrupt file.
192
+ report([{ name: entry.meta.name, ok: false, message: `Could not read ${entry.meta.name} — the transfer was incomplete.` }]);
193
+ return;
194
+ }
195
+ report([openDeliveredFile(entry.meta, bytes)]);
196
+ };
197
+ }