@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,74 @@
1
+ import { useState } from 'react';
2
+ import { ShieldAlert, Loader2 } from 'lucide-react';
3
+ import { useAdmin } from '../state/admin.context';
4
+ import { RolesApiError } from '../services/roles.api';
5
+
6
+ /**
7
+ * App-wide break-glass banner shown when `roles.yaml` fails to parse. A
8
+ * corrupted roles file is an app-wide admin lockout (the resolver hard-throws,
9
+ * so nobody resolves as admin and most surfaces 500). It renders for EVERY
10
+ * authenticated user — the backend recovery endpoint self-gates on the file
11
+ * actually being corrupted, and the "only press if you are from Bevel" copy is
12
+ * the honour-system layer on top of that hard gate.
13
+ */
14
+ export function RolesCorruptedBanner() {
15
+ const { rolesConfigCorrupted, rolesConfigErrors, runRolesRecovery } = useAdmin();
16
+ const [running, setRunning] = useState(false);
17
+ const [error, setError] = useState<string | null>(null);
18
+
19
+ if (!rolesConfigCorrupted) return null;
20
+
21
+ const onRecover = async () => {
22
+ if (running) return;
23
+ const confirmed = window.confirm(
24
+ 'Bevel Recovery will back up the corrupted roles.yaml to old-roles.yaml and ' +
25
+ 'restore the default Bevel roster. Only continue if you are from Bevel. Proceed?',
26
+ );
27
+ if (!confirmed) return;
28
+ setRunning(true);
29
+ setError(null);
30
+ try {
31
+ await runRolesRecovery();
32
+ // Reload so every view re-fetches with working access now that the
33
+ // lockout is cleared.
34
+ window.location.reload();
35
+ } catch (err) {
36
+ setRunning(false);
37
+ if (err instanceof RolesApiError && err.status === 409) {
38
+ // Someone else already recovered (file now parses) — just reload.
39
+ window.location.reload();
40
+ return;
41
+ }
42
+ setError(err instanceof Error ? err.message : 'Recovery failed. Please try again.');
43
+ }
44
+ };
45
+
46
+ return (
47
+ <div
48
+ role="alert"
49
+ className="flex flex-col gap-1 px-4 py-2.5 bg-red-600 text-white text-sm shrink-0"
50
+ >
51
+ <div className="flex items-center gap-2">
52
+ <ShieldAlert size={16} className="shrink-0" />
53
+ <span className="flex-1 font-semibold">
54
+ Roles file corrupted — contact Bevel for assistance.
55
+ </span>
56
+ <button
57
+ type="button"
58
+ onClick={onRecover}
59
+ disabled={running}
60
+ className="inline-flex items-center gap-1.5 rounded bg-white/15 hover:bg-white/25 disabled:opacity-60 px-2.5 py-1 text-xs font-medium border border-white/30"
61
+ >
62
+ {running && <Loader2 size={12} className="animate-spin" />}
63
+ {running ? 'Recovering…' : 'Bevel Recovery — only press if you are from Bevel'}
64
+ </button>
65
+ </div>
66
+ {rolesConfigErrors.length > 0 && (
67
+ <span className="pl-6 text-xs text-red-100/90 font-mono break-all">
68
+ {rolesConfigErrors.join('; ')}
69
+ </span>
70
+ )}
71
+ {error && <span className="pl-6 text-xs text-red-100">{error}</span>}
72
+ </div>
73
+ );
74
+ }
@@ -0,0 +1,92 @@
1
+ import { authFetch } from '../../../lib/api';
2
+
3
+ /**
4
+ * Single source of types for the admin inbox UI. Mirrors the backend shape in
5
+ * `feedback.interface.ts`. Re-declared here (rather than imported from
6
+ * `@bevel-software/platform-shared`) because the admin feature is small and lives entirely on
7
+ * the frontend + a couple of backend files — putting types in `shared` would
8
+ * pull a build-graph dependency for two interfaces.
9
+ */
10
+ export type FeedbackSource = 'user' | 'agent';
11
+
12
+ export interface FeedbackListItem {
13
+ id: string;
14
+ userId: string;
15
+ userEmail: string;
16
+ userName: string;
17
+ message: string;
18
+ source: FeedbackSource;
19
+ submittedAt: string;
20
+ }
21
+
22
+ export interface FeedbackListParams {
23
+ limit?: number;
24
+ cursor?: string;
25
+ source?: FeedbackSource;
26
+ q?: string;
27
+ }
28
+
29
+ export async function fetchAdminAccess(): Promise<{ isAdmin: boolean }> {
30
+ const res = await authFetch('/api/admin/access');
31
+ if (!res.ok) return { isAdmin: false };
32
+ return res.json();
33
+ }
34
+
35
+ /** One user account, as the admin user-administration dialog lists them. */
36
+ export interface AdminUser {
37
+ id: string;
38
+ email: string;
39
+ name: string;
40
+ /** Epoch ms of account creation. */
41
+ createdAt: number;
42
+ }
43
+
44
+ export async function fetchAdminUsers(): Promise<AdminUser[]> {
45
+ const res = await authFetch('/api/admin/users');
46
+ if (!res.ok) throw new Error('Failed to load user accounts');
47
+ const body = (await res.json()) as { users: AdminUser[] };
48
+ return body.users;
49
+ }
50
+
51
+ /**
52
+ * Permanently erase a user account (GDPR erasure path). The backend deletes
53
+ * the account and its personal data and anonymizes the user's past review
54
+ * activity; it refuses self-deletion (400).
55
+ */
56
+ export async function deleteAdminUser(userId: string): Promise<void> {
57
+ const res = await authFetch(`/api/admin/users/${encodeURIComponent(userId)}`, {
58
+ method: 'DELETE',
59
+ });
60
+ if (!res.ok) {
61
+ let serverError: string | undefined;
62
+ try {
63
+ const body = (await res.json()) as { error?: string };
64
+ if (typeof body.error === 'string' && body.error.length > 0) serverError = body.error;
65
+ } catch {
66
+ // Non-JSON error body — fall through to the fallback message.
67
+ }
68
+ throw new Error(serverError ?? 'Failed to delete this account');
69
+ }
70
+ }
71
+
72
+ export async function fetchFeedbackList(
73
+ params: FeedbackListParams,
74
+ ): Promise<FeedbackListItem[]> {
75
+ const qs = new URLSearchParams();
76
+ if (params.limit != null) qs.set('limit', String(params.limit));
77
+ if (params.cursor) qs.set('cursor', params.cursor);
78
+ if (params.source) qs.set('source', params.source);
79
+ if (params.q && params.q.trim().length > 0) qs.set('q', params.q.trim());
80
+ const res = await authFetch(`/api/admin/feedback?${qs.toString()}`);
81
+ if (!res.ok) throw new Error('Failed to load feedback');
82
+ const body = (await res.json()) as { items: FeedbackListItem[] };
83
+ return body.items;
84
+ }
85
+
86
+ export async function fetchUnreadCount(since: string | null): Promise<number> {
87
+ const qs = since ? `?since=${encodeURIComponent(since)}` : '';
88
+ const res = await authFetch(`/api/admin/feedback/unread-count${qs}`);
89
+ if (!res.ok) return 0;
90
+ const body = (await res.json()) as { count: number };
91
+ return typeof body.count === 'number' ? body.count : 0;
92
+ }
@@ -0,0 +1,136 @@
1
+ import { authFetch } from '../../../lib/api';
2
+
3
+ /**
4
+ * Typed client for the admin Roles & Members surface. Mirrors the backend shape
5
+ * in `roles-admin.service.ts`. Re-declared here (rather than imported from
6
+ * `@bevel-software/platform-shared`) to match the rest of the small admin feature, which
7
+ * keeps its types frontend-local.
8
+ */
9
+ export interface RoleRosterEntry {
10
+ canonical: string;
11
+ displayName: string;
12
+ members: string[];
13
+ isAdmin: boolean;
14
+ referencedBy: { path: string; verb: string }[];
15
+ }
16
+
17
+ /**
18
+ * Error carrying the backend's HTTP status and optional `kind` discriminator so
19
+ * callers can branch on 409 `self-admin-removal` (confirm flow) vs lock
20
+ * contention, surface 422 invariants verbatim, etc.
21
+ */
22
+ export class RolesApiError extends Error {
23
+ status: number;
24
+ kind?: string;
25
+ constructor(message: string, status: number, kind?: string) {
26
+ super(message);
27
+ this.name = 'RolesApiError';
28
+ this.status = status;
29
+ this.kind = kind;
30
+ }
31
+ }
32
+
33
+ async function parseRoster(res: Response): Promise<RoleRosterEntry[]> {
34
+ const body = (await res.json().catch(() => ({}))) as {
35
+ roles?: RoleRosterEntry[];
36
+ error?: string;
37
+ kind?: string;
38
+ };
39
+ if (!res.ok) {
40
+ throw new RolesApiError(
41
+ body.error || `Request failed (${res.status})`,
42
+ res.status,
43
+ body.kind,
44
+ );
45
+ }
46
+ return body.roles ?? [];
47
+ }
48
+
49
+ export async function fetchRoles(): Promise<RoleRosterEntry[]> {
50
+ const res = await authFetch('/api/access/roles');
51
+ return parseRoster(res);
52
+ }
53
+
54
+ /** Whether the default-branch roles.yaml currently parses. */
55
+ export interface RolesConfigHealth {
56
+ ok: boolean;
57
+ errors: string[];
58
+ }
59
+
60
+ /**
61
+ * Auth-only health probe for roles.yaml. On a transient/network failure we
62
+ * assume healthy rather than flash the scary "corrupted" banner on a blip — a
63
+ * real corruption persists and the next poll catches it.
64
+ */
65
+ export async function getRolesHealth(): Promise<RolesConfigHealth> {
66
+ try {
67
+ const res = await authFetch('/api/access/roles/health');
68
+ if (!res.ok) return { ok: true, errors: [] };
69
+ const body = (await res.json().catch(() => ({}))) as Partial<RolesConfigHealth>;
70
+ return { ok: body.ok !== false, errors: body.errors ?? [] };
71
+ } catch {
72
+ return { ok: true, errors: [] };
73
+ }
74
+ }
75
+
76
+ /** Trigger the Bevel Recovery: back up the corrupted file + restore the default. */
77
+ export async function recoverRoles(): Promise<RoleRosterEntry[]> {
78
+ const res = await authFetch('/api/access/roles/recover', { method: 'POST' });
79
+ return parseRoster(res);
80
+ }
81
+
82
+ export async function createRole(displayName: string): Promise<RoleRosterEntry[]> {
83
+ const res = await authFetch('/api/access/roles', {
84
+ method: 'POST',
85
+ headers: { 'Content-Type': 'application/json' },
86
+ body: JSON.stringify({ displayName }),
87
+ });
88
+ return parseRoster(res);
89
+ }
90
+
91
+ export async function deleteRole(canonical: string): Promise<RoleRosterEntry[]> {
92
+ const res = await authFetch(`/api/access/roles/${encodeURIComponent(canonical)}`, {
93
+ method: 'DELETE',
94
+ });
95
+ return parseRoster(res);
96
+ }
97
+
98
+ export async function renameRole(
99
+ canonical: string,
100
+ newDisplayName: string,
101
+ ): Promise<RoleRosterEntry[]> {
102
+ const res = await authFetch(`/api/access/roles/${encodeURIComponent(canonical)}`, {
103
+ method: 'PATCH',
104
+ headers: { 'Content-Type': 'application/json' },
105
+ body: JSON.stringify({ newDisplayName }),
106
+ });
107
+ return parseRoster(res);
108
+ }
109
+
110
+ export async function addMember(
111
+ canonical: string,
112
+ email: string,
113
+ ): Promise<RoleRosterEntry[]> {
114
+ const res = await authFetch(
115
+ `/api/access/roles/${encodeURIComponent(canonical)}/members`,
116
+ {
117
+ method: 'POST',
118
+ headers: { 'Content-Type': 'application/json' },
119
+ body: JSON.stringify({ email }),
120
+ },
121
+ );
122
+ return parseRoster(res);
123
+ }
124
+
125
+ export async function removeMember(
126
+ canonical: string,
127
+ email: string,
128
+ confirm?: boolean,
129
+ ): Promise<RoleRosterEntry[]> {
130
+ const qs = confirm ? '?confirm=true' : '';
131
+ const res = await authFetch(
132
+ `/api/access/roles/${encodeURIComponent(canonical)}/members/${encodeURIComponent(email)}${qs}`,
133
+ { method: 'DELETE' },
134
+ );
135
+ return parseRoster(res);
136
+ }
@@ -0,0 +1,223 @@
1
+ import {
2
+ createContext,
3
+ useCallback,
4
+ useContext,
5
+ useEffect,
6
+ useMemo,
7
+ useRef,
8
+ useState,
9
+ type ReactNode,
10
+ } from 'react';
11
+ import { useAuth } from '../../auth/state/auth.context';
12
+ import { fetchAdminAccess, fetchUnreadCount } from '../services/admin.api';
13
+ import { getRolesHealth, recoverRoles } from '../services/roles.api';
14
+
15
+ interface AdminContextValue {
16
+ isAdmin: boolean;
17
+ /** Number of feedback rows submitted after `lastSeen` (or total if null). */
18
+ unreadCount: number;
19
+ /** ISO timestamp; null means the admin has never opened the inbox. */
20
+ lastSeen: string | null;
21
+ /** Marks "now" as the new lastSeen, clears the badge, persists to storage. */
22
+ markSeen(): void;
23
+ /** Force a fresh count fetch — used after opening the inbox. */
24
+ refresh(): void;
25
+ /**
26
+ * True when the default-branch roles.yaml fails to parse — an app-wide admin
27
+ * lockout. Tracked independently of `isAdmin` (a corrupted file resolves
28
+ * nobody as admin, so this must surface even to non-admins) to drive the
29
+ * recovery banner.
30
+ */
31
+ rolesConfigCorrupted: boolean;
32
+ /** Parser errors backing `rolesConfigCorrupted`, for display. */
33
+ rolesConfigErrors: string[];
34
+ /** Run the Bevel Recovery: restore roles.yaml from the known-good default. */
35
+ runRolesRecovery(): Promise<void>;
36
+ }
37
+
38
+ export const AdminContext = createContext<AdminContextValue | null>(null);
39
+
40
+ // Per-admin so two accounts on the same machine don't share a baseline. The
41
+ // email is stable for the lifetime of an account.
42
+ function lastSeenKey(email: string): string {
43
+ return `bevel.adminFeedback.lastSeen.${email.toLowerCase()}`;
44
+ }
45
+
46
+ // 30s while the tab is visible. Hidden tabs skip the interval entirely so we
47
+ // don't burn battery / API quota for a backgrounded inbox.
48
+ const POLL_INTERVAL_MS = 30_000;
49
+
50
+ export function AdminProvider({ children }: { children: ReactNode }) {
51
+ const { user } = useAuth();
52
+ const email = user?.email ?? null;
53
+
54
+ const [isAdmin, setIsAdmin] = useState(false);
55
+ const [lastSeen, setLastSeen] = useState<string | null>(null);
56
+ const [unreadCount, setUnreadCount] = useState(0);
57
+ const [rolesConfigCorrupted, setRolesConfigCorrupted] = useState(false);
58
+ const [rolesConfigErrors, setRolesConfigErrors] = useState<string[]>([]);
59
+
60
+ // Latest lastSeen for the poller without re-creating the interval on every
61
+ // markSeen. Mirrors the pattern used in FeedbackDialog for submitting state.
62
+ const lastSeenRef = useRef<string | null>(null);
63
+ useEffect(() => {
64
+ lastSeenRef.current = lastSeen;
65
+ }, [lastSeen]);
66
+
67
+ // Resolve admin status + restore lastSeen whenever the signed-in email
68
+ // changes. Reset everything up front so a previous (possibly admin) user's
69
+ // state never lingers while the access check is in flight, and so a fetch
70
+ // failure falls back to "no admin" rather than stale access.
71
+ useEffect(() => {
72
+ setIsAdmin(false);
73
+ setLastSeen(null);
74
+ setUnreadCount(0);
75
+ if (!email) return;
76
+ let cancelled = false;
77
+ fetchAdminAccess()
78
+ .then((res) => {
79
+ if (cancelled) return;
80
+ setIsAdmin(res.isAdmin);
81
+ if (res.isAdmin) {
82
+ setLastSeen(localStorage.getItem(lastSeenKey(email)));
83
+ }
84
+ })
85
+ .catch(() => {
86
+ if (cancelled) return;
87
+ setIsAdmin(false);
88
+ setLastSeen(null);
89
+ setUnreadCount(0);
90
+ });
91
+ return () => {
92
+ cancelled = true;
93
+ };
94
+ }, [email]);
95
+
96
+ // roles.yaml health — polled INDEPENDENTLY of admin status. A corrupted file
97
+ // locks everyone out (nobody resolves as admin), so the recovery banner must
98
+ // reach non-admins too. On mount per signed-in user, then every 60s while the
99
+ // tab is visible so a mid-session corruption surfaces without a reload.
100
+ useEffect(() => {
101
+ // No synchronous reset here: the immediate check() below sets the correct
102
+ // value, and on logout the whole AdminProvider unmounts (state goes with
103
+ // it). Health is deployment-wide, so it never differs between users anyway.
104
+ if (!email) return;
105
+ let cancelled = false;
106
+ let timer: ReturnType<typeof setInterval> | null = null;
107
+
108
+ const check = () => {
109
+ getRolesHealth().then((h) => {
110
+ if (cancelled) return;
111
+ setRolesConfigCorrupted(!h.ok);
112
+ setRolesConfigErrors(h.errors);
113
+ });
114
+ };
115
+ const start = () => {
116
+ check();
117
+ if (timer === null) timer = setInterval(check, 60_000);
118
+ };
119
+ const stop = () => {
120
+ if (timer !== null) {
121
+ clearInterval(timer);
122
+ timer = null;
123
+ }
124
+ };
125
+ const onVisibility = () => {
126
+ if (document.visibilityState === 'visible') start();
127
+ else stop();
128
+ };
129
+
130
+ if (document.visibilityState === 'visible') start();
131
+ document.addEventListener('visibilitychange', onVisibility);
132
+ return () => {
133
+ cancelled = true;
134
+ stop();
135
+ document.removeEventListener('visibilitychange', onVisibility);
136
+ };
137
+ }, [email]);
138
+
139
+ const runRolesRecovery = useCallback(async () => {
140
+ await recoverRoles();
141
+ // The known-good default is now on disk; clear the banner. A full reload
142
+ // lets every view re-fetch with working access (the lockout poisoned them).
143
+ setRolesConfigCorrupted(false);
144
+ setRolesConfigErrors([]);
145
+ }, []);
146
+
147
+ const refresh = useCallback(() => {
148
+ if (!isAdmin) return;
149
+ fetchUnreadCount(lastSeenRef.current).then(setUnreadCount).catch(() => {
150
+ // Swallow — a transient failure shouldn't blank the badge. Next poll
151
+ // will resync.
152
+ });
153
+ }, [isAdmin]);
154
+
155
+ // Poll while admin + tab is visible. Re-run on visibility change so a tab
156
+ // returning to the foreground gets a fresh count immediately instead of
157
+ // waiting up to 30s.
158
+ useEffect(() => {
159
+ if (!isAdmin) return;
160
+ let timer: ReturnType<typeof setInterval> | null = null;
161
+
162
+ function start() {
163
+ refresh();
164
+ timer = setInterval(refresh, POLL_INTERVAL_MS);
165
+ }
166
+ function stop() {
167
+ if (timer !== null) {
168
+ clearInterval(timer);
169
+ timer = null;
170
+ }
171
+ }
172
+ function onVisibility() {
173
+ if (document.visibilityState === 'visible') start();
174
+ else stop();
175
+ }
176
+
177
+ if (document.visibilityState === 'visible') start();
178
+ document.addEventListener('visibilitychange', onVisibility);
179
+ return () => {
180
+ stop();
181
+ document.removeEventListener('visibilitychange', onVisibility);
182
+ };
183
+ }, [isAdmin, refresh]);
184
+
185
+ const markSeen = useCallback(() => {
186
+ if (!email) return;
187
+ const now = new Date().toISOString();
188
+ localStorage.setItem(lastSeenKey(email), now);
189
+ setLastSeen(now);
190
+ setUnreadCount(0);
191
+ }, [email]);
192
+
193
+ const value = useMemo<AdminContextValue>(
194
+ () => ({
195
+ isAdmin,
196
+ unreadCount,
197
+ lastSeen,
198
+ markSeen,
199
+ refresh,
200
+ rolesConfigCorrupted,
201
+ rolesConfigErrors,
202
+ runRolesRecovery,
203
+ }),
204
+ [
205
+ isAdmin,
206
+ unreadCount,
207
+ lastSeen,
208
+ markSeen,
209
+ refresh,
210
+ rolesConfigCorrupted,
211
+ rolesConfigErrors,
212
+ runRolesRecovery,
213
+ ],
214
+ );
215
+
216
+ return <AdminContext.Provider value={value}>{children}</AdminContext.Provider>;
217
+ }
218
+
219
+ export function useAdmin(): AdminContextValue {
220
+ const ctx = useContext(AdminContext);
221
+ if (!ctx) throw new Error('useAdmin must be used within AdminProvider');
222
+ return ctx;
223
+ }
@@ -0,0 +1,135 @@
1
+ import { useState, useEffect, type FormEvent } from 'react';
2
+ import { useAuth } from '../state/auth.context';
3
+ import {
4
+ startMicrosoftLogin,
5
+ fetchLoginProviders,
6
+ OAUTH_ERROR_KEY,
7
+ } from '../services/microsoft-oauth';
8
+
9
+ const OAUTH_ERROR_MESSAGES: Record<string, string> = {
10
+ state: 'Microsoft sign-in could not be verified. Please try again.',
11
+ auth: 'Microsoft sign-in failed. Please try again.',
12
+ start: 'Could not start Microsoft sign-in. Please try again.',
13
+ };
14
+
15
+ export function LoginScreen() {
16
+ const { login } = useAuth();
17
+ const [email, setEmail] = useState('');
18
+ const [password, setPassword] = useState('');
19
+ const [error, setError] = useState<string | null>(null);
20
+ const [submitting, setSubmitting] = useState(false);
21
+ // Default to password-only until the probe resolves, matching fetchLoginProviders'
22
+ // failure fallback so we never flash a button the backend can't service.
23
+ const [passwordEnabled, setPasswordEnabled] = useState(true);
24
+ const [microsoftEnabled, setMicrosoftEnabled] = useState(false);
25
+
26
+ // Surface an error returned by the OAuth callback (stored by useAuthState),
27
+ // and probe which login methods this deployment offers.
28
+ useEffect(() => {
29
+ let mounted = true;
30
+ const oauthError = sessionStorage.getItem(OAUTH_ERROR_KEY);
31
+ if (oauthError) {
32
+ sessionStorage.removeItem(OAUTH_ERROR_KEY);
33
+ setError(OAUTH_ERROR_MESSAGES[oauthError] ?? 'Microsoft sign-in failed.');
34
+ }
35
+ // Capability probe: never set state after unmount.
36
+ fetchLoginProviders()
37
+ .then((providers) => {
38
+ if (!mounted) return;
39
+ setPasswordEnabled(providers.password);
40
+ setMicrosoftEnabled(providers.microsoft);
41
+ })
42
+ .catch(() => {});
43
+ return () => {
44
+ mounted = false;
45
+ };
46
+ }, []);
47
+
48
+ async function handleSubmit(e: FormEvent<HTMLFormElement>) {
49
+ e.preventDefault();
50
+ setError(null);
51
+ setSubmitting(true);
52
+ try {
53
+ await login(email.trim(), password);
54
+ } catch (err) {
55
+ setError(err instanceof Error ? err.message : 'Login failed');
56
+ } finally {
57
+ setSubmitting(false);
58
+ }
59
+ }
60
+
61
+ return (
62
+ <div className="flex items-center justify-center h-full bg-white">
63
+ <form
64
+ onSubmit={handleSubmit}
65
+ className="bg-white p-8 rounded-xl border border-slate-200 w-full max-w-sm space-y-5"
66
+ >
67
+ <div className="text-center space-y-1">
68
+ <h1 className="text-2xl font-semibold text-slate-900">Bevel</h1>
69
+ <p className="text-sm text-slate-600">Sign in to continue</p>
70
+ </div>
71
+
72
+ {passwordEnabled && (
73
+ <>
74
+ <div className="space-y-3">
75
+ <label className="block space-y-1">
76
+ <span className="text-xs text-slate-600">Email</span>
77
+ <input
78
+ type="email"
79
+ required
80
+ autoComplete="email"
81
+ value={email}
82
+ onChange={(e) => setEmail(e.target.value)}
83
+ className="w-full rounded-md bg-slate-100 border border-slate-300 px-3 py-2 text-sm text-slate-900 focus:outline-none focus:border-slate-400"
84
+ />
85
+ </label>
86
+ <label className="block space-y-1">
87
+ <span className="text-xs text-slate-600">Password</span>
88
+ <input
89
+ type="password"
90
+ required
91
+ autoComplete="current-password"
92
+ value={password}
93
+ onChange={(e) => setPassword(e.target.value)}
94
+ className="w-full rounded-md bg-slate-100 border border-slate-300 px-3 py-2 text-sm text-slate-900 focus:outline-none focus:border-slate-400"
95
+ />
96
+ </label>
97
+ </div>
98
+
99
+ <button
100
+ type="submit"
101
+ disabled={submitting}
102
+ className="w-full rounded-md bg-bevel text-white text-sm font-medium py-2 hover:bg-bevel-deep disabled:opacity-60 disabled:cursor-not-allowed"
103
+ >
104
+ {submitting ? 'Signing in…' : 'Sign in'}
105
+ </button>
106
+ </>
107
+ )}
108
+
109
+ {error && (
110
+ <div className="text-sm text-red-600" role="alert">
111
+ {error}
112
+ </div>
113
+ )}
114
+
115
+ {passwordEnabled && microsoftEnabled && (
116
+ <div className="flex items-center gap-3 text-xs text-slate-400">
117
+ <span className="h-px flex-1 bg-slate-200" />
118
+ or
119
+ <span className="h-px flex-1 bg-slate-200" />
120
+ </div>
121
+ )}
122
+
123
+ {microsoftEnabled && (
124
+ <button
125
+ type="button"
126
+ onClick={startMicrosoftLogin}
127
+ className="w-full rounded-md border border-slate-300 bg-white text-slate-700 text-sm font-medium py-2 hover:bg-slate-50"
128
+ >
129
+ Sign in with Microsoft
130
+ </button>
131
+ )}
132
+ </form>
133
+ </div>
134
+ );
135
+ }