@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,364 @@
1
+ import { useCallback, useMemo, useState } from 'react';
2
+ import { MessageSquare, MessagesSquare } from 'lucide-react';
3
+ import { Group, Panel, Separator, useDefaultLayout } from 'react-resizable-panels';
4
+ import { usePrViewer } from '../state/pr-viewer.context';
5
+ import { useAuth } from '../../auth/state/auth.context';
6
+ import {
7
+ approvePrFile,
8
+ unapprovePrFile,
9
+ } from '../services/pr-approvals.api';
10
+ import {
11
+ deletePrComment,
12
+ editPrComment,
13
+ postPrComment,
14
+ } from '../services/pr-comments.api';
15
+ import { PrHeader } from './PrHeader';
16
+ import { PrFilesList } from './PrFilesList';
17
+ import { PrDiffPane } from './PrDiffPane';
18
+ import { PrCommentsPanel } from './PrCommentsPanel';
19
+
20
+ /**
21
+ * Full-overlay PR viewer. Mounts when `openPrNumber` is set — sits on top of
22
+ * the file viewer in the main content area (same absolute-inset-0 strategy as
23
+ * the agent-change ReviewPanel).
24
+ */
25
+ type CommentScope = 'file' | 'all';
26
+
27
+ const PR_LAYOUT_ID = 'bevel-pr-viewer-v1';
28
+ const PR_PANEL_IDS = ['files', 'diff', 'comments'];
29
+ const SEPARATOR_CLASS =
30
+ 'w-px bg-slate-100 hover:bg-bevel-deep/60 data-[dragging=true]:bg-bevel-deep transition-colors outline-none focus-visible:bg-bevel-deep cursor-col-resize';
31
+
32
+ function getSafeLocalStorage(): Storage | undefined {
33
+ if (typeof window === 'undefined') return undefined;
34
+ try {
35
+ const storage = window.localStorage;
36
+ const probeKey = `${PR_LAYOUT_ID}:storage-probe`;
37
+ storage.setItem(probeKey, '1');
38
+ storage.removeItem(probeKey);
39
+ return storage;
40
+ } catch {
41
+ return undefined;
42
+ }
43
+ }
44
+
45
+ export function PrViewer() {
46
+ const { openPrNumber, detail, selectedPath, isLoading, lastError, notFound, closeViewer, selectPath, refresh } =
47
+ usePrViewer();
48
+ const { user } = useAuth();
49
+ const currentUserEmail = user?.email ?? '';
50
+
51
+ // "Current file" is the more useful default for multi-file PRs — when a reviewer
52
+ // lands on a file they want to see that file's discussion first, not the whole thread.
53
+ const [commentScope, setCommentScope] = useState<CommentScope>('file');
54
+
55
+ const layoutStorage = useMemo(() => getSafeLocalStorage(), []);
56
+ const { defaultLayout, onLayoutChanged } = useDefaultLayout({
57
+ id: PR_LAYOUT_ID,
58
+ panelIds: PR_PANEL_IDS,
59
+ storage: layoutStorage,
60
+ });
61
+
62
+ // Tracks which path has an approve/unapprove request in flight. One-at-a-time
63
+ // keeps the UI simple and prevents a user from firing a second request before
64
+ // the first settles and the detail refreshes.
65
+ const [busyPath, setBusyPath] = useState<string | null>(null);
66
+
67
+ const handleApprove = useCallback(
68
+ async (path: string) => {
69
+ if (!openPrNumber || busyPath) return;
70
+ setBusyPath(path);
71
+ try {
72
+ await approvePrFile(openPrNumber, path);
73
+ await refresh();
74
+ } catch (err) {
75
+ console.error('[pr] approveFile failed:', err);
76
+ } finally {
77
+ setBusyPath(null);
78
+ }
79
+ },
80
+ [openPrNumber, busyPath, refresh],
81
+ );
82
+
83
+ const handleUnapprove = useCallback(
84
+ async (path: string) => {
85
+ if (!openPrNumber || busyPath) return;
86
+ setBusyPath(path);
87
+ try {
88
+ await unapprovePrFile(openPrNumber, path);
89
+ await refresh();
90
+ } catch (err) {
91
+ console.error('[pr] unapproveFile failed:', err);
92
+ } finally {
93
+ setBusyPath(null);
94
+ }
95
+ },
96
+ [openPrNumber, busyPath, refresh],
97
+ );
98
+
99
+ // Inline-comment handlers share the same post/edit/delete API as the side
100
+ // panel. Each awaits refresh() so the diff pane's inline-thread render picks
101
+ // up the new state without a second round-trip. Post/reply/edit rethrow so
102
+ // the composer surfaces the error; delete swallows because the icon button
103
+ // has no UI to show it — log instead, same pattern as handleApprove above.
104
+ const handlePostLineComment = useCallback(
105
+ async (path: string, line: number, body: string) => {
106
+ if (!openPrNumber) return;
107
+ try {
108
+ await postPrComment(openPrNumber, { body, path, line });
109
+ await refresh();
110
+ } catch (err) {
111
+ console.error('[pr] postLineComment failed:', err);
112
+ throw err;
113
+ }
114
+ },
115
+ [openPrNumber, refresh],
116
+ );
117
+ const handleReplyComment = useCallback(
118
+ async (parentId: string, body: string) => {
119
+ if (!openPrNumber) return;
120
+ try {
121
+ await postPrComment(openPrNumber, { body, parentId });
122
+ await refresh();
123
+ } catch (err) {
124
+ console.error('[pr] replyComment failed:', err);
125
+ throw err;
126
+ }
127
+ },
128
+ [openPrNumber, refresh],
129
+ );
130
+ const handleEditComment = useCallback(
131
+ async (commentId: string, body: string) => {
132
+ if (!openPrNumber) return;
133
+ try {
134
+ await editPrComment(openPrNumber, commentId, body);
135
+ await refresh();
136
+ } catch (err) {
137
+ console.error('[pr] editComment failed:', err);
138
+ throw err;
139
+ }
140
+ },
141
+ [openPrNumber, refresh],
142
+ );
143
+ const handleDeleteComment = useCallback(
144
+ async (commentId: string) => {
145
+ if (!openPrNumber) return;
146
+ try {
147
+ await deletePrComment(openPrNumber, commentId);
148
+ await refresh();
149
+ } catch (err) {
150
+ console.error('[pr] deleteComment failed:', err);
151
+ }
152
+ },
153
+ [openPrNumber, refresh],
154
+ );
155
+
156
+ const selectedFile = useMemo(() => {
157
+ if (!detail || !selectedPath) return null;
158
+ return detail.files.find((f) => f.path === selectedPath) ?? null;
159
+ }, [detail, selectedPath]);
160
+
161
+ // Inline-anchored comments for the currently-selected file. Narrowed here
162
+ // (rather than inside PrDiffPane) so the pane doesn't have to know about
163
+ // the detail shape or run this filter on every re-render.
164
+ const selectedFileLineComments = useMemo(() => {
165
+ if (!detail || !selectedPath) return [];
166
+ return detail.comments.filter(
167
+ (c) => c.path === selectedPath && c.line !== undefined,
168
+ );
169
+ }, [detail, selectedPath]);
170
+
171
+ // Unread/count hints on the scope toggle so the user knows there's discussion
172
+ // elsewhere even when they're filtering to one file.
173
+ const commentCounts = useMemo(() => {
174
+ if (!detail) return { total: 0, currentFile: 0 };
175
+ const total = detail.comments.length;
176
+ const currentFile = selectedPath
177
+ ? detail.comments.filter((c) => c.path === selectedPath).length
178
+ : 0;
179
+ return { total, currentFile };
180
+ }, [detail, selectedPath]);
181
+
182
+ if (openPrNumber === null) return null;
183
+
184
+ if (isLoading && !detail) {
185
+ return (
186
+ <div className="absolute inset-0 z-30 flex flex-col bg-white overflow-hidden">
187
+ <div className="h-10 border-b border-slate-200 flex items-center px-3 gap-2 shrink-0">
188
+ <span className="text-sm text-slate-700">Loading change request…</span>
189
+ <button
190
+ type="button"
191
+ onClick={closeViewer}
192
+ className="ml-auto text-xs text-slate-600 hover:text-slate-900 px-2 py-1 rounded hover:bg-slate-100"
193
+ >
194
+ Close
195
+ </button>
196
+ </div>
197
+ </div>
198
+ );
199
+ }
200
+
201
+ // The CR no longer exists (404) — the common case when a routine deep-links a
202
+ // change request whose row is gone (merged and cleaned up, or removed). Show a
203
+ // calm "no longer available" state rather than an alarming red error.
204
+ if (notFound) {
205
+ return (
206
+ <div className="absolute inset-0 z-30 flex flex-col bg-white overflow-hidden">
207
+ <div className="h-10 border-b border-slate-200 flex items-center px-3 gap-2 shrink-0">
208
+ <span className="text-sm text-slate-700">Change request #{openPrNumber}</span>
209
+ <button
210
+ type="button"
211
+ onClick={closeViewer}
212
+ className="ml-auto text-xs text-slate-600 hover:text-slate-900 px-2 py-1 rounded hover:bg-slate-100"
213
+ >
214
+ Close
215
+ </button>
216
+ </div>
217
+ <div className="flex-1 flex items-center justify-center px-6 text-center">
218
+ <div className="max-w-md space-y-2">
219
+ <div className="text-sm text-slate-700">
220
+ This change request is no longer available.
221
+ </div>
222
+ <div className="text-xs text-slate-600">
223
+ It may have been merged and cleaned up, or removed. There's nothing left to review.
224
+ </div>
225
+ </div>
226
+ </div>
227
+ </div>
228
+ );
229
+ }
230
+
231
+ if (lastError) {
232
+ return (
233
+ <div className="absolute inset-0 z-30 flex flex-col bg-white overflow-hidden">
234
+ <div className="h-10 border-b border-slate-200 flex items-center px-3 gap-2 shrink-0">
235
+ <span className="text-sm text-red-700">Couldn't load change request #{openPrNumber}</span>
236
+ <button
237
+ type="button"
238
+ onClick={closeViewer}
239
+ className="ml-auto text-xs text-slate-600 hover:text-slate-900 px-2 py-1 rounded hover:bg-slate-100"
240
+ >
241
+ Close
242
+ </button>
243
+ </div>
244
+ <div className="flex-1 flex items-center justify-center px-6 text-center">
245
+ <div className="max-w-md space-y-2">
246
+ <div className="text-sm text-slate-700">Couldn't load this change request.</div>
247
+ <div className="text-xs text-slate-600">{lastError}</div>
248
+ </div>
249
+ </div>
250
+ </div>
251
+ );
252
+ }
253
+
254
+ if (!detail) return null;
255
+
256
+ return (
257
+ <div className="absolute inset-0 z-30 flex flex-col bg-white overflow-hidden">
258
+ <PrHeader detail={detail} onCloseViewer={closeViewer} onResolved={closeViewer} onRefreshed={refresh} />
259
+ <Group
260
+ orientation="horizontal"
261
+ defaultLayout={defaultLayout}
262
+ onLayoutChanged={onLayoutChanged}
263
+ className="flex-1 flex min-h-0"
264
+ >
265
+ <Panel id="files" defaultSize="20%" minSize="12%" maxSize="40%">
266
+ <div className="h-full flex flex-col">
267
+ <PrFilesList
268
+ files={detail.files}
269
+ approvals={detail.approvals}
270
+ selectedPath={selectedPath}
271
+ currentUserEmail={currentUserEmail}
272
+ busyPath={busyPath}
273
+ onSelect={selectPath}
274
+ onApprove={handleApprove}
275
+ onUnapprove={handleUnapprove}
276
+ />
277
+ </div>
278
+ </Panel>
279
+ <Separator className={SEPARATOR_CLASS} />
280
+ <Panel id="diff" minSize="30%">
281
+ <div className="h-full min-w-0 min-h-0">
282
+ <PrDiffPane
283
+ file={selectedFile}
284
+ lineComments={selectedFileLineComments}
285
+ currentUserEmail={currentUserEmail}
286
+ currentHeadSha={detail.headSha}
287
+ onPostLineComment={(line, body) =>
288
+ selectedFile
289
+ ? handlePostLineComment(selectedFile.path, line, body)
290
+ : Promise.resolve()
291
+ }
292
+ onReplyComment={handleReplyComment}
293
+ onEditComment={handleEditComment}
294
+ onDeleteComment={handleDeleteComment}
295
+ />
296
+ </div>
297
+ </Panel>
298
+ <Separator className={SEPARATOR_CLASS} />
299
+ <Panel id="comments" defaultSize="25%" minSize="14%" maxSize="50%">
300
+ <div className="h-full flex flex-col">
301
+ <div className="flex items-center border-b border-slate-200 shrink-0">
302
+ <ScopeButton
303
+ active={commentScope === 'file'}
304
+ disabled={!selectedPath}
305
+ onClick={() => setCommentScope('file')}
306
+ icon={<MessageSquare size={11} />}
307
+ label={selectedPath ? 'Current file' : 'File'}
308
+ count={commentCounts.currentFile}
309
+ />
310
+ <ScopeButton
311
+ active={commentScope === 'all'}
312
+ onClick={() => setCommentScope('all')}
313
+ icon={<MessagesSquare size={11} />}
314
+ label="All"
315
+ count={commentCounts.total}
316
+ />
317
+ </div>
318
+ <PrCommentsPanel
319
+ detail={detail}
320
+ filterPath={commentScope === 'file' ? selectedPath : null}
321
+ />
322
+ </div>
323
+ </Panel>
324
+ </Group>
325
+ </div>
326
+ );
327
+ }
328
+
329
+ function ScopeButton({
330
+ active,
331
+ disabled,
332
+ onClick,
333
+ icon,
334
+ label,
335
+ count,
336
+ }: {
337
+ active: boolean;
338
+ disabled?: boolean;
339
+ onClick(): void;
340
+ icon: React.ReactNode;
341
+ label: string;
342
+ count: number;
343
+ }) {
344
+ return (
345
+ <button
346
+ type="button"
347
+ onClick={onClick}
348
+ disabled={disabled}
349
+ className={`flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs transition-colors ${
350
+ active
351
+ ? 'bg-white text-slate-900'
352
+ : 'text-slate-600 hover:text-slate-900 hover:bg-white/50'
353
+ } disabled:opacity-40 disabled:cursor-not-allowed`}
354
+ >
355
+ {icon}
356
+ {label}
357
+ {count > 0 && (
358
+ <span className={`text-[10px] px-1 rounded ${active ? 'bg-slate-100 text-slate-700' : 'bg-slate-100/80 text-slate-600'}`}>
359
+ {count}
360
+ </span>
361
+ )}
362
+ </button>
363
+ );
364
+ }
@@ -0,0 +1,150 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
+ import type { PullRequestDetail } from '@bevel-software/platform-shared';
3
+ import type { PrViewerContextValue } from '../state/pr-viewer.context';
4
+ import { fetchPrDetail } from '../services/pr-detail.api';
5
+ import { GitApiError } from '../../git/services/git.api';
6
+ import { useEventBus } from '../../workflow/state/event-bus.context';
7
+
8
+ export function usePrViewerState(): PrViewerContextValue {
9
+ const [openPrNumber, setOpenPrNumber] = useState<number | null>(null);
10
+ const [detail, setDetail] = useState<PullRequestDetail | null>(null);
11
+ const [selectedPath, setSelectedPath] = useState<string | null>(null);
12
+ const [isLoading, setIsLoading] = useState(false);
13
+ const [lastError, setLastError] = useState<string | null>(null);
14
+ const [notFound, setNotFound] = useState(false);
15
+
16
+ // Ignore responses for a PR the user has already closed or swapped away
17
+ // from. Kept synchronously in sync with `openPrNumber` by openPr/closeViewer —
18
+ // NOT via a useEffect, because effects run after the commit phase, and a
19
+ // stale in-flight fetch can resolve between `setOpenPrNumber(n)` and the
20
+ // effect firing. In that window `isLatest()` would still read the previous
21
+ // ref and accept the stale response. Every update path to `openPrNumber`
22
+ // must therefore update this ref first.
23
+ const openPrRef = useRef<number | null>(null);
24
+ const fetchSeqRef = useRef(0);
25
+
26
+ const loadDetail = useCallback(
27
+ async (
28
+ prNumber: number,
29
+ opts: { fresh?: boolean; preserveDetailOnError?: boolean } = {},
30
+ ) => {
31
+ const token = ++fetchSeqRef.current;
32
+ const isLatest = () => openPrRef.current === prNumber && fetchSeqRef.current === token;
33
+ setIsLoading(true);
34
+ setLastError(null);
35
+ setNotFound(false);
36
+ try {
37
+ const next = await fetchPrDetail(prNumber, { fresh: opts.fresh });
38
+ if (!isLatest()) return;
39
+ setDetail(next);
40
+ // Auto-select the first file so the diff pane isn't blank. Only on initial
41
+ // load — a refresh shouldn't snap the user back to file 0.
42
+ setSelectedPath((prev) => {
43
+ if (prev && next.files.some((f) => f.path === prev)) return prev;
44
+ return next.files[0]?.path ?? null;
45
+ });
46
+ } catch (err) {
47
+ if (!isLatest()) return;
48
+ // A 404 means the CR row is gone (merged-and-cleaned-up, removed, or a
49
+ // routine deep-linking a stale CR number). That's an expected, benign
50
+ // outcome — surface it as a calm "no longer available" state, not an
51
+ // alarming error. Any other status is a real failure worth showing +
52
+ // retrying.
53
+ const gone = err instanceof GitApiError && err.status === 404;
54
+ setNotFound(gone);
55
+ setLastError(err instanceof Error ? err.message : 'Unknown error');
56
+ // Initial load / PR swap nulls the stale detail so the viewer falls
57
+ // back to its error state. Refreshes preserve the currently-rendered
58
+ // detail — a transient network blip shouldn't wipe out the PR the
59
+ // user was already reading.
60
+ if (!opts.preserveDetailOnError) setDetail(null);
61
+ } finally {
62
+ if (isLatest()) setIsLoading(false);
63
+ }
64
+ },
65
+ [],
66
+ );
67
+
68
+ // Fetch whenever the open PR number changes (including on close → null).
69
+ useEffect(() => {
70
+ if (openPrNumber === null) {
71
+ setDetail(null);
72
+ setSelectedPath(null);
73
+ setIsLoading(false);
74
+ setLastError(null);
75
+ setNotFound(false);
76
+ return;
77
+ }
78
+ // Clear the previous PR's state synchronously so the viewer doesn't flash
79
+ // PR A's header/file list while PR B is still loading. `loadDetail` sets
80
+ // isLoading itself, but it only nulls `detail` on failure — on success it
81
+ // overwrites, which leaves the stale detail visible until the fetch
82
+ // resolves.
83
+ setDetail(null);
84
+ setSelectedPath(null);
85
+ setLastError(null);
86
+ setNotFound(false);
87
+ setIsLoading(true);
88
+ loadDetail(openPrNumber);
89
+ }, [openPrNumber, loadDetail]);
90
+
91
+ const openPr = useCallback((prNumber: number) => {
92
+ openPrRef.current = prNumber;
93
+ setOpenPrNumber(prNumber);
94
+ }, []);
95
+
96
+ const closeViewer = useCallback(() => {
97
+ openPrRef.current = null;
98
+ setOpenPrNumber(null);
99
+ }, []);
100
+
101
+ const selectPath = useCallback((path: string | null) => {
102
+ setSelectedPath(path);
103
+ }, []);
104
+
105
+ const refresh = useCallback(async () => {
106
+ const current = openPrRef.current;
107
+ if (current === null) return;
108
+ await loadDetail(current, { fresh: true, preserveDetailOnError: true });
109
+ }, [loadDetail]);
110
+
111
+ // Refresh the open CR detail when the workflow bus signals that this CR
112
+ // mutated server-side: someone added/removed an approval, merged it, or
113
+ // rejected it. We skip the refresh when the viewer is closed
114
+ // (`openPrRef.current === null`) — there's nothing to refresh. Merge and
115
+ // reject events drive the same `refresh` call because the detail-fetch
116
+ // returns the new `state` (merged / closed) which the viewer renders
117
+ // appropriately; we don't need a different code path per event kind.
118
+ const bus = useEventBus();
119
+ useEffect(() => {
120
+ if (!bus) return;
121
+ const triggerIfMatching = (number: number) => {
122
+ if (openPrRef.current !== number) return;
123
+ void refresh();
124
+ };
125
+ const offApproval = bus.subscribe('approval-changed', (e) => triggerIfMatching(e.number));
126
+ const offMerged = bus.subscribe('change-request-merged', (e) => triggerIfMatching(e.number));
127
+ const offRejected = bus.subscribe('change-request-rejected', (e) => triggerIfMatching(e.number));
128
+ return () => {
129
+ offApproval();
130
+ offMerged();
131
+ offRejected();
132
+ };
133
+ }, [bus, refresh]);
134
+
135
+ return useMemo(
136
+ () => ({
137
+ openPrNumber,
138
+ detail,
139
+ selectedPath,
140
+ isLoading,
141
+ lastError,
142
+ notFound,
143
+ openPr,
144
+ closeViewer,
145
+ selectPath,
146
+ refresh,
147
+ }),
148
+ [openPrNumber, detail, selectedPath, isLoading, lastError, notFound, openPr, closeViewer, selectPath, refresh],
149
+ );
150
+ }
@@ -0,0 +1,31 @@
1
+ import type { FileApprovalState } from '@bevel-software/platform-shared';
2
+ import { authFetch } from '../../../lib/api';
3
+ import { handleApiResponse } from '../../git/services/git.api';
4
+
5
+ export async function approvePrFile(
6
+ prNumber: number,
7
+ path: string,
8
+ ): Promise<FileApprovalState[]> {
9
+ const data = await handleApiResponse<{ approvals: FileApprovalState[] }>(
10
+ await authFetch(`/api/workflow/change-requests/${prNumber}/files/approve`, {
11
+ method: 'POST',
12
+ headers: { 'Content-Type': 'application/json' },
13
+ body: JSON.stringify({ path }),
14
+ }),
15
+ );
16
+ return data.approvals;
17
+ }
18
+
19
+ export async function unapprovePrFile(
20
+ prNumber: number,
21
+ path: string,
22
+ ): Promise<FileApprovalState[]> {
23
+ // `path` goes in the query string rather than a DELETE body — some proxies
24
+ // strip request bodies on DELETE. `encodeURIComponent` handles the slashes
25
+ // in KB paths (e.g. `Process/Checkout.md`) cleanly.
26
+ const qs = new URLSearchParams({ path }).toString();
27
+ const data = await handleApiResponse<{ approvals: FileApprovalState[] }>(
28
+ await authFetch(`/api/workflow/change-requests/${prNumber}/files/approve?${qs}`, { method: 'DELETE' }),
29
+ );
30
+ return data.approvals;
31
+ }
@@ -0,0 +1,19 @@
1
+ import type { CancelPrResult } from '@bevel-software/platform-shared';
2
+ import { authFetch } from '../../../lib/api';
3
+ import { handleApiResponse } from '../../git/services/git.api';
4
+
5
+ /**
6
+ * Close the change request without merging. The backend re-validates that the
7
+ * caller is the author or a base-branch admin (same predicate driving the
8
+ * `viewerCanCancel` UI hint), refuses if the PR is already merged/closed, and
9
+ * shells out to `gh pr close`. No body needed — author/admin gate is server-side.
10
+ */
11
+ export async function cancelPullRequest(prNumber: number): Promise<CancelPrResult> {
12
+ return handleApiResponse(
13
+ await authFetch(`/api/workflow/change-requests/${prNumber}/reject`, {
14
+ method: 'POST',
15
+ headers: { 'Content-Type': 'application/json' },
16
+ body: '{}',
17
+ }),
18
+ );
19
+ }
@@ -0,0 +1,45 @@
1
+ import type { PostPrCommentInput, PrReviewComment } from '@bevel-software/platform-shared';
2
+ import { authFetch } from '../../../lib/api';
3
+ import { handleApiResponse } from '../../git/services/git.api';
4
+
5
+ export async function listPrComments(prNumber: number): Promise<PrReviewComment[]> {
6
+ return handleApiResponse(await authFetch(`/api/workflow/change-requests/${prNumber}/comments`));
7
+ }
8
+
9
+ export async function postPrComment(
10
+ prNumber: number,
11
+ input: PostPrCommentInput,
12
+ ): Promise<PrReviewComment> {
13
+ return handleApiResponse(
14
+ await authFetch(`/api/workflow/change-requests/${prNumber}/comments`, {
15
+ method: 'POST',
16
+ headers: { 'Content-Type': 'application/json' },
17
+ body: JSON.stringify(input),
18
+ }),
19
+ );
20
+ }
21
+
22
+ export async function editPrComment(
23
+ prNumber: number,
24
+ commentId: string,
25
+ body: string,
26
+ ): Promise<PrReviewComment> {
27
+ return handleApiResponse(
28
+ await authFetch(`/api/workflow/change-requests/${prNumber}/comments/${commentId}`, {
29
+ method: 'PATCH',
30
+ headers: { 'Content-Type': 'application/json' },
31
+ body: JSON.stringify({ body }),
32
+ }),
33
+ );
34
+ }
35
+
36
+ export async function deletePrComment(
37
+ prNumber: number,
38
+ commentId: string,
39
+ ): Promise<void> {
40
+ await handleApiResponse(
41
+ await authFetch(`/api/workflow/change-requests/${prNumber}/comments/${commentId}`, {
42
+ method: 'DELETE',
43
+ }),
44
+ );
45
+ }
@@ -0,0 +1,17 @@
1
+ import type { PullRequestDetail } from '@bevel-software/platform-shared';
2
+ import { authFetch } from '../../../lib/api';
3
+ import { handleApiResponse } from '../../git/services/git.api';
4
+
5
+ /**
6
+ * Fetch the full PR detail (metadata + file diffs). `fresh` bypasses the
7
+ * backend's 30s detail cache — use from event-driven refreshes (post-merge,
8
+ * post-comment, post-open-change-request) but leave off for user-triggered
9
+ * navigation.
10
+ */
11
+ export async function fetchPrDetail(
12
+ prNumber: number,
13
+ opts: { fresh?: boolean } = {},
14
+ ): Promise<PullRequestDetail> {
15
+ const query = opts.fresh ? '?fresh=1' : '';
16
+ return handleApiResponse(await authFetch(`/api/workflow/change-requests/${prNumber}/detail${query}`));
17
+ }
@@ -0,0 +1,53 @@
1
+ import { authFetch } from '../../../lib/api';
2
+ import { handleApiResponse } from '../../git/services/git.api';
3
+
4
+ /** The 202 ack the merge endpoint returns — the merge then runs in the background. */
5
+ export interface MergeAccepted {
6
+ status: 'merging';
7
+ number: number;
8
+ }
9
+
10
+ /**
11
+ * Trigger the server-side merge. `bypass: true` tells the gate to proceed
12
+ * despite soft warnings (unapproved md-with-owner files); the bypassed list
13
+ * is inlined in the merge commit body for audit. Hard blocks (PR closed,
14
+ * no files) are refused regardless.
15
+ *
16
+ * **Asynchronous** — the gate re-validation + `gh pr merge` can take tens of
17
+ * seconds on a large change request (long enough to hit the gateway's idle
18
+ * timeout), so the endpoint acks with 202 and runs the merge in the
19
+ * background. The outcome arrives over the workflow event bus:
20
+ * `change-request-merged` on success, `change-request-merge-failed`
21
+ * (with a `conflicts` flag) on failure. Callers show a pending state until
22
+ * one of those events lands.
23
+ */
24
+ export async function mergePullRequest(
25
+ prNumber: number,
26
+ opts: { bypass?: boolean } = {},
27
+ ): Promise<MergeAccepted> {
28
+ return handleApiResponse(
29
+ await authFetch(`/api/workflow/change-requests/${prNumber}/merge`, {
30
+ method: 'POST',
31
+ headers: { 'Content-Type': 'application/json' },
32
+ body: JSON.stringify({ bypass: opts.bypass === true }),
33
+ }),
34
+ );
35
+ }
36
+
37
+ /**
38
+ * Re-runs the auto-merge of target → source on an existing change request.
39
+ * On clean merge, the CR detail refreshes to reflect the new diff. On
40
+ * conflicts, the response body carries the structured
41
+ * `change-request-conflicts` error payload (status 409) listing the
42
+ * conflicting paths — the caller catches it via `GitApiError` and
43
+ * routes the agent into the resolution flow.
44
+ */
45
+ export async function refreshChangeRequestFromTarget(prNumber: number): Promise<unknown> {
46
+ return handleApiResponse(
47
+ await authFetch(`/api/workflow/change-requests/${prNumber}/update-from-target`, {
48
+ method: 'POST',
49
+ headers: { 'Content-Type': 'application/json' },
50
+ body: '{}',
51
+ }),
52
+ );
53
+ }