@bevel-software/platform-core-frontend 0.21.0 → 0.22.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 (34) hide show
  1. package/package.json +2 -2
  2. package/src/core/registry.ts +57 -0
  3. package/src/modules/access/__tests__/ManageAccessDialog.request.test.tsx +376 -0
  4. package/src/modules/access/components/AccessRequestControl.tsx +155 -0
  5. package/src/modules/{library → access}/components/AccessRequestsBanner.tsx +62 -24
  6. package/src/modules/access/components/ManageAccessDialog.tsx +81 -4
  7. package/src/modules/access/hooks/useAccessRequests.ts +183 -0
  8. package/src/modules/access/requests.api.ts +121 -0
  9. package/src/modules/auth/components/LoginScreen.tsx +5 -0
  10. package/src/modules/change-requests/__tests__/ChangeRequestDialog.brings-itself-up-to-date.test.tsx +171 -38
  11. package/src/modules/change-requests/__tests__/ChangeRequestDialog.fork-point.test.tsx +34 -19
  12. package/src/modules/change-requests/__tests__/ChangeRequestDialog.test.tsx +173 -6
  13. package/src/modules/change-requests/components/ChangeRequestDialog.tsx +155 -98
  14. package/src/modules/library/__tests__/SkillPage.test.tsx +15 -0
  15. package/src/modules/library/__tests__/ToolPage.test.tsx +15 -1
  16. package/src/modules/library/__tests__/title-row-actions.ts +53 -1
  17. package/src/modules/library/components/PluginJoinRequests.tsx +2 -2
  18. package/src/modules/library/components/skill-page/SkillPage.tsx +2 -2
  19. package/src/modules/library/components/tool-page/ToolPage.tsx +11 -1
  20. package/src/modules/library/hooks/useJoinRequests.ts +26 -101
  21. package/src/modules/pr/services/pr-merge.api.ts +10 -2
  22. package/src/modules/settings/components/DeploymentPage.tsx +22 -0
  23. package/src/modules/settings/components/__tests__/DeploymentPage.test.tsx +72 -4
  24. package/src/modules/setup/__tests__/setup.first-run.test.tsx +276 -0
  25. package/src/modules/setup/__tests__/setup.github.test.tsx +416 -0
  26. package/src/modules/setup/__tests__/setup.kept-draft.test.tsx +275 -0
  27. package/src/modules/setup/__tests__/setup.repository.test.tsx +373 -0
  28. package/src/modules/setup/__tests__/setup.test.tsx +8 -14
  29. package/src/modules/setup/components/GitHubRepositoryPanel.tsx +369 -0
  30. package/src/modules/setup/components/SetupGate.tsx +1 -0
  31. package/src/modules/setup/components/SetupScreen.tsx +464 -38
  32. package/src/modules/setup/services/setup.api.ts +93 -0
  33. package/src/modules/setup/utils/kept-draft.ts +86 -0
  34. package/src/shared/components/SlotBoundary.tsx +51 -0
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.22.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.22.0"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@testing-library/jest-dom": "^6.9.1",
@@ -145,6 +145,42 @@ export interface ExplorerItemDef {
145
145
  Component: ComponentType<{ tree: FileTreeEntry | null }>;
146
146
  }
147
147
 
148
+ /**
149
+ * A way to sign in that the distribution runs for every deployment it hosts,
150
+ * shown in the "Single sign-on" section as a tab of its own, ahead of the
151
+ * form for the deployment's own identity provider.
152
+ *
153
+ * Core's form asks for an issuer, an application and a secret, because a
154
+ * self-hosted deployment has to bring its own. A hosted one does not: the
155
+ * host already runs sign-in with the accounts people have, and what is left
156
+ * for the admin to decide is who may use it. That decision is the
157
+ * distribution's, so is the panel that takes it, and core only gives it a
158
+ * place.
159
+ *
160
+ * The section opens on this tab unless the deployment has its own provider
161
+ * configured, in which case it opens on that one: the tab shown is the way
162
+ * of signing in that is in effect.
163
+ *
164
+ * THE PANEL SITS INSIDE THE SETTINGS FORM. It must not render a `<form>` of
165
+ * its own, its buttons must be `type="button"`, and it saves through its
166
+ * own requests: "Save and continue" saves core's settings and nothing of
167
+ * the panel's.
168
+ */
169
+ export interface SignInOptionDef {
170
+ /** The tab's name, e.g. "Google and Microsoft". */
171
+ label: string;
172
+ /** The name of the tab holding core's own form. Default "Your own provider". */
173
+ ownProviderLabel?: string;
174
+ Panel: ComponentType<SignInOptionPanelProps>;
175
+ }
176
+
177
+ export interface SignInOptionPanelProps {
178
+ /** Where the form stands: the first-run gate or the Deployment page. */
179
+ variant: 'setup' | 'settings';
180
+ /** Whether the deployment has an identity provider of its own configured. */
181
+ ownProviderConfigured: boolean;
182
+ }
183
+
148
184
  /** Context passed when the user asks to open a change request from a draft. */
