@bevel-software/platform-core-frontend 0.19.0 → 0.20.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.
@@ -2341,6 +2341,66 @@ describe('FileExplorer: delete and move ask first', () => {
2341
2341
  }
2342
2342
  });
2343
2343
 
2344
+ /**
2345
+ * The one drag test that actually DRAGS.
2346
+ *
2347
+ * Every other drop here hands the handler a `dataTransfer` built by the
2348
+ * test, with the source path and kind written in by hand. That skips the
2349
+ * handshake: `handleDragStart` writing the payload, and `handleDrop`
2350
+ * reading it back under the same two MIME keys. Stop setting the payload,
2351
+ * rename a key, or leave the row undraggable, and all of those tests still
2352
+ * pass while no real drag in the app does anything at all.
2353
+ *
2354
+ * This one grabs the row, lets the component's own `dragStart` fill a
2355
+ * DataTransfer that behaves like the browser's (what `setData` stores is
2356
+ * what `getData` returns), and drops THAT on the folder. So the refused
2357
+ * drag is evidenced end to end in the one place it can be: the criterion
2358
+ * has otherwise gone unevidenced through local, staging and production
2359
+ * testing, each time for want of a safe live fixture to drag.
2360
+ */
2361
+ it('a real drag — payload written by dragStart, read by drop — is refused with the sentence', async () => {
2362
+ const clash = 'A file named contract.pdf already exists in Sales.';
2363
+ const moveEntry = vi.fn().mockRejectedValue(new Error(clash));
2364
+ renderExplorer({ fileTree: TREE, moveEntry });
2365
+ openLegal();
2366
+
2367
+ // A row you cannot pick up cannot be dragged onto anything.
2368
+ const source = screen.getByText('contract.pdf').closest('[draggable]');
2369
+ expect(source).toHaveAttribute('draggable', 'true');
2370
+
2371
+ // Stands in for the browser's DataTransfer: a store, not a script.
2372
+ const store = new Map<string, string>();
2373
+ const dataTransfer = {
2374
+ setData: (type: string, value: string) => void store.set(type, value),
2375
+ getData: (type: string) => store.get(type) ?? '',
2376
+ files: [],
2377
+ items: undefined,
2378
+ effectAllowed: 'none',
2379
+ dropEffect: 'none',
2380
+ };
2381
+
2382
+ await act(async () => {
2383
+ fireEvent.dragStart(source!, { dataTransfer });
2384
+ });
2385
+ // The component put the drag's subject where the drop handler looks.
2386
+ expect(store.get(DRAG_MIME)).toBe(CONTRACT);
2387
+ expect(store.get(DRAG_KIND_MIME)).toBe('file');
2388
+
2389
+ await act(async () => {
2390
+ fireEvent.drop(screen.getByText('Sales'), { dataTransfer });
2391
+ });
2392
+ await act(async () => {
2393
+ fireEvent.click(screen.getByRole('button', { name: 'Move' }));
2394
+ });
2395
+
2396
+ // The destination was derived from the dragged row, not from the test.
2397
+ expect(moveEntry).toHaveBeenCalledWith(CONTRACT, `${KB}/KnowledgeBase/Sales/contract.pdf`);
2398
+ expect(screen.getByTestId('tree-move-error')).toHaveTextContent(clash);
2399
+ // Both entries where they were: the tree still shows each row.
2400
+ expect(screen.getByText('contract.pdf')).toBeInTheDocument();
2401
+ expect(screen.getByText('Sales')).toBeInTheDocument();
2402
+ });
2403
+
2344
2404
  it('a drop that lands says nothing', async () => {
2345
2405
  renderExplorer({ fileTree: TREE });
2346
2406
  openLegal();
@@ -392,6 +392,9 @@ describe('FileViewer', () => {
392
392
  owners: EMPTY_ELIGIBLE,
393
393
  };
394
394
  accessMock.fetchFileAccess.mockClear();
395
+ // mockClear keeps the implementation: a test that parks the lookup
396
+ // in flight would park every test after it.
397
+ accessMock.fetchFileAccess.mockImplementation(async () => accessMock.result);
395
398
  readBranchMock.mockImplementation(async () => '');
396
399
  // Restore the default "acquire succeeds" behaviour so a per-test 403
397
400
  // override doesn't leak into the next test.
@@ -988,6 +991,53 @@ describe('FileViewer', () => {
988
991
  expect(screen.queryByText(/Waiting on you/)).not.toBeInTheDocument();
989
992
  });
990
993
 
994
+ /**
995
+ * Switching files keeps the PREVIOUS file's grants in the access hook until
996
+ * the next lookup answers — which is why the "and N others" count is gated on
997
+ * `!access.loading`. The "Waiting on …" line is the same hazard: it names
998
+ * people, and naming the OUTGOING file's owners over the incoming file's box
999
+ * is a false statement about who decides this change. Mid-lookup it has to
1000
+ * fall back to the anonymous wording.
1001
+ */
1002
+ it('never names the previous file’s owners while the next lookup is in flight', async () => {
1003
+ accessMock.result = {
1004
+ canWrite: false,
1005
+ canOwner: false,
1006
+ eligible: { roles: ['Docs'], users: [] },
1007
+ owners: { roles: ['Docs'], users: [] },
1008
+ };
1009
+ readBranchMock.mockImplementation((async (branch: string) =>
1010
+ branch.startsWith('suggestions/') ? 'proposed' : 'current') as never);
1011
+ // The outgoing file's only job is to be the file we switch AWAY from,
1012
+ // leaving its owners behind in the hook. It renders a box of its own —
1013
+ // nothing is asserted on that one.
1014
+ const { rerender } = render(
1015
+ <ViewerHarness
1016
+ initialContent="outgoing"
1017
+ branch="target-company-state"
1018
+ filePath="knowledge-base/Knowledge/Other.md"
1019
+ changeRequests={[{ number: 34, title: 'Tighten the wording', who: 'Ali Raza' }]}
1020
+ />,
1021
+ );
1022
+ await waitFor(() => expect(accessMock.fetchFileAccess).toHaveBeenCalled());
1023
+
1024
+ // The incoming file's lookup never answers, so the box renders for the
1025
+ // whole of the in-flight window.
1026
+ accessMock.fetchFileAccess.mockImplementation(() => new Promise(() => {}));
1027
+ rerender(
1028
+ <ViewerHarness
1029
+ initialContent="incoming"
1030
+ branch="target-company-state"
1031
+ filePath="knowledge-base/Knowledge/Foo.md"
1032
+ changeRequests={[{ number: 34, title: 'Tighten the wording', who: 'Ali Raza' }]}
1033
+ />,
1034
+ );
1035
+
1036
+ expect(await screen.findByText(/proposed a change/)).toBeInTheDocument();
1037
+ expect(screen.getByText('Waiting on the owners')).toBeInTheDocument();
1038
+ expect(screen.queryByText('Waiting on Docs')).not.toBeInTheDocument();
1039
+ });
1040
+
991
1041
  it('says nothing on a file nobody has proposed a change to', () => {
992
1042
  render(<ViewerHarness initialContent="quiet" />);
993
1043
  expect(screen.queryByText(/proposed a change/)).not.toBeInTheDocument();
@@ -6,7 +6,7 @@ vi.mock('../../../../lib/api', () => ({
6
6
  authFetch: vi.fn(),
7
7
  }));
8
8
 
9
- import { uploadFile, createDirectory, rawFileUrl, writeFile, WorkspaceApiError } from '../workspace.api';
9
+ import { uploadFile, createDirectory, moveEntry, rawFileUrl, writeFile, WorkspaceApiError } from '../workspace.api';
10
10
  import { authFetch } from '../../../../lib/api';
11
11
 
12
12
  const mockedFetch = vi.mocked(authFetch);
@@ -126,3 +126,80 @@ describe('writeFile', () => {
126
126
  await expect(writeFile('ws', 'kb/notes.md', 'x')).resolves.toEqual({});
127
127
  });
128
128
  });
129
+
130
+ /**
131
+ * The refusal a rename or a drag shows is the SERVER's sentence, and this is
132
+ * the layer it has to survive to reach the sidebar intact.
133
+ *
134
+ * The explorer renders whatever `moveEntry` rejects with — the rename box puts
135
+ * it under the name you typed, a refused drop puts it under the row. Those
136
+ * components are tested against a stubbed `moveEntry`, so nothing there can
137
+ * tell whether a real 409 becomes that message or becomes "HTTP 409". This
138
+ * closes that half: the body the backend actually sends, through the real
139
+ * client, out as the message the UI renders.
140
+ */
141
+ describe('moveEntry carries the destination-taken refusal through unchanged', () => {
142
+ beforeEach(() => {
143
+ vi.clearAllMocks();
144
+ });
145
+
146
+ const SENTENCE = 'A file named Notes.md already exists in Sales.';
147
+
148
+ it('rejects with the sentence itself, not with the HTTP status', async () => {
149
+ mockedFetch.mockResolvedValueOnce(
150
+ // The WHOLE body `EntryExistsError` puts on the wire, not a convenient
151
+ // slice of it: the backend's `domainErrorBody` spreads the payload
152
+ // (`kind`, `entryKind`, `destination`) and then writes `error` last, so
153
+ // these four keys are what a client actually receives. The client here
154
+ // reads only `error`; the rest are present so this fixture cannot drift
155
+ // into testing a body the server never sends.
156
+ notOk(409, {
157
+ kind: 'entry-exists',
158
+ entryKind: 'file',
159
+ destination: 'kb/Sales/Notes.md',
160
+ error: SENTENCE,
161
+ }),
162
+ );
163
+
164
+ const err = await moveEntry('ws-1', 'kb/Sales/Report.docx', 'kb/Sales/Notes.md').catch((e) => e);
165
+
166
+ expect(err).toBeInstanceOf(WorkspaceApiError);
167
+ expect(err.status).toBe(409);
168
+ expect(err.message).toBe(SENTENCE);
169
+ });
170
+
171
+ it('says so for a folder in the way too, and sends the move as a PATCH of both paths', async () => {
172
+ const folder = 'A folder named Q4 already exists in Sales.';
173
+ mockedFetch.mockResolvedValueOnce(
174
+ notOk(409, {
175
+ kind: 'entry-exists',
176
+ entryKind: 'folder',
177
+ destination: 'kb/Sales/Q4',
178
+ error: folder,
179
+ }),
180
+ );
181
+
182
+ await expect(moveEntry('ws-1', 'kb/Archive/Q4', 'kb/Sales/Q4')).rejects.toMatchObject({
183
+ status: 409,
184
+ message: folder,
185
+ });
186
+
187
+ const [url, init] = mockedFetch.mock.calls[0] as [string, RequestInit];
188
+ expect(url).toBe('/api/workspace/ws-1/file');
189
+ expect(init.method).toBe('PATCH');
190
+ expect(JSON.parse(String(init.body))).toEqual({
191
+ oldPath: 'kb/Archive/Q4',
192
+ newPath: 'kb/Sales/Q4',
193
+ });
194
+ });
195
+
196
+ it('resolves silently when the move lands, so the explorer closes its box', async () => {
197
+ mockedFetch.mockResolvedValueOnce({
198
+ ok: true,
199
+ status: 200,
200
+ json: async () => ({ status: 'moved' }),
201
+ } as unknown as Response);
202
+
203
+ await expect(moveEntry('ws-1', 'kb/a.md', 'kb/b.md')).resolves.toBeUndefined();
204
+ });
205
+ });
@@ -1,266 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import { render, screen, waitFor, within } from '@testing-library/react';
3
- import userEvent from '@testing-library/user-event';
4
- import { ConnectionKeysPage } from '../components/ConnectionKeysPage';
5
- import { groupByAccount } from '../components/connection-keys-grouping';
6
- import { AdminContext } from '../state/admin.context';
7
- import {
8
- listConnectionKeys,
9
- revokeConnectionKey,
10
- type AdminConnectionKey,
11
- } from '../services/connection-keys.api';
12
-
13
- vi.mock('../services/connection-keys.api', () => ({
14
- listConnectionKeys: vi.fn(),
15
- revokeConnectionKey: vi.fn(),
16
- }));
17
-
18
- const ALICE = { id: 'u-alice', email: 'alice@example.com', name: 'Alice' };
19
- const BOB = { id: 'u-bob', email: 'bob@example.com', name: 'Bob' };
20
-
21
- const DAY = 24 * 60 * 60 * 1000;
22
- const NOW = Date.now();
23
-
24
- const ALICE_CI: AdminConnectionKey = {
25
- id: 'k-ci',
26
- label: 'CI pipeline',
27
- kind: 'key',
28
- createdAt: NOW - 10 * DAY,
29
- lastUsedAt: NOW - 2 * 60 * 60 * 1000,
30
- revokedAt: null,
31
- revokedBy: null,
32
- user: ALICE,
33
- };
34
- const ALICE_LAPTOP: AdminConnectionKey = {
35
- id: 'k-laptop',
36
- label: 'Laptop',
37
- kind: 'key',
38
- createdAt: NOW - 3 * DAY,
39
- lastUsedAt: null,
40
- revokedAt: null,
41
- revokedBy: null,
42
- user: ALICE,
43
- };
44
- const BOB_OLD: AdminConnectionKey = {
45
- id: 'k-old',
46
- label: 'Old script',
47
- kind: 'key',
48
- createdAt: NOW - 40 * DAY,
49
- lastUsedAt: NOW - 30 * DAY,
50
- revokedAt: NOW - 20 * DAY,
51
- revokedBy: 'owner',
52
- user: BOB,
53
- };
54
- const BOB_LINK: AdminConnectionKey = {
55
- id: 'k-link',
56
- label: 'Claude',
57
- kind: 'github-link',
58
- createdAt: NOW - 1 * DAY,
59
- lastUsedAt: NOW - 60 * 1000,
60
- revokedAt: null,
61
- revokedBy: null,
62
- user: BOB,
63
- };
64
-
65
- function renderPage(opts: { isAdmin?: boolean } = {}) {
66
- return render(
67
- <AdminContext.Provider
68
- value={{
69
- isAdmin: opts.isAdmin ?? true,
70
- unreadCount: 0,
71
- lastSeen: null,
72
- markSeen: () => {},
73
- refresh: () => {},
74
- rolesConfigCorrupted: false,
75
- rolesConfigErrors: [],
76
- runRolesRecovery: async () => {},
77
- }}
78
- >
79
- <ConnectionKeysPage />
80
- </AdminContext.Provider>,
81
- );
82
- }
83
-
84
- beforeEach(() => {
85
- vi.mocked(listConnectionKeys)
86
- .mockReset()
87
- .mockResolvedValue([ALICE_LAPTOP, ALICE_CI, BOB_OLD, BOB_LINK]);
88
- vi.mocked(revokeConnectionKey).mockReset().mockResolvedValue(undefined);
89
- });
90
-
91
- describe('groupByAccount', () => {
92
- it('groups in server order, live keys first, most recently used at the top', () => {
93
- const groups = groupByAccount([ALICE_LAPTOP, ALICE_CI, BOB_OLD, BOB_LINK], true);
94
- expect(groups.map((g) => g.user.id)).toEqual(['u-alice', 'u-bob']);
95
- // Alice: CI was used, Laptop never → CI first despite Laptop being newer.
96
- expect(groups[0].keys.map((k) => k.id)).toEqual(['k-ci', 'k-laptop']);
97
- // Bob: the live link outranks the revoked key.
98
- expect(groups[1].keys.map((k) => k.id)).toEqual(['k-link', 'k-old']);
99
- });
100
-
101
- it('drops revoked keys (and accounts left empty) when they are hidden', () => {
102
- const groups = groupByAccount([BOB_OLD, ALICE_CI], false);
103
- expect(groups.map((g) => g.user.id)).toEqual(['u-alice']);
104
- });
105
- });
106
-
107
- describe('ConnectionKeysPage', () => {
108
- it('shows the admins-only state (and never loads) for non-admins', () => {
109
- renderPage({ isAdmin: false });
110
- expect(screen.getByText(/Admins only/)).toBeInTheDocument();
111
- expect(listConnectionKeys).not.toHaveBeenCalled();
112
- });
113
-
114
- it('lists live keys per account with created / last used, hiding disconnected ones by default', async () => {
115
- renderPage();
116
- await waitFor(() => expect(screen.getByText('CI pipeline')).toBeInTheDocument());
117
-
118
- const alice = screen.getByRole('region', { name: 'Keys for alice@example.com' });
119
- expect(within(alice).getByText('Alice')).toBeInTheDocument();
120
- expect(within(alice).getByText('Created 1w ago')).toBeInTheDocument();
121
- expect(within(alice).getByText('Last used 2h ago')).toBeInTheDocument();
122
- expect(within(alice).getByText('Created 3d ago')).toBeInTheDocument();
123
- expect(within(alice).getByText('Last used never')).toBeInTheDocument();
124
- expect(
125
- within(alice).getByRole('button', { name: 'Revoke CI pipeline for alice@example.com' }),
126
- ).toBeInTheDocument();
127
-
128
- const bob = screen.getByRole('region', { name: 'Keys for bob@example.com' });
129
- expect(within(bob).getByText('Claude link')).toBeInTheDocument();
130
- expect(within(bob).queryByText('Old script')).not.toBeInTheDocument();
131
-
132
- expect(screen.getByText(/3 live keys · 1 disconnected/)).toBeInTheDocument();
133
- });
134
-
135
- it('reveals disconnected keys, without a revoke button, when toggled', async () => {
136
- renderPage();
137
- await waitFor(() => expect(screen.getByText('CI pipeline')).toBeInTheDocument());
138
-
139
- await userEvent.click(screen.getByRole('checkbox', { name: 'Show disconnected keys' }));
140
-
141
- const bob = screen.getByRole('region', { name: 'Keys for bob@example.com' });
142
- expect(within(bob).getByText('Old script')).toBeInTheDocument();
143
- expect(within(bob).getByText(/Disconnected by owner 2w ago/)).toBeInTheDocument();
144
- expect(
145
- within(bob).queryByRole('button', { name: 'Revoke Old script for bob@example.com' }),
146
- ).not.toBeInTheDocument();
147
- });
148
-
149
- it('revokes after confirmation and reloads the list', async () => {
150
- renderPage();
151
- await waitFor(() => expect(screen.getByText('CI pipeline')).toBeInTheDocument());
152
-
153
- await userEvent.click(
154
- screen.getByRole('button', { name: 'Revoke CI pipeline for alice@example.com' }),
155
- );
156
- const dialog = await screen.findByRole('dialog');
157
- expect(within(dialog).getByText(/Alice \(alice@example.com\)/)).toBeInTheDocument();
158
- expect(revokeConnectionKey).not.toHaveBeenCalled();
159
-
160
- await userEvent.click(within(dialog).getByRole('button', { name: 'Revoke key' }));
161
-
162
- await waitFor(() => expect(revokeConnectionKey).toHaveBeenCalledWith('k-ci'));
163
- await waitFor(() => expect(listConnectionKeys).toHaveBeenCalledTimes(2));
164
- });
165
-
166
- it('cancelling the confirm revokes nothing', async () => {
167
- renderPage();
168
- await waitFor(() => expect(screen.getByText('CI pipeline')).toBeInTheDocument());
169
-
170
- await userEvent.click(
171
- screen.getByRole('button', { name: 'Revoke CI pipeline for alice@example.com' }),
172
- );
173
- const dialog = await screen.findByRole('dialog');
174
- await userEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }));
175
-
176
- expect(revokeConnectionKey).not.toHaveBeenCalled();
177
- expect(listConnectionKeys).toHaveBeenCalledTimes(1);
178
- });
179
-
180
- it('surfaces a failed revoke inline and keeps the rows it had', async () => {
181
- renderPage();
182
- await waitFor(() => expect(screen.getByText('CI pipeline')).toBeInTheDocument());
183
- vi.mocked(revokeConnectionKey).mockRejectedValueOnce(new Error('Token not found'));
184
-
185
- await userEvent.click(
186
- screen.getByRole('button', { name: 'Revoke CI pipeline for alice@example.com' }),
187
- );
188
- await userEvent.click(
189
- within(await screen.findByRole('dialog')).getByRole('button', { name: 'Revoke key' }),
190
- );
191
-
192
- expect(await screen.findByRole('alert')).toHaveTextContent('Token not found');
193
- expect(screen.getByText('CI pipeline')).toBeInTheDocument();
194
- });
195
-
196
- it('keeps a revoked key disconnected when the reload after revoking fails', async () => {
197
- renderPage();
198
- await waitFor(() => expect(screen.getByText('CI pipeline')).toBeInTheDocument());
199
- vi.mocked(listConnectionKeys).mockRejectedValueOnce(new Error('Could not load connection keys'));
200
-
201
- await userEvent.click(
202
- screen.getByRole('button', { name: 'Revoke CI pipeline for alice@example.com' }),
203
- );
204
- await userEvent.click(
205
- within(await screen.findByRole('dialog')).getByRole('button', { name: 'Revoke key' }),
206
- );
207
-
208
- expect(await screen.findByRole('alert')).toHaveTextContent('Could not load connection keys');
209
- // The server said yes, so the row is disconnected regardless of the reload:
210
- // hidden with the other disconnected keys, and never offering Revoke again.
211
- expect(
212
- screen.queryByRole('button', { name: 'Revoke CI pipeline for alice@example.com' }),
213
- ).not.toBeInTheDocument();
214
- await userEvent.click(screen.getByRole('checkbox', { name: 'Show disconnected keys' }));
215
- expect(screen.getByText('CI pipeline')).toBeInTheDocument();
216
- expect(screen.getByText(/2 live keys · 2 disconnected/)).toBeInTheDocument();
217
- });
218
-
219
- it('ignores a stale list response that lands after a newer one', async () => {
220
- // Two revokes back to back: the reload from the FIRST resolves last, still
221
- // showing the second key as live. It must not win over the newer reload.
222
- const deferred = () => {
223
- let resolve!: (rows: AdminConnectionKey[]) => void;
224
- const promise = new Promise<AdminConnectionKey[]>((r) => (resolve = r));
225
- return { promise, resolve };
226
- };
227
- const first = deferred();
228
- const second = deferred();
229
- vi.mocked(listConnectionKeys)
230
- .mockReset()
231
- .mockResolvedValueOnce([ALICE_CI, ALICE_LAPTOP])
232
- .mockReturnValueOnce(first.promise)
233
- .mockReturnValueOnce(second.promise);
234
- renderPage();
235
- await waitFor(() => expect(screen.getByText('CI pipeline')).toBeInTheDocument());
236
-
237
- const revoke = async (name: string) => {
238
- await userEvent.click(screen.getByRole('button', { name }));
239
- await userEvent.click(
240
- within(await screen.findByRole('dialog')).getByRole('button', { name: 'Revoke key' }),
241
- );
242
- };
243
- await revoke('Revoke CI pipeline for alice@example.com');
244
- await revoke('Revoke Laptop for alice@example.com');
245
- await waitFor(() => expect(listConnectionKeys).toHaveBeenCalledTimes(3));
246
-
247
- const ciRevoked = { ...ALICE_CI, revokedAt: NOW };
248
- second.resolve([ciRevoked, { ...ALICE_LAPTOP, revokedAt: NOW }]);
249
- await waitFor(() => expect(screen.getByText(/0 live keys · 2 disconnected/)).toBeInTheDocument());
250
-
251
- // The stale reload: taken at face value, Laptop would come back to life.
252
- first.resolve([ciRevoked, ALICE_LAPTOP]);
253
- await new Promise((r) => setTimeout(r, 0));
254
- expect(screen.getByText(/0 live keys · 2 disconnected/)).toBeInTheDocument();
255
- expect(
256
- screen.queryByRole('button', { name: 'Revoke Laptop for alice@example.com' }),
257
- ).not.toBeInTheDocument();
258
- });
259
-
260
- it('shows the load error and no empty state when the first load fails', async () => {
261
- vi.mocked(listConnectionKeys).mockRejectedValueOnce(new Error('Could not load connection keys'));
262
- renderPage();
263
- expect(await screen.findByRole('alert')).toHaveTextContent('Could not load connection keys');
264
- expect(screen.queryByText(/No connection keys/)).not.toBeInTheDocument();
265
- });
266
- });