@bevel-software/platform-core-frontend 0.4.0 → 0.5.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 (326) hide show
  1. package/package.json +5 -3
  2. package/src/core/CoreAppShell.tsx +195 -56
  3. package/src/core/__tests__/AppChrome.test.tsx +125 -0
  4. package/src/core/__tests__/ShellRoutes.test.tsx +130 -95
  5. package/src/core/__tests__/bootstrap.test.ts +63 -0
  6. package/src/core/bootstrap.ts +73 -0
  7. package/src/core/events.ts +12 -0
  8. package/src/core/registry.ts +58 -9
  9. package/src/index.css +100 -11
  10. package/src/index.ts +24 -23
  11. package/src/lib/utils.ts +114 -138
  12. package/src/modules/access/__tests__/ManageAccessDialog.placement.test.tsx +281 -0
  13. package/src/modules/access/__tests__/ManageAccessDialog.test.tsx +166 -1
  14. package/src/modules/access/api.ts +49 -0
  15. package/src/modules/access/components/ManageAccessDialog.tsx +786 -481
  16. package/src/modules/access/hooks/useFileAccess.ts +1 -1
  17. package/src/modules/admin/__tests__/AdminRolesPage.suggest.test.tsx +86 -0
  18. package/src/modules/admin/__tests__/UserAccountsPage.test.tsx +172 -156
  19. package/src/modules/admin/__tests__/admin.unread.test.tsx +61 -0
  20. package/src/modules/admin/components/AdminRolesPage.tsx +44 -38
  21. package/src/modules/admin/components/RolesCorruptedBanner.tsx +11 -10
  22. package/src/modules/admin/components/UserAccountsPage.tsx +361 -353
  23. package/src/modules/admin/state/admin.context.tsx +15 -6
  24. package/src/modules/auth/components/AccountPage.tsx +11 -11
  25. package/src/modules/auth/components/LoginScreen.tsx +12 -12
  26. package/src/modules/auth/services/sso.ts +47 -1
  27. package/src/modules/change-requests/__tests__/ChangeRequestDialog.test.tsx +277 -0
  28. package/src/modules/change-requests/__tests__/author.test.ts +48 -0
  29. package/src/modules/change-requests/__tests__/conflict.test.ts +73 -0
  30. package/src/modules/change-requests/__tests__/diff.test.ts +134 -0
  31. package/src/modules/change-requests/__tests__/propose.test.ts +93 -0
  32. package/src/modules/change-requests/__tests__/useFileOnBranch.test.tsx +72 -0
  33. package/src/modules/change-requests/change-requests.css +22 -0
  34. package/src/modules/change-requests/components/ChangeBox.tsx +277 -0
  35. package/src/modules/change-requests/components/ChangeRequestDialog.tsx +713 -0
  36. package/src/modules/change-requests/components/ConflictHelp.tsx +47 -0
  37. package/src/modules/change-requests/components/CrFileTree.tsx +398 -0
  38. package/src/modules/change-requests/components/FileChangeBoxes.tsx +168 -0
  39. package/src/modules/change-requests/hooks/useApplyChangeRequest.ts +236 -0
  40. package/src/modules/change-requests/hooks/useCrFileDiffs.ts +79 -0
  41. package/src/modules/change-requests/hooks/useFileOnBranch.ts +80 -0
  42. package/src/modules/change-requests/services/change-requests.api.ts +45 -0
  43. package/src/modules/change-requests/services/propose.api.ts +162 -0
  44. package/src/modules/change-requests/utils/author.ts +47 -0
  45. package/src/modules/change-requests/utils/conflict.ts +38 -0
  46. package/src/modules/change-requests/utils/diff.ts +80 -0
  47. package/src/modules/git/__tests__/BranchSwitcher.test.tsx +27 -18
  48. package/src/modules/git/__tests__/FileHistoryPanel.test.tsx +36 -83
  49. package/src/modules/git/__tests__/PullNeededBanner.test.tsx +5 -5
  50. package/src/modules/git/__tests__/PullRequestsForMe.test.tsx +147 -0
  51. package/src/modules/git/__tests__/useAutoPullUpdates.test.tsx +2 -8
  52. package/src/modules/git/components/BranchSwitcher.tsx +68 -31
  53. package/src/modules/git/components/DiffView.tsx +4 -4
  54. package/src/modules/git/components/FileComparisonPanel.tsx +20 -20
  55. package/src/modules/git/components/FileHistoryPanel.tsx +71 -107
  56. package/src/modules/git/components/PullNeededBanner.tsx +6 -13
  57. package/src/modules/git/components/PullRequestsForMe.tsx +71 -36
  58. package/src/modules/git/components/UnifiedDiffView.tsx +4 -4
  59. package/src/modules/git/hooks/__tests__/useGitState.deleteBranch.test.tsx +2 -2
  60. package/src/modules/git/hooks/useGitState.ts +15 -14
  61. package/src/modules/git/services/__tests__/error-messages.test.ts +4 -4
  62. package/src/modules/git/services/error-messages.ts +7 -7
  63. package/src/modules/git/services/git.api.ts +17 -11
  64. package/src/modules/git/services/pr-prompts.ts +2 -2
  65. package/src/modules/git/state/git.context.ts +10 -1
  66. package/src/modules/layout/__tests__/SidebarFrameResponsive.test.tsx +224 -0
  67. package/src/modules/layout/__tests__/SidebarToggle.test.tsx +242 -0
  68. package/src/modules/layout/__tests__/breakpoints.test.ts +56 -0
  69. package/src/modules/layout/breakpoints.ts +6 -0
  70. package/src/modules/layout/components/AppLayout.tsx +17 -5
  71. package/src/modules/layout/components/DemoBanner.tsx +10 -1
  72. package/src/modules/layout/components/MaintenanceOverlay.tsx +104 -104
  73. package/src/modules/layout/components/MobileChatLayout.tsx +31 -26
  74. package/src/modules/layout/components/ResizableThreePaneLayout.tsx +59 -24
  75. package/src/modules/layout/components/SidebarFrame.tsx +317 -0
  76. package/src/modules/layout/components/SidebarToggle.tsx +86 -0
  77. package/src/modules/layout/components/SlideOverlay.tsx +1 -1
  78. package/src/modules/layout/components/__tests__/MobileChatLayout.test.tsx +40 -2
  79. package/src/modules/layout/components/__tests__/ResizableThreePaneLayout.test.tsx +19 -3
  80. package/src/modules/layout/state/sidebar.ts +200 -0
  81. package/src/modules/library/__tests__/AddToGroupDialog.test.tsx +313 -0
  82. package/src/modules/library/__tests__/ChangeRequestDock.test.tsx +84 -0
  83. package/src/modules/library/__tests__/GroupJoinRequests.test.tsx +178 -0
  84. package/src/modules/library/__tests__/GroupPage.test.tsx +479 -0
  85. package/src/modules/library/__tests__/GroupsIndexPage.test.tsx +283 -0
  86. package/src/modules/library/__tests__/GroupsSidebar.contextmenu.test.tsx +175 -0
  87. package/src/modules/library/__tests__/GroupsSidebar.locked.test.tsx +96 -0
  88. package/src/modules/library/__tests__/GroupsSidebar.test.tsx +142 -0
  89. package/src/modules/library/__tests__/GroupsSidebarMenu.test.tsx +142 -0
  90. package/src/modules/library/__tests__/LibraryCard.test.tsx +149 -0
  91. package/src/modules/library/__tests__/LibraryRoutes.test.tsx +378 -0
  92. package/src/modules/library/__tests__/LibrarySidebarMenu.test.tsx +347 -0
  93. package/src/modules/library/__tests__/LockedGroupView.test.tsx +203 -0
  94. package/src/modules/library/__tests__/NewGroupDialog.test.tsx +114 -0
  95. package/src/modules/library/__tests__/PersonalAddDialog.test.tsx +177 -0
  96. package/src/modules/library/__tests__/SkillPage.test.tsx +1063 -0
  97. package/src/modules/library/__tests__/ToolConnectionSection.test.tsx +259 -0
  98. package/src/modules/library/__tests__/ToolLogo.test.tsx +63 -0
  99. package/src/modules/library/__tests__/ToolPage.test.tsx +315 -0
  100. package/src/modules/library/__tests__/ToolSharePanel.test.tsx +36 -0
  101. package/src/modules/library/__tests__/ToolVarRow.test.tsx +260 -0
  102. package/src/modules/library/__tests__/WorkspaceItemRoute.test.tsx +197 -0
  103. package/src/modules/library/__tests__/auth-harness.tsx +37 -0
  104. package/src/modules/library/__tests__/oauth-fragment.test.ts +48 -0
  105. package/src/modules/library/__tests__/status.test.ts +210 -117
  106. package/src/modules/library/__tests__/useSkillDetail.test.tsx +102 -0
  107. package/src/modules/library/__tests__/useToolPage.test.tsx +146 -0
  108. package/src/modules/library/components/AccessRequestsBanner.tsx +101 -0
  109. package/src/modules/library/components/AddToGroupDialog.tsx +115 -0
  110. package/src/modules/library/components/ChangeRequestDock.tsx +71 -47
  111. package/src/modules/library/components/DeleteGroupDialog.tsx +87 -0
  112. package/src/modules/library/components/GroupIndexRow.tsx +63 -0
  113. package/src/modules/library/components/GroupJoinRequests.tsx +56 -0
  114. package/src/modules/library/components/GroupPage.tsx +373 -0
  115. package/src/modules/library/components/GroupsIndexPage.tsx +222 -0
  116. package/src/modules/library/components/GroupsSidebar.tsx +338 -0
  117. package/src/modules/library/components/GroupsSidebarMenu.tsx +160 -0
  118. package/src/modules/library/components/LibraryCard.tsx +153 -132
  119. package/src/modules/library/components/LibraryLayout.tsx +344 -0
  120. package/src/modules/library/components/LibraryPage.tsx +138 -254
  121. package/src/modules/library/components/LockGlyph.tsx +31 -0
  122. package/src/modules/library/components/LockedGroupView.tsx +159 -0
  123. package/src/modules/library/components/ManagedGroupRequests.tsx +70 -0
  124. package/src/modules/library/components/NewGroupDialog.tsx +112 -0
  125. package/src/modules/library/components/NewSkillPanel.tsx +151 -0
  126. package/src/modules/library/components/PageActions.tsx +156 -0
  127. package/src/modules/library/components/PendingSkillReview.tsx +63 -0
  128. package/src/modules/library/components/PersonalAddDialog.tsx +88 -0
  129. package/src/modules/library/components/PersonalGroupPage.tsx +125 -0
  130. package/src/modules/library/components/StatusDot.tsx +25 -0
  131. package/src/modules/library/components/ToolLogo.tsx +171 -0
  132. package/src/modules/library/components/group-page-parts.tsx +419 -0
  133. package/src/modules/library/components/skill-page/SkillFileEditor.tsx +134 -0
  134. package/src/modules/library/components/skill-page/SkillFilePane.tsx +117 -0
  135. package/src/modules/library/components/skill-page/SkillFileTabs.tsx +112 -0
  136. package/src/modules/library/components/skill-page/SkillPage.tsx +673 -0
  137. package/src/modules/library/components/skill-page/tab-ids.ts +33 -0
  138. package/src/modules/library/components/tool-page/ToolConnectionSection.tsx +175 -0
  139. package/src/modules/library/components/tool-page/ToolPage.tsx +228 -0
  140. package/src/modules/library/components/tool-page/ToolSharePanel.tsx +45 -0
  141. package/src/modules/library/components/tool-page/ToolVarRow.tsx +289 -0
  142. package/src/modules/library/hooks/useJoinRequests.ts +114 -0
  143. package/src/modules/library/hooks/useLibraryData.ts +134 -119
  144. package/src/modules/library/hooks/useSkillDetail.ts +119 -74
  145. package/src/modules/library/hooks/useToolPage.ts +145 -0
  146. package/src/modules/library/library.css +108 -320
  147. package/src/modules/library/routes/LibraryRoutes.tsx +134 -0
  148. package/src/modules/library/routes/WorkspaceItemRoute.tsx +74 -0
  149. package/src/modules/library/routes/library-paths.ts +191 -0
  150. package/src/modules/library/services/groups.api.ts +189 -0
  151. package/src/modules/library/services/library.api.ts +291 -164
  152. package/src/modules/library/services/tools.api.ts +60 -0
  153. package/src/modules/library/state/library-context.ts +22 -0
  154. package/src/modules/library/state/library-data.tsx +223 -0
  155. package/src/modules/library/state/toast.context.ts +32 -0
  156. package/src/modules/library/state/toast.tsx +84 -42
  157. package/src/modules/library/utils/clipboard.ts +33 -0
  158. package/src/modules/library/utils/group-summary.ts +68 -0
  159. package/src/modules/library/utils/names.ts +30 -0
  160. package/src/modules/library/utils/navigate-external.ts +15 -0
  161. package/src/modules/library/utils/oauth-fragment.ts +32 -0
  162. package/src/modules/library/utils/personal-group.ts +36 -0
  163. package/src/modules/library/utils/status.ts +199 -116
  164. package/src/modules/library/utils/toast-duration.ts +16 -0
  165. package/src/modules/onboarding/__tests__/onboarding.test.tsx +533 -0
  166. package/src/modules/onboarding/agent-clients.ts +48 -0
  167. package/src/modules/onboarding/components/ConnectAgentPill.tsx +133 -0
  168. package/src/modules/onboarding/components/RootLanding.tsx +54 -0
  169. package/src/modules/onboarding/components/WelcomePage.tsx +364 -0
  170. package/src/modules/onboarding/paths.ts +9 -0
  171. package/src/modules/onboarding/state/onboarding.ts +191 -0
  172. package/src/modules/pr/components/OpenChangeRequestDialog.tsx +10 -10
  173. package/src/modules/pr/services/pr-approvals.api.ts +19 -0
  174. package/src/modules/pr/services/pr-cancel.api.ts +11 -0
  175. package/src/modules/review/components/BinaryChangePlaceholder.tsx +3 -3
  176. package/src/modules/review/components/DiffViewer.tsx +4 -4
  177. package/src/modules/review/components/MarkdownDiffViewer.tsx +84 -26
  178. package/src/modules/review/components/ReviewFileRow.tsx +10 -10
  179. package/src/modules/review/components/ReviewPanel.tsx +49 -17
  180. package/src/modules/review/components/ReviewPanelSurface.tsx +1 -1
  181. package/src/modules/review/components/__tests__/MarkdownDiffViewer.test.tsx +122 -0
  182. package/src/modules/review/hooks/__tests__/useReviewState.test.ts +1 -1
  183. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +273 -171
  184. package/src/modules/secrets-vault/components/SecretsPage.tsx +313 -276
  185. package/src/modules/secrets-vault/components/ToolSecretsPanel.tsx +109 -92
  186. package/src/modules/secrets-vault/components/__tests__/SecretsPage.test.tsx +82 -51
  187. package/src/modules/secrets-vault/services/connect.api.ts +24 -3
  188. package/src/modules/settings/components/DeploymentPage.tsx +90 -0
  189. package/src/modules/settings/components/SettingsLayout.tsx +135 -0
  190. package/src/modules/settings/components/SettingsNav.tsx +114 -0
  191. package/src/modules/settings/components/__tests__/DeploymentPage.test.tsx +110 -0
  192. package/src/modules/settings/components/__tests__/SettingsLayout.test.tsx +249 -0
  193. package/src/modules/settings/settings-nav-items.tsx +166 -0
  194. package/src/modules/setup/__tests__/setup.test.tsx +540 -0
  195. package/src/modules/setup/components/SetupGate.tsx +67 -0
  196. package/src/modules/setup/components/SetupScreen.tsx +573 -0
  197. package/src/modules/setup/services/setup.api.ts +106 -0
  198. package/src/modules/setup/utils/git-host.ts +34 -0
  199. package/src/modules/toolbar/components/AppSwitcher.tsx +131 -108
  200. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +548 -548
  201. package/src/modules/toolbar/components/ProfileMenu.tsx +294 -0
  202. package/src/modules/toolbar/components/Toolbar.tsx +56 -54
  203. package/src/modules/toolbar/components/__tests__/AppSwitcher.test.tsx +176 -122
  204. package/src/modules/toolbar/components/__tests__/Toolbar.test.tsx +252 -77
  205. package/src/modules/tools/ToolsExplorerPage.tsx +45 -40
  206. package/src/modules/workspace/__tests__/design-system-parity.test.ts +133 -0
  207. package/src/modules/workspace/__tests__/testFixtures.ts +2 -0
  208. package/src/modules/workspace/components/EditorTabs.tsx +82 -50
  209. package/src/modules/workspace/components/FileExplorer.tsx +1292 -1068
  210. package/src/modules/workspace/components/FilePaneCard.tsx +53 -0
  211. package/src/modules/workspace/components/FileRoute.tsx +89 -84
  212. package/src/modules/workspace/components/FileViewer.tsx +1312 -906
  213. package/src/modules/workspace/components/KbDocumentShell.tsx +138 -0
  214. package/src/modules/workspace/components/KbFileRail.tsx +128 -0
  215. package/src/modules/workspace/components/KbPageHeader.tsx +390 -0
  216. package/src/modules/workspace/components/__tests__/EditorTabs.test.tsx +87 -3
  217. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +293 -39
  218. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +1 -16
  219. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +462 -44
  220. package/src/modules/workspace/components/__tests__/KbDocumentShell.test.tsx +84 -0
  221. package/src/modules/workspace/components/__tests__/KbFileRail.test.tsx +83 -0
  222. package/src/modules/workspace/components/__tests__/KbPageHeader.test.tsx +192 -0
  223. package/src/modules/workspace/components/renderers/CopyAnchorButton.tsx +64 -0
  224. package/src/modules/workspace/components/renderers/CsvRenderer.tsx +8 -8
  225. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +18 -9
  226. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +14 -14
  227. package/src/modules/workspace/components/renderers/ImageRenderer.tsx +2 -2
  228. package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +31 -165
  229. package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +18 -5
  230. package/src/modules/workspace/components/renderers/MermaidDiagram.tsx +27 -10
  231. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +2 -2
  232. package/src/modules/workspace/components/renderers/TextRenderer.tsx +11 -5
  233. package/src/modules/workspace/components/renderers/ToolForm.tsx +24 -24
  234. package/src/modules/workspace/components/renderers/ToolRenderer.tsx +27 -27
  235. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +11 -11
  236. package/src/modules/workspace/components/renderers/__tests__/DocxRenderer.test.tsx +66 -0
  237. package/src/modules/workspace/components/renderers/__tests__/KbMarkdownView.test.tsx +17 -1
  238. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.test.tsx +1 -1
  239. package/src/modules/workspace/components/renderers/__tests__/MermaidDiagram.test.tsx +58 -0
  240. package/src/modules/workspace/components/renderers/__tests__/lazyRenderer.test.tsx +68 -0
  241. package/src/modules/workspace/components/renderers/__tests__/rendererLayout.test.ts +64 -0
  242. package/src/modules/workspace/components/renderers/__tests__/sanitizeDocxHtml.test.ts +0 -0
  243. package/src/modules/workspace/components/renderers/chunk-boundary.tsx +71 -0
  244. package/src/modules/workspace/components/renderers/index.ts +78 -2
  245. package/src/modules/workspace/components/renderers/kbMarkdownPipeline.tsx +241 -0
  246. package/src/modules/workspace/components/renderers/lazyRenderer.tsx +59 -0
  247. package/src/modules/workspace/components/renderers/sanitizeDocxHtml.ts +91 -0
  248. package/src/modules/workspace/hooks/__tests__/useLinksOut.test.ts +59 -0
  249. package/src/modules/workspace/hooks/__tests__/useOpenChangeRequests.test.tsx +237 -0
  250. package/src/modules/workspace/hooks/__tests__/useWorkspaceState.test.tsx +185 -0
  251. package/src/modules/workspace/hooks/useAutoGrowTextarea.ts +30 -0
  252. package/src/modules/workspace/hooks/useLastCommit.ts +66 -0
  253. package/src/modules/workspace/hooks/useLinksOut.ts +56 -0
  254. package/src/modules/workspace/hooks/useOpenChangeRequests.ts +20 -0
  255. package/src/modules/workspace/hooks/useWorkspaceState.ts +123 -14
  256. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +1 -1
  257. package/src/modules/workspace/services/workspace.api.ts +9 -2
  258. package/src/modules/workspace/state/open-change-requests.context.ts +35 -0
  259. package/src/modules/workspace/state/open-change-requests.tsx +185 -0
  260. package/src/modules/workspace/state/workspace.context.ts +9 -0
  261. package/src/modules/workspace/utils/__tests__/diff.test.ts +87 -0
  262. package/src/modules/workspace/utils/diff.ts +130 -53
  263. package/src/modules/workspace/utils/fileTree.ts +182 -179
  264. package/src/modules/workspace/workspace.css +28 -0
  265. package/src/shared/components/Badge.tsx +62 -0
  266. package/src/shared/components/Banner.tsx +58 -0
  267. package/src/shared/components/Button.tsx +90 -0
  268. package/src/shared/components/Dialog.tsx +6 -6
  269. package/src/shared/components/Field.tsx +45 -0
  270. package/src/shared/components/IconButton.tsx +74 -0
  271. package/src/shared/components/ListRow.tsx +96 -0
  272. package/src/shared/components/Menu.tsx +88 -0
  273. package/src/shared/components/PageShell.tsx +54 -51
  274. package/src/shared/components/Surface.tsx +86 -0
  275. package/src/shared/components/__tests__/primitives.test.tsx +333 -0
  276. package/src/shared/components/index.ts +48 -0
  277. package/src/shared/components/useDismissableMenu.ts +71 -0
  278. package/src/shared/theme/__tests__/accent-contrast.test.ts +84 -0
  279. package/src/shared/theme/index.css +12 -0
  280. package/src/shared/theme/measure.ts +64 -0
  281. package/src/shared/theme/shadows.css +34 -0
  282. package/src/shared/theme/tokens.css +193 -0
  283. package/src/test-setup.ts +9 -0
  284. package/src/modules/access/components/AccessRestrictedBanner.tsx +0 -31
  285. package/src/modules/access/components/NodeOwnersBanner.tsx +0 -30
  286. package/src/modules/git/__tests__/ProtectedBranchBanner.test.tsx +0 -82
  287. package/src/modules/git/components/ProtectedBranchBanner.tsx +0 -42
  288. package/src/modules/library/__tests__/DetailDialog.test.tsx +0 -200
  289. package/src/modules/library/__tests__/diff.test.ts +0 -62
  290. package/src/modules/library/__tests__/loadout.test.tsx +0 -72
  291. package/src/modules/library/components/CompareView.tsx +0 -357
  292. package/src/modules/library/components/DetailDialog.tsx +0 -566
  293. package/src/modules/library/components/GearIcon.tsx +0 -12
  294. package/src/modules/library/components/LoadoutSidebar.tsx +0 -156
  295. package/src/modules/library/components/StatusGem.tsx +0 -21
  296. package/src/modules/library/components/SuggestChange.tsx +0 -171
  297. package/src/modules/library/components/particles.ts +0 -50
  298. package/src/modules/library/state/loadout.tsx +0 -129
  299. package/src/modules/library/utils/diff.ts +0 -102
  300. package/src/modules/pr/__tests__/PrApprovalBadge.test.tsx +0 -93
  301. package/src/modules/pr/__tests__/PrCancelButton.test.tsx +0 -158
  302. package/src/modules/pr/__tests__/PrCancelConfirmDialog.test.tsx +0 -44
  303. package/src/modules/pr/__tests__/PrMergeButton.test.tsx +0 -360
  304. package/src/modules/pr/__tests__/bucketize-comments.test.ts +0 -85
  305. package/src/modules/pr/__tests__/parsePatch.test.ts +0 -104
  306. package/src/modules/pr/__tests__/usePrViewerState.test.ts +0 -72
  307. package/src/modules/pr/components/PrApprovalBadge.tsx +0 -80
  308. package/src/modules/pr/components/PrCancelButton.tsx +0 -99
  309. package/src/modules/pr/components/PrCancelConfirmDialog.tsx +0 -119
  310. package/src/modules/pr/components/PrCommentComposer.tsx +0 -92
  311. package/src/modules/pr/components/PrCommentThread.tsx +0 -168
  312. package/src/modules/pr/components/PrCommentsPanel.tsx +0 -143
  313. package/src/modules/pr/components/PrDiffPane.tsx +0 -425
  314. package/src/modules/pr/components/PrFileRow.tsx +0 -164
  315. package/src/modules/pr/components/PrFilesList.tsx +0 -53
  316. package/src/modules/pr/components/PrHeader.tsx +0 -45
  317. package/src/modules/pr/components/PrHeaderOverflowMenu.tsx +0 -58
  318. package/src/modules/pr/components/PrMergeButton.tsx +0 -268
  319. package/src/modules/pr/components/PrMergeConfirmDialog.tsx +0 -112
  320. package/src/modules/pr/components/PrRefreshFromTargetButton.tsx +0 -110
  321. package/src/modules/pr/components/PrViewer.tsx +0 -364
  322. package/src/modules/pr/hooks/usePrViewerState.ts +0 -150
  323. package/src/modules/pr/state/pr-viewer.context.ts +0 -34
  324. package/src/modules/pr/utils/bucketize-comments.ts +0 -55
  325. package/src/modules/pr/utils/parsePatch.ts +0 -57
  326. package/src/modules/toolbar/components/AdminMenu.tsx +0 -271
