@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,130 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { render, screen, waitFor } from '@testing-library/react';
3
+ import userEvent from '@testing-library/user-event';
4
+ import type { FileTreeEntry } from '@bevel-software/platform-shared';
5
+ import type { AccessResponse } from '../api';
6
+
7
+ // --- Mock the API module ----------------------------------------------------
8
+ const api = vi.hoisted(() => ({
9
+ fetchFileAccess: vi.fn(),
10
+ grantAccess: vi.fn(),
11
+ revokeAccess: vi.fn(),
12
+ suggestPrincipals: vi.fn(),
13
+ }));
14
+ vi.mock('../api', async (importOriginal) => {
15
+ const actual = await importOriginal<typeof import('../api')>();
16
+ return { ...actual, ...api };
17
+ });
18
+
19
+ // --- Mock the context hooks the dialog reads --------------------------------
20
+ vi.mock('../../workspace/state/workspace.context', () => ({
21
+ useWorkspace: () => ({ workspaceId: 'ws-1', kbDirName: 'knowledge-base' }),
22
+ }));
23
+ vi.mock('../../auth/state/auth.context', () => ({
24
+ useAuth: () => ({ user: { email: 'me@x.com', name: 'Me' } }),
25
+ }));
26
+
27
+ import { ManageAccessDialog } from '../components/ManageAccessDialog';
28
+
29
+ const KB = 'knowledge-base';
30
+ const ENTRY: FileTreeEntry = {
31
+ name: 'Deal.md',
32
+ relativePath: `${KB}/Sales/Deal.md`,
33
+ type: 'file',
34
+ } as unknown as FileTreeEntry;
35
+ const A = { name: 'Alice', email: 'alice@x.com' };
36
+
37
+ /** Open Alice's row dropdown and click its "Can edit" item (the LAST exact match
38
+ * — the top add-row verb selector also reads "Can edit"). */
39
+ async function openAndUncheckEdit(user: ReturnType<typeof userEvent.setup>) {
40
+ const trigger = await screen.findByRole('button', { name: /can edit, can download/i });
41
+ await user.click(trigger);
42
+ const editItems = await screen.findAllByRole('button', { name: /^can edit$/i });
43
+ await user.click(editItems[editItems.length - 1]);
44
+ }
45
+
46
+ describe('ManageAccessDialog — unchecking an inherited verb on a mixed row', () => {
47
+ beforeEach(() => {
48
+ vi.clearAllMocks();
49
+ api.suggestPrincipals.mockResolvedValue({ groups: [], people: [], peopleWithheld: false });
50
+ });
51
+
52
+ it('write PURELY inherited (download direct): uncheck "Can edit" → 409 → opens prompt on FIRST click, revokes only write', async () => {
53
+ const user = userEvent.setup();
54
+ api.fetchFileAccess.mockResolvedValue({
55
+ canRead: true, canWrite: true, canDownload: true, canOwner: true,
56
+ eligible: { roles: [], users: [A] },
57
+ readers: { restricted: true, roles: [], users: [A] },
58
+ owners: { roles: [], users: [] },
59
+ downloaders: { roles: [], users: [A] },
60
+ sources: {
61
+ 'u:alice@x.com': {
62
+ read: [{ kind: 'ancestor', path: 'Sales/access.md' }],
63
+ write: [{ kind: 'ancestor', path: 'Sales/access.md' }],
64
+ download: [{ kind: 'direct' }],
65
+ },
66
+ },
67
+ } as AccessResponse);
68
+ const { GitApiError } = await import('../../git/services/git.api');
69
+ api.revokeAccess.mockRejectedValue(
70
+ new GitApiError(409, 'inherited', {
71
+ kind: 'inherited', error: 'inherited',
72
+ sources: { write: [{ kind: 'ancestor', path: 'Sales/access.md' }] },
73
+ }),
74
+ );
75
+
76
+ render(<ManageAccessDialog entry={ENTRY} onClose={() => {}} />);
77
+ await openAndUncheckEdit(user);
78
+
79
+ await waitFor(() => expect(api.revokeAccess).toHaveBeenCalledTimes(1));
80
+ expect(api.revokeAccess).toHaveBeenCalledWith('ws-1', expect.objectContaining({ verb: 'write' }));
81
+ expect(api.revokeAccess).not.toHaveBeenCalledWith('ws-1', expect.objectContaining({ verb: 'read' }));
82
+ await waitFor(() =>
83
+ expect(screen.getByRole('heading', { name: /remove from parent folder\?/i })).toBeInTheDocument(),
84
+ );
85
+ });
86
+
87
+ it('write DIRECT + also inherited: uncheck "Can edit" → 200 strips direct, still inherited → chains to prompt on the FIRST click (no second click)', async () => {
88
+ const user = userEvent.setup();
89
+ // write is `[direct, ancestor]` — Alice is named on the file AND inherits write.
90
+ api.fetchFileAccess.mockResolvedValue({
91
+ canRead: true, canWrite: true, canDownload: true, canOwner: true,
92
+ eligible: { roles: [], users: [A] },
93
+ readers: { restricted: true, roles: [], users: [A] },
94
+ owners: { roles: [], users: [] },
95
+ downloaders: { roles: [], users: [A] },
96
+ sources: {
97
+ 'u:alice@x.com': {
98
+ read: [{ kind: 'direct' }],
99
+ write: [{ kind: 'direct' }, { kind: 'ancestor', path: 'Sales/access.md' }],
100
+ download: [{ kind: 'direct' }],
101
+ },
102
+ },
103
+ } as AccessResponse);
104
+ // The 200 fresh view AFTER stripping the direct write: write now only inherited.
105
+ api.revokeAccess.mockResolvedValue({
106
+ canRead: true, canWrite: true, canDownload: true, canOwner: true,
107
+ eligible: { roles: [], users: [A] },
108
+ readers: { restricted: true, roles: [], users: [A] },
109
+ owners: { roles: [], users: [] },
110
+ downloaders: { roles: [], users: [A] },
111
+ sources: {
112
+ 'u:alice@x.com': {
113
+ read: [{ kind: 'direct' }],
114
+ write: [{ kind: 'ancestor', path: 'Sales/access.md' }], // direct gone, inherited remains
115
+ download: [{ kind: 'direct' }],
116
+ },
117
+ },
118
+ } as AccessResponse);
119
+
120
+ render(<ManageAccessDialog entry={ENTRY} onClose={() => {}} />);
121
+ await openAndUncheckEdit(user);
122
+
123
+ // ONE revoke (verb: write), and the prompt opens WITHOUT a second click.
124
+ await waitFor(() => expect(api.revokeAccess).toHaveBeenCalledTimes(1));
125
+ expect(api.revokeAccess).toHaveBeenCalledWith('ws-1', expect.objectContaining({ verb: 'write' }));
126
+ await waitFor(() =>
127
+ expect(screen.getByRole('heading', { name: /remove from parent folder\?/i })).toBeInTheDocument(),
128
+ );
129
+ });
130
+ });
@@ -0,0 +1,253 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { renderHook, waitFor } from '@testing-library/react';
3
+ import type { ReactNode } from 'react';
4
+
5
+ import {
6
+ WorkspaceContext,
7
+ type WorkspaceContextValue,
8
+ } from '../../workspace/state/workspace.context';
9
+
10
+ const apiMock = vi.hoisted(() => ({
11
+ fetchFileAccess: vi.fn(),
12
+ }));
13
+ vi.mock('../api', () => ({
14
+ fetchFileAccess: apiMock.fetchFileAccess,
15
+ fetchFileAccessBatch: vi.fn(),
16
+ }));
17
+
18
+ import { useFileAccess, formatEligible } from '../hooks/useFileAccess';
19
+
20
+ // Default branch for tests that exercise the network path. The hook
21
+ // short-circuits to canWrite=true on non-protected (draft) branches without
22
+ // hitting the API, so tests covering the API behavior need a protected branch.
23
+ const PROTECTED = 'current-company-state';
24
+ const DRAFT = 'alice/fix-onboarding';
25
+
26
+ function makeWorkspace(overrides: Partial<WorkspaceContextValue> = {}): WorkspaceContextValue {
27
+ return {
28
+ workspaceId: 'ws-1',
29
+ kbDirName: 'knowledge-base',
30
+ ...overrides,
31
+ } as unknown as WorkspaceContextValue;
32
+ }
33
+
34
+ function withWorkspace(value: WorkspaceContextValue) {
35
+ return ({ children }: { children: ReactNode }) => (
36
+ <WorkspaceContext.Provider value={value}>{children}</WorkspaceContext.Provider>
37
+ );
38
+ }
39
+
40
+ describe('useFileAccess', () => {
41
+ beforeEach(() => {
42
+ apiMock.fetchFileAccess.mockReset();
43
+ });
44
+
45
+ it('returns canWrite=null while the request is in flight, then the resolved value', async () => {
46
+ apiMock.fetchFileAccess.mockResolvedValueOnce({
47
+ canWrite: true,
48
+ eligible: { roles: ['Admin'], users: [] },
49
+ });
50
+
51
+ const { result } = renderHook(
52
+ () => useFileAccess('knowledge-base/Knowledge/Foo.md', PROTECTED),
53
+ { wrapper: withWorkspace(makeWorkspace()) },
54
+ );
55
+
56
+ expect(result.current.canWrite).toBeNull();
57
+ expect(result.current.loading).toBe(true);
58
+
59
+ await waitFor(() => {
60
+ expect(result.current.loading).toBe(false);
61
+ });
62
+ expect(result.current.canWrite).toBe(true);
63
+ expect(result.current.eligible.roles).toEqual(['Admin']);
64
+ });
65
+
66
+ it('returns canWrite=false with eligible when the backend denies a repo file', async () => {
67
+ apiMock.fetchFileAccess.mockResolvedValueOnce({
68
+ canWrite: false,
69
+ eligible: {
70
+ roles: ['Admin', 'Product Manager'],
71
+ users: [{ name: 'Felix Kissel', email: 'felix.kissel@example.com' }],
72
+ },
73
+ });
74
+
75
+ const { result } = renderHook(
76
+ () => useFileAccess('knowledge-base/Knowledge/Sales/Foo.md', PROTECTED),
77
+ { wrapper: withWorkspace(makeWorkspace()) },
78
+ );
79
+
80
+ await waitFor(() => expect(result.current.loading).toBe(false));
81
+ expect(result.current.canWrite).toBe(false);
82
+ expect(result.current.eligible.roles).toEqual(['Admin', 'Product Manager']);
83
+ expect(result.current.eligible.users[0].email).toBe('felix.kissel@example.com');
84
+ });
85
+
86
+ it('default-allows on transient API failure (does not trap the user)', async () => {
87
+ apiMock.fetchFileAccess.mockRejectedValueOnce(new Error('network down'));
88
+
89
+ const { result } = renderHook(
90
+ () => useFileAccess('knowledge-base/Knowledge/Foo.md', PROTECTED),
91
+ { wrapper: withWorkspace(makeWorkspace()) },
92
+ );
93
+
94
+ await waitFor(() => expect(result.current.loading).toBe(false));
95
+ expect(result.current.canWrite).toBe(true);
96
+ expect(result.current.error).toMatch(/network down/);
97
+ });
98
+
99
+ it('returns the no-path state without firing a request when path is null', () => {
100
+ renderHook(() => useFileAccess(null, PROTECTED), {
101
+ wrapper: withWorkspace(makeWorkspace()),
102
+ });
103
+ expect(apiMock.fetchFileAccess).not.toHaveBeenCalled();
104
+ });
105
+
106
+ // Regression for Bug B (path-prefix mismatch): the resolver expects
107
+ // repo-relative paths, so the hook must strip the kbDirName prefix before
108
+ // calling the API. A pre-fix call with `knowledge-base/Knowledge/Sales/Foo.md`
109
+ // would only match the root access.md and silently drop the Sales/ grant.
110
+ it('strips the kbDirName prefix before calling fetchFileAccess', async () => {
111
+ apiMock.fetchFileAccess.mockResolvedValueOnce({
112
+ canWrite: true,
113
+ eligible: { roles: ['Product Manager'], users: [] },
114
+ });
115
+
116
+ renderHook(
117
+ () => useFileAccess('knowledge-base/Knowledge/Sales/Foo.md', PROTECTED),
118
+ { wrapper: withWorkspace(makeWorkspace()) },
119
+ );
120
+
121
+ await waitFor(() =>
122
+ expect(apiMock.fetchFileAccess).toHaveBeenCalledWith(
123
+ 'ws-1',
124
+ 'Knowledge/Sales/Foo.md',
125
+ ),
126
+ );
127
+ });
128
+
129
+ // Bug A: files outside the KB are user-owned scratch space and must never
130
+ // be gated. Treat them as immediately writable; never hit the network.
131
+ it('short-circuits to canWrite=true for paths outside the KB repo', async () => {
132
+ const { result } = renderHook(() => useFileAccess('my-notes.txt', PROTECTED), {
133
+ wrapper: withWorkspace(makeWorkspace()),
134
+ });
135
+
136
+ await waitFor(() => expect(result.current.loading).toBe(false));
137
+ expect(result.current.canWrite).toBe(true);
138
+ expect(result.current.eligible).toEqual({ roles: [], users: [] });
139
+ expect(apiMock.fetchFileAccess).not.toHaveBeenCalled();
140
+ });
141
+
142
+ it('also short-circuits deeper non-repo paths (uploads, extracted zips)', async () => {
143
+ const { result } = renderHook(
144
+ () => useFileAccess('uploads/spec/diagram.png', PROTECTED),
145
+ { wrapper: withWorkspace(makeWorkspace()) },
146
+ );
147
+
148
+ await waitFor(() => expect(result.current.loading).toBe(false));
149
+ expect(result.current.canWrite).toBe(true);
150
+ expect(apiMock.fetchFileAccess).not.toHaveBeenCalled();
151
+ });
152
+
153
+ // The substring-not-prefix foot-gun: `knowledge-base-backup/...` happens
154
+ // to start with the kbDirName text but is NOT inside the repo dir. The
155
+ // `kbDirName + '/'` check guards against this.
156
+ it('treats `<kbDirName>-suffix/...` as non-repo (substring is not prefix)', async () => {
157
+ const { result } = renderHook(
158
+ () => useFileAccess('knowledge-base-backup/Knowledge/Foo.md', PROTECTED),
159
+ { wrapper: withWorkspace(makeWorkspace()) },
160
+ );
161
+
162
+ await waitFor(() => expect(result.current.loading).toBe(false));
163
+ expect(result.current.canWrite).toBe(true);
164
+ expect(apiMock.fetchFileAccess).not.toHaveBeenCalled();
165
+ });
166
+
167
+ // Clicking the KB folder entry itself (no trailing slash) shouldn't fire a
168
+ // request — directories don't have file-level write semantics here.
169
+ it('returns no-path state for the kbDirName entry itself (no trailing slash)', async () => {
170
+ const { result } = renderHook(() => useFileAccess('knowledge-base', PROTECTED), {
171
+ wrapper: withWorkspace(makeWorkspace()),
172
+ });
173
+
174
+ await waitFor(() => expect(result.current.loading).toBe(false));
175
+ expect(result.current.canWrite).toBe(true);
176
+ expect(apiMock.fetchFileAccess).not.toHaveBeenCalled();
177
+ });
178
+
179
+ // Before WorkspaceInfo hydrates, kbDirName is null. We can't classify the
180
+ // path yet, so hold the no-path state and don't fire a misclassified call.
181
+ it('holds the no-path state while kbDirName is still null (bootstrap)', () => {
182
+ renderHook(
183
+ () => useFileAccess('knowledge-base/Knowledge/Foo.md', PROTECTED),
184
+ { wrapper: withWorkspace(makeWorkspace({ kbDirName: null })) },
185
+ );
186
+
187
+ expect(apiMock.fetchFileAccess).not.toHaveBeenCalled();
188
+ });
189
+
190
+ it('respects a non-default kbDirName from config', async () => {
191
+ apiMock.fetchFileAccess.mockResolvedValueOnce({
192
+ canWrite: true,
193
+ eligible: { roles: ['Admin'], users: [] },
194
+ });
195
+
196
+ renderHook(() => useFileAccess('custom-kb/Knowledge/Foo.md', PROTECTED), {
197
+ wrapper: withWorkspace(makeWorkspace({ kbDirName: 'custom-kb' })),
198
+ });
199
+
200
+ await waitFor(() =>
201
+ expect(apiMock.fetchFileAccess).toHaveBeenCalledWith('ws-1', 'Knowledge/Foo.md'),
202
+ );
203
+ });
204
+
205
+ // Drafts are free-for-all. The backend skips the per-path gate on
206
+ // non-protected branches (lock-acquire, commit, push, revert all bail
207
+ // early), so the editor must mirror that — no API call, immediate
208
+ // canWrite=true, no read-only flicker.
209
+ it('skips the API on a non-protected branch and returns canWrite=true', async () => {
210
+ const { result } = renderHook(
211
+ () => useFileAccess('knowledge-base/Knowledge/Foo.md', DRAFT),
212
+ { wrapper: withWorkspace(makeWorkspace()) },
213
+ );
214
+
215
+ await waitFor(() => expect(result.current.loading).toBe(false));
216
+ expect(result.current.canWrite).toBe(true);
217
+ expect(result.current.eligible).toEqual({ roles: [], users: [] });
218
+ expect(apiMock.fetchFileAccess).not.toHaveBeenCalled();
219
+ });
220
+
221
+ // Branch still loading: hold canWrite=null so the caller stays optimistic
222
+ // (editor editable) until we know which gate applies. Don't fire the API
223
+ // yet because we'd be guessing.
224
+ it('holds canWrite=null while branch is still null (status bootstrap)', () => {
225
+ renderHook(
226
+ () => useFileAccess('knowledge-base/Knowledge/Foo.md', null),
227
+ { wrapper: withWorkspace(makeWorkspace()) },
228
+ );
229
+
230
+ expect(apiMock.fetchFileAccess).not.toHaveBeenCalled();
231
+ });
232
+ });
233
+
234
+ describe('formatEligible', () => {
235
+ it('joins roles and named users', () => {
236
+ expect(
237
+ formatEligible({
238
+ roles: ['Admin', 'Product Manager'],
239
+ users: [{ name: 'Felix Kissel', email: 'felix@example.com' }],
240
+ }),
241
+ ).toBe('Admin, Product Manager; Felix Kissel (felix@example.com)');
242
+ });
243
+
244
+ it('falls back to "no one" on empty', () => {
245
+ expect(formatEligible({ roles: [], users: [] })).toBe('no one');
246
+ });
247
+
248
+ it('formats users without names as bare email', () => {
249
+ expect(
250
+ formatEligible({ roles: [], users: [{ name: '', email: 'x@y.z' }] }),
251
+ ).toBe('x@y.z');
252
+ });
253
+ });
@@ -0,0 +1,205 @@
1
+ import { authFetch } from '../../lib/api';
2
+ import { GitApiError, handleApiResponse } from '../git/services/git.api';
3
+
4
+ export interface AccessEligible {
5
+ roles: string[];
6
+ users: { name: string; email: string }[];
7
+ }
8
+
9
+ export interface AccessReaders extends AccessEligible {
10
+ /** False when `read: everyone` applies cleanly (the lists are then empty). */
11
+ restricted: boolean;
12
+ }
13
+
14
+ /**
15
+ * ONE place a principal is named for a verb (mirrors the backend `GrantSource`).
16
+ * Both kinds are file-backed and removable from the dialog: `direct` → remove
17
+ * here; `ancestor` → remove-from-parent or deny-here. A principal who only
18
+ * resolves via a group / `everyone` / admin-rescue produces no source.
19
+ */
20
+ export type GrantSource =
21
+ | { kind: 'direct' }
22
+ | { kind: 'ancestor'; path: string };
23
+
24
+ /**
25
+ * EVERY scope that grants a principal one verb, ordered **closest-first**: `[0]`
26
+ * is the effective source, the rest are scopes that ALSO grant it. So a verb
27
+ * granted both on the target and a parent reads `[direct, ancestor]` — letting
28
+ * the dialog tell "granted here" apart from "granted here AND also inherited"
29
+ * (which a single winning source can't). Never empty (a verb with no grant is
30
+ * omitted from `GrantSources`).
31
+ */
32
+ export type VerbSources = GrantSource[];
33
+
34
+ /** Per-verb sources of a principal's access; only held verbs appear. */
35
+ export type GrantSources = Partial<Record<GrantVerb, VerbSources>>;
36
+
37
+ export interface AccessResponse {
38
+ /** True iff the current user may read the path (default-deny). */
39
+ canRead: boolean;
40
+ canWrite: boolean;
41
+ canDownload: boolean;
42
+ /** True iff the current user is an owner of the path (owner ⊇ write + download). */
43
+ canOwner: boolean;
44
+ /** Principals with write at this path (owners folded in). */
45
+ eligible: AccessEligible;
46
+ /** Who can read this path. `restricted: false` ⇒ everyone. */
47
+ readers: AccessReaders;
48
+ /** The owner set for this path — who to contact about the node. */
49
+ owners: AccessEligible;
50
+ /** Principals with `download` at this path (owners folded in; write is NOT). */
51
+ downloaders: AccessEligible;
52
+ /**
53
+ * Per-principal, per-verb sources of access. Keyed `u:<email>` / `r:<role>`
54
+ * (lowercased) to match the dialog's row keys, so a row can show where its
55
+ * access comes from (direct, inherited, or both) and which verbs are removable
56
+ * here. After a revoke, a principal whose direct entry was stripped but who
57
+ * remains inherited still appears here with only their `ancestor` source(s) —
58
+ * which is how the dialog chains into "Remove from parent?".
59
+ */
60
+ sources: Record<string, GrantSources>;
61
+ }
62
+
63
+ /**
64
+ * The 409 body the revoke route returns when a principal's access on the
65
+ * target is inherited (the target splice would no-op but they still resolve).
66
+ * The dialog turns this into the "Remove from parent?" confirmation.
67
+ */
68
+ export interface InheritedRevokeError {
69
+ kind: 'inherited';
70
+ error: string;
71
+ sources: GrantSources;
72
+ }
73
+
74
+ /** Narrow a thrown API error to the inherited-revoke 409 payload, else null. */
75
+ export function asInheritedError(err: unknown): InheritedRevokeError | null {
76
+ if (
77
+ err instanceof GitApiError &&
78
+ err.status === 409 &&
79
+ err.body &&
80
+ typeof err.body === 'object' &&
81
+ (err.body as { kind?: unknown }).kind === 'inherited'
82
+ ) {
83
+ return err.body as InheritedRevokeError;
84
+ }
85
+ return null;
86
+ }
87
+
88
+ /** A grantable principal — a person (by email) or a group (a roles.yaml role). */
89
+ export type Principal =
90
+ | { kind: 'user'; email: string; displayName: string }
91
+ | { kind: 'role'; role: string };
92
+
93
+ /** Verbs the share dialog can grant. */
94
+ export type GrantVerb = 'read' | 'write' | 'owner' | 'download';
95
+
96
+ export interface SuggestResponse {
97
+ groups: string[];
98
+ people: { name: string; email: string }[];
99
+ /** True when the query was too short to return people (groups still shown). */
100
+ peopleWithheld: boolean;
101
+ }
102
+
103
+ /**
104
+ * Autocomplete the share dialog: matching groups (roles) + people. People are
105
+ * withheld until the query is ≥ 2 chars (server-side harvesting guard).
106
+ */
107
+ export async function suggestPrincipals(
108
+ workspaceId: string,
109
+ query: string,
110
+ ): Promise<SuggestResponse> {
111
+ return handleApiResponse(
112
+ await authFetch(
113
+ `/api/workspace/${workspaceId}/access/suggest?q=${encodeURIComponent(query)}`,
114
+ ),
115
+ );
116
+ }
117
+
118
+ /**
119
+ * Grant a principal a verb on a path. `kind` distinguishes a folder target
120
+ * (edits the folder's access.md) from a file target (edits the node's own
121
+ * frontmatter). Returns the fresh resolved access for the path.
122
+ */
123
+ export async function grantAccess(
124
+ workspaceId: string,
125
+ input: { path: string; kind: 'folder' | 'file'; verb: GrantVerb; principal: Principal },
126
+ ): Promise<AccessResponse> {
127
+ return handleApiResponse(
128
+ await authFetch(`/api/workspace/${workspaceId}/access/grant`, {
129
+ method: 'POST',
130
+ headers: { 'Content-Type': 'application/json' },
131
+ body: JSON.stringify(input),
132
+ }),
133
+ );
134
+ }
135
+
136
+ /**
137
+ * Revoke a principal from a path. Three shapes:
138
+ * - default (no `mode`): remove the principal's DIRECT grant on the target
139
+ * (with `verb`, just that verb). If their access is inherited, the server
140
+ * responds 409 `{ kind: 'inherited', sources }` — use `asInheritedError`.
141
+ * - `mode: 'remove-from-parent'` + `ancestor`: cascade up — remove them from
142
+ * the granting ancestor folder (echo the ancestor path from the 409 sources
143
+ * verbatim; it's an opaque repo-relative token).
144
+ * - `mode: 'deny-here'`: per-item override — add a `deny` at the target only.
145
+ * Returns the fresh resolved access on success.
146
+ */
147
+ export async function revokeAccess(
148
+ workspaceId: string,
149
+ input: {
150
+ path: string;
151
+ kind: 'folder' | 'file';
152
+ principal: Principal;
153
+ verb?: GrantVerb;
154
+ mode?: 'remove-from-parent' | 'deny-here';
155
+ ancestor?: string;
156
+ },
157
+ ): Promise<AccessResponse> {
158
+ return handleApiResponse(
159
+ await authFetch(`/api/workspace/${workspaceId}/access/revoke`, {
160
+ method: 'POST',
161
+ headers: { 'Content-Type': 'application/json' },
162
+ body: JSON.stringify(input),
163
+ }),
164
+ );
165
+ }
166
+
167
+ /**
168
+ * Resolve write permission for a single file under the current user's identity
169
+ * in the given workspace.
170
+ *
171
+ * `relativePath` is repo-relative (`Knowledge/Foo.md`, not `knowledge-base/…`).
172
+ * UI callers that hold workspace-relative paths should go through
173
+ * `useFileAccess`, which strips the `kbDirName/` prefix and short-circuits for
174
+ * paths outside the KB repo.
175
+ */
176
+ export async function fetchFileAccess(
177
+ workspaceId: string,
178
+ relativePath: string,
179
+ kind: 'folder' | 'file' = 'file',
180
+ ): Promise<AccessResponse> {
181
+ return handleApiResponse(
182
+ await authFetch(
183
+ `/api/workspace/${workspaceId}/access?path=${encodeURIComponent(relativePath)}&kind=${kind}`,
184
+ ),
185
+ );
186
+ }
187
+
188
+ /**
189
+ * Batch lookup — one round trip resolves write permission for multiple paths.
190
+ * Caller-supplied path strings are the keys of the returned record. Throws if
191
+ * any path is rejected by the backend.
192
+ */
193
+ export async function fetchFileAccessBatch(
194
+ workspaceId: string,
195
+ relativePaths: string[],
196
+ ): Promise<{ results: Record<string, boolean> }> {
197
+ return handleApiResponse(
198
+ await authFetch(`/api/workspace/${workspaceId}/access/batch`, {
199
+ method: 'POST',
200
+ headers: { 'Content-Type': 'application/json' },
201
+ body: JSON.stringify({ paths: relativePaths }),
202
+ }),
203
+ );
204
+ }
205
+
@@ -0,0 +1,31 @@
1
+ import { Lock } from 'lucide-react';
2
+ import type { AccessEligible } from '../api';
3
+ import { formatEligible } from '../hooks/useFileAccess';
4
+
5
+ interface Props {
6
+ path: string;
7
+ eligible: AccessEligible;
8
+ }
9
+
10
+ /**
11
+ * Shown above the editor when the current user lacks `write` on the open
12
+ * file. The editor itself goes read-only — this banner explains *why*
13
+ * and names the people / roles who can change it.
14
+ */
15
+ export function AccessRestrictedBanner({ path, eligible }: Props) {
16
+ const summary = formatEligible(eligible);
17
+ return (
18
+ <div
19
+ role="status"
20
+ className="flex items-center gap-2 px-3 py-1.5 bg-slate-50 border-b border-slate-200 text-xs text-slate-700 shrink-0"
21
+ >
22
+ <Lock size={13} className="shrink-0 text-slate-500" />
23
+ <span className="flex-1">
24
+ You don't have permission to edit{' '}
25
+ <span className="font-mono text-slate-900">{path}</span>. Editing is restricted to{' '}
26
+ <span className="font-medium">{summary}</span>. Ask one of them, or have the access
27
+ rules for this folder broadened.
28
+ </span>
29
+ </div>
30
+ );
31
+ }