@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,377 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
+ import {
3
+ GitCompare,
4
+ ChevronDown,
5
+ Lock,
6
+ ArrowLeftRight,
7
+ Loader2,
8
+ AlertTriangle,
9
+ RefreshCw,
10
+ } from 'lucide-react';
11
+ import { protectedBranchDisplayName, isProtectedBranch, DEFAULT_BRANCH, type BranchInfo } from '@bevel-software/platform-shared';
12
+ import { useGit } from '../state/git.context';
13
+ import { UnifiedDiffView } from './UnifiedDiffView';
14
+ import { friendlyGitError } from '../services/error-messages';
15
+
16
+ interface Props {
17
+ filePath: string;
18
+ /**
19
+ * Optional initial picker overrides (used when the agent's chat tool-card
20
+ * deep-links into this panel via a `bevel:open-comparison` event). When
21
+ * omitted, the panel resolves sensible defaults from the workspace state.
22
+ */
23
+ initialFrom?: string | null;
24
+ initialTo?: string | null;
25
+ /**
26
+ * Bumped by the workspace whenever the file system changes (save, delete,
27
+ * tree refresh, etc). When this number changes, the panel refetches the
28
+ * comparison so a save you made on the Content tab shows up here without
29
+ * forcing the user to flip the pickers.
30
+ */
31
+ refreshKey?: number;
32
+ }
33
+
34
+ // The `bevel:open-comparison` deep-link event lives in core/events so
35
+ // dispatchers (the chat tool-card) and listeners (FileViewer) don't need to
36
+ // import this component module. Re-exported here for compatibility with
37
+ // existing import sites.
38
+ export {
39
+ OPEN_COMPARISON_EVENT,
40
+ type OpenComparisonDetail,
41
+ } from '../../../core/events';
42
+
43
+ /**
44
+ * Sort branches the same way the BranchSwitcher does: protected first (the
45
+ * default branch ahead of the other protected branches), then drafts
46
+ * alphabetically. Keeps both surfaces showing the same order so users don't
47
+ * have to relearn navigation.
48
+ */
49
+ function sortBranchesForPicker(branches: BranchInfo[]): BranchInfo[] {
50
+ return [...branches].sort((a, b) => {
51
+ if (a.isProtected !== b.isProtected) return a.isProtected ? -1 : 1;
52
+ if (a.isProtected && b.isProtected) {
53
+ if (a.name === DEFAULT_BRANCH) return -1;
54
+ if (b.name === DEFAULT_BRANCH) return 1;
55
+ }
56
+ return a.name.localeCompare(b.name);
57
+ });
58
+ }
59
+
60
+ /**
61
+ * Pick a sensible `from` for `currentBranch`:
62
+ * - On a feature branch → its fork base if available, else the protected
63
+ * branch other than `currentBranch`, else any other branch.
64
+ * - On a protected branch → the *other* protected branch so the comparison
65
+ * is non-empty by default (Current vs Target).
66
+ *
67
+ * Returns null if no other branch is available — the panel renders the
68
+ * "pick a different version" empty state in that case.
69
+ */
70
+ function defaultFromForCurrent(
71
+ currentBranch: string | null,
72
+ branches: BranchInfo[],
73
+ forkBase: string | null,
74
+ ): string | null {
75
+ if (!currentBranch || branches.length < 2) return null;
76
+
77
+ const others = branches.filter((b) => b.name !== currentBranch);
78
+ if (others.length === 0) return null;
79
+
80
+ if (forkBase && forkBase !== currentBranch && others.some((b) => b.name === forkBase)) {
81
+ return forkBase;
82
+ }
83
+
84
+ // On a protected branch, prefer the default branch as the comparison base so
85
+ // the picker opens on the canonical "official vs official" diff; if we're
86
+ // already on the default branch, any other protected branch works.
87
+ if (isProtectedBranch(currentBranch)) {
88
+ if (currentBranch !== DEFAULT_BRANCH && others.some((b) => b.name === DEFAULT_BRANCH)) {
89
+ return DEFAULT_BRANCH;
90
+ }
91
+ }
92
+
93
+ const protectedOther = others.find((b) => b.isProtected);
94
+ if (protectedOther) return protectedOther.name;
95
+
96
+ return others[0].name;
97
+ }
98
+
99
+ export function FileComparisonPanel({ filePath, initialFrom, initialTo, refreshKey = 0 }: Props) {
100
+ const git = useGit();
101
+ const { branches, fetchFileComparison, fetchForkBase } = git;
102
+ const currentBranch = git.status?.branch ?? null;
103
+
104
+ const [fromBranch, setFromBranch] = useState<string | null>(initialFrom ?? null);
105
+ const [toBranch, setToBranch] = useState<string | null>(initialTo ?? currentBranch);
106
+ const [diff, setDiff] = useState<string | null>(null);
107
+ const [loading, setLoading] = useState(false);
108
+ const [error, setError] = useState<string | null>(null);
109
+ // Bumped when the user clicks the manual refresh button — combined with
110
+ // the parent-supplied `refreshKey` so either signal forces a refetch.
111
+ const [manualRefresh, setManualRefresh] = useState(0);
112
+ // Token to drop late-arriving responses when the user changes pickers
113
+ // mid-flight — same pattern as `FileHistoryPanel.selectCommit`.
114
+ const requestSeqRef = useRef(0);
115
+ // Tracks the previous `currentBranch` so we can detect external branch
116
+ // switches and re-sync `to` (when the user hasn't manually overridden it).
117
+ const prevCurrentBranchRef = useRef<string | null>(currentBranch);
118
+
119
+ // Resolve a default `from` once branches + currentBranch are known. The
120
+ // user can override it; we only fill in when nothing has been picked yet.
121
+ const sortedBranches = useMemo(() => sortBranchesForPicker(branches), [branches]);
122
+ useEffect(() => {
123
+ if (initialFrom !== undefined && initialFrom !== null) return;
124
+ if (fromBranch !== null) return;
125
+ if (!currentBranch || branches.length === 0) return;
126
+ let cancelled = false;
127
+ (async () => {
128
+ let forkBase: string | null = null;
129
+ try {
130
+ forkBase = await fetchForkBase(currentBranch);
131
+ } catch {
132
+ // fork-base lookup failure is non-fatal; fall through to the
133
+ // protected-counterpart heuristic.
134
+ }
135
+ if (cancelled) return;
136
+ setFromBranch(defaultFromForCurrent(currentBranch, branches, forkBase));
137
+ })();
138
+ return () => {
139
+ cancelled = true;
140
+ };
141
+ }, [initialFrom, fromBranch, currentBranch, branches, fetchForkBase]);
142
+
143
+ // Sync `to` to the current branch when the user switches branches outside
144
+ // the panel — matches how the History tab refreshes per branch. Re-sync
145
+ // when `to` is null OR was tracking the previous current branch (i.e. the
146
+ // user hasn't manually overridden it); leave it alone if the user picked a
147
+ // specific branch to compare against.
148
+ useEffect(() => {
149
+ if (initialTo !== undefined && initialTo !== null) {
150
+ prevCurrentBranchRef.current = currentBranch;
151
+ return;
152
+ }
153
+ if (currentBranch) {
154
+ const wasFollowing = toBranch === prevCurrentBranchRef.current;
155
+ if (toBranch === null || wasFollowing) {
156
+ setToBranch(currentBranch);
157
+ }
158
+ }
159
+ prevCurrentBranchRef.current = currentBranch;
160
+ }, [currentBranch, toBranch, initialTo]);
161
+
162
+ // Apply external deep-link overrides whenever they change (the FileViewer
163
+ // re-mounts this panel with new initial values when the chat tool-card
164
+ // dispatches `bevel:open-comparison`).
165
+ useEffect(() => {
166
+ if (initialFrom !== undefined && initialFrom !== null) setFromBranch(initialFrom);
167
+ if (initialTo !== undefined && initialTo !== null) setToBranch(initialTo);
168
+ }, [initialFrom, initialTo]);
169
+
170
+ // Fetch the diff whenever the picker pair (or the file) changes, and also
171
+ // whenever the workspace's filesystem revision bumps (a save on the
172
+ // Content tab) or the user hits manual refresh. Skip when either side is
173
+ // unset or both sides are equal — those render dedicated empty states
174
+ // and shouldn't burn a network call.
175
+ useEffect(() => {
176
+ if (!fromBranch || !toBranch || fromBranch === toBranch) {
177
+ // Bump the seq so any in-flight fetch resolves into a no-op (its
178
+ // isLatest check fails) — otherwise a late response would re-populate
179
+ // the diff/loading/error we just cleared.
180
+ ++requestSeqRef.current;
181
+ setDiff(null);
182
+ setLoading(false);
183
+ setError(null);
184
+ return;
185
+ }
186
+ const token = ++requestSeqRef.current;
187
+ const isLatest = () => requestSeqRef.current === token;
188
+ setLoading(true);
189
+ setError(null);
190
+ fetchFileComparison(filePath, fromBranch, toBranch)
191
+ .then((d) => {
192
+ if (!isLatest()) return;
193
+ setDiff(d);
194
+ })
195
+ .catch((err) => {
196
+ if (!isLatest()) return;
197
+ setError(friendlyGitError(err));
198
+ setDiff(null);
199
+ })
200
+ .finally(() => {
201
+ if (isLatest()) setLoading(false);
202
+ });
203
+ }, [filePath, fromBranch, toBranch, fetchFileComparison, refreshKey, manualRefresh]);
204
+
205
+ const handleSwap = useCallback(() => {
206
+ setFromBranch((prevFrom) => {
207
+ setToBranch(prevFrom);
208
+ return toBranch;
209
+ });
210
+ }, [toBranch]);
211
+
212
+ return (
213
+ <div className="flex-1 flex flex-col min-h-0 bg-white">
214
+ <div className="flex items-center gap-2 px-3 py-2 border-b border-slate-200 shrink-0">
215
+ <GitCompare size={14} className="text-slate-600 shrink-0" />
216
+ <span className="text-xs text-slate-600 truncate flex-1 min-w-0">
217
+ Compare versions of {filePath}
218
+ </span>
219
+ <button
220
+ type="button"
221
+ onClick={() => setManualRefresh((n) => n + 1)}
222
+ disabled={loading || !fromBranch || !toBranch || fromBranch === toBranch}
223
+ title="Refresh comparison"
224
+ aria-label="Refresh comparison"
225
+ className="p-1 rounded text-slate-600 hover:text-slate-900 hover:bg-slate-100 disabled:opacity-40 disabled:cursor-not-allowed transition-colors shrink-0"
226
+ >
227
+ <RefreshCw size={12} className={loading ? 'animate-spin' : undefined} />
228
+ </button>
229
+ </div>
230
+
231
+ <div className="flex items-center gap-2 px-3 py-2 border-b border-slate-200 shrink-0">
232
+ <BranchPicker
233
+ label="From"
234
+ value={fromBranch}
235
+ branches={sortedBranches}
236
+ onChange={setFromBranch}
237
+ />
238
+ <button
239
+ type="button"
240
+ onClick={handleSwap}
241
+ disabled={!fromBranch || !toBranch}
242
+ title="Swap From and To"
243
+ aria-label="Swap From and To"
244
+ className="p-1.5 rounded text-slate-600 hover:text-slate-900 hover:bg-slate-100 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
245
+ >
246
+ <ArrowLeftRight size={14} />
247
+ </button>
248
+ <BranchPicker
249
+ label="To"
250
+ value={toBranch}
251
+ branches={sortedBranches}
252
+ onChange={setToBranch}
253
+ />
254
+ </div>
255
+
256
+ {error && (
257
+ <div className="flex items-start gap-2 px-3 py-2 bg-red-50 border-b border-red-300 text-xs text-red-700 shrink-0">
258
+ <AlertTriangle size={13} className="mt-0.5 shrink-0" />
259
+ <span className="flex-1">{error}</span>
260
+ </div>
261
+ )}
262
+
263
+ <div className="flex-1 overflow-auto">
264
+ {(!fromBranch || !toBranch) && !loading && !error && (
265
+ <div className="flex items-center justify-center h-full px-6 text-xs text-slate-600 text-center">
266
+ Pick two versions to compare.
267
+ </div>
268
+ )}
269
+ {fromBranch && toBranch && fromBranch === toBranch && !loading && !error && (
270
+ <div className="flex items-center justify-center h-full px-6 text-xs text-slate-600 text-center">
271
+ Pick two different versions to see what changed.
272
+ </div>
273
+ )}
274
+ {loading && (
275
+ <div className="flex items-center gap-2 px-3 py-3 text-xs text-slate-600">
276
+ <Loader2 size={13} className="animate-spin" />
277
+ Loading comparison…
278
+ </div>
279
+ )}
280
+ {!loading && !error && diff !== null && fromBranch !== toBranch && (
281
+ <UnifiedDiffView
282
+ diff={diff}
283
+ emptyMessage="This file is identical on both versions."
284
+ />
285
+ )}
286
+ </div>
287
+ </div>
288
+ );
289
+ }
290
+
291
+ interface BranchPickerProps {
292
+ label: string;
293
+ value: string | null;
294
+ branches: BranchInfo[];
295
+ onChange(name: string): void;
296
+ }
297
+
298
+ function BranchPicker({ label, value, branches, onChange }: BranchPickerProps) {
299
+ const [open, setOpen] = useState(false);
300
+ const ref = useRef<HTMLDivElement>(null);
301
+
302
+ useEffect(() => {
303
+ if (!open) return;
304
+ const handler = (e: MouseEvent) => {
305
+ if (ref.current && !ref.current.contains(e.target as Node)) {
306
+ setOpen(false);
307
+ }
308
+ };
309
+ document.addEventListener('mousedown', handler);
310
+ return () => document.removeEventListener('mousedown', handler);
311
+ }, [open]);
312
+
313
+ const valueIsProtected = !!value && (
314
+ branches.find((b) => b.name === value)?.isProtected ?? false
315
+ );
316
+ const valueDisplay = value ? protectedBranchDisplayName(value) ?? value : '— pick —';
317
+
318
+ return (
319
+ <div ref={ref} className="relative flex-1 min-w-0">
320
+ <div className="text-[10px] uppercase tracking-wide text-slate-600 mb-0.5">
321
+ {label}
322
+ </div>
323
+ <button
324
+ type="button"
325
+ onClick={() => setOpen((v) => !v)}
326
+ className="w-full flex items-center gap-1.5 px-2 py-1.5 text-xs rounded bg-slate-100 hover:bg-slate-200 border border-slate-300 text-slate-900 min-w-0"
327
+ aria-haspopup="listbox"
328
+ aria-expanded={open}
329
+ >
330
+ {valueIsProtected && <Lock size={11} className="text-slate-600 shrink-0" />}
331
+ <span className="truncate flex-1 text-left">{valueDisplay}</span>
332
+ <ChevronDown size={12} className={`text-slate-600 transition-transform ${open ? 'rotate-180' : ''}`} />
333
+ </button>
334
+
335
+ {open && (
336
+ <div
337
+ role="listbox"
338
+ className="absolute top-full left-0 right-0 z-40 mt-1 bg-slate-100 border border-slate-300 rounded-lg shadow-xl max-h-64 overflow-y-auto"
339
+ >
340
+ {branches.length === 0 && (
341
+ <div className="px-3 py-2 text-xs text-slate-600">No branches.</div>
342
+ )}
343
+ {branches.map((b) => {
344
+ const display = protectedBranchDisplayName(b.name);
345
+ const isSelected = b.name === value;
346
+ return (
347
+ <button
348
+ key={b.name}
349
+ role="option"
350
+ aria-selected={isSelected}
351
+ onClick={() => {
352
+ onChange(b.name);
353
+ setOpen(false);
354
+ }}
355
+ className={`flex items-center gap-2 w-full text-left px-3 py-1.5 text-xs ${
356
+ isSelected
357
+ ? 'bg-slate-200/80 text-slate-900'
358
+ : 'text-slate-700 hover:bg-slate-200/60'
359
+ }`}
360
+ >
361
+ {b.isProtected && <Lock size={11} className="text-slate-600 shrink-0" />}
362
+ <span className="truncate flex-1">
363
+ {display ?? <span className="font-mono">{b.name}</span>}
364
+ </span>
365
+ {display && (
366
+ <span className="font-mono text-[10px] text-slate-600 shrink-0 truncate max-w-[40%]">
367
+ {b.name}
368
+ </span>
369
+ )}
370
+ </button>
371
+ );
372
+ })}
373
+ </div>
374
+ )}
375
+ </div>
376
+ );
377
+ }
@@ -0,0 +1,320 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import { History, Undo2, AlertTriangle, Loader2 } from 'lucide-react';
3
+ import type { CommitAttribution } from '@bevel-software/platform-shared';
4
+ import { useGit } from '../state/git.context';
5
+ import { UnifiedDiffView } from './UnifiedDiffView';
6
+ import { friendlyGitError } from '../services/error-messages';
7
+ import { useFileAccess } from '../../access/hooks/useFileAccess';
8
+ import { useEventBus, canonicalizeWorkspaceId } from '../../workflow/state/event-bus.context';
9
+ import { useWorkspace } from '../../workspace/state/workspace.context';
10
+
11
+ function shortSha(sha: string): string {
12
+ return sha.slice(0, 7);
13
+ }
14
+
15
+ /**
16
+ * Human-readable relative time for the timeline ("2 hours ago", "3d ago"). Falls back to
17
+ * an absolute date once we cross ~a month so the label doesn't become meaningless.
18
+ */
19
+ function formatRelativeTime(iso: string): string {
20
+ if (!iso) return '';
21
+ const d = new Date(iso);
22
+ if (Number.isNaN(d.getTime())) return iso;
23
+ const diffMs = Date.now() - d.getTime();
24
+ if (diffMs < 0) return d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
25
+ const mins = Math.floor(diffMs / 60000);
26
+ if (mins < 1) return 'just now';
27
+ if (mins < 60) return `${mins}m ago`;
28
+ const hours = Math.floor(mins / 60);
29
+ if (hours < 24) return `${hours}h ago`;
30
+ const days = Math.floor(hours / 24);
31
+ if (days < 7) return `${days}d ago`;
32
+ const weeks = Math.floor(days / 7);
33
+ if (weeks < 5) return `${weeks}w ago`;
34
+ return d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
35
+ }
36
+
37
+ function formatAbsoluteTime(iso: string): string {
38
+ if (!iso) return '';
39
+ const d = new Date(iso);
40
+ if (Number.isNaN(d.getTime())) return iso;
41
+ return d.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
42
+ }
43
+
44
+ interface Props {
45
+ filePath: string;
46
+ /**
47
+ * Called after a successful undo so the parent can reconcile (reopen the file, refresh
48
+ * the tree, refetch status). Returning a Promise lets the panel await reconciliation
49
+ * before clearing its `reverting` flag so buttons don't re-enable while reload is in
50
+ * progress.
51
+ */
52
+ onRevertCompleted(): Promise<void>;
53
+ }
54
+
55
+ export function FileHistoryPanel({ filePath, onRevertCompleted }: Props) {
56
+ const git = useGit();
57
+ const [commits, setCommits] = useState<CommitAttribution[] | null>(null);
58
+ const [selected, setSelected] = useState<CommitAttribution | null>(null);
59
+ const [diff, setDiff] = useState<string | null>(null);
60
+ const [loading, setLoading] = useState(true);
61
+ const [diffLoading, setDiffLoading] = useState(false);
62
+ const [reverting, setReverting] = useState(false);
63
+ const [error, setError] = useState<string | null>(null);
64
+ const [notice, setNotice] = useState<string | null>(null);
65
+ const latestDiffRequestRef = useRef<string | null>(null);
66
+
67
+ // Revert (the backend's `git revert` flow) is gated by per-path write
68
+ // access on protected branches only — draft branches are free-for-all,
69
+ // mirroring the backend's revertCommit gate. The hook returns
70
+ // canWrite=true on drafts without a network call, so the button stays
71
+ // enabled. On protected branches, default-allow on loading / API failure
72
+ // so a transient hiccup doesn't grey out the button for users who
73
+ // actually have access — the backend will refuse with AccessDenied at
74
+ // click time if not. (Edge case: a commit may have touched other files
75
+ // the caller can't write. The backend checks all of them; the user sees
76
+ // a click-then-error for that, which is acceptable.)
77
+ const access = useFileAccess(filePath, git.status?.branch ?? null);
78
+ const cannotRevert = access.canWrite === false;
79
+
80
+ // Pull the stable callbacks out so the effect's deps don't include the whole
81
+ // `git` object — that object is a useMemo result that changes on every status
82
+ // poll, which would otherwise wipe local state (selection, loading) every 30s.
83
+ const { fetchFileHistory, fetchFileDiff, revert } = git;
84
+
85
+ useEffect(() => {
86
+ let cancelled = false;
87
+ setLoading(true);
88
+ setError(null);
89
+ setNotice(null);
90
+ setSelected(null);
91
+ setDiff(null);
92
+ setCommits(null);
93
+ latestDiffRequestRef.current = null;
94
+ fetchFileHistory(filePath, 20)
95
+ .then((history) => {
96
+ if (cancelled) return;
97
+ setCommits(history);
98
+ })
99
+ .catch((err) => {
100
+ if (cancelled) return;
101
+ setError(friendlyGitError(err));
102
+ })
103
+ .finally(() => {
104
+ if (!cancelled) setLoading(false);
105
+ });
106
+ return () => {
107
+ cancelled = true;
108
+ };
109
+ }, [filePath, fetchFileHistory]);
110
+
111
+ // Live refresh: when a commit lands on this file (someone else saves,
112
+ // an agent edit completes, etc.), refetch history so the new commit
113
+ // appears without the user having to switch tabs. Only acts on commit
114
+ // events (`newSha` set) — disk-only writes (mid-edit autosaves) don't
115
+ // change git history so refetching would be wasted work.
116
+ const bus = useEventBus();
117
+ const workspace = useWorkspace();
118
+ const workspaceId = workspace.workspaceId;
119
+ useEffect(() => {
120
+ if (!bus || !workspaceId) return;
121
+ // Per-subscription cancellation. When `filePath`/`workspaceId`
122
+ // changes the effect's cleanup flips this flag, so any in-flight
123
+ // fetchFileHistory from the previous file's events can't resolve
124
+ // and `setCommits` for the new file. Without the guard, a stale
125
+ // resolve would render the old file's commits in the new tab.
126
+ let cancelled = false;
127
+ const workspaceCanon = canonicalizeWorkspaceId(workspaceId);
128
+ const off = bus.subscribe('file-changed', (event) => {
129
+ if (canonicalizeWorkspaceId(event.workspaceId) !== workspaceCanon) return;
130
+ if (event.path !== filePath) return;
131
+ if (event.newSha === null) return;
132
+ // Refetch in the background; ignore failures (the next poll or
133
+ // manual reopen will recover).
134
+ fetchFileHistory(filePath, 20)
135
+ .then((history) => {
136
+ if (cancelled) return;
137
+ setCommits(history);
138
+ })
139
+ .catch((err) => console.warn('[FileHistoryPanel] live refresh failed:', err));
140
+ });
141
+ return () => {
142
+ cancelled = true;
143
+ off();
144
+ };
145
+ }, [bus, workspaceId, filePath, fetchFileHistory]);
146
+
147
+ const selectCommit = useCallback(
148
+ (commit: CommitAttribution) => {
149
+ setSelected(commit);
150
+ // Clear any banner left over from a previous failed diff/revert so the UI
151
+ // reflects only the currently-selected save's state.
152
+ setError(null);
153
+ setDiff(null);
154
+ setDiffLoading(true);
155
+ latestDiffRequestRef.current = commit.sha;
156
+ fetchFileDiff(filePath, commit.sha)
157
+ .then((d) => {
158
+ if (latestDiffRequestRef.current === commit.sha) setDiff(d);
159
+ })
160
+ .catch((err) => {
161
+ if (latestDiffRequestRef.current === commit.sha) {
162
+ setError(friendlyGitError(err));
163
+ }
164
+ })
165
+ .finally(() => {
166
+ if (latestDiffRequestRef.current === commit.sha) setDiffLoading(false);
167
+ });
168
+ },
169
+ [filePath, fetchFileDiff],
170
+ );
171
+
172
+ const handleRevert = useCallback(async () => {
173
+ if (!selected || reverting) return;
174
+ setError(null);
175
+ setNotice(null);
176
+ setReverting(true);
177
+ try {
178
+ const attr = await revert(selected.sha);
179
+ setNotice(`Undone. Created a new save (${shortSha(attr.sha)}) that reverses ${shortSha(selected.sha)}.`);
180
+ await onRevertCompleted();
181
+ } catch (err) {
182
+ setError(friendlyGitError(err));
183
+ } finally {
184
+ setReverting(false);
185
+ }
186
+ }, [revert, selected, reverting, onRevertCompleted]);
187
+
188
+ return (
189
+ <div className="flex-1 flex flex-col min-h-0 bg-white">
190
+ <div className="flex items-center gap-2 px-3 py-2 border-b border-slate-200 shrink-0">
191
+ <History size={14} className="text-slate-600 shrink-0" />
192
+ <span className="text-xs text-slate-600 truncate">Timeline — {filePath}</span>
193
+ </div>
194
+
195
+ {error && (
196
+ <div className="flex items-start gap-2 px-3 py-2 bg-red-50 border-b border-red-300 text-xs text-red-700 shrink-0">
197
+ <AlertTriangle size={13} className="mt-0.5 shrink-0" />
198
+ <span className="flex-1">{error}</span>
199
+ </div>
200
+ )}
201
+ {notice && !error && (
202
+ <div className="px-3 py-2 bg-emerald-50 border-b border-emerald-200/60 text-xs text-emerald-700 shrink-0">
203
+ {notice}
204
+ </div>
205
+ )}
206
+
207
+ <div className="flex-1 flex min-h-0">
208
+ {/* Left: commit list */}
209
+ <div className="w-72 shrink-0 overflow-y-auto border-r border-slate-200">
210
+ {loading && (
211
+ <div className="flex items-center gap-2 px-3 py-3 text-xs text-slate-600">
212
+ <Loader2 size={13} className="animate-spin" />
213
+ Loading timeline…
214
+ </div>
215
+ )}
216
+ {!loading && commits && commits.length === 0 && (
217
+ <div className="px-3 py-3 text-xs text-slate-600">
218
+ Nothing has been saved to this file yet.
219
+ </div>
220
+ )}
221
+ {!loading && commits && commits.length > 0 && (
222
+ <ul>
223
+ {commits.map((c) => {
224
+ const isSelected = selected?.sha === c.sha;
225
+ const who = c.authorName || c.authorEmail || 'unknown';
226
+ return (
227
+ <li key={c.sha}>
228
+ <button
229
+ type="button"
230
+ onClick={() => selectCommit(c)}
231
+ className={`w-full text-left px-3 py-2 border-b border-slate-200/60 text-xs transition-colors ${
232
+ isSelected
233
+ ? 'bg-slate-100 text-slate-900'
234
+ : 'text-slate-700 hover:bg-slate-100/80'
235
+ }`}
236
+ >
237
+ {/* Subject leads; SHA moves to a muted pill so non-technical users aren't
238
+ greeted by a hex string before any human context. */}
239
+ <div className="flex items-start gap-2">
240
+ <span className="flex-1 truncate">{c.subject || '(no message)'}</span>
241
+ <span
242
+ className="shrink-0 font-mono text-[9px] text-slate-500 bg-white border border-slate-200 rounded px-1 py-[1px]"
243
+ title={`Save id: ${c.sha}`}
244
+ >
245
+ {shortSha(c.sha)}
246
+ </span>
247
+ </div>
248
+ <div
249
+ className="mt-0.5 text-[10px] text-slate-600 truncate"
250
+ title={formatAbsoluteTime(c.committedAt)}
251
+ >
252
+ {who} · {formatRelativeTime(c.committedAt)}
253
+ </div>
254
+ </button>
255
+ </li>
256
+ );
257
+ })}
258
+ </ul>
259
+ )}
260
+ </div>
261
+
262
+ {/* Right: diff + revert */}
263
+ <div className="flex-1 flex flex-col min-w-0">
264
+ {!selected && (
265
+ <div className="flex-1 flex items-center justify-center px-6 text-xs text-slate-600">
266
+ Pick a save to see what changed.
267
+ </div>
268
+ )}
269
+ {selected && (
270
+ <>
271
+ <div className="flex items-center gap-2 px-3 py-2 border-b border-slate-200 shrink-0">
272
+ <span className="text-xs text-slate-700 truncate flex-1">
273
+ {selected.subject || '(no message)'}
274
+ </span>
275
+ <span
276
+ className="font-mono text-[10px] text-slate-600 shrink-0"
277
+ title={`Save id: ${selected.sha}`}
278
+ >
279
+ {shortSha(selected.sha)}
280
+ </span>
281
+ <button
282
+ type="button"
283
+ onClick={handleRevert}
284
+ disabled={reverting || cannotRevert || git.availability !== 'ready'}
285
+ title={
286
+ cannotRevert
287
+ ? "You don't have permission to edit this file"
288
+ : 'Creates a new save that reverses this one'
289
+ }
290
+ className="flex items-center gap-1.5 px-2.5 py-1 rounded text-xs font-medium bg-slate-100 hover:bg-slate-200 text-slate-900 border border-slate-300 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
291
+ >
292
+ {reverting ? (
293
+ <Loader2 size={12} className="animate-spin" />
294
+ ) : (
295
+ <Undo2 size={12} />
296
+ )}
297
+ Undo this save
298
+ </button>
299
+ </div>
300
+ <div className="flex-1 overflow-auto">
301
+ {diffLoading && (
302
+ <div className="flex items-center gap-2 px-3 py-3 text-xs text-slate-600">
303
+ <Loader2 size={13} className="animate-spin" />
304
+ Loading changes…
305
+ </div>
306
+ )}
307
+ {!diffLoading && diff !== null && (
308
+ <UnifiedDiffView
309
+ diff={diff}
310
+ emptyMessage="No file changes in this save."
311
+ />
312
+ )}
313
+ </div>
314
+ </>
315
+ )}
316
+ </div>
317
+ </div>
318
+ </div>
319
+ );
320
+ }