@bevel-software/platform-core-frontend 0.1.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 (203) hide show
  1. package/LICENSE +202 -0
  2. package/package.json +70 -0
  3. package/src/core/CoreAppShell.tsx +444 -0
  4. package/src/core/__tests__/ShellRoutes.test.tsx +95 -0
  5. package/src/core/events.ts +29 -0
  6. package/src/core/registry.ts +336 -0
  7. package/src/css-side-effect-imports.d.ts +7 -0
  8. package/src/html-extensions.ts +12 -0
  9. package/src/index.css +49 -0
  10. package/src/index.ts +23 -0
  11. package/src/lib/api.ts +57 -0
  12. package/src/lib/utils.ts +138 -0
  13. package/src/modules/access/__tests__/ManageAccessDialog.test.tsx +130 -0
  14. package/src/modules/access/__tests__/useFileAccess.test.tsx +253 -0
  15. package/src/modules/access/api.ts +205 -0
  16. package/src/modules/access/components/AccessRestrictedBanner.tsx +31 -0
  17. package/src/modules/access/components/ManageAccessDialog.tsx +1232 -0
  18. package/src/modules/access/components/NodeOwnersBanner.tsx +30 -0
  19. package/src/modules/access/hooks/useFileAccess.ts +151 -0
  20. package/src/modules/admin/components/AdminRolesPage.tsx +943 -0
  21. package/src/modules/admin/components/RolesCorruptedBanner.tsx +74 -0
  22. package/src/modules/admin/services/admin.api.ts +92 -0
  23. package/src/modules/admin/services/roles.api.ts +136 -0
  24. package/src/modules/admin/state/admin.context.tsx +223 -0
  25. package/src/modules/auth/components/LoginScreen.tsx +135 -0
  26. package/src/modules/auth/hooks/useAuthState.ts +59 -0
  27. package/src/modules/auth/services/auth.api.ts +24 -0
  28. package/src/modules/auth/services/microsoft-oauth.ts +57 -0
  29. package/src/modules/auth/state/auth.context.ts +18 -0
  30. package/src/modules/git/__tests__/BranchSwitcher.test.tsx +347 -0
  31. package/src/modules/git/__tests__/FileHistoryPanel.test.tsx +201 -0
  32. package/src/modules/git/__tests__/ProtectedBranchBanner.test.tsx +82 -0
  33. package/src/modules/git/__tests__/PullNeededBanner.test.tsx +441 -0
  34. package/src/modules/git/__tests__/git.api.test.ts +113 -0
  35. package/src/modules/git/__tests__/pr.api.test.ts +44 -0
  36. package/src/modules/git/__tests__/useAutoPullUpdates.test.tsx +212 -0
  37. package/src/modules/git/components/BranchSwitcher.tsx +527 -0
  38. package/src/modules/git/components/DiffView.tsx +30 -0
  39. package/src/modules/git/components/FileComparisonPanel.tsx +377 -0
  40. package/src/modules/git/components/FileHistoryPanel.tsx +320 -0
  41. package/src/modules/git/components/ProtectedBranchBanner.tsx +42 -0
  42. package/src/modules/git/components/PullNeededBanner.tsx +204 -0
  43. package/src/modules/git/components/PullRequestsForMe.tsx +244 -0
  44. package/src/modules/git/components/UnifiedDiffView.tsx +37 -0
  45. package/src/modules/git/hooks/__tests__/useGitState.deleteBranch.test.tsx +99 -0
  46. package/src/modules/git/hooks/useAutoPullUpdates.ts +121 -0
  47. package/src/modules/git/hooks/useGitState.ts +335 -0
  48. package/src/modules/git/services/__tests__/error-messages.test.ts +134 -0
  49. package/src/modules/git/services/error-messages.ts +257 -0
  50. package/src/modules/git/services/git.api.ts +163 -0
  51. package/src/modules/git/services/pr-prompts.ts +159 -0
  52. package/src/modules/git/services/pr.api.ts +39 -0
  53. package/src/modules/git/state/auto-update.context.ts +21 -0
  54. package/src/modules/git/state/git.context.ts +82 -0
  55. package/src/modules/layout/components/AppLayout.tsx +40 -0
  56. package/src/modules/layout/components/DemoBanner.tsx +57 -0
  57. package/src/modules/layout/components/MaintenanceOverlay.tsx +104 -0
  58. package/src/modules/layout/components/MobileChatLayout.tsx +153 -0
  59. package/src/modules/layout/components/ResizableThreePaneLayout.tsx +203 -0
  60. package/src/modules/layout/components/SlideOverlay.tsx +224 -0
  61. package/src/modules/layout/components/__tests__/MobileChatLayout.test.tsx +77 -0
  62. package/src/modules/layout/components/__tests__/ResizableThreePaneLayout.test.tsx +57 -0
  63. package/src/modules/layout/hooks/useMediaQuery.ts +23 -0
  64. package/src/modules/layout/state/__tests__/layout.context.test.tsx +39 -0
  65. package/src/modules/layout/state/layout.context.ts +46 -0
  66. package/src/modules/library/__tests__/DetailDialog.test.tsx +200 -0
  67. package/src/modules/library/__tests__/diff.test.ts +62 -0
  68. package/src/modules/library/__tests__/loadout.test.tsx +72 -0
  69. package/src/modules/library/__tests__/status.test.ts +117 -0
  70. package/src/modules/library/components/ChangeRequestDock.tsx +47 -0
  71. package/src/modules/library/components/CompareView.tsx +357 -0
  72. package/src/modules/library/components/DetailDialog.tsx +566 -0
  73. package/src/modules/library/components/GearIcon.tsx +12 -0
  74. package/src/modules/library/components/LibraryCard.tsx +132 -0
  75. package/src/modules/library/components/LibraryPage.tsx +254 -0
  76. package/src/modules/library/components/LoadoutSidebar.tsx +156 -0
  77. package/src/modules/library/components/StatusGem.tsx +21 -0
  78. package/src/modules/library/components/SuggestChange.tsx +171 -0
  79. package/src/modules/library/components/particles.ts +50 -0
  80. package/src/modules/library/hooks/useLibraryData.ts +119 -0
  81. package/src/modules/library/hooks/useSkillDetail.ts +74 -0
  82. package/src/modules/library/library.css +320 -0
  83. package/src/modules/library/services/library.api.ts +164 -0
  84. package/src/modules/library/state/loadout.tsx +129 -0
  85. package/src/modules/library/state/toast.tsx +42 -0
  86. package/src/modules/library/utils/diff.ts +102 -0
  87. package/src/modules/library/utils/status.ts +116 -0
  88. package/src/modules/pr/__tests__/PrApprovalBadge.test.tsx +93 -0
  89. package/src/modules/pr/__tests__/PrCancelButton.test.tsx +158 -0
  90. package/src/modules/pr/__tests__/PrCancelConfirmDialog.test.tsx +44 -0
  91. package/src/modules/pr/__tests__/PrMergeButton.test.tsx +360 -0
  92. package/src/modules/pr/__tests__/bucketize-comments.test.ts +85 -0
  93. package/src/modules/pr/__tests__/parsePatch.test.ts +104 -0
  94. package/src/modules/pr/__tests__/usePrViewerState.test.ts +72 -0
  95. package/src/modules/pr/components/OpenChangeRequestDialog.tsx +193 -0
  96. package/src/modules/pr/components/PrApprovalBadge.tsx +80 -0
  97. package/src/modules/pr/components/PrCancelButton.tsx +99 -0
  98. package/src/modules/pr/components/PrCancelConfirmDialog.tsx +119 -0
  99. package/src/modules/pr/components/PrCommentComposer.tsx +92 -0
  100. package/src/modules/pr/components/PrCommentThread.tsx +168 -0
  101. package/src/modules/pr/components/PrCommentsPanel.tsx +143 -0
  102. package/src/modules/pr/components/PrDiffPane.tsx +425 -0
  103. package/src/modules/pr/components/PrFileRow.tsx +164 -0
  104. package/src/modules/pr/components/PrFilesList.tsx +53 -0
  105. package/src/modules/pr/components/PrHeader.tsx +45 -0
  106. package/src/modules/pr/components/PrHeaderOverflowMenu.tsx +58 -0
  107. package/src/modules/pr/components/PrMergeButton.tsx +268 -0
  108. package/src/modules/pr/components/PrMergeConfirmDialog.tsx +112 -0
  109. package/src/modules/pr/components/PrRefreshFromTargetButton.tsx +110 -0
  110. package/src/modules/pr/components/PrViewer.tsx +364 -0
  111. package/src/modules/pr/hooks/usePrViewerState.ts +150 -0
  112. package/src/modules/pr/services/pr-approvals.api.ts +31 -0
  113. package/src/modules/pr/services/pr-cancel.api.ts +19 -0
  114. package/src/modules/pr/services/pr-comments.api.ts +45 -0
  115. package/src/modules/pr/services/pr-detail.api.ts +17 -0
  116. package/src/modules/pr/services/pr-merge.api.ts +53 -0
  117. package/src/modules/pr/services/pr-open.api.ts +30 -0
  118. package/src/modules/pr/state/pr-viewer.context.ts +34 -0
  119. package/src/modules/pr/utils/bucketize-comments.ts +55 -0
  120. package/src/modules/pr/utils/parsePatch.ts +57 -0
  121. package/src/modules/review/__tests__/review.api.test.ts +121 -0
  122. package/src/modules/review/components/BinaryChangePlaceholder.tsx +15 -0
  123. package/src/modules/review/components/DiffViewer.tsx +78 -0
  124. package/src/modules/review/components/MarkdownDiffViewer.tsx +263 -0
  125. package/src/modules/review/components/ReviewFileRow.tsx +114 -0
  126. package/src/modules/review/components/ReviewPanel.tsx +260 -0
  127. package/src/modules/review/components/ReviewPanelSurface.tsx +52 -0
  128. package/src/modules/review/components/__tests__/ReviewPanel.test.tsx +106 -0
  129. package/src/modules/review/hooks/__tests__/useReviewState.test.ts +88 -0
  130. package/src/modules/review/hooks/useReviewState.ts +256 -0
  131. package/src/modules/review/services/review.api.ts +72 -0
  132. package/src/modules/review/state/ReviewProvider.tsx +28 -0
  133. package/src/modules/review/state/review.context.ts +29 -0
  134. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +488 -0
  135. package/src/modules/secrets-vault/components/SecretsPage.tsx +276 -0
  136. package/src/modules/secrets-vault/components/ToolSecretsPanel.tsx +362 -0
  137. package/src/modules/secrets-vault/components/__tests__/SecretsPage.test.tsx +51 -0
  138. package/src/modules/secrets-vault/services/connect.api.ts +113 -0
  139. package/src/modules/secrets-vault/services/secrets.api.ts +82 -0
  140. package/src/modules/secrets-vault/services/tool-secrets.api.ts +116 -0
  141. package/src/modules/toolbar/components/AdminMenu.tsx +250 -0
  142. package/src/modules/toolbar/components/AppSwitcher.tsx +108 -0
  143. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +548 -0
  144. package/src/modules/toolbar/components/Toolbar.tsx +123 -0
  145. package/src/modules/toolbar/components/__tests__/AppSwitcher.test.tsx +122 -0
  146. package/src/modules/toolbar/components/__tests__/Toolbar.test.tsx +353 -0
  147. package/src/modules/toolbar/services/external-api-keys.api.ts +65 -0
  148. package/src/modules/tools/ToolsExplorerPage.tsx +380 -0
  149. package/src/modules/workflow/hooks/useEventBusSubscription.ts +24 -0
  150. package/src/modules/workflow/hooks/useFileLock.ts +430 -0
  151. package/src/modules/workflow/services/lock.api.ts +139 -0
  152. package/src/modules/workflow/state/EventBusFocusBinder.tsx +25 -0
  153. package/src/modules/workflow/state/EventBusProvider.tsx +232 -0
  154. package/src/modules/workflow/state/event-bus.context.ts +75 -0
  155. package/src/modules/workspace/__tests__/testFixtures.ts +54 -0
  156. package/src/modules/workspace/__tests__/useWorkspaceState.test.ts +91 -0
  157. package/src/modules/workspace/components/EditorTabs.tsx +384 -0
  158. package/src/modules/workspace/components/FileExplorer.tsx +1068 -0
  159. package/src/modules/workspace/components/FileRoute.tsx +392 -0
  160. package/src/modules/workspace/components/FileViewer.tsx +906 -0
  161. package/src/modules/workspace/components/__tests__/EditorTabs.test.tsx +241 -0
  162. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +666 -0
  163. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +330 -0
  164. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +492 -0
  165. package/src/modules/workspace/components/renderers/CsvRenderer.tsx +174 -0
  166. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +87 -0
  167. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +231 -0
  168. package/src/modules/workspace/components/renderers/ImageRenderer.tsx +50 -0
  169. package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +287 -0
  170. package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +252 -0
  171. package/src/modules/workspace/components/renderers/MermaidDiagram.tsx +268 -0
  172. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +81 -0
  173. package/src/modules/workspace/components/renderers/TextRenderer.tsx +86 -0
  174. package/src/modules/workspace/components/renderers/ToolForm.tsx +404 -0
  175. package/src/modules/workspace/components/renderers/ToolRenderer.tsx +417 -0
  176. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +157 -0
  177. package/src/modules/workspace/components/renderers/__tests__/CsvRenderer.test.ts +57 -0
  178. package/src/modules/workspace/components/renderers/__tests__/KbMarkdownView.test.tsx +95 -0
  179. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.test.tsx +328 -0
  180. package/src/modules/workspace/components/renderers/__tests__/PdfRenderer.test.tsx +167 -0
  181. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +318 -0
  182. package/src/modules/workspace/components/renderers/csvUtils.ts +76 -0
  183. package/src/modules/workspace/components/renderers/htmlSandbox.ts +332 -0
  184. package/src/modules/workspace/components/renderers/index.ts +39 -0
  185. package/src/modules/workspace/components/renderers/types.ts +27 -0
  186. package/src/modules/workspace/hooks/__tests__/useWorkspaceState.test.tsx +298 -0
  187. package/src/modules/workspace/hooks/useWorkspaceState.ts +1315 -0
  188. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +99 -0
  189. package/src/modules/workspace/routing/kb-routes.ts +266 -0
  190. package/src/modules/workspace/services/__tests__/workspace.api.test.ts +72 -0
  191. package/src/modules/workspace/services/workspace.api.ts +185 -0
  192. package/src/modules/workspace/state/workspace.context.ts +235 -0
  193. package/src/modules/workspace/utils/__tests__/frontmatter.test.ts +107 -0
  194. package/src/modules/workspace/utils/diff.ts +53 -0
  195. package/src/modules/workspace/utils/fileTree.ts +179 -0
  196. package/src/modules/workspace/utils/frontmatter.ts +80 -0
  197. package/src/modules/workspace/utils/readDroppedEntries.ts +119 -0
  198. package/src/modules/workspace/utils/tab-persistence.ts +23 -0
  199. package/src/shared/components/Dialog.tsx +198 -0
  200. package/src/shared/components/PageShell.tsx +51 -0
  201. package/src/shared/components/useModalLayer.ts +35 -0
  202. package/src/shared/markdown/Markdown.tsx +62 -0
  203. package/src/test-setup.ts +59 -0
