@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,59 @@
1
+ import { useState, useCallback, useEffect, useMemo } from 'react';
2
+ import type { AuthUser } from '@bevel-software/platform-shared';
3
+ import type { AuthContextValue } from '../state/auth.context';
4
+ import { loginWithPassword, fetchCurrentUser } from '../services/auth.api';
5
+ import { getToken, setToken, clearToken } from '../../../lib/api';
6
+ import { consumeMicrosoftCallback, OAUTH_ERROR_KEY } from '../services/microsoft-oauth';
7
+
8
+ export function useAuthState(): AuthContextValue {
9
+ const [user, setUser] = useState<AuthUser | null>(null);
10
+ const [token, setTokenState] = useState<string | null>(getToken());
11
+ const [isLoading, setIsLoading] = useState(true);
12
+
13
+ // On mount: first absorb a Microsoft OAuth callback (if we landed on it),
14
+ // then validate whatever token we have (from the callback or localStorage).
15
+ useEffect(() => {
16
+ const cb = consumeMicrosoftCallback();
17
+ if (cb.error) {
18
+ sessionStorage.setItem(OAUTH_ERROR_KEY, cb.error);
19
+ }
20
+ if (cb.token) {
21
+ setToken(cb.token);
22
+ setTokenState(cb.token);
23
+ }
24
+ const activeToken = cb.token ?? getToken();
25
+ if (!activeToken) {
26
+ setIsLoading(false);
27
+ return;
28
+ }
29
+
30
+ fetchCurrentUser()
31
+ .then(setUser)
32
+ .catch(() => {
33
+ clearToken();
34
+ setTokenState(null);
35
+ })
36
+ .finally(() => setIsLoading(false));
37
+ }, []); // eslint-disable-line react-hooks/exhaustive-deps
38
+
39
+ const login = useCallback(async (email: string, password: string) => {
40
+ const result = await loginWithPassword(email, password);
41
+ setToken(result.token);
42
+ setTokenState(result.token);
43
+ setUser(result.user);
44
+ }, []);
45
+
46
+ const logout = useCallback(() => {
47
+ clearToken();
48
+ setTokenState(null);
49
+ setUser(null);
50
+ }, []);
51
+
52
+ return useMemo(() => ({
53
+ user,
54
+ token,
55
+ isLoading,
56
+ login,
57
+ logout,
58
+ }), [user, token, isLoading, login, logout]);
59
+ }
@@ -0,0 +1,24 @@
1
+ import type { AuthUser, LoginResponse } from '@bevel-software/platform-shared';
2
+ import { authFetch } from '../../../lib/api';
3
+
4
+ export async function loginWithPassword(
5
+ email: string,
6
+ password: string,
7
+ ): Promise<LoginResponse> {
8
+ const res = await fetch('/api/auth/login', {
9
+ method: 'POST',
10
+ headers: { 'Content-Type': 'application/json' },
11
+ body: JSON.stringify({ email, password }),
12
+ });
13
+ if (!res.ok) {
14
+ const body = await res.json().catch(() => ({}));
15
+ throw new Error(body.error || 'Login failed');
16
+ }
17
+ return res.json();
18
+ }
19
+
20
+ export async function fetchCurrentUser(): Promise<AuthUser> {
21
+ const res = await authFetch('/api/auth/me');
22
+ if (!res.ok) throw new Error('Not authenticated');
23
+ return res.json();
24
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * "Sign in with Microsoft" client helpers.
3
+ *
4
+ * The flow is a full-page redirect (not fetch): the button sends the browser to
5
+ * the backend, which bounces to Microsoft and back to
6
+ * `/auth/microsoft/callback#token=…` (or `#error=…`). We read the JWT out of the
7
+ * URL fragment — fragments aren't sent to servers or stored in Referer/logs.
8
+ */
9
+
10
+ const CALLBACK_PATH = '/auth/microsoft/callback';
11
+ /** Set when the callback carried an error, read once by the login screen. */
12
+ export const OAUTH_ERROR_KEY = 'bevel_oauth_error';
13
+
14
+ /** Kick off the OAuth round-trip. */
15
+ export function startMicrosoftLogin(): void {
16
+ window.location.href = '/api/auth/microsoft/login';
17
+ }
18
+
19
+ /** Which login methods this deployment offers. */
20
+ export interface LoginProviders {
21
+ password: boolean;
22
+ microsoft: boolean;
23
+ }
24
+
25
+ /**
26
+ * Probe which login methods are enabled. On failure default to
27
+ * password-only so a transient error never hides the only working method
28
+ * (and never surfaces a Microsoft button the backend can't service).
29
+ */
30
+ export async function fetchLoginProviders(): Promise<LoginProviders> {
31
+ try {
32
+ const res = await fetch('/api/auth/providers');
33
+ if (!res.ok) return { password: true, microsoft: false };
34
+ const body = (await res.json()) as Partial<LoginProviders>;
35
+ return { password: body.password !== false, microsoft: !!body.microsoft };
36
+ } catch {
37
+ return { password: true, microsoft: false };
38
+ }
39
+ }
40
+
41
+ /**
42
+ * If the current page is the OAuth callback, extract the token/error from the
43
+ * fragment and scrub the URL (so the token never lingers in the address bar or
44
+ * browser history). Returns {} when not on the callback path.
45
+ */
46
+ export function consumeMicrosoftCallback(): { token?: string; error?: string } {
47
+ if (window.location.pathname !== CALLBACK_PATH) return {};
48
+ const raw = window.location.hash.startsWith('#')
49
+ ? window.location.hash.slice(1)
50
+ : window.location.hash;
51
+ const params = new URLSearchParams(raw);
52
+ const token = params.get('token') ?? undefined;
53
+ const error = params.get('error') ?? undefined;
54
+ // Replace the callback URL with the app root so a reload doesn't re-process it.
55
+ window.history.replaceState({}, '', '/');
56
+ return { token, error };
57
+ }
@@ -0,0 +1,18 @@
1
+ import { createContext, useContext } from 'react';
2
+ import type { AuthUser } from '@bevel-software/platform-shared';
3
+
4
+ export interface AuthContextValue {
5
+ user: AuthUser | null;
6
+ token: string | null;
7
+ isLoading: boolean;
8
+ login: (email: string, password: string) => Promise<void>;
9
+ logout: () => void;
10
+ }
11
+
12
+ export const AuthContext = createContext<AuthContextValue | null>(null);
13
+
14
+ export function useAuth(): AuthContextValue {
15
+ const ctx = useContext(AuthContext);
16
+ if (!ctx) throw new Error('useAuth must be used within AuthContext.Provider');
17
+ return ctx;
18
+ }
@@ -0,0 +1,347 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { render, screen, fireEvent, waitFor } from '@testing-library/react';
3
+ import { MemoryRouter } from 'react-router-dom';
4
+ import type {
5
+ BranchInfo,
6
+ CommitAttribution,
7
+ WorkingTreeStatus,
8
+ } from '@bevel-software/platform-shared';
9
+
10
+ // BranchSwitcher fetches `roles.yaml` access on mount to determine whether the
11
+ // current user is an admin (the backend treats "can write roles.yaml" as the
12
+ // admin-membership signal). Default the mock to `canWrite: false` so the
13
+ // existing author-only / dropdown tests keep their non-admin semantics;
14
+ // admin-specific cases below override the resolved value in `beforeEach`.
15
+ vi.mock('../../access/api', () => ({
16
+ fetchFileAccess: vi.fn().mockResolvedValue({
17
+ canWrite: false,
18
+ canDownload: false,
19
+ eligible: { roles: [], users: [] },
20
+ }),
21
+ }));
22
+ import { fetchFileAccess } from '../../access/api';
23
+
24
+ import { BranchSwitcher } from '../components/BranchSwitcher';
25
+ import { GitContext, type GitContextValue } from '../state/git.context';
26
+ import { ReviewContext, type ReviewContextValue } from '../../review/state/review.context';
27
+ import { AuthContext, type AuthContextValue } from '../../auth/state/auth.context';
28
+ import {
29
+ WorkspaceContext,
30
+ type WorkspaceContextValue,
31
+ } from '../../workspace/state/workspace.context';
32
+
33
+ function makeAttr(): CommitAttribution {
34
+ return {
35
+ sha: 'abcdef1234567890',
36
+ authorName: 'Alice',
37
+ authorEmail: 'alice@example.com',
38
+ subject: 's',
39
+ committedAt: '2026-04-29T00:00:00Z',
40
+ };
41
+ }
42
+
43
+ function makeStatus(overrides: Partial<WorkingTreeStatus> = {}): WorkingTreeStatus {
44
+ return {
45
+ branch: 'alice/draft',
46
+ hasUpstream: true,
47
+ unmergedFromUpstream: false,
48
+ ...overrides,
49
+ };
50
+ }
51
+
52
+ function makeGit(overrides: Partial<GitContextValue> = {}): GitContextValue {
53
+ const branches: BranchInfo[] = [];
54
+ return {
55
+ status: makeStatus(),
56
+ branches,
57
+ availability: 'ready',
58
+ lastError: null,
59
+ refreshStatus: async () => null,
60
+ refreshBranches: async () => {},
61
+ createBranch: async () => {},
62
+ deleteBranch: async () => {},
63
+ pull: async () => {},
64
+ fetchForkBase: async () => null,
65
+ revert: async () => makeAttr(),
66
+ fetchFileHistory: async () => [],
67
+ fetchFileDiff: async () => '',
68
+ fetchFileComparison: async () => '',
69
+ ...overrides,
70
+ };
71
+ }
72
+
73
+ function makeReview(overrides: Partial<ReviewContextValue> = {}): ReviewContextValue {
74
+ return {
75
+ session: null,
76
+ selectedPath: null,
77
+ fileDiff: null,
78
+ isLoadingDiff: false,
79
+ lastError: null,
80
+ isLoading: false,
81
+ refresh: async () => {},
82
+ selectPath: async () => {},
83
+ acceptOne: async () => {},
84
+ rejectOne: async () => {},
85
+ acceptAll: async () => {},
86
+ rejectAll: async () => {},
87
+ clearError: () => {},
88
+ ...overrides,
89
+ };
90
+ }
91
+
92
+ // BranchSwitcher mounts DirtySwitchDialog + ShareChangesDialog (both closed),
93
+ // whose hook bodies still reach into Auth / Chat / Workspace / Review on mount.
94
+ const auth = {
95
+ user: { id: 'u1', email: 'alice@example.com', name: 'Alice' },
96
+ token: 't',
97
+ isLoading: false,
98
+ login: async () => {},
99
+ logout: () => {},
100
+ } as unknown as AuthContextValue;
101
+
102
+ const workspace = {
103
+ workspaceId: 'ws-1',
104
+ openFilePath: null,
105
+ } as unknown as WorkspaceContextValue;
106
+
107
+ function renderSwitcher(git: GitContextValue = makeGit()) {
108
+ return render(
109
+ <MemoryRouter>
110
+ <AuthContext.Provider value={auth}>
111
+ <WorkspaceContext.Provider value={workspace}>
112
+ <GitContext.Provider value={git}>
113
+ <ReviewContext.Provider value={makeReview()}>
114
+ <BranchSwitcher />
115
+ </ReviewContext.Provider>
116
+ </GitContext.Provider>
117
+ </WorkspaceContext.Provider>
118
+ </AuthContext.Provider>
119
+ </MemoryRouter>,
120
+ );
121
+ }
122
+
123
+ // The dropdown is portaled to document.body (position: fixed) so the toolbar's
124
+ // mobile second row — which clips with overflow-x-auto/overflow-y-hidden —
125
+ // cannot hide it. These tests guard that portal and the click-outside handler,
126
+ // which now has to span both the trigger and the portaled panel.
127
+ describe('BranchSwitcher dropdown', () => {
128
+ const PANEL_ANCHOR = 'Start a shared draft…';
129
+
130
+ it('portals the dropdown panel to document.body, outside the trigger wrapper', () => {
131
+ renderSwitcher();
132
+ const trigger = screen.getByTitle('Your active shared draft');
133
+ expect(screen.queryByText(PANEL_ANCHOR)).toBeNull();
134
+
135
+ fireEvent.click(trigger);
136
+
137
+ const anchor = screen.getByText(PANEL_ANCHOR);
138
+ const panel = anchor.closest('div.fixed');
139
+ expect(panel).not.toBeNull();
140
+ // Portaled straight to <body>, not nested in the BranchSwitcher wrapper —
141
+ // that is what escapes the toolbar's overflow clip on mobile.
142
+ expect(panel?.parentElement).toBe(document.body);
143
+ const wrapper = trigger.closest('div.relative');
144
+ expect(wrapper).not.toBeNull();
145
+ expect(wrapper).not.toContainElement(anchor);
146
+ });
147
+
148
+ it('keeps the menu open when a click lands inside the portaled panel', () => {
149
+ renderSwitcher();
150
+ fireEvent.click(screen.getByTitle('Your active shared draft'));
151
+ const anchor = screen.getByText(PANEL_ANCHOR);
152
+
153
+ // Regression guard: the panel lives outside the trigger ref, so the
154
+ // click-outside handler must also check panelRef — otherwise the first
155
+ // mousedown inside the panel would close the menu before any click lands.
156
+ fireEvent.mouseDown(anchor);
157
+
158
+ expect(screen.getByText(PANEL_ANCHOR)).toBeInTheDocument();
159
+ });
160
+
161
+ it('closes the menu when a click lands outside both trigger and panel', () => {
162
+ renderSwitcher();
163
+ fireEvent.click(screen.getByTitle('Your active shared draft'));
164
+ expect(screen.getByText(PANEL_ANCHOR)).toBeInTheDocument();
165
+
166
+ fireEvent.mouseDown(document.body);
167
+
168
+ expect(screen.queryByText(PANEL_ANCHOR)).toBeNull();
169
+ });
170
+ });
171
+
172
+ // Delete affordance: a freshly-published draft has `hasRemote: true`, which
173
+ // the legacy `canDelete = !hasRemote && !isProtected && !current` rule hid
174
+ // (the orphan-cleanup mental model). Now the picker also offers delete for
175
+ // drafts authored by the current user (per `<email-localpart>/...` naming),
176
+ // and routes the destructive remote-delete through a confirm dialog.
177
+ describe('BranchSwitcher — author-can-delete affordance', () => {
178
+ beforeEach(() => {
179
+ vi.mocked(fetchFileAccess).mockResolvedValue({
180
+ canRead: true,
181
+ canWrite: false,
182
+ canDownload: false,
183
+ canOwner: false,
184
+ eligible: { roles: [], users: [] },
185
+ readers: { restricted: false, roles: [], users: [] },
186
+ owners: { roles: [], users: [] },
187
+ downloaders: { roles: [], users: [] },
188
+ sources: {},
189
+ });
190
+ });
191
+
192
+ function makeGitWithBranches(branches: BranchInfo[]): GitContextValue {
193
+ // Status branch must be a non-protected draft (so the trigger label
194
+ // stays "Your active shared draft") AND must NOT match any picker row
195
+ // name (otherwise that row gets the `current` flag and canDelete
196
+ // collapses regardless of authorship — different code path from the
197
+ // one we're trying to test here).
198
+ return makeGit({
199
+ status: makeStatus({ branch: 'alice/elsewhere' }),
200
+ branches,
201
+ });
202
+ }
203
+
204
+ it("shows the delete button for the current user's own published draft", () => {
205
+ renderSwitcher(makeGitWithBranches([
206
+ {
207
+ name: 'alice/my-draft',
208
+ isProtected: false,
209
+ ahead: 0,
210
+ behind: 0,
211
+ hasRemote: true,
212
+ },
213
+ ]));
214
+ fireEvent.click(screen.getByTitle('Your active shared draft'));
215
+ // aria-label mirrors the tooltip so screen-reader users hear the
216
+ // destructive-action warning, not just "delete".
217
+ expect(
218
+ screen.getByLabelText(
219
+ 'Delete shared draft "alice/my-draft" — removes it for everyone',
220
+ ),
221
+ ).toBeInTheDocument();
222
+ });
223
+
224
+ it("hides the delete button for another user's draft", () => {
225
+ renderSwitcher(makeGitWithBranches([
226
+ {
227
+ name: 'bob/other-draft',
228
+ isProtected: false,
229
+ ahead: 0,
230
+ behind: 0,
231
+ hasRemote: true,
232
+ },
233
+ ]));
234
+ fireEvent.click(screen.getByTitle('Your active shared draft'));
235
+ expect(
236
+ screen.queryByLabelText(
237
+ 'Delete shared draft "bob/other-draft" — removes it for everyone',
238
+ ),
239
+ ).toBeNull();
240
+ });
241
+
242
+ it('keeps the orphan-cleanup path (hasRemote=false) deletable for anyone', () => {
243
+ // PR merged + remote head pruned scenario: branch is local-only, anyone
244
+ // who has it in their picker can tidy it up because there's nothing on
245
+ // origin left to authorise against.
246
+ renderSwitcher(makeGitWithBranches([
247
+ {
248
+ name: 'bob/merged-and-pruned',
249
+ isProtected: false,
250
+ ahead: 0,
251
+ behind: 0,
252
+ hasRemote: false,
253
+ },
254
+ ]));
255
+ fireEvent.click(screen.getByTitle('Your active shared draft'));
256
+ expect(
257
+ screen.getByLabelText('Delete this draft (no longer shared)'),
258
+ ).toBeInTheDocument();
259
+ });
260
+ });
261
+
262
+ // Admin-can-delete affordance: when the current user is admin per the
263
+ // workspace's `roles.yaml` (signal: `canWrite('roles.yaml') === true`), the
264
+ // picker offers delete on any non-protected, non-current branch — including
265
+ // teammates' drafts AND unprefixed CLI branches with no author. Backend gate
266
+ // at `GitService.deleteBranch` is the authoritative check; this suite covers
267
+ // the UI surface only.
268
+ describe('BranchSwitcher — admin-can-delete affordance', () => {
269
+ beforeEach(() => {
270
+ vi.mocked(fetchFileAccess).mockResolvedValue({
271
+ canRead: true,
272
+ canWrite: true,
273
+ canDownload: false,
274
+ canOwner: false,
275
+ eligible: { roles: ['Admin'], users: [] },
276
+ readers: { restricted: false, roles: [], users: [] },
277
+ owners: { roles: [], users: [] },
278
+ downloaders: { roles: [], users: [] },
279
+ sources: {},
280
+ });
281
+ });
282
+
283
+ function makeGitWithBranches(branches: BranchInfo[]): GitContextValue {
284
+ // Status branch is alice's elsewhere-draft so no row collides with
285
+ // `current` (which would short-circuit canDelete regardless of admin).
286
+ return makeGit({
287
+ status: makeStatus({ branch: 'alice/elsewhere' }),
288
+ branches,
289
+ });
290
+ }
291
+
292
+ it("shows the delete button on another user's draft when the current user is admin", async () => {
293
+ renderSwitcher(makeGitWithBranches([
294
+ {
295
+ name: 'bob/other-draft',
296
+ isProtected: false,
297
+ ahead: 0,
298
+ behind: 0,
299
+ hasRemote: true,
300
+ },
301
+ ]));
302
+ fireEvent.click(screen.getByTitle('Your active shared draft'));
303
+ // `findBy` waits for the admin-status fetch to resolve and re-render.
304
+ expect(
305
+ await screen.findByLabelText(
306
+ 'Delete shared draft "bob/other-draft" — removes it for everyone',
307
+ ),
308
+ ).toBeInTheDocument();
309
+ });
310
+
311
+ it('shows the delete button on an unprefixed CLI branch when the current user is admin', async () => {
312
+ renderSwitcher(makeGitWithBranches([
313
+ {
314
+ name: 'fix/some-cli-branch',
315
+ isProtected: false,
316
+ ahead: 0,
317
+ behind: 0,
318
+ hasRemote: true,
319
+ },
320
+ ]));
321
+ fireEvent.click(screen.getByTitle('Your active shared draft'));
322
+ expect(
323
+ await screen.findByLabelText(
324
+ 'Delete shared draft "fix/some-cli-branch" — removes it for everyone',
325
+ ),
326
+ ).toBeInTheDocument();
327
+ });
328
+
329
+ it('still hides delete on protected branches (admin power does not extend here)', async () => {
330
+ renderSwitcher(makeGitWithBranches([
331
+ {
332
+ name: 'current-company-state',
333
+ isProtected: true,
334
+ ahead: 0,
335
+ behind: 0,
336
+ hasRemote: true,
337
+ },
338
+ ]));
339
+ fireEvent.click(screen.getByTitle('Your active shared draft'));
340
+ // Wait for the admin-status fetch to land so the assertion isn't racing
341
+ // an in-flight re-render.
342
+ await waitFor(() => {
343
+ expect(vi.mocked(fetchFileAccess)).toHaveBeenCalled();
344
+ });
345
+ expect(screen.queryByLabelText(/^Delete /)).toBeNull();
346
+ });
347
+ });