149
185
  export interface CrCreationInput {
150
186
  workspaceId: string | null;
@@ -310,6 +346,27 @@ export interface AppRegistry {
310
346
  * page simply never mentions a directory connection.
311
347
  */
312
348
  groupsDirectoryPanel?: ComponentType<GroupsDirectoryPanelProps>;
349
+ /**
350
+ * A panel at the foot of the Deployment page, below the settings form.
351
+ * Core's page holds what every deployment has — the repository, the branch
352
+ * model, sign-in. What a deployment IS beyond that belongs to the
353
+ * distribution that runs it: a hosted workspace has a plan and can be
354
+ * deleted by its admin, a self-hosted one is deleted by whoever owns the
355
+ * server, and core knows neither. The page reserves this slot for it.
356
+ *
357
+ * Rendered for admins only, like the page itself, and independently of the
358
+ * settings load: a panel that offers a way out of the deployment must not
359
+ * disappear because the settings could not be read. Rendered inside a
360
+ * boundary, so the independence holds both ways: a panel that throws loses
361
+ * its own place on the page, never the settings form above it. Absent means
362
+ * the page ends with its form, as it always has.
363
+ */
364
+ deploymentPanel?: ComponentType;
365
+ /**
366
+ * A way to sign in that the DISTRIBUTION runs, offered beside the
367
+ * deployment's own identity provider. See {@link SignInOptionDef}.
368
+ */
369
+ signInOption?: SignInOptionDef;
313
370
  /**
314
371
  * How many unread items the gear menu's badge should show, if anything is
315
372
  * counting. CORE COUNTS NOTHING: the feedback inbox behind that badge is an
@@ -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
+ });
@@ -0,0 +1,155 @@
1
+ import { useCallback, useEffect, useState } from 'react';
2
+ import { Banner, Button, TextAreaField } from '../../../shared/components';
3
+ import {
4
+ fetchAccessRequestStatus,
5
+ sendAccessRequest,
6
+ LEVEL_WORDS,
7
+ REQUEST_NOTE_MAX,
8
+ type AccessRequestStatus,
9
+ type RequestLevel,
10
+ } from '../requests.api';
11
+
12
+ /**
13
+ * "You can read this, but you can't share it" — with something to do about it.
14
+ *
15
+ * The read-only Manage access dialog used to end at "Ask an owner: Ed." and
16
+ * leave the reader to find Ed some other way. This is the rest of that
17
+ * sentence: choose Can edit or Owner, say why if it helps, and the people who
18
+ * can already edit the item answer it in the same dialog.
19
+ *
20
+ * ONE OPEN REQUEST PER PERSON PER ITEM. While it is open the control is
21
+ * replaced by what was asked and who is being waited on, and the level cannot
22
+ * be changed — a person who wants the other level waits for the answer, or an
23
+ * editor grants it directly. Sending twice (a double click, two tabs) is
24
+ * answered by the request the first send opened, so there is still exactly
25
+ * one.
26
+ *
27
+ * NOTHING SAYS "Requested" UNLESS THE REQUEST EXISTS. The state is read back
28
+ * from the server, and a send that fails says so and keeps the control — a
29
+ * hopeful local "sent!" is the one lie this surface must not tell, because
30
+ * the person would then wait on nobody.
31
+ */
32
+ export interface AccessRequestControlProps {
33
+ workspaceId: string;
34
+ /** The item, exactly as the dialog addresses it for a grant. */
35
+ target: { path: string; kind: 'folder' | 'file' };
36
+ /** `file` or `folder` — the word the surrounding sentences use. */
37
+ targetKind: 'folder' | 'file';
38
+ /**
39
+ * The same up-to-three names the "Ask an owner" line shows, or '' when the
40
+ * item names nobody. Kept identical on purpose: the line that says who to
41
+ * ask and the line that says who is being waited on must not disagree.
42
+ */
43
+ ownerNames: string;
44
+ }
45
+
46
+ export function AccessRequestControl({
47
+ workspaceId,
48
+ target,
49
+ targetKind,
50
+ ownerNames,
51
+ }: AccessRequestControlProps) {
52
+ const [status, setStatus] = useState<AccessRequestStatus | null>(null);
53
+ const [level, setLevel] = useState<RequestLevel>('write');
54
+ const [note, setNote] = useState('');
55
+ const [sending, setSending] = useState(false);
56
+ const [error, setError] = useState<string | null>(null);
57
+ const { path, kind } = target;
58
+
59
+ useEffect(() => {
60
+ let cancelled = false;
61
+ fetchAccessRequestStatus(workspaceId, { path, kind })
62
+ .then((next) => {
63
+ if (!cancelled) setStatus(next);
64
+ })
65
+ .catch(() => {
66
+ // A status that cannot be read is reported as nothing outstanding:
67
+ // the control stays, and a send would find the open request anyway.
68
+ if (!cancelled) setStatus({ state: 'none' });
69
+ });
70
+ return () => {
71
+ cancelled = true;
72
+ };
73
+ }, [workspaceId, path, kind]);
74
+
75
+ const send = useCallback(async () => {
76
+ setSending(true);
77
+ setError(null);
78
+ try {
79
+ const opened = await sendAccessRequest(workspaceId, {
80
+ path,
81
+ kind,
82
+ level,
83
+ note: note.trim() || undefined,
84
+ });
85
+ // The server's answer, not the click's hope: a second send while a
86
+ // request is open comes back with THAT request, level and all.
87
+ setStatus({ state: 'pending', level: opened.level, number: opened.number });
88
+ } catch (err) {
89
+ setError(err instanceof Error ? err.message : String(err));
90
+ } finally {
91
+ setSending(false);
92
+ }
93
+ }, [workspaceId, path, kind, level, note]);
94
+
95
+ // Nothing at all until the server has spoken: a control that flashes up and
96
+ // is then replaced by "Requested" reads as a send that happened by itself.
97
+ if (!status) return null;
98
+
99
+ if (status.state === 'pending') {
100
+ const who = ownerNames || `the people who can edit its access`;
101
+ return (
102
+ <p className="mt-2 text-detail text-ink-muted" role="status">
103
+ {`Requested: ${LEVEL_WORDS[status.level ?? 'write']}. Waiting on ${who}.`}
104
+ </p>
105
+ );
106
+ }
107
+
108
+ return (
109
+ <div className="mt-2 flex flex-col gap-2">
110
+ {status.state === 'not-accepted' && (
111
+ <p className="text-detail text-ink-muted">
112
+ {`Your last request for ${LEVEL_WORDS[status.level ?? 'write']} wasn't accepted.`}
113
+ </p>
114
+ )}
115
+ <div
116
+ role="radiogroup"
117
+ aria-label={`What to ask for on this ${targetKind}`}
118
+ className="flex items-center gap-4"
119
+ >
120
+ {(['write', 'owner'] as const).map((option) => (
121
+ <label key={option} className="flex items-center gap-1.5 text-detail text-ink">
122
+ <input
123
+ type="radio"
124
+ name="access-request-level"
125
+ value={option}
126
+ checked={level === option}
127
+ disabled={sending}
128
+ onChange={() => setLevel(option)}
129
+ />
130
+ {LEVEL_WORDS[option]}
131
+ </label>
132
+ ))}
133
+ </div>
134
+ <TextAreaField
135
+ aria-label="Why you need it (optional)"
136
+ placeholder="Why you need it (optional)"
137
+ maxLength={REQUEST_NOTE_MAX}
138
+ disabled={sending}
139
+ value={note}
140
+ onChange={(e) => setNote(e.target.value)}
141
+ />
142
+ <div>
143
+ <Button variant="outline" size="sm" disabled={sending} onClick={() => void send()}>
144
+ Request access
145
+ </Button>
146
+ </div>
147
+ {error && (
148
+ <Banner tone="danger" role="alert">
149
+ {/* One trailing stop, whatever the server's sentence ended with. */}
150
+ {`Couldn't send your request: ${error.replace(/\s*\.$/, '')}.`}
151
+ </Banner>
152
+ )}
153
+ </div>
154
+ );
155
+ }