@@ -0,0 +1,360 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import { render, screen, fireEvent, act } from '@testing-library/react';
3
+ import type { ReactNode } from 'react';
4
+ import type { PullRequestDetail, WorkflowEvent } from '@bevel-software/platform-shared';
5
+ import { PrMergeButton } from '../components/PrMergeButton';
6
+ // The button doesn't seed chat directly — on a conflicted apply it calls the
7
+ // change-request port's `resolveCrConflicts`. In the enterprise build a
8
+ // registry provider binds that port to chat seeding; core tests mount a stub
9
+ // port and assert the port itself is invoked.
10
+ import { CrCreationPortContext, type CrCreationPort } from '../../../core/registry';
11
+ import { EventBusContext, type EventBusContextValue } from '../../workflow/state/event-bus.context';
12
+ import { mergePullRequest } from '../services/pr-merge.api';
13
+ import { fetchPrDetail } from '../services/pr-detail.api';
14
+
15
+ vi.mock('../services/pr-merge.api', () => ({
16
+ mergePullRequest: vi.fn().mockResolvedValue({ status: 'merging', number: 1 }),
17
+ }));
18
+
19
+ vi.mock('../services/pr-detail.api', () => ({
20
+ fetchPrDetail: vi.fn(),
21
+ }));
22
+
23
+ /** A test double for the event bus that lets a test push events to subscribers. */
24
+ function makeFakeBus() {
25
+ const handlers: Record<string, ((e: WorkflowEvent) => void)[]> = {};
26
+ const bus: EventBusContextValue & { emit(e: WorkflowEvent): void } = {
27
+ subscribe(kind, handler) {
28
+ (handlers[kind] ??= []).push(handler as (e: WorkflowEvent) => void);
29
+ return () => {
30
+ handlers[kind] = (handlers[kind] ?? []).filter((h) => h !== handler);
31
+ };
32
+ },
33
+ setFocus() {},
34
+ emit(e) {
35
+ (handlers[e.kind] ?? []).forEach((h) => h(e));
36
+ },
37
+ };
38
+ return bus;
39
+ }
40
+
41
+ /**
42
+ * `PrMergeButton` reads the change-request port to hand off merge-conflict
43
+ * outcomes (so a registered resolver — the enterprise agent flow — picks up
44
+ * the resolution instead of the user). Tests render under a stub port;
45
+ * conflict-path tests can pass a spying `resolveCrConflicts` to assert the
46
+ * hand-off payload.
47
+ */
48
+ function makeStubPort(resolveCrConflicts: ReturnType<typeof vi.fn> = vi.fn()): CrCreationPort {
49
+ return { start: vi.fn(), resolveCrConflicts };
50
+ }
51
+
52
+ function renderWithChat(ui: ReactNode, resolveCrConflicts: ReturnType<typeof vi.fn> = vi.fn()) {
53
+ return render(
54
+ <CrCreationPortContext.Provider value={makeStubPort(resolveCrConflicts)}>
55
+ {ui}
56
+ </CrCreationPortContext.Provider>,
57
+ );
58
+ }
59
+
60
+ function renderWithBus(
61
+ ui: ReactNode,
62
+ bus: ReturnType<typeof makeFakeBus>,
63
+ resolveCrConflicts: ReturnType<typeof vi.fn> = vi.fn(),
64
+ ) {
65
+ return render(
66
+ <EventBusContext.Provider value={bus}>
67
+ <CrCreationPortContext.Provider value={makeStubPort(resolveCrConflicts)}>
68
+ {ui}
69
+ </CrCreationPortContext.Provider>
70
+ </EventBusContext.Provider>,
71
+ );
72
+ }
73
+
74
+ function detail(overrides: Partial<PullRequestDetail>): PullRequestDetail {
75
+ return {
76
+ number: 1,
77
+ title: 'Test PR',
78
+ author: { login: 'alice' },
79
+ branch: 'feature/x',
80
+ base: 'current-company-state',
81
+ state: overrides.state ?? 'open',
82
+ createdAt: '2026-04-20T10:00:00Z',
83
+ touchedNodePaths: [],
84
+ review: { approvals: 0, changesRequested: 0, pendingLogins: [] },
85
+ url: 'https://github.com/acme/repo/pull/1',
86
+ body: '',
87
+ headSha: 'head',
88
+ baseSha: 'base',
89
+ files: [],
90
+ comments: [],
91
+ approvals: [],
92
+ mergeableInBevel: overrides.mergeableInBevel ?? true,
93
+ mergeBlockedReasons: overrides.mergeBlockedReasons ?? [],
94
+ mergeWarnings: overrides.mergeWarnings ?? [],
95
+ // Default to admin (true) so existing tests describe the admin-with-bypass
96
+ // path. The non-admin path has its own dedicated test below.
97
+ viewerCanBypassMerge: overrides.viewerCanBypassMerge ?? true,
98
+ // Default true for parity with the admin assumption above — keeps existing
99
+ // tests focused on the merge gate; the cancel button has its own test file.
100
+ viewerCanCancel: overrides.viewerCanCancel ?? true,
101
+ ...overrides,
102
+ };
103
+ }
104
+
105
+ describe('PrMergeButton', () => {
106
+ it('is hidden when the PR is already merged', () => {
107
+ const { container } = renderWithChat(
108
+ <PrMergeButton detail={detail({ state: 'merged', mergeableInBevel: true })} onMerged={() => {}} />,
109
+ );
110
+ expect(container.firstChild).toBeNull();
111
+ });
112
+
113
+ it('is hidden when the PR is closed', () => {
114
+ const { container } = renderWithChat(
115
+ <PrMergeButton detail={detail({ state: 'closed' })} onMerged={() => {}} />,
116
+ );
117
+ expect(container.firstChild).toBeNull();
118
+ });
119
+
120
+ it('is disabled when a hard block applies (mergeableInBevel = false)', () => {
121
+ renderWithChat(
122
+ <PrMergeButton
123
+ detail={detail({
124
+ mergeableInBevel: false,
125
+ mergeBlockedReasons: ['This pull request has no file changes to approve.'],
126
+ })}
127
+ onMerged={() => {}}
128
+ />,
129
+ );
130
+ const btn = screen.getByRole('button', { name: /apply draft/i });
131
+ expect(btn).toBeDisabled();
132
+ expect(btn.getAttribute('title')).toContain('no file changes');
133
+ });
134
+
135
+ it('joins multiple hard-block reasons into the tooltip on newlines', () => {
136
+ renderWithChat(
137
+ <PrMergeButton
138
+ detail={detail({
139
+ mergeableInBevel: false,
140
+ mergeBlockedReasons: [
141
+ 'This pull request has already been merged.',
142
+ 'This pull request has no file changes to approve.',
143
+ ],
144
+ })}
145
+ onMerged={() => {}}
146
+ />,
147
+ );
148
+ const btn = screen.getByRole('button', { name: /apply draft/i });
149
+ expect(btn.getAttribute('title')).toMatch(/already been merged/);
150
+ expect(btn.getAttribute('title')).toMatch(/no file changes/);
151
+ });
152
+
153
+ it('is enabled with the default (purple) label when the gate is clean', () => {
154
+ renderWithChat(
155
+ <PrMergeButton
156
+ detail={detail({ mergeableInBevel: true, mergeWarnings: [] })}
157
+ onMerged={() => {}}
158
+ />,
159
+ );
160
+ const btn = screen.getByRole('button', { name: /^apply draft to current company state$/i });
161
+ expect(btn).toBeEnabled();
162
+ expect(btn.getAttribute('title')).toMatch(/all files confirmed/i);
163
+ expect(btn.getAttribute('title')).toMatch(/Current company state/);
164
+ });
165
+
166
+ it('stays enabled when warnings exist but no hard block (admin bypass path)', () => {
167
+ // Same "Apply draft …" label as the clean path — the bypass dialog
168
+ // appears AFTER the user clicks, not as a relabel up front. The
169
+ // amber color + tooltip carry the "something to review" signal.
170
+ renderWithChat(
171
+ <PrMergeButton
172
+ detail={detail({
173
+ mergeableInBevel: true,
174
+ mergeBlockedReasons: [],
175
+ mergeWarnings: ['Waiting on Bob to approve B.md.'],
176
+ viewerCanBypassMerge: true,
177
+ })}
178
+ onMerged={() => {}}
179
+ />,
180
+ );
181
+ const btn = screen.getByRole('button', { name: /^apply draft to current company state$/i });
182
+ expect(btn).toBeEnabled();
183
+ expect(btn.getAttribute('title')).toMatch(/1 confirmation pending/i);
184
+ expect(btn.getAttribute('title')).toMatch(/click to review/i);
185
+ });
186
+
187
+ it('drops the "to {base}" suffix in compact mode while keeping the full tooltip', () => {
188
+ renderWithChat(
189
+ <PrMergeButton
190
+ detail={detail({
191
+ mergeableInBevel: true,
192
+ mergeBlockedReasons: [],
193
+ mergeWarnings: ['Waiting on Bob to approve B.md.'],
194
+ viewerCanBypassMerge: true,
195
+ })}
196
+ onMerged={() => {}}
197
+ compact
198
+ />,
199
+ );
200
+ const btn = screen.getByRole('button', { name: /^apply draft$/i });
201
+ expect(btn).toBeEnabled();
202
+ expect(btn.getAttribute('title')).toMatch(/1 confirmation pending/i);
203
+ expect(btn.getAttribute('title')).toMatch(/click to review/i);
204
+ });
205
+
206
+ it('disables the merge button with admin-only copy when the viewer cannot bypass', () => {
207
+ // Non-admin user: backend would 403 on a bypass click. Frontend should
208
+ // surface that as a disabled button up front instead of letting the
209
+ // user open the bypass dialog only to hit an error.
210
+ renderWithChat(
211
+ <PrMergeButton
212
+ detail={detail({
213
+ mergeableInBevel: true,
214
+ mergeBlockedReasons: [],
215
+ mergeWarnings: ['Waiting on approval for test.md from Admin.'],
216
+ viewerCanBypassMerge: false,
217
+ })}
218
+ onMerged={() => {}}
219
+ />,
220
+ );
221
+ const btn = screen.getByRole('button', { name: /waiting on confirmations/i });
222
+ expect(btn).toBeDisabled();
223
+ expect(btn.getAttribute('title')).toMatch(/only an admin can apply now/i);
224
+ });
225
+
226
+ describe('async merge (202 + event bus)', () => {
227
+ it('shows "Applying…" on click and completes via change-request-merged', async () => {
228
+ vi.mocked(mergePullRequest).mockResolvedValueOnce({ status: 'merging', number: 1 });
229
+ const onMerged = vi.fn();
230
+ const bus = makeFakeBus();
231
+ renderWithBus(<PrMergeButton detail={detail({ mergeableInBevel: true })} onMerged={onMerged} />, bus);
232
+
233
+ fireEvent.click(screen.getByRole('button', { name: /apply draft/i }));
234
+ // Pending state shows immediately; the POST only acks (202).
235
+ expect(screen.getByRole('button', { name: /applying/i })).toBeInTheDocument();
236
+ expect(mergePullRequest).toHaveBeenCalledWith(1, {});
237
+ await act(async () => {}); // flush the awaited 202 ack
238
+
239
+ // onMerged fires only when the merge event for THIS CR lands.
240
+ expect(onMerged).not.toHaveBeenCalled();
241
+ act(() => bus.emit({ kind: 'change-request-merged', number: 1, id: 1, ts: '' }));
242
+ expect(onMerged).toHaveBeenCalledTimes(1);
243
+ });
244
+
245
+ it('hands conflicts to the change-request port (does not error) when the merge reports conflicts', async () => {
246
+ vi.mocked(mergePullRequest).mockResolvedValueOnce({ status: 'merging', number: 1 });
247
+ const resolveCrConflicts = vi.fn();
248
+ const bus = makeFakeBus();
249
+ renderWithBus(<PrMergeButton detail={detail({ mergeableInBevel: true })} onMerged={() => {}} />, bus, resolveCrConflicts);
250
+
251
+ fireEvent.click(screen.getByRole('button', { name: /apply draft/i }));
252
+ await act(async () => {});
253
+ act(() =>
254
+ bus.emit({
255
+ kind: 'change-request-merge-failed',
256
+ forUserId: 'u',
257
+ number: 1,
258
+ reason: 'conflicts',
259
+ conflicts: true,
260
+ id: 1,
261
+ ts: '',
262
+ }),
263
+ );
264
+ expect(resolveCrConflicts).toHaveBeenCalledWith(
265
+ expect.objectContaining({ kind: 'apply', changeRequestNumber: 1, base: 'current-company-state' }),
266
+ );
267
+ expect(screen.queryByRole('alert')).toBeNull();
268
+ });
269
+
270
+ it('surfaces the reason as an error banner on a non-conflict merge failure', async () => {
271
+ vi.mocked(mergePullRequest).mockResolvedValueOnce({ status: 'merging', number: 1 });
272
+ const bus = makeFakeBus();
273
+ renderWithBus(<PrMergeButton detail={detail({ mergeableInBevel: true })} onMerged={() => {}} />, bus);
274
+
275
+ fireEvent.click(screen.getByRole('button', { name: /apply draft/i }));
276
+ await act(async () => {});
277
+ act(() =>
278
+ bus.emit({
279
+ kind: 'change-request-merge-failed',
280
+ forUserId: 'u',
281
+ number: 1,
282
+ reason: 'gh pr merge failed: timed out',
283
+ conflicts: false,
284
+ id: 1,
285
+ ts: '',
286
+ }),
287
+ );
288
+ expect(screen.getByRole('alert').textContent).toMatch(/timed out/);
289
+ });
290
+
291
+ it('closes the bypass dialog (not just shows the error) when a bypass merge fails', async () => {
292
+ vi.mocked(mergePullRequest).mockResolvedValueOnce({ status: 'merging', number: 1 });
293
+ const bus = makeFakeBus();
294
+ renderWithBus(
295
+ <PrMergeButton
296
+ detail={detail({
297
+ mergeableInBevel: true,
298
+ mergeWarnings: ['Waiting on Bob to approve B.md.'],
299
+ viewerCanBypassMerge: true,
300
+ })}
301
+ onMerged={() => {}}
302
+ />,
303
+ bus,
304
+ );
305
+
306
+ fireEvent.click(screen.getByRole('button', { name: /apply draft/i }));
307
+ // Confirm through the bypass dialog (acknowledge checkbox enables it).
308
+ fireEvent.click(screen.getByRole('checkbox'));
309
+ fireEvent.click(screen.getByRole('button', { name: /with bypass/i }));
310
+ expect(screen.getByRole('dialog')).toBeInTheDocument();
311
+ await act(async () => {});
312
+
313
+ act(() =>
314
+ bus.emit({
315
+ kind: 'change-request-merge-failed',
316
+ forUserId: 'u',
317
+ number: 1,
318
+ reason: 'gh pr merge failed',
319
+ conflicts: false,
320
+ id: 1,
321
+ ts: '',
322
+ }),
323
+ );
324
+ // Dialog dismissed, error surfaced in the button row (not stranded behind it).
325
+ expect(screen.queryByRole('dialog')).toBeNull();
326
+ expect(screen.getByRole('alert').textContent).toMatch(/gh pr merge failed/);
327
+ });
328
+
329
+ it('completes via the polling fallback when the merge event is lost (SSE drop)', async () => {
330
+ // Reproduces the reported bug: the apply lands server-side but the
331
+ // `change-request-merged` event never arrives (proxy 502 / backend
332
+ // restart took the SSE connection with it). The button must still
333
+ // resolve off the CR's real state instead of spinning "Applying…".
334
+ vi.useFakeTimers();
335
+ try {
336
+ vi.mocked(mergePullRequest).mockResolvedValueOnce({ status: 'merging', number: 1 });
337
+ // First poll: still open (merge in flight). Second poll: merged.
338
+ vi.mocked(fetchPrDetail)
339
+ .mockResolvedValueOnce(detail({ state: 'open' }))
340
+ .mockResolvedValueOnce(detail({ state: 'merged' }));
341
+ const onMerged = vi.fn();
342
+ const bus = makeFakeBus();
343
+ renderWithBus(<PrMergeButton detail={detail({ mergeableInBevel: true })} onMerged={onMerged} />, bus);
344
+
345
+ fireEvent.click(screen.getByRole('button', { name: /apply draft/i }));
346
+ await act(async () => {}); // flush the 202 ack → arms the poll
347
+
348
+ // NO SSE event arrives. First poll tick: CR still open → keep waiting.
349
+ await act(async () => { await vi.advanceTimersByTimeAsync(4_000); });
350
+ expect(onMerged).not.toHaveBeenCalled();
351
+
352
+ // Second poll tick: CR now reads merged → resolve without the event.
353
+ await act(async () => { await vi.advanceTimersByTimeAsync(4_000); });
354
+ expect(onMerged).toHaveBeenCalledTimes(1);
355
+ } finally {
356
+ vi.useRealTimers();
357
+ }
358
+ });
359
+ });
360
+ });
@@ -0,0 +1,85 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import type { PrReviewComment } from '@bevel-software/platform-shared';
3
+ import { bucketizeComments } from '../utils/bucketize-comments';
4
+
5
+ function comment(overrides: Partial<PrReviewComment>): PrReviewComment {
6
+ return {
7
+ id: overrides.id ?? 'c-1',
8
+ author: overrides.author ?? { email: 'a@x', name: 'A' },
9
+ body: overrides.body ?? 'hi',
10
+ parentId: overrides.parentId,
11
+ headSha: overrides.headSha ?? 'sha',
12
+ path: overrides.path,
13
+ line: overrides.line,
14
+ createdAt: overrides.createdAt ?? '2026-04-20T10:00:00Z',
15
+ updatedAt: overrides.updatedAt,
16
+ };
17
+ }
18
+
19
+ describe('bucketizeComments', () => {
20
+ it('returns empty for empty input', () => {
21
+ expect(bucketizeComments([])).toEqual([]);
22
+ });
23
+
24
+ it('buckets a single root comment', () => {
25
+ const c = comment({ id: 'r-1' });
26
+ const out = bucketizeComments([c]);
27
+ expect(out).toEqual([{ root: c, replies: [] }]);
28
+ });
29
+
30
+ it('attaches replies to their root, preserving order', () => {
31
+ const root = comment({ id: 'root', createdAt: '2026-04-20T10:00:00Z' });
32
+ const r1 = comment({ id: 'r1', parentId: 'root', createdAt: '2026-04-20T11:00:00Z' });
33
+ const r2 = comment({ id: 'r2', parentId: 'root', createdAt: '2026-04-20T12:00:00Z' });
34
+ const out = bucketizeComments([root, r1, r2]);
35
+ expect(out).toHaveLength(1);
36
+ expect(out[0].root.id).toBe('root');
37
+ expect(out[0].replies.map((c) => c.id)).toEqual(['r1', 'r2']);
38
+ });
39
+
40
+ it('flattens nested replies into the same bucket', () => {
41
+ // A reply-to-a-reply chain (r2 -> r1 -> root) must land in the root bucket,
42
+ // not become its own thread.
43
+ const root = comment({ id: 'root' });
44
+ const r1 = comment({ id: 'r1', parentId: 'root' });
45
+ const r2 = comment({ id: 'r2', parentId: 'r1' });
46
+ const out = bucketizeComments([root, r1, r2]);
47
+ expect(out).toHaveLength(1);
48
+ expect(out[0].replies.map((c) => c.id).sort()).toEqual(['r1', 'r2']);
49
+ });
50
+
51
+ it('re-roots orphan replies when the parent is deleted', () => {
52
+ // If the user deletes the root, the replies remain but no longer have a
53
+ // parent in the list. They should still render as standalone threads
54
+ // rather than silently disappearing.
55
+ const r1 = comment({ id: 'r1', parentId: 'deleted-root' });
56
+ const r2 = comment({ id: 'r2', parentId: 'deleted-root' });
57
+ const out = bucketizeComments([r1, r2]);
58
+ expect(out).toHaveLength(2);
59
+ expect(out[0].root.id).toBe('r1');
60
+ expect(out[1].root.id).toBe('r2');
61
+ });
62
+
63
+ it('handles a parent cycle defensively (no infinite loop)', () => {
64
+ // Cycles shouldn't happen in a well-formed DB, but a malicious or buggy
65
+ // insert (a↔b mutual parent) must not hang the UI. The guard set ensures
66
+ // the walk terminates and the orphans surface as their own threads.
67
+ const a = comment({ id: 'a', parentId: 'b' });
68
+ const b = comment({ id: 'b', parentId: 'a' });
69
+ const out = bucketizeComments([a, b]);
70
+ // Neither points at a valid, unvisited root — both end up as their own
71
+ // buckets. The exact count is less important than "doesn't crash".
72
+ expect(out.length).toBeGreaterThan(0);
73
+ });
74
+
75
+ it('preserves multiple independent roots', () => {
76
+ const r1 = comment({ id: 'r1' });
77
+ const r2 = comment({ id: 'r2' });
78
+ const r1_reply = comment({ id: 'r1-r', parentId: 'r1' });
79
+ const out = bucketizeComments([r1, r2, r1_reply]);
80
+ expect(out).toHaveLength(2);
81
+ const byRootId = Object.fromEntries(out.map((b) => [b.root.id, b]));
82
+ expect(byRootId['r1'].replies.map((c) => c.id)).toEqual(['r1-r']);
83
+ expect(byRootId['r2'].replies).toEqual([]);
84
+ });
85
+ });
@@ -0,0 +1,104 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { parsePatch } from '../utils/parsePatch';
3
+
4
+ describe('parsePatch', () => {
5
+ it('returns empty for no patch', () => {
6
+ expect(parsePatch(undefined)).toEqual([]);
7
+ expect(parsePatch('')).toEqual([]);
8
+ });
9
+
10
+ it('parses a simple hunk', () => {
11
+ const patch = [
12
+ '@@ -1,2 +1,3 @@',
13
+ ' unchanged',
14
+ '-removed',
15
+ '+added',
16
+ '+added2',
17
+ ].join('\n');
18
+ const out = parsePatch(patch);
19
+ expect(out).toHaveLength(1);
20
+ expect(out[0].oldStart).toBe(1);
21
+ expect(out[0].newStart).toBe(1);
22
+ expect(out[0].lines).toEqual([
23
+ { type: 'same', text: 'unchanged' },
24
+ { type: 'removed', text: 'removed' },
25
+ { type: 'added', text: 'added' },
26
+ { type: 'added', text: 'added2' },
27
+ ]);
28
+ });
29
+
30
+ it('parses multiple hunks with distinct line offsets', () => {
31
+ const patch = [
32
+ '@@ -10,1 +10,2 @@',
33
+ ' first-hunk-context',
34
+ '+new-line-1',
35
+ '@@ -50,1 +51,1 @@',
36
+ '-deleted',
37
+ '+replacement',
38
+ ].join('\n');
39
+ const out = parsePatch(patch);
40
+ expect(out).toHaveLength(2);
41
+ expect(out[0].oldStart).toBe(10);
42
+ expect(out[0].newStart).toBe(10);
43
+ expect(out[1].oldStart).toBe(50);
44
+ expect(out[1].newStart).toBe(51);
45
+ });
46
+
47
+ it('handles single-line hunk headers (no comma/count)', () => {
48
+ // GitHub emits `@@ -1 +1 @@` for single-line diffs.
49
+ const patch = '@@ -1 +1 @@\n-old\n+new';
50
+ const out = parsePatch(patch);
51
+ expect(out).toHaveLength(1);
52
+ expect(out[0].oldStart).toBe(1);
53
+ expect(out[0].newStart).toBe(1);
54
+ });
55
+
56
+ it('ignores the "\" marker', () => {
57
+ const patch = [
58
+ '@@ -1,1 +1,1 @@',
59
+ '-old',
60
+ '\',
61
+ '+new',
62
+ '\',
63
+ ].join('\n');
64
+ const out = parsePatch(patch);
65
+ expect(out[0].lines).toEqual([
66
+ { type: 'removed', text: 'old' },
67
+ { type: 'added', text: 'new' },
68
+ ]);
69
+ });
70
+
71
+ it('preserves empty context lines inside a hunk', () => {
72
+ // An unprefixed empty string in the middle of a hunk represents an empty
73
+ // context line. Losing it would misalign the rendered line numbers.
74
+ const patch = ['@@ -1,3 +1,3 @@', ' a', '', ' c'].join('\n');
75
+ const out = parsePatch(patch);
76
+ expect(out[0].lines).toEqual([
77
+ { type: 'same', text: 'a' },
78
+ { type: 'same', text: '' },
79
+ { type: 'same', text: 'c' },
80
+ ]);
81
+ });
82
+
83
+ it('skips preamble before the first hunk', () => {
84
+ const patch = [
85
+ 'diff --git a/foo b/foo', // GitHub's patch strings don't normally include
86
+ 'index abc..def 100644', // the `diff --git` headers, but be lenient.
87
+ '--- a/foo',
88
+ '+++ b/foo',
89
+ '@@ -1,1 +1,1 @@',
90
+ '-old',
91
+ '+new',
92
+ ].join('\n');
93
+ const out = parsePatch(patch);
94
+ expect(out).toHaveLength(1);
95
+ expect(out[0].lines).toEqual([
96
+ { type: 'removed', text: 'old' },
97
+ { type: 'added', text: 'new' },
98
+ ]);
99
+ });
100
+
101
+ it('returns empty when no hunk header is present', () => {
102
+ expect(parsePatch('this is not a patch at all')).toEqual([]);
103
+ });
104
+ });
@@ -0,0 +1,72 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { renderHook, act, waitFor } from '@testing-library/react';
3
+ import { usePrViewerState } from '../hooks/usePrViewerState';
4
+ import { fetchPrDetail } from '../services/pr-detail.api';
5
+ import { GitApiError } from '../../git/services/git.api';
6
+
7
+ vi.mock('../services/pr-detail.api', () => ({
8
+ fetchPrDetail: vi.fn(),
9
+ }));
10
+
11
+ // The event bus is optional in the hook (null → no subscriptions), which is the
12
+ // default when no EventBusContext is mounted. renderHook mounts the hook with no
13
+ // provider, so `useEventBus()` returns null and the bus effect is a no-op.
14
+
15
+ const mockFetch = vi.mocked(fetchPrDetail);
16
+
17
+ describe('usePrViewerState — a deleted/absent CR surfaces as notFound, not an error', () => {
18
+ beforeEach(() => {
19
+ mockFetch.mockReset();
20
+ });
21
+
22
+ it('sets notFound (not a generic error) when the CR load 404s', async () => {
23
+ // This is the routine-deep-link case: the run pinned a CR number whose row
24
+ // is gone, so the detail fetch 404s. The viewer must show the calm
25
+ // "no longer available" state, driven by `notFound`, rather than the
26
+ // alarming error banner driven by `lastError` alone.
27
+ mockFetch.mockRejectedValue(new GitApiError(404, 'change request not found'));
28
+
29
+ const { result } = renderHook(() => usePrViewerState());
30
+ act(() => {
31
+ result.current.openPr(2);
32
+ });
33
+
34
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
35
+ expect(result.current.notFound).toBe(true);
36
+ expect(result.current.detail).toBeNull();
37
+ // lastError is still populated (for diagnostics), but the component branches
38
+ // on notFound FIRST, so the user never sees the red error for a gone CR.
39
+ expect(result.current.lastError).toBe('change request not found');
40
+ });
41
+
42
+ it('does NOT set notFound for a transient (non-404) failure', async () => {
43
+ // A 500 / network blip is a real, retryable failure — it must keep the
44
+ // error affordance, not masquerade as "the CR is gone".
45
+ mockFetch.mockRejectedValue(new GitApiError(500, 'internal error'));
46
+
47
+ const { result } = renderHook(() => usePrViewerState());
48
+ act(() => {
49
+ result.current.openPr(7);
50
+ });
51
+
52
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
53
+ expect(result.current.notFound).toBe(false);
54
+ expect(result.current.lastError).toBe('internal error');
55
+ });
56
+
57
+ it('clears notFound when the viewer is closed', async () => {
58
+ mockFetch.mockRejectedValue(new GitApiError(404, 'change request not found'));
59
+ const { result } = renderHook(() => usePrViewerState());
60
+
61
+ act(() => {
62
+ result.current.openPr(2);
63
+ });
64
+ await waitFor(() => expect(result.current.notFound).toBe(true));
65
+
66
+ act(() => {
67
+ result.current.closeViewer();
68
+ });
69
+ await waitFor(() => expect(result.current.notFound).toBe(false));
70
+ expect(result.current.openPrNumber).toBeNull();
71
+ });
72
+ });