@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,1232 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
+ import { X, Lock, Loader2, ChevronDown, Check, Globe } from 'lucide-react';
3
+ import type { FileTreeEntry } from '@bevel-software/platform-shared';
4
+ import { useWorkspace } from '../../workspace/state/workspace.context';
5
+ import { useAuth } from '../../auth/state/auth.context';
6
+ import {
7
+ fetchFileAccess,
8
+ grantAccess,
9
+ revokeAccess,
10
+ suggestPrincipals,
11
+ asInheritedError,
12
+ type AccessResponse,
13
+ type GrantVerb,
14
+ type GrantSource,
15
+ type GrantSources,
16
+ type Principal,
17
+ type SuggestResponse,
18
+ } from '../api';
19
+
20
+ interface Props {
21
+ entry: FileTreeEntry;
22
+ onClose: () => void;
23
+ }
24
+
25
+ type Role = 'Owner' | 'Can edit' | 'Can read' | 'Can download';
26
+
27
+ /** Which verbs a principal holds at the target (independent flags). */
28
+ interface VerbSet {
29
+ owner: boolean;
30
+ write: boolean;
31
+ read: boolean;
32
+ download: boolean;
33
+ }
34
+
35
+ interface PrincipalRow {
36
+ key: string;
37
+ label: string;
38
+ sub?: string;
39
+ verbs: VerbSet;
40
+ isRole: boolean;
41
+ isYou: boolean;
42
+ /** The principal to send on grant / revoke. */
43
+ principal: Principal;
44
+ /** Per-verb origin of this row's access (from the resolver). */
45
+ sources?: GrantSources;
46
+ /**
47
+ * How this row may be managed HERE, derived from `sources` (now MECE —
48
+ * every source is `direct` or `ancestor`):
49
+ * - 'direct' — ≥1 verb is granted directly on the target; the verb
50
+ * editor is shown and Remove acts in place.
51
+ * - 'inherited' — ≥1 verb comes from an ancestor folder (and none direct);
52
+ * Remove opens the "Remove from parent?" flow.
53
+ * - 'external' — no file-backed source for any verb (a defensive fallback;
54
+ * a real grantee row always resolves to direct/ancestor,
55
+ * since rows are built from file-named principals). Shown
56
+ * read-only with no Remove.
57
+ */
58
+ manage: 'direct' | 'inherited' | 'external';
59
+ /** The distinct ancestor access.md path(s) this row inherits any verb from. */
60
+ ancestors: string[];
61
+ }
62
+
63
+ /**
64
+ * Classify a row's manageability from its per-verb sources (now MECE — every
65
+ * source is `direct` or `ancestor`):
66
+ * - any `direct` verb → 'direct' (editable in place).
67
+ * - else any `ancestor` verb → 'inherited' (remove-from-parent / deny-here).
68
+ * - else (no source for any verb) → 'external' (defensive fallback; a real
69
+ * grantee row always has a file source, since rows are built from
70
+ * file-named principals).
71
+ */
72
+ function classifyManage(sources: GrantSources | undefined): {
73
+ manage: 'direct' | 'inherited' | 'external';
74
+ ancestors: string[];
75
+ } {
76
+ const lists = sources ? Object.values(sources).filter((l): l is GrantSource[] => !!l) : [];
77
+ // A row is 'direct' (editable in place) when ANY verb's WINNING source (the
78
+ // closest, `[0]`) is direct — even if that same verb is ALSO inherited from a
79
+ // parent (`[direct, ancestor]`); the inherited tail still feeds `ancestors`
80
+ // below, so Remove can chain to the parent after stripping the direct entry.
81
+ const hasDirectWinner = lists.some((l) => l[0]?.kind === 'direct');
82
+ // Every ancestor named for any verb (including the tails of direct+ancestor
83
+ // verbs), so the confirm flow knows all the parents to offer.
84
+ const ancestors = [
85
+ ...new Set(lists.flatMap((l) => l.filter((s) => s.kind === 'ancestor').map((s) => (s as { path: string }).path))),
86
+ ];
87
+ if (hasDirectWinner) return { manage: 'direct', ancestors };
88
+ if (ancestors.length > 0) return { manage: 'inherited', ancestors };
89
+ return { manage: 'external', ancestors: [] };
90
+ }
91
+
92
+ /**
93
+ * A short, human folder label for an ancestor `access.md` path. Renders the
94
+ * LEAF folder only (the deepest segment) so long chains don't overflow the row;
95
+ * the full repo-relative path is exposed separately as a hover title.
96
+ */
97
+ function folderLabel(accessMdPath: string): string {
98
+ const dir = accessMdPath.replace(/\/?access\.md$/, '');
99
+ if (dir === '') return 'the root folder';
100
+ const segs = dir.split('/');
101
+ return segs[segs.length - 1];
102
+ }
103
+
104
+ /** The full folder path (for a hover title), repo-relative. */
105
+ function folderPath(accessMdPath: string): string {
106
+ const dir = accessMdPath.replace(/\/?access\.md$/, '');
107
+ return dir === '' ? 'the root folder' : dir;
108
+ }
109
+
110
+ /** The distinct ancestor `access.md` path(s) named across a per-verb sources map. */
111
+ function ancestorsFromSources(sources: GrantSources | undefined): string[] {
112
+ if (!sources) return [];
113
+ return [
114
+ ...new Set(
115
+ Object.values(sources)
116
+ .filter((l): l is GrantSource[] => !!l)
117
+ .flatMap((l) => l.filter((s) => s.kind === 'ancestor').map((s) => (s as { path: string }).path)),
118
+ ),
119
+ ];
120
+ }
121
+
122
+ /** The checklist order; download is independent and rendered separately. */
123
+ const TIER_ROLES: Role[] = ['Owner', 'Can edit', 'Can read'];
124
+
125
+ const AVATAR_COLORS = ['#863bff', '#0ea5e9', '#16a34a', '#f59e0b', '#ec4899', '#7e14ff'];
126
+
127
+ function initials(label: string): string {
128
+ const parts = label.replace(/[<>]/g, '').trim().split(/[\s@.]+/).filter(Boolean);
129
+ if (parts.length === 0) return '?';
130
+ if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
131
+ return (parts[0][0] + parts[1][0]).toUpperCase();
132
+ }
133
+
134
+ function avatarColor(seed: string): string {
135
+ let h = 0;
136
+ for (let i = 0; i < seed.length; i++) h = (h * 31 + seed.charCodeAt(i)) | 0;
137
+ return AVATAR_COLORS[Math.abs(h) % AVATAR_COLORS.length];
138
+ }
139
+
140
+ const EMAIL_RE = /^[^<>\s@]+@[^<>\s@]+\.[^<>\s@]+$/;
141
+
142
+ /** Human noun for a verb, used in the verb-scoped confirmation copy. */
143
+ const VERB_NOUN: Record<GrantVerb, string> = {
144
+ owner: 'owner',
145
+ write: 'edit',
146
+ read: 'read',
147
+ download: 'download',
148
+ };
149
+
150
+ /** The verb each UI role maps to when granting. */
151
+ const ROLE_TO_VERB: Record<Role, GrantVerb> = {
152
+ Owner: 'owner',
153
+ 'Can edit': 'write',
154
+ 'Can read': 'read',
155
+ 'Can download': 'download',
156
+ };
157
+
158
+ /** The VerbSet key each UI role reads/writes. */
159
+ const ROLE_TO_KEY: Record<Role, keyof VerbSet> = {
160
+ Owner: 'owner',
161
+ 'Can edit': 'write',
162
+ 'Can read': 'read',
163
+ 'Can download': 'download',
164
+ };
165
+
166
+ /** The built-in `everyone` group — grantable as public READ only (see backend). */
167
+ function isEveryoneRole(p: Principal): boolean {
168
+ return p.kind === 'role' && p.role.trim().toLowerCase() === 'everyone';
169
+ }
170
+
171
+ /** A short summary of the verbs a row holds, for the dropdown trigger. */
172
+ function summarizeVerbs(v: VerbSet): string {
173
+ const parts: string[] = [];
174
+ if (v.owner) parts.push('Owner');
175
+ else if (v.write) parts.push('Can edit');
176
+ else if (v.read) parts.push('Can read');
177
+ if (v.download) parts.push('Can download');
178
+ return parts.length ? parts.join(', ') : 'No access';
179
+ }
180
+
181
+ /**
182
+ * Google-Drive-style "Manage access" sheet. Reads the resolved access for a KB
183
+ * path and lets anyone who can write the path's access config share it: add one
184
+ * or more people/groups as chips and grant them a shared verb (Owner / Can edit /
185
+ * Can read / Can download). Each existing grantee's verbs are editable inline via
186
+ * a multi-select checklist (independent verbs); toggling a box grants or revokes
187
+ * that single verb. Grants/revokes write the folder's `access.md` (folder target)
188
+ * or the node's own frontmatter (file target) server-side and commit + push. When
189
+ * the user can't write the access config, the add affordance is disabled and
190
+ * names the owners to ask.
191
+ */
192
+ export function ManageAccessDialog({ entry, onClose }: Props) {
193
+ const { workspaceId, kbDirName } = useWorkspace();
194
+ const { user } = useAuth();
195
+ const [data, setData] = useState<AccessResponse | null>(null);
196
+ const [loading, setLoading] = useState(true);
197
+ const [error, setError] = useState<string | null>(null);
198
+
199
+ // Add-row state. `newVerbs` holds the (independent) verbs to grant the chips;
200
+ // it mirrors the per-row checklist so a new person can be given several at once.
201
+ const [query, setQuery] = useState('');
202
+ const [newVerbs, setNewVerbs] = useState<VerbSet>({
203
+ owner: false,
204
+ write: true,
205
+ read: false,
206
+ download: false,
207
+ });
208
+ const [verbOpen, setVerbOpen] = useState(false);
209
+ const [suggest, setSuggest] = useState<SuggestResponse | null>(null);
210
+ const [pickedChips, setPickedChips] = useState<Principal[]>([]);
211
+ const [busy, setBusy] = useState(false);
212
+ const [mutateError, setMutateError] = useState<string | null>(null);
213
+ // Which existing row's verb checklist is open (one at a time).
214
+ const [openRowKey, setOpenRowKey] = useState<string | null>(null);
215
+ // When set, the "Remove from parent?" confirmation is open for this principal.
216
+ // `ancestors` are the granting access.md path(s) (repo-relative, opaque) to
217
+ // echo back on remove-from-parent. `verb` scopes the action to a single verb
218
+ // (set when the flow was triggered by unchecking ONE inherited verb); absent
219
+ // ⇒ the whole principal (every verb), as for the row's Remove button.
220
+ const [confirmRemove, setConfirmRemove] = useState<{
221
+ principal: Principal;
222
+ label: string;
223
+ ancestors: string[];
224
+ verb?: GrantVerb;
225
+ } | null>(null);
226
+
227
+ // Repo-relative path the access resolver expects (strip the `<kbDir>/`
228
+ // prefix). `null` ⇒ the item isn't inside the KB, so it isn't governed.
229
+ const repoRelative = useMemo(() => {
230
+ if (!kbDirName) return null;
231
+ if (entry.relativePath === kbDirName) return '';
232
+ const prefix = `${kbDirName}/`;
233
+ return entry.relativePath.startsWith(prefix) ? entry.relativePath.slice(prefix.length) : null;
234
+ }, [entry.relativePath, kbDirName]);
235
+
236
+ const targetKind: 'folder' | 'file' = entry.type === 'directory' ? 'folder' : 'file';
237
+
238
+ const reload = useCallback(() => {
239
+ if (repoRelative === null || !workspaceId) return;
240
+ fetchFileAccess(workspaceId, repoRelative, targetKind)
241
+ .then((res) => {
242
+ setData(res);
243
+ setLoading(false);
244
+ })
245
+ .catch((err) => {
246
+ setError(err instanceof Error ? err.message : String(err));
247
+ setLoading(false);
248
+ });
249
+ }, [workspaceId, repoRelative, targetKind]);
250
+
251
+ useEffect(() => {
252
+ if (repoRelative === null || !workspaceId) return;
253
+ let cancelled = false;
254
+ fetchFileAccess(workspaceId, repoRelative, targetKind)
255
+ .then((res) => {
256
+ if (!cancelled) {
257
+ setData(res);
258
+ setLoading(false);
259
+ }
260
+ })
261
+ .catch((err) => {
262
+ if (!cancelled) {
263
+ setError(err instanceof Error ? err.message : String(err));
264
+ setLoading(false);
265
+ }
266
+ });
267
+ return () => {
268
+ cancelled = true;
269
+ };
270
+ }, [workspaceId, repoRelative, targetKind]);
271
+
272
+ useEffect(() => {
273
+ const onKey = (e: KeyboardEvent) => {
274
+ if (e.key === 'Escape') onClose();
275
+ };
276
+ document.addEventListener('keydown', onKey);
277
+ return () => document.removeEventListener('keydown', onKey);
278
+ }, [onClose]);
279
+
280
+ // Debounced autocomplete. People are withheld server-side until q ≥ 2 chars.
281
+ const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
282
+ useEffect(() => {
283
+ if (!workspaceId || repoRelative === null) return;
284
+ if (debounceRef.current) clearTimeout(debounceRef.current);
285
+ const q = query.trim();
286
+ if (!q) {
287
+ setSuggest(null);
288
+ return;
289
+ }
290
+ debounceRef.current = setTimeout(() => {
291
+ suggestPrincipals(workspaceId, q)
292
+ .then(setSuggest)
293
+ .catch(() => setSuggest(null));
294
+ }, 200);
295
+ return () => {
296
+ if (debounceRef.current) clearTimeout(debounceRef.current);
297
+ };
298
+ }, [query, workspaceId, repoRelative]);
299
+
300
+ const myEmail = user?.email?.toLowerCase() ?? '';
301
+
302
+ const principals = useMemo<PrincipalRow[]>(() => {
303
+ if (!data) return [];
304
+ // Aggregate the four resolver lists into ONE row per principal carrying its
305
+ // independent verb set. Membership IS the displayed set — we do NOT subtract
306
+ // the rollup. The resolver already folds owner⊇write⊇read on the lower lists,
307
+ // so an owner legitimately shows owner+write+read checked; download is its own
308
+ // axis (owner folds in, write does not), sourced from `downloaders`.
309
+ const rows = new Map<string, PrincipalRow>();
310
+ const touchRole = (role: string): PrincipalRow => {
311
+ const key = `r:${role.toLowerCase()}`;
312
+ let row = rows.get(key);
313
+ if (!row) {
314
+ row = {
315
+ key,
316
+ label: role,
317
+ isRole: true,
318
+ isYou: false,
319
+ principal: { kind: 'role', role },
320
+ verbs: { owner: false, write: false, read: false, download: false },
321
+ manage: 'direct',
322
+ ancestors: [],
323
+ };
324
+ rows.set(key, row);
325
+ }
326
+ return row;
327
+ };
328
+ const touchUser = (u: { name: string; email: string }): PrincipalRow => {
329
+ const key = `u:${u.email.toLowerCase()}`;
330
+ let row = rows.get(key);
331
+ if (!row) {
332
+ row = {
333
+ key,
334
+ label: u.name || u.email,
335
+ sub: u.email,
336
+ isRole: false,
337
+ isYou: u.email.toLowerCase() === myEmail,
338
+ principal: { kind: 'user', email: u.email, displayName: u.name || u.email },
339
+ verbs: { owner: false, write: false, read: false, download: false },
340
+ manage: 'direct',
341
+ ancestors: [],
342
+ };
343
+ rows.set(key, row);
344
+ }
345
+ return row;
346
+ };
347
+
348
+ for (const r of data.owners.roles) touchRole(r).verbs.owner = true;
349
+ for (const u of data.owners.users) touchUser(u).verbs.owner = true;
350
+ for (const r of data.eligible.roles) touchRole(r).verbs.write = true;
351
+ for (const u of data.eligible.users) touchUser(u).verbs.write = true;
352
+ // Read membership is per-principal only for a restricted node. When
353
+ // `restricted` is false, read is `everyone` and the reader lists are empty.
354
+ if (data.readers.restricted) {
355
+ for (const r of data.readers.roles) touchRole(r).verbs.read = true;
356
+ for (const u of data.readers.users) touchUser(u).verbs.read = true;
357
+ }
358
+ for (const r of data.downloaders.roles) touchRole(r).verbs.download = true;
359
+ for (const u of data.downloaders.users) touchUser(u).verbs.download = true;
360
+
361
+ // Attach each row's per-verb source + manageability (direct / inherited /
362
+ // external) from the resolver's `sources` map, keyed by the same row key.
363
+ for (const row of rows.values()) {
364
+ row.sources = data.sources?.[row.key];
365
+ const { manage, ancestors } = classifyManage(row.sources);
366
+ row.manage = manage;
367
+ row.ancestors = ancestors;
368
+ }
369
+
370
+ return [...rows.values()];
371
+ }, [data, myEmail]);
372
+
373
+ // Split direct (granted here, editable) from inherited/external (granted at a
374
+ // parent or via a role) so the main list stays clean and the rest collapses
375
+ // into a hidden "Inherited access" section.
376
+ const directRows = useMemo(() => principals.filter((p) => p.manage === 'direct'), [principals]);
377
+ const inheritedRows = useMemo(
378
+ () => principals.filter((p) => p.manage !== 'direct'),
379
+ [principals],
380
+ );
381
+ const [showInherited, setShowInherited] = useState(false);
382
+
383
+ const governed = repoRelative !== null;
384
+ // The dialog can mutate only if the current user can write this path's access
385
+ // config — exactly what the backend gate enforces. `canWrite` on the path is
386
+ // the same signal (folder access.md / node frontmatter both gate on write).
387
+ const canManage = !!data?.canWrite;
388
+
389
+ // Resolve the CURRENT typed query into a principal to append as a chip: an
390
+ // exact group match or a free-typed email. (Suggestion clicks append directly.)
391
+ const addPending: Principal | null = useMemo(() => {
392
+ const q = query.trim();
393
+ if (!q) return null;
394
+ const groupHit = suggest?.groups.find((g) => g.toLowerCase() === q.toLowerCase());
395
+ if (groupHit) return { kind: 'role', role: groupHit };
396
+ if (EMAIL_RE.test(q)) return { kind: 'user', email: q, displayName: q.split('@')[0] };
397
+ return null;
398
+ }, [query, suggest]);
399
+
400
+ const principalKey = (p: Principal): string =>
401
+ p.kind === 'role' ? `r:${p.role.toLowerCase()}` : `u:${p.email.toLowerCase()}`;
402
+
403
+ const addChip = useCallback((p: Principal) => {
404
+ setPickedChips((chips) =>
405
+ chips.some((c) => principalKey(c) === principalKey(p)) ? chips : [...chips, p],
406
+ );
407
+ setQuery('');
408
+ setSuggest(null);
409
+ }, []);
410
+
411
+ const removeChip = useCallback((p: Principal) => {
412
+ setPickedChips((chips) => chips.filter((c) => principalKey(c) !== principalKey(p)));
413
+ }, []);
414
+
415
+ // The new-grant checklist stores independent flags, but owner⊇write⊇read folds
416
+ // for display (selecting Owner implies edit+read; Edit implies read; owner also
417
+ // folds in download). `effectiveNewVerbs` is what the boxes render as checked.
418
+ const effectiveNewVerbs = useMemo<VerbSet>(
419
+ () => ({
420
+ owner: newVerbs.owner,
421
+ write: newVerbs.owner || newVerbs.write,
422
+ read: newVerbs.owner || newVerbs.write || newVerbs.read,
423
+ download: newVerbs.owner || newVerbs.download,
424
+ }),
425
+ [newVerbs],
426
+ );
427
+
428
+ // The minimal verb list to send: the single highest tier verb (the lower ones
429
+ // fold in server-side) plus download when it's chosen independently of owner.
430
+ const grantVerbs = useMemo<GrantVerb[]>(() => {
431
+ const verbs: GrantVerb[] = [];
432
+ if (effectiveNewVerbs.owner) verbs.push('owner');
433
+ else if (effectiveNewVerbs.write) verbs.push('write');
434
+ else if (effectiveNewVerbs.read) verbs.push('read');
435
+ if (effectiveNewVerbs.download && !effectiveNewVerbs.owner) verbs.push('download');
436
+ return verbs;
437
+ }, [effectiveNewVerbs]);
438
+
439
+ const doGrant = useCallback(async () => {
440
+ if (!workspaceId || repoRelative === null || pickedChips.length === 0 || grantVerbs.length === 0)
441
+ return;
442
+ setBusy(true);
443
+ setMutateError(null);
444
+ // No batch grant endpoint exists, so apply each principal/verb pair and
445
+ // collect failures rather than stopping on the first — one refused grant
446
+ // must not silently skip the remaining pairs. Partial success is reported
447
+ // after reload so the user sees exactly what didn't apply.
448
+ const failures: string[] = [];
449
+ try {
450
+ for (const principal of pickedChips) {
451
+ const label = principal.kind === 'role' ? principal.role : principal.email;
452
+ // `everyone` is public-read only — the backend rejects any other verb for
453
+ // it, so clamp here to avoid a guaranteed failure when a higher verb is
454
+ // also selected for the other chips.
455
+ const verbsForPrincipal = isEveryoneRole(principal)
456
+ ? (effectiveNewVerbs.read ? (['read'] as GrantVerb[]) : [])
457
+ : grantVerbs;
458
+ // Don't silently drop the Everyone chip when nothing read-equivalent was
459
+ // picked (e.g. only "Can download"): record it as a failure so the chip
460
+ // stays visible and the user is told why, rather than a no-op clear.
461
+ if (isEveryoneRole(principal) && verbsForPrincipal.length === 0) {
462
+ failures.push(`${label}: "Everyone" can only be granted read access — select "Can read".`);
463
+ continue;
464
+ }
465
+ for (const verb of verbsForPrincipal) {
466
+ try {
467
+ await grantAccess(workspaceId, {
468
+ path: entry.relativePath,
469
+ kind: targetKind,
470
+ verb,
471
+ principal,
472
+ });
473
+ } catch (err) {
474
+ failures.push(`${label} (${verb}): ${err instanceof Error ? err.message : String(err)}`);
475
+ }
476
+ }
477
+ }
478
+ if (failures.length === 0) {
479
+ setPickedChips([]);
480
+ setQuery('');
481
+ setSuggest(null);
482
+ } else {
483
+ setMutateError(
484
+ `${failures.length} grant${failures.length === 1 ? '' : 's'} failed (the rest were applied):\n${failures.join('\n')}`,
485
+ );
486
+ }
487
+ } finally {
488
+ reload();
489
+ setBusy(false);
490
+ }
491
+ }, [workspaceId, repoRelative, pickedChips, entry.relativePath, targetKind, grantVerbs, effectiveNewVerbs, reload]);
492
+
493
+ // Revoke the public-read grant (`read: everyone`) at THIS path. Clears the
494
+ // "Anyone can read" state when it was granted here; an inherited public grant
495
+ // (from a parent folder) stays and is removed where it was set.
496
+ const removePublicRead = useCallback(async () => {
497
+ if (!workspaceId || repoRelative === null) return;
498
+ setBusy(true);
499
+ setMutateError(null);
500
+ try {
501
+ await revokeAccess(workspaceId, {
502
+ path: entry.relativePath,
503
+ kind: targetKind,
504
+ principal: { kind: 'role', role: 'everyone' },
505
+ verb: 'read',
506
+ });
507
+ reload();
508
+ } catch (err) {
509
+ // The public-read grant lives in a parent folder — route the 409 into the
510
+ // same "Remove from parent? / Restrict here?" confirmation the grantee rows
511
+ // use, instead of a raw error toast.
512
+ const inherited = asInheritedError(err);
513
+ if (inherited) {
514
+ setConfirmRemove({
515
+ principal: { kind: 'role', role: 'everyone' },
516
+ label: 'Everyone',
517
+ ancestors: ancestorsFromSources(inherited.sources),
518
+ verb: 'read',
519
+ });
520
+ } else {
521
+ setMutateError(err instanceof Error ? err.message : String(err));
522
+ reload();
523
+ }
524
+ } finally {
525
+ setBusy(false);
526
+ }
527
+ }, [workspaceId, repoRelative, entry.relativePath, targetKind, reload]);
528
+
529
+ // Toggle a single verb on an existing grantee: check → grant that verb, uncheck
530
+ // → revoke just that verb. The server's fresh view is authoritative (we never
531
+ // flip optimistically); a refused revoke (e.g. last-owner) surfaces its message
532
+ // and we re-sync.
533
+ const doToggleVerb = useCallback(
534
+ async (principal: Principal, role: Role, currentlyOn: boolean) => {
535
+ if (!workspaceId || repoRelative === null) return;
536
+ setBusy(true);
537
+ setMutateError(null);
538
+ try {
539
+ const grantVerb = ROLE_TO_VERB[role];
540
+ const res = currentlyOn
541
+ ? await revokeAccess(workspaceId, {
542
+ path: entry.relativePath,
543
+ kind: targetKind,
544
+ principal,
545
+ verb: grantVerb,
546
+ })
547
+ : await grantAccess(workspaceId, {
548
+ path: entry.relativePath,
549
+ kind: targetKind,
550
+ verb: grantVerb,
551
+ principal,
552
+ });
553
+ setData(res);
554
+ // When UNCHECKING, the direct entry for this verb was stripped (200) but
555
+ // the principal may STILL hold the SAME verb via an ancestor — i.e. the
556
+ // verb was `[direct, ancestor]`. The fresh view still lists them with the
557
+ // ancestor for this verb; chain into the verb-scoped "Remove from parent?"
558
+ // so one uncheck finishes the job instead of a half-removal (the direct
559
+ // bit gone, the inherited bit silently remaining and the box re-checking).
560
+ if (currentlyOn) {
561
+ const key = principal.kind === 'role'
562
+ ? `r:${principal.role.toLowerCase()}`
563
+ : `u:${principal.email.toLowerCase()}`;
564
+ const stillForVerb = res.sources?.[key]?.[grantVerb] ?? [];
565
+ const ancestors = ancestorsFromSources({ [grantVerb]: stillForVerb });
566
+ if (ancestors.length > 0) {
567
+ const label =
568
+ principal.kind === 'role' ? principal.role : principal.displayName || principal.email;
569
+ setConfirmRemove({ principal, label, ancestors, verb: grantVerb });
570
+ }
571
+ }
572
+ } catch (err) {
573
+ // Unchecking a verb the principal holds via INHERITANCE (e.g. they're
574
+ // direct on `download` but inherit `write`) can't be done in place — the
575
+ // target splice no-ops and the route 409s. Convert that into the same
576
+ // "Remove from parent?" flow a Remove uses, instead of a raw error toast.
577
+ const inherited = asInheritedError(err);
578
+ if (inherited) {
579
+ const label =
580
+ principal.kind === 'role' ? principal.role : principal.displayName || principal.email;
581
+ // Scope the confirmation to the single verb the user unchecked, so
582
+ // "Restrict just this file" / "Remove from parent" act on THAT verb
583
+ // only and leave the principal's other (e.g. direct download) verbs.
584
+ setConfirmRemove({
585
+ principal,
586
+ label,
587
+ ancestors: ancestorsFromSources(inherited.sources),
588
+ verb: ROLE_TO_VERB[role],
589
+ });
590
+ } else {
591
+ setMutateError(err instanceof Error ? err.message : String(err));
592
+ reload(); // re-sync after a refused/rolled-back toggle
593
+ }
594
+ } finally {
595
+ setBusy(false);
596
+ }
597
+ },
598
+ [workspaceId, repoRelative, entry.relativePath, targetKind, reload],
599
+ );
600
+
601
+ const doRevoke = useCallback(
602
+ async (row: PrincipalRow) => {
603
+ if (!workspaceId || repoRelative === null) return;
604
+ // An inherited / external row can't be removed in place — open the
605
+ // "Remove from parent?" flow instead of firing a revoke that 409s.
606
+ if (row.manage !== 'direct') {
607
+ setConfirmRemove({
608
+ principal: row.principal,
609
+ label: row.label,
610
+ ancestors: row.ancestors,
611
+ });
612
+ return;
613
+ }
614
+ setBusy(true);
615
+ setMutateError(null);
616
+ try {
617
+ const res = await revokeAccess(workspaceId, {
618
+ path: entry.relativePath,
619
+ kind: targetKind,
620
+ principal: row.principal,
621
+ });
622
+ setData(res);
623
+ // The direct entry was removed, but the FRESH view may still list this
624
+ // principal with only `ancestor` source(s) — i.e. they're still inherited
625
+ // from a parent. Open "Remove from parent?" so the one Remove click can
626
+ // finish the job instead of leaving a row that reappears as inherited (a
627
+ // silent half-removal). We read the just-revoked row's post-revoke sources
628
+ // straight from the response, so it reflects the real current tree.
629
+ const ancestors = ancestorsFromSources(res.sources?.[row.key]);
630
+ if (ancestors.length > 0) {
631
+ setConfirmRemove({ principal: row.principal, label: row.label, ancestors });
632
+ }
633
+ } catch (err) {
634
+ // Defensive: a revoke that 409s straight away (a row that was purely
635
+ // inherited but somehow reached here) — fall back to the confirmation.
636
+ const inherited = asInheritedError(err);
637
+ if (inherited) {
638
+ setConfirmRemove({
639
+ principal: row.principal,
640
+ label: row.label,
641
+ ancestors: ancestorsFromSources(inherited.sources),
642
+ });
643
+ } else {
644
+ setMutateError(err instanceof Error ? err.message : String(err));
645
+ reload(); // re-sync the row state after a refused/rolled-back revoke
646
+ }
647
+ } finally {
648
+ setBusy(false);
649
+ }
650
+ },
651
+ [workspaceId, repoRelative, entry.relativePath, targetKind, reload],
652
+ );
653
+
654
+ /** Cascade up: remove the principal from the granting ancestor folder (optionally scoped to one verb). */
655
+ const doRemoveFromParent = useCallback(
656
+ async (principal: Principal, ancestorAccessMd: string, verb?: GrantVerb) => {
657
+ if (!workspaceId || repoRelative === null) return;
658
+ setBusy(true);
659
+ setMutateError(null);
660
+ try {
661
+ const res = await revokeAccess(workspaceId, {
662
+ path: entry.relativePath,
663
+ kind: targetKind,
664
+ principal,
665
+ mode: 'remove-from-parent',
666
+ // The ancestor is a FOLDER — strip the trailing `/access.md` so the
667
+ // server resolves it as a folder target. The path is opaque to us
668
+ // otherwise (repo-relative, echoed from the 409 sources).
669
+ ancestor: ancestorAccessMd.replace(/\/?access\.md$/, ''),
670
+ verb,
671
+ });
672
+ setData(res);
673
+ setConfirmRemove(null);
674
+ } catch (err) {
675
+ setMutateError(err instanceof Error ? err.message : String(err));
676
+ reload();
677
+ } finally {
678
+ setBusy(false);
679
+ }
680
+ },
681
+ [workspaceId, repoRelative, entry.relativePath, targetKind, reload],
682
+ );
683
+
684
+ /** Per-item override: add a `deny` at the target (optionally scoped to one verb), keeping the parent grant. */
685
+ const doDenyHere = useCallback(
686
+ async (principal: Principal, verb?: GrantVerb) => {
687
+ if (!workspaceId || repoRelative === null) return;
688
+ setBusy(true);
689
+ setMutateError(null);
690
+ try {
691
+ const res = await revokeAccess(workspaceId, {
692
+ path: entry.relativePath,
693
+ kind: targetKind,
694
+ principal,
695
+ mode: 'deny-here',
696
+ verb,
697
+ });
698
+ setData(res);
699
+ setConfirmRemove(null);
700
+ } catch (err) {
701
+ setMutateError(err instanceof Error ? err.message : String(err));
702
+ reload();
703
+ } finally {
704
+ setBusy(false);
705
+ }
706
+ },
707
+ [workspaceId, repoRelative, entry.relativePath, targetKind, reload],
708
+ );
709
+
710
+ const ownerNames = useMemo(() => {
711
+ if (!data) return '';
712
+ const names = [
713
+ ...data.owners.roles,
714
+ ...data.owners.users.map((u) => u.name || u.email),
715
+ ];
716
+ return names.slice(0, 3).join(', ');
717
+ }, [data]);
718
+
719
+ // One grantee row. Direct rows get the inline verb editor; inherited rows are
720
+ // read-only with a Remove that opens the cascade flow; external rows are
721
+ // read-only with no action. `dense` trims the avatar/labels in the collapsed
722
+ // inherited section so a deep folder chain doesn't overflow.
723
+ const renderRow = (p: PrincipalRow) => (
724
+ <div key={p.key} className="flex items-center gap-3 py-2 group">
725
+ <div
726
+ className="w-9 h-9 rounded-full flex items-center justify-center text-[13px] font-bold text-white shrink-0"
727
+ style={{ background: p.isRole ? '#64748b' : avatarColor(p.label) }}
728
+ >
729
+ {initials(p.label)}
730
+ </div>
731
+ <div className="flex-1 min-w-0">
732
+ <div className="text-sm text-slate-900 font-medium truncate">
733
+ {p.label}
734
+ {p.isYou && <span className="text-slate-400 font-normal"> (you)</span>}
735
+ {p.isRole && (
736
+ <span className="ml-1.5 text-[10px] uppercase tracking-wide text-slate-400">role</span>
737
+ )}
738
+ </div>
739
+ {p.sub && <div className="text-xs text-slate-500 truncate">{p.sub}</div>}
740
+ </div>
741
+ {canManage && p.manage === 'inherited' ? (
742
+ // Inherited from a parent folder — read-only here. Leaf folder name only
743
+ // (full path on hover); Remove opens the "Remove from parent?" flow.
744
+ <div className="flex items-center gap-2 shrink-0">
745
+ <span
746
+ className="text-xs text-slate-400 italic max-w-[10rem] truncate"
747
+ title={p.ancestors.map(folderPath).join(', ')}
748
+ >
749
+ via {p.ancestors.map(folderLabel).join(', ')}
750
+ </span>
751
+ <span className="text-sm text-slate-400">{summarizeVerbs(p.verbs)}</span>
752
+ <button
753
+ type="button"
754
+ disabled={busy}
755
+ onClick={() => doRevoke(p)}
756
+ className="px-2 py-1 rounded text-sm text-red-600 hover:bg-red-50 disabled:cursor-not-allowed"
757
+ >
758
+ Remove
759
+ </button>
760
+ </div>
761
+ ) : canManage && p.manage === 'external' ? (
762
+ // No file-backed grant to remove here — managed elsewhere (a group's
763
+ // membership, the everyone policy, or admin rescue).
764
+ <span
765
+ className="text-sm text-slate-400 shrink-0"
766
+ title="Granted via a role or policy — manage it there"
767
+ >
768
+ {summarizeVerbs(p.verbs)}
769
+ </span>
770
+ ) : canManage ? (
771
+ <div className="relative shrink-0">
772
+ <button
773
+ type="button"
774
+ disabled={busy}
775
+ onClick={() => setOpenRowKey((k) => (k === p.key ? null : p.key))}
776
+ className="px-2 py-1 rounded text-sm text-slate-600 flex items-center gap-1 hover:bg-slate-100 disabled:cursor-not-allowed"
777
+ >
778
+ {summarizeVerbs(p.verbs)}
779
+ <ChevronDown size={14} />
780
+ </button>
781
+ {openRowKey === p.key && (
782
+ <div className="absolute right-0 z-20 mt-1 bg-white border border-slate-200 rounded-lg shadow-lg w-44 py-1">
783
+ {TIER_ROLES.map((role) => {
784
+ const k = ROLE_TO_KEY[role];
785
+ const checked = p.verbs[k];
786
+ const disabled =
787
+ busy ||
788
+ (role === 'Can edit' && p.verbs.owner) ||
789
+ (role === 'Can read' && (p.verbs.owner || p.verbs.write));
790
+ return (
791
+ <button
792
+ key={role}
793
+ type="button"
794
+ disabled={disabled}
795
+ onClick={() => doToggleVerb(p.principal, role, checked)}
796
+ className="w-full flex items-center gap-2 px-3 py-1.5 text-sm hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed"
797
+ >
798
+ <span className="w-4 h-4 border border-slate-300 rounded flex items-center justify-center shrink-0">
799
+ {checked && <Check size={12} className="text-bevel" />}
800
+ </span>
801
+ <span className="flex-1 text-left">{role}</span>
802
+ </button>
803
+ );
804
+ })}
805
+ <div className="border-t border-slate-100 my-1" />
806
+ {(() => {
807
+ const checked = p.verbs.download;
808
+ const disabled = busy || p.verbs.owner;
809
+ return (
810
+ <button
811
+ type="button"
812
+ disabled={disabled}
813
+ onClick={() => doToggleVerb(p.principal, 'Can download', checked)}
814
+ className="w-full flex items-center gap-2 px-3 py-1.5 text-sm hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed"
815
+ >
816
+ <span className="w-4 h-4 border border-slate-300 rounded flex items-center justify-center shrink-0">
817
+ {checked && <Check size={12} className="text-bevel" />}
818
+ </span>
819
+ <span className="flex-1 text-left">Can download</span>
820
+ </button>
821
+ );
822
+ })()}
823
+ <div className="border-t border-slate-100 my-1" />
824
+ <button
825
+ type="button"
826
+ disabled={busy}
827
+ onClick={() => {
828
+ setOpenRowKey(null);
829
+ doRevoke(p);
830
+ }}
831
+ className="w-full text-left px-3 py-1.5 text-sm text-red-600 hover:bg-red-50 disabled:cursor-not-allowed"
832
+ >
833
+ Remove access
834
+ </button>
835
+ </div>
836
+ )}
837
+ </div>
838
+ ) : (
839
+ <span className="text-sm text-slate-500 shrink-0">{summarizeVerbs(p.verbs)}</span>
840
+ )}
841
+ </div>
842
+ );
843
+
844
+ return (
845
+ <div
846
+ className="fixed inset-0 z-[70] bg-slate-900/45 flex items-center justify-center p-4"
847
+ onMouseDown={(e) => {
848
+ if (e.target === e.currentTarget) onClose();
849
+ }}
850
+ >
851
+ <div
852
+ role="dialog"
853
+ aria-modal="true"
854
+ aria-labelledby="manage-access-title"
855
+ className="w-full max-w-[540px] max-h-[86vh] overflow-auto bg-white rounded-2xl shadow-2xl"
856
+ >
857
+ <div className="flex items-start justify-between gap-3 px-6 pt-5 pb-2">
858
+ <div className="min-w-0">
859
+ <h2 id="manage-access-title" className="text-lg font-bold text-slate-900">
860
+ Manage access
861
+ </h2>
862
+ <div className="mt-0.5 text-sm text-slate-500 truncate" title={entry.relativePath}>
863
+ {entry.name}
864
+ </div>
865
+ </div>
866
+ <button
867
+ type="button"
868
+ onClick={onClose}
869
+ className="p-1.5 rounded hover:bg-slate-100 text-slate-600 hover:text-slate-900 shrink-0"
870
+ aria-label="Close"
871
+ >
872
+ <X size={16} />
873
+ </button>
874
+ </div>
875
+
876
+ <div className="px-6 pb-2">
877
+ {governed && canManage && (
878
+ <div className="my-3">
879
+ <div className="flex gap-2 relative">
880
+ <div className="flex-1 relative">
881
+ <div className="w-full border border-slate-200 rounded-lg px-2 py-1.5 flex flex-wrap items-center gap-1.5 focus-within:ring-2 focus-within:ring-bevel/40">
882
+ {pickedChips.map((c) => {
883
+ const label = c.kind === 'role' ? c.role : c.displayName || c.email;
884
+ return (
885
+ <span
886
+ key={principalKey(c)}
887
+ className="inline-flex items-center gap-1 bg-slate-100 text-slate-700 rounded px-2 py-1 text-xs"
888
+ >
889
+ {label}
890
+ <button
891
+ type="button"
892
+ onClick={() => removeChip(c)}
893
+ className="text-slate-400 hover:text-red-600"
894
+ aria-label={`Remove ${label}`}
895
+ >
896
+ <X size={12} />
897
+ </button>
898
+ </span>
899
+ );
900
+ })}
901
+ <input
902
+ value={query}
903
+ onChange={(e) => setQuery(e.target.value)}
904
+ onKeyDown={(e) => {
905
+ if (e.key === 'Enter' && addPending) {
906
+ e.preventDefault();
907
+ addChip(addPending);
908
+ }
909
+ }}
910
+ placeholder={pickedChips.length ? '' : 'Add people or roles…'}
911
+ className="flex-1 min-w-[8rem] px-1 py-1 text-sm focus:outline-none"
912
+ />
913
+ </div>
914
+ {query.trim() && suggest && (suggest.groups.length > 0 || suggest.people.length > 0) && (
915
+ <div className="absolute z-10 left-0 right-0 mt-1 bg-white border border-slate-200 rounded-lg shadow-lg max-h-56 overflow-auto">
916
+ {suggest.groups.map((g) => (
917
+ <button
918
+ key={`g:${g}`}
919
+ type="button"
920
+ onClick={() => addChip({ kind: 'role', role: g })}
921
+ className="w-full text-left px-3 py-2 text-sm hover:bg-slate-50 flex items-center gap-2"
922
+ >
923
+ <span className="w-6 h-6 rounded-full bg-slate-500 text-white text-[10px] flex items-center justify-center">
924
+ {initials(g)}
925
+ </span>
926
+ <span className="flex-1">{g}</span>
927
+ <span className="text-[10px] uppercase tracking-wide text-slate-400">
928
+ role
929
+ </span>
930
+ </button>
931
+ ))}
932
+ {suggest.people.map((p) => (
933
+ <button
934
+ key={`p:${p.email}`}
935
+ type="button"
936
+ onClick={() => addChip({ kind: 'user', email: p.email, displayName: p.name })}
937
+ className="w-full text-left px-3 py-2 text-sm hover:bg-slate-50 flex items-center gap-2"
938
+ >
939
+ <span
940
+ className="w-6 h-6 rounded-full text-white text-[10px] flex items-center justify-center"
941
+ style={{ background: avatarColor(p.name || p.email) }}
942
+ >
943
+ {initials(p.name || p.email)}
944
+ </span>
945
+ <span className="flex-1 truncate">{p.name || p.email}</span>
946
+ <span className="text-xs text-slate-400 truncate">{p.email}</span>
947
+ </button>
948
+ ))}
949
+ </div>
950
+ )}
951
+ </div>
952
+
953
+ <div className="relative">
954
+ <button
955
+ type="button"
956
+ onClick={() => setVerbOpen((o) => !o)}
957
+ className="h-full px-3 rounded-lg border border-slate-200 text-sm text-slate-700 flex items-center gap-1 hover:bg-slate-50 max-w-[12rem]"
958
+ >
959
+ <span className="truncate">{summarizeVerbs(effectiveNewVerbs)}</span>
960
+ <ChevronDown size={14} className="shrink-0" />
961
+ </button>
962
+ {verbOpen && (
963
+ <div className="absolute right-0 z-10 mt-1 bg-white border border-slate-200 rounded-lg shadow-lg w-44 py-1">
964
+ {TIER_ROLES.map((role) => {
965
+ const k = ROLE_TO_KEY[role];
966
+ const checked = effectiveNewVerbs[k];
967
+ const disabled =
968
+ (role === 'Can edit' && effectiveNewVerbs.owner) ||
969
+ (role === 'Can read' && (effectiveNewVerbs.owner || effectiveNewVerbs.write));
970
+ return (
971
+ <button
972
+ key={role}
973
+ type="button"
974
+ disabled={disabled}
975
+ aria-pressed={checked}
976
+ onClick={() => setNewVerbs((v) => ({ ...v, [k]: !v[k] }))}
977
+ className="w-full flex items-center gap-2 px-3 py-1.5 text-sm hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed"
978
+ >
979
+ <span className="w-4 h-4 border border-slate-300 rounded flex items-center justify-center shrink-0">
980
+ {checked && <Check size={12} className="text-bevel" />}
981
+ </span>
982
+ <span className="flex-1 text-left">{role}</span>
983
+ </button>
984
+ );
985
+ })}
986
+ <div className="border-t border-slate-100 my-1" />
987
+ <button
988
+ type="button"
989
+ disabled={effectiveNewVerbs.owner}
990
+ aria-pressed={effectiveNewVerbs.download}
991
+ onClick={() => setNewVerbs((v) => ({ ...v, download: !v.download }))}
992
+ className="w-full flex items-center gap-2 px-3 py-1.5 text-sm hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed"
993
+ >
994
+ <span className="w-4 h-4 border border-slate-300 rounded flex items-center justify-center shrink-0">
995
+ {effectiveNewVerbs.download && <Check size={12} className="text-bevel" />}
996
+ </span>
997
+ <span className="flex-1 text-left">Can download</span>
998
+ </button>
999
+ </div>
1000
+ )}
1001
+ </div>
1002
+
1003
+ <button
1004
+ type="button"
1005
+ disabled={pickedChips.length === 0 || grantVerbs.length === 0 || busy}
1006
+ onClick={doGrant}
1007
+ className="px-4 rounded-lg text-sm font-medium bg-bevel hover:bg-bevel-deep text-white disabled:bg-bevel/40 disabled:cursor-not-allowed flex items-center gap-1.5"
1008
+ >
1009
+ {busy && <Loader2 size={14} className="animate-spin" />}
1010
+ Share
1011
+ </button>
1012
+ </div>
1013
+ {query.trim() && !addPending && !suggest?.peopleWithheld && (
1014
+ <div className="mt-1.5 text-xs text-slate-500">
1015
+ Type a full email to add someone, or pick a role from the list.
1016
+ </div>
1017
+ )}
1018
+ {pickedChips.some(isEveryoneRole) && (
1019
+ <div className="mt-1.5 text-xs text-slate-500">
1020
+ “Everyone” makes this {targetKind} publicly readable — it can only be granted read access.
1021
+ </div>
1022
+ )}
1023
+ {mutateError && (
1024
+ <div className="mt-2 text-sm text-red-700 bg-red-50 border border-red-200 rounded-lg px-3 py-2">
1025
+ {mutateError}
1026
+ </div>
1027
+ )}
1028
+ </div>
1029
+ )}
1030
+
1031
+ {!governed ? (
1032
+ <div className="py-8 text-center text-sm text-slate-500">
1033
+ This item isn't part of the knowledge base, so it isn't governed by access control.
1034
+ </div>
1035
+ ) : loading ? (
1036
+ <div className="flex items-center gap-2 py-8 justify-center text-sm text-slate-500">
1037
+ <Loader2 size={16} className="animate-spin" /> Loading access…
1038
+ </div>
1039
+ ) : error ? (
1040
+ <div className="py-6 text-sm text-red-700 bg-red-50 border border-red-200 rounded-lg px-3">
1041
+ Couldn't load access: {error}
1042
+ </div>
1043
+ ) : (
1044
+ <>
1045
+ {!canManage && (
1046
+ <div className="flex items-center gap-3 bg-bevel-soft rounded-lg px-3 py-2.5 mb-3 text-sm text-bevel-deep">
1047
+ <span className="flex-1">
1048
+ Only people with edit access can share this {targetKind}.
1049
+ {ownerNames && <> Ask an owner: {ownerNames}.</>}
1050
+ </span>
1051
+ </div>
1052
+ )}
1053
+
1054
+ <div className="text-sm font-bold text-slate-700 my-2">People with access</div>
1055
+
1056
+ {data && !data.readers.restricted && (
1057
+ <div className="flex items-center gap-3 py-1.5">
1058
+ <span className="w-8 h-8 rounded-full bg-emerald-600 text-white flex items-center justify-center shrink-0">
1059
+ <Globe size={16} />
1060
+ </span>
1061
+ <div className="flex-1 min-w-0">
1062
+ <div className="text-sm text-slate-800">Anyone can read</div>
1063
+ <div className="text-xs text-slate-500">Public — every signed-in user can read this {targetKind}</div>
1064
+ </div>
1065
+ {canManage && (
1066
+ <button
1067
+ type="button"
1068
+ disabled={busy}
1069
+ onClick={removePublicRead}
1070
+ className="text-xs text-slate-500 hover:text-red-600 disabled:opacity-50 px-2 py-1"
1071
+ >
1072
+ Remove
1073
+ </button>
1074
+ )}
1075
+ </div>
1076
+ )}
1077
+
1078
+ {directRows.length === 0 ? (
1079
+ <div className="text-sm text-slate-500 py-2">
1080
+ {inheritedRows.length > 0
1081
+ ? 'No one is granted directly here — everyone below inherits access from a parent folder.'
1082
+ : 'No explicit grants at this path.'}
1083
+ </div>
1084
+ ) : (
1085
+ directRows.map(renderRow)
1086
+ )}
1087
+
1088
+ {inheritedRows.length > 0 && (
1089
+ <div className="mt-3 border-t border-slate-100 pt-2">
1090
+ <button
1091
+ type="button"
1092
+ onClick={() => setShowInherited((v) => !v)}
1093
+ className="w-full flex items-center gap-1.5 py-1 text-sm font-medium text-slate-500 hover:text-slate-700"
1094
+ >
1095
+ <ChevronDown
1096
+ size={14}
1097
+ className={`transition-transform ${showInherited ? 'rotate-180' : ''}`}
1098
+ />
1099
+ Inherited access ({inheritedRows.length})
1100
+ <span className="font-normal text-slate-400">
1101
+ — from parent folders &amp; roles
1102
+ </span>
1103
+ </button>
1104
+ {showInherited && <div className="mt-1">{inheritedRows.map(renderRow)}</div>}
1105
+ </div>
1106
+ )}
1107
+
1108
+ <div className="flex items-center gap-3 border-t border-slate-100 mt-4 pt-4">
1109
+ <div className="w-9 h-9 rounded-full bg-slate-100 text-slate-600 flex items-center justify-center shrink-0">
1110
+ <Lock size={16} />
1111
+ </div>
1112
+ <div className="flex-1">
1113
+ <div className="text-sm font-semibold text-slate-800">Restricted</div>
1114
+ <div className="text-xs text-slate-500">
1115
+ Only people granted access can edit this item.
1116
+ </div>
1117
+ </div>
1118
+ </div>
1119
+ </>
1120
+ )}
1121
+ </div>
1122
+
1123
+ <div className="flex items-center justify-end gap-3 px-6 py-4">
1124
+ <button
1125
+ type="button"
1126
+ onClick={onClose}
1127
+ className="px-5 py-2 rounded-lg text-sm font-medium bg-bevel hover:bg-bevel-deep text-white"
1128
+ >
1129
+ Done
1130
+ </button>
1131
+ </div>
1132
+ </div>
1133
+
1134
+ {confirmRemove && (
1135
+ <div
1136
+ className="fixed inset-0 z-[80] bg-slate-900/40 flex items-center justify-center p-4"
1137
+ onMouseDown={(e) => {
1138
+ if (e.target === e.currentTarget && !busy) setConfirmRemove(null);
1139
+ }}
1140
+ >
1141
+ <div role="dialog" aria-modal="true" className="bg-white rounded-2xl shadow-xl w-full max-w-md p-6">
1142
+ {(() => {
1143
+ // When the flow was triggered by unchecking ONE verb, the whole
1144
+ // confirmation is scoped to it ("their EDIT access", "remove EDIT
1145
+ // from the parent"); otherwise it's the whole principal.
1146
+ const va = confirmRemove.verb ? `${VERB_NOUN[confirmRemove.verb]} access` : 'access';
1147
+ return (
1148
+ <>
1149
+ <h3 className="text-lg font-semibold text-slate-900">
1150
+ {confirmRemove.ancestors.length ? 'Remove from parent folder?' : 'Restrict access here?'}
1151
+ </h3>
1152
+ <p className="mt-2 text-sm text-slate-600">
1153
+ {confirmRemove.ancestors.length ? (
1154
+ <>
1155
+ {confirmRemove.label}'s {va} here is inherited from{' '}
1156
+ <span className="font-medium" title={confirmRemove.ancestors.map(folderPath).join(', ')}>
1157
+ {confirmRemove.ancestors.map(folderLabel).join(', ')}
1158
+ </span>
1159
+ . Remove their {va} from the parent — which also removes it from other items in
1160
+ that folder — or restrict just this {targetKind} while leaving the parent grant
1161
+ intact.
1162
+ </>
1163
+ ) : (
1164
+ <>
1165
+ {confirmRemove.label}'s {va} here comes from a role or policy, not a grant on
1166
+ this {targetKind}. You can't remove it here — but you can restrict their {va} on
1167
+ just this {targetKind} by adding a block.
1168
+ </>
1169
+ )}
1170
+ </p>
1171
+ </>
1172
+ );
1173
+ })()}
1174
+
1175
+ {mutateError && (
1176
+ <div className="mt-3 text-sm text-red-700 bg-red-50 border border-red-200 rounded-lg px-3 py-2">
1177
+ {mutateError}
1178
+ </div>
1179
+ )}
1180
+
1181
+ <div className="mt-5 flex flex-col gap-2">
1182
+ {confirmRemove.ancestors.length === 1 && (
1183
+ <button
1184
+ type="button"
1185
+ disabled={busy}
1186
+ onClick={() => doRemoveFromParent(confirmRemove.principal, confirmRemove.ancestors[0], confirmRemove.verb)}
1187
+ className="w-full px-4 py-2.5 rounded-lg text-sm font-medium bg-bevel hover:bg-bevel-deep text-white disabled:bg-bevel/40 disabled:cursor-not-allowed"
1188
+ >
1189
+ Remove from {folderLabel(confirmRemove.ancestors[0])}
1190
+ </button>
1191
+ )}
1192
+ {confirmRemove.ancestors.length > 1 && (
1193
+ <>
1194
+ <div className="text-xs text-slate-500">
1195
+ Inherited from multiple folders — remove from one at a time:
1196
+ </div>
1197
+ {confirmRemove.ancestors.map((a) => (
1198
+ <button
1199
+ key={a}
1200
+ type="button"
1201
+ disabled={busy}
1202
+ onClick={() => doRemoveFromParent(confirmRemove.principal, a, confirmRemove.verb)}
1203
+ className="w-full px-4 py-2.5 rounded-lg text-sm font-medium bg-bevel hover:bg-bevel-deep text-white disabled:bg-bevel/40 disabled:cursor-not-allowed"
1204
+ >
1205
+ Remove from {folderLabel(a)}
1206
+ </button>
1207
+ ))}
1208
+ </>
1209
+ )}
1210
+ <button
1211
+ type="button"
1212
+ disabled={busy}
1213
+ onClick={() => doDenyHere(confirmRemove.principal, confirmRemove.verb)}
1214
+ className="w-full px-4 py-2.5 rounded-lg text-sm font-medium border border-slate-300 text-slate-700 hover:bg-slate-50 disabled:cursor-not-allowed"
1215
+ >
1216
+ Restrict just this {targetKind}
1217
+ </button>
1218
+ <button
1219
+ type="button"
1220
+ disabled={busy}
1221
+ onClick={() => setConfirmRemove(null)}
1222
+ className="w-full px-4 py-2 rounded-lg text-sm text-slate-500 hover:bg-slate-50 disabled:cursor-not-allowed"
1223
+ >
1224
+ Cancel
1225
+ </button>
1226
+ </div>
1227
+ </div>
1228
+ </div>
1229
+ )}
1230
+ </div>
1231
+ );
1232
+ }