@bevel-software/platform-core-frontend 0.21.0 → 0.23.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 (72) hide show
  1. package/package.json +2 -2
  2. package/src/core/CoreAppShell.tsx +2 -0
  3. package/src/core/registry.ts +140 -0
  4. package/src/lib/api.ts +49 -0
  5. package/src/modules/access/__tests__/ManageAccessDialog.request.test.tsx +376 -0
  6. package/src/modules/access/api.ts +6 -4
  7. package/src/modules/access/components/AccessRequestControl.tsx +155 -0
  8. package/src/modules/{library → access}/components/AccessRequestsBanner.tsx +62 -24
  9. package/src/modules/access/components/ManageAccessDialog.tsx +81 -4
  10. package/src/modules/access/hooks/useAccessRequests.ts +183 -0
  11. package/src/modules/access/requests.api.ts +121 -0
  12. package/src/modules/admin/__tests__/UserAccountsPage.test.tsx +89 -1
  13. package/src/modules/admin/components/UserAccountsPage.tsx +93 -5
  14. package/src/modules/auth/components/LoginScreen.tsx +8 -0
  15. package/src/modules/auth/services/account.api.ts +26 -3
  16. package/src/modules/change-requests/__tests__/ChangeRequestDialog.brings-itself-up-to-date.test.tsx +171 -38
  17. package/src/modules/change-requests/__tests__/ChangeRequestDialog.fork-point.test.tsx +34 -19
  18. package/src/modules/change-requests/__tests__/ChangeRequestDialog.test.tsx +173 -6
  19. package/src/modules/change-requests/components/BranchFilePreview.tsx +7 -1
  20. package/src/modules/change-requests/components/ChangeRequestDialog.tsx +155 -98
  21. package/src/modules/git/__tests__/FileHistoryPanel.test.tsx +89 -10
  22. package/src/modules/git/__tests__/HistoryVersionPreview.test.tsx +479 -0
  23. package/src/modules/git/components/FileHistoryPanel.tsx +52 -65
  24. package/src/modules/git/components/HistoryVersionPreview.tsx +410 -0
  25. package/src/modules/layout/__tests__/ReadOnlyBanner.test.tsx +157 -0
  26. package/src/modules/layout/components/ReadOnlyBanner.tsx +96 -0
  27. package/src/modules/library/__tests__/SkillPage.test.tsx +15 -0
  28. package/src/modules/library/__tests__/ToolPage.test.tsx +15 -1
  29. package/src/modules/library/__tests__/title-row-actions.ts +53 -1
  30. package/src/modules/library/components/PluginJoinRequests.tsx +2 -2
  31. package/src/modules/library/components/skill-page/SkillPage.tsx +2 -2
  32. package/src/modules/library/components/tool-page/ToolPage.tsx +11 -1
  33. package/src/modules/library/hooks/useJoinRequests.ts +26 -101
  34. package/src/modules/pr/services/pr-merge.api.ts +10 -2
  35. package/src/modules/settings/components/DeploymentPage.tsx +22 -0
  36. package/src/modules/settings/components/__tests__/DeploymentPage.test.tsx +72 -4
  37. package/src/modules/setup/__tests__/setup.first-run.test.tsx +276 -0
  38. package/src/modules/setup/__tests__/setup.github.test.tsx +416 -0
  39. package/src/modules/setup/__tests__/setup.kept-draft.test.tsx +275 -0
  40. package/src/modules/setup/__tests__/setup.repository-change.test.tsx +296 -0
  41. package/src/modules/setup/__tests__/setup.repository.test.tsx +463 -0
  42. package/src/modules/setup/__tests__/setup.test.tsx +13 -17
  43. package/src/modules/setup/components/GitHubRepositoryPanel.tsx +369 -0
  44. package/src/modules/setup/components/SetupGate.tsx +1 -0
  45. package/src/modules/setup/components/SetupScreen.tsx +608 -41
  46. package/src/modules/setup/services/setup.api.ts +171 -3
  47. package/src/modules/setup/utils/kept-draft.ts +86 -0
  48. package/src/modules/workspace/components/FileExplorer.tsx +140 -12
  49. package/src/modules/workspace/components/FileViewer.tsx +11 -1
  50. package/src/modules/workspace/components/TreeActionConfirm.tsx +5 -7
  51. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +603 -29
  52. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +23 -6
  53. package/src/modules/workspace/components/renderers/DownloadFileButton.tsx +41 -8
  54. package/src/modules/workspace/components/renderers/EmailRenderer.tsx +20 -5
  55. package/src/modules/workspace/components/renderers/ImageRenderer.tsx +39 -16
  56. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +27 -7
  57. package/src/modules/workspace/components/renderers/PptxRenderer.tsx +20 -5
  58. package/src/modules/workspace/components/renderers/RetryReadButton.tsx +37 -0
  59. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +20 -5
  60. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +186 -7
  61. package/src/modules/workspace/components/renderers/__tests__/readPane.test.tsx +59 -0
  62. package/src/modules/workspace/components/renderers/htmlSandbox.ts +80 -20
  63. package/src/modules/workspace/components/renderers/index.ts +6 -1
  64. package/src/modules/workspace/components/renderers/readPane.ts +22 -0
  65. package/src/modules/workspace/components/renderers/rendererWorkspace.ts +50 -9
  66. package/src/modules/workspace/components/renderers/useReadRetry.ts +27 -0
  67. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +79 -0
  68. package/src/modules/workspace/routing/kb-routes.ts +25 -10
  69. package/src/modules/workspace/services/workspace.api.ts +22 -1
  70. package/src/shared/components/SlotBoundary.tsx +51 -0
  71. package/src/shared/markdown/__tests__/hrefs.test.ts +111 -0
  72. package/src/shared/markdown/hrefs.ts +80 -4
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bevel-software/platform-core-frontend",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "description": "Open-source core UI of the Bevel platform (raw TS/TSX source): workspace explorer/viewer, branches & change requests, Library, secrets, tools, access control.",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -45,7 +45,7 @@
45
45
  "tailwind-merge": "^3.5.0",
