@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,527 @@
1
+ import { useEffect, useMemo, useRef, useState } from 'react';
2
+ import { createPortal } from 'react-dom';
3
+ import { useLocation, useNavigate } from 'react-router-dom';
4
+ import { ChevronDown, GitBranch, Plus, Lock, Check, GitPullRequest, Trash2, Loader2 } from 'lucide-react';
5
+ import { protectedBranchDisplayName, branchAuthorLocalpart, isBranchAuthoredBy, DEFAULT_BRANCH } from '@bevel-software/platform-shared';
6
+ import { useGit } from '../state/git.context';
7
+ import { parseGitError, type GitErrorInfo } from '../services/error-messages';
8
+ import { useAuth } from '../../auth/state/auth.context';
9
+ import { useWorkspace } from '../../workspace/state/workspace.context';
10
+ import { kbFileUrl, KB_ROUTE_PREFIX } from '../../workspace/routing/kb-routes';
11
+ import { useCrCreationPort } from '../../../core/registry';
12
+ import { fetchFileAccess } from '../../access/api';
13
+
14
+ /**
15
+ * Convert a free-text "what are you changing?" answer into a branch name slug.
16
+ * Non-technical users type a sentence; we kebab-case it and prefix the user's
17
+ * email local-part so the name still matches the documented convention.
18
+ */
19
+ function slugifyDraftName(email: string, text: string): string {
20
+ // `branchAuthorLocalpart` returns null for missing / unsanitizable emails;
21
+ // the UI keeps a friendly `user` placeholder so the create form never blocks
22
+ // on a malformed identity. Authorship checks elsewhere use the strict
23
+ // helper and refuse delete when localpart is null.
24
+ const localPart = branchAuthorLocalpart(email) ?? 'user';
25
+ const slug = text
26
+ .toLowerCase()
27
+ .replace(/[^a-z0-9]+/g, '-')
28
+ .replace(/^-+|-+$/g, '');
29
+ return `${localPart}/${slug || 'draft'}`;
30
+ }
31
+
32
+ /**
33
+ * Place the branch dropdown just below its trigger. Coordinates are
34
+ * viewport-fixed because the panel is portaled to <body> (so the toolbar's
35
+ * mobile `overflow` row can't clip it). The left edge is clamped to keep the
36
+ * 288px-wide panel fully on screen on narrow phones.
37
+ */
38
+ function computePanelPosition(triggerRect: DOMRect): { top: number; left: number } {
39
+ const PANEL_WIDTH = 400; // matches Tailwind w-[400px]
40
+ const MARGIN = 8; // min gap kept from the viewport edge
41
+ const GAP = 4; // vertical gap below the trigger (matches the old top-8)
42
+ const maxLeft = window.innerWidth - PANEL_WIDTH - MARGIN;
43
+ const left = Math.max(MARGIN, Math.min(triggerRect.left, maxLeft));
44
+ return { top: triggerRect.bottom + GAP, left };
45
+ }
46
+
47
+ export function BranchSwitcher() {
48
+ const git = useGit();
49
+ const navigate = useNavigate();
50
+ const location = useLocation();
51
+ const { user } = useAuth();
52
+ const { openFilePath, workspaceId } = useWorkspace();
53
+ const crPort = useCrCreationPort();
54
+ // True iff the current user is an admin per the active workspace's
55
+ // `roles.yaml`. We piggy-back on the existing per-file access endpoint —
56
+ // `canWrite` on `roles.yaml` already encodes "is admin" in the backend's
57
+ // access model (only admins can rotate that file). Saves us from adding a
58
+ // dedicated `/access/me` route just for this affordance. Defaults to
59
+ // `false` while the fetch is in flight; the backend gate is authoritative
60
+ // anyway, so a brief false-negative just means the delete button appears
61
+ // a moment later.
62
+ const [isAdmin, setIsAdmin] = useState(false);
63
+ useEffect(() => {
64
+ // No workspace → nothing to fetch and no admin-only affordance to render
65
+ // (the branch list is empty too, so canDelete has no rows to apply to).
66
+ // Skip resetting state — the next mount with a real workspaceId fetches
67
+ // fresh, so a stale `true` can't cross a workspace boundary.
68
+ if (!workspaceId) return;
69
+ let cancelled = false;
70
+ fetchFileAccess(workspaceId, 'roles.yaml')
71
+ .then((r) => {
72
+ if (!cancelled) setIsAdmin(r.canWrite);
73
+ })
74
+ .catch(() => {
75
+ if (!cancelled) setIsAdmin(false);
76
+ });
77
+ return () => {
78
+ cancelled = true;
79
+ };
80
+ }, [workspaceId]);
81
+ const [open, setOpen] = useState(false);
82
+ const [creating, setCreating] = useState(false);
83
+ const [newBranchName, setNewBranchName] = useState('');
84
+ const [error, setError] = useState<GitErrorInfo | null>(null);
85
+ // Fixed-viewport coordinates for the portaled dropdown panel. `null` until the
86
+ // menu is first opened, then recomputed from the trigger's bounding rect on
87
+ // every open. The panel is portaled to `document.body` so the toolbar's mobile
88
+ // second row (`overflow-x-auto`/`overflow-y-hidden`) can't clip it — an inline
89
+ // absolutely-positioned child can't escape an `overflow-x-auto` ancestor.
90
+ const [panelPos, setPanelPos] = useState<{ top: number; left: number } | null>(null);
91
+ // Derived from URL: branch the route is pointing at. Used to label the
92
+ // picker "Switching to X…" while the per-branch workspace bootstrap is
93
+ // resolving in the background. Under the per-branch workspace model the
94
+ // "switch" is purely the workspace re-bootstrap — there's no git op to
95
+ // track an in-flight flag on, so we infer mid-switch from the URL-vs-status
96
+ // mismatch directly. When the bootstrap completes, useGitState refreshes
97
+ // status against the new workspaceId, status.branch flips to urlBranch,
98
+ // and this falls back to null.
99
+ const urlBranch = useMemo(() => {
100
+ const prefix = `${KB_ROUTE_PREFIX}/`;
101
+ if (!location.pathname.startsWith(prefix)) return null;
102
+ const rest = location.pathname.slice(prefix.length);
103
+ const slash = rest.indexOf('/');
104
+ const branchPart = slash === -1 ? rest : rest.slice(0, slash);
105
+ return branchPart ? decodeURIComponent(branchPart) : null;
106
+ }, [location.pathname]);
107
+ const switchingTo =
108
+ urlBranch && git.status?.branch && urlBranch !== git.status.branch
109
+ ? urlBranch
110
+ : null;
111
+ // When the user clicks "Propose this draft as a change request into…" we
112
+ // swap the dropdown into a target-picker view. The PR only fires once they
113
+ // pick a base branch from the list.
114
+ const [choosingTarget, setChoosingTarget] = useState(false);
115
+ const ref = useRef<HTMLDivElement>(null);
116
+ // The dropdown is portaled to `document.body`, so it's no longer a DOM
117
+ // descendant of `ref`. The click-outside handler needs this second ref to
118
+ // tell a click inside the panel from a click away from it.
119
+ const panelRef = useRef<HTMLDivElement>(null);
120
+
121
+ useEffect(() => {
122
+ if (!open) return;
123
+ const handler = (e: MouseEvent) => {
124
+ const target = e.target as Node;
125
+ // The panel is portaled out of `ref`, so a click inside it would
126
+ // otherwise read as "outside" and close the menu on the first mousedown.
127
+ if (!ref.current?.contains(target) && !panelRef.current?.contains(target)) {
128
+ setOpen(false);
129
+ setCreating(false);
130
+ setChoosingTarget(false);
131
+ setError(null);
132
+ }
133
+ };
134
+ document.addEventListener('mousedown', handler);
135
+ return () => document.removeEventListener('mousedown', handler);
136
+ }, [open]);
137
+
138
+ // While the menu is open, re-anchor the portaled panel to the trigger on
139
+ // resize (phone rotation) or scroll. Subscribe-only effect: setState runs
140
+ // solely inside the external-event callback, never synchronously in the
141
+ // effect body. The initial position is computed in the trigger's onClick.
142
+ //
143
+ // Scrolls *inside* the panel (the branch list, the target picker) bubble
144
+ // up to this capture-phase listener but don't move the trigger, so skip
145
+ // those — otherwise every wheel tick inside the dropdown forces a
146
+ // getBoundingClientRect + setState round trip.
147
+ useEffect(() => {
148
+ if (!open) return;
149
+ const reposition = (e?: Event) => {
150
+ if (e && panelRef.current?.contains(e.target as Node)) return;
151
+ const r = ref.current?.getBoundingClientRect();
152
+ if (r) setPanelPos(computePanelPosition(r));
153
+ };
154
+ const onResize = () => reposition();
155
+ window.addEventListener('resize', onResize);
156
+ window.addEventListener('scroll', reposition, true);
157
+ return () => {
158
+ window.removeEventListener('resize', onResize);
159
+ window.removeEventListener('scroll', reposition, true);
160
+ };
161
+ }, [open]);
162
+
163
+ const branch = git.status?.branch ?? '…';
164
+ // Under the per-branch workspace model the workspace IS the current branch.
165
+ // Derive "is this the row I'm on?" from `git.status.branch` instead of a
166
+ // `BranchInfo.isCurrent` flag (which no longer exists — see
167
+ // packages/shared/src/git/types.ts).
168
+ const isCurrentBranch = (b: { name: string }) => b.name === git.status?.branch;
169
+ const currentBranch = git.branches.find(isCurrentBranch);
170
+ // Tooltip for the button needs to match what the user is actually on — on a
171
+ // protected branch (Current/Target company state) calling it "your active
172
+ // shared draft" is wrong, it's the official version everyone sees.
173
+ const branchLabel = (() => {
174
+ if (switchingTo) return `Switching to ${switchingTo}…`;
175
+ const protectedName = protectedBranchDisplayName(git.status?.branch);
176
+ if (protectedName) return `${protectedName} (official version)`;
177
+ return 'Your active shared draft';
178
+ })();
179
+ // With auto-commit-and-push on lock release there is no dirty tree to gate
180
+ // on — a draft is always ready to propose. The only gate left is "not a
181
+ // protected branch", which the share flow enforces server-side too.
182
+ const canOpenPr = !!currentBranch && !currentBranch.isProtected;
183
+
184
+ async function doDelete(name: string, hasRemote: boolean) {
185
+ // Two reasons a branch reaches doDelete: (1) it's an orphan with no
186
+ // remote counterpart (PR merged + remote head pruned — tidy-up, no
187
+ // confirm needed), or (2) it's a draft authored by the current user
188
+ // who wants to discard it. Case 2 is destructive for the whole team
189
+ // (the remote ref goes away for everyone), so confirm explicitly.
190
+ if (hasRemote) {
191
+ const ok = window.confirm(
192
+ `Delete shared draft "${name}"? This removes it from the remote for everyone.`,
193
+ );
194
+ if (!ok) return;
195
+ }
196
+ try {
197
+ await git.deleteBranch(name);
198
+ } catch (err) {
199
+ setError(parseGitError(err));
200
+ }
201
+ }
202
+
203
+ function doSwitch(name: string) {
204
+ // No-op when the user clicks the branch they're already on — otherwise a dirty
205
+ // tree would pop the commit-first dialog for a switch that has nothing to do.
206
+ if (name === git.status?.branch) {
207
+ setOpen(false);
208
+ return;
209
+ }
210
+ // Close the dropdown + lock the top button immediately so the UI doesn't
211
+ // leave the menu open while the switch is in flight.
212
+ setOpen(false);
213
+ setCreating(false);
214
+ setChoosingTarget(false);
215
+ setError(null);
216
+
217
+ // No dirty-tree pre-flight — lock release auto-commits any pending
218
+ // edits and pushes them. FileRoute owns the actual switch; we just
219
+ // declare intent by changing the URL.
220
+ navigate(kbFileUrl(name, openFilePath ?? ''));
221
+ }
222
+
223
+ async function doCreate() {
224
+ const text = newBranchName.trim();
225
+ if (!text) return;
226
+ const name = user?.email ? slugifyDraftName(user.email, text) : text;
227
+ try {
228
+ // Create the branch server-side on the current workspace's clone, then
229
+ // navigate to the new branch's URL. The URL change triggers the
230
+ // per-branch workspace bootstrap, which clones (or fetches) the new
231
+ // branch into its own workspace dir. No explicit "switch" step.
232
+ await git.createBranch(name);
233
+ setNewBranchName('');
234
+ setCreating(false);
235
+ setOpen(false);
236
+ navigate(kbFileUrl(name, openFilePath ?? ''));
237
+ } catch (err) {
238
+ setError(parseGitError(err));
239
+ }
240
+ }
241
+
242
+ function doOpenPr(base: string) {
243
+ if (!currentBranch) return;
244
+ // Hand off to the registered change-request port. The enterprise registry
245
+ // routes this to the chat agent (cascade impact analysis, push if needed,
246
+ // `gh pr create`, PR-list refresh on turn end — see ChatAgentPortsProvider);
247
+ // without an override, the core default opens the direct
248
+ // OpenChangeRequestDialog against POST /api/workflow/change-requests.
249
+ crPort?.start({
250
+ workspaceId,
251
+ branch: currentBranch.name,
252
+ targetBranch: base,
253
+ });
254
+ setOpen(false);
255
+ setChoosingTarget(false);
256
+ }
257
+
258
+ // Branches we can propose INTO — anything other than the current draft.
259
+ // Protected branches rise to the top because they're the usual targets;
260
+ // among the protected branches the default branch comes first because it's
261
+ // the default destination for shared drafts (other company states are updated
262
+ // separately by leadership). Other drafts follow alphabetically.
263
+ const targetBranches = git.branches
264
+ .filter((b) => !isCurrentBranch(b))
265
+ .sort((a, b) => {
266
+ if (a.isProtected !== b.isProtected) return a.isProtected ? -1 : 1;
267
+ if (a.isProtected && b.isProtected) {
268
+ if (a.name === DEFAULT_BRANCH) return -1;
269
+ if (b.name === DEFAULT_BRANCH) return 1;
270
+ }
271
+ return a.name.localeCompare(b.name);
272
+ });
273
+
274
+ return (
275
+ <div ref={ref} className="relative min-w-0">
276
+ <button
277
+ onClick={() => {
278
+ if (open) {
279
+ setOpen(false);
280
+ } else {
281
+ // Fire-and-forget a refresh on open so branches created/deleted in
282
+ // other workspaces surface without the user waiting for a poll.
283
+ // `fresh: true` forces a server-side `git fetch --prune`, bypassing
284
+ // the implicit-fetch TTL, so a draft another workspace just deleted
285
+ // is pruned now rather than lingering until the TTL lapses. The
286
+ // cached list renders immediately; the refreshed list lands async.
287
+ void git.refreshBranches({ fresh: true });
288
+ // Measure the trigger now — in an event handler the button is on
289
+ // screen, and this setState batches with setOpen so the portal's
290
+ // first paint is already correctly positioned.
291
+ const r = ref.current?.getBoundingClientRect();
292
+ if (r) setPanelPos(computePanelPosition(r));
293
+ setOpen(true);
294
+ }
295
+ setError(null);
296
+ }}
297
+ className="flex items-center gap-1.5 px-2 py-1 text-xs rounded hover:bg-slate-100 text-slate-700 disabled:opacity-60 disabled:cursor-not-allowed"
298
+ title={branchLabel}
299
+ // Stay clickable mid-switch so the user can re-pick a branch — the
300
+ // switch is just URL navigation and re-navigating cancels cleanly.
301
+ // Only disabled before the very first status load, when there's no
302
+ // branch name to show yet.
303
+ disabled={git.availability === 'loading' && !git.status}
304
+ >
305
+ {switchingTo ? (
306
+ <Loader2 size={13} className="animate-spin text-slate-500" />
307
+ ) : (
308
+ <GitBranch size={13} />
309
+ )}
310
+ <span className="max-w-[160px] truncate">
311
+ {switchingTo ?? branch}
312
+ </span>
313
+ <ChevronDown size={12} className={`transition-transform ${open ? 'rotate-180' : ''}`} />
314
+ </button>
315
+
316
+ {open && panelPos && createPortal(
317
+ <div
318
+ ref={panelRef}
319
+ className="fixed z-50 w-[400px] bg-slate-100 border border-slate-300 rounded-lg shadow-xl overflow-hidden"
320
+ style={{ top: panelPos.top, left: panelPos.left }}
321
+ >
322
+ {!creating && !choosingTarget && (
323
+ <>
324
+ <button
325
+ className="flex items-center gap-2 w-full text-left px-3 py-2 text-sm text-slate-700 hover:bg-slate-200/80"
326
+ onClick={() => setCreating(true)}
327
+ >
328
+ <Plus size={14} />
329
+ Start a shared draft…
330
+ </button>
331
+ <button
332
+ className="flex items-center gap-2 w-full text-left px-3 py-2 text-sm text-slate-700 hover:bg-slate-200/80 border-b border-slate-300 disabled:opacity-50 disabled:cursor-not-allowed"
333
+ onClick={() => setChoosingTarget(true)}
334
+ disabled={!canOpenPr}
335
+ title={
336
+ !currentBranch
337
+ ? 'No draft selected'
338
+ : currentBranch.isProtected
339
+ ? "You can't propose changes from an official version — switch to a draft first"
340
+ : 'Pick where this change request should land'
341
+ }
342
+ >
343
+ <GitPullRequest size={14} />
344
+ Propose this draft as a change request into…
345
+ </button>
346
+ </>
347
+ )}
348
+
349
+ {choosingTarget && (
350
+ <div className="border-b border-slate-300">
351
+ <div className="flex items-center justify-between px-3 pt-2 pb-1">
352
+ <span className="text-[11px] text-slate-600 uppercase tracking-wide">
353
+ Apply draft to…
354
+ </span>
355
+ <button
356
+ className="text-[11px] text-slate-600 hover:text-slate-700"
357
+ onClick={() => setChoosingTarget(false)}
358
+ >
359
+ Cancel
360
+ </button>
361
+ </div>
362
+ <div className="max-h-48 overflow-y-auto">
363
+ {targetBranches.length === 0 && (
364
+ <div className="px-3 py-2 text-xs text-slate-600">
365
+ No other branches to target.
366
+ </div>
367
+ )}
368
+ {targetBranches.map((b) => {
369
+ const displayName = protectedBranchDisplayName(b.name);
370
+ // Default destination for shared drafts: visually distinguish
371
+ // the default branch so users see the recommended path without
372
+ // having to read the slug. Others stay available, just quieter.
373
+ const isDefaultTarget = b.name === DEFAULT_BRANCH;
374
+ return (
375
+ <button
376
+ key={b.name}
377
+ onClick={() => doOpenPr(b.name)}
378
+ className={`flex items-center gap-2 w-full text-left px-3 py-1.5 text-sm ${
379
+ isDefaultTarget
380
+ ? 'bg-emerald-50 text-emerald-700 hover:bg-emerald-100'
381
+ : 'text-slate-700 hover:bg-slate-200/60'
382
+ }`}
383
+ >
384
+ {b.isProtected && <Lock size={11} className="text-slate-600" />}
385
+ {displayName ? (
386
+ <span className="truncate flex-1" title={b.name}>
387
+ {displayName}
388
+ {isDefaultTarget && (
389
+ <span className="ml-1.5 text-[10px] uppercase tracking-wide text-emerald-600">
390
+ default
391
+ </span>
392
+ )}
393
+ </span>
394
+ ) : (
395
+ <span className="truncate flex-1" title={b.name}>{b.name}</span>
396
+ )}
397
+ </button>
398
+ );
399
+ })}
400
+ </div>
401
+ </div>
402
+ )}
403
+
404
+ {creating && (
405
+ <div className="px-3 py-2 border-b border-slate-300 space-y-2">
406
+ <div className="text-[11px] text-slate-600">What are you changing?</div>
407
+ <input
408
+ autoFocus
409
+ type="text"
410
+ placeholder="e.g. Add owner to Checkout process"
411
+ value={newBranchName}
412
+ onChange={(e) => setNewBranchName(e.target.value)}
413
+ onKeyDown={(e) => {
414
+ if (e.key === 'Enter') doCreate();
415
+ if (e.key === 'Escape') {
416
+ setCreating(false);
417
+ setNewBranchName('');
418
+ }
419
+ }}
420
+ className="w-full bg-white border border-slate-300 rounded px-2 py-1 text-xs focus:outline-none focus:border-slate-400"
421
+ />
422
+ <div className="flex justify-end gap-1">
423
+ <button
424
+ onClick={() => {
425
+ setCreating(false);
426
+ setNewBranchName('');
427
+ }}
428
+ className="px-2 py-0.5 text-xs rounded hover:bg-slate-200 text-slate-700"
429
+ >
430
+ Cancel
431
+ </button>
432
+ <button
433
+ onClick={doCreate}
434
+ disabled={!newBranchName.trim()}
435
+ className="px-2 py-0.5 text-xs rounded bg-emerald-600 hover:bg-emerald-500 text-white disabled:opacity-50"
436
+ >
437
+ Start draft
438
+ </button>
439
+ </div>
440
+ </div>
441
+ )}
442
+
443
+ <div className="max-h-64 overflow-y-auto">
444
+ {git.branches.length === 0 && (
445
+ <div className="px-3 py-2 text-xs text-slate-600">No drafts yet.</div>
446
+ )}
447
+ {git.branches.map((b) => {
448
+ const current = isCurrentBranch(b);
449
+ // Three delete cases reach the picker:
450
+ // 1. Orphan — `hasRemote === false`. A branch whose remote
451
+ // counterpart was pruned (typically PR merged + GitHub
452
+ // auto-deletes the head). Pure local tidy-up, anyone can
453
+ // do it because there's nothing left on origin to push
454
+ // the delete to.
455
+ // 2. Authored draft — branch matches `<my-localpart>/...`.
456
+ // The current user owns it; delete pushes the remote
457
+ // ref away too so the discard is total. Confirm dialog
458
+ // lives in doDelete because this is destructive for
459
+ // every teammate who could see the draft.
460
+ // 3. Admin cleanup — current user is admin per `roles.yaml`.
461
+ // Admins can delete any non-protected, non-current branch,
462
+ // including teammates' drafts AND unprefixed CLI branches
463
+ // that have no author. Backend gate at
464
+ // `GitService.deleteBranch` is the authoritative check.
465
+ // The current branch and protected branches are never
466
+ // deletable (regression-guarded server-side too).
467
+ const isAuthoredByMe = isBranchAuthoredBy(b.name, user?.email);
468
+ const isOrphan = b.hasRemote === false;
469
+ const canDelete =
470
+ !b.isProtected && !current && (isOrphan || isAuthoredByMe || isAdmin);
471
+ const deleteTitle = isOrphan
472
+ ? 'Delete this draft (no longer shared)'
473
+ : `Delete shared draft "${b.name}" — removes it for everyone`;
474
+ return (
475
+ <div
476
+ key={b.name}
477
+ className={`flex items-stretch w-full text-sm group ${
478
+ current
479
+ ? 'bg-slate-200/70 text-slate-900'
480
+ : 'text-slate-700 hover:bg-slate-200/60'
481
+ }`}
482
+ >
483
+ <button
484
+ onClick={() => doSwitch(b.name)}
485
+ disabled={current}
486
+ aria-current={current ? 'true' : undefined}
487
+ className={`flex items-center gap-2 flex-1 min-w-0 text-left px-3 py-1.5 ${
488
+ current ? 'cursor-default' : ''
489
+ }`}
490
+ >
491
+ {current ? <Check size={12} /> : <span className="w-3" />}
492
+ {b.isProtected && <Lock size={11} className="text-slate-600" />}
493
+ <span className="truncate flex-1" title={b.name}>{b.name}</span>
494
+ </button>
495
+ {canDelete && (
496
+ <button
497
+ onClick={(e) => {
498
+ e.stopPropagation();
499
+ doDelete(b.name, !isOrphan);
500
+ }}
501
+ title={deleteTitle}
502
+ aria-label={deleteTitle}
503
+ className="px-2 text-slate-600 hover:text-red-600 hover:bg-slate-100/80 opacity-0 group-hover:opacity-100 focus:opacity-100 transition-opacity"
504
+ >
505
+ <Trash2 size={12} />
506
+ </button>
507
+ )}
508
+ </div>
509
+ );
510
+ })}
511
+ </div>
512
+
513
+ {error && (
514
+ <div
515
+ role="alert"
516
+ className="px-3 py-2 text-xs text-red-600 border-t border-slate-300"
517
+ >
518
+ {error.message}
519
+ </div>
520
+ )}
521
+ </div>,
522
+ document.body,
523
+ )}
524
+
525
+ </div>
526
+ );
527
+ }
@@ -0,0 +1,30 @@
1
+ export function DiffView({ diff }: { diff: string }) {
2
+ if (!diff.trim()) {
3
+ return (
4
+ <div className="px-3 py-3 text-xs text-slate-600">
5
+ No file changes in this save.
6
+ </div>
7
+ );
8
+ }
9
+ const lines = diff.split('\n');
10
+ return (
11
+ <pre className="px-3 py-2 text-xs font-mono leading-5 whitespace-pre">
12
+ {lines.map((line, i) => {
13
+ let cls = 'text-slate-700';
14
+ if (line.startsWith('+++') || line.startsWith('---')) cls = 'text-slate-600';
15
+ else if (line.startsWith('@@')) cls = 'text-sky-600';
16
+ else if (line.startsWith('+')) cls = 'text-emerald-700 bg-emerald-50';
17
+ else if (line.startsWith('-')) cls = 'text-red-700 bg-red-50';
18
+ else if (line.startsWith('diff ') || line.startsWith('index ')) cls = 'text-slate-600';
19
+ // <pre> expects phrasing content; use a block-displayed <span> so each
20
+ // diff line still takes a full row without violating the HTML content
21
+ // model (div-in-pre triggers hydration warnings in strict mode).
22
+ return (
23
+ <span key={i} className={`block ${cls}`}>
24
+ {line || '\u00A0'}
25
+ </span>
26
+ );
27
+ })}
28
+ </pre>
29
+ );
30
+ }