@@ -0,0 +1,236 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import type { PullRequestSummary } from '@bevel-software/platform-shared';
3
+ import { useEventBus } from '../../workflow/state/event-bus.context';
4
+ import { fetchPrDetail } from '../../pr/services/pr-detail.api';
5
+ import { approvePrFile } from '../../pr/services/pr-approvals.api';
6
+ import { mergePullRequest } from '../../pr/services/pr-merge.api';
7
+
8
+ /**
9
+ * Safety net for the async apply: if neither a `change-request-merged` nor a
10
+ * `change-request-merge-failed` event lands in this window (a dropped SSE
11
+ * connection, a backend restart mid-merge), stop the spinner and say so rather
12
+ * than spin forever. Same budget the change-request viewer's apply button uses.
13
+ */
14
+ const APPLY_RESULT_TIMEOUT_MS = 180_000;
15
+
16
+ /** Polling backstop cadence for a lost outcome event. Same source as above. */
17
+ const APPLY_POLL_INTERVAL_MS = 4_000;
18
+
19
+ export type ApplyPhase = 'idle' | 'approving' | 'applying';
20
+
21
+ /** Why an apply did not land. `conflicts` is git's answer, not a guess. */
22
+ export interface ApplyRefusal {
23
+ reason: string;
24
+ conflicts: boolean;
25
+ }
26
+
27
+ export interface ApplyChangeRequest {
28
+ /** The change request an apply is currently running for, if any. */
29
+ activeCr: number | null;
30
+ phase: ApplyPhase;
31
+ /** Refusals by change-request number, from the attempt that produced them. */
32
+ refusals: Map<number, ApplyRefusal>;
33
+ apply(cr: PullRequestSummary): void;
34
+ }
35
+
36
+ /**
37
+ * Approving a change request, end to end and honestly reported.
38
+ *
39
+ * TWO things this exists to get right, both of which the Library got wrong by
40
+ * calling `mergePullRequest` and awaiting it:
41
+ *
42
+ * 1. **Approving is not merging.** The merge gate requires a recorded per-file
43
+ * approval from an eligible approver for every markdown file that has
44
+ * owners — which is precisely the case the skill page is built for, since a
45
+ * SKILL.md inside a group folder inherits that folder's `access.md`. Going
46
+ * straight to merge is refused with "Waiting on approval for …". So the
47
+ * owner's click records the approvals FIRST, then merges. Files the caller
48
+ * is not eligible for are skipped rather than treated as failures: the gate
49
+ * is the authority on whether what remains is enough, and it reports what is
50
+ * still outstanding by name.
51
+ *
52
+ * 2. **The merge is asynchronous.** `POST …/merge` acks 202 and runs the merge
53
+ * in the background, because gate re-validation plus `gh pr merge` can
54
+ * outlive the gateway's idle timeout. Every conflict, gate block and git
55
+ * error therefore arrives over the event bus as
56
+ * `change-request-merge-failed` — NEVER as a rejection of the call. Awaiting
57
+ * the POST tells you the server agreed to try, and a success message printed
58
+ * there is a claim nothing has verified. This waits for the outcome, with a
59
+ * state poll and a timeout behind the event in case the stream drops.
60
+ */
61
+ export function useApplyChangeRequest(opts: {
62
+ onApplied(): void;
63
+ /**
64
+ * Which change request was refused, and why. The number is passed because a
65
+ * caller showing several boxes has to attribute the refusal to one of them,
66
+ * and reading it back out of `refusals` in an effect costs a commit — during
67
+ * which a conflicted change request still offers the button that just failed.
68
+ */
69
+ onFailed?(number: number, refusal: ApplyRefusal): void;
70
+ }): ApplyChangeRequest {
71
+ const { onApplied, onFailed } = opts;
72
+ const bus = useEventBus();
73
+ const [activeCr, setActiveCr] = useState<number | null>(null);
74
+ const [phase, setPhase] = useState<ApplyPhase>('idle');
75
+ const [refusals, setRefusals] = useState<Map<number, ApplyRefusal>>(new Map());
76
+
77
+ /**
78
+ * The in-flight change-request number, as a ref as well as state. Merging is
79
+ * irreversible, so re-entry has to be refused in the same tick — `phase`
80
+ * alone leaves a one-render window where a double-click issues two merges.
81
+ * It is also what the bus handlers read: they must ignore events for change
82
+ * requests this hook did not start (another tab, another user).
83
+ */
84
+ const runningRef = useRef<number | null>(null);
85
+ const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
86
+ const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
87
+
88
+ /**
89
+ * Latest callbacks, so the bus subscription never has to re-register.
90
+ * Assigned in an effect rather than during render: a render React discards
91
+ * (StrictMode, a suspended sibling) must not leave a ref pointing at
92
+ * callbacks from a commit that never happened.
93
+ */
94
+ const onAppliedRef = useRef(onApplied);
95
+ const onFailedRef = useRef(onFailed);
96
+ useEffect(() => {
97
+ onAppliedRef.current = onApplied;
98
+ onFailedRef.current = onFailed;
99
+ });
100
+
101
+ const stop = useCallback(() => {
102
+ if (timeoutRef.current) clearTimeout(timeoutRef.current);
103
+ if (pollRef.current) clearInterval(pollRef.current);
104
+ timeoutRef.current = null;
105
+ pollRef.current = null;
106
+ runningRef.current = null;
107
+ setActiveCr(null);
108
+ setPhase('idle');
109
+ }, []);
110
+
111
+ const fail = useCallback(
112
+ (number: number, refusal: ApplyRefusal) => {
113
+ stop();
114
+ setRefusals((m) => new Map(m).set(number, refusal));
115
+ onFailedRef.current?.(number, refusal);
116
+ },
117
+ [stop],
118
+ );
119
+
120
+ const succeed = useCallback(() => {
121
+ stop();
122
+ onAppliedRef.current();
123
+ }, [stop]);
124
+
125
+ useEffect(() => {
126
+ if (!bus) return;
127
+ const offMerged = bus.subscribe('change-request-merged', (e) => {
128
+ if (runningRef.current !== e.number) return;
129
+ succeed();
130
+ });
131
+ const offFailed = bus.subscribe('change-request-merge-failed', (e) => {
132
+ if (runningRef.current !== e.number) return;
133
+ fail(e.number, {
134
+ reason: e.reason || "Couldn't apply this change.",
135
+ conflicts: e.conflicts === true,
136
+ });
137
+ });
138
+ return () => {
139
+ offMerged();
140
+ offFailed();
141
+ };
142
+ }, [bus, succeed, fail]);
143
+
144
+ // Timers are cleared on unmount only — not on every re-subscribe above, which
145
+ // would disarm the safety net of an apply that is still running.
146
+ useEffect(
147
+ () => () => {
148
+ if (timeoutRef.current) clearTimeout(timeoutRef.current);
149
+ if (pollRef.current) clearInterval(pollRef.current);
150
+ },
151
+ [],
152
+ );
153
+
154
+ const apply = useCallback(
155
+ (cr: PullRequestSummary) => {
156
+ if (runningRef.current !== null) return;
157
+ runningRef.current = cr.number;
158
+ setActiveCr(cr.number);
159
+ setPhase('approving');
160
+ setRefusals((m) => {
161
+ if (!m.has(cr.number)) return m;
162
+ const next = new Map(m);
163
+ next.delete(cr.number);
164
+ return next;
165
+ });
166
+
167
+ void (async () => {
168
+ try {
169
+ // Fresh, because approvals pin to the current head: approving against
170
+ // a cached head would record consent to a revision nobody read.
171
+ const detail = await fetchPrDetail(cr.number, { fresh: true });
172
+ if (runningRef.current !== cr.number) return;
173
+
174
+ for (const a of detail.approvals) {
175
+ if (a.isApproved) continue;
176
+ // No eligible approvers means the gate ignores the file entirely.
177
+ const gateCares =
178
+ a.eligibleApprovers.roles.length > 0 || a.eligibleApprovers.users.length > 0;
179
+ if (!gateCares) continue;
180
+ // A refusal here is "not your file", which is normal on a change
181
+ // request spanning several owners — let the gate below decide
182
+ // whether what did get approved is enough.
183
+ await approvePrFile(cr.number, a.path).catch(() => undefined);
184
+ if (runningRef.current !== cr.number) return;
185
+ }
186
+
187
+ setPhase('applying');
188
+ // 202 ack only — the outcome arrives on the bus subscription above.
189
+ await mergePullRequest(cr.number);
190
+ // The outcome can beat this ack home (SSE is a separate connection);
191
+ // only arm the safety net if this attempt is still the running one,
192
+ // so a timer cannot fire into a later attempt.
193
+ if (runningRef.current !== cr.number) return;
194
+ timeoutRef.current = setTimeout(() => {
195
+ if (runningRef.current !== cr.number) return;
196
+ fail(cr.number, {
197
+ reason: 'Applying is taking longer than expected. Reload to check whether it landed.',
198
+ conflicts: false,
199
+ });
200
+ }, APPLY_RESULT_TIMEOUT_MS);
201
+ // Backstop for a lost event. `merged` is the ONLY state that means
202
+ // the apply landed — `closed` means somebody declined or withdrew it
203
+ // while this was running, and treating "left `open`" as success
204
+ // reported a declined change as applied.
205
+ pollRef.current = setInterval(() => {
206
+ if (runningRef.current !== cr.number) return;
207
+ void fetchPrDetail(cr.number, { fresh: true })
208
+ .then((latest) => {
209
+ if (runningRef.current !== cr.number) return;
210
+ if (latest.state === 'merged') succeed();
211
+ else if (latest.state !== 'open') {
212
+ fail(cr.number, {
213
+ reason: 'This change request was closed before it could be applied.',
214
+ conflicts: false,
215
+ });
216
+ }
217
+ })
218
+ .catch(() => undefined);
219
+ }, APPLY_POLL_INTERVAL_MS);
220
+ } catch (err) {
221
+ // The POST itself failed (auth, network, a hard gate block returned
222
+ // synchronously) — no background job started, so report it now
223
+ // instead of waiting for an event that will never come.
224
+ if (runningRef.current !== cr.number) return;
225
+ fail(cr.number, {
226
+ reason: err instanceof Error ? err.message : "Couldn't apply this change.",
227
+ conflicts: false,
228
+ });
229
+ }
230
+ })();
231
+ },
232
+ [fail, succeed],
233
+ );
234
+
235
+ return { activeCr, phase, refusals, apply };
236
+ }
@@ -0,0 +1,79 @@
1
+ import { useEffect, useMemo, useRef, useState } from 'react';
2
+ import type { PullRequestSummary } from '@bevel-software/platform-shared';
3
+ import { readFileOnBranch } from '../services/change-requests.api';
4
+ import { isBinaryFile } from '../../workspace/components/renderers';
5
+ import { diffLines, hasChanges, type DiffLine } from '../utils/diff';
6
+
7
+ /**
8
+ * For each open change request touching `repoRelativePath`, that branch's copy
9
+ * of the file diffed against the file as it stands on the default branch.
10
+ *
11
+ * Against CURRENT main, not against what the author forked from: the person
12
+ * deciding is being asked "should this text become that text?", and the only
13
+ * honest answer to that compares the proposal with what is there right now.
14
+ *
15
+ * Keyed by CR number + path + revision so a tab switch or a reload can never
16
+ * show the previous file's diff under this file's heading.
17
+ */
18
+ export function useCrFileDiffs(
19
+ crs: PullRequestSummary[],
20
+ repoRelativePath: string,
21
+ mainRaw: string | null,
22
+ revision = 0,
23
+ ): Map<number, DiffLine[] | null> {
24
+ const [contents, setContents] = useState<Map<string, string>>(new Map());
25
+ /** Requests already made, so a failed read is not retried on every render. */
26
+ const asked = useRef<Set<string>>(new Set());
27
+
28
+ // Only the change requests that actually touch this file have anything to show.
29
+ const relevant = useMemo(
30
+ () => crs.filter((c) => c.touchedNodePaths.includes(repoRelativePath)),
31
+ [crs, repoRelativePath],
32
+ );
33
+ const key = (n: number) => `${n}::${repoRelativePath}::${revision}`;
34
+ const wanted = relevant.map((c) => `${c.number}|${c.branch}`).join(',');
35
+
36
+ /**
37
+ * No `cancelled` flag — see `useDefaultBranchFile` for why one would deadlock
38
+ * against the `asked` guard under StrictMode. Stale answers are discarded by
39
+ * the KEY (cr + path + revision), not by cleanup.
40
+ */
41
+ useEffect(() => {
42
+ // A binary file has no honest text diff, and line-diffing decoded binary
43
+ // bytes is quadratic enough to hang the tab — never even read it. The
44
+ // boxes render their own binary notice instead of a diff.
45
+ if (isBinaryFile(repoRelativePath)) return;
46
+ for (const cr of relevant) {
47
+ const k = key(cr.number);
48
+ if (asked.current.has(k)) continue;
49
+ asked.current.add(k);
50
+ readFileOnBranch(cr.branch, repoRelativePath)
51
+ .then((content) => setContents((m) => new Map(m).set(k, content)))
52
+ .catch(() => {
53
+ // Deliberately NOT `''`. Storing empty for an unreadable branch copy
54
+ // would diff as "every line deleted" and present a proposal to erase
55
+ // the file. No content means no claim: the box keeps waiting.
56
+ });
57
+ }
58
+ // `contents` is intentionally out: it changes on every arrival, and the
59
+ // `asked` guard already makes each (cr, file, revision) fetch once.
60
+ // eslint-disable-next-line react-hooks/exhaustive-deps
61
+ }, [wanted, repoRelativePath, revision]);
62
+
63
+ return useMemo(() => {
64
+ const out = new Map<number, DiffLine[] | null>();
65
+ for (const cr of relevant) {
66
+ const branchRaw = contents.get(key(cr.number));
67
+ if (mainRaw === null || branchRaw === undefined) {
68
+ out.set(cr.number, null);
69
+ continue;
70
+ }
71
+ const d = diffLines(mainRaw, branchRaw);
72
+ // A proposal whose text now matches main has been overtaken — showing an
73
+ // empty diff would ask for a decision about nothing.
74
+ out.set(cr.number, hasChanges(d) ? d : []);
75
+ }
76
+ return out;
77
+ // eslint-disable-next-line react-hooks/exhaustive-deps
78
+ }, [relevant, contents, mainRaw, repoRelativePath, revision]);
79
+ }
@@ -0,0 +1,80 @@
1
+ import { useEffect, useRef, useState } from 'react';
2
+ import { DEFAULT_BRANCH } from '@bevel-software/platform-shared';
3
+ import { readFileOnBranch } from '../services/change-requests.api';
4
+
5
+ /**
6
+ * The file's RAW text on the default branch.
7
+ *
8
+ * Not `skill.body`, which is what the skills API returns for SKILL.md: that has
9
+ * already had the frontmatter parsed off. Two things here need the bytes as
10
+ * they sit in git, and both break quietly on the parsed body —
11
+ *
12
+ * - the DIFF, whose other side is a raw branch read. Body-vs-raw makes the
13
+ * frontmatter look like a deletion and marks the entire file as changed.
14
+ * - the EDITOR, whose text is written back as the whole file. Seeding it from
15
+ * the body would commit a SKILL.md with its `name`/`description`/
16
+ * `allowed-tools` frontmatter deleted.
17
+ *
18
+ * Keyed by path + revision, so a tab switch cannot show the previous file.
19
+ */
20
+ export function useDefaultBranchFile(
21
+ repoRelativePath: string | null,
22
+ revision = 0,
23
+ ): string | null {
24
+ return useFileOnBranch(DEFAULT_BRANCH, repoRelativePath, revision);
25
+ }
26
+
27
+ /**
28
+ * The same read against ANY branch — `null` branch means "don't fetch". The
29
+ * skill page uses it to seed an incremental proposal: when the caller already
30
+ * has an open change request, the editor's base is the file as it reads on
31
+ * THEIR suggestions branch, so a second round of edits stacks on the first
32
+ * instead of silently starting over from the default branch.
33
+ */
34
+ export function useFileOnBranch(
35
+ branch: string | null,
36
+ repoRelativePath: string | null,
37
+ revision = 0,
38
+ ): string | null {
39
+ /**
40
+ * Answers are cached PER KEY, not as "the last one". The skill page's tabs
41
+ * make the path oscillate (SKILL.md → a bundled file → SKILL.md), and with a
42
+ * single-slot state the return leg found its key already in `asked` — so no
43
+ * refetch — while the slot held the other tab's answer: the hook returned
44
+ * null forever and the pane sat on "Loading…". A map keeps every settled
45
+ * answer addressable for as long as the page is mounted (bounded: one entry
46
+ * per file per revision).
47
+ */
48
+ const cache = useRef<Map<string, string>>(new Map());
49
+ const asked = useRef<Set<string>>(new Set());
50
+ const [, arrived] = useState(0);
51
+ const key = `${branch ?? ''}::${repoRelativePath ?? ''}::${revision}`;
52
+
53
+ /**
54
+ * No `cancelled` flag, deliberately — pairing one with the `asked` guard
55
+ * DEADLOCKS under StrictMode's double-invoked effects: the first run starts
56
+ * the fetch and marks the key asked, its cleanup sets `cancelled`, and the
57
+ * second run sees the key already asked and never refetches. The result
58
+ * arrives and is thrown away, so the caller waits forever. (That is exactly
59
+ * how this shipped: the change-request view sat on "Loading…" while both
60
+ * reads returned 200.)
61
+ *
62
+ * A late answer needs no discarding at all anymore: it lands in the cache
63
+ * under its own key, and the read below simply doesn't look there.
64
+ */
65
+ useEffect(() => {
66
+ if (!branch || !repoRelativePath || asked.current.has(key)) return;
67
+ asked.current.add(key);
68
+ readFileOnBranch(branch, repoRelativePath)
69
+ .then((content) => {
70
+ cache.current.set(key, content);
71
+ arrived((n) => n + 1);
72
+ })
73
+ .catch(() => {
74
+ // Leave it unset rather than storing '': an empty string would diff as
75
+ // "the whole file was deleted".
76
+ });
77
+ }, [branch, repoRelativePath, key]);
78
+
79
+ return cache.current.get(key) ?? null;
80
+ }
@@ -0,0 +1,45 @@
1
+ import type { PullRequestSummary } from '@bevel-software/platform-shared';
2
+ import { authFetch } from '../../../lib/api';
3
+ import { handleApiResponse } from '../../git/services/git.api';
4
+ import { getOrCreateWorkspace, readFile } from '../../workspace/services/workspace.api';
5
+
6
+ /**
7
+ * The change-request module's data access — the reads every review surface
8
+ * shares. The Library's skill pages and the Knowledge viewer both build their
9
+ * boxes, diffs and suggestion overlays from these three calls; they live here
10
+ * so neither surface has to import the other's service layer.
11
+ */
12
+
13
+ /**
14
+ * All open change requests (callers filter to a folder or a file).
15
+ * `opts.fresh` bypasses the backend's 30s list cache — for event-driven
16
+ * refreshes that KNOW the list just changed, where a cached answer would
17
+ * hide the very change that triggered them.
18
+ */
19
+ export async function listOpenChangeRequests(
20
+ opts: { fresh?: boolean } = {},
21
+ ): Promise<PullRequestSummary[]> {
22
+ return handleApiResponse<PullRequestSummary[]>(
23
+ await authFetch(`/api/workflow/change-requests${opts.fresh ? '?fresh=1' : ''}`),
24
+ );
25
+ }
26
+
27
+ /**
28
+ * The caller's own change requests (any state; callers filter to open). The
29
+ * identity filter lives server-side — an email-hash match — which is the only
30
+ * place it can: the broad list deliberately exposes no email to compare
31
+ * against. Same `fresh` contract as above.
32
+ */
33
+ export async function listMyChangeRequests(
34
+ opts: { fresh?: boolean } = {},
35
+ ): Promise<PullRequestSummary[]> {
36
+ return handleApiResponse<PullRequestSummary[]>(
37
+ await authFetch(`/api/workflow/change-requests/mine${opts.fresh ? '?fresh=1' : ''}`),
38
+ );
39
+ }
40
+
41
+ /** Read a file from a branch's shared workspace (bootstraps the clone if needed). */
42
+ export async function readFileOnBranch(branch: string, repoRelativePath: string): Promise<string> {
43
+ const { workspace } = await getOrCreateWorkspace(branch);
44
+ return readFile(workspace.id, `${workspace.kbDirName}/${repoRelativePath}`);
45
+ }
@@ -0,0 +1,162 @@
1
+ import {
2
+ DEFAULT_BRANCH,
3
+ branchSegment,
4
+ suggestionsBranchPrefixFor,
5
+ type PullRequestSummary,
6
+ } from '@bevel-software/platform-shared';
7
+ import { createBranch, deleteBranch } from '../../git/services/git.api';
8
+ import { getOrCreateWorkspace, writeFile } from '../../workspace/services/workspace.api';
9
+ import { openChangeRequest } from '../../pr/services/pr-open.api';
10
+ import { listMyChangeRequests } from './change-requests.api';
11
+
12
+ /** The default branch's workspace id (id = encodeURIComponent(branch)), read lazily. */
13
+ const defaultWorkspaceId = () => encodeURIComponent(DEFAULT_BRANCH);
14
+
15
+ // The segment cleaner lives in `@bevel-software/platform-shared` now — the
16
+ // server judges "may this caller delete this suggestions branch?" from the
17
+ // same naming, and the two sides must never disagree. Re-exported for the
18
+ // library's per-skill branch naming.
19
+ export { branchSegment };
20
+
21
+ /** The identity a proposal is filed under — enough to name its branch. */
22
+ export interface ProposalAuthor {
23
+ email: string;
24
+ /** The stable user id — what makes the branch name collision-proof. */
25
+ id: string;
26
+ }
27
+
28
+ /**
29
+ * The one personal suggestions branch bundling ALL of a user's Knowledge
30
+ * proposals. Skills keep their per-skill branches (a skill is one decision);
31
+ * the knowledge folder gets one branch and one change request per person, so
32
+ * every edit a reader proposes lands in the same reviewable bundle.
33
+ *
34
+ * The email's local part alone is NOT the identity: `branchSegment` is lossy
35
+ * (`alex+ops@…` and `alex-ops@…` both clean to `alex-ops`), and two users
36
+ * mapping to one branch means one can silently rewrite the other's pending
37
+ * proposal. A slice of the stable user id disambiguates; the local part stays
38
+ * for the human reading the branch list.
39
+ */
40
+ export function knowledgeSuggestionBranchFor(user: ProposalAuthor): string {
41
+ return `${suggestionsBranchPrefixFor(user)}knowledge`;
42
+ }
43
+
44
+ export interface ProposeKnowledgeChangeInput {
45
+ /** Repo-root-relative path of the file being proposed on (no kbDirName prefix). */
46
+ repoRelativePath: string;
47
+ /** The file's full new text — what the author typed in the editor. */
48
+ content: string;
49
+ userEmail: string;
50
+ /** Stable user id — see {@link knowledgeSuggestionBranchFor}. */
51
+ userId: string;
52
+ userName: string;
53
+ }
54
+
55
+ /**
56
+ * Propose a change to a Knowledge file: commit the new text to the author's
57
+ * personal suggestions branch (forked from the default branch) and make sure
58
+ * an open change request against the default branch exists for it.
59
+ *
60
+ * Save = share: `writeFile` on the branch workspace auto-commits and pushes,
61
+ * so the proposal survives the tab closing the moment this resolves. The
62
+ * existing-request lookup is by BRANCH against the caller's own requests —
63
+ * `touchedNodePaths` is empty until computed, so a path-derived check would
64
+ * open a second request against the branch that already has one.
65
+ */
66
+ export async function proposeKnowledgeChange(
67
+ input: ProposeKnowledgeChangeInput,
68
+ ): Promise<{ branch: string }> {
69
+ const target = await ensureKnowledgeSuggestionWorkspace({
70
+ email: input.userEmail,
71
+ id: input.userId,
72
+ });
73
+ await writeFile(
74
+ target.workspaceId,
75
+ `${target.kbDirName}/${input.repoRelativePath}`,
76
+ input.content,
77
+ );
78
+ await ensureKnowledgeChangeRequest(target, input.userName);
79
+ return { branch: target.branch };
80
+ }
81
+
82
+ /**
83
+ * The caller's personal suggestions workspace, ready to be written to.
84
+ * Splitting the propose flow in two lets writes of ANY shape ride it — a
85
+ * typed proposal writes one file between these calls, an upload into a folder
86
+ * the caller may not write streams many.
87
+ */
88
+ export interface KnowledgeSuggestionTarget {
89
+ branch: string;
90
+ workspaceId: string;
91
+ kbDirName: string;
92
+ /** The caller's open request on this branch, or null when the write must open one. */
93
+ existingCr: PullRequestSummary | null;
94
+ }
95
+
96
+ export async function ensureKnowledgeSuggestionWorkspace(
97
+ user: ProposalAuthor,
98
+ ): Promise<KnowledgeSuggestionTarget> {
99
+ const branch = knowledgeSuggestionBranchFor(user);
100
+
101
+ // FRESH, not the 30s cache: a second proposal inside the cache window must
102
+ // see the request the first one just opened, or it opens a duplicate
103
+ // against the same branch.
104
+ const mine = await listMyChangeRequests({ fresh: true });
105
+ const existingCr = mine.find((c) => c.state === 'open' && c.branch === branch) ?? null;
106
+
107
+ if (!existingCr) {
108
+ try {
109
+ await createBranch(defaultWorkspaceId(), branch, DEFAULT_BRANCH);
110
+ } catch (err) {
111
+ // ONLY an already-exists refusal is evidence of a leftover branch (a
112
+ // withdrawn round, a merge whose retirement failed) worth resetting —
113
+ // a transient failure is not, and "delete on any error" could tear
114
+ // down a branch the failure said nothing about. The server refuses the
115
+ // delete outright while the branch carries an open request, so a race
116
+ // with a concurrent proposal cannot wipe an active branch either.
117
+ const alreadyExists =
118
+ err instanceof Error && /already exists/i.test(err.message);
119
+ if (alreadyExists) {
120
+ // TRY a reset: delete the leftover (the server also retires its
121
+ // stale workspace clone) and recreate fresh from the default branch.
122
+ // The server recognises `suggestions/<who>-<id>/…` as the caller's
123
+ // own, so this needs no admin role.
124
+ try {
125
+ await deleteBranch(defaultWorkspaceId(), branch);
126
+ await createBranch(defaultWorkspaceId(), branch, DEFAULT_BRANCH);
127
+ } catch {
128
+ // Strictly best-effort: on any refusal fall back to plain reuse —
129
+ // the change request is what makes the branch reviewable either way.
130
+ }
131
+ }
132
+ // Non-exists failures fall through to the write below, which surfaces
133
+ // anything real with its own error.
134
+ }
135
+ }
136
+
137
+ const { workspace } = await getOrCreateWorkspace(branch);
138
+ return { branch, workspaceId: workspace.id, kbDirName: workspace.kbDirName, existingCr };
139
+ }
140
+
141
+ /**
142
+ * Open the caller's one Knowledge change request, unless it already exists.
143
+ * Returns the request either way (the server's created row, or the existing
144
+ * one) so callers can announce it — the optimistic suggestion rows need its
145
+ * number and branch the moment the write lands.
146
+ */
147
+ export async function ensureKnowledgeChangeRequest(
148
+ target: KnowledgeSuggestionTarget,
149
+ userName: string,
150
+ ): Promise<PullRequestSummary | null> {
151
+ if (target.existingCr) return target.existingCr;
152
+ const created = await openChangeRequest({
153
+ sourceBranch: target.branch,
154
+ targetBranch: DEFAULT_BRANCH,
155
+ title: `Changes from ${userName}. Knowledge`,
156
+ });
157
+ // The endpoint returns the created request; treat an unexpected shape as
158
+ // "no summary to announce" rather than a failure — the request exists.
159
+ return created && typeof (created as PullRequestSummary).number === 'number'
160
+ ? (created as PullRequestSummary)
161
+ : null;
162
+ }
@@ -0,0 +1,47 @@
1
+ import type { PullRequestSummary } from '@bevel-software/platform-shared';
2
+
3
+ /**
4
+ * Who to name as the author of a change request.
5
+ *
6
+ * ONLY `appAuthor` — the app user the backend resolved by matching the hashed
7
+ * identity in the PR body. The `author` field beside it is the GitHub account
8
+ * that physically opened the PR, which is the shared service account
9
+ * (`pr.types.ts`: "Use this in user-facing surfaces — `author.login` is always
10
+ * the shared service account"). In practice `author.login` arrives as an opaque
11
+ * `user-42ee38e1c062`, and `author.name` is the service account's display name,
12
+ * so falling through to either attributes a person's change to the robot or
13
+ * prints a hash where a name belongs.
14
+ *
15
+ * `appAuthor` is absent for PRs opened outside this backend, or when the person
16
+ * has since been removed from the users table. "Someone" is the honest answer
17
+ * to that, and reads correctly in every sentence these surfaces build:
18
+ * "Someone proposed a change", "Waiting on Someone", a byline on its own.
19
+ *
20
+ * BLANK counts as absent, and the trim is not cosmetic. `??` alone lets an
21
+ * empty or whitespace-only name through, which reaches the compare view's
22
+ * blocked banner as "files changed after ⎵ wrote this". Padding is the subtler
23
+ * half: callers take a first name with `split(' ')[0]`, and on `' Olga'` that
24
+ * yields an empty string from a name that was never empty.
25
+ */
26
+ export function changeAuthorName(cr: PullRequestSummary): string {
27
+ return cr.appAuthor?.name?.trim() || 'Someone';
28
+ }
29
+
30
+ /**
31
+ * "today", "yesterday", or a plain date. A change box is read by someone
32
+ * deciding whether to act now, and "3 Aug" answers that worse than "today"
33
+ * does — but an exact timestamp answers it no better, so it stops there.
34
+ * Shared by the skill page's boxes and the Knowledge viewer's.
35
+ */
36
+ export function formatWhen(iso: string): string {
37
+ const then = new Date(iso);
38
+ if (Number.isNaN(then.getTime())) return 'recently';
39
+ // LOCAL calendar days, not elapsed milliseconds: a request from 23:59
40
+ // yesterday is "yesterday" at 00:01, not "today". Future timestamps (clock
41
+ // skew) collapse to "today" rather than a nonsense negative.
42
+ const startOfDay = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
43
+ const days = Math.round((startOfDay(new Date()) - startOfDay(then)) / 86_400_000);
44
+ if (days <= 0) return 'today';
45
+ if (days === 1) return 'yesterday';
46
+ return then.toLocaleDateString(undefined, { day: 'numeric', month: 'short' });
47
+ }