46
46
  "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
47
47
  "yaml": "^2.9.0",
48
- "@bevel-software/platform-shared": "0.21.0"
48
+ "@bevel-software/platform-shared": "0.23.0"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@testing-library/jest-dom": "^6.9.1",
@@ -23,6 +23,7 @@ import { EventBusFocusBinder } from '../modules/workflow/state/EventBusFocusBind
23
23
  import { ChangeRequestStaleBinder } from '../modules/workflow/state/ChangeRequestStaleBinder';
24
24
  import { Toolbar } from '../modules/toolbar/components/Toolbar';
25
25
  import { DemoBanner } from '../modules/layout/components/DemoBanner';
26
+ import { ReadOnlyBanner } from '../modules/layout/components/ReadOnlyBanner';
26
27
  import { FileExplorer } from '../modules/workspace/components/FileExplorer';
27
28
  import { FileViewer } from '../modules/workspace/components/FileViewer';
28
29
  import { OpenChangeRequestsProvider } from '../modules/workspace/state/open-change-requests';
@@ -175,6 +176,7 @@ function AuthenticatedAppInner() {
175
176
  // and its onboarding-import banner after these.
176
177
  const CORE_BANNERS: BannerDef[] = [
177
178
  { id: 'demo', order: 20, node: <DemoBanner /> },
179
+ { id: 'read-only', order: 25, node: <ReadOnlyBanner /> },
178
180
  { id: 'roles-corrupted', order: 30, node: <RolesCorruptedBanner /> },
179
181
  ];
180
182
 
@@ -145,6 +145,119 @@ export interface ExplorerItemDef {
145
145
  Component: ComponentType<{ tree: FileTreeEntry | null }>;
146
146
  }
147
147
 
148
+ /**
149
+ * The folder a right-click menu was opened on, as the entry is told about it.
150
+ *
151
+ * Everything here is what the explorer ALREADY knows when it draws the menu;
152
+ * nothing new is asked of the server on an entry's behalf, and nothing here is
153
+ * a gate. `canWrite` and `branchProtected` are for deciding whether to OFFER a
154
+ * verb — the routes an entry's action goes through decide whether to allow it,
155
+ * exactly as they do for "New folder".
156
+ */
157
+ export interface FolderMenuContext {
158
+ /** Workspace-relative path of the folder, e.g. `knowledge-base/Data`. */
159
+ path: string;
160
+ /**
161
+ * The branch the explorer's rows came from — the branch the workspace IS,
162
+ * never the one a route may be navigating to. Empty only before the
163
+ * workspace has bootstrapped, which is before there is a row to right-click.
164
+ */
165
+ branch: string;
166
+ /**
167
+ * Whether the viewer may write into this folder — the same answer the
168
+ * explorer's own write hints read, and `false` while it is still unknown.
169
+ */
170
+ canWrite: boolean;
171
+ /** Whether {@link branch} is one of the deployment's protected branches. */
172
+ branchProtected: boolean;
173
+ }
174
+
175
+ /**
176
+ * What a folder menu entry's action may do: the operations Hexis's own entries
177
+ * use, and only those. An entry creates nothing itself — it asks through here,
178
+ * so whatever it creates travels the same routes "New file" and "New folder"
179
+ * travel, and the access rules, the platform-file rules and the
180
+ * protected-branch rules apply to it unchanged.
181
+ *
182
+ * `createFolder` and `createFile` REJECT when the route refuses; an entry that
183
+ * lets the rejection through has its message shown the way a refused "New
184
+ * folder" shows one, so handling it is optional rather than the entry's
185
+ * problem. Paths are workspace-relative, as {@link FolderMenuContext.path} is.
186
+ */
187
+ export interface FolderMenuTools {
188
+ createFolder: (path: string) => Promise<void>;
189
+ createFile: (path: string, content?: string) => Promise<void>;
190
+ /** Re-read the file tree, so what was created shows up in it. */
191
+ refreshTree: () => Promise<void>;
192
+ /** Open a path in the surface this tree belongs to. */
193
+ openPath: (path: string) => void;
194
+ /** Show a failure the way the explorer shows its own. */
195
+ showError: (message: string) => void;
196
+ }
197
+
198
+ /**
199
+ * An entry a DEPLOYMENT adds to a folder's right-click menu in the explorer.
200
+ *
201
+ * Core registers none. The explorer and its menus are core's, but a verb like
202
+ * "New ontology" belongs to the distribution that has ontologies, so core
203
+ * offers the place rather than the entry.
204
+ *
205
+ * Registered entries are drawn after core's own, behind a separator, in the
206
+ * order registered — a deployment's verbs read as additions rather than as
207
+ * part of the tree's own vocabulary. With none registered there is no
208
+ * separator and the menu is exactly as it was.
209
+ *
210
+ * `appliesTo` is called every time a folder's menu opens, so keep it cheap and
211
+ * synchronous; one that throws leaves its entry out of that menu and is
212
+ * logged, and the rest of the menu is unaffected.
213
+ */
214
+ export interface FolderMenuItemDef {
215
+ /** Stable, and unique among registered entries — it keys the rendered row. */
216
+ id: string;
217
+ label: string;
218
+ icon?: ReactNode;
219
+ /** Whether this entry belongs in THIS folder's menu. */
220
+ appliesTo: (folder: FolderMenuContext) => boolean;
221
+ /** What the entry does. A rejection's message is shown as an error. */
222
+ run: (folder: FolderMenuContext, tools: FolderMenuTools) => void | Promise<void>;
223
+ }
224
+
225
+ /**
226
+ * A way to sign in that the distribution runs for every deployment it hosts,
227
+ * shown in the "Single sign-on" section as a tab of its own, ahead of the
228
+ * form for the deployment's own identity provider.
229
+ *
230
+ * Core's form asks for an issuer, an application and a secret, because a
231
+ * self-hosted deployment has to bring its own. A hosted one does not: the
232
+ * host already runs sign-in with the accounts people have, and what is left
233
+ * for the admin to decide is who may use it. That decision is the
234
+ * distribution's, so is the panel that takes it, and core only gives it a
235
+ * place.
236
+ *
237
+ * The section opens on this tab unless the deployment has its own provider
238
+ * configured, in which case it opens on that one: the tab shown is the way
239
+ * of signing in that is in effect.
240
+ *
241
+ * THE PANEL SITS INSIDE THE SETTINGS FORM. It must not render a `<form>` of
242
+ * its own, its buttons must be `type="button"`, and it saves through its
243
+ * own requests: "Save and continue" saves core's settings and nothing of
244
+ * the panel's.
245
+ */
246
+ export interface SignInOptionDef {
247
+ /** The tab's name, e.g. "Google and Microsoft". */
248
+ label: string;
249
+ /** The name of the tab holding core's own form. Default "Your own provider". */
250
+ ownProviderLabel?: string;
251
+ Panel: ComponentType<SignInOptionPanelProps>;
252
+ }
253
+
254
+ export interface SignInOptionPanelProps {
255
+ /** Where the form stands: the first-run gate or the Deployment page. */
256
+ variant: 'setup' | 'settings';
257
+ /** Whether the deployment has an identity provider of its own configured. */
258
+ ownProviderConfigured: boolean;
259
+ }
260
+
148
261
  /** Context passed when the user asks to open a change request from a draft. */
149
262
  export interface CrCreationInput {
150
263
  workspaceId: string | null;
@@ -301,6 +414,11 @@ export interface AppRegistry {
301
414
  renderers: FileRendererDef[];
302
415
  /** Extra rows in the explorer's Pinned section (see {@link ExplorerItemDef}). */
303
416
  explorerItems: ExplorerItemDef[];
417
+ /**
418
+ * Extra entries in a FOLDER's right-click menu in the explorer, drawn after
419
+ * core's own behind a separator (see {@link FolderMenuItemDef}).
420
+ */
421
+ folderMenuItems: FolderMenuItemDef[];
304
422
  /**
305
423
  * The Groups settings page's directory-connection panel. Core's Groups
306
424
  * page manages MANUAL groups and renders the IdP-synced roster read-only;
@@ -310,6 +428,27 @@ export interface AppRegistry {
310
428
  * page simply never mentions a directory connection.
311
429
  */
312
430
  groupsDirectoryPanel?: ComponentType<GroupsDirectoryPanelProps>;
431
+ /**
432
+ * A panel at the foot of the Deployment page, below the settings form.
433
+ * Core's page holds what every deployment has — the repository, the branch
434
+ * model, sign-in. What a deployment IS beyond that belongs to the
435
+ * distribution that runs it: a hosted workspace has a plan and can be
436
+ * deleted by its admin, a self-hosted one is deleted by whoever owns the
437
+ * server, and core knows neither. The page reserves this slot for it.
438
+ *
439
+ * Rendered for admins only, like the page itself, and independently of the
440
+ * settings load: a panel that offers a way out of the deployment must not
441
+ * disappear because the settings could not be read. Rendered inside a
442
+ * boundary, so the independence holds both ways: a panel that throws loses
443
+ * its own place on the page, never the settings form above it. Absent means
444
+ * the page ends with its form, as it always has.
445
+ */
446
+ deploymentPanel?: ComponentType;
447
+ /**
448
+ * A way to sign in that the DISTRIBUTION runs, offered beside the
449
+ * deployment's own identity provider. See {@link SignInOptionDef}.
450
+ */
451
+ signInOption?: SignInOptionDef;
313
452
  /**
314
453
  * How many unread items the gear menu's badge should show, if anything is
315
454
  * counting. CORE COUNTS NOTHING: the feedback inbox behind that badge is an
@@ -366,6 +505,7 @@ export const EMPTY_REGISTRY: AppRegistry = {
366
505
  fileViewerPanels: [],
367
506
  renderers: [],
368
507
  explorerItems: [],
508
+ folderMenuItems: [],
369
509
  apps: [],
370
510
  toolbarItems: [],
371
511
  };
package/src/lib/api.ts CHANGED
@@ -13,6 +13,53 @@ export const API_UNREACHABLE_EVENT = 'bevel:api-unreachable';
13
13
 
14
14
  const PROXY_DOWN_STATUSES = new Set([502, 503, 504]);
15
15
 
16
+ /**
17
+ * Window event dispatched when the server refused a change because the
18
+ * deployment is read-only (a 403 whose body carries `workspace_read_only`).
19
+ * The read-only banner listens for it and asks the server what to say, so
20
+ * the app learns of the state from the first refusal instead of asking on a
21
+ * timer.
22
+ */
23
+ export const WRITE_REFUSED_EVENT = 'bevel:write-refused';
24
+
25
+ /**
26
+ * Window event dispatched when a change went through. While the read-only
27
+ * banner is up it asks again on this: switching accounts off is how an admin
28
+ * ends the state, and those requests succeed.
29
+ */
30
+ export const WRITE_ACCEPTED_EVENT = 'bevel:write-accepted';
31
+
32
+ /**
33
+ * The server's `READ_ONLY_CODE`, as `modules/write-access/write-access.ts`
34
+ * in core-backend exports it. The two must stay the same string: this is
35
+ * what the banner recognises a refusal by.
36
+ */
37
+ const READ_ONLY_CODE = 'workspace_read_only';
38
+ const READING_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
39
+
40
+ function methodOf(input: RequestInfo | URL, init: RequestInit | undefined): string {
41
+ const fromRequest = typeof input === 'object' && 'method' in input ? (input as Request).method : undefined;
42
+ return (init?.method ?? fromRequest ?? 'GET').toUpperCase();
43
+ }
44
+
45
+ /** Tell the banner what a mutating request's answer says about the deployment. Never throws, never delays the caller. */
46
+ function signalWriteAccess(input: RequestInfo | URL, init: RequestInit | undefined, response: Response): void {
47
+ if (READING_METHODS.has(methodOf(input, init))) return;
48
+ if (response.ok) {
49
+ window.dispatchEvent(new Event(WRITE_ACCEPTED_EVENT));
50
+ return;
51
+ }
52
+ if (response.status !== 403) return;
53
+ // A copy is read, so the caller still has the body to itself.
54
+ void response
55
+ .clone()
56
+ .json()
57
+ .then((body: { code?: unknown } | null) => {
58
+ if (body?.code === READ_ONLY_CODE) window.dispatchEvent(new Event(WRITE_REFUSED_EVENT));
59
+ })
60
+ .catch(() => undefined);
61
+ }
62
+
16
63
  function signalUnreachable(): void {
17
64
  window.dispatchEvent(new Event(API_UNREACHABLE_EVENT));
18
65
  }
@@ -98,5 +145,7 @@ export async function authFetch(
98
145
  clearToken();
99
146
  }
100
147
 
148
+ signalWriteAccess(input, init, response);
149
+
101
150
  return response;
102
151
  }
@@ -0,0 +1,376 @@
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 { DEFAULT_BRANCH, type FileTreeEntry } from '@bevel-software/platform-shared';
5
+ import type { AccessResponse } from '../api';
6
+
7
+ /**
8
+ * "Only people with edit access can share this folder. Ask an owner: Ed." —
9
+ * and now something to do about it.
10
+ *
11
+ * Three things are asserted here, because each of them is a way the surface
12
+ * could lie:
13
+ * - the control appears exactly where a request can actually be made, and
14
+ * nowhere else (an editor, a draft branch, a change-request-only file, a
15
+ * file whose folder governs it);
16
+ * - nothing says "Requested" unless the server said the request exists — a
17
+ * failed send keeps the control and says why;
18
+ * - an editor's Accept is the dialog's own grant, and a refused one leaves
19
+ * the request on screen with its refusal, rather than in a toast this
20
+ * dialog has no host for.
21
+ */
22
+
23
+ const api = vi.hoisted(() => ({
24
+ fetchFileAccess: vi.fn(),
25
+ grantAccess: vi.fn(),
26
+ revokeAccess: vi.fn(),
27
+ suggestPrincipals: vi.fn(),
28
+ }));
29
+ vi.mock('../api', async (importOriginal) => {
30
+ const actual = await importOriginal<typeof import('../api')>();
31
+ return { ...actual, ...api };
32
+ });
33
+
34
+ const requests = vi.hoisted(() => ({
35
+ fetchAccessRequestStatus: vi.fn(),
36
+ sendAccessRequest: vi.fn(),
37
+ listAccessRequests: vi.fn(),
38
+ reconcileAccessRequest: vi.fn(),
39
+ }));
40
+ vi.mock('../requests.api', async (importOriginal) => {
41
+ const actual = await importOriginal<typeof import('../requests.api')>();
42
+ return { ...actual, ...requests };
43
+ });
44
+
45
+ const cancelPullRequest = vi.hoisted(() => vi.fn());
46
+ vi.mock('../../pr/services/pr-cancel.api', () => ({ cancelPullRequest }));
47
+
48
+ const workspace = vi.hoisted(() => ({ workspaceId: 'target-company-state' }));
49
+ vi.mock('../../workspace/state/workspace.context', () => ({
50
+ useWorkspace: () => ({ workspaceId: workspace.workspaceId, kbDirName: 'knowledge-base' }),
51
+ }));
52
+ vi.mock('../../auth/state/auth.context', () => ({
53
+ useAuth: () => ({ user: { email: 'rita@x.io', name: 'Rita' } }),
54
+ }));
55
+
56
+ import { ManageAccessDialog } from '../components/ManageAccessDialog';
57
+
58
+ const FOLDER: FileTreeEntry = {
59
+ name: 'Research',
60
+ relativePath: 'knowledge-base/Research',
61
+ type: 'directory',
62
+ } as unknown as FileTreeEntry;
63
+ const PDF: FileTreeEntry = {
64
+ name: 'Deck.pdf',
65
+ relativePath: 'knowledge-base/Research/Deck.pdf',
66
+ type: 'file',
67
+ } as unknown as FileTreeEntry;
68
+
69
+ const ED = { name: 'Ed', email: 'ed@x.io' };
70
+
71
+ /** Rita can read Research; Ed owns it. She cannot change its access. */
72
+ const READER_VIEW = {
73
+ canRead: true,
74
+ canWrite: false,
75
+ canDownload: false,
76
+ canOwner: false,
77
+ eligible: { roles: [], users: [ED] },
78
+ readers: { restricted: true, roles: [], users: [ED] },
79
+ owners: { roles: [], users: [ED] },
80
+ downloaders: { roles: [], users: [] },
81
+ sources: {},
82
+ } as AccessResponse;
83
+
84
+ const EDITOR_VIEW = { ...READER_VIEW, canWrite: true } as AccessResponse;
85
+ const NO_OWNER_VIEW = { ...READER_VIEW, owners: { roles: [], users: [] } } as AccessResponse;
86
+
87
+ const RITA_PROPOSAL = {
88
+ verb: 'owner' as const,
89
+ id: 'user:rita@x.io',
90
+ principal: { kind: 'user' as const, email: 'rita@x.io', displayName: 'Rita' },
91
+ label: 'Rita',
92
+ };
93
+
94
+ const requestRow = (over: Record<string, unknown> = {}) => ({
95
+ number: 77,
96
+ branch: 'rita/join-research',
97
+ requesterName: 'Rita',
98
+ createdAt: '2026-01-01T00:00:00.000Z',
99
+ proposals: [RITA_PROPOSAL],
100
+ ...over,
101
+ });
102
+
103
+ const control = () => screen.queryByRole('button', { name: 'Request access' });
104
+
105
+ beforeEach(() => {
106
+ vi.clearAllMocks();
107
+ workspace.workspaceId = 'target-company-state';
108
+ api.suggestPrincipals.mockResolvedValue({ roles: [], groups: [], people: [], peopleWithheld: false });
109
+ api.fetchFileAccess.mockResolvedValue(READER_VIEW);
110
+ api.grantAccess.mockResolvedValue(EDITOR_VIEW);
111
+ api.revokeAccess.mockResolvedValue(READER_VIEW);
112
+ requests.fetchAccessRequestStatus.mockResolvedValue({ state: 'none' });
113
+ requests.sendAccessRequest.mockResolvedValue({ number: 77, level: 'write' });
114
+ requests.listAccessRequests.mockResolvedValue([]);
115
+ requests.reconcileAccessRequest.mockResolvedValue(true);
116
+ cancelPullRequest.mockResolvedValue(undefined);
117
+ });
118
+
119
+ describe('the person asking', () => {
120
+ it('offers a level choice with Can edit selected, a note field and Request access', async () => {
121
+ render(<ManageAccessDialog entry={FOLDER} onClose={() => {}} />);
122
+ expect(await screen.findByText(/Ask an owner: Ed\./)).toBeInTheDocument();
123
+
124
+ const canEdit = await screen.findByRole('radio', { name: 'Can edit' });
125
+ expect(canEdit).toBeChecked();
126
+ expect(screen.getByRole('radio', { name: 'Owner' })).not.toBeChecked();
127
+ expect(screen.getByRole('textbox', { name: /Why you need it/i })).toHaveAttribute(
128
+ 'maxlength',
129
+ '500',
130
+ );
131
+ expect(control()).toBeInTheDocument();
132
+ });
133
+
134
+ it('sends the level chosen and the note, then says who it is waiting on', async () => {
135
+ const user = userEvent.setup();
136
+ requests.sendAccessRequest.mockResolvedValue({ number: 77, level: 'owner' });
137
+ render(<ManageAccessDialog entry={FOLDER} onClose={() => {}} />);
138
+
139
+ await user.click(await screen.findByRole('radio', { name: 'Owner' }));
140
+ await user.type(
141
+ screen.getByRole('textbox', { name: /Why you need it/i }),
142
+ 'I maintain these pages now',
143
+ );
144
+ await user.click(control()!);
145
+
146
+ await waitFor(() =>
147
+ expect(requests.sendAccessRequest).toHaveBeenCalledWith('target-company-state', {
148
+ path: FOLDER.relativePath,
149
+ kind: 'folder',
150
+ level: 'owner',
151
+ note: 'I maintain these pages now',
152
+ }),
153
+ );
154
+ // The control is GONE, replaced by what was asked and who answers it.
155
+ expect(await screen.findByText('Requested: Owner. Waiting on Ed.')).toBeInTheDocument();
156
+ expect(control()).not.toBeInTheDocument();
157
+ expect(screen.queryByRole('radio', { name: 'Can edit' })).not.toBeInTheDocument();
158
+ });
159
+
160
+ it('a double click sends once — the button waits for the answer', async () => {
161
+ const user = userEvent.setup();
162
+ let release: (value: { number: number; level: 'write' }) => void = () => {};
163
+ requests.sendAccessRequest.mockReturnValue(
164
+ new Promise((resolve) => {
165
+ release = resolve;
166
+ }),
167
+ );
168
+ render(<ManageAccessDialog entry={FOLDER} onClose={() => {}} />);
169
+
170
+ const button = await screen.findByRole('button', { name: 'Request access' });
171
+ await user.click(button);
172
+ await waitFor(() => expect(button).toBeDisabled());
173
+ await user.click(button);
174
+
175
+ expect(requests.sendAccessRequest).toHaveBeenCalledTimes(1);
176
+ release({ number: 77, level: 'write' });
177
+ expect(await screen.findByText('Requested: Can edit. Waiting on Ed.')).toBeInTheDocument();
178
+ });
179
+
180
+ it('shows the level the SERVER reports, not the one this tab typed', async () => {
181
+ // Two tabs. This one sends Can edit while an Owner request is already
182
+ // open; the server answers with that open request, Owner and all. Echoing
183
+ // what was typed would caption somebody else's request with the wrong
184
+ // level until the dialog was reopened.
185
+ const user = userEvent.setup();
186
+ requests.sendAccessRequest.mockResolvedValue({ number: 31, level: 'owner' });
187
+ render(<ManageAccessDialog entry={FOLDER} onClose={() => {}} />);
188
+
189
+ await user.click(await screen.findByRole('button', { name: 'Request access' }));
190
+
191
+ expect(await screen.findByText('Requested: Owner. Waiting on Ed.')).toBeInTheDocument();
192
+ expect(screen.queryByText(/Requested: Can edit/)).not.toBeInTheDocument();
193
+ });
194
+
195
+ it('shows the same line, and no control, when the dialog is reopened while the request is open', async () => {
196
+ requests.fetchAccessRequestStatus.mockResolvedValue({
197
+ state: 'pending',
198
+ level: 'owner',
199
+ number: 77,
200
+ });
201
+ render(<ManageAccessDialog entry={FOLDER} onClose={() => {}} />);
202
+ expect(await screen.findByText('Requested: Owner. Waiting on Ed.')).toBeInTheDocument();
203
+ expect(control()).not.toBeInTheDocument();
204
+ });
205
+
206
+ it('names the people who can edit its access when the item names no owner', async () => {
207
+ api.fetchFileAccess.mockResolvedValue(NO_OWNER_VIEW);
208
+ requests.fetchAccessRequestStatus.mockResolvedValue({ state: 'pending', level: 'write' });
209
+ render(<ManageAccessDialog entry={FOLDER} onClose={() => {}} />);
210
+ expect(
211
+ await screen.findByText('Requested: Can edit. Waiting on the people who can edit its access.'),
212
+ ).toBeInTheDocument();
213
+ });
214
+
215
+ it('a failed send says why and keeps the control — nothing reads as Requested', async () => {
216
+ const user = userEvent.setup();
217
+ requests.sendAccessRequest.mockRejectedValue(new Error('the server could not be reached'));
218
+ render(<ManageAccessDialog entry={FOLDER} onClose={() => {}} />);
219
+
220
+ await user.click(await screen.findByRole('button', { name: 'Request access' }));
221
+
222
+ expect(
223
+ await screen.findByText("Couldn't send your request: the server could not be reached."),
224
+ ).toBeInTheDocument();
225
+ expect(control()).toBeInTheDocument();
226
+ expect(screen.queryByText(/^Requested:/)).not.toBeInTheDocument();
227
+ });
228
+
229
+ it('after a request closed without the access, offers a new one at the level chosen that time', async () => {
230
+ const user = userEvent.setup();
231
+ requests.fetchAccessRequestStatus.mockResolvedValue({
232
+ state: 'not-accepted',
233
+ level: 'owner',
234
+ number: 31,
235
+ });
236
+ render(<ManageAccessDialog entry={FOLDER} onClose={() => {}} />);
237
+
238
+ expect(
239
+ await screen.findByText("Your last request for Owner wasn't accepted."),
240
+ ).toBeInTheDocument();
241
+ // The control is back, and it starts from Can edit again.
242
+ expect(await screen.findByRole('radio', { name: 'Can edit' })).toBeChecked();
243
+ await user.click(control()!);
244
+ await waitFor(() =>
245
+ expect(requests.sendAccessRequest).toHaveBeenCalledWith(
246
+ 'target-company-state',
247
+ expect.objectContaining({ level: 'write' }),
248
+ ),
249
+ );
250
+ });
251
+ });
252
+
253
+ describe('where no request control appears', () => {
254
+ it('not for someone who can already edit the item', async () => {
255
+ api.fetchFileAccess.mockResolvedValue(EDITOR_VIEW);
256
+ render(<ManageAccessDialog entry={FOLDER} onClose={() => {}} />);
257
+ await screen.findByText(/On this folder/i);
258
+ expect(control()).not.toBeInTheDocument();
259
+ expect(screen.queryByText(/Only people with edit access/)).not.toBeInTheDocument();
260
+ expect(requests.fetchAccessRequestStatus).not.toHaveBeenCalled();
261
+ });
262
+
263
+ it('not on a draft branch view', async () => {
264
+ workspace.workspaceId = 'rita%2Fdraft';
265
+ render(<ManageAccessDialog entry={FOLDER} onClose={() => {}} />);
266
+ expect(await screen.findByText(/Ask an owner: Ed\./)).toBeInTheDocument();
267
+ expect(control()).not.toBeInTheDocument();
268
+ expect(requests.fetchAccessRequestStatus).not.toHaveBeenCalled();
269
+ expect(requests.listAccessRequests).not.toHaveBeenCalled();
270
+ });
271
+
272
+ it('not on a file that exists only in a change request', async () => {
273
+ render(
274
+ <ManageAccessDialog
275
+ entry={{ ...FOLDER, name: 'New.md', relativePath: 'knowledge-base/Research/New.md', type: 'file' } as FileTreeEntry}
276
+ proposal={{ number: 12, branch: 'rita/draft' }}
277
+ onClose={() => {}}
278
+ />,
279
+ );
280
+ expect(await screen.findByText(/Ask an owner: Ed\./)).toBeInTheDocument();
281
+ expect(control()).not.toBeInTheDocument();
282
+ expect(requests.fetchAccessRequestStatus).not.toHaveBeenCalled();
283
+ });
284
+
285
+ it('not on a file its folder governs — which keeps its pointer at the folder', async () => {
286
+ api.fetchFileAccess.mockResolvedValue({ ...READER_VIEW, governedByFolder: 'Research' });
287
+ const onManageAncestor = vi.fn();
288
+ render(
289
+ <ManageAccessDialog entry={PDF} onClose={() => {}} onManageAncestor={onManageAncestor} />,
290
+ );
291
+ expect(
292
+ await screen.findByRole('button', { name: 'Manage access on Research' }),
293
+ ).toBeInTheDocument();
294
+ expect(control()).not.toBeInTheDocument();
295
+ expect(requests.fetchAccessRequestStatus).not.toHaveBeenCalled();
296
+ });
297
+ });
298
+
299
+ describe('the editors', () => {
300
+ const asEditor = () => {
301
+ api.fetchFileAccess.mockResolvedValue(EDITOR_VIEW);
302
+ requests.listAccessRequests.mockResolvedValue([
303
+ requestRow({ note: 'I maintain these pages now' }),
304
+ ]);
305
+ };
306
+
307
+ it('shows one line per open request, with the note, Accept and Decline — and no Manage access link', async () => {
308
+ asEditor();
309
+ render(<ManageAccessDialog entry={FOLDER} onClose={() => {}} />);
310
+
311
+ expect(await screen.findByText(/Rita asked for access to Research:/)).toBeInTheDocument();
312
+ expect(screen.getByText('Owner')).toBeInTheDocument();
313
+ expect(screen.getByText('I maintain these pages now')).toBeInTheDocument();
314
+ expect(screen.getByRole('button', { name: 'Grant Owner to Rita' })).toBeInTheDocument();
315
+ expect(
316
+ screen.getByRole('button', { name: 'Decline the request from Rita' }),
317
+ ).toBeInTheDocument();
318
+ expect(screen.queryByRole('button', { name: 'Manage access' })).not.toBeInTheDocument();
319
+ expect(requests.listAccessRequests).toHaveBeenCalledWith('target-company-state', {
320
+ path: FOLDER.relativePath,
321
+ kind: 'folder',
322
+ });
323
+ });
324
+
325
+ it('Accept is the dialog\'s own grant: the row is re-read, then the request is settled', async () => {
326
+ const user = userEvent.setup();
327
+ asEditor();
328
+ render(<ManageAccessDialog entry={FOLDER} onClose={() => {}} />);
329
+
330
+ await user.click(await screen.findByRole('button', { name: 'Grant Owner to Rita' }));
331
+
332
+ await waitFor(() =>
333
+ expect(api.grantAccess).toHaveBeenCalledWith(encodeURIComponent(DEFAULT_BRANCH), {
334
+ path: FOLDER.relativePath,
335
+ kind: 'folder',
336
+ verb: 'owner',
337
+ principal: RITA_PROPOSAL.principal,
338
+ }),
339
+ );
340
+ // The dialog re-reads its rows BEFORE the line goes, so the new row is on
341
+ // screen by the time the request disappears.
342
+ await waitFor(() => expect(api.fetchFileAccess.mock.calls.length).toBeGreaterThan(1));
343
+ await waitFor(() =>
344
+ expect(requests.reconcileAccessRequest).toHaveBeenCalledWith('target-company-state', 77, {
345
+ path: FOLDER.relativePath,
346
+ kind: 'folder',
347
+ }),
348
+ );
349
+ });
350
+
351
+ it('a failed Accept shows its error on that line, and the request stays', async () => {
352
+ const user = userEvent.setup();
353
+ asEditor();
354
+ api.grantAccess.mockRejectedValue(new Error('You can no longer edit this folder'));
355
+ render(<ManageAccessDialog entry={FOLDER} onClose={() => {}} />);
356
+
357
+ await user.click(await screen.findByRole('button', { name: 'Grant Owner to Rita' }));
358
+
359
+ expect(await screen.findByText('You can no longer edit this folder')).toBeInTheDocument();
360
+ expect(screen.getByText(/Rita asked for access to Research:/)).toBeInTheDocument();
361
+ expect(requests.reconcileAccessRequest).not.toHaveBeenCalled();
362
+ });
363
+
364
+ it('Decline closes the change request and grants nothing', async () => {
365
+ const user = userEvent.setup();
366
+ asEditor();
367
+ render(<ManageAccessDialog entry={FOLDER} onClose={() => {}} />);
368
+
369
+ await user.click(
370
+ await screen.findByRole('button', { name: 'Decline the request from Rita' }),
371
+ );
372
+
373
+ await waitFor(() => expect(cancelPullRequest).toHaveBeenCalledWith(77));
374
+ expect(api.grantAccess).not.toHaveBeenCalled();
375
+ });
376
+ });
@@ -392,7 +392,7 @@ export interface PathPrincipals {
392
392
  write: AccessPrincipalRef[];
393
393
  }
394
394
 
395
- /** One file's holders where it is now and where a move would put it. */
395
+ /** One file's or folder's holders where it is now and where a move would put it. */
396
396
  export interface ProspectiveAccess {
397
397
  before: PathPrincipals;
398
398
  after: PathPrincipals;
@@ -400,9 +400,11 @@ export interface ProspectiveAccess {
400
400
 
401
401
  /**
402
402
  * Resolve who holds read and write on `relativePath` today and who would hold
403
- * them once the file sits in `toDir` — the destination's folder rules with the
404
- * file's own frontmatter layered on top. Both paths are repo-relative
405
- * (`Knowledge/Foo.md`, `Knowledge/Sales`); `toDir` is `''` for the repo root.
403
+ * them once it sits in `toDir` — the destination's folder rules with what the
404
+ * move carries layered on top: a file's own frontmatter, or the `access.md`
405
+ * files inside a folder, counted at the paths they land on. Both paths are
406
+ * repo-relative (`Knowledge/Foo.md`, `Knowledge/Sales`); `toDir` is `''` for
407
+ * the repo root.
406
408
  *
407
409
  * `signal` lets the move dialog give up on it: the answer decorates the
408
410
  * confirmation and must never hold it open.