@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,58 @@
1
+ import { useEffect, useRef, useState, type ReactNode } from 'react';
2
+ import { MoreHorizontal } from 'lucide-react';
3
+
4
+ interface Props {
5
+ children: ReactNode;
6
+ }
7
+
8
+ /**
9
+ * Container-query-friendly overflow menu for the change-request header. When
10
+ * the header runs out of horizontal space, secondary actions collapse into
11
+ * this "⋯" dropdown instead of spilling under the chat panel.
12
+ *
13
+ * Children are rendered as stacked rows in the popover — pass the existing
14
+ * action buttons (PrRefreshFromTargetButton, PrCancelButton) and they keep
15
+ * their existing dialog/callback behavior unchanged.
16
+ */
17
+ export function PrHeaderOverflowMenu({ children }: Props) {
18
+ const [open, setOpen] = useState(false);
19
+ const ref = useRef<HTMLDivElement>(null);
20
+
21
+ useEffect(() => {
22
+ if (!open) return;
23
+ const onMouseDown = (e: MouseEvent) => {
24
+ if (ref.current && !ref.current.contains(e.target as Node)) {
25
+ setOpen(false);
26
+ }
27
+ };
28
+ const onKey = (e: KeyboardEvent) => {
29
+ if (e.key === 'Escape') setOpen(false);
30
+ };
31
+ document.addEventListener('mousedown', onMouseDown);
32
+ document.addEventListener('keydown', onKey);
33
+ return () => {
34
+ document.removeEventListener('mousedown', onMouseDown);
35
+ document.removeEventListener('keydown', onKey);
36
+ };
37
+ }, [open]);
38
+
39
+ return (
40
+ <div ref={ref} className="relative">
41
+ <button
42
+ type="button"
43
+ onClick={() => setOpen((v) => !v)}
44
+ className="flex items-center px-2 py-1 text-xs rounded text-slate-700 hover:bg-slate-100"
45
+ aria-label="More actions"
46
+ aria-expanded={open}
47
+ title="More actions"
48
+ >
49
+ <MoreHorizontal size={14} />
50
+ </button>
51
+ {open && (
52
+ <div className="absolute right-0 top-full mt-1 z-40 bg-white border border-slate-200 rounded shadow-md py-1 flex flex-col items-stretch min-w-[14rem]">
53
+ {children}
54
+ </div>
55
+ )}
56
+ </div>
57
+ );
58
+ }
@@ -0,0 +1,268 @@
1
+ import { useEffect, useRef, useState } from 'react';
2
+ import { GitMerge } from 'lucide-react';
3
+ import { protectedBranchDisplayName, type PullRequestDetail } from '@bevel-software/platform-shared';
4
+ import { mergePullRequest } from '../services/pr-merge.api';
5
+ import { fetchPrDetail } from '../services/pr-detail.api';
6
+ import { PrMergeConfirmDialog } from './PrMergeConfirmDialog';
7
+ import { useCrCreationPort } from '../../../core/registry';
8
+ import { PR_STALE_EVENT } from '../../../core/events';
9
+ import { useEventBus } from '../../workflow/state/event-bus.context';
10
+
11
+ /**
12
+ * Safety net for the async merge: if neither a `change-request-merged` nor a
13
+ * `change-request-merge-failed` event lands within this window (a dropped SSE
14
+ * connection, a backend crash mid-merge), stop the spinner and tell the user to
15
+ * refresh. Generous — `gh pr merge` alone has a 60s server budget.
16
+ */
17
+ const MERGE_RESULT_TIMEOUT_MS = 180_000;
18
+
19
+ /**
20
+ * Polling fallback cadence while a merge is in flight. The merge outcome
21
+ * normally arrives over the SSE event bus, but that connection can drop (proxy
22
+ * 502 / backend restart mid-merge) and take the `change-request-merged` event
23
+ * with it — leaving the button stuck on "Applying…" even though the apply
24
+ * landed. So we ALSO poll the CR's real state as a backstop: once it leaves
25
+ * `open`, the apply succeeded. Bounded by `MERGE_RESULT_TIMEOUT_MS` above.
26
+ */
27
+ const MERGE_POLL_INTERVAL_MS = 4_000;
28
+
29
+ interface Props {
30
+ detail: PullRequestDetail;
31
+ /** Invoked after a successful merge. The viewer uses this to close itself + refresh state. */
32
+ onMerged(): void;
33
+ /**
34
+ * Drop the "to {base}" suffix from the button label so it stays narrow.
35
+ * The full sentence still appears in the `title` tooltip. The change-request
36
+ * header passes this so the button + overflow menu + close `X` all fit
37
+ * even when the chat panel is open.
38
+ */
39
+ compact?: boolean;
40
+ }
41
+
42
+ /**
43
+ * Three-state merge action:
44
+ * - Hidden for merged/closed PRs.
45
+ * - Disabled (neutral) when a hard block applies (no files, etc.).
46
+ * - Yellow when soft warnings exist (pending md-with-owner approvals) —
47
+ * clicking opens a confirm dialog with a bypass checkbox.
48
+ * - Purple (default) when the gate is clean — one click merges directly.
49
+ */
50
+ export function PrMergeButton({ detail, onMerged, compact = false }: Props) {
51
+ const [busy, setBusy] = useState(false);
52
+ const [error, setError] = useState<string | null>(null);
53
+ const [showBypassDialog, setShowBypassDialog] = useState(false);
54
+ const crPort = useCrCreationPort();
55
+ // Merge is irreversible — guard with a ref so a rapid double-click (or the
56
+ // button + dialog-confirm both firing in the same tick) can't issue two
57
+ // `gh pr merge` calls. The `busy` state alone has a one-render lag window
58
+ // where both click handlers still see `busy=false` even though the first
59
+ // has already kicked off the request.
60
+ const mergingRef = useRef(false);
61
+ const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
62
+ const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
63
+ const bus = useEventBus();
64
+
65
+ const stopMerging = () => {
66
+ if (timeoutRef.current) {
67
+ clearTimeout(timeoutRef.current);
68
+ timeoutRef.current = null;
69
+ }
70
+ if (pollRef.current) {
71
+ clearInterval(pollRef.current);
72
+ pollRef.current = null;
73
+ }
74
+ mergingRef.current = false;
75
+ setBusy(false);
76
+ };
77
+
78
+ // Shared success path — run when the apply lands, whether that's signalled by
79
+ // the `change-request-merged` SSE event below or detected by the polling
80
+ // fallback in `runMerge` (the event is lost if the SSE connection drops
81
+ // mid-merge, which is what leaves the button stuck on "Applying…").
82
+ function succeed() {
83
+ stopMerging();
84
+ setShowBypassDialog(false);
85
+ // Refresh the PR sidebar immediately (same mechanism the share dialog uses).
86
+ window.dispatchEvent(new CustomEvent(PR_STALE_EVENT));
87
+ onMerged();
88
+ }
89
+
90
+ // Polling fallback for a lost merge-result event. `fetchPrDetail` with
91
+ // `fresh` bypasses the 30s detail cache so a just-merged CR shows its
92
+ // terminal state promptly. Failures (often the same outage that dropped the
93
+ // SSE event) are swallowed — the next tick retries until the merge lands or
94
+ // the safety timeout fires.
95
+ async function pollMergeState() {
96
+ if (!mergingRef.current) return;
97
+ try {
98
+ const latest = await fetchPrDetail(detail.number, { fresh: true });
99
+ if (!mergingRef.current) return;
100
+ if (latest.state !== 'open') succeed();
101
+ } catch {
102
+ /* transient — keep polling */
103
+ }
104
+ }
105
+
106
+ // The merge runs in the background server-side (the POST only acks with 202),
107
+ // so its outcome arrives over the event bus. We react only to events for THIS
108
+ // change request that THIS button kicked off (`mergingRef`) — other tabs /
109
+ // users get the same global success event but shouldn't drive this button's
110
+ // close-and-seed-chat side effects.
111
+ useEffect(() => {
112
+ if (!bus) return;
113
+ const offMerged = bus.subscribe('change-request-merged', (e) => {
114
+ if (!mergingRef.current || e.number !== detail.number) return;
115
+ succeed();
116
+ });
117
+ const offFailed = bus.subscribe('change-request-merge-failed', (e) => {
118
+ if (!mergingRef.current || e.number !== detail.number) return;
119
+ stopMerging();
120
+ if (e.conflicts && crPort?.resolveCrConflicts) {
121
+ // **The user never sees the conflict.** Hand it to the change-request
122
+ // port — the enterprise registry seeds the chat composer with a
123
+ // resolution request and auto-sends it; the agent walks the resolution
124
+ // flow (same behaviour as the old synchronous path, now event-driven).
125
+ // Without a registered resolver the failure falls through to the
126
+ // inline error below.
127
+ crPort.resolveCrConflicts({
128
+ kind: 'apply',
129
+ changeRequestNumber: detail.number,
130
+ base: detail.base,
131
+ conflictedPaths: [],
132
+ });
133
+ setShowBypassDialog(false);
134
+ return;
135
+ }
136
+ // Close the bypass dialog (if the merge was triggered through it) before
137
+ // surfacing the error, so the banner isn't stranded behind the dialog.
138
+ setShowBypassDialog(false);
139
+ setError(e.reason || "Couldn't apply changes");
140
+ });
141
+ return () => {
142
+ offMerged();
143
+ offFailed();
144
+ };
145
+ // eslint-disable-next-line react-hooks/exhaustive-deps
146
+ }, [bus, detail.number, detail.base, onMerged, crPort]);
147
+
148
+ // Clear a pending safety timeout only when the button truly unmounts (a merge
149
+ // that succeeds unmounts it) — NOT on every re-subscribe above, which would
150
+ // drop the timer for an in-flight merge.
151
+ useEffect(() => () => {
152
+ if (timeoutRef.current) clearTimeout(timeoutRef.current);
153
+ if (pollRef.current) clearInterval(pollRef.current);
154
+ }, []);
155
+
156
+ // Merged/closed PRs don't get the button at all — nothing to do.
157
+ if (detail.state !== 'open') return null;
158
+
159
+ const hardBlocked = !detail.mergeableInBevel;
160
+ const hasWarnings = detail.mergeWarnings.length > 0;
161
+ // Yellow vs purple is decided by warnings only when there's no hard block.
162
+ const needsBypass = !hardBlocked && hasWarnings;
163
+ // Bypass is admin-only on the backend (`mergePr` throws `BypassAuthError`
164
+ // on a 403 for non-admins). Surface the same gate here so the button is
165
+ // disabled with explanatory copy instead of "click → bypass dialog → 403".
166
+ const cannotBypass = needsBypass && !detail.viewerCanBypassMerge;
167
+
168
+ // Capitalised display for protected branches ("Current company state" /
169
+ // "Target company state"); fall back to the raw name for any non-protected
170
+ // base (rare in practice — most apply targets are one of the two protected
171
+ // branches — but keep the path open).
172
+ const protectedLabel = protectedBranchDisplayName(detail.base);
173
+ const baseDisplay = protectedLabel ?? detail.base;
174
+ const baseInTooltip = protectedLabel !== null ? `the ${baseDisplay}` : baseDisplay;
175
+
176
+ const tooltip = hardBlocked
177
+ ? (detail.mergeBlockedReasons.length > 0
178
+ ? detail.mergeBlockedReasons.join('\n')
179
+ : `Not ready to apply to ${baseInTooltip}`)
180
+ : cannotBypass
181
+ ? `Waiting on ${detail.mergeWarnings.length} confirmation${detail.mergeWarnings.length === 1 ? '' : 's'} — only an admin can apply now`
182
+ : needsBypass
183
+ ? `${detail.mergeWarnings.length} confirmation${detail.mergeWarnings.length === 1 ? '' : 's'} pending — click to review`
184
+ : `All files confirmed — apply this draft to ${baseInTooltip}`;
185
+
186
+ async function runMerge(opts: { bypass?: boolean }) {
187
+ if (mergingRef.current) return;
188
+ mergingRef.current = true;
189
+ setBusy(true);
190
+ setError(null);
191
+ try {
192
+ // 202 ack only — the merge runs in the background and reports via the
193
+ // event-bus subscription above. Arm a safety timeout so a lost event
194
+ // can't leave the button spinning forever.
195
+ await mergePullRequest(detail.number, opts);
196
+ // A merged/failed event can land before this 202 ack resolves (SSE is a
197
+ // separate connection); only arm the safety timeout if this attempt is
198
+ // still in flight, so the timer can't outlive it and fire during a retry.
199
+ if (!mergingRef.current) return;
200
+ timeoutRef.current = setTimeout(() => {
201
+ if (!mergingRef.current) return;
202
+ stopMerging();
203
+ setError('Applying is taking longer than expected — refresh to check its status.');
204
+ }, MERGE_RESULT_TIMEOUT_MS);
205
+ // Backstop the SSE event with state polling — see MERGE_POLL_INTERVAL_MS.
206
+ pollRef.current = setInterval(() => void pollMergeState(), MERGE_POLL_INTERVAL_MS);
207
+ } catch (err) {
208
+ // The POST itself failed (auth / bad request / network) — no background
209
+ // job started, so reset immediately rather than wait for an event.
210
+ stopMerging();
211
+ setShowBypassDialog(false);
212
+ setError(err instanceof Error ? err.message : "Couldn't apply changes");
213
+ }
214
+ }
215
+
216
+ function handleClick() {
217
+ if (busy || hardBlocked || cannotBypass) return;
218
+ if (needsBypass) {
219
+ setShowBypassDialog(true);
220
+ return;
221
+ }
222
+ void runMerge({});
223
+ }
224
+
225
+ const buttonClass = needsBypass
226
+ ? 'bg-amber-600 hover:bg-amber-500 text-white'
227
+ : 'bg-purple-700 hover:bg-purple-600 text-white';
228
+
229
+ return (
230
+ <div className="flex items-center gap-2">
231
+ {error && (
232
+ <span
233
+ role="alert"
234
+ aria-live="assertive"
235
+ className="text-[11px] text-red-700 max-w-xs truncate"
236
+ title={error}
237
+ >
238
+ {error}
239
+ </span>
240
+ )}
241
+ <button
242
+ type="button"
243
+ onClick={handleClick}
244
+ disabled={busy || hardBlocked || cannotBypass}
245
+ title={tooltip}
246
+ className={`flex items-center gap-1.5 px-2.5 py-1 text-xs rounded whitespace-nowrap shrink-0 disabled:bg-slate-100 disabled:text-slate-600 disabled:cursor-not-allowed ${buttonClass}`}
247
+ >
248
+ <GitMerge size={12} />
249
+ {busy
250
+ ? 'Applying…'
251
+ : cannotBypass
252
+ ? `Waiting on confirmations`
253
+ : compact
254
+ ? 'Apply draft'
255
+ : `Apply draft to ${baseDisplay}`}
256
+ </button>
257
+ {showBypassDialog && (
258
+ <PrMergeConfirmDialog
259
+ warnings={detail.mergeWarnings}
260
+ base={detail.base}
261
+ busy={busy}
262
+ onConfirm={() => void runMerge({ bypass: true })}
263
+ onCancel={() => setShowBypassDialog(false)}
264
+ />
265
+ )}
266
+ </div>
267
+ );
268
+ }
@@ -0,0 +1,112 @@
1
+ import { useEffect, useState } from 'react';
2
+ import { AlertTriangle, GitMerge, X } from 'lucide-react';
3
+ import { protectedBranchDisplayName } from '@bevel-software/platform-shared';
4
+
5
+ interface Props {
6
+ /** Soft warnings from the gate — one line per pending approval. */
7
+ warnings: string[];
8
+ /** Base branch the draft applies to — surfaced in the title + confirm button. */
9
+ base: string;
10
+ busy: boolean;
11
+ onConfirm(): void;
12
+ onCancel(): void;
13
+ }
14
+
15
+ /**
16
+ * Shown when the user clicks Merge on a PR with pending approvals. Lists the
17
+ * approvers the merge would skip and requires an explicit bypass checkbox
18
+ * before the Merge button in the dialog becomes enabled — so "click yellow,
19
+ * click confirm, done" isn't possible without acknowledging the warning.
20
+ */
21
+ export function PrMergeConfirmDialog({ warnings, base, busy, onConfirm, onCancel }: Props) {
22
+ const [bypassAck, setBypassAck] = useState(false);
23
+ const baseDisplay = protectedBranchDisplayName(base) ?? base;
24
+
25
+ // Escape to dismiss. Attach on mount, detach on unmount — standard modal pattern.
26
+ useEffect(() => {
27
+ function onKey(e: KeyboardEvent) {
28
+ if (e.key === 'Escape' && !busy) onCancel();
29
+ }
30
+ window.addEventListener('keydown', onKey);
31
+ return () => window.removeEventListener('keydown', onKey);
32
+ }, [busy, onCancel]);
33
+
34
+ return (
35
+ <div
36
+ className="fixed inset-0 z-50 flex items-center justify-center bg-white/60"
37
+ role="dialog"
38
+ aria-modal="true"
39
+ aria-labelledby="pr-merge-confirm-title"
40
+ >
41
+ <div className="w-[28rem] max-w-[90vw] bg-white border border-slate-200 rounded-md shadow-xl">
42
+ <div className="flex items-center gap-2 px-4 py-3 border-b border-slate-200">
43
+ <AlertTriangle size={14} className="text-amber-600 shrink-0" />
44
+ <h2
45
+ id="pr-merge-confirm-title"
46
+ className="text-sm font-medium text-slate-900 flex-1"
47
+ >
48
+ Apply draft to {baseDisplay} without all confirmations?
49
+ </h2>
50
+ <button
51
+ type="button"
52
+ onClick={onCancel}
53
+ disabled={busy}
54
+ aria-label="Cancel"
55
+ className="p-1 rounded text-slate-600 hover:text-slate-900 hover:bg-slate-100 disabled:opacity-40"
56
+ >
57
+ <X size={14} aria-hidden="true" />
58
+ </button>
59
+ </div>
60
+
61
+ <div className="px-4 py-3 space-y-3">
62
+ <p className="text-xs text-slate-700">
63
+ This draft has not been approved by:
64
+ </p>
65
+ <ul className="text-xs text-slate-700 space-y-1 max-h-48 overflow-y-auto bg-white/50 border border-slate-200 rounded px-3 py-2">
66
+ {warnings.map((w, i) => (
67
+ <li key={i} className="flex gap-1.5">
68
+ <span className="text-amber-600 shrink-0">•</span>
69
+ <span className="break-words">{w}</span>
70
+ </li>
71
+ ))}
72
+ </ul>
73
+ <label className="flex items-start gap-2 text-xs text-slate-700 cursor-pointer select-none">
74
+ <input
75
+ type="checkbox"
76
+ checked={bypassAck}
77
+ onChange={(e) => setBypassAck(e.target.checked)}
78
+ disabled={busy}
79
+ className="mt-0.5 accent-amber-500"
80
+ />
81
+ <span>
82
+ Bypass approval requirements and apply anyway.{' '}
83
+ <span className="text-slate-600">
84
+ The bypassed list is recorded in the merge commit body.
85
+ </span>
86
+ </span>
87
+ </label>
88
+ </div>
89
+
90
+ <div className="flex items-center justify-end gap-2 px-4 py-3 border-t border-slate-200">
91
+ <button
92
+ type="button"
93
+ onClick={onCancel}
94
+ disabled={busy}
95
+ className="px-3 py-1 text-xs rounded text-slate-700 hover:bg-slate-100 disabled:opacity-40"
96
+ >
97
+ Cancel
98
+ </button>
99
+ <button
100
+ type="button"
101
+ onClick={onConfirm}
102
+ disabled={busy || !bypassAck}
103
+ className="flex items-center gap-1.5 px-3 py-1 text-xs rounded bg-amber-600 hover:bg-amber-500 text-white disabled:bg-slate-100 disabled:text-slate-600 disabled:cursor-not-allowed"
104
+ >
105
+ <GitMerge size={12} aria-hidden="true" />
106
+ {busy ? 'Applying…' : `Apply to ${baseDisplay} with bypass`}
107
+ </button>
108
+ </div>
109
+ </div>
110
+ </div>
111
+ );
112
+ }
@@ -0,0 +1,110 @@
1
+ import { useRef, useState } from 'react';
2
+ import { RefreshCw } from 'lucide-react';
3
+ import { protectedBranchDisplayName, type PullRequestDetail } from '@bevel-software/platform-shared';
4
+ import { refreshChangeRequestFromTarget } from '../services/pr-merge.api';
5
+ import { GitApiError } from '../../git/services/git.api';
6
+ import { useCrCreationPort } from '../../../core/registry';
7
+ import { PR_STALE_EVENT } from '../../../core/events';
8
+
9
+ interface Props {
10
+ detail: PullRequestDetail;
11
+ /** Invoked after a successful refresh so the viewer can re-fetch the detail. */
12
+ onRefreshed(): void;
13
+ }
14
+
15
+ /**
16
+ * "Update from target" — re-runs the auto-merge of the target branch into
17
+ * this change request's source branch (PLAN §1). The button is the
18
+ * counterpart to the auto-merge that happens on CR open; users hit it
19
+ * when the target advances mid-review and they want the diff to reflect
20
+ * what the merge would actually produce now.
21
+ *
22
+ * Conflicts come back as a 409 with the `change-request-conflicts`
23
+ * structured payload. **The user never sees the conflict directly** — per
24
+ * the design rule "if it doesn't work out of the box, the agent fixes it
25
+ * not the user", the conflict is handed to the change-request port (the
26
+ * enterprise registry seeds a chat prompt and auto-sends it so the agent
27
+ * walks its conflict-resolution flow). Other 409s / 5xx (auth, infra) are
28
+ * still shown inline since they're not the "two versions disagree" case.
29
+ */
30
+ export function PrRefreshFromTargetButton({ detail, onRefreshed }: Props) {
31
+ const [busy, setBusy] = useState(false);
32
+ const [error, setError] = useState<string | null>(null);
33
+ const inFlightRef = useRef(false);
34
+ const crPort = useCrCreationPort();
35
+
36
+ if (detail.state !== 'open') return null;
37
+
38
+ const baseLabel = protectedBranchDisplayName(detail.base) ?? detail.base;
39
+
40
+ async function run() {
41
+ if (inFlightRef.current) return;
42
+ inFlightRef.current = true;
43
+ setBusy(true);
44
+ setError(null);
45
+ try {
46
+ await refreshChangeRequestFromTarget(detail.number);
47
+ window.dispatchEvent(new CustomEvent(PR_STALE_EVENT));
48
+ onRefreshed();
49
+ } catch (err) {
50
+ if (err instanceof GitApiError) {
51
+ const body = err.body;
52
+ if (
53
+ body && typeof body === 'object' && 'kind' in body &&
54
+ (body as { kind?: string }).kind === 'change-request-conflicts' &&
55
+ crPort?.resolveCrConflicts
56
+ ) {
57
+ // Defensive narrowing: `body` came off the wire, so the array
58
+ // shape is asserted but the element type isn't actually checked
59
+ // by the JSON parser. Filter to strings so downstream code (the
60
+ // enterprise prompt builder) gets the type its signature claims.
61
+ const rawPaths = (body as { conflictedPaths?: unknown }).conflictedPaths;
62
+ const paths = Array.isArray(rawPaths)
63
+ ? rawPaths.filter((item): item is string => typeof item === 'string')
64
+ : [];
65
+ crPort.resolveCrConflicts({
66
+ kind: 'refresh',
67
+ changeRequestNumber: detail.number,
68
+ base: detail.base,
69
+ conflictedPaths: paths,
70
+ });
71
+ // No inline error — the chat panel shows the agent picking it up.
72
+ // (Without a registered resolver the 409 falls through to the
73
+ // inline error below instead.)
74
+ return;
75
+ }
76
+ setError(err.message);
77
+ return;
78
+ }
79
+ setError(err instanceof Error ? err.message : "Couldn't refresh from target");
80
+ } finally {
81
+ setBusy(false);
82
+ inFlightRef.current = false;
83
+ }
84
+ }
85
+
86
+ return (
87
+ <div className="flex items-center gap-2">
88
+ {error && (
89
+ <span
90
+ role="alert"
91
+ aria-live="assertive"
92
+ className="text-[11px] text-red-700 max-w-xs truncate"
93
+ title={error}
94
+ >
95
+ {error}
96
+ </span>
97
+ )}
98
+ <button
99
+ type="button"
100
+ onClick={() => void run()}
101
+ disabled={busy}
102
+ title={`Pull the latest ${baseLabel} into this draft so the diff reflects what the merge would produce now.`}
103
+ className="flex items-center gap-1.5 px-2.5 py-1 text-xs rounded whitespace-nowrap shrink-0 text-slate-700 bg-slate-100 hover:bg-slate-200 disabled:opacity-50 disabled:cursor-not-allowed"
104
+ >
105
+ <RefreshCw size={12} className={busy ? 'animate-spin' : ''} />
106
+ {busy ? 'Refreshing…' : `Update from ${baseLabel}`}
107
+ </button>
108
+ </div>
109
+ );
110
+ }